Open History to see the last commit
1import type { mediaKindFromPath } from "./mediaPreview.ts";
2import {
3 isNetworkPath,
4 isWindowsAbsolutePath,
5 stripSlashPrefixedWindowsDrive,
6 workspaceRelativeFilePath,
7} from "./path.ts";
8import {
9 type FilePathPosition,
10 formatFilePathPosition,
11 parseFileUrlHref,
12 resolvePathLinkTarget,
13 splitFilePathPosition,
14} from "./fileLinks.ts";
15
16const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
17
18// Names may use any script (`線性代數/考試.pdf`) and routing punctuation (`posts.$id.tsx`,
19// `(group)/[id]/+page.svelte`, `@scope/pkg`). The final segment is optional so an explicit
20// folder link may end in `/` (`patches/`, `docs/My Folder/`). A bare name with no slash still fails.
21const RELATIVE_FILE_PATH_PATTERN =
22 /^(?:[\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+(?::\d+|-\d+)?)?)?$/u;
23
24// No `@` here: `me@example.com` is an address, not a file.
25const RELATIVE_FILE_NAME_PATTERN =
26 /^[\p{L}\p{M}\p{N}._$+()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+()[\]-]+)*\.[\p{L}\p{M}\p{N}_-]+(?::\d+(?::\d+|-\d+)?)?$/u;
27
28const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
29
30const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+|-\d+)?$/;
31
32const POSITION_ONLY_PATTERN = /^\d+(?::\d+|-\d+)?$/;
33
34const INLINE_CODE_WHITESPACE_PATTERN = /\s/;
35
36// Inline code with spaces is a file only when it is absolute and every word is a plain name:
37// `/Users/me/Mobile Documents/a - b.md` is, `/usr/bin/python3 -m venv .venv` (a flag) is not.
38// A space only in the last segment reads as a command (`/usr/local/bin/node server.js`), so it
39// must sit under a user root, and nothing after a bin folder counts.
40const SPACED_ABSOLUTE_PATH_ROOT_PATTERN = /^(?:\/|~\/|[A-Za-z]:[\\/])/;
41const SPACED_PATH_BODY_PATTERN =
42 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: (?!-+\p{L})[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?:[\\/]|$))+$/u;
43
44function isSpacedAbsoluteFilePath(text: string): boolean {
45 const root = SPACED_ABSOLUTE_PATH_ROOT_PATTERN.exec(text)?.[0];
46 if (root === undefined) return false;
47 const body = text.slice(root.length).replace(POSITION_SUFFIX_PATTERN, "");
48 if (!SPACED_PATH_BODY_PATTERN.test(body)) return false;
49 const firstSpace = body.indexOf(" ");
50 const foldersBeforeSpace = body.slice(0, firstSpace).split(PATH_SEPARATOR_PATTERN).slice(0, -1);
51 if (foldersBeforeSpace.some((folder) => folder === "bin" || folder === "sbin")) return false;
52 const spaceInFolder = PATH_SEPARATOR_PATTERN.test(body.slice(firstSpace));
53 if (!spaceInFolder && root === "/" && !/^(?:Users|home)[\\/]/.test(body)) return false;
54 if (PATH_SEPARATOR_PATTERN.test(body.at(-1) ?? "")) return true;
55 const basename = body.split(PATH_SEPARATOR_PATTERN).at(-1) ?? "";
56 return FILE_EXTENSION_PATTERN.test(basename) || EXTENSIONLESS_FILE_NAMES.has(basename);
57}
58
59const PATH_SEPARATOR_PATTERN = /[\\/]/;
60// Agents shorten long paths with a `...` or `…` segment, which no file chip can open.
61const ELIDED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
62
63const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
64const ANY_FILE_EXTENSION_PATTERN = /\.[^./\\]+$/;
65const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
66const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
67
68const POSIX_FILE_ROOT_PREFIXES = [
69 "/Users/",
70 "/home/",
71 "/tmp/",
72 "/var/",
73 "/etc/",
74 "/opt/",
75 "/mnt/",
76 "/Volumes/",
77 "/private/",
78 "/root/",
79 "/usr/",
80 "/bin/",
81 "/sbin/",
82 "/lib/",
83 "/lib64/",
84 "/srv/",
85 "/dev/",
86 "/proc/",
87 "/sys/",
88 "/run/",
89 "/boot/",
90 "/media/",
91 "/workspace/",
92 "/workspaces/",
93] as const;
94
95export const EXTENSIONLESS_FILE_NAMES: ReadonlySet<string> = new Set([
96 "Makefile",
97 "makefile",
98 "GNUmakefile",
99 "Dockerfile",
100 "Containerfile",
101 "Justfile",
102 "justfile",
103 "Rakefile",
104 "Gemfile",
105 "Procfile",
106 "Brewfile",
107 "Caddyfile",
108 "Vagrantfile",
109 "Jenkinsfile",
110 "Podfile",
111 "Fastfile",
112 "BUILD",
113 "WORKSPACE",
114 "LICENSE",
115 "LICENCE",
116 "COPYING",
117 "NOTICE",
118 "AUTHORS",
119 "CONTRIBUTORS",
120 "CHANGELOG",
121 "README",
122 "CODEOWNERS",
123]);
124
125const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
126
127const GENERIC_HOSTNAME_TLDS = new Set([
128 "com",
129 "net",
130 "org",
131 "io",
132 "dev",
133 "app",
134 "ai",
135 "co",
136 "edu",
137 "gov",
138 "mil",
139 "info",
140 "biz",
141 "xyz",
142 "me",
143 "tv",
144 "gg",
145 "chat",
146 "cloud",
147 "site",
148 "online",
149 "tech",
150 "store",
151 "link",
152]);
153
154const COUNTRY_HOSTNAME_TLDS = new Set([
155 "uk",
156 "de",
157 "fr",
158 "nl",
159 "se",
160 "no",
161 "fi",
162 "dk",
163 "pl",
164 "ch",
165 "at",
166 "be",
167 "es",
168 "it",
169 "pt",
170 "eu",
171 "us",
172 "ca",
173 "au",
174 "nz",
175 "jp",
176 "kr",
177 "cn",
178 "br",
179 "ru",
180 "mx",
181 "ie",
182 "cz",
183 "tr",
184 "sg",
185 "hk",
186 // C++ sources end in `.cc`, so `allocator.cc:217` names a file, not a host and port.
187 "cc",
188]);
189
190function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
191 if (segment.startsWith(".")) return false;
192 const lowered = segment.toLowerCase();
193 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
194 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
195 const labels = lowered.split(".");
196 const lastLabel = labels.at(-1);
197 if (labels.length < 2 || lastLabel === undefined) return false;
198 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
199 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
200}
201
202export function inlineCodeFilePathCandidate(codeText: string): string | null {
203 const trimmed = codeText.trim();
204 if (trimmed.length === 0 || trimmed.includes("`") || /[<>]/.test(trimmed)) return null;
205 if (INLINE_CODE_WHITESPACE_PATTERN.test(trimmed) && !isSpacedAbsoluteFilePath(trimmed)) {
206 return null;
207 }
208
209 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
210 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
211 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
212 if (ELIDED_PATH_SEGMENT_PATTERN.test(candidate.replace(POSITION_SUFFIX_PATTERN, ""))) return null;
213
214 const hasExplicitPathShape =
215 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
216 candidate.startsWith("/") ||
217 isWindowsAbsolutePath(candidate);
218 if (!hasExplicitPathShape) {
219 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
220 // Markdown destinations accept `patches/`. Inline code still needs a
221 // file-shaped final segment, so a trailing slash stays plain code.
222 if (withoutPosition.endsWith("/")) return null;
223 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
224 if (looksLikeHostname(firstSegment, hasPosition)) return null;
225 const basename =
226 withoutPosition
227 .replace(/[/\\]+$/, "")
228 .split(/[\\/]/)
229 .at(-1) ?? "";
230 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
231 if (!FILE_EXTENSION_PATTERN.test(basename)) {
232 if (!hasPosition) return EXTENSIONLESS_FILE_NAMES.has(basename) ? candidate : null;
233 // A `:line` suffix alone does not make `I/W217:220` a file reference.
234 if (
235 withoutPosition.includes("/") &&
236 !ANY_FILE_EXTENSION_PATTERN.test(basename) &&
237 !EXTENSIONLESS_FILE_NAMES.has(basename)
238 ) {
239 return null;
240 }
241 }
242 }
243 return candidate;
244}
245
246export function safeDecodeURIComponent(value: string): string {
247 try {
248 return decodeURIComponent(value);
249 } catch {
250 return value;
251 }
252}
253
254export function normalizeMarkdownLinkDestination(value: string): string {
255 const trimmed = value.trim();
256 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
257}
258
259export function splitMarkdownLinkSearchAndHash(value: string): {
260 readonly path: string;
261 readonly hash: string;
262} {
263 const hashIndex = value.indexOf("#");
264 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
265 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
266 const queryIndex = pathWithSearch.indexOf("?");
267 return {
268 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
269 hash,
270 };
271}
272
273/**
274 * The decoded path a markdown destination names on the host, before any workspace resolution, or
275 * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.
276 */
277export function markdownDestinationHostPath(source: string): string | null {
278 if (/^file:/i.test(source)) {
279 const target = parseFileUrlHref(source);
280 return target === null
281 ? null
282 : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));
283 }
284 return stripSlashPrefixedWindowsDrive(
285 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
286 );
287}
288
289const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
290const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
291
292export type MarkdownImageSource =
293 | { readonly _tag: "Direct"; readonly uri: string }
294 | { readonly _tag: "WorkspaceFile"; readonly path: string; readonly relative?: true }
295 | { readonly _tag: "Blocked" };
296
297function joinWorkspacePath(workspaceRoot: string, relativePath: string): string {
298 const separator = isWindowsAbsolutePath(workspaceRoot) ? "\\" : "/";
299 const root = workspaceRoot.replace(/[\\/]+$/, "");
300 const path = relativePath.replace(/[\\/]/g, separator).replace(/^[\\/]+/, "");
301 return `${root}${separator}${path}`;
302}
303
304/** Rendering is not a click, so a network path loads only from the project's own share. */
305function hostFileSource(
306 path: string,
307 workspaceRoot: string | null | undefined,
308): MarkdownImageSource {
309 return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
310 ? { _tag: "Blocked" }
311 : { _tag: "WorkspaceFile", path };
312}
313
314/**
315 * Filesystem paths belong to the environment host and must never reach a
316 * browser or native image component without first becoming a signed asset URL.
317 */
318export function classifyMarkdownImageSource(
319 value: string | null | undefined,
320 workspaceRoot?: string | null,
321): MarkdownImageSource {
322 if (value === null || value === undefined) return { _tag: "Blocked" };
323
324 const source = normalizeMarkdownLinkDestination(value);
325 if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {
326 return { _tag: "Blocked" };
327 }
328 if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {
329 return { _tag: "Direct", uri: source };
330 }
331
332 const path = markdownDestinationHostPath(source);
333 if (path === null) return { _tag: "Blocked" };
334 if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot);
335 if (path.length === 0) return { _tag: "Blocked" };
336 if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
337 return hostFileSource(path, workspaceRoot);
338 }
339 if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
340 return { _tag: "Blocked" };
341 }
342 if (!workspaceRoot) return { _tag: "Blocked" };
343
344 return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path), relative: true };
345}
346
347export function shouldRenderMarkdownImageAsFileLink(
348 source: MarkdownImageSource,
349 mediaKind: ReturnType<typeof mediaKindFromPath>,
350): boolean {
351 return source._tag === "WorkspaceFile" && mediaKind === null;
352}
353
354export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
355 const destination = parseMarkdownFileLink(href);
356 if (!destination) return false;
357 const normalize = (path: string) =>
358 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
359 const labelPosition = splitFilePathPosition(label.trim());
360 if (
361 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
362 (labelPosition.column !== undefined && labelPosition.column !== destination.column) ||
363 (labelPosition.endLine !== undefined && labelPosition.endLine !== destination.endLine)
364 ) {
365 return false;
366 }
367 let labelPath = normalize(labelPosition.path);
368 let destinationPath = normalize(destination.path);
369 if (labelPath.length === 0) return true;
370 if (isWindowsAbsolutePath(destination.path)) {
371 labelPath = labelPath.toLowerCase();
372 destinationPath = destinationPath.toLowerCase();
373 }
374 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
375}
376
377export function isRelativeFilePath(path: string): boolean {
378 return (
379 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
380 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
381 );
382}
383
384function looksLikePosixFilesystemPath(path: string): boolean {
385 if (!path.startsWith("/")) return false;
386 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
387 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
388 const basename = path.slice(path.lastIndexOf("/") + 1);
389 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
390}
391
392function looksLikeFilePath(path: string, authoredPath: string): boolean {
393 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
394 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
395 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
396 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
397}
398
399function hasExternalScheme(path: string): boolean {
400 if (isWindowsAbsolutePath(path)) return false;
401 const match = path.match(EXTERNAL_SCHEME_PATTERN);
402 if (!match) return false;
403 const rest = match[2] ?? "";
404 if (rest.startsWith("//")) return true;
405 return !POSITION_ONLY_PATTERN.test(rest);
406}
407
408export function parseMarkdownFileLink(href: string): FilePathPosition | null {
409 const normalized = normalizeMarkdownLinkDestination(href);
410 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
411 return null;
412 }
413
414 const source =
415 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
416 splitMarkdownLinkSearchAndHash(normalized);
417 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
418 const hash = safeDecodeURIComponent(source.hash.trim());
419 if (path.length === 0 || hasExternalScheme(path)) return null;
420
421 const position = parseFilePathLink(path, hash);
422 // `src\a.ts` is Windows-relative. A link that already parses keeps its spelling, since POSIX
423 // names may contain `\`; a rooted `\\host` or `\foo` would change root if rewritten.
424 if (position || /^[\\/]/.test(path) || isWindowsAbsolutePath(path)) return position;
425 return path.includes("\\") ? parseFilePathLink(path.replaceAll("\\", "/"), hash) : null;
426}
427
428function parseFilePathLink(path: string, hash: string): FilePathPosition | null {
429 const position = splitFilePathPosition(path, hash);
430 return !ELIDED_PATH_SEGMENT_PATTERN.test(position.path) && looksLikeFilePath(position.path, path)
431 ? position
432 : null;
433}
434
435const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
436
437const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
438
439export function extractInlineCodeSpans(text: string): string[] {
440 const spans: string[] = [];
441 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
442 for (let index = 0; index < segments.length; index += 2) {
443 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
444 const span = match[1]?.trim();
445 if (span) spans.push(span);
446 }
447 }
448 return spans;
449}
450
451function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
452 let runStart = -1;
453 let runEnd = -1;
454 return (start: number) => {
455 if (start >= runStart && start <= runEnd) return runEnd;
456 delimiter.lastIndex = start;
457 runStart = start;
458 let match = delimiter.exec(markdown);
459 while (match?.[0].length === 2 && match[0][0] === "\\") match = delimiter.exec(markdown);
460 runEnd = match?.index ?? markdown.length;
461 return runEnd;
462 };
463}
464
465function markdownLinkTailScanner(markdown: string) {
466 // A blank line ends the paragraph, so no part of a link's tail runs past one.
467 const whitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g);
468 // Escape pairs (`\"`, `\\`) match so the finder can skip them.
469 const doubleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\"]|"|\n[ \t\r]*\n/g);
470 const singleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\']|'|\n[ \t\r]*\n/g);
471 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g);
472 return (start: number) => {
473 const end = whitespaceEnd(start);
474 const quote = markdown[end];
475 if (quote === ")") return end + 1;
476 if (end === start || (quote !== '"' && quote !== "'")) return null;
477 const quoteEnd = (quote === '"' ? doubleQuoteEnd : singleQuoteEnd)(end + 1);
478 if (markdown[quoteEnd] !== quote) return null;
479 const close = titleWhitespaceEnd(quoteEnd + 1);
480 return markdown[close] === ")" ? close + 1 : null;
481 };
482}
483
484// micromark's own nesting limit. It also keeps link scanning linear: a scan only runs past another
485// link's opening parenthesis while that parenthesis counts toward this depth.
486const MAX_BARE_DESTINATION_PAREN_DEPTH = 32;
487
488function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null {
489 const delimiter = /[\s()\\]/g;
490 delimiter.lastIndex = start;
491 let depth = 0;
492 while (true) {
493 const index = delimiter.exec(markdown)?.index ?? markdown.length;
494 const char = markdown[index];
495 if (char === "\\") {
496 if (/[()\\]/.test(markdown[index + 1] ?? "")) delimiter.lastIndex = index + 2;
497 } else if (char === "(") {
498 if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null;
499 depth += 1;
500 } else if (char === ")" && depth > 0) {
501 depth -= 1;
502 } else {
503 return depth === 0 ? index : null;
504 }
505 }
506}
507
508function markdownLinkDestinationScanner(markdown: string) {
509 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
510 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
511 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
512 const angleTail = markdownLinkTailScanner(markdown);
513 const bareTail = markdownLinkTailScanner(markdown);
514 return (start: number) => {
515 if (markdown[start] !== "(") return null;
516 const hrefStart = whitespaceEnd(start + 1);
517 if (markdown[hrefStart] === "<") {
518 const hrefEnd = angleEnd(hrefStart + 1);
519 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
520 const end = angleTail(hrefEnd + 1);
521 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
522 }
523 }
524 const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart);
525 if (hrefEnd === null) return null;
526 const end = bareTail(hrefEnd);
527 return end === null ? null : { hrefStart, hrefEnd, end };
528 };
529}
530
531// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them
532// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels.
533export function extractMarkdownLinkHrefs(markdown: string): string[] {
534 const hrefs: string[] = [];
535 const scanDestination = markdownLinkDestinationScanner(markdown);
536 const bracket = /[[\]\\]|\n[ \t\r]*\n/g;
537 let openBrackets = 0;
538 for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) {
539 if (match[0] === "\\") {
540 bracket.lastIndex = match.index + 2;
541 } else if (match[0].startsWith("\n")) {
542 openBrackets = 0;
543 } else if (match[0] === "[") {
544 openBrackets += 1;
545 } else if (openBrackets > 0) {
546 openBrackets -= 1;
547 const destination = scanDestination(match.index + 1);
548 if (!destination) continue;
549 // A link cannot contain a link, so the brackets still open around it become text.
550 openBrackets = 0;
551 bracket.lastIndex = destination.end;
552 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
553 if (href) hrefs.push(href);
554 }
555 }
556 return hrefs;
557}
558
559export function resolveMarkdownFileLinkTarget(
560 href: string | undefined,
561 cwd?: string,
562 baseDir: string | undefined = cwd,
563): string | null {
564 return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null;
565}
566
567/** Resolves the displayed position and the editor target, which opens at the start line. */
568export function resolveMarkdownFileLink(
569 href: string | undefined,
570 cwd?: string,
571 baseDir: string | undefined = cwd,
572): { sourcePath: string; targetPath: string; position: FilePathPosition } | null {
573 const source = href ? parseMarkdownFileLink(href) : null;
574 if (!source) return null;
575
576 const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir);
577 if (!targetPath) return null;
578 return {
579 sourcePath: source.path,
580 targetPath,
581 position: {
582 ...splitFilePathPosition(targetPath),
583 ...(source.endLine !== undefined ? { endLine: source.endLine } : {}),
584 },
585 };
586}
587
588function resolveParsedFileLinkTarget(
589 target: FilePathPosition,
590 cwd: string | undefined,
591 baseDir: string | undefined,
592): string | null {
593 const pathWithPosition = formatFilePathPosition(target);
594 if (!isRelativeFilePath(pathWithPosition)) {
595 // Opening a network path makes Windows sign in to its host with the user's
596 // NTLM credentials, so only the project's own share becomes a file link.
597 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
598 ? null
599 : pathWithPosition;
600 }
601 if (!baseDir) return null;
602 return resolvePathLinkTarget(pathWithPosition, baseDir);
603}
604
605export function isWindowsDrivePathHref(href: string): boolean {
606 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
607}
608
609// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
610// and a file-shaped last segment.
611export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
612 const paths: Array<{ index: number; path: string }> = [];
613 for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
614 const source = match[2]!;
615 let parentheses = 0;
616 let brackets = 0;
617 for (const character of source) {
618 if (character === "(") parentheses += 1;
619 if (character === ")") parentheses -= 1;
620 if (character === "[") brackets += 1;
621 if (character === "]") brackets -= 1;
622 }
623 let end = source.length;
624 while (end > 0) {
625 const character = source[end - 1]!;
626 if (character === ")" && parentheses < 0) parentheses += 1;
627 else if (character === "]" && brackets < 0) brackets += 1;
628 else if (!".,;!?:".includes(character)) break;
629 end -= 1;
630 }
631 const path = source.slice(0, end);
632 // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
633 if (path.endsWith("/") && source.startsWith("...", end)) continue;
634 if (
635 !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
636 !POSITION_SUFFIX_PATTERN.test(path)
637 )
638 continue;
639 // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
640 const basename = path.slice(path.lastIndexOf("/") + 1);
641 if (
642 !POSITION_SUFFIX_PATTERN.test(path) &&
643 !FILE_EXTENSION_PATTERN.test(basename) &&
644 !EXTENSIONLESS_FILE_NAMES.has(basename)
645 )
646 continue;
647 if (!parseMarkdownFileLink(path)) continue;
648 paths.push({ index: match.index + match[1]!.length, path });
649 }
650 return paths;
651}
652
653// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
654export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;