| 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; |
| 3 | import { fileURLToPath } from "node:url"; |
| 4 | import { build } from "esbuild"; |
| 5 | |
| 6 | const bundle = await build({ |
| 7 | entryPoints: [fileURLToPath(new URL("./service.ts", import.meta.url))], bundle: true, write: false, format: "esm", platform: "node", |
| 8 | plugins: [{ name: "worker-host", setup(build) { |
| 9 | build.onResolve({ filter: /^cloudflare:workers$/ }, () => ({ path: "host", namespace: "host" })); |
| 10 | build.onLoad({ filter: /.*/, namespace: "host" }, () => ({ contents: "export class DurableObject {}" })); |
| 11 | } }], |
| 12 | }); |
| 13 | const { Folios } = await import(`data:text/javascript;base64,${Buffer.from(bundle.outputFiles[0].text).toString("base64")}`); |
| 14 | |
| 15 | test("a cold room never holds up page state; its snapshot is saved in the background", async () => { |
| 16 | let resolve!: (value: Uint8Array) => void; |
| 17 | const pending = new Promise<Uint8Array>((done) => { resolve = done; }); |
| 18 | const deferred: Promise<unknown>[] = []; |
| 19 | const writes: unknown[][] = []; |
| 20 | const statement = { bind: (...values: unknown[]) => { writes.push(values); return statement; }, run: async () => ({ success: true }) }; |
| 21 | const service = new Folios({ DB: { prepare: () => statement } }, (work: Promise<unknown>) => deferred.push(work)); |
| 22 | service.ready = async () => ({ state: () => pending }); |
| 23 | assert.equal(service.stateFor({ slug: "cold" }, { id: "folio_cold", state: null }), null); |
| 24 | assert.equal(deferred.length, 1); |
| 25 | assert.deepEqual(writes, []); |
| 26 | const bytes = new Uint8Array([1, 2, 3]); |
| 27 | resolve(bytes); |
| 28 | await Promise.all(deferred); |
| 29 | assert.deepEqual(writes, [[bytes, "folio_cold"]]); |
| 30 | }); |
| 31 | |
| 32 | test("saved state and trashed documents never wake the live room", () => { |
| 33 | const service = new Folios({}, () => assert.fail("must not start background work")); |
| 34 | assert.equal(service.stateFor({}, { state: [104, 105] }), btoa("hi")); |
| 35 | assert.equal(service.stateFor({}, { state: null, trashed_at: "2026-10-15" }), null); |
| 36 | }); |