@pramen/cms 0.0.61 → 0.0.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -50,7 +50,7 @@ import {
50
50
  resolveSecret,
51
51
  authorizeHandler,
52
52
  } from "@pramen/server";
53
- import type { HandlerContext, Policy, FileRef, BootstrapFn, JsonValue, SchemaDef, FieldDef, FieldType } from "@pramen/server";
53
+ import type { HandlerContext, Policy, FileRef, BootstrapFn, DataMigration, MigrationContext, JsonValue, SchemaDef, FieldDef, FieldType, WhereClause } from "@pramen/server";
54
54
  import type { EnvBag } from "@pramen/server";
55
55
  import { isSafeHref, normalizeHref } from "./href";
56
56
  import { NAV_ORDER } from "./nav";
@@ -1023,6 +1023,18 @@ export const cmsSchema = {
1023
1023
  // Hierarchical vocabularies allow `parentId` on their terms; flat ones reject it on
1024
1024
  // write. Enforced in the handler, not the schema — one term table serves both.
1025
1025
  hierarchical: defaultTo(t.bool(), false),
1026
+ // What this vocabulary classifies — a subset of `TAXONOMY_TARGETS`. NULL means EVERYTHING,
1027
+ // which is both the backward-compatible reading for rows written before this column and a
1028
+ // legitimate authored value ("Topics classifies whatever there is"). Without it a site with
1029
+ // "Categories" for articles and tags for images offers both on both, so a photo can be
1030
+ // filed under "Local news" and `getTermTree("category")` fills up with terms like "hero"
1031
+ // that no page listing will ever use.
1032
+ //
1033
+ // A `t.json()` array rather than two booleans: the set of things a CMS classifies grows
1034
+ // (collections are the obvious next one), and a column per target would need a migration
1035
+ // each time. It is not queryable — JSON in a TEXT cell — but nothing pages by taxonomy:
1036
+ // `listTaxonomies` reads them all and narrows in memory.
1037
+ appliesTo: t.json(),
1026
1038
  createdAt: defaultTo(t.text(), expr.now()),
1027
1039
  })),
1028
1040
 
@@ -1045,6 +1057,7 @@ export const cmsSchema = {
1045
1057
  taxonomy: r.belongsTo("cms_taxonomies", "taxonomyId", { onDelete: "cascade" }),
1046
1058
  parent: r.belongsTo("cms_terms", "parentId", { onDelete: "setNull" }),
1047
1059
  pages: r.hasMany("cms_page_terms", "termId"),
1060
+ media: r.hasMany("cms_media_terms", "termId"),
1048
1061
  }),
1049
1062
  // A slug identifies a term WITHIN its vocabulary — `/category/news` and `/tag/news`
1050
1063
  // are two different terms, and both are legitimate.
@@ -1069,6 +1082,28 @@ export const cmsSchema = {
1069
1082
  { unique: [["pageId", "termId"]] },
1070
1083
  ),
1071
1084
 
1085
+ // The same junction for media. A SECOND table rather than one polymorphic
1086
+ // `cms_object_terms(objectType, objectId, termId)`: a polymorphic key cannot carry a real
1087
+ // foreign key, and the FKs are what does the work here — purging a media row or deleting a
1088
+ // term takes its assignments with it, with no handler remembering to. A `where` traversal
1089
+ // also needs a typed column to join on; `objectId` would have to be filtered by a
1090
+ // discriminator the read engine has no way to require, so one forgotten `objectType`
1091
+ // clause silently mixes a page's tags into a media query.
1092
+ cms_media_terms: Entity(
1093
+ (t) => ({
1094
+ id: primaryKey(generated(t.uuid())),
1095
+ mediaId: indexed(notNull(t.uuid())),
1096
+ termId: indexed(notNull(t.uuid())),
1097
+ }),
1098
+ (r) => ({
1099
+ // `cascade` on both ends, as on the page junction. Note this fires on PURGE, not on
1100
+ // trashing: `deleteMedia` only stamps `deletedAt`, so a restored file keeps its tags.
1101
+ media: r.belongsTo("cms_media", "mediaId", { onDelete: "cascade" }),
1102
+ term: r.belongsTo("cms_terms", "termId", { onDelete: "cascade" }),
1103
+ }),
1104
+ { unique: [["mediaId", "termId"]] },
1105
+ ),
1106
+
1072
1107
  // A named template region an admin fills without touching code — the sidebar, the footer
1073
1108
  // column, the pre-footer strip.
1074
1109
  //
