Cotton code
747 lines · 49.5 KB · TypeScriptRaw
/** * Cotton Cinemas in the object (src/films.ts): a kit keep stays add-only on * a film table holding rows; reshape_films moves the old film family onto * the Cinemas shape once, keeping every row; find_film asks TMDB (a fetch * stubbed here, with a fake key) and fills only empty columns; and the Mac's * queue reads what waits for it and says film_converted. Every film, series, * person and id is invented; the old definitions are the kit's before * Cinemas (test/fixtures/films-old). */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { USER_AGENT, type Fetcher } from "../src/artwork.ts";import type { Business } from "../src/business.ts";import type { Env } from "../src/env.ts";import { derivedId } from "../src/import/ids.ts";import { bodyAad } from "../src/seal.ts";import { Store } from "../src/store.ts";import { openArrivalRow } from "./arrival_keys.ts";import { sealRow } from "./seal-device.ts";import { DATABASE_ID, KIT_MANIFESTS, PERSONAL_TABLES, http, personalObject, FILMS_OPEN } from "./personal.ts";import OLD_FILM from "./fixtures/films-old/film.json";import OLD_SEASON from "./fixtures/films-old/film_season.json";import OLD_EPISODE from "./fixtures/films-old/film_episode.json";import OLD_FILMS from "./fixtures/films-old/films.json";type Doc = Record<string, unknown>;const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const KEY = "test-tmdb-key";const JPEG = Uint8Array.from(atob("/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA="), (c) => c.charCodeAt(0));const PHOTO_KEY = new RegExp(`^${DATABASE_ID}/photos/[0-9a-f]{64}\\.jpg$`);const kitTable = (id: string): Doc => PERSONAL_TABLES.find((t) => t.id === id)!;const kitTool = (id: string): Doc => KIT_MANIFESTS.find((t) => t.id === id)!;const keys = (t: Doc | undefined): string[] => ((t?.columns as Doc[] | undefined) ?? []).map((c) => String(c.key));async function act(slug: string, credential: string, name: string, args: Record<string, unknown> = {}) {  return http<Record<string, unknown>>(slug, "POST", "/v1/act", { act: name, args }, { authorization: `Bearer ${credential}` });}async function row(slug: string, table: string, id: string): Promise<Doc> {  const data = await runInDurableObject(stub(slug), (_i, state) => new Store(state.storage.sql, () => new Date()).get(table, id)?.data ?? null);  expect(data, `${table} ${id}`).not.toBeNull();  return data!;}async function rows(slug: string, table: string): Promise<{ id: string; data: Doc }[]> {  return runInDurableObject(stub(slug), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan(table)].map((r) => ({ id: r.id, data: r.data })));}async function definitions(slug: string, credential: string): Promise<{ tables: Doc[]; tools: Doc[] }> {  return (await http<{ tables: Doc[]; tools: Doc[] }>(slug, "GET", "/v1/definitions", undefined, { authorization: `Bearer ${credential}` })).body;}/** Rows written straight into the object, as an older phone wrote them: their own times. */async function insert(slug: string, table: string, list: { id: string; data: Doc; at: string }[]): Promise<void> {  await runInDurableObject(stub(slug), (_i, state) => {    for (const r of list) state.storage.sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES (?, ?, ?, NULL, 1, 0, ?, ?)", table, r.id, JSON.stringify(r.data), r.at, r.at);  });}/** As if a later Worker shipped another kit: the next request keeps the kit. */async function olderKit(slug: string): Promise<void> {  await runInDurableObject(stub(slug), (_i, state) => {    state.storage.sql.exec("UPDATE meta SET value = 'an-older-kit' WHERE key = 'kit_version'");  });}/** RULE (owner, 5 Nov 2026: "film tables may be reshaped"): the keep never breaks a film table holding rows, and the owner's one-time reshape carries every row onto the Cinemas shape. */describe("reshape_films", () => {  const SLUG = "films-reshape";  let credential = "";  const ROWS = [    { id: "f-ferry", data: { title: "Night Ferry", year: "2019", kind: "film", status: "watchlist", notes: "Ines said watch it" }, at: "2026-10-20T04:00:00.000Z" },    { id: "f-comets", data: { title: "Paper Comets", kind: "film", status: "watched", watched_on: "2026-10-01", rating: 4, notes: "Better the second time" }, at: "2026-09-30T20:30:00.000Z" },    { id: "f-quiet", data: { title: "The Quiet Engines", kind: "film", status: "watchlist" }, at: "2026-10-22T10:00:00.000Z" },  ];  it("keeps the kit add-only on a film table holding rows: new columns come, notes stays a column, nothing is retired", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...FILMS_OPEN }));    // The object as the live one stands: the old film family and Films tool held, rows in film.    await runInDurableObject(stub(SLUG), (_i, state) => {      const store = new Store(state.storage.sql, () => new Date());      store.replaceDefinitions("table", [...store.definitions("table").filter((t) => !["film", "film_season", "film_episode", "watch"].includes(String(t.id))), OLD_FILM, OLD_SEASON, OLD_EPISODE] as Doc[]);      store.replaceDefinitions("tool", [...store.definitions("tool").filter((t) => t.id !== "cinemas"), OLD_FILMS as Doc]);    });    await insert(SLUG, "film", ROWS);    await olderKit(SLUG);    const { tables } = await definitions(SLUG, credential);    const film = tables.find((t) => t.id === "film")!;    expect(keys(film).slice(0, keys(OLD_FILM as Doc).length), "every held column stays, in its place").toEqual(keys(OLD_FILM as Doc));    expect(keys(film)).toEqual(expect.arrayContaining(["review", "added_on", "backdrop", "needs_mac", "source_file", "filled_from", "tmdb_id"]));    expect(film.retired, "notes is still a column: it is not retired").toBeUndefined();    expect((film.columns as Doc[]).find((c) => c.key === "status")?.choices, "the held choices stand, the kit's new ones after them").toEqual(["watchlist", "watched", "want_to_watch", "watching", "stopped"]);    expect(tables.find((t) => t.id === "film_season"), "a table with no rows is the kit's whole").toEqual(kitTable("film_season"));    expect(tables.find((t) => t.id === "watch")).toEqual(kitTable("watch"));    expect((await row(SLUG, "film", "f-ferry")).notes, "no row is touched").toBe("Ines said watch it");  });  it("maps every row's values, lays the kit's family whole, and swaps the Films tool for Cinemas", async () => {    const res = await act(SLUG, credential, "reshape_films");    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ mapped: { status: 2, review: 2, added_on: 3 }, removed: ["films"] });    // film_season, film_episode and watch held no rows: the keep laid them whole already.    expect(res.body.laid).toEqual(["film", "cinemas"]);    const defs = await definitions(SLUG, credential);    for (const id of ["film", "film_season", "film_episode", "watch"]) expect(defs.tables.find((t) => t.id === id), id).toEqual(kitTable(id));    expect(defs.tools.some((t) => t.id === "films"), "the Films tool is gone").toBe(false);    expect(defs.tools.find((t) => t.id === "cinemas")).toEqual(kitTool("cinemas"));    const ferry = await row(SLUG, "film", "f-ferry");    expect(ferry).toMatchObject({ status: "want_to_watch", review: "Ines said watch it", added_on: "2026-10-20" });    expect(ferry.notes, "notes stays stored, retired").toBe("Ines said watch it");    // Made at 20:30 UTC on 30 Sep: 1 Oct in the database's own zone.    expect(await row(SLUG, "film", "f-comets")).toMatchObject({ status: "watched", review: "Better the second time", added_on: "2026-10-01", rating: 4 });    const quiet = await row(SLUG, "film", "f-quiet");    expect(quiet).toMatchObject({ status: "want_to_watch", added_on: "2026-10-22" });    expect(quiet.review).toBeUndefined();  });  it("does nothing run again, and answers zeros", async () => {    const res = await act(SLUG, credential, "reshape_films");    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ mapped: { status: 0, review: 0, added_on: 0 }, laid: [], removed: [], changed: [] });  });});type Answer = { json: unknown } | { status: number } | { bytes: Uint8Array } | { throws: true };/** TMDB, stubbed: each URL prefix answered, every request kept. */function tmdb(answers: [string, Answer][]): { fetch: Fetcher; asked: { url: string; agent: string | null }[] } {  const asked: { url: string; agent: string | null }[] = [];  return {    asked,    fetch: async (url, init) => {      asked.push({ url, agent: new Headers(init?.headers).get("user-agent") });      const hit = answers.find(([prefix]) => url.startsWith(prefix))?.[1];      if (!hit) return new Response("not stubbed", { status: 599 });      if ("throws" in hit) throw new TypeError(`network lost for ${url}`);      if ("json" in hit) return Response.json(hit.json);      if ("bytes" in hit) return new Response(hit.bytes, { headers: { "content-type": "image/jpeg" } });      return new Response(null, { status: hit.status });    },  };}async function given(slug: string, fetch: Fetcher): Promise<void> {  await runInDurableObject(stub(slug), (instance: Business) => {    instance.filmFetcher = fetch;  });}const API = "https://api.themoviedb.org/3";const IMAGES = "https://image.tmdb.org/t/p/";const FERRY = {  id: 501,  title: "Night Ferry",  release_date: "2019-03-02",  runtime: 112,  overview: "A ferry crosses a strait at night, and its passengers are not who they say.",  genres: [{ name: "Drama" }, { name: "Mystery" }],  poster_path: "/ferry-poster.jpg",  backdrop_path: "/ferry-backdrop.jpg",  original_language: "en",  spoken_languages: [{ iso_639_1: "en", english_name: "English" }],  production_countries: [{ iso_3166_1: "GB", name: "United Kingdom" }],  imdb_id: "tt0000501",  external_ids: { imdb_id: "tt0000501", tvdb_id: 334501 },  credits: {    cast: ["Orla Venn", "Tobias Marr", "Ines Calder", "Wren Hollis", "Jonah Pike", "Sixth Person"].map((name) => ({ name })),    crew: [{ job: "Writer", name: "Pell Ashby" }, { job: "Director", name: "Mara Quill" }],  },  release_dates: { results: [{ iso_3166_1: "US", release_dates: [{ certification: "PG-13" }] }, { iso_3166_1: "IN", release_dates: [{ certification: "" }, { certification: "UA" }] }] },};const LOWMARSH = {  id: 702,  name: "Lowmarsh",  first_air_date: "2021-04-11",  episode_run_time: [48],  overview: "A fen town and the people who never leave it.",  genres: [{ name: "Drama" }],  poster_path: "/lowmarsh-poster.jpg",  backdrop_path: null,  original_language: "en",  spoken_languages: [{ iso_639_1: "en", english_name: "English" }],  production_countries: [],  origin_country: ["GB"],  created_by: [{ name: "Hal Brenner" }],  external_ids: { imdb_id: "tt0000702", tvdb_id: "770702" },  credits: { cast: [{ name: "Orla Venn" }] },  content_ratings: { results: [{ iso_3166_1: "US", rating: "TV-14" }] },  seasons: [    { season_number: 0, name: "Specials", id: 9000 },    { season_number: 1, name: "Season 1", id: 9001, air_date: "2021-04-11", poster_path: "/lowmarsh-s1.jpg" },  ],};const LOWMARSH_S1 = {  id: 9001,  name: "Season 1",  air_date: "2021-04-11",  poster_path: "/lowmarsh-s1.jpg",  episodes: [    { episode_number: 1, name: "Cicadas", overview: "The town wakes.", runtime: 51, air_date: "2021-04-11", still_path: "/e1.jpg", id: 8001 },    { episode_number: 2, name: "The Long Night", overview: "Nobody sleeps.", runtime: 47, air_date: "2021-04-18", still_path: "/e2.jpg", id: 8002 },  ],};/** RULE (Cinemas definition, 5 Nov 2026): Find a film asks TMDB from the object, fills only empty columns and says where each came from; the key is the Worker's and is never said. */describe("find_film", () => {  const SLUG = "films-find";  let credential = "";  let made = "";  const said: string[] = [];  const answered = async (name: string, args: Record<string, unknown>) => {    const res = await act(SLUG, credential, name, args);    said.push(JSON.stringify(res.body));    return res;  };  it("makes a Want to watch film from a query's best match, every column filled from TMDB, the pictures kept once", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true, ...FILMS_OPEN }));    const s = tmdb([      [`${API}/search/multi?`, { json: { results: [{ media_type: "person", id: 1 }, { media_type: "movie", id: 400, release_date: "2001-01-01" }, { media_type: "movie", id: 501, release_date: "2019-03-02" }] } }],      [`${API}/movie/501?`, { json: FERRY }],      [IMAGES, { bytes: JPEG }],    ]);    await given(SLUG, s.fetch);    const res = await answered("find_film", { query: "Night Ferry (2019)" });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ made: true, seasons: { made: 0, filled: 0 } });    made = String(res.body.film);    const search = new URL(s.asked[0]!.url);    expect(search.searchParams.get("query"), "the year is taken off the words and matched").toBe("Night Ferry");    expect(search.searchParams.get("api_key"), "the key goes as TMDB's v3 parameter").toBe(KEY);    expect(new URL(s.asked[1]!.url).searchParams.get("append_to_response")).toBe("release_dates,credits,external_ids");    expect(s.asked.every((a) => a.agent === USER_AGENT), "TMDB is told who asks").toBe(true);    expect(s.asked.filter((a) => a.url.startsWith(IMAGES)).map((a) => a.url)).toEqual([`${IMAGES}w780/ferry-poster.jpg`, `${IMAGES}w1280/ferry-backdrop.jpg`]);    const film = await row(SLUG, "film", made);    expect(film).toMatchObject({      title: "Night Ferry",      year: "2019",      kind: "film",      status: "want_to_watch",      synopsis: FERRY.overview,      genres: "Drama, Mystery",      director: "Mara Quill",      cast: "Orla Venn, Tobias Marr, Ines Calder, Wren Hollis, Jonah Pike",      certificate: "UA",      language: "English",      country: "United Kingdom",      minutes: 112,      tmdb_id: "501",      imdb_id: "tt0000501",      tvdb_id: "334501",    });    expect(String(film.poster)).toMatch(PHOTO_KEY);    expect(String(film.backdrop)).toMatch(PHOTO_KEY);    expect(film.added_on).toMatch(/^\d{4}-\d{2}-\d{2}$/);    const from = JSON.parse(String(film.filled_from)) as Record<string, string>;    expect(Object.keys(from).sort()).toEqual(["backdrop", "cast", "certificate", "country", "director", "genres", "imdb_id", "language", "minutes", "poster", "synopsis", "title", "tmdb_id", "tvdb_id", "year"]);    expect(new Set(Object.values(from))).toEqual(new Set(["tmdb"]));  });  it("finds the same film again by its TMDB id rather than making another", async () => {    await given(SLUG, tmdb([[`${API}/search/multi?`, { json: { results: [{ media_type: "movie", id: 501 }] } }], [`${API}/movie/501?`, { json: FERRY }]]).fetch);    const res = await answered("find_film", { query: "night ferry" });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ film: made, made: false, filled: [] });    expect((await rows(SLUG, "film")).length).toBe(1);  });  it("fills only a named film's empty columns, by its title and year, and says only those", async () => {    const id = ((await act(SLUG, credential, "create", { table: "film", data: { title: "Night Ferry", year: "2019", kind: "film", director: "Someone Else", filled_from: JSON.stringify({ title: "file" }) } })).body.made as { id: string }).id;    const s = tmdb([[`${API}/search/movie?`, { json: { results: [{ id: 501, release_date: "2019-03-02" }] } }], [`${API}/movie/501?`, { json: FERRY }], [IMAGES, { bytes: JPEG }]]);    await given(SLUG, s.fetch);    const res = await answered("find_film", { film: id });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(new URL(s.asked[0]!.url).searchParams.get("year")).toBe("2019");    const film = await row(SLUG, "film", id);    expect(film.director, "a column the owner filled stays").toBe("Someone Else");    expect(film.title).toBe("Night Ferry");    expect(film.synopsis).toBe(FERRY.overview);    expect(res.body.filled).not.toContain("director");    expect(res.body.filled).not.toContain("title");    const from = JSON.parse(String(film.filled_from)) as Record<string, string>;    expect(from.title, "what came before stays said").toBe("file");    expect(from.director).toBeUndefined();    expect(from.synopsis).toBe("tmdb");  });  it("never lays a found poster over a frame the owner picked from the film", async () => {    const id = ((await act(SLUG, credential, "create", { table: "film", data: { title: "Night Ferry", year: "2019", kind: "film", poster: "picked/frame.jpg", poster_before: "found/first.jpg", poster_from: 61.5 } })).body.made as { id: string }).id;    const s = tmdb([[`${API}/search/movie?`, { json: { results: [{ id: 501, release_date: "2019-03-02" }] } }], [`${API}/movie/501?`, { json: FERRY }], [IMAGES, { bytes: JPEG }]]);    await given(SLUG, s.fetch);    const res = await answered("find_film", { film: id });    expect(res.status, JSON.stringify(res.body)).toBe(200);    const film = await row(SLUG, "film", id);    expect(film.poster, "the picked frame stays worn").toBe("picked/frame.jpg");    expect(film.poster_before, "the original to go back to stays").toBe("found/first.jpg");    expect(film.poster_from).toBe(61.5);    expect(res.body.filled).not.toContain("poster");  });  it("gives a series its seasons and episodes, matching held ones by number and filling only what is empty", async () => {    const series = ((await act(SLUG, credential, "create", { table: "film", data: { title: "Lowmarsh", kind: "series" } })).body.made as { id: string }).id;    await act(SLUG, credential, "create", { table: "film_season", id: "s-low-1", data: { film: series, number: 1, title: "The Fen Year" } });    await act(SLUG, credential, "create", { table: "film_episode", id: "e-low-1", data: { season: "s-low-1", series, number: 1, title: "Cicadas (my cut)" } });    const s = tmdb([      [`${API}/search/tv?`, { json: { results: [{ id: 702, first_air_date: "2021-04-11" }] } }],      [`${API}/tv/702?`, { json: LOWMARSH }],      [`${API}/tv/702/season/1?`, { json: LOWMARSH_S1 }],      [IMAGES, { bytes: JPEG }],    ]);    await given(SLUG, s.fetch);    const res = await answered("find_film", { film: series });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ film: series, made: false, seasons: { made: 0, filled: 1 }, episodes: { made: 1, filled: 1 } });    expect(new URL(s.asked[1]!.url).searchParams.get("append_to_response")).toBe("content_ratings,credits,external_ids");    expect(s.asked.some((a) => a.url.includes("/season/0")), "TMDB's Specials are no season of the series").toBe(false);    expect(await row(SLUG, "film", series)).toMatchObject({ kind: "series", director: "Hal Brenner", certificate: "TV-14", country: "GB", minutes: 48, tmdb_id: "702", imdb_id: "tt0000702", tvdb_id: "770702" });    const season = await row(SLUG, "film_season", "s-low-1");    expect(season).toMatchObject({ title: "The Fen Year", year: "2021", tmdb_id: "9001" });    expect(String(season.poster)).toMatch(PHOTO_KEY);    expect((await rows(SLUG, "film_season")).length, "season 1 is matched, not made again").toBe(1);    const first = await row(SLUG, "film_episode", "e-low-1");    expect(first).toMatchObject({ title: "Cicadas (my cut)", synopsis: "The town wakes.", minutes: 51, aired: "2021-04-11", tmdb_id: "8001" });    expect(String(first.still)).toMatch(PHOTO_KEY);    const second = (await rows(SLUG, "film_episode")).find((e) => e.data.number === 2)!;    expect(second.data).toMatchObject({ season: "s-low-1", series, title: "The Long Night", minutes: 47, aired: "2021-04-18" });  });  it("refuses TMDB asked too often, TMDB not answering, and nothing found, and never says the key", async () => {    const refused = async (answers: [string, Answer][], args: Record<string, unknown>, status: number, code: string): Promise<void> => {      await given(SLUG, tmdb(answers).fetch);      const res = await answered("find_film", args);      expect(res.status, JSON.stringify(res.body)).toBe(status);      expect(res.body.code).toBe(code);    };    await refused([[`${API}/search/multi?`, { status: 429 }]], { query: "Busy Day" }, 503, "lookup_failed");    await refused([[`${API}/search/multi?`, { status: 403 }]], { query: "Busy Day" }, 503, "lookup_failed");    await refused([[`${API}/search/multi?`, { throws: true }]], { query: "Busy Day" }, 502, "lookup_failed");    await refused([[`${API}/search/multi?`, { json: { results: [] } }]], { query: "Nowhere Found" }, 404, "no_film_found");    await refused([], {}, 400, "bad_args");    await refused([], { film: "no-such-film" }, 404, "no_such_record");    expect(said.some((body) => body.includes(KEY)), "no answer says the key").toBe(false);    const stored = await runInDurableObject(stub(SLUG), (_i, state) => state.storage.sql.exec<{ n: number }>("SELECT count(*) AS n FROM rows WHERE data LIKE ?", `%${KEY}%`).one().n);    expect(Number(stored), "no row holds the key").toBe(0);  });  it("answers not connected on a server holding no TMDB key, asking nothing", async () => {    const s = tmdb([]);    const res = await runInDurableObject(stub(SLUG), async (instance: Business) => {      instance.filmFetcher = s.fetch;      const held = (instance as unknown as { env: Env }).env;      const key = held.TMDB_API_KEY;      delete held.TMDB_API_KEY;      try {        return await instance.fetch(new Request("https://example.test/v1/act", { method: "POST", headers: { authorization: `Bearer ${credential}`, "content-type": "application/json" }, body: JSON.stringify({ act: "find_film", args: { query: "Night Ferry" } }) }));      } finally {        held.TMDB_API_KEY = key;      }    });    expect(res.status).toBe(404);    const body = (await res.json()) as { code: string; message: string };    expect(body.code).toBe("not_connected");    expect(body.message).toMatch(/TMDB is not connected on this server/);    expect(s.asked).toEqual([]);  });});async function upload(slug: string, key: string, auth: string, body: Uint8Array, type: string): Promise<void> {  const res = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${auth}`, "content-type": type, "content-length": String(body.length) }, body });  expect(res.status, await res.text()).toBe(201);}async function held(slug: string, key: string, auth: string): Promise<number> {  return (await SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "HEAD", headers: { authorization: `Bearer ${auth}` } })).status;}/** RULE (Cinemas definition, 5 Nov 2026): a file the phone cannot play waits for the Mac; the Mac reads what waits, converts it, and says so, and the upload goes. */describe("the Mac's queue", () => {  const SLUG = "films-queue";  let credential = "";  let owner = "";  const folder = (id: string): string => `${DATABASE_ID}/films/${id}/`;  it("lists the films and episodes waiting for the Mac, and nothing that plays or waits for nothing", async () => {    ({ credential, owner } = await personalObject(SLUG, { arrival: true, ...FILMS_OPEN }));    const ok = async (table: string, id: string, data: Doc): Promise<void> => {      const res = await act(SLUG, credential, "create", { table, id, data });      expect(res.status, JSON.stringify(res.body)).toBe(200);    };    await ok("film", "f-wait", { title: "Night Ferry", needs_mac: true, source_file: `${folder("f-wait")}source.mkv` });    await ok("film", "f-plays", { title: "Paper Comets", needs_mac: false, file: `${folder("f-plays")}whole.mp4` });    await ok("film", "f-poster", { title: "The Quiet Engines" });    await ok("film", "s-low", { title: "Lowmarsh", kind: "series" });    await ok("film_season", "s-low-2", { film: "s-low", number: 2, title: "Season 2" });    await ok("film_episode", "e-low-2-5", { season: "s-low-2", series: "s-low", number: 5, title: "Cicadas", needs_mac: true, source_file: `${folder("e-fresh")}source.avi` });    const res = await http<{ rows: Doc[] }>(SLUG, "GET", "/v1/films/pending", undefined, { authorization: `Bearer ${owner}` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body.rows).toEqual([      { table: "film", id: "f-wait", title: "Night Ferry", source_file: `${folder("f-wait")}source.mkv` },      { table: "film_episode", id: "e-low-2-5", title: "Cicadas", source_file: `${folder("e-fresh")}source.avi`, series: "s-low", series_title: "Lowmarsh", season_number: 2, number: 5 },    ]);    expect((await http(SLUG, "GET", "/v1/films/pending")).status, "the queue is the owner's").toBe(403);  });  it("takes film_converted: the stream becomes the file, the upload goes, an empty poster is filled", async () => {    // The Mac converts and lays the stream, by its device credential (an assistant's token drops no file: AVATAR SEAL 4).    await upload(SLUG, `${folder("f-wait")}source.mkv`, credential, new TextEncoder().encode("an invented matroska file"), "video/x-matroska");    await upload(SLUG, `${folder("e-fresh")}source.avi`, credential, new TextEncoder().encode("an invented avi file"), "application/octet-stream");    const master = `${folder("f-wait")}master.m3u8`;    const before = await act(SLUG, credential, "film_converted", { table: "film", id: "f-wait", file: master });    expect(before.status, "the stream must be there first").toBe(404);    expect(before.body.code).toBe("no_stream");    await upload(SLUG, master, credential, new TextEncoder().encode("#EXTM3U\n"), "application/vnd.apple.mpegurl");    await upload(SLUG, `${folder("f-wait")}poster.jpg`, credential, JPEG, "image/jpeg");    const res = await act(SLUG, credential, "film_converted", { table: "film", id: "f-wait", file: master, poster: `${folder("f-wait")}poster.jpg` });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ table: "film", id: "f-wait", file: master, dropped: `${folder("f-wait")}source.mkv` });    const film = await row(SLUG, "film", "f-wait");    expect(film).toMatchObject({ file: master, needs_mac: false, poster: `${folder("f-wait")}poster.jpg` });    expect(film.source_file ?? null).toBeNull();    expect(await held(SLUG, `${folder("f-wait")}source.mkv`, credential), "the upload went once the write was kept").toBe(404);    expect(await held(SLUG, master, credential), "the stream stays").toBe(200);    const whole = `${folder("e-low-2-5")}whole.mp4`;    await upload(SLUG, whole, credential, new TextEncoder().encode("an invented mp4"), "video/mp4");    const episode = await act(SLUG, credential, "film_converted", { table: "film_episode", id: "e-low-2-5", file: whole });    expect(episode.status, JSON.stringify(episode.body)).toBe(200);    expect(episode.body.dropped, "an upload in a folder of its own goes too").toBe(`${folder("e-fresh")}source.avi`);    expect(await held(SLUG, `${folder("e-fresh")}source.avi`, credential)).toBe(404);    expect((await http<{ rows: Doc[] }>(SLUG, "GET", "/v1/films/pending", undefined, { authorization: `Bearer ${credential}` })).body.rows).toEqual([]);    // SERVER 27 (LOW): an assistant's token never says a film is converted, its stream held or not: the same refusal,    // so it learns nothing of what the films folder holds, and the upload stays for the owner's devices.    const tokenSource = `${folder("f-token")}source.mkv`;    const tokenWhole = `${folder("f-token")}whole.mp4`;    expect((await act(SLUG, credential, "create", { table: "film", id: "f-token", data: { title: "Second Ferry", needs_mac: true, source_file: tokenSource } })).status).toBe(200);    await upload(SLUG, tokenSource, credential, new TextEncoder().encode("another invented matroska file"), "video/x-matroska");    await upload(SLUG, tokenWhole, credential, new TextEncoder().encode("another invented mp4"), "video/mp4");    for (const file of [tokenWhole, `${folder("f-token")}never-sent.mp4`]) {      const byToken = await act(SLUG, owner, "film_converted", { table: "film", id: "f-token", file });      expect([byToken.status, byToken.body.code], file).toEqual([403, "sealed_kind"]);    }    expect(await held(SLUG, tokenSource, credential), "the upload stays").toBe(200);  });  it("refuses a stream outside the row's folder, a table that is no film's, and anyone but the owner's devices", async () => {    const code = async (args: Record<string, unknown>, auth = credential): Promise<[number, unknown]> => {      const res = await act(SLUG, auth, "film_converted", args);      return [res.status, res.body.code];    };    expect(await code({ table: "film", id: "f-plays", file: `${folder("f-wait")}master.m3u8` })).toEqual([400, "bad_file"]);    expect(await code({ table: "film", id: "f-plays", file: `${folder("f-plays")}whole.mkv` })).toEqual([400, "bad_file"]);    expect(await code({ table: "film", id: "f-plays", file: `${folder("f-plays")}master.m3u8`, poster: `${folder("f-wait")}poster.jpg` })).toEqual([400, "bad_file"]);    expect(await code({ table: "book", id: "f-plays", file: `${folder("f-plays")}master.m3u8` })).toEqual([400, "bad_args"]);    expect(await code({ table: "film", id: "f-gone", file: `${folder("f-gone")}master.m3u8` })).toEqual([404, "no_such_record"]);    // A token, the owner's own included, is refused before anything is read: a row there or not, a key good or bad.    expect(await code({ table: "film", id: "f-gone", file: `${folder("f-gone")}master.m3u8` }, owner)).toEqual([403, "sealed_kind"]);    expect(await code({ table: "film", id: "f-plays", file: `${folder("f-wait")}master.m3u8` }, owner)).toEqual([403, "sealed_kind"]);  });});/** RULE (5 Nov 2026): erasing a film takes every film folder it holds a file in, its upload's too. */describe("an erased film waiting for the Mac", () => {  it("takes its upload's folder with it", async () => {    // The phone's emptied Bin erases, by its device credential: a token erases nothing (EMPTY BIN 1).    const SLUG = "films-erase";    const { credential: device } = await personalObject(SLUG, { arrival: true, ...FILMS_OPEN });    const source = `${DATABASE_ID}/films/fresh-folder/source.mkv`;    await upload(SLUG, source, device, new TextEncoder().encode("an invented matroska file"), "video/x-matroska");    const made = await act(SLUG, device, "create", { table: "film", id: "f-erase", data: { title: "Gone Soon", needs_mac: true, source_file: source } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    // A plain delete is a phone's Bin, which Undo reverses: the upload stays. The Bin emptied (an erase) takes it.    expect((await act(SLUG, device, "delete", { table: "film", id: "f-erase" })).status).toBe(200);    expect(await held(SLUG, source, device), "in a phone's Bin, the upload stays").toBe(200);    expect((await act(SLUG, device, "create", { table: "film", id: "f-erase-2", data: { title: "Gone Soon", needs_mac: true, source_file: source } })).status).toBe(200);    expect((await act(SLUG, device, "delete", { table: "film", id: "f-erase-2", erase: "bin" })).status).toBe(200);    expect(await held(SLUG, source, device)).toBe(404);  });});/** RULE (owner, 17 Nov 2026): a film's original goes with the film when it is erased, as its stream does. */describe("an erased film keeping its original", () => {  it("takes the original's pieces and index with its folder, and an original laid in a folder of its own with that one", async () => {    // The phone's emptied Bin erases, by its device credential: a token erases nothing (EMPTY BIN 1).    const SLUG = "films-erase-original";    const { credential: device } = await personalObject(SLUG, { arrival: true, ...FILMS_OPEN });    const bytes = new TextEncoder().encode("invented bytes");    const keys = [`${DATABASE_ID}/films/f-orig/master.m3u8`, `${DATABASE_ID}/films/f-orig/original/piece-000000.bin`, `${DATABASE_ID}/films/f-orig/original/index.json`];    for (const key of keys) await upload(SLUG, key, device, bytes, "application/octet-stream");    const made = await act(SLUG, device, "create", { table: "film", id: "f-orig", data: { title: "Kept Whole", file: keys[0], original: keys[2], original_bytes: 14, original_sha256: "a".repeat(64) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    // A second film whose stream lies in a fresh folder, its original in its own.    const elsewhere = [`${DATABASE_ID}/films/fresh-stream/master.m3u8`, `${DATABASE_ID}/films/f-orig2/original/piece-000000.bin`, `${DATABASE_ID}/films/f-orig2/original/index.json`];    for (const key of elsewhere) await upload(SLUG, key, device, bytes, "application/octet-stream");    expect((await act(SLUG, device, "create", { table: "film", id: "f-orig2", data: { title: "Kept Apart", file: elsewhere[0], original: elsewhere[2] } })).status).toBe(200);    for (const id of ["f-orig", "f-orig2"]) expect((await act(SLUG, device, "delete", { table: "film", id, erase: "bin" })).status).toBe(200);    for (const key of [...keys, ...elsewhere]) expect(await held(SLUG, key, device), key).toBe(404);  });});/** * RULE (e2e rulings R1, R2; 16 Nov 2026): films are sealed. * A film find_film makes lands sealed at arrival under the id its TMDB id * derives, so the same work finds it again; a sealed series' details, its * seasons' and its episodes' go as fill patches the phone lays only where * each is empty; a named sealed film is looked up by the words its phone * hands over, never by a column the object cannot read. */describe("films under the seal", () => {  const SLUG = "films-sealed";  let credential = "";  const DK = new Uint8Array(32).fill(9);  const ask = (args: Record<string, unknown>) => act(SLUG, credential, "find_film", args);  it("lands a found film sealed at arrival under its TMDB id's own id, and finds it again by that id", async () => {    ({ credential } = await personalObject(SLUG, { arrival: true }));    await given(SLUG, tmdb([[`${API}/search/multi?`, { json: { results: [{ media_type: "movie", id: 501 }] } }], [`${API}/movie/501?`, { json: FERRY }]]).fetch);    const res = await ask({ query: "night ferry" });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(res.body).toMatchObject({ made: true, film: derivedId("film", ["tmdb", "film", "501"]) });    const film = await row(SLUG, "film", String(res.body.film));    expect(String(film.dek_enc)).toMatch(/^a1:/);    expect(film).toMatchObject({ kind: "film", status: "want_to_watch" });    expect(film).not.toHaveProperty("title");    // Its length is sealed with the words (LOCK TABLES 2 part 4).    expect(film).not.toHaveProperty("minutes");    expect(film).not.toHaveProperty("director");    expect(await openArrivalRow(film, bodyAad(DATABASE_ID, "film", String(res.body.film)), "film", String(res.body.film))).toMatchObject({ title: "Night Ferry", director: "Mara Quill", tmdb_id: "501", minutes: 112 });    await given(SLUG, tmdb([[`${API}/search/multi?`, { json: { results: [{ media_type: "movie", id: 501 }] } }], [`${API}/movie/501?`, { json: FERRY }]]).fetch);    expect((await ask({ query: "the night ferry" })).body).toMatchObject({ film: res.body.film, made: false });    expect((await rows(SLUG, "film")).length).toBe(1);  });  it("fills a sealed series, its season and its episode as fill patches, looked up by the words its phone hands over", async () => {    const seal = async (table: string, id: string, clear: Record<string, unknown>, words: Record<string, unknown>) => {      const made = await act(SLUG, credential, "create", { table, id, data: { ...clear, ...(await sealRow(DK, table, id, 1, words)) } });      expect(made.status, JSON.stringify(made.body)).toBe(200);    };    await seal("film", "f-low", { kind: "series" }, { title: "Lowmarsh" });    await seal("film_season", "s-low", { film: "f-low", number: 1 }, { title: "The Fen Year" });    await seal("film_episode", "e-low", { season: "s-low", series: "f-low", number: 1 }, { title: "Cicadas (my cut)" });    const s = tmdb([      [`${API}/search/tv?`, { json: { results: [{ id: 702, first_air_date: "2021-04-11" }] } }],      [`${API}/tv/702?`, { json: LOWMARSH }],      [`${API}/tv/702/season/1?`, { json: LOWMARSH_S1 }],    ]);    await given(SLUG, s.fetch);    expect((await ask({ film: "f-low" })).status, "a sealed film with no words handed over has nothing to look up by").toBe(400);    const res = await ask({ film: "f-low", title: "Lowmarsh" });    expect(res.status, JSON.stringify(res.body)).toBe(200);    expect(new URL(s.asked[0]!.url).searchParams.get("query")).toBe("Lowmarsh");    expect(res.body).toMatchObject({ film: "f-low", seasons: { made: 0, filled: 1 }, episodes: { made: 1, filled: 1 } });    for (const [table, id] of [["film", "f-low"], ["film_season", "s-low"], ["film_episode", "e-low"]] as const) {      const held = await row(SLUG, table, id);      const patches = held.arrival_patches as Doc[];      expect(patches, `${table} ${id}`).toHaveLength(1);      expect(patches[0]!.fill).toBe(true);      expect(held, "the person's title stays sealed").not.toHaveProperty("title");    }    const episode = await row(SLUG, "film_episode", "e-low");    expect(await openArrivalRow((episode.arrival_patches as Doc[])[0]!, bodyAad(DATABASE_ID, "film_episode", "e-low"), "film_episode", "e-low")).toMatchObject({ synopsis: "The town wakes." });    const second = (await rows(SLUG, "film_episode")).find((e) => e.data.number === 2)!;    expect(String(second.data.dek_enc)).toMatch(/^a1:/);    expect(second.data).toMatchObject({ season: "s-low", series: "f-low" });  });});/** * RULE (e2e rulings R2, 16 Nov 2026): a token holds no key * (the Mac's film and fetch importers speak with an owner token), so its * clear words for a sealed table are sealed at arrival, never refused and * never kept clear; a device, which holds the key, still sends them sealed. */describe("a token's clear write to a sealed table", () => {  it("lands sealed at arrival, and a device's clear one is refused", async () => {    const slug = "films-token-arrival";    const { credential, owner } = await personalObject(slug, { arrival: true });    const made = await http<{ made: { id: string } }>(slug, "POST", "/v1/act", { act: "create", args: { table: "film", data: { title: "An Invented Import", kind: "film", status: "want_to_watch" } } }, { authorization: `Bearer ${owner}` });    expect(made.status, JSON.stringify(made.body)).toBe(200);    const film = await row(slug, "film", made.body.made.id);    expect(String(film.dek_enc)).toMatch(/^a1:/);    expect(film).not.toHaveProperty("title");    expect(await openArrivalRow(film, bodyAad(DATABASE_ID, "film", made.body.made.id), "film", made.body.made.id)).toMatchObject({ title: "An Invented Import" });    const device = await act(slug, credential, "create", { table: "film", data: { title: "Clear From A Phone", kind: "film" } });    expect(device.status).toBe(400);    expect(device.body.code).toBe("sealed_in_clear");  });});/** * RULE (17 Nov 2026): an ask for subtitles is found in * one cheap read. Find subtitles and Make subtitles set the sealed row's clear * `subtitle_work`; `GET /v1/films/subtitles/asked` lists those rows by table, * id and ask, the longest waiting first, never a title, and a row the Mac has * moved on (finding, ready, failed) asks no more. */describe("the subtitles asked for", () => {  const SLUG = "films-subtitles-asked";  const DK = new Uint8Array(32).fill(7);  it("lists the sealed films and episodes asking, by id and ask only, and drops one the Mac has taken", async () => {    const { credential, owner } = await personalObject(SLUG, { arrival: true });    const seal = async (table: string, id: string, clear: Record<string, unknown>, words: Record<string, unknown>) => {      const made = await act(SLUG, credential, "create", { table, id, data: { ...clear, ...(await sealRow(DK, table, id, 1, words)) } });      expect(made.status, JSON.stringify(made.body)).toBe(200);    };    const master = (id: string) => `${DATABASE_ID}/films/${id}/master.m3u8`;    await seal("film", "f-quiet", { kind: "film", file: master("f-quiet") }, { title: "The Quiet Engines" });    await seal("film", "f-ferry", { kind: "film", file: master("f-ferry") }, { title: "Night Ferry" });    await seal("film", "s-low", { kind: "series" }, { title: "Lowmarsh" });    await seal("film_season", "s-low-1", { film: "s-low", number: 1 }, { title: "The Fen Year" });    await seal("film_episode", "e-low-1", { season: "s-low-1", series: "s-low", number: 1, file: master("e-low-1") }, { title: "Cicadas" });    const asked = async () => {      const res = await http<{ rows: Doc[] }>(SLUG, "GET", "/v1/films/subtitles/asked", undefined, { authorization: `Bearer ${owner}` });      expect(res.status, JSON.stringify(res.body)).toBe(200);      return res.body.rows;    };    expect(await asked(), "nothing asked yet").toEqual([]);    // The phone's acts, as its kit holds them: a clear patch of subtitle_work on the sealed row.    const tap = async (table: string, id: string, command: "find_subtitles" | "generate_subtitles") => {      const def = kitTable(table);      const cmd = (def.commands as Doc[]).find((c) => c.id === command)!;      const patch = (cmd.data as { patch: Doc }).patch;      const res = await act(SLUG, credential, "update", { table, id, data: patch });      expect(res.status, JSON.stringify(res.body)).toBe(200);    };    await tap("film", "f-quiet", "find_subtitles");    await tap("film_episode", "e-low-1", "generate_subtitles");    await tap("film", "f-ferry", "generate_subtitles");    const rows = await asked();    expect(rows.map((r) => [r.table, r.id, r.ask])).toEqual([      ["film", "f-quiet", "find"],      ["film_episode", "e-low-1", "generate"],      ["film", "f-ferry", "generate"],    ]);    for (const r of rows) expect(Object.keys(r).sort(), "ids, the ask, its time and version: never a title").toEqual(["ask", "asked_at", "id", "table", "version"]);    for (const r of rows) expect(r.version, "the version the Mac opens it from").toEqual(expect.any(Number));    expect(JSON.stringify(rows)).not.toMatch(/Quiet|Ferry|Cicadas|Lowmarsh/);    // The Mac, with its owner token, takes one and says how it went: it asks no more.    const taken = await act(SLUG, owner, "update", { table: "film", id: "f-quiet", data: { subtitle_work: "finding", subtitle_note: "Finding English subtitles on OpenSubtitles" } });    expect(taken.status, JSON.stringify(taken.body)).toBe(200);    const failed = await act(SLUG, owner, "update", { table: "film_episode", id: "e-low-1", data: { subtitle_work: "failed", subtitle_note: "Subtitles were not made: no speech was heard" } });    expect(failed.status, JSON.stringify(failed.body)).toBe(200);    expect((await asked()).map((r) => r.id)).toEqual(["f-ferry"]);    expect((await http(SLUG, "GET", "/v1/films/subtitles/asked")).status, "the asks are the owner's").toBe(403);  });  /** RULE (SUBTITLE FILE, 25 Nov 2026): Give subtitles writes the given file's key, its language and `file` in the clear on the sealed row; the Mac finds it among the asks as `file`. */  it("lists a film given a subtitle file on the phone as asking `file`", async () => {    const slug = `${SLUG}-file`;    const { credential, owner } = await personalObject(slug, { arrival: true });    const key = `${DATABASE_ID}/films/f-given/given/sub-0123456789abcdef.srt`;    const made = await act(slug, credential, "create", { table: "film", id: "f-given", data: { kind: "film", file: `${DATABASE_ID}/films/f-given/master.m3u8`, ...(await sealRow(DK, "film", "f-given", 1, { title: "Paper Comets" })) } });    expect(made.status, JSON.stringify(made.body)).toBe(200);    const give = await act(slug, credential, "update", { table: "film", id: "f-given", data: { subtitle_given: key, subtitle_given_language: "en", subtitle_work: "file", subtitle_note: "Waiting for your Mac to add your subtitles" } });    expect(give.status, JSON.stringify(give.body)).toBe(200);    const res = await http<{ rows: Doc[] }>(slug, "GET", "/v1/films/subtitles/asked", undefined, { authorization: `Bearer ${owner}` });    expect(res.body.rows.map((r) => [r.table, r.id, r.ask])).toEqual([["film", "f-given", "file"]]);    const give_ = (kitTable("film").commands as Doc[]).find((c) => c.id === "give_subtitles")!;    expect(give_).toMatchObject({ method: "films.subtitleFile", pick: { kind: "file", argument: "path", accept: ["srt", "vtt"] } });  });  // RULE (FILMS TRUE, 25 Nov 2026): a run that died where it stood leaves its row finding, generating or translating, and  // the phone offers no ask while it does; once quiet STALE_RUN_HOURS the object lists it again as the ask it ran.  it("lists a run that went quiet for hours again as the ask it ran, and leaves one still going", async () => {    const slug = `${SLUG}-stale`;    const { credential, owner } = await personalObject(slug, { arrival: true });    const film = async (id: string, work: Record<string, unknown>) => {      const made = await act(slug, credential, "create", { table: "film", id, data: { kind: "film", file: `${DATABASE_ID}/films/${id}/master.m3u8`, ...(await sealRow(DK, "film", id, 1, { title: "Paper Comets" })) } });      expect(made.status, JSON.stringify(made.body)).toBe(200);      const ran = await act(slug, credential, "update", { table: "film", id, data: work });      expect(ran.status, JSON.stringify(ran.body)).toBe(200);    };    await film("f-finding", { subtitle_work: "finding" });    await film("f-making", { subtitle_work: "generating", subtitle_note: "Making subtitles: 40%" });    await film("f-giving", { subtitle_work: "translating", subtitle_given: `${DATABASE_ID}/films/f-giving/given/sub-0123456789abcdef.srt` });    await film("f-going", { subtitle_work: "generating" });    const hours = (h: number) => new Date(Date.now() - h * 3600_000).toISOString();    await runInDurableObject(stub(slug), (_i, state) => {      for (const id of ["f-finding", "f-making", "f-giving"]) state.storage.sql.exec("UPDATE rows SET updated_at = ? WHERE table_id = 'film' AND id = ?", hours(7), id);      state.storage.sql.exec("UPDATE rows SET updated_at = ? WHERE table_id = 'film' AND id = ?", hours(1), "f-going");    });    const res = await http<{ rows: Doc[] }>(slug, "GET", "/v1/films/subtitles/asked", undefined, { authorization: `Bearer ${owner}` });    expect(res.body.rows.map((r) => [r.id, r.ask]).sort()).toEqual([["f-finding", "find"], ["f-giving", "file"], ["f-making", "generate"]]);  });});/** * `film:open` finds one film by its id or an id's prefix without opening the * sealed table (owner, 17 Nov 2026: 6.5 minutes to find one row): * `GET /v1/films/find` answers the row's id, version and clear columns, * never a title; a prefix naming several answers each, and a binned row none. */describe("a film found by its id", () => {  const SLUG = "films-found-by-id";  const DK = new Uint8Array(32).fill(9);  it("answers one sealed film or episode by id or prefix, clear columns only, never a title", async () => {    const { credential, owner } = await personalObject(SLUG, { arrival: true });    const seal = async (table: string, id: string, clear: Record<string, unknown>, words: Record<string, unknown>) => {      const made = await act(SLUG, credential, "create", { table, id, data: { ...clear, ...(await sealRow(DK, table, id, 1, words)) } });      expect(made.status, JSON.stringify(made.body)).toBe(200);    };    const master = (id: string) => `${DATABASE_ID}/films/${id}/master.m3u8`;    await seal("film", "a1b2c3d4-quiet", { kind: "film", file: master("a1b2c3d4-quiet"), minutes: 94, sha256: "ab".repeat(32) }, { title: "The Quiet Engines" });    await seal("film", "a1b2ffff-ferry", { kind: "film", file: master("a1b2ffff-ferry"), minutes: 101 }, { title: "Night Ferry" });    await seal("film", "c0ffee00-nofile", { kind: "film" }, { title: "Unsent" });    await seal("film", "s0000001-low", { kind: "series" }, { title: "Lowmarsh" });    await seal("film_season", "s0000001-low-1", { film: "s0000001-low", number: 1 }, { title: "The Fen Year" });    await seal("film_episode", "e0000001-low", { season: "s0000001-low-1", series: "s0000001-low", number: 1, file: master("e0000001-low"), minutes: 44 }, { title: "Cicadas" });    const find = async (id: string, who: string | null = owner) => {      const res = await http<{ rows: Doc[] }>(SLUG, "GET", `/v1/films/find?id=${encodeURIComponent(id)}`, undefined, who ? { authorization: `Bearer ${who}` } : {});      return res;    };    const one = await find("a1b2c3d4");    expect(one.status, JSON.stringify(one.body)).toBe(200);    expect(one.body.rows).toEqual([      { table: "film", id: "a1b2c3d4-quiet", version: expect.any(Number), kind: "film", file: master("a1b2c3d4-quiet"), original: null },    ]);    expect((await find("a1b2c3d4-quiet")).body.rows.map((r) => r.id), "the whole id").toEqual(["a1b2c3d4-quiet"]);    expect((await find("a1b2")).body.rows.map((r) => r.id), "a prefix naming two answers both").toEqual(["a1b2c3d4-quiet", "a1b2ffff-ferry"]);    expect((await find("e0000001")).body.rows, "an episode").toEqual([expect.objectContaining({ table: "film_episode", id: "e0000001-low", kind: "episode" })]);    expect((await find("c0ffee00")).body.rows, "a film with no file is found, with none").toEqual([expect.objectContaining({ id: "c0ffee00-nofile", file: null })]);    expect((await find("zzzz9999")).body.rows).toEqual([]);    expect(JSON.stringify((await find("a1b2")).body)).not.toMatch(/Quiet|Ferry/);    expect((await find("a1")).status, "too short a prefix").toBe(400);    expect((await find("a1b2", null)).status, "the films are the owner's").toBe(403);    const binned = await act(SLUG, owner, "delete", { table: "film", id: "a1b2ffff-ferry" });    expect(binned.status, JSON.stringify(binned.body)).toBe(200);    expect((await find("a1b2ffff")).body.rows, "a binned film is not found").toEqual([]);    expect((await find("a1b2ffff-ferry")).body.rows, "nor by its whole id").toEqual([]);  });});