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

markdown-links.ts

439 lines13.6 KB

1import { formatWorkspaceRelativePath } from "./filePathDisplay";
2import {
3 isTerminalLinkActivation,
4 resolvePathLinkTarget,
5 splitPathAndPosition,
6} from "./terminal-links";
7​
8const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
9const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
10const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
11const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
12const RELATIVE_FILE_PATH_PATTERN =
13 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
14const RELATIVE_FILE_NAME_PATTERN =
15 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
16const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
17const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
18// Standard OS and dev-container roots; deliberately excludes app-route-ish
19// prefixes like /app/ or /chat/ so SPA routes never read as files.
20const POSIX_FILE_ROOT_PREFIXES = [
21 "/Users/",
22 "/home/",
23 "/tmp/",
24 "/var/",
25 "/etc/",
26 "/opt/",
27 "/mnt/",
28 "/Volumes/",
29 "/private/",
30 "/root/",
31 "/usr/",
32 "/bin/",
33 "/sbin/",
34 "/lib/",
35 "/lib64/",
36 "/srv/",
37 "/dev/",
38 "/proc/",
39 "/sys/",
40 "/run/",
41 "/boot/",
42 "/media/",
43 "/workspace/",
44 "/workspaces/",
45] as const;
46const MARKDOWN_LINK_HREF_PATTERN =
47 /\[[^\]]*]\(\s*(?:<([^>\n]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/g;
48​
49export interface MarkdownFileLinkMeta {
50 filePath: string;
51 targetPath: string;
52 displayPath: string;
53 workspaceRelativePath: string | null;
54 basename: string;
55 line?: number;
56 column?: number;
58​
59export function extractMarkdownLinkHrefs(markdown: string): string[] {
60 const hrefs: string[] = [];
61 for (const match of markdown.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
62 const href = (match[1] ?? match[2])?.trim();
63 if (href) hrefs.push(href);
64 }
65 return hrefs;
67​
68export function shouldOpenMarkdownFileLinkInEditor(
69 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
70 platform?: string,
71): boolean {
72 return isTerminalLinkActivation(event, platform);
74​
75export function shouldOpenMarkdownFileLinkInBrowserByDefault(path: string): boolean {
76 return /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
78​
79function safeDecode(value: string): string {
80 try {
81 return decodeURIComponent(value);
82 } catch {
83 return value;
84 }
86​
87function unwrapMarkdownLinkDestination(value: string): string {
88 return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
90​
91export function normalizeMarkdownLinkDestination(value: string): string {
92 return unwrapMarkdownLinkDestination(value.trim());
94​
95function stripSearchAndHash(value: string): { path: string; hash: string } {
96 const hashIndex = value.indexOf("#");
97 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
98 const rawHash = hashIndex >= 0 ? value.slice(hashIndex) : "";
99 const queryIndex = pathWithSearch.indexOf("?");
100 const path = queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch;
101 return { path, hash: rawHash };
103​
104function normalizeWindowsDrivePath(path: string): string {
105 return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
107​
108function parseFileUrlHref(
109 href: string,
110 options?: { readonly decodePath?: boolean },
111): { path: string; hash: string } | null {
112 try {
113 const parsed = new URL(href);
114 if (parsed.protocol.toLowerCase() !== "file:") return null;
115​
116 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
117 const rawPath = uncHostname
118 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
119 : parsed.pathname;
120 if (rawPath.length === 0) return null;
121​
122 // Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
123 const normalizedPath = normalizeWindowsDrivePath(rawPath);
124​
125 return {
126 path: options?.decodePath === false ? normalizedPath : safeDecode(normalizedPath),
127 hash: parsed.hash,
128 };
129 } catch {
130 return null;
131 }
133​
134export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
135 if (!href) return null;
136 const normalizedHref = normalizeMarkdownLinkDestination(href);
137 const target = parseFileUrlHref(normalizedHref, { decodePath: false });
138 if (!target) return null;
139 return `${target.path}${target.hash}`;
141​
142function looksLikePosixFilesystemPath(path: string): boolean {
143 if (!path.startsWith("/")) return false;
144 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
145 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
146 const basename = path.slice(path.lastIndexOf("/") + 1);
147 return /\.[A-Za-z0-9_-]+$/.test(basename);
149​
150function appendLineColumnFromHash(path: string, hash: string): string {
151 if (!hash || POSITION_SUFFIX_PATTERN.test(path)) return path;
152 const match = hash.match(/^#L(\d+)(?:C(\d+))?$/i);
153 if (!match?.[1]) return path;
154 const line = match[1];
155 const column = match[2];
156 return `${path}:${line}${column ? `:${column}` : ""}`;
158​
159function isLikelyPathCandidate(path: string): boolean {
160 if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
161 if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
162 if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
163 return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
165​
166function isRelativePath(path: string): boolean {
167 return (
168 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
169 (!path.startsWith("/") &&
170 !WINDOWS_DRIVE_PATH_PATTERN.test(path) &&
171 !WINDOWS_UNC_PATH_PATTERN.test(path))
172 );
174​
175function hasExternalScheme(path: string): boolean {
176 const match = path.match(EXTERNAL_SCHEME_PATTERN);
177 if (!match) return false;
178 const rest = match[2] ?? "";
179 if (rest.startsWith("//")) return true;
180 return !POSITION_ONLY_PATTERN.test(rest);
182​
183export function resolveMarkdownFileLinkTarget(
184 href: string | undefined,
185 cwd?: string,
186): string | null {
187 if (!href) return null;
188 const rawHref = normalizeMarkdownLinkDestination(href);
189 if (rawHref.length === 0 || rawHref.startsWith("#")) return null;
190​
191 const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
192 ? parseFileUrlHref(rawHref)
193 : null;
194 const source = fileUrlTarget ?? stripSearchAndHash(rawHref);
195 const decodedPath = normalizeWindowsDrivePath(
196 fileUrlTarget ? source.path.trim() : safeDecode(source.path.trim()),
197 );
198 const decodedHash = safeDecode(source.hash.trim());
199​
200 if (decodedPath.length === 0) return null;
201 if (
202 !WINDOWS_DRIVE_PATH_PATTERN.test(decodedPath) &&
203 !WINDOWS_UNC_PATH_PATTERN.test(decodedPath) &&
204 hasExternalScheme(decodedPath)
205 ) {
206 return null;
207 }
208​
209 if (!isLikelyPathCandidate(decodedPath)) return null;
210​
211 const pathWithPosition = appendLineColumnFromHash(decodedPath, decodedHash);
212 if (!isRelativePath(pathWithPosition)) {
213 return pathWithPosition;
214 }
215​
216 if (!cwd) return null;
217 return resolvePathLinkTarget(pathWithPosition, cwd);
219​
220const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
221const PATH_SEPARATOR_PATTERN = /[\\/]/;
222const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
223const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
224const BARE_EXTENSIONLESS_POSITION_PATTERN = /^[A-Za-z0-9_-]+(?::\d+){1,2}$/;
225// Any `Name:digits` shape also matches `error:1`, `port:3000`, `TODO:12`, so
226// extensionless linking is limited to conventional filenames.
227const EXTENSIONLESS_FILE_NAMES = new Set([
228 "Makefile",
229 "makefile",
230 "GNUmakefile",
231 "Dockerfile",
232 "Containerfile",
233 "Justfile",
234 "justfile",
235 "Rakefile",
236 "Gemfile",
237 "Procfile",
238 "Brewfile",
239 "Caddyfile",
240 "Vagrantfile",
241 "Jenkinsfile",
242 "Podfile",
243 "Fastfile",
244 "BUILD",
245 "WORKSPACE",
246 "LICENSE",
247 "LICENCE",
248 "COPYING",
249 "NOTICE",
250 "AUTHORS",
251 "CONTRIBUTORS",
252 "CHANGELOG",
253 "README",
254 "CODEOWNERS",
255]);
256const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
257// Allowlists, not full public-suffix detection: treating every dotted first
258// segment as a host would swallow real paths like `conf.d/x.conf` or
259// `Makefile.in:12`. Extensions that double as filename suffixes (`sh`, `md`,
260// `ts`, `rs`, `in`, ...) are deliberately absent from both sets.
261const GENERIC_HOSTNAME_TLDS = new Set([
262 "com",
263 "net",
264 "org",
265 "io",
266 "dev",
267 "app",
268 "ai",
269 "co",
270 "edu",
271 "gov",
272 "mil",
273 "info",
274 "biz",
275 "xyz",
276 "me",
277 "tv",
278 "cc",
279 "gg",
280 "chat",
281 "cloud",
282 "site",
283 "online",
284 "tech",
285 "store",
286 "link",
287]);
288// Country codes collide with file extensions (`.pl` Perl, `.pt` PyTorch,
289// `.es` ES modules), so they only count as host evidence when the candidate
290// lacks a :line suffix — an explicit line reference marks a file and wins.
291const COUNTRY_HOSTNAME_TLDS = new Set([
292 "uk",
293 "de",
294 "fr",
295 "nl",
296 "se",
297 "no",
298 "fi",
299 "dk",
300 "pl",
301 "ch",
302 "at",
303 "be",
304 "es",
305 "it",
306 "pt",
307 "eu",
308 "us",
309 "ca",
310 "au",
311 "nz",
312 "jp",
313 "kr",
314 "cn",
315 "br",
316 "ru",
317 "mx",
318 "ie",
319 "cz",
320 "tr",
321 "sg",
322 "hk",
323]);
324​
325/** `127.0.0.1`, `localhost`, `example.com`, `1.2.3` — hosts and versions, not files. */
326function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
327 if (segment.startsWith(".")) return false;
328 const lowered = segment.toLowerCase();
329 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
330 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
331 const labels = lowered.split(".");
332 const lastLabel = labels[labels.length - 1];
333 if (labels.length < 2 || lastLabel === undefined) return false;
334 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
335 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
337​
338/**
339 * Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
340 * `origin/main`) rather than deliberate link destinations, so auto-linking
341 * them demands stronger path evidence than an explicit markdown link does:
342 * an unambiguous path prefix, a file extension, or a :line suffix.
343 */
344export function resolveInlineCodeFileLinkMeta(
345 codeText: string,
346 cwd?: string,
347): MarkdownFileLinkMeta | null {
348 const trimmed = codeText.trim();
349 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
350​
351 // Windows drive/UNC paths keep their backslashes; any other backslashes are
352 // relative Windows-style paths, which neither the shape checks nor the
353 // downstream resolver understand — normalize them to forward slashes.
354 const candidate =
355 WINDOWS_DRIVE_PATH_PATTERN.test(trimmed) || WINDOWS_UNC_PATH_PATTERN.test(trimmed)
356 ? trimmed
357 : trimmed.replaceAll("\\", "/");
358​
359 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
360 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
361​
362 const hasExplicitPathShape =
363 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
364 candidate.startsWith("/") ||
365 WINDOWS_DRIVE_PATH_PATTERN.test(candidate) ||
366 WINDOWS_UNC_PATH_PATTERN.test(candidate);
367 if (!hasExplicitPathShape) {
368 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
369 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
370 if (looksLikeHostname(firstSegment, hasPosition)) return null;
371 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basenameOfPath(withoutPosition))) {
372 return null;
373 }
374 }
375​
376 const resolved = resolveMarkdownFileLinkMeta(candidate, cwd);
377 if (resolved) return resolved;
378​
379 // `Makefile:12` — conventional extensionless names fail the generic
380 // markdown-link candidate patterns, but here the :line suffix already
381 // marked the span as a file reference.
382 if (
383 cwd &&
384 BARE_EXTENSIONLESS_POSITION_PATTERN.test(candidate) &&
385 EXTENSIONLESS_FILE_NAMES.has(candidate.replace(POSITION_SUFFIX_PATTERN, ""))
386 ) {
387 return buildFileLinkMetaFromTarget(resolvePathLinkTarget(candidate, cwd), cwd);
388 }
389 return null;
391​
392function basenameOfPath(path: string): string {
393 // A trailing separator is a valid way to write a directory, so trim it before
394 // taking the final segment. Without this the segment reads as empty and the
395 // chip renders with no label at all.
396 const trimmed = path.replace(/[/\\]+$/, "") || path;
397 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
398 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
400​
401function workspaceRelativePath(path: string, workspaceRoot: string | undefined): string | null {
402 if (!workspaceRoot) return null;
403 const normalizedPath = normalizeWindowsDrivePath(path.replaceAll("\\", "/"));
404 const normalizedRoot = normalizeWindowsDrivePath(workspaceRoot.replaceAll("\\", "/")).replace(
405 /\/+$/,
406 "",
407 );
408 const pathForCompare = normalizedPath.toLowerCase();
409 const rootForCompare = normalizedRoot.toLowerCase();
410 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
411 return normalizedPath.slice(normalizedRoot.length + 1);
413​
414export function resolveMarkdownFileLinkMeta(
415 href: string | undefined,
416 cwd?: string,
417): MarkdownFileLinkMeta | null {
418 const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
419 if (!targetPath) return null;
420 return buildFileLinkMetaFromTarget(targetPath, cwd);
422​
423function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
424 const { path, line, column } = splitPathAndPosition(targetPath);
425 const parsedLine = line ? Number.parseInt(line, 10) : Number.NaN;
426 const parsedColumn = column ? Number.parseInt(column, 10) : Number.NaN;
427 const lineNumber = Number.isFinite(parsedLine) ? parsedLine : undefined;
428 const columnNumber = Number.isFinite(parsedColumn) ? parsedColumn : undefined;
429​
430 return {
431 filePath: path,
432 targetPath,
433 displayPath: formatWorkspaceRelativePath(targetPath, cwd),
434 workspaceRelativePath: workspaceRelativePath(path, cwd),
435 basename: basenameOfPath(path),
436 ...(lineNumber !== undefined ? { line: lineNumber } : {}),
437 ...(columnNumber !== undefined ? { column: columnNumber } : {}),
438 };