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

markdownImages.ts

70 lines2.5 KB

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