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