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

markdownLinks.ts

369 lines11.9 KB

1import { isWindowsAbsolutePath } from "@t3tools/shared/path";
2​
3const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
4const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
5const RELATIVE_FILE_PATH_PATTERN =
6 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
7const RELATIVE_FILE_NAME_PATTERN =
8 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
9const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
10const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
11const POSITION_SUFFIX_CAPTURE_PATTERN = /:(\d+)(?::(\d+))?$/;
12const POSITION_HASH_PATTERN = /^#L(\d+)(?:C(\d+))?$/i;
13const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
14const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
15const PATH_SEPARATOR_PATTERN = /[\\/]/;
16const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
17// A final dot between digits marks a version or model id (`glm-5.3`,
18// `Qwen2.5-Coder`), not an extension. `ls.1` and `libfoo.so.1` stay files.
19const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
20const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
21// Standard OS and dev-container roots; deliberately excludes app-route-ish
22// prefixes like /app/ or /chat/ so SPA routes never read as files.
23const POSIX_FILE_ROOT_PREFIXES = [
24 "/Users/",
25 "/home/",
26 "/tmp/",
27 "/var/",
28 "/etc/",
29 "/opt/",
30 "/mnt/",
31 "/Volumes/",
32 "/private/",
33 "/root/",
34 "/usr/",
35 "/bin/",
36 "/sbin/",
37 "/lib/",
38 "/lib64/",
39 "/srv/",
40 "/dev/",
41 "/proc/",
42 "/sys/",
43 "/run/",
44 "/boot/",
45 "/media/",
46 "/workspace/",
47 "/workspaces/",
48] as const;
49// `Name:digits` also matches `error:1`, `port:3000`, and `TODO:12`.
50const EXTENSIONLESS_FILE_NAMES = new Set([
51 "Makefile",
52 "makefile",
53 "GNUmakefile",
54 "Dockerfile",
55 "Containerfile",
56 "Justfile",
57 "justfile",
58 "Rakefile",
59 "Gemfile",
60 "Procfile",
61 "Brewfile",
62 "Caddyfile",
63 "Vagrantfile",
64 "Jenkinsfile",
65 "Podfile",
66 "Fastfile",
67 "BUILD",
68 "WORKSPACE",
69 "LICENSE",
70 "LICENCE",
71 "COPYING",
72 "NOTICE",
73 "AUTHORS",
74 "CONTRIBUTORS",
75 "CHANGELOG",
76 "README",
77 "CODEOWNERS",
78]);
79const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
80// These allowlists avoid classifying dotted directories such as `conf.d/`
81// or filenames such as `Makefile.in:12` as hosts.
82const GENERIC_HOSTNAME_TLDS = new Set([
83 "com",
84 "net",
85 "org",
86 "io",
87 "dev",
88 "app",
89 "ai",
90 "co",
91 "edu",
92 "gov",
93 "mil",
94 "info",
95 "biz",
96 "xyz",
97 "me",
98 "tv",
99 "cc",
100 "gg",
101 "chat",
102 "cloud",
103 "site",
104 "online",
105 "tech",
106 "store",
107 "link",
108]);
109// Country codes also name file extensions. A :line suffix makes `.pl`
110// and `.pt` files more likely than hostnames.
111const COUNTRY_HOSTNAME_TLDS = new Set([
112 "uk",
113 "de",
114 "fr",
115 "nl",
116 "se",
117 "no",
118 "fi",
119 "dk",
120 "pl",
121 "ch",
122 "at",
123 "be",
124 "es",
125 "it",
126 "pt",
127 "eu",
128 "us",
129 "ca",
130 "au",
131 "nz",
132 "jp",
133 "kr",
134 "cn",
135 "br",
136 "ru",
137 "mx",
138 "ie",
139 "cz",
140 "tr",
141 "sg",
142 "hk",
143]);
144​
145function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
146 if (segment.startsWith(".")) return false;
147 const lowered = segment.toLowerCase();
148 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
149 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
150 const labels = lowered.split(".");
151 const lastLabel = labels.at(-1);
152 if (labels.length < 2 || lastLabel === undefined) return false;
153 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
154 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
156​
157/**
158 * Picks path-shaped inline code for the client's markdown file-link resolver.
159 * It does not resolve paths or turn plain prose and fenced code into links.
160 */
161export function inlineCodeFilePathCandidate(codeText: string): string | null {
162 const trimmed = codeText.trim();
163 if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
164​
165 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
166 const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
167 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
168​
169 const hasExplicitPathShape =
170 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
171 candidate.startsWith("/") ||
172 isWindowsAbsolutePath(candidate);
173 if (!hasExplicitPathShape) {
174 const withoutPosition = candidate.replace(POSITION_SUFFIX_PATTERN, "");
175 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
176 if (looksLikeHostname(firstSegment, hasPosition)) return null;
177 const basename =
178 withoutPosition
179 .replace(/[/\\]+$/, "")
180 .split(/[\\/]/)
181 .at(-1) ?? "";
182 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
183 if (!hasPosition && !FILE_EXTENSION_PATTERN.test(basename)) return null;
184 }
185 return candidate;
187​
188export function safeDecodeURIComponent(value: string): string {
189 try {
190 return decodeURIComponent(value);
191 } catch {
192 return value;
193 }
195​
196export function normalizeMarkdownLinkDestination(value: string): string {
197 const trimmed = value.trim();
198 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
200​
201/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
202export function stripSlashPrefixedWindowsDrive(path: string): string {
203 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
205​
206export function splitMarkdownLinkSearchAndHash(value: string): {
207 readonly path: string;
208 readonly hash: string;
209} {
210 const hashIndex = value.indexOf("#");
211 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
212 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
213 const queryIndex = pathWithSearch.indexOf("?");
214 return {
215 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
216 hash,
217 };
219​
220/**
221 * Turns a `file:` URL into a host path, still percent-encoded so callers that
222 * decode every destination in one place do not decode file URLs twice. A
223 * non-localhost authority becomes a UNC share.
224 */
225export function parseFileUrlHref(
226 href: string,
227): { readonly path: string; readonly hash: string } | null {
228 try {
229 const parsed = new URL(href);
230 if (parsed.protocol.toLowerCase() !== "file:") return null;
231​
232 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
233 const path = uncHostname
234 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
235 : parsed.pathname;
236 if (path.length === 0) return null;
237 return { path: stripSlashPrefixedWindowsDrive(path), hash: parsed.hash };
238 } catch {
239 return null;
240 }
242​
243export interface FilePathPosition {
244 readonly path: string;
245 readonly line?: number;
246 readonly column?: number;
248​
249export function splitFilePathPosition(path: string, hash = ""): FilePathPosition {
250 const suffixMatch = path.match(POSITION_SUFFIX_CAPTURE_PATTERN);
251 const match = suffixMatch ?? hash.match(POSITION_HASH_PATTERN);
252 if (!match?.[1]) return { path };
253​
254 const line = Number.parseInt(match[1], 10);
255 const column = match[2] === undefined ? undefined : Number.parseInt(match[2], 10);
256 return {
257 path: suffixMatch ? path.slice(0, -suffixMatch[0].length) : path,
258 ...(line > 0 ? { line } : {}),
259 ...(column !== undefined && column > 0 ? { column } : {}),
260 };
262​
263export function formatFilePathPosition(position: FilePathPosition): string {
264 if (!position.line) return position.path;
265 return `${position.path}:${position.line}${position.column ? `:${position.column}` : ""}`;
267​
268/** Keeps filename and destination-path labels compact without discarding prose. */
269export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
270 const destination = parseMarkdownFileLink(href);
271 if (!destination) return false;
272 const normalize = (path: string) =>
273 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
274 const labelPosition = splitFilePathPosition(label.trim());
275 if (
276 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
277 (labelPosition.column !== undefined && labelPosition.column !== destination.column)
278 ) {
279 return false;
280 }
281 let labelPath = normalize(labelPosition.path);
282 let destinationPath = normalize(destination.path);
283 if (labelPath.length === 0) return true;
284 if (isWindowsAbsolutePath(destination.path)) {
285 labelPath = labelPath.toLowerCase();
286 destinationPath = destinationPath.toLowerCase();
287 }
288 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
290​
291export function isRelativeFilePath(path: string): boolean {
292 return (
293 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
294 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
295 );
297​
298function looksLikePosixFilesystemPath(path: string): boolean {
299 if (!path.startsWith("/")) return false;
300 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
301 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
302 const basename = path.slice(path.lastIndexOf("/") + 1);
303 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename);
305​
306/**
307 * Decides whether a decoded link destination is a file path rather than a route
308 * or prose. Only a `:line` suffix the author wrote counts as evidence; a `#L`
309 * anchor never turns `/chat/settings` into a file.
310 */
311function looksLikeFilePath(path: string, authoredPath: string): boolean {
312 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
313 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
314 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
315 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
317​
318function hasExternalScheme(path: string): boolean {
319 if (isWindowsAbsolutePath(path)) return false;
320 const match = path.match(EXTERNAL_SCHEME_PATTERN);
321 if (!match) return false;
322 const rest = match[2] ?? "";
323 if (rest.startsWith("//")) return true;
324 return !POSITION_ONLY_PATTERN.test(rest);
326​
327export function parseMarkdownFileLink(href: string): FilePathPosition | null {
328 const normalized = normalizeMarkdownLinkDestination(href);
329 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
330 return null;
331 }
332​
333 const source =
334 (normalized.toLowerCase().startsWith("file:") ? parseFileUrlHref(normalized) : null) ??
335 splitMarkdownLinkSearchAndHash(normalized);
336 // A percent-encoded drive colon (`/c%3A/`) only becomes strippable once decoded.
337 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(source.path.trim()));
338 const hash = safeDecodeURIComponent(source.hash.trim());
339 if (path.length === 0 || hasExternalScheme(path)) return null;
340​
341 const position = splitFilePathPosition(path, hash);
342 return looksLikeFilePath(position.path, path) ? position : null;
344​
345export function fileBasename(path: string): string {
346 // A trailing separator is a valid way to write a directory. Trim it before
347 // taking the final segment so the label is never empty.
348 const trimmed = path.replace(/[/\\]+$/, "");
349 if (trimmed.length === 0) return path;
350 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
351 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
353​
354export function workspaceRelativeFilePath(
355 path: string,
356 workspaceRoot: string | null | undefined,
357): string | null {
358 if (!workspaceRoot) return null;
359 const normalizedPath = stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"));
360 const normalizedRoot = stripSlashPrefixedWindowsDrive(
361 workspaceRoot.replaceAll("\\", "/"),
362 ).replace(/\/+$/, "");
363 const caseInsensitive = isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot));
364 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
365 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
366 if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";
367 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
368 return normalizedPath.slice(normalizedRoot.length + 1);