@@ -1092,17 +1127,178 @@ export const cmsSchema = {
1092
1127
 
1093
1128
  // Media: a fileRef column holds only R2 metadata; bytes live in R2, uploaded via
1094
1129
  // ctx.files + the Worker /files/* route. Block `fields` reference a media id.
1095
- cms_media: Entity((t) => ({
1096
- id: primaryKey(generated(t.uuid())),
1097
- file: t.fileRef(),
1098
- alt: t.text(),
1099
- // Soft delete, as on cms_pages. The R2 OBJECT is deliberately kept while a media row
1100
- // is trasheddeleting the bytes would make restore a lie. `purgeMedia` drops both.
1101
- deletedAt: indexed(t.text()),
1102
- createdAt: defaultTo(t.text(), expr.now()),
1103
- })),
1130
+ cms_media: Entity(
1131
+ (t) => ({
1132
+ id: primaryKey(generated(t.uuid())),
1133
+ file: t.fileRef(),
1134
+ // The three fields the library SORTS and FILTERS by, projected out of `file` into real
1135
+ // columns. `file` is a `t.fileRef()` JSON in a TEXT cell so its `filename`,
1136
+ // `contentType` and `size` are invisible to `orderBy` and `where`, and sorting a library
1137
+ // after the page has been fetched sorts one page, which is not sorting.
1138
+ //
1139
+ // A duplicate, deliberately, and the cost is named: they are written where a media row is
1140
+ // CREATED and nowhere else (`updateMedia` never touches the file), so there is one writer
1141
+ // and `file` stays the source of truth for serving. SQLite generated columns would remove
1142
+ // the duplication outright — `GENERATED ALWAYS AS (json_extract(file,'$.filename'))` — but
1143
+ // the schema DSL has no way to declare one, and `generated()` here means something else
1144
+ // entirely (auto-mint a uuid on insert).
1145
+ //
1146
+ // Nullable, so adding them is a plain `ADD COLUMN` on an existing store rather than a
1147
+ // gated table rebuild; `cmsMigrations` backfills what is already there.
1148
+ filename: indexed(t.text()),
1149
+ contentType: indexed(t.text()),
1150
+ size: t.int(),
1151
+ alt: t.text(),
1152
+ // Soft delete, as on cms_pages. The R2 OBJECT is deliberately kept while a media row
1153
+ // is trashed — deleting the bytes would make restore a lie. `purgeMedia` drops both.
1154
+ deletedAt: indexed(t.text()),
1155
+ createdAt: defaultTo(t.text(), expr.now()),
1156
+ }),
1157
+ (r) => ({
1158
+ // Media is classified by the SAME vocabularies pages are, through the same `cms_terms`
1159
+ // table — a deployment that declares "Topics" gets to tag a photo with one without
1160
+ // declaring it twice, and the terms screen stays the one place a vocabulary is edited.
1161
+ //
1162
+ // The traversal is what makes tagging worth having: `where: { terms: { id } }` compiles
1163
+ // to a subquery through the junction, so the library filters by term IN SQL like it
1164
+ // filters by kind. A tag you cannot filter a paged library by is decoration.
1165
+ terms: r.manyToMany("cms_terms", { through: "cms_media_terms", sourceColumn: "mediaId", targetColumn: "termId" }),
1166
+ }),
1167
+ ),
1104
1168
  };
1105
1169
 
