Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import fs from "node:fs";
3import os from "node:os";
4import path from "node:path";
5
6import { describe, expect, it } from "vitest";
7
8import {
9 createAttachmentId,
10 parseThreadSegmentFromAttachmentId,
11 resolveAttachmentPathById,
12} from "./attachmentStore.ts";
13
14describe("attachmentStore", () => {
15 it("sanitizes thread ids when creating attachment ids", () => {
16 const attachmentId = createAttachmentId("thread.folder/unsafe space");
17 expect(attachmentId).toBeTruthy();
18 if (!attachmentId) {
19 return;
20 }
21
22 const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
23 expect(threadSegment).toBeTruthy();
24 expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
25 expect(threadSegment).not.toContain(".");
26 expect(threadSegment).not.toContain("%");
27 expect(threadSegment).not.toContain("/");
28 });
29
30 it("parses exact thread segments from attachment ids without prefix collisions", () => {
31 const fooId = "foo-00000000-0000-4000-8000-000000000001";
32 const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
33
34 expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
35 expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
36 });
37
38 it("normalizes created thread segments to lowercase", () => {
39 const attachmentId = createAttachmentId("Thread.Foo");
40 expect(attachmentId).toBeTruthy();
41 if (!attachmentId) {
42 return;
43 }
44 expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
45 });
46
47 it("resolves attachment path by id using the extension that exists on disk", () => {
48 const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
49 try {
50 const attachmentId = "thread-1-attachment";
51 const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
52 fs.writeFileSync(pngPath, Buffer.from("hello"));
53
54 const resolved = resolveAttachmentPathById({
55 attachmentsDir,
56 attachmentId,
57 });
58 expect(resolved).toBe(pngPath);
59 } finally {
60 fs.rmSync(attachmentsDir, { recursive: true, force: true });
61 }
62 });
63
64 it("returns null when no attachment file exists for the id", () => {
65 const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
66 try {
67 const resolved = resolveAttachmentPathById({
68 attachmentsDir,
69 attachmentId: "thread-1-missing",
70 });
71 expect(resolved).toBeNull();
72 } finally {
73 fs.rmSync(attachmentsDir, { recursive: true, force: true });
74 }
75 });
76});