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