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

markdown-links.ts

309 lines10.4 KB

1import {
2 inlineCodeFilePathCandidate,
3 isConventionalFilePosition,
4} from "@t3tools/client-runtime/markdown-links";
5​
6import { formatWorkspaceRelativePath } from "./filePathDisplay";
7import {
8 isTerminalLinkActivation,
9 resolvePathLinkTarget,
10 splitPathAndPosition,
11} from "./terminal-links";
12​
13const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
14const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
15const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
16const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
17const RELATIVE_FILE_PATH_PATTERN =
18 /^(?:[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\/)+[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*(?::\d+){0,2}$/;
19const RELATIVE_FILE_NAME_PATTERN =
20 /^[A-Za-z0-9._-]+(?: +[A-Za-z0-9._-]+)*\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
21const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
22const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
23// Standard OS and dev-container roots; deliberately excludes app-route-ish
24// prefixes like /app/ or /chat/ so SPA routes never read as files.
25const POSIX_FILE_ROOT_PREFIXES = [
26 "/Users/",
27 "/home/",
28 "/tmp/",
29 "/var/",
30 "/etc/",
31 "/opt/",
32 "/mnt/",
33 "/Volumes/",
34 "/private/",
35 "/root/",
36 "/usr/",
37 "/bin/",
38 "/sbin/",
39 "/lib/",
40 "/lib64/",
41 "/srv/",
42 "/dev/",
43 "/proc/",
44 "/sys/",
45 "/run/",
46 "/boot/",
47 "/media/",
48 "/workspace/",
49 "/workspaces/",
50] as const;
51const MARKDOWN_LINK_HREF_PATTERN =
52 /\[[^\]]*]\(\s*(?:<([^>\n]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/g;
53​
54export interface MarkdownFileLinkMeta {
55 filePath: string;
56 targetPath: string;
57 displayPath: string;
58 workspaceRelativePath: string | null;
59 basename: string;
60 line?: number;
61 column?: number;
63​
64export function extractMarkdownLinkHrefs(markdown: string): string[] {
65 const hrefs: string[] = [];
66 for (const match of markdown.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
67 const href = (match[1] ?? match[2])?.trim();
68 if (href) hrefs.push(href);
69 }
70 return hrefs;
72​
73export function shouldOpenMarkdownFileLinkInEditor(
74 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
75 platform?: string,
76): boolean {
77 return isTerminalLinkActivation(event, platform);
79​
80export function shouldOpenMarkdownFileLinkInBrowserByDefault(path: string): boolean {
81 return /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
83​
84function safeDecode(value: string): string {
85 try {
86 return decodeURIComponent(value);
87 } catch {
88 return value;
89 }
91​
92export function isWindowsDrivePathHref(href: string): boolean {
93 return WINDOWS_DRIVE_PATH_PATTERN.test(safeDecode(href));
95​
96function unwrapMarkdownLinkDestination(value: string): string {
97 return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
99​
100export function normalizeMarkdownLinkDestination(value: string): string {
101 return unwrapMarkdownLinkDestination(value.trim());
103​
104function stripSearchAndHash(value: string): { path: string; hash: string } {
105 const hashIndex = value.indexOf("#");
106 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
107 const rawHash = hashIndex >= 0 ? value.slice(hashIndex) : "";
108 const queryIndex = pathWithSearch.indexOf("?");
109 const path = queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch;
110 return { path, hash: rawHash };
112​
113function normalizeWindowsDrivePath(path: string): string {
114 return /^\/[A-Za-z]:[\\/]/.test(path) ? path.slice(1) : path;
116​
117function parseFileUrlHref(
118 href: string,
119 options?: { readonly decodePath?: boolean },
120): { path: string; hash: string } | null {
121 try {
122 const parsed = new URL(href);
123 if (parsed.protocol.toLowerCase() !== "file:") return null;
124​
125 const uncHostname = parsed.hostname.toLowerCase() === "localhost" ? "" : parsed.hostname;
126 const rawPath = uncHostname
127 ? `\\\\${uncHostname}${parsed.pathname.replaceAll("/", "\\")}`
128 : parsed.pathname;
129 if (rawPath.length === 0) return null;
130​
131 // Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
132 const normalizedPath = normalizeWindowsDrivePath(rawPath);
133​
134 return {
135 path: options?.decodePath === false ? normalizedPath : safeDecode(normalizedPath),
136 hash: parsed.hash,
137 };
138 } catch {
139 return null;
140 }
142​
143export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
144 if (!href) return null;
145 const normalizedHref = normalizeMarkdownLinkDestination(href);
146 const target = parseFileUrlHref(normalizedHref, { decodePath: false });
147 if (!target) return null;
148 return `${target.path}${target.hash}`;
150​
151function looksLikePosixFilesystemPath(path: string): boolean {
152 if (!path.startsWith("/")) return false;
153 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
154 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
155 const basename = path.slice(path.lastIndexOf("/") + 1);
156 return /\.[A-Za-z0-9_-]+$/.test(basename);
158​
159function appendLineColumnFromHash(path: string, hash: string): string {
160 if (!hash || POSITION_SUFFIX_PATTERN.test(path)) return path;
161 const match = hash.match(/^#L(\d+)(?:C(\d+))?$/i);
162 if (!match?.[1]) return path;
163 const line = match[1];
164 const column = match[2];
165 return `${path}:${line}${column ? `:${column}` : ""}`;
167​
168function isLikelyPathCandidate(path: string): boolean {
169 if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
170 if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
171 if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
172 return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
174​
175function isRelativePath(path: string): boolean {
176 return (
177 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
178 (!path.startsWith("/") &&
179 !WINDOWS_DRIVE_PATH_PATTERN.test(path) &&
180 !WINDOWS_UNC_PATH_PATTERN.test(path))
181 );
183​
184function hasExternalScheme(path: string): boolean {
185 const match = path.match(EXTERNAL_SCHEME_PATTERN);
186 if (!match) return false;
187 const rest = match[2] ?? "";
188 if (rest.startsWith("//")) return true;
189 return !POSITION_ONLY_PATTERN.test(rest);
191​
192/**
193 * `baseDir` anchors relative links; it defaults to the workspace root and is the
194 * file's own directory when rendering a markdown file. `cwd` stays the workspace
195 * root so the result still knows whether the target is inside it.
196 */
197export function resolveMarkdownFileLinkTarget(
198 href: string | undefined,
199 cwd?: string,
200 baseDir: string | undefined = cwd,
201): string | null {
202 if (!href) return null;
203 const rawHref = normalizeMarkdownLinkDestination(href);
204 if (rawHref.length === 0 || rawHref.startsWith("#") || rawHref.startsWith("//")) return null;
205​
206 const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
207 ? parseFileUrlHref(rawHref)
208 : null;
209 const source = fileUrlTarget ?? stripSearchAndHash(rawHref);
210 const decodedPath = normalizeWindowsDrivePath(
211 fileUrlTarget ? source.path.trim() : safeDecode(source.path.trim()),
212 );
213 const decodedHash = safeDecode(source.hash.trim());
214​
215 if (decodedPath.length === 0) return null;
216 if (
217 !WINDOWS_DRIVE_PATH_PATTERN.test(decodedPath) &&
218 !WINDOWS_UNC_PATH_PATTERN.test(decodedPath) &&
219 hasExternalScheme(decodedPath)
220 ) {
221 return null;
222 }
223​
224 if (!isLikelyPathCandidate(decodedPath)) return null;
225​
226 const pathWithPosition = appendLineColumnFromHash(decodedPath, decodedHash);
227 if (!isRelativePath(pathWithPosition)) {
228 return pathWithPosition;
229 }
230​
231 if (!baseDir) return null;
232 return resolvePathLinkTarget(pathWithPosition, baseDir);
234​
235/**
236 * Inline code spans mostly hold identifiers, commands, and refs (`node.meta`,
237 * `origin/main`) rather than deliberate link destinations, so auto-linking
238 * them demands stronger path evidence than an explicit markdown link does:
239 * an unambiguous path prefix, a file extension, or a :line suffix.
240 */
241export function resolveInlineCodeFileLinkMeta(
242 codeText: string,
243 cwd?: string,
244 baseDir: string | undefined = cwd,
245): MarkdownFileLinkMeta | null {
246 const candidate = inlineCodeFilePathCandidate(codeText);
247 if (candidate === null) return null;
248​
249 const resolved = resolveMarkdownFileLinkMeta(candidate, cwd, baseDir);
250 if (resolved) return resolved;
251​
252 // `Makefile:12` — conventional extensionless names fail the generic
253 // markdown-link candidate patterns, but here the :line suffix already
254 // marked the span as a file reference.
255 if (baseDir && isConventionalFilePosition(candidate)) {
256 return buildFileLinkMetaFromTarget(resolvePathLinkTarget(candidate, baseDir), cwd);
257 }
258 return null;
260​
261function basenameOfPath(path: string): string {
262 // A trailing separator is a valid way to write a directory, so trim it before
263 // taking the final segment. Without this the segment reads as empty and the
264 // chip renders with no label at all.
265 const trimmed = path.replace(/[/\\]+$/, "") || path;
266 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
267 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
269​
270function workspaceRelativePath(path: string, workspaceRoot: string | undefined): string | null {
271 if (!workspaceRoot) return null;
272 const normalizedPath = normalizeWindowsDrivePath(path.replaceAll("\\", "/"));
273 const normalizedRoot = normalizeWindowsDrivePath(workspaceRoot.replaceAll("\\", "/")).replace(
274 /\/+$/,
275 "",
276 );
277 const pathForCompare = normalizedPath.toLowerCase();
278 const rootForCompare = normalizedRoot.toLowerCase();
279 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
280 return normalizedPath.slice(normalizedRoot.length + 1);
282​
283export function resolveMarkdownFileLinkMeta(
284 href: string | undefined,
285 cwd?: string,
286 baseDir: string | undefined = cwd,
287): MarkdownFileLinkMeta | null {
288 const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);
289 if (!targetPath) return null;
290 return buildFileLinkMetaFromTarget(targetPath, cwd);
292​
293function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string): MarkdownFileLinkMeta {
294 const { path, line, column } = splitPathAndPosition(targetPath);
295 const parsedLine = line ? Number.parseInt(line, 10) : Number.NaN;
296 const parsedColumn = column ? Number.parseInt(column, 10) : Number.NaN;
297 const lineNumber = Number.isFinite(parsedLine) ? parsedLine : undefined;
298 const columnNumber = Number.isFinite(parsedColumn) ? parsedColumn : undefined;
299​
300 return {
301 filePath: path,
302 targetPath,
303 displayPath: formatWorkspaceRelativePath(targetPath, cwd),
304 workspaceRelativePath: workspaceRelativePath(path, cwd),
305 basename: basenameOfPath(path),
306 ...(lineNumber !== undefined ? { line: lineNumber } : {}),
307 ...(columnNumber !== undefined ? { column: columnNumber } : {}),
308 };