Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 299f95183b275faa5ebc1b6d49cf19eabcb4970b
parent fec54f9b501306c7774d01fb7263464ba7e97958
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 19:26:35 -0500

umtool: the inspector's routes -- provenance, title, teaser, ledger, embed-ids, still-frame, post-item/inspector (redesign L6)

Each a thin door over the shared writer (the CLI's checks word for word), the manifest's token, a 409 on a
stale one, one undo point per write. /api/report/ledger is new (GET the schema's vocabulary and the rows,
POST add|set|rm). A recording chosen from disk keeps its extension in post-narration's multipart upload.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/embed-ids/route.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/ledger/route.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/post-item/inspector/route.ts | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/post-narration/route.ts | 4+++-
Aumtool/app/api/report/provenance/route.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/still-frame/route.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/teaser/route.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/report/title/route.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 519 insertions(+), 1 deletion(-)

diff --git a/umtool/app/api/report/embed-ids/route.ts b/umtool/app/api/report/embed-ids/route.ts @@ -0,0 +1,57 @@ +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken } from "@/lib/report/manifest.mjs"; +import { embedIdFixes, embedIdRows } from "@/lib/report/embedIds.mjs"; +import { setSiteVideos } from "@/lib/report/inspectorEdits.mjs"; +import { readLinkCheck } from "@/lib/report/linkCheck.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// THE PUBLISHED EMBED ID (umtool redesign L6, the Links panel's "Use the published embed id"; 4 and 8 Nov: a +// Rumble clip's QR named the URL-slug folder the corpus keeps it under, and the archive serves the EMBED id): +// every clip of the cut citing such a folder, its embed id read from the folder's metadata.info.json through L1's +// one mapping (shareLine.mjs siteVideoFor), with what the last link check (out/links.json) said of its QR. The +// fix writes `siteVideo` (and a citeUrl that named the folder) -- one write, one undo point. No network: the +// check is `umtool links <p>`'s; `umtool links <p> --embed-ids` is this route's twin. +// +// GET ?project=<id> { rows: [{ clip, channel, video, siteVideo, url, fixedUrl, citeUrl, state }], checkedAt, token } +// POST { project, token, clips?: [id…] } those rows fixed (no clips: every row) +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const doc = await readLinkCheck(r.project.dir); + const rows = await embedIdRows(r.project.dir, r.manifest as Record<string, unknown>, { doc }); + return Response.json({ rows, checkedAt: doc?.checkedAt ?? null, token: await manifestToken(r.project.dir) }, { headers: noStore }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/embed-ids"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const clips = Array.isArray(body.clips) ? body.clips.map(String) : null; + try { + const { result, editNotes } = await withEditNotes(r.project, async () => { + // The rows as the manifest is NOW (read inside the request, the writer checks the token). + const m = (await readManifest(r.project.dir)) as Record<string, unknown>; + const rows = await embedIdRows(r.project.dir, m, { doc: await readLinkCheck(r.project.dir) }); + return setSiteVideos(r.project.dir, embedIdFixes(rows, clips), { token: typeof body.token === "string" ? body.token : null }); + }); + return Response.json({ ok: true, fixed: result.fixed, token: result.token, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/ledger/route.ts b/umtool/app/api/report/ledger/route.ts @@ -0,0 +1,105 @@ +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, addLedgerRow, manifestToken, removeLedgerRow, updateLedgerRow } from "@/lib/report/manifest.mjs"; +import { isMeasureLedger, parseLedgerValue } from "@/lib/report/ledgerRows.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { EVENTS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureSchema } from "umtool-report-to-video/ledger-totals"; + +export const dynamic = "force-dynamic"; + +// A MEASURE LEDGER's ROWS (umtool redesign L6, the inspector's Ledger panel; weight video rev 9): the rows the +// instruments draw from (`manifest.ledger`, read by the build through ledgerSchema), added, changed and removed +// through the manifest's own writers -- addLedgerRow / updateLedgerRow / removeLedgerRow, each row checked by +// ledgerRows.mjs ledgerRowOf against the schema (the CLI's checks, word for word), one undo point each. +// `umtool ledger <p> add|set|rm` is the same writer. +// +// GET ?project=<id>[&entry=<timeline id>] the schema's vocabulary (tracks, forms, regimes, declared fields, +// events, the six adjudication words), the rows (those pinned to the +// entry when one is named), the token +// POST { project, token, op: "add", row } a new row (its id in it) +// POST { project, token, op: "set", id, patch, unset?: [key…] } a row changed +// POST { project, token, op: "rm", id } a row removed (refused while anything names it) +// A string value is read as the CLI reads a flag's text (ledgerRows.mjs parseLedgerValue: a number key a +// number, true/false, "a|b" a list for flags, "null" clears). +const noStore = { "cache-control": "no-store" }; +type Row = Record<string, unknown> & { id?: string; entryId?: string }; + +const parsed = (patch: unknown) => { + const out: Record<string, unknown> = {}; + if (!patch || typeof patch !== "object" || Array.isArray(patch)) return out; + for (const [k, v] of Object.entries(patch as Record<string, unknown>)) out[k] = typeof v === "string" ? parseLedgerValue(k, v) : v; + return out; +}; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { ledgerSchema?: Record<string, unknown>; ledger?: Row[] }; + const rows = Array.isArray(m.ledger) ? m.ledger : []; + const entry = url.searchParams.get("entry"); + let schema = null; + let schemaError = null; + if (isMeasureLedger(m)) { + try { + const s = measureSchema(m.ledgerSchema); + schema = { + unit: (m.ledgerSchema?.unit as string | undefined) ?? "", + tracks: s.tracks.map((t: { key: string; label: string; role: string; regimes: string[] | null }) => ({ key: t.key, label: t.label, role: t.role, regimes: t.regimes })), + forms: s.forms, + regimes: s.regimes.map((x: { key: string; label: string }) => ({ key: x.key, label: x.label })), + fields: s.fields.map((f: { key: string; label?: string; kind?: string; options?: unknown }) => ({ key: f.key, label: f.label ?? f.key, kind: f.kind ?? "text", options: Array.isArray(f.options) ? f.options : null })), + events: EVENTS, promiseForms: PROMISE_FORMS, outcomes: PROMISE_OUTCOMES, scopeConfidence: SCOPE_CONFIDENCE, valueKinds: VALUE_KINDS, + }; + } catch (e) { + schemaError = e instanceof Error ? e.message : String(e); + } + } + return Response.json( + { + kind: isMeasureLedger(m) ? "measure" : rows.length || m.ledgerSchema ? "headcount" : null, + schema, + schemaError, + total: rows.length, + rows: entry ? rows.filter((x) => x?.entryId === entry) : rows, + entries: ((r.manifest as { timeline?: { id?: string; type?: string }[] }).timeline ?? []).map((e) => String(e?.id ?? "")).filter(Boolean), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/ledger"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const token = typeof body.token === "string" ? body.token : null; + const id = String(body.id ?? ""); + try { + if (body.op === "add") { + const row = parsed(body.row); + const { result, editNotes } = await withEditNotes(r.project, () => addLedgerRow(r.project.dir, row, { token })); + return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "set") { + const unset = Array.isArray(body.unset) ? body.unset.map(String) : []; + const { result, editNotes } = await withEditNotes(r.project, () => updateLedgerRow(r.project.dir, id, parsed(body.patch), { token, unset })); + return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "rm") { + const { result, editNotes } = await withEditNotes(r.project, () => removeLedgerRow(r.project.dir, id, { token })); + return Response.json({ ok: true, removed: result.row?.id ?? id, token: result.token, editNotes }, { headers: noStore }); + } + return Response.json({ error: "op is add, set or rm" }, { status: 400 }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/post-item/inspector/route.ts b/umtool/app/api/report/post-item/inspector/route.ts @@ -0,0 +1,107 @@ +import { readdir, stat } from "node:fs/promises"; +import path from "node:path"; +import { cardText, excerptErrors, excerptRanges, excerptSpansOf } from "umtool-report-to-video/post-item"; +import { pickedTake } from "umtool-report-to-video/post-narration"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs"; +import { attachmentOf } from "@/lib/report/postsCli.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// A POST ITEM, AS THE INSPECTOR EDITS IT (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item +// excerpt=…` and `posts narrate --recording` by hand): the card's words as the excerpt reads them (cardText), +// the excerpt's spans and where they stand, the item's attachments and the post's files it does not carry, and +// its narration's takes. Its writes are the post bench's: POST /api/report/post-item {op: "set"} (the excerpt, +// an attachment off or its sound), the multipart POST /api/report/post-narration (a recording), and here: +// +// GET ?project=<id>&id=<item> the view above, and the token +// POST { project, token, id, op: "media-on", file: "posts-media/…" } a file of the post put back on the item, +// measured as `posts set-item media.add=` measures one +const noStore = { "cache-control": "no-store" }; +const MEDIA_RE = /\.(png|jpe?g|webp|gif|mp4|m4v|mov|webm)$/i; +type Entry = Record<string, unknown> & { id: string; type?: string; post?: string; media?: Array<Record<string, unknown>>; narration?: Record<string, unknown> }; + +/** The post's own files in the project (posts-media/<channel>/<postId>/), pictures and videos, its screenshots left out. */ +async function postFiles(dir: string, e: Entry): Promise<string[]> { + const roots = new Set<string>(); + if (typeof e.post === "string" && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(e.post)) roots.add(`posts-media/${e.post}`); + for (const m of e.media ?? []) if (typeof m?.src === "string" && m.src.startsWith("posts-media/")) roots.add(path.posix.dirname(m.src)); + const out: string[] = []; + for (const rel of roots) { + if (rel.split("/").includes("..")) continue; + const names = await readdir(path.join(dir, ...rel.split("/"))).catch(() => [] as string[]); + for (const n of names.sort()) { + if (!MEDIA_RE.test(n) || /^shot/i.test(n) || n.startsWith(".")) continue; + const st = await stat(path.join(dir, ...rel.split("/"), n)).catch(() => null); + if (st?.isFile()) out.push(`${rel}/${n}`); + } + } + return out; +} + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const r = await resolveReport(q.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[]; + const id = q.get("id") ?? ""; + const e = tl.find((x) => x?.type === "post" && x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const text = cardText(e) as string; + const spans = excerptSpansOf(e) as string[] | null; + const media = (e.media ?? []).map((m, i) => ({ + i, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null, + mute: m?.mute === true, seconds: typeof m?.seconds === "number" ? m.seconds : null, audio: m?.audio === true, + })); + const carried = new Set(media.map((m) => m.src)); + const takes = Array.isArray(e.narration?.takes) ? (e.narration.takes as Array<Record<string, unknown>>) : []; + const picked = pickedTake(e) as (Record<string, unknown> & { file: string; index: number }) | null; + return Response.json( + { + id: e.id, post: e.post ?? null, author: e.author ?? null, handle: e.handle ?? null, text, + excerpt: spans, ranges: spans ? excerptRanges(text, spans) : null, excerptErrors: excerptErrors(e), + media, files: (await postFiles(r.project.dir, e)).filter((f) => !carried.has(f)), + narration: { + takes: takes.map((t, i) => ({ i, file: String(t.file ?? ""), engine: typeof t.engine === "string" ? t.engine : null, voice: typeof t.voice === "string" ? t.voice : null, seconds: typeof t.seconds === "number" ? t.seconds : null })), + picked: picked ? picked.index : null, + off: e.narration?.off === true, + }, + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/post-item/inspector"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + if (body.op !== "media-on") return Response.json({ error: "op is media-on" }, { status: 400 }); + const id = String(body.id ?? ""); + const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[]; + const e = tl.find((x) => x?.type === "post" && x.id === id); + if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 }); + const file = String(body.file ?? ""); + // Only one of the post's own files (the list GET gives): never a path from elsewhere in the project. + if (!(await postFiles(r.project.dir, e)).includes(file)) return Response.json({ error: `${file} is not one of ${id}'s post files` }, { status: 400 }); + try { + const att = await attachmentOf(r.project.dir, file); + const { result, editNotes } = await withEditNotes(r.project, () => + updatePostItem(r.project.dir, id, { mediaAdd: [att] }, { token: typeof body.token === "string" ? body.token : null }), + ); + return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } catch (e2) { + if (e2 instanceof StaleToken) return Response.json({ error: e2.message, stale: true }, { status: 409 }); + if (e2 instanceof StructureRefused) return Response.json({ error: e2.message, errors: e2.errors }, { status: 400 }); + return Response.json({ error: e2 instanceof Error ? e2.message : String(e2) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts @@ -354,7 +354,9 @@ async function record(request: Request) { const parts = []; for (const [k, b] of blobs.entries()) { if (b.size > 200 * 1024 * 1024) return Response.json({ error: "a part is larger than 200 MB" }, { status: 413 }); - const f = path.join(up, `p${k + 1}.${/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm"}`); + // A file chosen from disk (the inspector's "Use my recording") keeps its own extension; a browser recording its type's. + const own = /\.(wav|mp3|m4a|aac|ogg|opus|flac|webm|mp4|mov)$/i.exec(typeof b.name === "string" ? b.name : "")?.[1]?.toLowerCase(); + const f = path.join(up, `p${k + 1}.${own ?? (/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm")}`); await writeFile(f, new Uint8Array(await b.arrayBuffer())); parts.push({ file: f, text: texts[k] ?? "", para: Number.isInteger(paras[k]) ? paras[k] : k }); } diff --git a/umtool/app/api/report/provenance/route.ts b/umtool/app/api/report/provenance/route.ts @@ -0,0 +1,68 @@ +import { readdir } from "node:fs/promises"; +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { provenanceView, updateProvenance } from "@/lib/report/inspectorEdits.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; +import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs"; +import { CHANNELS_DIR, SITES_DIR } from "@/lib/paths.mjs"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT'S PROVENANCE (umtool redesign L6, the inspector's Provenance panel; `umtool provenance` is the +// same writer): provenance.siteOrigin, channelSlug and channel -- the keys agents set by hand this week (a +// `umtool new` with no --from leaves channelSlug empty, and `check` blocks on it). The link policy beside them +// is /api/report/link-policy's. +// +// GET ?project=<id> the three keys, the link policy, the cut's channels (with their clip counts) and the +// corpus's, the sites (SITES_DIR, each with a siteUrl), the token +// PUT { project, token, patch: { siteOrigin?, channelSlug?, channel? } } set them ("" or null removes one) +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { provenance?: Record<string, unknown>; timeline?: { type?: string; channel?: string }[] }; + const counts = new Map<string, number>(); + for (const e of m.timeline ?? []) if (e?.type === "clip" && typeof e.channel === "string" && e.channel) counts.set(e.channel, (counts.get(e.channel) ?? 0) + 1); + const corpus = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR, { withFileTypes: true }).then( + (d) => d.filter((x) => x.isDirectory() && !x.name.startsWith(".")).map((x) => x.name).sort().slice(0, 4000), + () => [] as string[], + ); + return Response.json( + { + provenance: provenanceView(m), + linkPolicy: m.provenance?.linkPolicy ?? null, + channels: [...counts].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)), + corpusChannels: corpus, + sites: [...sitesByOrigin(SITES_DIR)].map(([origin, s]) => ({ origin, siteId: s.siteId, title: s.title })), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/provenance"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const { result, editNotes } = await withEditNotes(r.project, () => + updateProvenance(r.project.dir, (body.patch ?? {}) as Record<string, unknown>, { token: typeof body.token === "string" ? body.token : null }), + ); + invalidateProjects(); + return Response.json({ ok: true, ...result, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/still-frame/route.ts b/umtool/app/api/report/still-frame/route.ts @@ -0,0 +1,55 @@ +import { readFile, stat } from "node:fs/promises"; +import { resolveClip, resolveReport } from "@/lib/report/serve.mjs"; +import { StillRefused, grabStill, listShots, shotFileOf } from "@/lib/report/stillGrab.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// A STILL AT SECOND N (umtool redesign L6: Play's Still button; `umtool still` is the twin): one frame of the +// clip on screen at the playhead's SOURCE second, grabbed from its fetched window (lib/report/stillGrab.mjs: a +// single `ffmpeg -ss -frames:v 1`, not heavy work) into the project's shots/ beside its other shots -- where a +// clip's fx.zoom / fx.receipts read pictures from. Nothing is fetched, and nothing in the cut is written. +// +// GET ?project=<id> { shots: [{ rel, name, bytes, mtime, still: { clip, at } | null }] } +// GET ?project=<id>&file=shots/<name> the picture +// POST { project, clip, at, take? } grab it -> { rel, clip, video, at, bytes } +const noStore = { "cache-control": "no-store" }; +const TYPES: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const file = url.searchParams.get("file"); + if (file) { + const abs = shotFileOf(r.project.dir, file); + if (!abs) return new Response("not a picture in shots/", { status: 404 }); + const st = await stat(abs).catch(() => null); + if (!st?.isFile()) return new Response("gone", { status: 404 }); + const ext = abs.slice(abs.lastIndexOf(".")).toLowerCase(); + return new Response(new Uint8Array(await readFile(abs)), { headers: { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": "no-cache" } }); + } + return Response.json({ shots: await listShots(r.project.dir) }, { headers: noStore }); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/still-frame"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const take = typeof body.take === "string" && body.take ? body.take : null; + const r = await resolveClip(String(body.project ?? ""), String(body.clip ?? ""), { take }); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + try { + const done = await grabStill(r.project, r.manifest, r.clip.id, Number(body.at)); + const { file: _abs, ...rest } = done; + return Response.json({ ok: true, ...rest }, { headers: noStore }); + } catch (e) { + if (e instanceof StillRefused) return Response.json({ error: e.message }, { status: e.status }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 }); + } +} diff --git a/umtool/app/api/report/teaser/route.ts b/umtool/app/api/report/teaser/route.ts @@ -0,0 +1,69 @@ +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, updateTeaser } from "@/lib/report/manifest.mjs"; +import { insertTeaser, teaserLimits, teaserLineOf } from "@/lib/report/inspectorEdits.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// A TEASER OR CLOSING CARD (umtool redesign L6, the inspector's Insert a card): a `type: "teaser"` entry -- its +// lines (the first its title; each with a break and a hold), its beat -- inserted at the start, the end, or +// beside an entry, or an existing one's lines and beat changed. Checked by the build's validateTeaser; one write, +// one undo point each. `umtool timeline <p> teaser-insert` / `timeline <p> teaser <id> <patch>` are the twins. +// +// GET ?project=<id> the cut's entries (id, type, a label) for the position, +// its teasers as written, the limits, the token +// POST { project, token, op: "insert", spec: { id?, lines, beat? }, position: "start" | "end" | { after } | { before } } +// POST { project, token, op: "set", id, patch: { lines?, beat? } } +const noStore = { "cache-control": "no-store" }; +type Entry = { id?: string; type?: string; heading?: string; title?: string; label?: string; lines?: unknown[]; beat?: number; video?: string }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const tl = (Array.isArray((r.manifest as { timeline?: unknown }).timeline) ? (r.manifest as { timeline: Entry[] }).timeline : []) as Entry[]; + return Response.json( + { + entries: tl.map((e, at) => ({ id: String(e?.id ?? ""), type: String(e?.type ?? "?"), at, label: e?.heading ?? e?.title ?? e?.label ?? e?.video ?? null })), + teasers: tl.flatMap((e, at) => (e?.type === "teaser" ? [{ id: String(e.id), at, lines: e.lines ?? [], beat: typeof e.beat === "number" ? e.beat : null }] : [])), + limits: teaserLimits(), + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/teaser"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const token = typeof body.token === "string" ? body.token : null; + try { + if (body.op === "insert") { + const { result, editNotes } = await withEditNotes(r.project, () => insertTeaser(r.project.dir, (body.spec ?? {}) as Record<string, unknown>, body.position ?? "end", { token })); + invalidateProjects(); + return Response.json({ ok: true, id: result.id, at: result.at, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } + if (body.op === "set") { + const patch = { ...((body.patch ?? {}) as Record<string, unknown>) }; + // The lines as the insert writes them: a line that is only its words is a string, empty keys left out. + if (Array.isArray(patch.lines)) patch.lines = patch.lines.map((l: unknown) => teaserLineOf(l)); + const { result, editNotes } = await withEditNotes(r.project, () => updateTeaser(r.project.dir, String(body.id ?? ""), patch, { token })); + return Response.json({ ok: true, id: result.id, entry: result.entry, token: result.token, editNotes }, { headers: noStore }); + } + return Response.json({ error: "op is insert or set" }, { status: 400 }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +} diff --git a/umtool/app/api/report/title/route.ts b/umtool/app/api/report/title/route.ts @@ -0,0 +1,55 @@ +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; +import { SUBTITLE_MAX, TITLE_MAX, updateTitle } from "@/lib/report/inspectorEdits.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; + +export const dynamic = "force-dynamic"; + +// THE PROJECT'S TITLE AND SUBTITLE (umtool redesign L6, item 7; 9 Nov: four news projects' were set with jq): +// the manifest's `title` and `subtitle`. `umtool title <p> "<title>" [--subtitle "…"]` is the same writer. +// +// GET ?project=<id> { title, subtitle, limits, token } +// PUT { project, token, title?, subtitle? } set them (subtitle "" or null removes it); one undo point +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const r = await resolveReport(url.searchParams.get("project") ?? ""); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const m = r.manifest as { title?: unknown; subtitle?: unknown }; + return Response.json( + { + title: typeof m.title === "string" ? m.title : null, + subtitle: typeof m.subtitle === "string" ? m.subtitle : null, + limits: { title: TITLE_MAX, subtitle: SUBTITLE_MAX }, + token: await manifestToken(r.project.dir), + }, + { headers: noStore }, + ); +} + +export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/title"); + if (refused) return refused; + let body: Record<string, unknown>; + try { + body = await request.json(); + } catch { + return Response.json({ error: "expected JSON" }, { status: 400 }); + } + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const patch: Record<string, unknown> = {}; + if ("title" in body) patch.title = body.title; + if ("subtitle" in body) patch.subtitle = body.subtitle; + try { + const { result, editNotes } = await withEditNotes(r.project, () => updateTitle(r.project.dir, patch, { token: typeof body.token === "string" ? body.token : null })); + invalidateProjects(); + return Response.json({ ok: true, ...result, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } +}