Open History to see the last commit
1import type { MARKDOWN_FILE_ICON_SOURCES } from "./markdownFileIcons.generated";
2
3const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
4const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
5const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
6const RELATIVE_FILE_PATH_PATTERN = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}$/;
7const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
8const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
9const POSIX_FILE_ROOT_PREFIXES = [
10 "/Users/",
11 "/home/",
12 "/tmp/",
13 "/var/",
14 "/etc/",
15 "/opt/",
16 "/mnt/",
17 "/Volumes/",
18 "/private/",
19 "/root/",
20] as const;
21
22export type MarkdownLinkPresentation =
23 | {
24 readonly kind: "external";
25 readonly href: string;
26 readonly host: string;
27 }
28 | {
29 readonly kind: "file";
30 readonly href: string;
31 readonly icon: MarkdownFileIcon;
32 readonly label: string;
33 readonly path: string;
34 readonly line?: number;
35 readonly column?: number;
36 }
37 | {
38 readonly kind: "link";
39 readonly href: string | null;
40 };
41
42export type MarkdownFileIcon = keyof typeof MARKDOWN_FILE_ICON_SOURCES;
43
44const FILE_ICON_BY_NAME: Readonly<Record<string, MarkdownFileIcon>> = {
45 ".babelrc": "babel",
46 ".babelrc.json": "babel",
47 ".bash_profile": "bash",
48 ".bashrc": "bash",
49 ".browserslistrc": "browserslist",
50 ".dockerignore": "docker",
51 ".eslintignore": "eslint",
52 ".eslintrc": "eslint",
53 ".eslintrc.cjs": "eslint",
54 ".eslintrc.js": "eslint",
55 ".eslintrc.json": "eslint",
56 ".eslintrc.yaml": "eslint",
57 ".eslintrc.yml": "eslint",
58 ".gitattributes": "git",
59 ".gitignore": "git",
60 ".gitkeep": "git",
61 ".gitmodules": "git",
62 ".oxlintrc.json": "oxc",
63 ".postcssrc": "postcss",
64 ".postcssrc.json": "postcss",
65 ".postcssrc.yaml": "postcss",
66 ".postcssrc.yml": "postcss",
67 ".prettierignore": "prettier",
68 ".prettierrc": "prettier",
69 ".prettierrc.json": "prettier",
70 ".prettierrc.cjs": "prettier",
71 ".prettierrc.js": "prettier",
72 ".prettierrc.mjs": "prettier",
73 ".prettierrc.toml": "prettier",
74 ".prettierrc.yaml": "prettier",
75 ".prettierrc.yml": "prettier",
76 ".stylelintignore": "stylelint",
77 ".stylelintrc": "stylelint",
78 ".stylelintrc.cjs": "stylelint",
79 ".stylelintrc.js": "stylelint",
80 ".stylelintrc.json": "stylelint",
81 ".stylelintrc.mjs": "stylelint",
82 ".stylelintrc.yaml": "stylelint",
83 ".stylelintrc.yml": "stylelint",
84 ".terraform.lock.hcl": "terraform",
85 ".zprofile": "bash",
86 ".zshenv": "bash",
87 ".zshrc": "bash",
88 "agents.md": "agents",
89 "babel.config.js": "babel",
90 "babel.config.cjs": "babel",
91 "babel.config.json": "babel",
92 "babel.config.mjs": "babel",
93 "biome.json": "biome",
94 "biome.jsonc": "biome",
95 "bun.lock": "bun",
96 "bun.lockb": "bun",
97 "bunfig.toml": "bun",
98 "claude.md": "claude",
99 "compose.yaml": "docker",
100 "compose.yml": "docker",
101 "docker-compose.yaml": "docker",
102 "docker-compose.yml": "docker",
103 "docker-compose.override.yml": "docker",
104 dockerfile: "docker",
105 "eslint.config.js": "eslint",
106 "eslint.config.cjs": "eslint",
107 "eslint.config.mjs": "eslint",
108 "eslint.config.mts": "eslint",
109 "eslint.config.ts": "eslint",
110 gemfile: "ruby",
111 "next.config.js": "nextjs",
112 "next.config.mjs": "nextjs",
113 "next.config.mts": "nextjs",
114 "next.config.ts": "nextjs",
115 "package.json": "package",
116 "pnpm-lock.yaml": "pnpm",
117 "pnpm-workspace.yaml": "pnpm",
118 "postcss.config.js": "postcss",
119 "postcss.config.cjs": "postcss",
120 "postcss.config.mjs": "postcss",
121 "postcss.config.ts": "postcss",
122 "prettier.config.js": "prettier",
123 "prettier.config.cjs": "prettier",
124 "prettier.config.mjs": "prettier",
125 rakefile: "ruby",
126 "readme.md": "readme",
127 "stylelint.config.js": "stylelint",
128 "stylelint.config.cjs": "stylelint",
129 "stylelint.config.mjs": "stylelint",
130 "svgo.config.js": "svgo",
131 "svgo.config.cjs": "svgo",
132 "svgo.config.mjs": "svgo",
133 "svgo.config.ts": "svgo",
134 "tailwind.config.js": "tailwind",
135 "tailwind.config.cjs": "tailwind",
136 "tailwind.config.mjs": "tailwind",
137 "tailwind.config.ts": "tailwind",
138 "tsconfig.json": "tsconfig",
139 "vite.config.js": "vite",
140 "vite.config.mjs": "vite",
141 "vite.config.mts": "vite",
142 "vite.config.ts": "vite",
143 "webpack.config.js": "webpack",
144 "webpack.config.babel.js": "webpack",
145 "webpack.config.cjs": "webpack",
146 "webpack.config.mjs": "webpack",
147 "webpack.config.ts": "webpack",
148};
149
150const FILE_ICON_BY_EXTENSION: Readonly<Record<string, MarkdownFileIcon>> = {
151 "7z": "zip",
152 astro: "astro",
153 avif: "image",
154 "code-workspace": "vscode",
155 bash: "bash",
156 bmp: "image",
157 bz2: "zip",
158 c: "c",
159 cc: "cpp",
160 cpp: "cpp",
161 cxx: "cpp",
162 css: "css",
163 csv: "table",
164 cts: "typescript",
165 db: "database",
166 env: "text",
167 "env.development": "text",
168 "env.local": "text",
169 "env.production": "text",
170 eot: "font",
171 erb: "ruby",
172 fish: "bash",
173 gif: "image",
174 go: "go",
175 gql: "graphql",
176 graphql: "graphql",
177 gz: "zip",
178 h: "c",
179 hh: "cpp",
180 hpp: "cpp",
181 hxx: "cpp",
182 htm: "html",
183 html: "html",
184 ico: "image",
185 icns: "image",
186 ini: "text",
187 inl: "cpp",
188 jar: "zip",
189 jpeg: "image",
190 jpg: "image",
191 js: "javascript",
192 jsx: "react",
193 json: "json",
194 jsonc: "json",
195 less: "css",
196 md: "markdown",
197 mdx: "markdown",
198 "mdx.tsx": "markdown",
199 mjs: "javascript",
200 mts: "typescript",
201 png: "image",
202 postcss: "css",
203 py: "python",
204 pyi: "python",
205 pyw: "python",
206 pyx: "python",
207 rake: "ruby",
208 rar: "zip",
209 rb: "ruby",
210 rs: "rust",
211 sass: "sass",
212 scss: "sass",
213 sh: "bash",
214 sql: "database",
215 sqlite: "database",
216 sqlite3: "database",
217 svelte: "svelte",
218 svg: "svg",
219 swift: "swift",
220 tar: "zip",
221 tf: "terraform",
222 tfstate: "terraform",
223 tfvars: "terraform",
224 tgz: "zip",
225 ts: "typescript",
226 tsv: "table",
227 tsx: "react",
228 txt: "text",
229 woff: "font",
230 woff2: "font",
231 vue: "vue",
232 wasm: "wasm",
233 webp: "image",
234 yml: "yml",
235 yaml: "yml",
236 zig: "zig",
237 zip: "zip",
238 zsh: "bash",
239};
240
241function safeDecode(value: string): string {
242 try {
243 return decodeURIComponent(value);
244 } catch {
245 return value;
246 }
247}
248
249function normalizeDestination(value: string): string {
250 const trimmed = value.trim();
251 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
252}
253
254function fileUrlTarget(href: string): { readonly path: string; readonly hash: string } | null {
255 try {
256 const parsed = new URL(href);
257 if (parsed.protocol.toLowerCase() !== "file:") {
258 return null;
259 }
260 const path = /^\/[A-Za-z]:[\\/]/.test(parsed.pathname)
261 ? parsed.pathname.slice(1)
262 : parsed.pathname;
263 return { path, hash: parsed.hash };
264 } catch {
265 return null;
266 }
267}
268
269function stripSearchAndHash(value: string): { readonly path: string; readonly hash: string } {
270 const hashIndex = value.indexOf("#");
271 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
272 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
273 const queryIndex = pathWithSearch.indexOf("?");
274 return {
275 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
276 hash,
277 };
278}
279
280function splitFilePosition(
281 path: string,
282 hash: string,
283): { readonly path: string; readonly line?: number; readonly column?: number } {
284 const suffixMatch = path.match(/:(\d+)(?::(\d+))?$/);
285 const hashMatch = suffixMatch ? null : hash.match(/^#L(\d+)(?:C(\d+))?$/i);
286 const match = suffixMatch ?? hashMatch;
287 if (!match?.[1]) {
288 return { path };
289 }
290
291 const line = Number.parseInt(match[1], 10);
292 const column = match[2] ? Number.parseInt(match[2], 10) : undefined;
293 const pathWithoutPosition = suffixMatch ? path.slice(0, -suffixMatch[0].length) : path;
294 return {
295 path: pathWithoutPosition,
296 ...(line > 0 ? { line } : {}),
297 ...(column !== undefined && column > 0 ? { column } : {}),
298 };
299}
300
301function looksLikePosixFilesystemPath(path: string): boolean {
302 if (!path.startsWith("/")) {
303 return false;
304 }
305 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) {
306 return true;
307 }
308 if (POSITION_SUFFIX_PATTERN.test(path)) {
309 return true;
310 }
311 const basename = path.slice(path.lastIndexOf("/") + 1);
312 return /\.[A-Za-z0-9_-]+$/.test(basename);
313}
314
315function looksLikeFilePath(value: string): boolean {
316 if (WINDOWS_DRIVE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value)) {
317 return true;
318 }
319 if (RELATIVE_PATH_PREFIX_PATTERN.test(value)) {
320 return true;
321 }
322 if (value.startsWith("/")) {
323 return looksLikePosixFilesystemPath(value);
324 }
325 if (FILE_ICON_BY_NAME[value.replace(POSITION_SUFFIX_PATTERN, "").toLowerCase()]) {
326 return true;
327 }
328 return RELATIVE_FILE_PATH_PATTERN.test(value) || RELATIVE_FILE_NAME_PATTERN.test(value);
329}
330
331function fileLabel(value: string): string {
332 const normalized = value.replaceAll("\\", "/");
333 const basename = normalized.slice(normalized.lastIndexOf("/") + 1);
334 return basename || normalized;
335}
336
337export function resolveMarkdownFileIcon(value: string): MarkdownFileIcon {
338 const basename = fileLabel(value).replace(POSITION_SUFFIX_PATTERN, "").toLowerCase();
339 const exactIcon = FILE_ICON_BY_NAME[basename];
340 if (exactIcon) return exactIcon;
341 if (basename.startsWith("tsconfig.") && basename.endsWith(".json")) {
342 return "tsconfig";
343 }
344 const segments = basename.split(".");
345 for (let index = 1; index < segments.length; index += 1) {
346 const icon = FILE_ICON_BY_EXTENSION[segments.slice(index).join(".")];
347 if (icon) return icon;
348 }
349 return "default";
350}
351
352export function resolveMarkdownLinkPresentation(href: string): MarkdownLinkPresentation {
353 const normalized = normalizeDestination(href);
354 try {
355 const parsed = new URL(normalized);
356 if (parsed.protocol === "http:" || parsed.protocol === "https:") {
357 return {
358 kind: "external",
359 href: parsed.toString(),
360 host: parsed.hostname,
361 };
362 }
363 } catch {
364 // Relative paths and non-URL link destinations are handled below.
365 }
366
367 const source = normalized.toLowerCase().startsWith("file:")
368 ? fileUrlTarget(normalized)
369 : stripSearchAndHash(normalized);
370 const decodedSource = source
371 ? { path: safeDecode(source.path.trim()), hash: safeDecode(source.hash.trim()) }
372 : null;
373 const fileTarget = decodedSource
374 ? splitFilePosition(decodedSource.path, decodedSource.hash)
375 : null;
376 const targetWithPosition = fileTarget
377 ? `${fileTarget.path}${
378 fileTarget.line
379 ? `:${fileTarget.line}${fileTarget.column ? `:${fileTarget.column}` : ""}`
380 : ""
381 }`
382 : null;
383 if (fileTarget && targetWithPosition && looksLikeFilePath(targetWithPosition)) {
384 return {
385 kind: "file",
386 href: normalized,
387 icon: resolveMarkdownFileIcon(fileTarget.path),
388 label: fileLabel(targetWithPosition),
389 path: fileTarget.path,
390 ...(fileTarget.line ? { line: fileTarget.line } : {}),
391 ...(fileTarget.column ? { column: fileTarget.column } : {}),
392 };
393 }
394
395 return {
396 kind: "link",
397 href: /^(?:mailto|tel):/i.test(normalized) ? normalized : null,
398 };
399}