Open History to see the last commit
1import {
2 isNetworkPath,
3 isWindowsAbsolutePath,
4 stripSlashPrefixedWindowsDrive,
5 workspaceRelativeFilePath,
6} from "./path.ts";
7import {
8 type FilePathPosition,
9 formatFilePathPosition,
10 parseFileUrlHref,
11 resolvePathLinkTarget,
12 splitFilePathPosition,
13} from "./fileLinks.ts";
14
15const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
16
17// Names may use any script (`線性代數/考試.pdf`) and routing punctuation (`posts.$id.tsx`,
18// `(group)/[id]/+page.svelte`, `@scope/pkg`). The final segment is optional so an explicit
19// folder link may end in `/` (`patches/`, `docs/My Folder/`). A bare name with no slash still fails.
20const RELATIVE_FILE_PATH_PATTERN =
21 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+@()[\]-]+)*\/)+(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?::\d+){0,2})?$/u;
22
23// No `@` here: `me@example.com` is an address, not a file.
24const RELATIVE_FILE_NAME_PATTERN =
25 /^[\p{L}\p{M}\p{N}._$+()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+()[\]-]+)*\.[\p{L}\p{M}\p{N}_-]+(?::\d+){0,2}$/u;
26
27const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
28
29const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
30
31const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
32
33const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
34
35const PATH_SEPARATOR_PATTERN = /[\\/]/;
36// Agents shorten long paths with a `...` or `…` segment, which no file chip can open.
37const ELIDED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
38
39const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
40const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
41const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
42
43const POSIX_FILE_ROOT_PREFIXES = [
44 "/Users/",
45 "/home/",
46 "/tmp/",
47 "/var/",
48 "/etc/",
49 "/opt/",
50 "/mnt/",
51 "/Volumes/",
52 "/private/",
53 "/root/",
54 "/usr/",
55 "/bin/",
56 "/sbin/",
57 "/lib/",
58 "/lib64/",
59 "/srv/",
60 "/dev/",
61 "/proc/",
62 "/sys/",
63 "/run/",
64 "/boot/",
65 "/media/",
66 "/workspace/",
67 "/workspaces/",
68] as const;
69
70const EXTENSIONLESS_FILE_NAMES = new Set([
71 "Makefile",
72 "makefile",
73 "GNUmakefile",
74 "Dockerfile",
75 "Containerfile",
76 "Justfile",
77 "justfile",
78 "Rakefile",
79 "Gemfile",
80 "Procfile",
81 "Brewfile",
82 "Caddyfile",
83 "Vagrantfile",
84 "Jenkinsfile",
85 "Podfile",
86 "Fastfile",
87 "BUILD",
88 "WORKSPACE",
89 "LICENSE",
90 "LICENCE",
91 "COPYING",
92 "NOTICE",
93 "AUTHORS",
94 "CONTRIBUTORS",
95 "CHANGELOG",
96 "README",
97 "CODEOWNERS",
98]);
99
100const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
101
102const GENERIC_HOSTNAME_TLDS = new Set([
103 "com",
104 "net",
105 "org",
106 "io",
107 "dev",
108 "app",
109 "ai",
110 "co",
111 "edu",
112 "gov",
113 "mil",
114 "info",
115 "biz",
116 "xyz",
117 "me",
118 "tv",
119 "gg",
120 "chat",
121 "cloud",
122 "site",
123 "online",
124 "tech",
125 "store",
126 "link",
127]);
128
129const COUNTRY_HOSTNAME_TLDS = new Set([
130 "uk",
131 "de",
132 "fr",
133 "nl",
134 "se",
135 "no",
136 "fi",
137 "dk",
138 "pl",
139 "ch",
140 "at",
141 "be",
142 "es",
143 "it",
144 "pt",
145 "eu",
146 "us",
147 "ca",
148 "au",
149 "nz",
150 "jp",
151 "kr",
152 "cn",
153 "br",
154 "ru",
155 "mx",
156 "ie",
157 "cz",
158 "tr",
159 "sg",
160 "hk",
161 // C++ sources end in `.cc`, so `allocator.cc:217` names a file, not a host and port.
162 "cc",
163]);
164
165function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
166 if (segment.startsWith(".")) return false;
167 const lowered = segment.toLowerCase();
168 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
169 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
170 const labels = lowered.split(".");
171 const lastLabel = labels.at(-1);
172 if (labels.length < 2 || lastLabel === undefined) return false;
173 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
174 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
175}
176
177export function inlineCodeFilePathCandidate(codeText: string): string | null {
178 const trimmed = codeText.trim();
179 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
180
181 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
182 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
183 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
184 if (ELIDED_PATH_SEGMENT_PATTERN.test(candidate.replace(POSITION_SUFFIX_PATTERN, ""))) return null;
185
186 const hasExplicitPathShape =
187 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
188 candidate.startsWith("/") ||
189 isWindowsAbsolutePath(candidate);
190 if (!hasExplicitPathShape) {
191 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
192 // Markdown destinations accept `patches/`. Inline code still needs a
193 // file-shaped final segment, so a trailing slash stays plain code.
194 if (withoutPosition.endsWith("/")) return null;
195 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
196 if (looksLikeHostname(firstSegment, hasPosition)) return null;
197 const basename =
198 withoutPosition
199 .replace(/[/\\]+$/, "")
200 .split(/[\\/]/)
201 .at(-1) ?? "";
202 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
203 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
204 }
205 return candidate;
206}
207
208export function safeDecodeURIComponent(value: string): string {
209 try {
210 return decodeURIComponent(value);
211 } catch {
212 return value;
213 }
214}
215
216export function normalizeMarkdownLinkDestination(value: string): string {
217 const trimmed = value.trim();
218 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
219}
220
221export function splitMarkdownLinkSearchAndHash(value: string): {
222 readonly path: string;
223 readonly hash: string;
224} {
225 const hashIndex = value.indexOf("#");
226 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
227 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
228 const queryIndex = pathWithSearch.indexOf("?");
229 return {
230 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
231 hash,
232 };
233}
234
235/**
236 * The decoded path a markdown destination names on the host, before any workspace resolution, or
237 * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.
238 */
239export function markdownDestinationHostPath(source: string): string | null {
240 if (/^file:/i.test(source)) {
241 const target = parseFileUrlHref(source);
242 return target === null
243 ? null
244 : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));
245 }
246 return stripSlashPrefixedWindowsDrive(
247 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
248 );
249}
250
251export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
252 const destination = parseMarkdownFileLink(href);
253 if (!destination) return false;
254 const normalize = (path: string) =>
255 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
256 const labelPosition = splitFilePathPosition(label.trim());
257 if (
258 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
259 (labelPosition.column !== undefined && labelPosition.column !== destination.column)
260 ) {
261 return false;
262 }
263 let labelPath = normalize(labelPosition.path);
264 let destinationPath = normalize(destination.path);
265 if (labelPath.length === 0) return true;
266 if (isWindowsAbsolutePath(destination.path)) {
267 labelPath = labelPath.toLowerCase();
268 destinationPath = destinationPath.toLowerCase();
269 }
270 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
271}
272
273export function isRelativeFilePath(path: string): boolean {
274 return (
275 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
276 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
277 );
278}
279
280function looksLikePosixFilesystemPath(path: string): boolean {
281 if (!path.startsWith("/")) return false;
282 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
283 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
284 const basename = path.slice(path.lastIndexOf("/") + 1);
285 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
286}
287
288function looksLikeFilePath(path: string, authoredPath: string): boolean {
289 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
290 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
291 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
292 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
293}
294
295function hasExternalScheme(path: string): boolean {
296 if (isWindowsAbsolutePath(path)) return false;
297 const match = path.match(EXTERNAL_SCHEME_PATTERN);
298 if (!match) return false;
299 const rest = match[2] ?? "";
300 if (rest.startsWith("//")) return true;
301 return !POSITION_ONLY_PATTERN.test(rest);
302}
303
304export function parseMarkdownFileLink(href: string): FilePathPosition | null {
305 const normalized = normalizeMarkdownLinkDestination(href);
306 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
307 return null;
308 }
309
310 const source =
311 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
312 splitMarkdownLinkSearchAndHash(normalized);
313 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
314 const hash = safeDecodeURIComponent(source.hash.trim());
315 if (path.length === 0 || hasExternalScheme(path)) return null;
316
317 const position = parseFilePathLink(path, hash);
318 // `src\a.ts` is Windows-relative. A link that already parses keeps its spelling, since POSIX
319 // names may contain `\`; a rooted `\\host` or `\foo` would change root if rewritten.
320 if (position || /^[\\/]/.test(path) || isWindowsAbsolutePath(path)) return position;
321 return path.includes("\\") ? parseFilePathLink(path.replaceAll("\\", "/"), hash) : null;
322}
323
324function parseFilePathLink(path: string, hash: string): FilePathPosition | null {
325 const position = splitFilePathPosition(path, hash);
326 return looksLikeFilePath(position.path, path) ? position : null;
327}
328
329const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
330
331const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
332
333export function extractInlineCodeSpans(text: string): string[] {
334 const spans: string[] = [];
335 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
336 for (let index = 0; index < segments.length; index += 2) {
337 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
338 const span = match[1]?.trim();
339 if (span) spans.push(span);
340 }
341 }
342 return spans;
343}
344
345function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
346 let runStart = -1;
347 let runEnd = -1;
348 return (start: number) => {
349 if (start >= runStart && start <= runEnd) return runEnd;
350 delimiter.lastIndex = start;
351 runStart = start;
352 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
353 return runEnd;
354 };
355}
356
357function markdownLinkTailScanner(markdown: string) {
358 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
359 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
360 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
361 return (start: number) => {
362 const end = whitespaceEnd(start);
363 if (markdown[end] === ")") return end + 1;
364 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
365 const quoteEnd = titleEnd(end + 1);
366 if (quoteEnd === markdown.length) return null;
367 const close = titleWhitespaceEnd(quoteEnd + 1);
368 return markdown[close] === ")" ? close + 1 : null;
369 };
370}
371
372function markdownLinkDestinationScanner(markdown: string) {
373 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
374 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
375 const bareEnd = markdownRunEndFinder(markdown, /[\s)]/g);
376 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
377 const angleTail = markdownLinkTailScanner(markdown);
378 const bareTail = markdownLinkTailScanner(markdown);
379 return (start: number) => {
380 if (markdown[start] !== "(") return null;
381 const hrefStart = whitespaceEnd(start + 1);
382 if (markdown[hrefStart] === "<") {
383 const hrefEnd = angleEnd(hrefStart + 1);
384 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
385 const end = angleTail(hrefEnd + 1);
386 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
387 }
388 }
389 const hrefEnd = bareEnd(hrefStart);
390 if (hrefEnd === hrefStart) return null;
391 const end = bareTail(hrefEnd);
392 return end === null ? null : { hrefStart, hrefEnd, end };
393 };
394}
395
396export function extractMarkdownLinkHrefs(markdown: string): string[] {
397 const hrefs: string[] = [];
398 const scanDestination = markdownLinkDestinationScanner(markdown);
399 let cursor = 0;
400 while (cursor < markdown.length) {
401 const labelStart = markdown.indexOf("[", cursor);
402 if (labelStart === -1) break;
403 const labelEnd = markdown.indexOf("]", labelStart + 1);
404 if (labelEnd === -1) break;
405
406 // Skip a failed label once; nested openings share its closing bracket.
407 cursor = labelEnd + 1;
408 const destination = scanDestination(cursor);
409 if (!destination) continue;
410 cursor = destination.end;
411 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
412 if (href) hrefs.push(href);
413 }
414 return hrefs;
415}
416
417export function resolveMarkdownFileLinkTarget(
418 href: string | undefined,
419 cwd?: string,
420 baseDir: string | undefined = cwd,
421): string | null {
422 if (!href) return null;
423 const target = parseMarkdownFileLink(href);
424 if (!target) return null;
425
426 const pathWithPosition = formatFilePathPosition(target);
427 if (!isRelativeFilePath(pathWithPosition)) {
428 // Opening a network path makes Windows sign in to its host with the user's
429 // NTLM credentials, so only the project's own share becomes a file link.
430 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
431 ? null
432 : pathWithPosition;
433 }
434 if (!baseDir) return null;
435 return resolvePathLinkTarget(pathWithPosition, baseDir);
436}
437
438export function isWindowsDrivePathHref(href: string): boolean {
439 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
440}