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

attachmentStore.test.ts

77 lines2.6 KB

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