Open History to see the last commit
1import { isWindowsAbsolutePath } from "@t3tools/shared/path";
2
3import {
4 normalizeMarkdownLinkDestination,
5 parseFileUrlHref,
6 safeDecodeURIComponent,
7 splitMarkdownLinkSearchAndHash,
8 stripSlashPrefixedWindowsDrive,
9} from "./markdownLinks.ts";
10
11const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
12const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
13
14export type MarkdownImageSource =
15 | { readonly _tag: "Direct"; readonly uri: string }
16 | { readonly _tag: "WorkspaceFile"; readonly path: string }
17 | { readonly _tag: "Blocked" };
18
19export function markdownImageSourceFragment(source: string): string {
20 return splitMarkdownLinkSearchAndHash(normalizeMarkdownLinkDestination(source)).hash;
21}
22
23function joinWorkspacePath(workspaceRoot: string, relativePath: string): string {
24 const separator = isWindowsAbsolutePath(workspaceRoot) ? "\\" : "/";
25 const root = workspaceRoot.replace(/[\\/]+$/, "");
26 const path = relativePath.replace(/[\\/]/g, separator).replace(/^[\\/]+/, "");
27 return `${root}${separator}${path}`;
28}
29
30/**
31 * Classifies a markdown image or video source by where its bytes must be loaded from.
32 * Filesystem paths belong to the environment host and must never reach a
33 * browser or native image component without first becoming a signed asset URL.
34 */
35export function classifyMarkdownImageSource(
36 value: string | null | undefined,
37 workspaceRoot?: string | null,
38): MarkdownImageSource {
39 if (value === null || value === undefined) return { _tag: "Blocked" };
40
41 const source = normalizeMarkdownLinkDestination(value);
42 if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {
43 return { _tag: "Blocked" };
44 }
45 if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {
46 return { _tag: "Direct", uri: source };
47 }
48
49 if (/^file:/i.test(source)) {
50 const target = parseFileUrlHref(source);
51 return target === null
52 ? { _tag: "Blocked" }
53 : {
54 _tag: "WorkspaceFile",
55 path: stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)),
56 };
57 }
58
59 const path = stripSlashPrefixedWindowsDrive(
60 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
61 );
62 if (path.length === 0) return { _tag: "Blocked" };
63 if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
64 return { _tag: "WorkspaceFile", path };
65 }
66 if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
67 return { _tag: "Blocked" };
68 }
69 if (!workspaceRoot) return { _tag: "Blocked" };
70
71 return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path) };
72}