import { afterEach, describe, expect, test } from "bun:test"; import { mkdirSync } from "node:fs"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { Database } from "bun:sqlite"; import { BundledDatabase } from "./bundled_database"; import { IndexStore } from "./store/store"; const tempRoots: string[] = []; afterEach(async () => { await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); }); describe("bundled database", () => { test("bootstraps a missing local database from the packaged baseline", async () => { const root = await tempRoot(); const bundlePath = join(root, "assets", "seed.sqlite3"); const localPath = join(root, "cache", "index.sqlite3"); createBundleDatabase(bundlePath, [{ name: "rg", description: "Recursive text search tool." }], "seed-db-test"); const bundle = new BundledDatabase(bundlePath, "seed-db-test"); bundle.ensureBootstrapped(localPath); const store = IndexStore.openExisting(localPath); expect(store.seededCommandNames()).toEqual([ { name: "rg", description: "Recursive text search tool." }, ]); expect(store.metaValue("bundled_seed_version")).toBe("seed-db-test"); store.close(); }); test("merges bundled seed rows into an existing local database without wiping it", async () => { const root = await tempRoot(); const bundlePath = join(root, "assets", "seed.sqlite3"); const localPath = join(root, "cache", "index.sqlite3"); createBundleDatabase( bundlePath, [{ name: "bun", description: "JavaScript runtime and package manager." }], "seed-db-test-v2", ); const store = IndexStore.open(localPath); store.importSeedEntries([{ name: "rg", description: "Recursive text search tool." }], "seed-import"); store.setMetaValue("bundled_seed_version", "seed-db-test-v1"); const bundle = new BundledDatabase(bundlePath, "seed-db-test-v2"); bundle.syncInto(store); expect(store.seededCommandNames()).toEqual([ { name: "bun", description: "JavaScript runtime and package manager." }, { name: "rg", description: "Recursive text search tool." }, ]); expect(store.metaValue("bundled_seed_version")).toBe("seed-db-test-v2"); store.close(); }); }); async function tempRoot(): Promise { const root = await mkdtemp(join(tmpdir(), "tool-query-bundle-")); tempRoots.push(root); return root; } function createBundleDatabase( path: string, entries: Array<{ name: string; description: string }>, version: string, ): void { mkdirSync(dirname(path), { recursive: true }); const store = IndexStore.open(path); store.importSeedEntries(entries, "seed-import"); store.setMetaValue("bundled_seed_version", version); store.close(); const database = new Database(path, { strict: true }); try { database.exec("PRAGMA wal_checkpoint(TRUNCATE);"); database.exec("VACUUM;"); } finally { database.close(); } }