commit aad26e6376302f43224a8009f9ee5c14c4e1f6a0
parent efd657eabdc650ec88efdc35ff7ab1bab448ffa7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 19:36:17 -0500
sites: pnpm ops create-site — the New site form over HTTP, and update as the site page's Save
On 9 Nov an agent had to call writeSite from a tsx script to make a site.
create-site builds the FormData the site form posts (sites/lib/siteFormData.ts:
siteToFormData, applySiteFields) and saves it through saveSiteAction, so the
form's validation and sentences. A create is private and unlisted unless
asked; an existing id is refused (409) unless "update": true, which lays the
given keys over the stored site's form and keeps every other key. Unknown
channels, keys and wrong types are refused before anything is written. The
stored site -> FormData -> action round trip is pinned. COMMANDS.md
regenerated; OPERATING.md "Add a channel" names create-site and channel-rank.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
8 files changed, 593 insertions(+), 0 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -125,6 +125,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` |
| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": <n> (a rank already held, and every rank below it, shift down one) or null (unranked), "top": true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked channel). Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` |
| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "<regex with named groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` |
+| `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept. An unknown channel is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` |
| `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` |
| `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` |
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -61,6 +61,12 @@ pnpm ops get channel example
- `"fetchPlaylist": true` on `create-channel` stores the playlist at once (the form's "Fetch playlist now"); a social channel's is `"fetchPostsNow": true`.
- Rename or delete: `pnpm ops rename-channel --json '{"slug":"old","newSlug":"new"}'`,
`pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` — both refused while the channel is busy.
+- A site for it: `pnpm ops create-site --json '{"siteId":"example","siteTitle":"Examplealyzer","channels":["example"]}'`
+ — the New site form, private and unlisted unless `"audience": "public"` / `"listed": true`. An existing id is
+ refused; `"update": true` is the site page's Save with the keys given changed, every other key kept.
+- Its place in the queue: `pnpm ops channel-rank --json '{"slug":"example","top":true}'` (or `"bottom"`,
+ `"before"`/`"after": "<slug>"`, `"rank": <n>`, `"rank": null`) — the rank alone; /channels' "Add to top" also
+ sets the tier to normal and turns the download lane on.
## Archive a new creator end to end, without interruptions
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, unknown keys and keys of the wrong type are refused before anything is written. It answers the saved site.
- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: if the rank is already taken, that channel and every one below it shift down one. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
- **Configure's Caption languages field (`subLangs`) is checked when you save.** Before, any text was saved, and a value yt-dlp's `--sub-langs` cannot use failed every caption download on the channel at the moment it ran. Configure and `pnpm ops channel-config` (`patch.subLangs`) now refuse it, in the field's words, with what you typed kept. Refused: an empty entry (two commas, or one at an end), a space inside an entry, a bare `-`, an entry that is not a regular expression, or a value over 200 characters. Spaces around an entry are dropped (`en.* , es` saves as `en.*,es`). `all` and `-<lang>` exclusions are accepted as before (`common/lib/channelConfig.ts` `subLangsProblem`).
- **Transcribe refuses a video that is live.** On 4 Nov a transcribe-one on a live YouTube video downloaded the stream at 1x and held `platform:youtube` for the stream's whole length. Now the video page's Transcribe and `pnpm ops transcribe-one` refuse a video whose `metadata.info.json` says it is live (`is_live`), scheduled (`is_upcoming`) or still processing its VOD (`post_live`), before anything is queued. The refusal names `pnpm ops record-live` for the stream (not for `post_live`), says to wait for the VOD otherwise, and names `refresh-metadata` to re-read the record once the stream has ended. The job checks again just before its download, in case the record was re-read while it waited. A video whose audio or container is already on disk still transcribes, since nothing is downloaded. A finished stream (`was_live`) downloads as before (`common/lib/liveNow.ts`).
diff --git a/editor/app/api/ops/create-site/route.test.ts b/editor/app/api/ops/create-site/route.test.ts
@@ -0,0 +1,189 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { setupOpsCorpus, callPost } from "../_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/create-site/route.test.ts"
+//
+// `create-site`: the New site form over HTTP, saved by the form's own action
+// (saveSiteAction -> writeSite) — and "update": the site page's Save with the
+// given keys changed. The action does not revalidate, so its writes are
+// tested here, against a temp corpus.
+
+const corpus = await setupOpsCorpus(null);
+for (const slug of ["pooled", "critic", "other"]) {
+ await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` });
+}
+await corpus.writeSite("neighbour", {});
+const { POST } = await import("./route");
+const { getSite, writeSite } = await import("yt-dlp-transcript-common/lib/site");
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { siteToFormData } = await import("../../../sites/lib/siteFormData");
+const { saveSiteAction } = await import("../../../sites/actions");
+test.after(() => corpus.cleanup());
+
+const siteFile = async (id: string) =>
+ JSON.parse(await readFile(path.join(corpus.transcripts, "sites", id, "site.json"), "utf8")) as Record<
+ string,
+ unknown
+ >;
+
+test("a create is private and unlisted by default, its header the title, through the form's writer", async () => {
+ const r = await callPost(POST, { siteId: "efapalyzer", siteTitle: "Efapalyzer", channels: ["pooled"] });
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ assert.equal(r.body.created, true);
+ const file = await siteFile("efapalyzer");
+ assert.equal(file.siteTitle, "Efapalyzer");
+ assert.equal(file.headerTitle, "Efapalyzer");
+ assert.equal(file.audience, "private");
+ assert.equal(file.listed, false);
+ assert.deepEqual(file.channels, [{ slug: "pooled", order: 0 }]);
+ assert.equal("publish" in file, false, "publish off");
+ assert.equal("search" in file, false, "search on (absent)");
+ assert.deepEqual((r.body.site as { siteId: string }).siteId, "efapalyzer");
+
+ // Public, listed, grouped, cited, with a policy: every key the form's.
+ const pub = await callPost(POST, {
+ siteId: "shown",
+ siteTitle: "Shownalyzer",
+ headerTitle: "Shownalyzer",
+ wordmarkLead: "Shown",
+ audience: "public",
+ listed: true,
+ accent: "#cc3366",
+ cloudflareProject: "shown-pages",
+ siteUrl: "https://shown.example/",
+ publishAuto: "production",
+ groups: [
+ { id: "main", name: "Main", selectedByDefault: true },
+ { id: "extra", name: "Extra" },
+ ],
+ defaultGroupId: "main",
+ channels: [{ slug: "pooled", groupId: "extra" }],
+ citedChannels: ["critic", "pooled"],
+ archiveMaxMB: 24,
+ });
+ assert.equal(pub.status, 200, JSON.stringify(pub.body));
+ const s = await siteFile("shown");
+ assert.equal("audience" in s, false, "public is the absent default");
+ assert.equal("listed" in s, false, "listed is the absent default");
+ assert.equal(s.accent, "#cc3366");
+ assert.equal(s.siteUrl, "https://shown.example");
+ assert.deepEqual(s.publish, { auto: "production" });
+ assert.deepEqual(s.channels, [{ slug: "pooled", groupId: "extra", order: 0 }]);
+ assert.deepEqual(s.citedChannels, [{ slug: "critic" }], "a pooled slug is dropped from the cited scope");
+ assert.equal(s.archiveMaxBytes, 24 * 1024 * 1024);
+ assert.equal(s.wordmarkLead, "Shown");
+});
+
+test("an existing id is refused unless update; update keeps every key it does not name", async () => {
+ const before = await siteFile("shown");
+ const again = await callPost(POST, { siteId: "shown", siteTitle: "Other" });
+ assert.equal(again.status, 409);
+ assert.match(String(again.body.error), /Site "shown" already exists\. "update": true saves the keys given over it/);
+ assert.deepEqual(await siteFile("shown"), before, "nothing written");
+
+ const up = await callPost(POST, { siteId: "shown", update: true, homeTagline: "Every stream, searchable" });
+ assert.equal(up.status, 200, JSON.stringify(up.body));
+ assert.equal(up.body.created, false);
+ assert.deepEqual(await siteFile("shown"), { ...before, homeTagline: "Every stream, searchable" });
+
+ const none = await callPost(POST, { siteId: "nosuch", update: true, siteTitle: "X" });
+ assert.equal(none.status, 404);
+ assert.match(String(none.body.error), /Site "nosuch" not found — leave out "update" to create it/);
+});
+
+test("the form's refusals, and the door's, before anything is written", async () => {
+ for (const [body, status, re] of [
+ [{ siteId: "Bad Id", siteTitle: "X" }, 400, /not a valid site id/],
+ [{ siteId: "new", siteTitle: "X" }, 400, /new/],
+ [{ siteId: "untitled" }, 400, /a new site needs a "siteTitle"/],
+ [{ siteId: "blank", siteTitle: " " }, 400, /Site title is required/],
+ [{ siteId: "lead", siteTitle: "Leadalyzer", wordmarkLead: "lead" }, 400, /Wordmark lead must be how the header title starts/],
+ [{ siteId: "url", siteTitle: "U", siteUrl: "shown.example" }, 400, /Public URL must be an absolute http\(s\):\/\/ URL/],
+ [{ siteId: "aud", siteTitle: "A", audience: "friends" }, 400, /Unknown audience "friends"/],
+ [{ siteId: "pol", siteTitle: "P", audience: "public", publishAuto: "production" }, 400, /cloudflareProject/],
+ [{ siteId: "acc", siteTitle: "A", accent: "chartreuse" }, 400, /Unknown brand accent "chartreuse"/],
+ [{ siteId: "grp", siteTitle: "G", groups: [] }, 400, /At least one channel group is required/],
+ [{ siteId: "grp2", siteTitle: "G", groups: [{ name: "No id" }] }, 400, /"groups"\[0\] is not a channel group/],
+ [{ siteId: "ch", siteTitle: "C", channels: ["pooled", "ghost"] }, 400, /not a channel: "ghost"/],
+ [{ siteId: "cit", siteTitle: "C", citedChannels: ["ghost"] }, 400, /not a channel: "ghost"/],
+ [{ siteId: "typ", siteTitle: "T", listed: "yes" }, 400, /"listed" must be a boolean/],
+ [{ siteId: "typ2", siteTitle: "T", archiveMaxMB: "12" }, 400, /"archiveMaxMB" must be a number/],
+ [{ siteId: "unk", siteTitle: "U", pages: ["a"] }, 400, /pages/],
+ ] as const) {
+ const r = await callPost(POST, body);
+ assert.equal(r.status, status, JSON.stringify(body) + " " + JSON.stringify(r.body));
+ assert.match(String(r.body.error), re, JSON.stringify(r.body));
+ const id = (body as { siteId: string }).siteId;
+ if (id !== "new" && /^[a-z0-9-]+$/.test(id)) {
+ await assert.rejects(readFile(path.join(corpus.transcripts, "sites", id, "site.json")), `${id}: nothing written`);
+ }
+ }
+});
+
+// The round trip "update" rests on: a stored site, made into the form it would
+// post untouched, saved by the form's action, is the same site.json.
+test("siteToFormData -> saveSiteAction gives a full site back unchanged", async () => {
+ const paths = getPaths();
+ await writeSite(
+ {
+ siteId: "full",
+ siteTitle: "Fullalyzer",
+ siteDescription: "Everything set",
+ headerTitle: "Fullalyzer",
+ wordmarkLead: "Full",
+ homeTagline: "All of it",
+ socialLinks: [{ label: "Site", url: "https://full.example", svg: '<svg viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>' }],
+ groups: [
+ { id: "main", name: "Main", selectedByDefault: true, order: 0, description: "The main ones" },
+ { id: "side", name: "Side", selectedByDefault: false, order: 1, inline: true },
+ ],
+ defaultGroupId: "side",
+ channels: [
+ { slug: "pooled", groupId: "main", order: 0 },
+ { slug: "other", order: 1 },
+ ],
+ citedChannels: [{ slug: "critic" }],
+ cloudflareProject: "full-pages",
+ accent: "brass",
+ siteUrl: "https://full.example",
+ pages: ["intro"],
+ relatedSites: [{ label: "Friends", siteIds: ["neighbour"] }],
+ search: false,
+ pwa: true,
+ archives: false,
+ duplicates: false,
+ transcriptDownloads: false,
+ archiveMaxBytes: 12_345_678,
+ hubUrl: "https://hub.example",
+ publish: { auto: "preview" },
+ },
+ paths,
+ );
+ const before = await siteFile("full");
+ const r = await saveSiteAction(undefined, siteToFormData(getSite("full", paths)));
+ assert.equal(r.ok, true, JSON.stringify(r));
+ assert.deepEqual(await siteFile("full"), before);
+ // And a private, inheriting, default-accent one.
+ await writeSite(
+ {
+ siteId: "plain",
+ siteTitle: "Plain",
+ siteDescription: "",
+ headerTitle: "Plain",
+ homeTagline: "",
+ groups: [{ id: "default", name: "All", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [],
+ audience: "private",
+ listed: false,
+ },
+ paths,
+ );
+ const plain = await siteFile("plain");
+ assert.equal((await saveSiteAction(undefined, siteToFormData(getSite("plain", paths)))).ok, true);
+ assert.deepEqual(await siteFile("plain"), plain);
+});
diff --git a/editor/app/api/ops/create-site/route.ts b/editor/app/api/ops/create-site/route.ts
@@ -0,0 +1,134 @@
+import { existsSync } from "node:fs";
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ getSite,
+ isValidSiteId,
+ siteConfigFile,
+ type Site,
+} from "yt-dlp-transcript-common/lib/site";
+import {
+ DEFAULT_GROUP_FALLBACK_ID,
+ FALLBACK_GROUP,
+} from "yt-dlp-transcript-common/lib/channelGroups";
+import { channelExists, isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { saveSiteAction } from "../../../sites/actions";
+import {
+ SITE_OPS_FIELDS,
+ SiteFieldError,
+ applySiteFields,
+ readChannels,
+ siteToFormData,
+} from "../../../sites/lib/siteFormData";
+import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { siteId, siteTitle, …the site form's fields…, update? }
+// -> { ok, siteId, created, site }
+//
+// THE NEW SITE FORM, OVER HTTP (lane editor-gaps; 9 Nov an agent had to call
+// writeSite from a tsx script to make a site). The body's keys are the form's
+// fields (app/sites/lib/siteFormData.ts SITE_OPS_FIELDS), built into the
+// FormData the form posts and saved by the form's own action — saveSiteAction,
+// so writeSite — with its validation and its sentences: a bad site id or a
+// reserved one, no title, a wordmark lead that is not how the header starts,
+// a URL that is not absolute, an unknown accent, audience or publish policy, a
+// group list with none, a deploying policy with no Pages project.
+//
+// A CREATE IS PRIVATE AND UNLISTED unless the body says otherwise ("audience":
+// "public", "listed": true) — the form defaults the other way because a
+// person at it is building a public site; a script making one is usually
+// making a reading copy. "headerTitle" defaults to "siteTitle". Every other
+// key is the form's default: one inline group, no channels, search, archives,
+// duplicates and transcript downloads on, publish off.
+//
+// AN EXISTING ID IS REFUSED (409) unless "update": true, which is the site
+// page's Save with the given keys changed: the stored site is the form, the
+// body's keys are laid over it, every key not named stays (the published page
+// list is the Reports tab's and is always kept). "update" on a site that does
+// not exist is a 404.
+//
+// Refused before anything is written, beside the action's own refusals: an
+// unknown key, a key of the wrong type, a channel (or cited channel) that does
+// not exist.
+export async function POST(request: Request) {
+ return ops(request, ["siteId", "update", ...SITE_OPS_FIELDS], async (body) => {
+ const siteId = reqString(body, "siteId").trim();
+ if (!isValidSiteId(siteId)) {
+ throw new OpsInputError(`"${siteId}" is not a valid site id (lowercase letters, numbers and hyphens)`);
+ }
+ const update = optBool(body, "update") === true;
+ const paths = getPaths();
+ const exists = existsSync(siteConfigFile(paths, siteId));
+ if (exists && !update) {
+ return opsFail(
+ `Site "${siteId}" already exists. "update": true saves the keys given over it, as its form's Save does ` +
+ `(site-config sets its cited channels and publish policy alone).`,
+ 409,
+ );
+ }
+ if (!exists && update) {
+ return opsFail(`Site "${siteId}" not found — leave out "update" to create it`, 404);
+ }
+ if (!update && typeof body.siteTitle !== "string") {
+ throw new OpsInputError('a new site needs a "siteTitle"');
+ }
+ await refuseUnknownChannels(body);
+
+ const fields: Record<string, unknown> = {};
+ for (const key of SITE_OPS_FIELDS) if (body[key] !== undefined) fields[key] = body[key];
+ if (!update && fields.headerTitle === undefined) fields.headerTitle = fields.siteTitle;
+ const fd = siteToFormData(update ? getSite(siteId, paths) : blankSite(siteId));
+ try {
+ applySiteFields(fd, fields);
+ } catch (e) {
+ if (e instanceof SiteFieldError) throw new OpsInputError(e.message);
+ throw e;
+ }
+ const saved = await saveSiteAction(undefined, fd);
+ if (!saved.ok) return opsFail(saved.error);
+ return NextResponse.json({ ok: true, siteId, created: !update, site: getSite(siteId, paths) });
+ });
+}
+
+// What /sites/new starts from, private and unlisted.
+function blankSite(siteId: string): Site {
+ return {
+ siteId,
+ siteTitle: "",
+ siteDescription: "",
+ headerTitle: "",
+ homeTagline: "",
+ groups: [{ ...FALLBACK_GROUP }],
+ defaultGroupId: DEFAULT_GROUP_FALLBACK_ID,
+ channels: [],
+ audience: "private",
+ listed: false,
+ };
+}
+
+// The form offers only channels that exist; a slug here is checked the same.
+async function refuseUnknownChannels(body: Record<string, unknown>): Promise<void> {
+ const slugs: string[] = [];
+ try {
+ if (body.channels !== undefined) slugs.push(...readChannels(body.channels).map((c) => c.slug));
+ } catch (e) {
+ if (e instanceof SiteFieldError) throw new OpsInputError(e.message);
+ throw e;
+ }
+ if (Array.isArray(body.citedChannels)) {
+ slugs.push(...body.citedChannels.filter((s): s is string => typeof s === "string").map((s) => s.trim()));
+ }
+ const paths = getPaths();
+ const missing: string[] = [];
+ for (const slug of new Set(slugs)) {
+ if (!isValidChannelSlug(slug)) {
+ throw new OpsInputError(`"${slug}" is not a valid channel slug`);
+ }
+ if (!(await channelExists(paths, slug))) missing.push(slug);
+ }
+ if (missing.length > 0) {
+ throw new OpsInputError(`not a channel: ${missing.map((s) => `"${s}"`).join(", ")}`);
+ }
+}
diff --git a/editor/app/sites/lib/siteFormData.ts b/editor/app/sites/lib/siteFormData.ts
@@ -0,0 +1,208 @@
+// THE SITE FORM'S FIELDS, BUILT WITHOUT A BROWSER — for `pnpm ops create-site`.
+//
+// The site form posts a FormData that saveSiteAction rebuilds the whole Site
+// from (a key it does not post is dropped on save). So an ops caller goes
+// through the same action with the same FormData: `siteToFormData` is the form
+// a site would post if nothing in it were touched (what SiteForm seeds from),
+// and `applySiteFields` lays the caller's keys over it. A create starts from a
+// blank site, an update from the stored one — "update" is the site page's Save
+// with those fields changed, and every key not named stays as it was.
+//
+// Pure: no fs, no server. The round trip (stored site -> FormData -> action ->
+// the same site.json) is pinned in app/api/ops/create-site/route.test.ts.
+
+import { isAccentId } from "yt-dlp-transcript-common/lib/brand";
+import { parseChannelGroup } from "yt-dlp-transcript-common/lib/channelGroups";
+import type { Site } from "yt-dlp-transcript-common/lib/site";
+import { CITED_CHANNELS_FIELD } from "./citedChannelsFromForm";
+
+const MB = 1024 * 1024;
+
+const on = (fd: FormData, key: string, value: boolean) => {
+ if (value) fd.set(key, "on");
+ else fd.delete(key);
+};
+
+export function siteToFormData(site: Site): FormData {
+ const fd = new FormData();
+ fd.set("siteId", site.siteId);
+ fd.set("siteTitle", site.siteTitle);
+ fd.set("headerTitle", site.headerTitle);
+ fd.set("wordmarkLead", site.wordmarkLead ?? "");
+ fd.set("siteDescription", site.siteDescription);
+ fd.set("homeTagline", site.homeTagline);
+ setAccent(fd, site.accent);
+ fd.set("cloudflareProject", site.cloudflareProject ?? "");
+ fd.set("siteUrl", site.siteUrl ?? "");
+ fd.set("audience", site.audience === "private" ? "private" : "public");
+ fd.set("publishAuto", site.publish?.auto ?? "off");
+ // The opt-out checkboxes: absent / true = ticked.
+ on(fd, "search", site.search !== false);
+ on(fd, "listed", site.listed !== false);
+ on(fd, "archives", site.archives !== false);
+ on(fd, "duplicates", site.duplicates !== false);
+ on(fd, "transcriptDownloads", site.transcriptDownloads !== false);
+ on(fd, "pwa", site.pwa === true);
+ fd.set("hubUrl", site.hubUrl ?? "");
+ // bytes / 2^20 is exact in binary and String() round-trips, so the action's
+ // floor(MB * 2^20) gives the stored bytes back.
+ fd.set("archiveMaxMB", site.archiveMaxBytes !== undefined ? String(site.archiveMaxBytes / MB) : "");
+ setSocialLinks(fd, site.socialLinks);
+ fd.set("groupsJson", JSON.stringify(site.groups));
+ fd.set("defaultGroupId", site.defaultGroupId);
+ fd.set("channelsJson", JSON.stringify(site.channels));
+ fd.set(CITED_CHANNELS_FIELD, JSON.stringify((site.citedChannels ?? []).map((c) => c.slug)));
+ fd.set("relatedSitesJson", JSON.stringify(site.relatedSites ?? []));
+ return fd;
+}
+
+function setAccent(fd: FormData, accent: string | undefined) {
+ // Absent = the default accent (the radio group's first choice reads the same).
+ if (!accent || isAccentId(accent)) {
+ fd.set("accent", accent ?? "");
+ fd.delete("accentCustom");
+ return;
+ }
+ fd.set("accent", "custom");
+ fd.set("accentCustom", accent);
+}
+
+function setSocialLinks(fd: FormData, links: unknown[] | undefined | null) {
+ if (links === undefined || links === null) {
+ fd.set("inheritSocialLinks", "on");
+ fd.delete("socialLinksJson");
+ return;
+ }
+ fd.delete("inheritSocialLinks");
+ fd.set("socialLinksJson", JSON.stringify(links));
+}
+
+// The keys `create-site` takes beyond `siteId` and `update`, each the form
+// field of the same meaning.
+export const SITE_OPS_FIELDS = [
+ "siteTitle",
+ "headerTitle",
+ "siteDescription",
+ "homeTagline",
+ "wordmarkLead",
+ "accent",
+ "cloudflareProject",
+ "siteUrl",
+ "hubUrl",
+ "audience",
+ "publishAuto",
+ "listed",
+ "search",
+ "archives",
+ "duplicates",
+ "transcriptDownloads",
+ "pwa",
+ "archiveMaxMB",
+ "groups",
+ "defaultGroupId",
+ "channels",
+ "citedChannels",
+ "socialLinks",
+ "relatedSites",
+] as const;
+
+const STRING_FIELDS = new Set([
+ "siteTitle",
+ "headerTitle",
+ "siteDescription",
+ "homeTagline",
+ "wordmarkLead",
+ "cloudflareProject",
+ "siteUrl",
+ "hubUrl",
+ "audience",
+ "publishAuto",
+ "defaultGroupId",
+]);
+const BOOL_FIELDS = new Set(["listed", "search", "archives", "duplicates", "transcriptDownloads", "pwa"]);
+
+// A key of the wrong shape, in the caller's words. The VALUES are the action's
+// to judge (its sentences: an unknown audience, a bad URL, a group list with
+// none) — only what cannot be turned into a form field is refused here.
+export class SiteFieldError extends Error {}
+
+export function applySiteFields(fd: FormData, fields: Record<string, unknown>): void {
+ for (const [key, v] of Object.entries(fields)) {
+ if (v === undefined) continue;
+ if (STRING_FIELDS.has(key)) {
+ if (typeof v !== "string") throw new SiteFieldError(`"${key}" must be a string`);
+ fd.set(key, v);
+ } else if (BOOL_FIELDS.has(key)) {
+ if (typeof v !== "boolean") throw new SiteFieldError(`"${key}" must be a boolean`);
+ on(fd, key, v);
+ } else if (key === "accent") {
+ if (typeof v !== "string") throw new SiteFieldError(`"accent" must be a string (an accent id or "#rrggbb")`);
+ // A hex is the form's "custom"; anything else is the radio's id, for the
+ // action to accept or refuse by name.
+ const a = v.trim();
+ if (/^#?[0-9a-f]{6}$/i.test(a)) setAccent(fd, a);
+ else {
+ fd.set("accent", a);
+ fd.delete("accentCustom");
+ }
+ } else if (key === "archiveMaxMB") {
+ if (v !== null && (typeof v !== "number" || !Number.isFinite(v))) {
+ throw new SiteFieldError(`"archiveMaxMB" must be a number of MB, or null for the global default`);
+ }
+ fd.set("archiveMaxMB", v === null ? "" : String(v));
+ } else if (key === "groups") {
+ if (!Array.isArray(v)) throw new SiteFieldError(`"groups" must be an array of {id, name, …}`);
+ // The parser drops a group it cannot read, which on a form is a row the
+ // operator can see; over ops it would vanish without a word.
+ const bad = v.findIndex((g) => parseChannelGroup(g) === null);
+ if (bad >= 0) {
+ throw new SiteFieldError(
+ `"groups"[${bad}] is not a channel group: it needs an "id" (lowercase letters, digits, hyphens) and a "name"`,
+ );
+ }
+ fd.set("groupsJson", JSON.stringify(v.map((g, order) => (isObject(g) ? { order, ...g } : g))));
+ } else if (key === "channels") {
+ fd.set("channelsJson", JSON.stringify(readChannels(v)));
+ } else if (key === "citedChannels") {
+ if (!Array.isArray(v) || v.some((s) => typeof s !== "string")) {
+ throw new SiteFieldError(`"citedChannels" must be an array of channel slugs`);
+ }
+ fd.set(CITED_CHANNELS_FIELD, JSON.stringify(v));
+ } else if (key === "socialLinks") {
+ if (v !== null && !Array.isArray(v)) {
+ throw new SiteFieldError(`"socialLinks" must be an array of {label, url, svg}, or null to inherit the global default`);
+ }
+ setSocialLinks(fd, v as unknown[] | null);
+ } else if (key === "relatedSites") {
+ if (!Array.isArray(v)) throw new SiteFieldError(`"relatedSites" must be an array of {label?, siteIds}`);
+ fd.set("relatedSitesJson", JSON.stringify(v));
+ } else {
+ throw new SiteFieldError(`unknown site field "${key}"`);
+ }
+ }
+}
+
+// `channels`: slugs, or {slug, groupId?} — the pool, in the order given.
+export function readChannels(v: unknown): { slug: string; groupId?: string; order: number }[] {
+ if (!Array.isArray(v)) {
+ throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`);
+ }
+ return v.map((entry, order) => {
+ if (typeof entry === "string") return { slug: entry.trim(), order };
+ if (isObject(entry) && typeof entry.slug === "string") {
+ if (entry.groupId !== undefined && typeof entry.groupId !== "string") {
+ throw new SiteFieldError(`"channels": the groupId of "${entry.slug}" must be a string`);
+ }
+ return {
+ slug: entry.slug.trim(),
+ ...(typeof entry.groupId === "string" && entry.groupId.trim() ? { groupId: entry.groupId.trim() } : {}),
+ order,
+ };
+ }
+ throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`);
+ });
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts
@@ -340,6 +340,39 @@ test("channel-priority sets and ends the focus", async ({ request }) => {
await expect.poll(async () => (await focusOf())?.kind ?? "none").toBe("none");
});
+// create-site (lane editor-gaps): the New site form over HTTP — the form's
+// action, so the site the /sites list shows; an existing id refused unless
+// "update", which keeps every key it does not name.
+test("create-site makes a private, unlisted site the /sites list shows; update changes only what it names", async ({
+ request,
+ page,
+}) => {
+ await resetData("one-youtube-channel-with-data");
+ await settings();
+ const made = await ops(request, "create-site", {
+ siteId: "opsalyzer",
+ siteTitle: "Opsalyzer",
+ channels: ["test-youtube"],
+ });
+ expect(made.status, JSON.stringify(made.body)).toBe(200);
+ type SiteFile = { siteTitle: string; homeTagline: string; audience?: string; listed?: boolean; channels: { slug: string }[] };
+ const file = `${testPaths().transcriptsDir}/sites/opsalyzer/site.json`;
+ const site = await readJson<SiteFile>(file);
+ expect(site).toMatchObject({ siteTitle: "Opsalyzer", audience: "private", listed: false });
+ expect(site.channels.map((c) => c.slug)).toEqual(["test-youtube"]);
+
+ await page.goto("/sites");
+ await expect(page.getByRole("link", { name: /Opsalyzer/ })).toBeVisible();
+
+ const again = await ops(request, "create-site", { siteId: "opsalyzer", siteTitle: "Other" });
+ expect(again.status).toBe(409);
+ expect(again.body.error).toMatch(/already exists/);
+
+ const up = await ops(request, "create-site", { siteId: "opsalyzer", update: true, homeTagline: "Searchable" });
+ expect(up.status, JSON.stringify(up.body)).toBe(200);
+ expect(await readJson<SiteFile>(file)).toEqual({ ...site, homeTagline: "Searchable" });
+});
+
// channel-rank (lane editor-gaps): one channel moved in the order through the
// deck's one writer — the rank alone; the tier and the lanes untouched, and
// the four lane roots recompiled in the same write.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -75,6 +75,8 @@
// pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'
// pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'
// pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'
+// pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'
+// pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'
// pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'
// pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'
// pnpm ops articles-config --json '{"id":"demo-article","published":true}'
@@ -380,6 +382,10 @@ const ACTIONS = [
// | top | bottom | before | after), through the deck's one writer.
"channel-rank",
"channel-config",
+ // The New site form ({siteId, siteTitle, …its fields}), or the site page's
+ // Save with some keys changed ({siteId, update: true, …}), through the
+ // form's own action. Synchronous; no job.
+ "create-site",
// A site's cited-only channels and its publish policy ({siteId,
// citedChannels?, publishAuto?}), through the site form's own writer.
"site-config",
@@ -1427,6 +1433,21 @@ export function usage() {
' download-missing leave the channel alone; "" (or "auto") is automatic',
' (CHANNEL.md, downloadMode).',
"",
+ 'create-site is the New site form: {"siteId", "siteTitle"} and any of its',
+ ' fields — "headerTitle" (default the title), "siteDescription",',
+ ' "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl",',
+ ' "cloudflareProject", "hubUrl", "audience" ("private" | "public"; default',
+ ' PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives",',
+ ' "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the',
+ ' global default), "groups" ([{"id", "name", "selectedByDefault"?,',
+ ' "description"?, "inline"?}]), "defaultGroupId", "channels" (slugs, or',
+ ' {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks"',
+ ' ([{"label", "url", "svg"}], null = inherit), "relatedSites". Saved by',
+ ' the form\'s action (its validation, its sentences). An existing id is',
+ ' refused (409) unless "update": true — the site page\'s Save with the',
+ ' keys given changed, every other key kept. An unknown channel is refused.',
+ ' Answers {siteId, created, site}.',
+ "",
'site-config sets two keys of a site as its form does: {"siteId"} and any of',
' "citedChannels" (the WHOLE cited scope, channel slugs: what the site\'s',
' reports may cite without publishing the channel; [] clears it; a slug the',