import { isAbsolute } from "node:path"; import { externalUrl, findLinks, type LinkRule, linkUrl } from "../links/contract.ts"; export interface ReferenceContext { recordId: string; matchers?: LinkRule[]; } export interface ReferencePart { text: string; href?: string; } export interface FileReference { path: string; line?: number; } export function fileReference(text: string): FileReference | undefined { if (!text.isWellFormed()) { return undefined; } const match = /^(.*?)(?::(\d+)(?:-\d+)?(?::\d+)?)?$/.exec(text); if (!match) { return undefined; } const path = match[1]; if ( !isAbsolute(path) || path.startsWith("//") || path.includes("\0") || /[\n\r<>"|?*]/.test(path) ) { return undefined; } const line = match[2] ? Number(match[2]) : undefined; if (line !== undefined && (!Number.isSafeInteger(line) || line < 1)) { return undefined; } return { path, line }; } function fileTarget(text: string, recordId: string): string | undefined { const file = recordId ? fileReference(text) : undefined; return file ? `/records/${encodeURIComponent(recordId)}/file?path=${encodeURIComponent(file.path)}${file.line ? `#L${file.line}` : ""}` : undefined; } export function referenceTarget(text: string, context: ReferenceContext): string | undefined { if (/^https?:\/\//i.test(text)) { return externalUrl(text); } for (const rule of context.matchers ?? []) { for (const match of text.matchAll(rule.pattern)) { if (match.index === 0 && match[0].length === text.length) { const href = linkUrl(rule, match); if (href) { return href; } } } } return fileTarget(text, context.recordId); } const FILES = /(? a.index - b.index); const parts: ReferencePart[] = []; let offset = 0; for (const match of matches) { if (match.index < offset) { continue; } if (match.index > offset) { parts.push({ text: text.slice(offset, match.index) }); } parts.push({ text: match.text, href: match.href }); offset = match.index + match.text.length; } parts.push({ text: text.slice(offset) }); return parts; }