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

markdownLinks.ts

650 lines22.3 KB

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);
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);
201​
202export function inlineCodeFilePathCandidate(codeText: string): string | null {
203 const trimmed = codeText.trim();
204 if (trimmed.length === 0 || trimmed.includes("`")) 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;
245​
246export function safeDecodeURIComponent(value: string): string {
247 try {
248 return decodeURIComponent(value);
249 } catch {
250 return value;
251 }
253​
254export function normalizeMarkdownLinkDestination(value: string): string {
255 const trimmed = value.trim();
256 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
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 };
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 );
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}`;
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 };
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 };
346​
347export function shouldRenderMarkdownImageAsFileLink(
348 source: MarkdownImageSource,
349 mediaKind: ReturnType<typeof mediaKindFromPath>,
350): boolean {
351 return source._tag === "WorkspaceFile" && mediaKind === null;
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}`);
376​
377export function isRelativeFilePath(path: string): boolean {
378 return (
379 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
380 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
381 );
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);
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);
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);
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;
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;
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;
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 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
459 return runEnd;
460 };
462​
463function markdownLinkTailScanner(markdown: string) {
464 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
465 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
466 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
467 return (start: number) => {
468 const end = whitespaceEnd(start);
469 if (markdown[end] === ")") return end + 1;
470 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
471 const quoteEnd = titleEnd(end + 1);
472 if (quoteEnd === markdown.length) return null;
473 const close = titleWhitespaceEnd(quoteEnd + 1);
474 return markdown[close] === ")" ? close + 1 : null;
475 };
477​
478// micromark's own nesting limit. It also keeps link scanning linear: a scan only runs past another
479// link's opening parenthesis while that parenthesis counts toward this depth.
480const MAX_BARE_DESTINATION_PAREN_DEPTH = 32;
481​
482function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null {
483 const delimiter = /[\s()\\]/g;
484 delimiter.lastIndex = start;
485 let depth = 0;
486 while (true) {
487 const index = delimiter.exec(markdown)?.index ?? markdown.length;
488 const char = markdown[index];
489 if (char === "\\") {
490 if (/[()\\]/.test(markdown[index + 1] ?? "")) delimiter.lastIndex = index + 2;
491 } else if (char === "(") {
492 if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null;
493 depth += 1;
494 } else if (char === ")" && depth > 0) {
495 depth -= 1;
496 } else {
497 return depth === 0 ? index : null;
498 }
499 }
501​
502function markdownLinkDestinationScanner(markdown: string) {
503 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
504 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
505 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
506 const angleTail = markdownLinkTailScanner(markdown);
507 const bareTail = markdownLinkTailScanner(markdown);
508 return (start: number) => {
509 if (markdown[start] !== "(") return null;
510 const hrefStart = whitespaceEnd(start + 1);
511 if (markdown[hrefStart] === "<") {
512 const hrefEnd = angleEnd(hrefStart + 1);
513 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
514 const end = angleTail(hrefEnd + 1);
515 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
516 }
517 }
518 const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart);
519 if (hrefEnd === null || hrefEnd === hrefStart) return null;
520 const end = bareTail(hrefEnd);
521 return end === null ? null : { hrefStart, hrefEnd, end };
522 };
524​
525// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one.
526function unescapedLabelEnd(markdown: string, start: number): number {
527 let end = markdown.indexOf("]", start);
528 while (end !== -1) {
529 let backslashes = 0;
530 while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1;
531 if (backslashes % 2 === 0) return end;
532 end = markdown.indexOf("]", end + 1);
533 }
534 return -1;
536​
537export function extractMarkdownLinkHrefs(markdown: string): string[] {
538 const hrefs: string[] = [];
539 const scanDestination = markdownLinkDestinationScanner(markdown);
540 let cursor = 0;
541 while (cursor < markdown.length) {
542 const labelStart = markdown.indexOf("[", cursor);
543 if (labelStart === -1) break;
544 const labelEnd = unescapedLabelEnd(markdown, labelStart + 1);
545 if (labelEnd === -1) break;
546​
547 // Skip a failed label once; nested openings share its closing bracket.
548 cursor = labelEnd + 1;
549 const destination = scanDestination(cursor);
550 if (!destination) continue;
551 cursor = destination.end;
552 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
553 if (href) hrefs.push(href);
554 }
555 return hrefs;
557​
558export function resolveMarkdownFileLinkTarget(
559 href: string | undefined,
560 cwd?: string,
561 baseDir: string | undefined = cwd,
562): string | null {
563 return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null;
565​
566/** Resolves the displayed position and the editor target, which opens at the start line. */
567export function resolveMarkdownFileLink(
568 href: string | undefined,
569 cwd?: string,
570 baseDir: string | undefined = cwd,
571): { sourcePath: string; targetPath: string; position: FilePathPosition } | null {
572 const source = href ? parseMarkdownFileLink(href) : null;
573 if (!source) return null;
574​
575 const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir);
576 if (!targetPath) return null;
577 return {
578 sourcePath: source.path,
579 targetPath,
580 position: {
581 ...splitFilePathPosition(targetPath),
582 ...(source.endLine !== undefined ? { endLine: source.endLine } : {}),
583 },
584 };
586​
587function resolveParsedFileLinkTarget(
588 target: FilePathPosition,
589 cwd: string | undefined,
590 baseDir: string | undefined,
591): string | null {
592 const pathWithPosition = formatFilePathPosition(target);
593 if (!isRelativeFilePath(pathWithPosition)) {
594 // Opening a network path makes Windows sign in to its host with the user's
595 // NTLM credentials, so only the project's own share becomes a file link.
596 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
597 ? null
598 : pathWithPosition;
599 }
600 if (!baseDir) return null;
601 return resolvePathLinkTarget(pathWithPosition, baseDir);
603​
604export function isWindowsDrivePathHref(href: string): boolean {
605 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
607​
608// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
609// and a file-shaped last segment.
610export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
611 const paths: Array<{ index: number; path: string }> = [];
612 for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
613 const source = match[2]!;
614 let parentheses = 0;
615 let brackets = 0;
616 for (const character of source) {
617 if (character === "(") parentheses += 1;
618 if (character === ")") parentheses -= 1;
619 if (character === "[") brackets += 1;
620 if (character === "]") brackets -= 1;
621 }
622 let end = source.length;
623 while (end > 0) {
624 const character = source[end - 1]!;
625 if (character === ")" && parentheses < 0) parentheses += 1;
626 else if (character === "]" && brackets < 0) brackets += 1;
627 else if (!".,;!?:".includes(character)) break;
628 end -= 1;
629 }
630 const path = source.slice(0, end);
631 // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
632 if (path.endsWith("/") && source.startsWith("...", end)) continue;
633 if (
634 !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
635 !POSITION_SUFFIX_PATTERN.test(path)
636 )
637 continue;
638 // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
639 const basename = path.slice(path.lastIndexOf("/") + 1);
640 if (
641 !POSITION_SUFFIX_PATTERN.test(path) &&
642 !FILE_EXTENSION_PATTERN.test(basename) &&
643 !EXTENSIONLESS_FILE_NAMES.has(basename)
644 )
645 continue;
646 if (!parseMarkdownFileLink(path)) continue;
647 paths.push({ index: match.index + match[1]!.length, path });
648 }
649 return paths;