1170
+ // --- media: what the library may be sorted and filtered by ---------------------------------
1171
+ //
1172
+ // A CLOSED vocabulary on the server, not a column name and a direction from the client. The
1173
+ // two inputs compile straight into `ORDER BY` and `WHERE`, so letting a caller name the column
1174
+ // would hand it the ability to order by — and therefore probe — any column on the table,
1175
+ // `alt` and `deletedAt` included. Six sorts and five kinds is what the screen offers.
1176
+
1177
+ /** How a media list may be ordered. */
1178
+ export type MediaSort = "newest" | "oldest" | "name" | "name_desc" | "largest" | "smallest";
1179
+
1180
+ /** …resolved to the order the read engine takes. `createdAt` is ISO-8601 TEXT (`expr.now()`),
1181
+ * so a lexicographic sort on it IS chronological. */
1182
+ const MEDIA_SORTS: Record<MediaSort, { column: string; dir: "asc" | "desc" }> = {
1183
+ newest: { column: "createdAt", dir: "desc" },
1184
+ oldest: { column: "createdAt", dir: "asc" },
1185
+ name: { column: "filename", dir: "asc" },
1186
+ name_desc: { column: "filename", dir: "desc" },
1187
+ largest: { column: "size", dir: "desc" },
1188
+ smallest: { column: "size", dir: "asc" },
1189
+ };
1190
+
1191
+ /** The coarse type buckets the library filters by — the first segment of a MIME type, which
1192
+ * is the distinction someone browsing a library actually makes ("show me the images"). */
1193
+ export const MEDIA_KINDS = ["image", "video", "audio", "document", "other"] as const;
1194
+ export type MediaKind = (typeof MEDIA_KINDS)[number];
1195
+
1196
+ /** MIME prefixes for the buckets that have one. `document` is a LIST rather than a prefix
1197
+ * because the useful documents share no MIME family — a PDF is `application/pdf` and a Word
1198
+ * file is `application/vnd.openxmlformats-…`. */
1199
+ const DOCUMENT_PREFIXES = ["application/pdf", "text/", "application/msword", "application/vnd."] as const;
1200
+
1201
+ /** Trim and cap a search needle. Capped because it lands in a `LIKE` pattern: the engine
1202
+ * escapes `%` and `_` for us, so this is not an injection guard — it is a bound on work a
1203
+ * caller can ask the database to do per row. */
1204
+ function mediaQuery(raw: unknown): string | undefined {
1205
+ const q = typeof raw === "string" ? raw.trim().slice(0, 120) : "";
1206
+ return q === "" ? undefined : q;
1207
+ }
1208
+
1209
+ /** Match a needle against the two fields that NAME a file: what it was uploaded as, and what
1210
+ * an editor wrote about it. `alt` is included because it is the only human description a
1211
+ * media row carries, and searching a library for "logo" should find the file somebody
1212
+ * described as a logo even when the upload was called `IMG_2831.png`. */
1213
+ function mediaSearchWhere(q: string): WhereClause<typeof cmsSchema, "cms_media"> {
1214
+ return { OR: [{ filename: { contains: q } }, { alt: { contains: q } }] };
1215
+ }
1216
+
1217
+ /** The `where` clause for one bucket, or `undefined` for "everything".
1218
+ *
1219
+ * `other` is the interesting one: it is defined as NOT any of the buckets that have a
1220
+ * definition, so a file type nobody anticipated still has exactly one home rather than
1221
+ * disappearing from every filter. A row whose `contentType` is NULL — uploaded before the
1222
+ * projection columns existed and never backfilled — lands there too, which is the honest
1223
+ * place for it.
1224
+ *
1225
+ * That NULL case needs its OWN clause, and did not have one. SQL is three-valued: against a
1226
+ * NULL column every `LIKE` is NULL, so the `OR` is NULL and `NOT NULL` is NULL — which is not
1227
+ * TRUE, so the row is excluded. `other` therefore matched everything except the rows it
1228
+ * documents as belonging there, and a legacy row was invisible under ALL FIVE chips, with only
1229
+ * "clear the filter" to find it and nothing on screen saying why. Exactly the deployment that
1230
+ * upgraded and did not spread `cmsMigrations`. */
1231
+ function mediaKindWhere(kind: MediaKind | undefined): WhereClause<typeof cmsSchema, "cms_media"> | undefined {
1232
+ if (kind === undefined) return undefined;
1233
+ if (kind === "image" || kind === "video" || kind === "audio") return { contentType: { startsWith: `${kind}/` } };
1234
+ const documents = { OR: DOCUMENT_PREFIXES.map((p) => ({ contentType: { startsWith: p } })) };
1235
+ if (kind === "document") return documents;
1236
+ const known = { OR: [{ contentType: { startsWith: "image/" } }, { contentType: { startsWith: "video/" } }, { contentType: { startsWith: "audio/" } }, documents] };
1237
+ return { OR: [{ contentType: { isNull: true } }, { NOT: known }] };
1238
+ }
1239
+
1240
+ // --- taxonomies: what a vocabulary classifies ---------------------------------------------
1241
+
1242
+ /** The object types a vocabulary can be applied to. A CLOSED vocabulary, like `MEDIA_KINDS`:
1243
+ * it decides which panels offer a taxonomy AND which assignments are accepted, so an unknown
1244
+ * value must not be storable. */
1245
+ export const TAXONOMY_TARGETS = ["page", "media"] as const;
1246
+ export type TaxonomyTarget = (typeof TAXONOMY_TARGETS)[number];
1247
+
1248
+ /** Whether a vocabulary applies to `target`.
1249
+ *
1250
+ * The permissive readings all collapse to TRUE, deliberately: NULL (never narrowed, or written
1251
+ * before the column existed), a non-array, an array of things that are not targets. A stored
1252
+ * value nobody can interpret must not silently stop a vocabulary from working — the failure
1253
+ * would be a taxonomy that has quietly vanished from every panel, with the row still there. */
1254
+ export function taxonomyApplies(row: { appliesTo?: unknown }, target: TaxonomyTarget): boolean {
1255
+ const list = row.appliesTo;
1256
+ if (!Array.isArray(list)) return true;
1257
+ const targets = list.filter((v): v is TaxonomyTarget => (TAXONOMY_TARGETS as readonly unknown[]).includes(v));
1258
+ return targets.length === 0 || targets.includes(target);
1259
+ }
1260
+
1261
+ /** Parse an `appliesTo` input. `undefined` stays undefined (the field was not sent); `null`
1262
+ * clears the narrowing back to "everything". An unknown target is a 400 rather than a silent
1263
+ * drop — dropping it would store a NARROWER set than the caller asked for, which is the one
1264
+ * direction that loses assignments. */
1265
+ function parseAppliesTo(raw: unknown): TaxonomyTarget[] | null | undefined {
1266
+ if (raw === undefined) return undefined;
1267
+ if (raw === null) return null;
1268
+ if (!Array.isArray(raw)) throw new BadRequest("appliesTo must be a list or null");
1269
+ const out: TaxonomyTarget[] = [];
1270
+ for (const v of raw) {
1271
+ if (typeof v !== "string" || !(TAXONOMY_TARGETS as readonly string[]).includes(v)) {
1272
+ throw new BadRequest(`appliesTo must contain only ${TAXONOMY_TARGETS.join(", ")}`);
1273
+ }
1274
+ if (!out.includes(v as TaxonomyTarget)) out.push(v as TaxonomyTarget);
1275
+ }
1276
+ // A vocabulary that classifies nothing is not a narrowing, it is a vocabulary nobody can
1277
+ // reach — and it reads identically to NULL in storage, which means the opposite.
1278
+ if (out.length === 0) throw new BadRequest("appliesTo must name at least one of " + TAXONOMY_TARGETS.join(", "));
1279
+ return out;
1280
+ }
1281
+
1282
+ /** Refuse term ids from a vocabulary that does not classify `target`.
1283
+ *
1284
+ * The write side, not just the UI. Hiding a vocabulary from a panel without changing what the
1285
+ * server accepts is the `hideI18n` mistake this package already retired once: the control
1286
+ * disappears, the request does not, and `appliesTo` becomes a hint rather than a rule. It also
1287
+ * has to be here for the assignments the panel never made — a script, a migration, an older
1288
+ * editor build that has not learned the capability.
1289
+ *
1290
+ * Reads the terms' taxonomies through `ctx.db`, so an unreadable vocabulary refuses the
1291
+ * assignment rather than being waved through. */
1292
+ async function assertTermsApplyTo(db: CmsDb, termIds: readonly string[], target: TaxonomyTarget): Promise<void> {
1293
+ if (termIds.length === 0) return;
1294
+ const terms = await db.find({ from: "cms_terms", where: { id: { in: [...termIds] } }, select: ["id", "taxonomyId"], limit: termIds.length });
1295
+ const taxIds = [...new Set(terms.map((t) => String(t.taxonomyId)))];
1296
+ if (taxIds.length === 0) return;
1297
+ const taxa = await db.find({ from: "cms_taxonomies", where: { id: { in: taxIds } }, select: ["id", "slug", "appliesTo"], limit: taxIds.length });
1298
+ const bad = taxa.filter((t) => !taxonomyApplies(t, target));
1299
+ if (bad[0]) throw new BadRequest(`vocabulary '${String(bad[0].slug)}' does not apply to ${target}`);
1300
+ }
1301
+
1106
1302
  /** Block Kit — custom admin pages, described as JSON and rendered by the editor. See
1107
1303
  * `./blockkit`. Re-exported so a host imports `adminPage` beside `collection`. */
1108
1304
  export {
@@ -3103,11 +3299,36 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3103
3299
  // `parentId` on its terms; a flat one refuses it rather than storing something no
3104
3300
  // listing renders.
3105
3301
 
3106
- /** Every vocabulary. PUBLIC like content types, a taxonomy's slug is structural (it
3107
- * is a URL segment) and a front end routes on it. */
3108
- listTaxonomies: query((ctx) => cdb(ctx).find({ from: "cms_taxonomies", orderBy: { column: "label" }, limit: PAGE_LIST_MAX_LIMIT })),
3302
+ /** Every vocabulary, or just the ones that classify `target`. PUBLIC like content
3303
+ * types, a taxonomy's slug is structural (it is a URL segment) and a front end routes on
3304
+ * it.
3305
+ *
3306
+ * Narrowed HERE rather than in each caller, so the page panel, the media panel and the
3307
+ * write-side guard cannot disagree about what a vocabulary applies to. In memory, because
3308
+ * `appliesTo` is a `t.json()` column that `where` cannot see into — which costs nothing:
3309
+ * this handler already reads every taxonomy, and nothing pages by them.
3310
+ *
3311
+ * No `target` means EVERY vocabulary, which is what the Taxonomies screen needs: the one
3312
+ * place that edits `appliesTo` must be able to see a vocabulary it has narrowed away. */
3313
+ listTaxonomies: query(async (ctx, input: { target?: TaxonomyTarget }) => {
3314
+ const rows = await cdb(ctx).find({ from: "cms_taxonomies", orderBy: { column: "label" }, limit: PAGE_LIST_MAX_LIMIT });
3315
+ const target = input?.target;
3316
+ return target === undefined ? rows : rows.filter((r) => taxonomyApplies(r, target));
3317
+ }, {
3318
+ input: (raw): { target?: TaxonomyTarget } => {
3319
+ const t = asObj(raw).target;
3320
+ // Unrecognised narrows to nothing rather than falling back to everything: this one
3321
+ // decides what a panel OFFERS, and answering "all of them" to a question the server
3322
+ // did not understand is how a media panel ends up listing page-only vocabularies.
3323
+ if (t === undefined || t === null) return {};
3324
+ if (typeof t !== "string" || !(TAXONOMY_TARGETS as readonly string[]).includes(t)) {
3325
+ throw new BadRequest(`target must be one of ${TAXONOMY_TARGETS.join(", ")}`);
3326
+ }
3327
+ return { target: t as TaxonomyTarget };
3328
+ },
3329
+ }),
3109
3330
 
3110
- createTaxonomy: mutation(async (ctx, input: { slug: string; label: string; pluralLabel?: string; description?: string; hierarchical?: boolean }) => {
3331
+ createTaxonomy: mutation(async (ctx, input: { slug: string; label: string; pluralLabel?: string; description?: string; hierarchical?: boolean; appliesTo?: TaxonomyTarget[] | null }) => {
3111
3332
  const db = cdb(ctx);
3112
3333
  const clash = await db.find({ from: "cms_taxonomies", where: { slug: input.slug }, select: ["id"], limit: 1 });
3113
3334
  if (clash[0]) throw new Conflict(`taxonomy '${input.slug}' already exists`);
@@ -3117,10 +3338,13 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3117
3338
  pluralLabel: input.pluralLabel ?? null,
3118
3339
  description: input.description ?? null,
3119
3340
  hierarchical: input.hierarchical ?? false,
3341
+ // Unsent means EVERY target, which is what a vocabulary created before this existed
3342
+ // means too — one reading of NULL, so an old row and a new one behave alike.
3343
+ appliesTo: input.appliesTo ?? null,
3120
3344
  });
3121
3345
  }, {
3122
3346
  ...editor,
3123
- input: (raw): { slug: string; label: string; pluralLabel?: string; description?: string; hierarchical?: boolean } => {
3347
+ input: (raw): { slug: string; label: string; pluralLabel?: string; description?: string; hierarchical?: boolean; appliesTo?: TaxonomyTarget[] | null } => {
3124
3348
  const o = asObj(raw);
3125
3349
  return {
3126
3350
  slug: assertKey(o.slug, "taxonomy slug"),
@@ -3128,6 +3352,7 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3128
3352
  pluralLabel: typeof o.pluralLabel === "string" ? o.pluralLabel : undefined,
3129
3353
  description: typeof o.description === "string" ? o.description : undefined,
3130
3354
  hierarchical: typeof o.hierarchical === "boolean" ? o.hierarchical : undefined,
3355
+ appliesTo: parseAppliesTo(o.appliesTo),
3131
3356
  };
3132
3357
  },
3133
3358
  }),
@@ -3137,8 +3362,15 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3137
3362
  *
3138
3363
  * Turning `hierarchical` OFF is refused while any term still has a parent. Allowing it
3139
3364
  * would leave a stored hierarchy that no reader renders and no writer can clear, and
3140
- * flattening the terms silently is a destructive edit behind a checkbox. */
3141
- updateTaxonomy: mutation(async (ctx, input: { id: string; label?: string; pluralLabel?: string | null; description?: string | null; hierarchical?: boolean }) => {
3365
+ * flattening the terms silently is a destructive edit behind a checkbox.
3366
+ *
3367
+ * NARROWING `appliesTo` is refused on exactly the same grounds, and it is the same bug:
3368
+ * dropping a target this vocabulary is already used for would strand those assignments —
3369
+ * still stored, still returned by `listPageTerms`/`listMediaTerms`, but invisible in the
3370
+ * panel that could remove them, because the panel only renders vocabularies that apply.
3371
+ * Unassign them first; then the narrowing is a settings change rather than a silent
3372
+ * orphaning. WIDENING is always fine — it strands nothing. */
3373
+ updateTaxonomy: mutation(async (ctx, input: { id: string; label?: string; pluralLabel?: string | null; description?: string | null; hierarchical?: boolean; appliesTo?: TaxonomyTarget[] | null }) => {
3142
3374
  const db = cdb(ctx);
3143
3375
  const rows = await db.find({ from: "cms_taxonomies", where: { id: input.id }, limit: 1 });
3144
3376
  const row = rows[0];
@@ -3147,21 +3379,33 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3147
3379
  const nested = await db.find({ from: "cms_terms", where: { taxonomyId: input.id, parentId: { isNull: false } }, select: ["id"], limit: 1 });
3148
3380
  if (nested[0]) throw new BadRequest("this vocabulary still has nested terms — move them to the top level before making it flat");
3149
3381
  }
3382
+ if (input.appliesTo !== undefined && input.appliesTo !== null) {
3383
+ const next = input.appliesTo;
3384
+ for (const target of TAXONOMY_TARGETS) {
3385
+ // Only a target this vocabulary applies to TODAY and would not after the patch.
3386
+ if (next.includes(target) || !taxonomyApplies(row, target)) continue;
3387
+ const junction = target === "page" ? "cms_page_terms" : "cms_media_terms";
3388
+ const used = await db.find({ from: junction, where: { term: { taxonomyId: input.id } }, select: ["id"], limit: 1 });
3389
+ if (used[0]) throw new BadRequest(`this vocabulary is still assigned to ${target === "page" ? "pages" : "media"} — remove those assignments before narrowing it`);
3390
+ }
3391
+ }
3150
3392
  const patch: Record<string, unknown> = {};
3151
- for (const k of ["label", "pluralLabel", "description", "hierarchical"] as const) {
3393
+ for (const k of ["label", "pluralLabel", "description", "hierarchical", "appliesTo"] as const) {
3152
3394
  if (input[k] !== undefined) patch[k] = input[k];
3153
3395
  }
3154
3396
  return db.update("cms_taxonomies", input.id, patch);
3155
3397
  }, {
3156
3398
  ...editor,
3157
- input: (raw): { id: string; label?: string; pluralLabel?: string | null; description?: string | null; hierarchical?: boolean } => {
3399
+ input: (raw): { id: string; label?: string; pluralLabel?: string | null; description?: string | null; hierarchical?: boolean; appliesTo?: TaxonomyTarget[] | null } => {
3158
3400
  const o = asObj(raw);
3159
3401
  if (typeof o.id !== "string" || o.id === "") throw new BadRequest("id is required");
3160
- const out: { id: string; label?: string; pluralLabel?: string | null; description?: string | null; hierarchical?: boolean } = { id: o.id };
3402
+ const out: { id: string; label?: string; pluralLabel?: string | null; description?: string | null; hierarchical?: boolean; appliesTo?: TaxonomyTarget[] | null } = { id: o.id };
3161
3403
  if (o.label !== undefined) out.label = assertLabel(o.label, "taxonomy label");
3162
3404
  if (o.pluralLabel !== undefined) out.pluralLabel = typeof o.pluralLabel === "string" ? o.pluralLabel : null;
3163
3405
  if (o.description !== undefined) out.description = typeof o.description === "string" ? o.description : null;
3164
3406
  if (typeof o.hierarchical === "boolean") out.hierarchical = o.hierarchical;
3407
+ const appliesTo = parseAppliesTo(o.appliesTo);
3408
+ if (appliesTo !== undefined) out.appliesTo = appliesTo;
3165
3409
  return out;
3166
3410
  },
3167
3411
  }),
@@ -3330,6 +3574,7 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3330
3574
  // uuid — the FK would catch it, but as a driver error with no HTTP status.
3331
3575
  const found = await db.find({ from: "cms_terms", where: { id: { in: [...wanted] } }, select: ["id"], limit: wanted.size });
3332
3576
  if (found.length !== wanted.size) throw new BadRequest("one or more termIds are not terms");
3577
+ await assertTermsApplyTo(db, [...wanted], "page");
3333
3578
  }
3334
3579
  const existing = await db.find({ from: "cms_page_terms", where: { pageId: input.pageId }, select: ["id", "termId"], limit: MAX_TERMS });
3335
3580
  const have = new Map(existing.map((l) => [String(l.termId), String(l.id)]));
@@ -3512,7 +3757,15 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3512
3757
  filename: input.ref.filename,
3513
3758
  uploadedAt: Date.now(),
3514
3759
  };
3515
- return cdb(ctx).insert("cms_media", { file, alt: input.alt ?? null });
3760
+ // The projection columns go in beside `file`, from the SAME resolved values — never
3761
+ // from `input`, which is the client's claim about a blob it has just uploaded.
3762
+ return cdb(ctx).insert("cms_media", {
3763
+ file,
3764
+ filename: file.filename ?? null,
3765
+ contentType: file.contentType ?? null,
3766
+ size: file.size ?? null,
3767
+ alt: input.alt ?? null,
3768
+ });
3516
3769
  }, {
3517
3770
  ...editor,
3518
3771
  input: (raw): { ref: FileRef; alt?: string } => {
@@ -3531,11 +3784,45 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3531
3784
  },
3532
3785
  }),
3533
3786
 
3534
- listMedia: query((ctx, input: { limit?: number; offset?: number }) => {
3787
+ listMedia: query((ctx, input: { limit?: number; offset?: number; sort?: MediaSort; kind?: MediaKind; q?: string; term?: string }) => {
3535
3788
  const limit = Math.min(Math.max(Math.trunc(Number(input?.limit ?? 50)) || 50, 1), 200);
3536
3789
  const offset = Math.max(Math.trunc(Number(input?.offset ?? 0)) || 0, 0);
3537
- return cdb(ctx).find({ from: "cms_media", orderBy: { column: "createdAt", dir: "desc" }, limit, offset });
3538
- }, viewer),
3790
+ // The narrowings AND together a search inside a type filter inside a tag is all
3791
+ // three. Built as a list so none has to know whether the others are present.
3792
+ const clauses = [
3793
+ mediaKindWhere(input?.kind),
3794
+ input?.q ? mediaSearchWhere(input.q) : undefined,
3795
+ // A relation traversal, compiled to a subquery through `cms_media_terms`. Filtering
3796
+ // by term therefore costs the same page of rows as filtering by kind — the whole
3797
+ // reason the assignments are a junction rather than a JSON array on the media row.
3798
+ input?.term ? { terms: { id: input.term } } : undefined,
3799
+ ].filter(
3800
+ (c): c is WhereClause<typeof cmsSchema, "cms_media"> => c !== undefined,
3801
+ );
3802
+ const where = clauses.length === 0 ? undefined : clauses.length === 1 ? clauses[0] : { AND: clauses };
3803
+ return cdb(ctx).find({ from: "cms_media", where, orderBy: MEDIA_SORTS[input?.sort ?? "newest"], limit, offset });
3804
+ }, {
3805
+ ...viewer,
3806
+ // Parsed, not cast: `sort` names an ORDER BY and `kind` a WHERE, and both arrive from a
3807
+ // browser. Anything unrecognised falls back to the default rather than erroring — a
3808
+ // stale bookmark carrying a sort this build dropped should show the library, not a 400.
3809
+ input: (raw): { limit?: number; offset?: number; sort?: MediaSort; kind?: MediaKind; q?: string; term?: string } => {
3810
+ const o = asObj(raw);
3811
+ const sort = typeof o.sort === "string" && o.sort in MEDIA_SORTS ? (o.sort as MediaSort) : undefined;
3812
+ const kind = typeof o.kind === "string" && (MEDIA_KINDS as readonly string[]).includes(o.kind) ? (o.kind as MediaKind) : undefined;
3813
+ return {
3814
+ limit: typeof o.limit === "number" ? o.limit : undefined,
3815
+ offset: typeof o.offset === "number" ? o.offset : undefined,
3816
+ sort,
3817
+ kind,
3818
+ q: mediaQuery(o.q),
3819
+ // An id, not a slug: a slug identifies a term only within its vocabulary, and the
3820
+ // filter has no vocabulary to resolve it against. An id that is not a term matches
3821
+ // nothing, which is the same answer as a term with no files.
3822
+ term: typeof o.term === "string" && o.term !== "" ? o.term : undefined,
3823
+ };
3824
+ },
3825
+ }),
3539
3826
 
3540
3827
  getMedia: query(async (ctx, input: { id: string }) => {
3541
3828
  const rows = await cdb(ctx).find({ from: "cms_media", where: { id: input.id }, limit: 1 });
@@ -3563,6 +3850,63 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3563
3850
  },
3564
3851
  }),
