/** * Every kit, bundled into the Worker. A kit is what an app ships, in one * folder per app (crates/cotton-core/kits/<app>/): its kit.json names the * tables, tools and boards it ships, its tables sit in `tables/<id>.json` and * its tools in `tools/<id>/manifest.json`. An entry may name another kit's * file (`"shell/home"`), so a file is defined once and listed by any kit. * * A new number's first sign-in makes its personal object from the personal * kit (src/directory.ts), and every personal object is kept to it * (src/kit_keep.ts): its own tool (the kit.json itself, the object's map of * its tables), its tools, the shell's boards and its tables. The business * kits (yoga, kitchen) ride along so the Worker and its tests read every kit * from the one module. * * Bundlers take a JSON import but no directory, so this writes the module * that imports each file: * * pnpm -s kit write src/kits.ts and assets/kit-pictures/ * pnpm -s kit --check fail when src/kits.ts differs or the pictures folder * is missing or stale * * WHERE THE PICTURES LIVE. A tool's fan tile names kit pictures (`fan_tile`, * its stock and its pictograms, each `pictures/<sha256>.png` in the tool's * folder): the object serves each by its reference (`photo:<sha256>`, * src/media.ts) from the Worker's static assets (wrangler.jsonc `assets`, * binding ASSETS), never from its bundle. This copies them to * apps/business/assets/kit-pictures/<sha256>.png, a GENERATED folder that is * gitignored: the Worker tests write it as their config loads * (vitest.config.ts) and `pnpm worker:deploy` writes it before wrangler. A * changed pictogram is a new picture and a new manifest: this, then a deploy, * and a signed-in phone draws it with no new build. * * Run it after `pnpm personal-tables` or any change to a kit's files. */import { createHash } from"node:crypto";import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from"node:fs";import { dirname, join, resolve } from"node:path";import { fileURLToPath } from"node:url";const here = dirname(fileURLToPath(import.meta.url));const KITS = resolve(here, "../../../crates/cotton-core/kits");const OUT = join(here, "../src/kits.ts");/** The generated folder of kit pictures the Worker serves as static assets (gitignored). */exportconst PICTURES_DIR = join(here, "../assets/kit-pictures");const FROM = "../../../crates/cotton-core/kits";interfaceKitJson { id: string; name: string; format_version?: number; instructions?: string; tables: string[]; tools: string[]; boards: string[];/** What a first pull carries first, per table (src/first.ts). */ first?: Record<string, unknown>;}const read = (path: string): KitJson => JSON.parse(readFileSync(path, "utf8")) asKitJson;/** Where an entry of `kit`'s list lives: its own, or `<other kit>/<id>`. */function home(kit: string, entry: string): { kit: string; id: string } {const at = entry.indexOf("/");return at < 0 ? { kit, id: entry } : { kit: entry.slice(0, at), id: entry.slice(at + 1) };}function file(path: string): string {if (!existsSync(join(KITS, path))) thrownewError(`a kit lists ${path}, which crates/cotton-core/kits does not hold`);return path;}/** Every kit read from crates/cotton-core/kits: src/kits.ts's text and the fan tile pictures by hash. */exportfunction collect(): { kits: string[]; files: number; module: string; pictures: Map<string, Buffer> } {const kits = readdirSync(KITS, { withFileTypes: true }) .filter((d) => d.isDirectory() && existsSync(join(KITS, d.name, "kit.json"))) .map((d) => d.name) .sort();const imports: string[] = [];/** Every fan tile picture a kit's tool names, by its hash: the file's bytes. */const tilePictures = newMap<string, Buffer>();/** The photos a tool's fan tile names, each read from the tool's own `pictures/` and held to its hash. */function tileOf(toolDir: string): void {const manifest = JSON.parse(readFileSync(join(KITS, toolDir, "manifest.json"), "utf8")) as { fan_tile?: Record<string, unknown> };const tile = manifest.fan_tile;if (!tile) return;const photos: string[] = [];const add = (photo: unknown) => {const ref = (photo as { photo?: unknown } | undefined)?.photo;if (typeof ref === "string") photos.push(ref); }; add(tile.stock);for (const part of ["pictures", "views", "acts", "doors"]) for (const photo ofObject.values((tile[part] asRecord<string, unknown> | undefined) ?? {})) add(photo);for (const ref of photos) {const sha = /^photo:([0-9a-f]{64})$/.exec(ref)?.[1];if (!sha) thrownewError(`kits/${toolDir}: its fan tile names ${ref}, which is no kit picture`);if (tilePictures.has(sha)) continue;const bytes = readFileSync(join(KITS, file(`${toolDir}/pictures/${sha}.png`)));if (createHash("sha256").update(bytes).digest("hex") !== sha) thrownewError(`kits/${toolDir}/pictures/${sha}.png is not the picture its name says`); tilePictures.set(sha, bytes); } }const entries: string[] = [];const bound = newMap<string, string>();/** The module binding for a file under kits/, imported once however many kits list it. */const bind = (path: string): string => {let name = bound.get(path);if (!name) { name = `d${bound.size}`; bound.set(path, name); imports.push(`import ${name} from "${FROM}/${path}";`); }return name; };for (const id of kits) {const kit = read(join(KITS, id, "kit.json"));if (kit.id !== id) thrownewError(`kits/${id}/kit.json names ${kit.id}`);const self = bind(`${id}/kit.json`);// The kit's tables in id order, as the object is made holding them.const tables = kit.tables .map((t) => home(id, t)) .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) .map((t) => bind(file(`${t.kit}/tables/${t.id}.json`)));const tools = kit.tools.map((t) => home(id, t)).map((t) => { tileOf(`${t.kit}/tools/${t.id}`);return bind(file(`${t.kit}/tools/${t.id}/manifest.json`)); });const boards = kit.boards.map((b) => home(id, b)).map((b) => bind(file(`${b.kit}/boards/${b.id}.json`)));// A kit.json carrying a tool's format is a tool of its own: the object's map// of its tables (personal), served with the keys a tool file keeps.let own = "[]";if (kit.format_version !== undefined) {if (kit.tables.some((t) => t.includes("/"))) thrownewError(`kits/${id}: a kit that is its own tool lists only its own tables`); own = `[{ format_version: ${self}.format_version, id: ${self}.id, name: ${self}.name, tables: ${self}.tables, instructions: ${self}.instructions }]`; } entries.push(` ${JSON.stringify(id)}: { id: ${self}.id, name: ${self}.name, own: ${own}, tools: [${tools.join(", ")}], tables: [${tables.join(", ")}], boards: [${boards.join(", ")}], first: ${kit.first ? `${self}.first` : "{}"} },`, ); }const module = ["// Written by scripts/kit.ts (pnpm -s kit); do not edit.","/** Every kit as the repository ships it (crates/cotton-core/kits/<app>/): what an object is made from. */", ...imports,"","type Doc = Record<string, unknown>;","","/** A kit as the Worker holds it: its own tool (when its kit.json is one), its tools, its tables in id order and its boards. */","export interface ShippedKit {"," id: string;"," name: string;"," own: Doc[];"," tools: Doc[];"," tables: Doc[];"," boards: Doc[];"," /** What a first pull carries first, per table (src/first.ts). */"," first: Record<string, unknown>;","}","","/** Every kit, by id. */","export const KITS: Record<string, ShippedKit> = {", ...entries,"};","","/** The personal kit: what a new number's object is made from and every personal object is kept to. */",'export const PERSONAL: ShippedKit = KITS["personal"]!;',"", ].join("\n");return { kits, files: bound.size, module, pictures: tilePictures };}/** Lays the pictures folder to exactly the kits' set: each `<sha256>.png`, and nothing else. */exportfunction writePictures(pictures: Map<string, Buffer> = collect().pictures): void { mkdirSync(PICTURES_DIR, { recursive: true });for (const name of readdirSync(PICTURES_DIR)) if (!pictures.has(name.replace(/\.png$/, "")) || !name.endsWith(".png")) rmSync(join(PICTURES_DIR, name), { recursive: true });for (const [sha, bytes] of pictures) {const path = join(PICTURES_DIR, `${sha}.png`);if (!existsSync(path) || !readFileSync(path).equals(bytes)) writeFileSync(path, bytes); }}/** Why the pictures folder is not the kits' set (missing, an extra, a missing or a changed file), or null when it is. */exportfunction picturesStale(pictures: Map<string, Buffer>): string | null {if (!existsSync(PICTURES_DIR)) return"assets/kit-pictures/ is missing";const held = readdirSync(PICTURES_DIR).sort();const want = [...pictures.keys()].sort().map((sha) => `${sha}.png`);if (held.join() !== want.join()) return`assets/kit-pictures/ holds ${held.length} files, the kits name ${want.length} pictures`;for (const name of held) {const sha = createHash("sha256").update(readFileSync(join(PICTURES_DIR, name))).digest("hex");if (`${sha}.png` !== name) return`assets/kit-pictures/${name} is not the picture its name says`; }returnnull;}function main(): void {const { kits, files, module, pictures } = collect();if (process.argv.includes("--check")) {let held = "";try { held = readFileSync(OUT, "utf8"); } catch {// absent: differs }const stale = held !== module ? "src/kits.ts is stale" : picturesStale(pictures);if (stale) { console.error(`${stale}: run pnpm -s kit`); process.exit(1); } } else { writeFileSync(OUT, module); writePictures(pictures); console.log(`src/kits.ts: ${kits.length} kits (${kits.join(", ")}), ${files} files; assets/kit-pictures/: ${pictures.size} tile pictures`); }}if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();