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

markdownLinks.ts

410 lines12.1 KB

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