3565
3852
 
3853
+ /** A media asset's assigned terms.
3854
+ *
3855
+ * The media row is read FIRST, through `ctx.db`, so the caller's own scope decides
3856
+ * whether this answers — the junction and `cms_terms` are granted unscoped, so without
3857
+ * it anyone holding an id could read a TRASHED file's tags and the non-empty answer
3858
+ * would confirm the file exists. Same rule as `listPageTerms`, for the same reason. */
3859
+ listMediaTerms: query(async (ctx, input: { mediaId: string }): Promise<Term[]> => {
3860
+ const db = cdb(ctx);
3861
+ const media = await db.find({ from: "cms_media", where: { id: input.mediaId }, select: ["id"], limit: 1 });
3862
+ if (!media[0]) return [];
3863
+ const links = await db.find({ from: "cms_media_terms", where: { mediaId: input.mediaId }, select: ["termId"], limit: MAX_TERMS });
3864
+ const ids = links.map((l) => String(l.termId));
3865
+ if (ids.length === 0) return [];
3866
+ const rows = await db.find({ from: "cms_terms", where: { id: { in: ids } }, orderBy: [{ column: "position" }, { column: "label" }], limit: ids.length });
3867
+ return rows as unknown as Term[];
3868
+ }, {
3869
+ ...viewer,
3870
+ input: (raw): { mediaId: string } => {
3871
+ const id = asObj(raw).mediaId;
3872
+ if (typeof id !== "string" || id === "") throw new BadRequest("mediaId is required");
3873
+ return { mediaId: id };
3874
+ },
3875
+ }),
3876
+
3877
+ /** Replace a media asset's term assignments wholesale — set semantics, like
3878
+ * `setPageTerms`, and for the same reason: the panel holds the whole selection, and two
3879
+ * calls each patching one end of it race into a state neither asked for. */
3880
+ setMediaTerms: mutation(async (ctx, input: { mediaId: string; termIds: string[] }) => {
3881
+ const db = cdb(ctx);
3882
+ const media = await db.find({ from: "cms_media", where: { id: input.mediaId }, select: ["id"], limit: 1 });
3883
+ if (!media[0]) throw notFound("media");
3884
+ const wanted = new Set(input.termIds);
3885
+ if (wanted.size > 0) {
3886
+ const found = await db.find({ from: "cms_terms", where: { id: { in: [...wanted] } }, select: ["id"], limit: wanted.size });
3887
+ if (found.length !== wanted.size) throw new BadRequest("one or more termIds are not terms");
3888
+ await assertTermsApplyTo(db, [...wanted], "media");
3889
+ }
3890
+ const existing = await db.find({ from: "cms_media_terms", where: { mediaId: input.mediaId }, select: ["id", "termId"], limit: MAX_TERMS });
3891
+ const have = new Map(existing.map((l) => [String(l.termId), String(l.id)]));
3892
+ for (const [termId, linkId] of have) if (!wanted.has(termId)) await db.delete("cms_media_terms", linkId);
3893
+ for (const termId of wanted) if (!have.has(termId)) await db.insert("cms_media_terms", { mediaId: input.mediaId, termId });
3894
+ return { ok: true as const, count: wanted.size };
3895
+ }, {
3896
+ ...editor,
3897
+ input: (raw): { mediaId: string; termIds: string[] } => {
3898
+ const o = asObj(raw);
3899
+ if (typeof o.mediaId !== "string" || o.mediaId === "") throw new BadRequest("mediaId is required");
3900
+ if (!Array.isArray(o.termIds)) throw new BadRequest("termIds must be a list");
3901
+ const ids = o.termIds.map((v) => {
3902
+ if (typeof v !== "string" || v === "") throw new BadRequest("termIds must be a list of ids");
3903
+ return v;
3904
+ });
3905
+ if (ids.length > MAX_TERMS) throw new BadRequest(`a file may carry at most ${MAX_TERMS} terms`);
3906
+ return { mediaId: o.mediaId, termIds: ids };
3907
+ },
3908
+ }),
3909
+
3566
3910
  /** Trash a media row. The R2 OBJECT IS KEPT — deleting the bytes here would make
3567
3911
  * `restoreMedia` a lie, and a block still referencing the id would render a dead url
3568
3912
  * with no way back. `purgeMedia` is what drops both — and `listTrash` is how you find
@@ -3964,6 +4308,11 @@ export function createCmsHandlers(opts: CmsHandlerOpts = {}) {
3964
4308
  // the next cold start. That is GitHub #48 in the deployment that upgraded the editor to
3965
4309
  // fix it. Absent ⇒ the editor treats no type as code-defined, which is correct there.
3966
4310
  codeDefinedTypes: true as const,
4311
+ // Media carries taxonomy terms, and `listMedia` understands `term`. Declared for the
4312
+ // usual reason: an older server has neither handler, so the detail panel's Tags
4313
+ // section would 404 on open and the library's tag filter would send an argument that
4314
+ // is ignored — a filter that visibly does nothing. Absent ⇒ neither is drawn.
4315
+ mediaTerms: true as const,
3967
4316
  // PER-CALLER, unlike everything else here. `viewer` is `editorRoles ∪ reviewerRoles`,
3968
4317
  // so a reviewer-only session reaches this handler and every read handler — but every
3969
4318
  // WRITE is `editorRoles`. Without this the editor renders the authoring surfaces
@@ -4579,7 +4928,7 @@ export function cmsPolicies(opts: CmsPolicyOpts = {}): { public: Policy[]; edito
4579
4928
  "cms_content_types", "cms_block_types", "cms_blocks", "cms_pages", "cms_page_blocks", "cms_page_revisions", "cms_media", "cms_audit",
4580
4929
  // Site furniture. Full CRUD for an editor, like every other cms_ table — the per-handler
4581
4930
  // `auth` gate is what separates editor from reviewer; this is the row scope.
4582
- "cms_menus", "cms_redirects", "cms_taxonomies", "cms_terms", "cms_page_terms", "cms_widget_areas",
4931
+ "cms_menus", "cms_redirects", "cms_taxonomies", "cms_terms", "cms_page_terms", "cms_media_terms", "cms_widget_areas",
4583
4932
  ] as const;
4584
4933
  // Soft-deleted rows are filtered in the ACL, not in each handler. A read scope is
4585
4934
  // AND-merged into every `ctx.db` read, so one policy hides a trashed row from the public
@@ -4636,6 +4985,10 @@ export function cmsPolicies(opts: CmsPolicyOpts = {}): { public: Policy[]; edito
4636
4985
  policy(`${p}:public:taxonomies:read`, "cms_taxonomies", "read", allow()),
4637
4986
  policy(`${p}:public:terms:read`, "cms_terms", "read", allow()),
4638
4987
  policy(`${p}:public:page-terms:read`, "cms_page_terms", "read", allow()),
4988
+ // The media junction, for the same reason as the page one: `where: { terms: … }` on a
4989
+ // media row compiles to a subquery THROUGH it, so without the grant the library's tag
4990
+ // filter matches nothing and reads as "no files carry this tag".
4991
+ policy(`${p}:public:media-terms:read`, "cms_media_terms", "read", allow()),
4639
4992
  policy(`${p}:public:widget-areas:read`, "cms_widget_areas", "read", allow()),
4640
4993
  ],
4641
4994
  editor: editorPolicies,
@@ -5876,6 +6229,63 @@ export function createCollectionTasks(collections: readonly CollectionDef[]) {
5876
6229
  * between the revision insert and the page update leaves the page unpublished with an orphan
5877
6230
  * revision until the next at-least-once redelivery re-runs (the token still matches, so it
5878
6231
  * completes). Acceptable for a scheduled job; the interactive path is atomic. */
