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