import { beforeEach, describe, expect, mock, test } from "bun:test";
import { Database } from "bun:sqlite";
import { applyCombinedSchema } from "./test-schema.test-helper";
import { fakeStorage } from "./do-test-storage";
mock.module("cloudflare:workers", () => ({
env: {},
DurableObject: class {
ctx: unknown;
constructor(ctx: unknown) {
this.ctx = ctx;
}
},
}));
type Statement = { sql: string; params: unknown[] };
let seeds: Record<string, Record<string, number>> = {};
let flushed: Statement[][] = [];
let failing: (statement: Statement) => boolean = () => false;
const seeded = async (sql: string, ...params: unknown[]) => {
if (sql.startsWith("SELECT 1 AS ok")) return { ok: 1 };
for (const [fragment, rows] of Object.entries(seeds)) {
if (sql.includes(fragment)) return rows[String(params.at(-1))] !== undefined ? rows[String(params.at(-1))] : null;
}
return null;
};
const record = async (statements: Statement[]) => {
if (statements.some(failing)) throw new Error("D1 rejected the batch");
flushed.push(statements);
return [];
};
const stmt = (sql: string, ...params: unknown[]): Statement => ({ sql, params });
mock.module("./db", () => ({ stmt, first: seeded, batch: record }));
// Every repository and account object shares the recorder: the tests check statements, not which store.
const scoped = (scopeId: string) => ({ scopeId, first: seeded, batch: record });
mock.module("./scoped-db", () => ({ stmt, repoDb: scoped, accountDb: scoped }));
mock.module("./scoped-db/locators", () => ({ locate: async (_kind: string, key: string) => `repo-of-${key}` }));
mock.module("./sites/caps", () => ({ afterHostingFlush: async () => undefined }));