6232
+ /**
6233
+ * The CMS's own data migrations — spread into `app.migrations`.
6234
+ *
6235
+ * migrations: [...cmsMigrations]
6236
+ *
6237
+ * Opt-in like every other fragment this package ships (`cmsHandlers`, `cmsPolicies`,
6238
+ * `cmsTasks`), and with the same consequence for forgetting it: nothing breaks loudly. Media
6239
+ * rows written before the projection columns existed keep NULL `filename`/`contentType`, so
6240
+ * they sort together under a name sort and answer only the `other` type filter. New uploads
6241
+ * are unaffected — `createMedia` writes the columns itself.
6242
+ */
6243
+ export const cmsMigrations: readonly DataMigration[] = [
6244
+ {
6245
+ // Fill the columns `cms_media` grew for sorting and filtering, out of the `file` JSON that
6246
+ // has always held the same three values.
6247
+ id: "cms:2026-09-04-media-projection-columns",
6248
+ // `MigrationContext<typeof cmsSchema>` is what types `db` here — the `DataMigration`
6249
+ // contract is schema-agnostic, so an unparameterized ctx hands back untyped rows.
6250
+ async up({ db, driver }: MigrationContext<typeof cmsSchema>) {
6251
+ const d = driver.dialect;
6252
+ const t = d.id("cms_media");
6253
+ const set = (c: string, path: string) => `${d.id(c)} = json_extract(${d.id("file")}, '$.${path}')`;
6254
+ try {
6255
+ // One statement for the whole table. `WHERE filename IS NULL` makes it cheap on a
6256
+ // store that has nothing to do, and keeps it off rows a later upload already filled.
6257
+ await driver.exec(
6258
+ `UPDATE ${t} SET ${set("filename", "filename")}, ${set("contentType", "contentType")}, ${set("size", "size")} ` +
6259
+ `WHERE ${d.id("filename")} IS NULL AND ${d.id("contentType")} IS NULL`,
6260
+ [],
6261
+ );
6262
+ return;
6263
+ } catch {
6264
+ // `json_extract` is a JSON1 function. It is present in D1 and in every ordinary SQLite
6265
+ // build, but nothing in this repo has depended on it before and DO SQLite is
6266
+ // Cloudflare's own engine — so a missing function must not brick a tenant's boot,
6267
+ // which is exactly what a data migration's fail-closed contract would otherwise do.
6268
+ // The fallback walks the rows through the ORM, where the fileRef codec has already
6269
+ // parsed the same JSON for us. Slower, and bounded by how many media a tenant has.
6270
+ }
6271
+ // No chunking: this runs inside `blockConcurrencyWhile` on a tenant's first fetch, so a
6272
+ // very large library will stall that one request — which is still the right trade
6273
+ // against leaving half the table unsorted forever, since a migration runs ONCE.
6274
+ const rows = await db.find({ from: "cms_media", where: { filename: { isNull: true }, contentType: { isNull: true } } });
6275
+ for (const row of rows) {
6276
+ const file = row.file;
6277
+ if (!file || typeof file !== "object" || Array.isArray(file)) continue;
6278
+ const ref = file as { filename?: unknown; contentType?: unknown; size?: unknown };
6279
+ await db.update("cms_media", String(row.id), {
6280
+ filename: typeof ref.filename === "string" ? ref.filename : null,
6281
+ contentType: typeof ref.contentType === "string" ? ref.contentType : null,
6282
+ size: typeof ref.size === "number" ? ref.size : null,
6283
+ });
6284
+ }
6285
+ },
6286
+ },
6287
+ ];
6288
+
5879
6289
  export const cmsTasks = {
5880
6290
  "cms:publish": async (ctx: HandlerContext, payload: unknown) => {
5881
6291
  const { pageId, token } = asObj(payload) as { pageId?: string; token?: string };