/** * The open films seed and the artwork engine end to end against `wrangler * dev`, on a throwaway personal object (nothing here reaches a deployed one): * * cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-films-seed-open.ts [--cache ] * * The object is onboarded with the kit (`dev-worker.ts`), the owner signs in * and mints an owner token into a file, as the coordinator holds one. * * 1. The kit's film table as it ships slips a poster and plays no file: the * seed refuses before it downloads or sends anything. * 2. The throwaway's film table is given a file column its slip plays from * (`file`, `slip.player`), put as the owner may put definitions. * 3. Two books are made with no cover; the seed runs: each film's file is * sent in parts and comes back whole, each row holds it, and each poster * and both covers are filled by the object's artwork engine off the * writes, from Wikidata/Commons and Open Library over the network. * 4. A second run sends nothing, makes no row and changes none. * * wrangler dev is stopped and the temp dir removed however it ends. */ import { spawnSync, type ChildProcess } from "node:child_process"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { check, startDevWorker, stop } from "./dev-worker.ts"; import { personalSlug } from "../dev-server"; const DATABASE = "22222222-2222-4222-8222-222222222222"; const cache = process.argv.includes("--cache") ? process.argv[process.argv.indexOf("--cache") + 1]! : join(process.env.HOME ?? "", ".cache/cottondb/open-films"); const tmp = mkdtempSync(join(tmpdir(), "e2e-films-")); let wrangler: ChildProcess | null = null; const cleanup = (): void => { stop(wrangler); wrangler = null; rmSync(tmp, { recursive: true, force: true }); }; process.on("SIGINT", () => { cleanup(); process.exit(130); }); type Doc = Record; async function main(): Promise { const dev = await startDevWorker(tmp, DATABASE, (c) => (wrangler = c)); const base = `${dev.base}/b/${personalSlug()}`; const minted = await dev.api<{ token?: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "films seed e2e", scopes: ["owner"], expires_in_days: 1, allow: "all" } }, dev.credential); const token = minted.token!; const tokenFile = join(tmp, "owner-token"); writeFileSync(tokenFile, token, { mode: 0o600 }); const seed = (): { status: number; out: string; seconds: number } => { const started = Date.now(); const r = spawnSync("pnpm", ["-s", "films-seed-open", "--base", base, "--token-file", tokenFile, "--cache", cache, "--wait", "120"], { cwd: join(import.meta.dirname, "../.."), encoding: "utf8" }); const out = `${r.stdout}${r.stderr}`; check(!out.includes(token), "the token is never printed"); return { status: r.status ?? -1, out, seconds: (Date.now() - started) / 1000 }; }; const films = async (): Promise<{ id: string; data: Doc }[]> => { const r = await dev.api<{ result: { content: { text: string }[] } }>("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_records", arguments: { table: "film", limit: 100 } } }, token); return (JSON.parse(r.result.content[0]!.text) as { records: { id: string; data: Doc }[] }).records; }; const books = async (): Promise<{ id: string; data: Doc }[]> => { const r = await dev.api<{ result: { content: { text: string }[] } }>("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_records", arguments: { table: "book", limit: 100 } } }, token); return (JSON.parse(r.result.content[0]!.text) as { records: { id: string; data: Doc }[] }).records; }; const head = async (key: string): Promise<{ status: number; bytes: number; type: string }> => { const r = await fetch(`${base}/v1/media/${key}`, { method: "HEAD", headers: { authorization: `Bearer ${token}` } }); return { status: r.status, bytes: Number(r.headers.get("content-length") ?? -1), type: r.headers.get("content-type") ?? "" }; }; console.log("\n1. the kit's film table as it ships"); const refused = seed(); check(refused.status === 1 && refused.out.includes("names no player column"), `the seed refuses: ${refused.out.trim()}`); check((await films()).length === 0, "no film row was made"); console.log("\n2. the throwaway's film table plays its file"); const defs = await dev.api<{ tools: Doc[]; tables: Doc[]; flavour: Doc }>("GET", "/v1/definitions"); const tables = defs.tables.map((t) => t.id === "film" ? { ...t, columns: [...(t.columns as Doc[]), { key: "file", name: "Film", type: "file" }], slip: { ...(t.slip as Doc), player: "file" } } : t, ); await dev.api("PUT", "/v1/admin/definitions", { tools: defs.tools, tables, flavour: defs.flavour }, token); const film = (await dev.api<{ tables: Doc[] }>("GET", "/v1/definitions")).tables.find((t) => t.id === "film")!; check((film.slip as Doc).player === "file", "the film table's slip plays from its file column"); console.log("\n3. the first run, with two books waiting for their covers"); for (const data of [{ title: "The Hobbit", author: "J.R.R. Tolkien" }, { title: "Piranesi", author: "Susanna Clarke" }]) { await dev.api("POST", "/v1/act", { act: "create", args: { table: "book", data } }, token); } const first = seed(); console.log(first.out.trim().split("\n").map((l) => ` ${l}`).join("\n")); check(first.status === 0, `the seed ran in ${first.seconds.toFixed(1)} s`); const made = await films(); check(made.length === 4, `four film rows: ${made.map((r) => r.data.title).join(", ")}`); for (const r of made) { const file = String(r.data.file ?? ""); const kept = await head(file); check(kept.status === 200 && kept.bytes > 100_000_000 && kept.type.startsWith("video/"), `${String(r.data.title)}: its file ${file} is kept, ${(kept.bytes / 1e6).toFixed(1)} MB ${kept.type}`); check(r.data.kind === "film" && r.data.status === "want_to_watch" && String(r.data.review).includes("CC BY"), `${String(r.data.title)}: kind film, to watch, its licence in its review`); const poster = String(r.data.poster ?? ""); const picture = poster ? await head(poster) : { status: 0, bytes: 0, type: "" }; check(picture.status === 200 && picture.type.startsWith("image/"), `${String(r.data.title)}: its poster ${poster} (${(picture.bytes / 1e3).toFixed(0)} KB ${picture.type})`); } check(!first.out.includes("official poster"), "every poster came from the artwork engine, none from the seed"); const until = Date.now() + 60_000; let covered = await books(); while (covered.some((b) => !b.data.cover) && Date.now() < until) { await new Promise((r) => setTimeout(r, 2000)); covered = await books(); } for (const b of covered) { const cover = String(b.data.cover ?? ""); const picture = cover ? await head(cover) : { status: 0, bytes: 0, type: "" }; check(picture.status === 200 && picture.type.startsWith("image/"), `${String(b.data.title)}: its cover ${cover} (${(picture.bytes / 1e3).toFixed(0)} KB) from Open Library`); } console.log("\n4. the second run"); const before = JSON.stringify(await films()); const second = seed(); console.log(second.out.trim().split("\n").map((l) => ` ${l}`).join("\n")); check(second.status === 0 && !/\bsent\b/.test(second.out.split("OPEN FILMS")[1] ?? "") && (second.out.match(/row \S+ kept/g) ?? []).length === 4, `the second run sends nothing and keeps every row (${second.seconds.toFixed(1)} s)`); check(JSON.stringify(await films()) === before, "no film row changed"); console.log("\nE2E FILMS SEED + ARTWORK: passed"); } main() .catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }) .finally(cleanup);