Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4
5import type { ChatAttachment } from "@t3tools/contracts";
6
7import {
8 normalizeAttachmentRelativePath,
9 resolveAttachmentRelativePath,
10} from "./attachmentPaths.ts";
11import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
12
13const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
14const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
15const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
16const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
17const ATTACHMENT_ID_PATTERN = new RegExp(
18 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
19 "i",
20);
21
22export function toSafeThreadAttachmentSegment(threadId: string): string | null {
23 const segment = threadId
24 .trim()
25 .toLowerCase()
26 .replace(/[^a-z0-9_-]+/gi, "-")
27 .replace(/-+/g, "-")
28 .replace(/^[-_]+|[-_]+$/g, "")
29 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
30 .replace(/[-_]+$/g, "");
31 if (segment.length === 0) {
32 return null;
33 }
34 return segment;
35}
36
37export function createAttachmentId(threadId: string): string | null {
38 const threadSegment = toSafeThreadAttachmentSegment(threadId);
39 if (!threadSegment) {
40 return null;
41 }
42 return `${threadSegment}-${NodeCrypto.randomUUID()}`;
43}
44
45export function createDeterministicAttachmentId(
46 threadId: string,
47 stableKey: string,
48): string | null {
49 const threadSegment = toSafeThreadAttachmentSegment(threadId);
50 if (!threadSegment) return null;
51 const hash = NodeCrypto.createHash("sha256").update(stableKey).digest("hex").slice(0, 32);
52 const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
53 return `${threadSegment}-${uuid}`;
54}
55
56export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
57 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
58 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
59 return null;
60 }
61 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
62 if (!match) {
63 return null;
64 }
65 return match[1]?.toLowerCase() ?? null;
66}
67
68export function attachmentRelativePath(attachment: ChatAttachment): string {
69 switch (attachment.type) {
70 case "image": {
71 const extension = inferImageExtension({
72 mimeType: attachment.mimeType,
73 fileName: attachment.name,
74 });
75 return `${attachment.id}${extension}`;
76 }
77 }
78}
79
80export function resolveAttachmentPath(input: {
81 readonly attachmentsDir: string;
82 readonly attachment: ChatAttachment;
83}): string | null {
84 return resolveAttachmentRelativePath({
85 attachmentsDir: input.attachmentsDir,
86 relativePath: attachmentRelativePath(input.attachment),
87 });
88}
89
90export function resolveAttachmentPathById(input: {
91 readonly attachmentsDir: string;
92 readonly attachmentId: string;
93}): string | null {
94 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
95 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
96 return null;
97 }
98 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
99 const maybePath = resolveAttachmentRelativePath({
100 attachmentsDir: input.attachmentsDir,
101 relativePath: `${normalizedId}${extension}`,
102 });
103 if (maybePath && NodeFS.existsSync(maybePath)) {
104 return maybePath;
105 }
106 }
107 return null;
108}
109
110export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
111 const normalized = normalizeAttachmentRelativePath(relativePath);
112 if (!normalized || normalized.includes("/")) {
113 return null;
114 }
115 const extensionIndex = normalized.lastIndexOf(".");
116 if (extensionIndex <= 0) {
117 return null;
118 }
119 const id = normalized.slice(0, extensionIndex);
120 return id.length > 0 && !id.includes(".") ? id : null;
121}