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
230export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
231 const destination = parseMarkdownFileLink(href);
232 if (!destination) return false;
233 const normalize = (path: string) =>
234 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
235 const labelPosition = splitFilePathPosition(label.trim());
236 if (
237 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
238 (labelPosition.column !== undefined && labelPosition.column !== destination.column)
239 ) {
240 return false;
241 }
242 let labelPath = normalize(labelPosition.path);
243 let destinationPath = normalize(destination.path);
244 if (labelPath.length === 0) return true;
245 if (isWindowsAbsolutePath(destination.path)) {
246 labelPath = labelPath.toLowerCase();
247 destinationPath = destinationPath.toLowerCase();
248 }
249 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
250}
251
252export function isRelativeFilePath(path: string): boolean {
253 return (
254 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
255 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
256 );
257}
258
259function looksLikePosixFilesystemPath(path: string): boolean {
260 if (!path.startsWith("/")) return false;
261 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
262 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
263 const basename = path.slice(path.lastIndexOf("/") + 1);
264 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
265}
266
267function looksLikeFilePath(path: string, authoredPath: string): boolean {
268 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
269 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
270 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
271 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
272}
273
274function hasExternalScheme(path: string): boolean {
275 if (isWindowsAbsolutePath(path)) return false;
276 const match = path.match(EXTERNAL_SCHEME_PATTERN);
277 if (!match) return false;
278 const rest = match[2] ?? "";
279 if (rest.startsWith("//")) return true;
280 return !POSITION_ONLY_PATTERN.test(rest);
281}
282
283export function parseMarkdownFileLink(href: string): FilePathPosition | null {
284 const normalized = normalizeMarkdownLinkDestination(href);
285 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
286 return null;
287 }
288
289 const source =
290 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
291 splitMarkdownLinkSearchAndHash(normalized);
292 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
293 const hash = safeDecodeURIComponent(source.hash.trim());
294 if (path.length === 0 || hasExternalScheme(path)) return null;
295
296 const position = splitFilePathPosition(path, hash);
297 return looksLikeFilePath(position.path, path) ? position : null;
298}
299
300const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
301
302const INLINE_CODE_SPAN_PATTERN = /`([^`\n]+)`/g;
303
304export function extractInlineCodeSpans(text: string): string[] {
305 const spans: string[] = [];
306 const segments = text.split(FENCED_CODE_SEGMENT_PATTERN);
307 for (let index = 0; index < segments.length; index += 2) {
308 for (const match of (segments[index] ?? "").matchAll(INLINE_CODE_SPAN_PATTERN)) {
309 const span = match[1]?.trim();
310 if (span) spans.push(span);
311 }
312 }
313 return spans;
314}
315
316function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
317 let runStart = -1;
318 let runEnd = -1;
319 return (start: number) => {
320 if (start >= runStart && start <= runEnd) return runEnd;
321 delimiter.lastIndex = start;
322 runStart = start;
323 runEnd = delimiter.exec(markdown)?.index ?? markdown.length;
324 return runEnd;
325 };
326}
327
328function markdownLinkTailScanner(markdown: string) {
329 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
330 const titleEnd = markdownRunEndFinder(markdown, /["']/g);
331 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
332 return (start: number) => {
333 const end = whitespaceEnd(start);
334 if (markdown[end] === ")") return end + 1;
335 if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null;
336 const quoteEnd = titleEnd(end + 1);
337 if (quoteEnd === markdown.length) return null;
338 const close = titleWhitespaceEnd(quoteEnd + 1);
339 return markdown[close] === ")" ? close + 1 : null;
340 };
341}
342
343function markdownLinkDestinationScanner(markdown: string) {
344 const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g);
345 const angleEnd = markdownRunEndFinder(markdown, /[>\n]/g);
346 const bareEnd = markdownRunEndFinder(markdown, /[\s)]/g);
347 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
348 const angleTail = markdownLinkTailScanner(markdown);
349 const bareTail = markdownLinkTailScanner(markdown);
350 return (start: number) => {
351 if (markdown[start] !== "(") return null;
352 const hrefStart = whitespaceEnd(start + 1);
353 if (markdown[hrefStart] === "<") {
354 const hrefEnd = angleEnd(hrefStart + 1);
355 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
356 const end = angleTail(hrefEnd + 1);
357 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
358 }
359 }
360 const hrefEnd = bareEnd(hrefStart);
361 if (hrefEnd === hrefStart) return null;
362 const end = bareTail(hrefEnd);
363 return end === null ? null : { hrefStart, hrefEnd, end };
364 };
365}
366
367export function extractMarkdownLinkHrefs(markdown: string): string[] {
368 const hrefs: string[] = [];
369 const scanDestination = markdownLinkDestinationScanner(markdown);
370 let cursor = 0;
371 while (cursor < markdown.length) {
372 const labelStart = markdown.indexOf("[", cursor);
373 if (labelStart === -1) break;
374 const labelEnd = markdown.indexOf("]", labelStart + 1);
375 if (labelEnd === -1) break;
376
377 // Skip a failed label once; nested openings share its closing bracket.
378 cursor = labelEnd + 1;
379 const destination = scanDestination(cursor);
380 if (!destination) continue;
381 cursor = destination.end;
382 const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim();
383 if (href) hrefs.push(href);
384 }
385 return hrefs;
386}
387
388export function resolveMarkdownFileLinkTarget(
389 href: string | undefined,
390 cwd?: string,
391 baseDir: string | undefined = cwd,
392): string | null {
393 if (!href) return null;
394 const target = parseMarkdownFileLink(href);
395 if (!target) return null;
396
397 const pathWithPosition = formatFilePathPosition(target);
398 if (!isRelativeFilePath(pathWithPosition)) {
399 // Opening a network path makes Windows sign in to its host with the user's
400 // NTLM credentials, so only the project's own share becomes a file link.
401 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
402 ? null
403 : pathWithPosition;
404 }
405 if (!baseDir) return null;
406 return resolvePathLinkTarget(pathWithPosition, baseDir);
407}
408
409export function isWindowsDrivePathHref(href: string): boolean {
410 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
411}