Cotton code
108 lines · 5.1 KB · TypeScriptRaw
/** * THE FILM TABLES ONTO COTTON CINEMAS, ONCE (owner, 5 Nov 2026: Cotton * Cinemas, the film tables may be reshaped): the object's `reshape_films` * act (src/films.ts), run with an owner `ctn_` token after the Worker * carrying the cinemas kit is deployed. * *   pnpm film:reshape --base <url> --token-file <path> * * --base        the object's address: https://cottondb.com (the token names the *               object), <the dev Worker's address (config/dev-server.json)>, or *               http://127.0.0.1:8787/b/<slug> under `wrangler dev` * --token-file  a file holding this Mac's device credential (ctd_, from seal-device), or an owner `ctn_` *               token while token scopes are off; never printed * * Every film row is kept: status watchlist becomes want_to_watch, notes are * copied into an empty review (notes stays stored, retired), an empty * added_on is the day the row was made; the kit's film, film_season, * film_episode and watch are laid whole, the Films tool goes and the kit's * Cinemas tool is laid. Run again it does nothing and answers zeros. Prints * the act's answer. * * Tests: `pnpm -s test:scripts` (film-reshape.test.ts); the act itself is * test/films.test.ts. */import { readFileSync } from "node:fs";import { homedir } from "node:os";import { isAbsolute, join, resolve } from "node:path";import { pathToFileURL } from "node:url";export class ReshapeRefusal extends Error {}export interface ReshapeArgs {  base: string;  token: string;}const USAGE = "pnpm film:reshape --base <url> --token-file <path>";export function parseArgs(argv: string[], cwd = process.env.INIT_CWD ?? process.cwd()): ReshapeArgs {  const values = new Map<string, string>();  for (let i = 0; i < argv.length; i++) {    const flag = argv[i]!;    if (!flag.startsWith("--")) throw new ReshapeRefusal(`unexpected ${flag}: ${USAGE}`);    const name = flag.slice(2);    if (!["base", "token-file"].includes(name)) throw new ReshapeRefusal(`no option --${name}: ${USAGE}`);    const value = argv[++i];    if (value === undefined || value.startsWith("--")) throw new ReshapeRefusal(`--${name} needs a value`);    values.set(name, value);  }  const base = values.get("base");  const file = values.get("token-file");  if (!base || !file) throw new ReshapeRefusal(`--base and --token-file are needed: ${USAGE}`);  if (!/^https?:\/\//.test(base)) throw new ReshapeRefusal("--base is the object's address, http(s)://…");  const path = file.startsWith("~/") ? join(homedir(), file.slice(2)) : isAbsolute(file) ? file : resolve(cwd, file);  let token: string;  try {    token = readFileSync(path, "utf8").trim();  } catch {    throw new ReshapeRefusal(`--token-file ${file} cannot be read`);  }  // An owner ctn_ token, or this Mac's device credential (ctd_, from seal-device): once token scopes are on, the  // switch keeps a ctn_ token to /mcp, so this act goes with the device credential (TOKEN-SCOPES-GO-LIVE.md).  if (!token) throw new ReshapeRefusal(`--token-file ${file} is empty`);  return { base: base.replace(/\/+$/, ""), token };}/** What the act answers: the rows whose values moved, the definitions laid and the tool removed. */export interface Reshaped {  mapped: { status: number; review: number; added_on: number };  laid: string[];  removed: string[];}/** The act at the object; its refusal said in its own words, never with the token. */export async function reshapeFilms(args: ReshapeArgs, fetcher: typeof fetch = fetch): Promise<Reshaped> {  const res = await fetcher(`${args.base}/v1/act`, {    method: "POST",    headers: { authorization: `Bearer ${args.token}`, "content-type": "application/json" },    body: JSON.stringify({ act: "reshape_films", args: {} }),    signal: AbortSignal.timeout(300_000),  });  const text = await res.text();  let answer: Record<string, unknown>;  try {    answer = text ? (JSON.parse(text) as Record<string, unknown>) : {};  } catch {    throw new ReshapeRefusal(`the object answered ${res.status}: ${text.slice(0, 200)}`);  }  if (!res.ok) throw new ReshapeRefusal(`the object refused (${res.status} ${String(answer.code ?? "")}): ${String(answer.message ?? text.slice(0, 200))}`);  const { mapped, laid, removed } = answer;  const counts = mapped as Record<string, unknown> | undefined;  if (!counts || typeof counts !== "object" || !["status", "review", "added_on"].every((k) => typeof counts[k] === "number") || !Array.isArray(laid) || !Array.isArray(removed)) {    throw new ReshapeRefusal(`the object answered no reshape: ${text.slice(0, 200)}`);  }  return { mapped: { status: counts.status as number, review: counts.review as number, added_on: counts.added_on as number }, laid: laid.map(String), removed: removed.map(String) };}async function main(): Promise<void> {  const done = await reshapeFilms(parseArgs(process.argv.slice(2)));  console.log(JSON.stringify(done, null, 2));}if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {  main().catch((error: unknown) => {    console.error(`film:reshape: ${error instanceof ReshapeRefusal ? error.message : String(error)}`);    process.exit(1);  });}