Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdown-links.ts

434 lines13.4 KB

1import { formatWorkspaceRelativePath } from "./filePathDisplay";
2import {
3 isTerminalLinkActivation,
4 resolvePathLinkTarget,
5 splitPathAndPosition,
6} from "./terminal-links";
7​
8const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
9const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
10const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
11const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
12const RELATIVE_FILE_PATH_PATTERN =
13 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
14const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
15const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
16const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
17// Standard OS and dev-container roots; deliberately excludes app-route-ish
18// prefixes like /app/ or /chat/ so SPA routes never read as files.
19const POSIX_FILE_ROOT_PREFIXES = [
20 "/Users/",
21 "/home/",
22 "/tmp/",
23 "/var/",
24 "/etc/",
25 "/opt/",
26 "/mnt/",
27 "/Volumes/",
28 "/private/",
29 "/root/",
30 "/usr/",
31 "/bin/",
32 "/sbin/",
33 "/lib/",
34 "/lib64/",
35 "/srv/",
36 "/dev/",
37 "/proc/",
38 "/sys/",
39 "/run/",
40 "/boot/",
41 "/media/",
42 "/workspace/",
43 "/workspaces/",
44] as const;
45const MARKDOWN_LINK_HREF_PATTERN =
46 /\[[^\]]*]\(\s*(?:<([^>\n]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/g;
47​
48export interface MarkdownFileLinkMeta {
49 filePath: string;
50 targetPath: string;
51 displayPath: string;
52 workspaceRelativePath: string | null;
53 basename: string;
54 line?: number;
55 column?: number;
57​
58export function extractMarkdownLinkHrefs(markdown: string): string[] {
59 const hrefs: string[] = [];
60 for (const match of markdown.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
61 const href = (match[1] ?? match[2])?.trim();
62 if (href) hrefs.push(href);
63 }
64 return hrefs;
66​
67export function shouldOpenMarkdownFileLinkInEditor(
68 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
69 platform?: string,
70): boolean {
71 return isTerminalLinkActivation(event, platform);
73​
74function safeDecode(value: string): string {
75 try {
76 return decodeURIComponent(value);
77 } catch {
78 return value;
79 }
81​
82function unwrapMarkdownLinkDestination(value: string): string {
83 return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
85​
86export function normalizeMarkdownLinkDestination(value: string): string {
87 return unwrapMarkdownLinkDestination(value.trim());
89​
90function stripSearchAndHash(value: string): { path: string; hash: string } {
91 const hashIndex = value.indexOf("#");
92 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
93 const rawHash = hashIndex >= 0 ? value.slice(hashIndex) : "";
94 const queryIndex = pathWithSearch.indexOf("?");
95 const path = queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch;
96 return { path, hash: rawHash };
98​
99function normalizeWindowsDrivePath(path: string): string {
100 return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
102​
103function parseFileUrlHref(
104 href: string,
105 options?: { readonly decodePath?: boolean },
106): { path: string; hash: string } | null {
107 try {
108 const parsed = new URL(href);
109 if (parsed.protocol.toLowerCase() !== "file:") return null;
110​
111 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
112 const rawPath = uncHostname
113 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
114 : parsed.pathname;
115 if (rawPath.length === 0) return null;
116​
117 // Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
118 const normalizedPath = normalizeWindowsDrivePath(rawPath);
119​
120 return {
121 path: options?.decodePath === false ? normalizedPath : safeDecode(normalizedPath),
122 hash: parsed.hash,
123 };
124 } catch {
125 return null;
126 }
128​
129export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
130 if (!href) return null;
131 const normalizedHref = normalizeMarkdownLinkDestination(href);
132 const target = parseFileUrlHref(normalizedHref, { decodePath: false });
133 if (!target) return null;
134 return `${target.path}${target.hash}`;
136​
137function looksLikePosixFilesystemPath(path: string): boolean {
138 if (!path.startsWith("/")) return false;
139 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
140 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
141 const basename = path.slice(path.lastIndexOf("/") + 1);
142 return /\.[A-Za-z0-9_-]+$/.test(basename);
144​
145function appendLineColumnFromHash(path: string, hash: string): string {
146 if (!hash || POSITION_SUFFIX_PATTERN.test(path)) return path;
147 const match = hash.match(/^#L(\d+)(?:C(\d+))?$/i);
148 if (!match?.[1]) return path;
149 const line = match[1];
150 const column = match[2];
151 return `${path}:${line}${column ? `:${column}` : ""}`;
153​
154function isLikelyPathCandidate(path: string): boolean {
155 if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
156 if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
157 if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
158 return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
160​
161function isRelativePath(path: string): boolean {
162 return (
163 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
164 (!path.startsWith("/") &&
165 !WINDOWS_DRIVE_PATH_PATTERN.test(path) &&
166 !WINDOWS_UNC_PATH_PATTERN.test(path))
167 );
169​
170function hasExternalScheme(path: string): boolean {
171 const match = path.match(EXTERNAL_SCHEME_PATTERN);
172 if (!match) return false;
173 const rest = match[2] ?? "";
174 if (rest.startsWith("//")) return true;
175 return !POSITION_ONLY_PATTERN.test(rest);
177​
178export function resolveMarkdownFileLinkTarget(
179 href: string | undefined,
180 cwd?: string,
181): string | null {
182 if (!href) return null;
183 const rawHref = normalizeMarkdownLinkDestination(href);
184 if (rawHref.length === 0 || rawHref.startsWith("#")) return null;
185​
186 const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
187 ? parseFileUrlHref(rawHref)
188 : null;
189 const source = fileUrlTarget ?? stripSearchAndHash(rawHref);
190 const decodedPath = normalizeWindowsDrivePath(
191 fileUrlTarget ? source.path.trim() : safeDecode(source.path.trim()),
192 );
193 const decodedHash = safeDecode(source.hash.trim());
194​
195 if (decodedPath.length === 0) return null;
196 if (
197 !WINDOWS_DRIVE_PATH_PATTERN.test(decodedPath) &&
198 !WINDOWS_UNC_PATH_PATTERN.test(decodedPath) &&
199 hasExternalScheme(decodedPath)
200 ) {
201 return null;
202 }
203​
204 if (!isLikelyPathCandidate(decodedPath)) return null;
205​
206 const pathWithPosition = appendLineColumnFromHash(decodedPath, decodedHash);
207 if (!isRelativePath(pathWithPosition)) {
208 return pathWithPosition;
209 }
210​
211 if (!cwd) return null;
212 return resolvePathLinkTarget(pathWithPosition, cwd);
214​
215const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
216const PATH_SEPARATOR_PATTERN = /[\\/]/;
217const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
218const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
219const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
220// Any `Name:digits` shape also matches `error:1`, `port:3000`, `TODO:12`, so
221// extensionless linking is limited to conventional filenames.
222const EXTENSIONLESS_FILE_NAMES = new Set([
223 "Makefile",
224 "makefile",
225 "GNUmakefile",
226 "Dockerfile",
227 "Containerfile",
228 "Justfile",
229 "justfile",
230 "Rakefile",
231 "Gemfile",
232 "Procfile",
233 "Brewfile",
234 "Caddyfile",
235 "Vagrantfile",
236 "Jenkinsfile",
237 "Podfile",
238 "Fastfile",
239 "BUILD",
240 "WORKSPACE",
241 "LICENSE",
242 "LICENCE",
243 "COPYING",
244 "NOTICE",
245 "AUTHORS",
246 "CONTRIBUTORS",
247 "CHANGELOG",
248 "README",
249 "CODEOWNERS",
250]);
251const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
252// Allowlists, not full public-suffix detection: treating every dotted first
253// segment as a host would swallow real paths like `conf.d/x.conf` or
254// `Makefile.in:12`. Extensions that double as filename suffixes (`sh`, `md`,
255// `ts`, `rs`, `in`, ...) are deliberately absent from both sets.
256const GENERIC_HOSTNAME_TLDS = new Set([
257 "com",
258 "net",
259 "org",
260 "io",
261 "dev",
262 "app",
263 "ai",
264 "co",
265 "edu",
266 "gov",
267 "mil",
268 "info",
269 "biz",
270 "xyz",
271 "me",
272 "tv",
273 "cc",
274 "gg",
275 "chat",
276 "cloud",
277 "site",
278 "online",
279 "tech",
280 "store",
281 "link",
282]);
283// Country codes collide with file extensions (`.pl` Perl, `.pt` PyTorch,
284// `.es` ES modules), so they only count as host evidence when the candidate
285// lacks a :line suffix — an explicit line reference marks a file and wins.
286const COUNTRY_HOSTNAME_TLDS = new Set([
287 "uk",
288 "de",
289 "fr",
290 "nl",
291 "se",
292 "no",
293 "fi",
294 "dk",
295 "pl",
296 "ch",
297 "at",
298 "be",
299 "es",
300 "it",
301 "pt",
302 "eu",
303 "us",
304 "ca",
305 "au",
306 "nz",
307 "jp",
308 "kr",
309 "cn",
310 "br",
311 "ru",
312 "mx",
313 "ie",
314 "cz",
315 "tr",
316 "sg",
317 "hk",
318]);
319​
320/** `127.0.0.1`, `localhost`, `example.com`, `1.2.3` — hosts and versions, not files. */
321function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
322 if (segment.startsWith(".")) return false;
323 const lowered = segment.toLowerCase();
324 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
325 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
326 const labels = lowered.split(".");
327 const lastLabel = labels[labels.length - 1];
328 if (labels.length < 2 || lastLabel === undefined) return false;
329 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
330 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
332​
333/**
334 * Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
335 * `origin/main`) rather than deliberate link destinations, so auto-linking
336 * them demands stronger path evidence than an explicit markdown link does:
337 * an unambiguous path prefix, a file extension, or a :line suffix.
338 */
339export function resolveInlineCodeFileLinkMeta(
340 codeText: string,
341 cwd?: string,
342): MarkdownFileLinkMeta | null {
343 const trimmed = codeText.trim();
344 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
345​
346 // Windows drive/UNC paths keep their backslashes; any other backslashes are
347 // relative Windows-style paths, which neither the shape checks nor the
348 // downstream resolver understand — normalize them to forward slashes.
349 const candidate =
350 WINDOWS_DRIVE_PATH_PATTERN.test(trimmed) || WINDOWS_UNC_PATH_PATTERN.test(trimmed)
351 ? trimmed
352 : trimmed.replaceAll("\\", "/");
353​
354 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
355 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
356​
357 const hasExplicitPathShape =
358 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
359 candidate.startsWith("/") ||
360 WINDOWS_DRIVE_PATH_PATTERN.test(candidate) ||
361 WINDOWS_UNC_PATH_PATTERN.test(candidate);
362 if (!hasExplicitPathShape) {
363 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
364 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
365 if (looksLikeHostname(firstSegment, hasPosition)) return null;
366 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basenameOfPath(withoutPosition))) {
367 return null;
368 }
369 }
370​
371 const resolved = resolveMarkdownFileLinkMeta(candidate, cwd);
372 if (resolved) return resolved;
373​
374 // `Makefile:12` — conventional extensionless names fail the generic
375 // markdown-link candidate patterns, but here the :line suffix already
376 // marked the span as a file reference.
377 if (
378 cwd &&
379 BARE_EXTENSIONLESS_POSITION_PATTERN.test(candidate) &&
380 EXTENSIONLESS_FILE_NAMES.has(candidate.replace(POSITION_SUFFIX_PATTERN, ""))
381 ) {
382 return buildFileLinkMetaFromTarget(resolvePathLinkTarget(candidate, cwd), cwd);
383 }
384 return null;
386​
387function basenameOfPath(path: string): string {
388 // A trailing separator is a valid way to write a directory, so trim it before
389 // taking the final segment. Without this the segment reads as empty and the
390 // chip renders with no label at all.
391 const trimmed = path.replace(/[/\\]+$/, "") || path;
392 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
393 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
395​
396function workspaceRelativePath(path: string, workspaceRoot: string | undefined): string | null {
397 if (!workspaceRoot) return null;
398 const normalizedPath = normalizeWindowsDrivePath(path.replaceAll("\\", "/"));
399 const normalizedRoot = normalizeWindowsDrivePath(workspaceRoot.replaceAll("\\", "/")).replace(
400 /\/+$/,
401 "",
402 );
403 const pathForCompare = normalizedPath.toLowerCase();
404 const rootForCompare = normalizedRoot.toLowerCase();
405 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
406 return normalizedPath.slice(normalizedRoot.length + 1);
408​
409export function resolveMarkdownFileLinkMeta(
410 href: string | undefined,
411 cwd?: string,
412): MarkdownFileLinkMeta | null {
413 const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
414 if (!targetPath) return null;
415 return buildFileLinkMetaFromTarget(targetPath, cwd);
417​
418function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
419 const { path, line, column } = splitPathAndPosition(targetPath);
420 const parsedLine = line ? Number.parseInt(line, 10) : Number.NaN;
421 const parsedColumn = column ? Number.parseInt(column, 10) : Number.NaN;
422 const lineNumber = Number.isFinite(parsedLine) ? parsedLine : undefined;
423 const columnNumber = Number.isFinite(parsedColumn) ? parsedColumn : undefined;
424​
425 return {
426 filePath: path,
427 targetPath,
428 displayPath: formatWorkspaceRelativePath(targetPath, cwd),
429 workspaceRelativePath: workspaceRelativePath(path, cwd),
430 basename: basenameOfPath(path),
431 ...(lineNumber !== undefined ? { line: lineNumber } : {}),
432 ...(columnNumber !== undefined ? { column: columnNumber } : {}),
433 };