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

attachmentStore.test.ts

75 lines2.5 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 attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
48 try {
49 const attachmentId = "thread-1-attachment";
50 const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
51 fs.writeFileSync(pngPath, Buffer.from("hello"));
52​
53 const resolved = resolveAttachmentPathById({
54 attachmentsDir,
55 attachmentId,
56 });
57 expect(resolved).toBe(pngPath);
58 } finally {
59 fs.rmSync(attachmentsDir, { recursive: true, force: true });
60 }
61 });
62​
63 it("returns null when no attachment file exists for the id", () => {
64 const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
65 try {
66 const resolved = resolveAttachmentPathById({
67 attachmentsDir,
68 attachmentId: "thread-1-missing",
69 });
70 expect(resolved).toBeNull();
71 } finally {
72 fs.rmSync(attachmentsDir, { recursive: true, force: true });
73 }
74 });
75});