bearminion 1.20.0 → 1.22.0

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +3 -3
  3. package/dist/astro.d.ts +16 -7
  4. package/dist/astro.js +212 -93
  5. package/dist/cli.js +903 -4
  6. package/dist/content-types-46XqPaW4.js +505 -0
  7. package/dist/content.d.ts +24 -3
  8. package/dist/content.js +83 -6
  9. package/dist/{editor-context-DzRwKENi.d.ts → editor-context-D1yfPp21.d.ts} +95 -8
  10. package/dist/{github-store-Dt_YuOPD.js → github-store-B2folBeq.js} +551 -206
  11. package/dist/{github-store-DsLCe5MR.d.ts → github-store-CuhvbFCh.d.ts} +1 -1
  12. package/dist/hosted-astro.js +1 -1
  13. package/dist/{hosted-middleware-CsROahka.js → hosted-middleware-DHLIedeV.js} +1 -1
  14. package/dist/hosted-overlay.js +1 -1
  15. package/dist/hosted.d.ts +10 -4
  16. package/dist/hosted.js +68 -9
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +11 -6
  19. package/dist/{migrate-b408EaLp.js → migrate-Cm30puW8.js} +2 -2
  20. package/dist/{page-wlcQJAA-.js → page-C7zE_HD1.js} +5 -1
  21. package/dist/{page-BGSTL63-.d.ts → page-CpVElMPH.d.ts} +193 -37
  22. package/dist/{request-guards-BcSUj8Gc.js → request-guards-DtNVdqQ7.js} +1 -1
  23. package/dist/{collections-Bm3RWg2K.js → routing-jKeq4LwO.js} +213 -57
  24. package/dist/routing-yPy8hEfZ.d.ts +137 -0
  25. package/dist/{theme-BvqJ8UnS.js → theme-DTVVNMlr.js} +1 -1
  26. package/dist/ui/mount.js +3294 -1259
  27. package/package.json +2 -2
  28. package/registry/default/files/src/components/organisms/EntryList.astro +83 -0
  29. package/registry/default/files/src/components/organisms/Pagination.astro +56 -0
  30. package/registry/default/files/src/components/sections/contact/definition.ts +6 -2
  31. package/registry/default/files/src/components/sections/faq/definition.ts +2 -2
  32. package/registry/default/files/src/components/sections/media/Media.astro +2 -2
  33. package/registry/default/files/src/components/sections/media/MediaPlayer.astro +2 -2
  34. package/registry/default/files/src/components/sections/pricing/definition.ts +16 -1
  35. package/registry/default/files/src/components/sections/shared.ts +3 -0
  36. package/registry/default/files/src/components/sections/stats/definition.ts +6 -1
  37. package/registry/default/files/src/components/sections/testimonials/definition.ts +13 -1
  38. package/registry/default/files/src/components/sections/text-image/definition.ts +1 -1
  39. package/registry/default/files/src/components/seo/Seo.astro +3 -1
  40. package/registry/default/files/src/content.config.ts +21 -0
  41. package/registry/default/files/src/env.d.ts +2 -0
  42. package/registry/default/files/src/lib/content.ts +81 -0
  43. package/registry/default/files/src/lib/editing.ts +6 -0
  44. package/registry/default/files/src/lib/sitemap.ts +48 -0
  45. package/registry/default/files/src/pages/[...slug].astro +30 -16
  46. package/registry/default/registry.json +77 -21
  47. package/dist/preview-DFLna-Be.d.ts +0 -42
@@ -1,8 +1,9 @@
1
- import { O as ContentReadError, T as imageFields, _ as parseKey, a as listEntries, b as PreviewUnavailableError, d as validateEditorPage, f as validatePage, g as pageKey, h as SITE_KEY, i as fieldDefinitions, k as ContentValidationError, l as updateEntry, m as PAGES_DIR, n as createEntry, o as readEntry, p as validateSite, r as deleteEntry, s as renameEntry, u as fieldIssues, v as StoreError, y as StoreKeyError } from "./collections-Bm3RWg2K.js";
2
- import { c as withoutOrphanSections, d as isOrphanSection, i as isSystemPage } from "./page-wlcQJAA-.js";
3
- import { r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
1
+ import { A as ContentValidationError, E as imageFields, _ as updateEntry, b as validateSite, d as deleteEntry, f as fieldDefinitions, h as renameEntry, k as ContentReadError, m as readEntry, o as matchPath, p as listEntries, r as isDraft, u as createEntry, v as fieldIssues, x as PreviewUnavailableError, y as validateEditorPage } from "./routing-jKeq4LwO.js";
2
+ import { a as isSystemPage, m as isOrphanSection, u as withoutOrphanSections } from "./page-C7zE_HD1.js";
3
+ import { D as StoreKeyError, E as StoreError, S as SITE_KEY, a as PAGES_TYPE, f as entryKey, g as listingPath, i as LISTING_MIGRATION_TYPE, l as createEntrySchema, m as listingKey, p as entryPath, u as createListingSchema, v as reservedSlugs, w as parseKey, x as sortEntries, y as resolveTypes } from "./content-types-46XqPaW4.js";
4
+ import { r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-Cm30puW8.js";
4
5
  import { n as formatBytes, t as DEFAULT_IMAGE_BYTE_LIMIT } from "./upload-rules-Cao9uY5K.js";
5
- import { i as readSlug, n as isLocalRequest, r as isSameOriginRequest } from "./request-guards-BcSUj8Gc.js";
6
+ import { i as readSlug, n as isLocalRequest, r as isSameOriginRequest } from "./request-guards-DtNVdqQ7.js";
6
7
  import { C as missingAssetIssues, S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-DBEfw_Gq.js";
7
8
  import { z } from "zod";
8
9
  //#region src/video-sniff.ts
@@ -196,6 +197,36 @@ const NO_HISTORY = {
196
197
  };
197
198
  //#endregion
198
199
  //#region src/api.ts
200
+ /** The site's content types. A context built by hand without them has the built-in ones. */
201
+ const typesOf = (context) => context.types ?? resolveTypes({});
202
+ const isPages = (type) => type.id === PAGES_TYPE;
203
+ const noun = (type) => isPages(type) ? "page" : "entry";
204
+ /** The pull-request scope of one entry. Pages keep `page:<slug>`, so pull requests opened before types existed still match. */
205
+ const entryScope = (type, slug) => isPages(type) ? `page:${slug}` : `${type.id}:${slug}`;
206
+ const entryHistory = (type, slug) => isPages(type) ? ["page", slug] : ["entry", `${type.id}/${slug}`];
207
+ const entryRoute = (type, slug) => isPages(type) ? `/pages/${slug}` : `/types/${type.id}/entries/${slug}`;
208
+ /** Rename and delete locks. The `pages` option of `bearminion()` rules pages; other types carry their own. */
209
+ function entryRules(context, type) {
210
+ return isPages(type) ? context.pageRules : {
211
+ rename: type.rename,
212
+ delete: type.delete
213
+ };
214
+ }
215
+ /** The type of a document stored in `type`'s folder: the home and 404 pages are stored among the pages. */
216
+ function documentType(context, type, slug) {
217
+ if (!isPages(type)) return type;
218
+ const types = typesOf(context);
219
+ return slug === "index" ? types.home : slug === "404" ? types.notFound : type;
220
+ }
221
+ /** Validate an entry for the editor (orphaned sections kept), or strictly as the build would. */
222
+ function validateEntry(context, type, slug, input, strict = false) {
223
+ return createEntrySchema(context.sections, documentType(context, type, slug), { tolerateOrphans: !strict }).safeParse(input);
224
+ }
225
+ /** Why `slug` cannot be an entry of `type`, or null when it can. */
226
+ function reservedSlug(context, type, slug) {
227
+ if (slug === "index" || !reservedSlugs(typesOf(context), type).has(slug)) return null;
228
+ return problem(409, "reserved_slug", `"${slug}" cannot be used here: ${!isPages(type) && slug === "page" ? `"/${type.prefix}/${slug}" is where the listing's page numbers live.` : `"/${slug}" is the address of another content type.`}`);
229
+ }
199
230
  /**
200
231
  * Dev-server API. Returns null when the URL is not under {@link API_PREFIX}
201
232
  * so other middleware can continue. Every write is schema-checked first.
@@ -209,7 +240,8 @@ async function handleEditorRequest(request, context, meta = {}) {
209
240
  }
210
241
  }
211
242
  async function route(request, context, meta) {
212
- const pathname = stripTrailingSlash(new URL(request.url).pathname);
243
+ const url = new URL(request.url);
244
+ const pathname = stripTrailingSlash(url.pathname);
213
245
  if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
214
246
  if (meta.authenticated) {
215
247
  if (!isSameOriginRequest(request.headers, request.url)) return problem(403, "forbidden", "The editor API refuses cross-site requests.");
@@ -231,10 +263,15 @@ async function route(request, context, meta) {
231
263
  }
232
264
  if (parts.length === 1 && parts[0] === "pages") {
233
265
  if (method === "GET") return getPages(context);
234
- if (method === "POST") return createPage(request, context);
266
+ if (method === "POST") return createPage(request, context, typesOf(context).pages);
235
267
  return methodNotAllowed(["GET", "POST"]);
236
268
  }
237
269
  if (parts[0] === "collections") return collectionRoute(request, context, parts.slice(1), method);
270
+ if (parts[0] === "types") return typeRoute(request, context, parts.slice(1), method);
271
+ if (parts.length === 1 && parts[0] === "document") {
272
+ if (method === "GET") return getDocumentAt(context, url.searchParams.get("path") ?? "");
273
+ return methodNotAllowed(["GET"]);
274
+ }
238
275
  if (parts.length === 1 && parts[0] === "forms") {
239
276
  if (method === "GET") return getForms(context);
240
277
  return methodNotAllowed(["GET"]);
@@ -248,7 +285,7 @@ async function route(request, context, meta) {
248
285
  return methodNotAllowed(["POST"]);
249
286
  }
250
287
  if (parts.length === 1 && parts[0] === "images") {
251
- if (method === "GET") return getImages(scoped(context, "uploads"));
288
+ if (method === "GET") return getImages(scoped(context, "uploads"), new URL(request.url).searchParams.get("usage") === "1");
252
289
  if (method === "POST") return postImage(request, scoped(context, "uploads"));
253
290
  return methodNotAllowed(["GET", "POST"]);
254
291
  }
@@ -273,6 +310,20 @@ async function route(request, context, meta) {
273
310
  if (method === "POST") return postSitePreview(request, context, meta);
274
311
  return methodNotAllowed(["POST"]);
275
312
  }
313
+ if (parts[0] === "history" && parts[1] === "types" && parts.length >= 4 && parts.length <= 5) {
314
+ if (method !== "GET") return methodNotAllowed(["GET"]);
315
+ const type = typesOf(context).get(decodeSegment(parts[2] ?? ""));
316
+ const name = parts[3] ?? "";
317
+ if (!type) return problem(404, "not_found", "Unknown content type.");
318
+ if (type.kind === "single") {
319
+ if (name !== SINGLE_HISTORY) return problem(404, "not_found", "Unknown editor API route.");
320
+ return getHistory(context, ...singleHistory(type), parts[4]);
321
+ }
322
+ if (name === LISTING_HISTORY && type.listing) return getHistory(context, "entry", `${type.id}/${LISTING_HISTORY}`, parts[4]);
323
+ const slug = readSlug(name);
324
+ if (slug === null) return badSlug();
325
+ return getHistory(context, ...entryHistory(type, slug), parts[4]);
326
+ }
276
327
  if (parts[0] === "history" && (parts[1] === "site" || parts[1] === "pages")) {
277
328
  if (method !== "GET") return methodNotAllowed(["GET"]);
278
329
  if (parts[1] === "site" && parts.length <= 3) return getHistory(context, "site", "", parts[2]);
@@ -286,9 +337,10 @@ async function route(request, context, meta) {
286
337
  const slug = readSlug(parts[1] ?? "");
287
338
  if (slug === null) return badSlug();
288
339
  const entry = scoped(context, `page:${slug}`);
289
- if (method === "GET") return getPage(entry, slug);
290
- if (method === "PUT") return putPage(request, entry, slug);
291
- if (method === "DELETE") return deletePage(entry, slug);
340
+ const pages = typesOf(context).pages;
341
+ if (method === "GET") return getPage(entry, slug, pages);
342
+ if (method === "PUT") return putPage(request, entry, slug, pages);
343
+ if (method === "DELETE") return deletePage(entry, slug, pages);
292
344
  return methodNotAllowed([
293
345
  "GET",
294
346
  "PUT",
@@ -298,13 +350,7 @@ async function route(request, context, meta) {
298
350
  if (parts.length === 3 && parts[0] === "pages" && parts[2] === "rename") {
299
351
  const slug = readSlug(parts[1] ?? "");
300
352
  if (slug === null) return badSlug();
301
- if (method === "POST") return renamePage(request, scoped(context, `page:${slug}`), slug);
302
- return methodNotAllowed(["POST"]);
303
- }
304
- if (parts.length === 3 && parts[0] === "pages" && parts[2] === "set-home") {
305
- const slug = readSlug(parts[1] ?? "");
306
- if (slug === null) return badSlug();
307
- if (method === "POST") return setHome(request, scoped(context, `page:${slug}`), slug);
353
+ if (method === "POST") return renamePage(request, scoped(context, `page:${slug}`), slug, typesOf(context).pages);
308
354
  return methodNotAllowed(["POST"]);
309
355
  }
310
356
  return problem(404, "not_found", "Unknown editor API route.");
@@ -527,17 +573,18 @@ async function writeDocuments(context, documents, removals = []) {
527
573
  }
528
574
  const saveSchema = z.object({
529
575
  page: z.object({
530
- /** The slug the page is stored under now. The document's own `slug` is where it goes. */
531
- from: z.string(),
532
- document: z.unknown(),
533
- /** Where the current home page moves when this page becomes `index`. */
534
- previousHomeSlug: z.string().optional()
576
+ /** The id of the entry's content type. Default `pages`. */
577
+ type: z.string().optional(),
578
+ /** True when `document` is the listing page of `type`, not one of its entries. */
579
+ listing: z.boolean().optional(),
580
+ /** The slug the page is stored under now. The document's own `slug` is where it goes. A single and a listing page have one fixed place and need none. */
581
+ from: z.string().optional(),
582
+ document: z.unknown()
535
583
  }).strict().optional(),
536
584
  site: z.unknown().optional()
537
585
  }).strict().refine((value) => value.page !== void 0 || value.site !== void 0, { message: "Nothing to save." });
538
586
  /**
539
- * Save the editor draft in one request: a page (with its rename or promotion to home, when the slug
540
- * changed) and the site. Every document is validated before anything is written, and all writes and
587
+ * Save the editor draft in one request: a page (with its rename, when the slug changed) and the site. Every document is validated before anything is written, and all writes and
541
588
  * removals go to the store as one `apply`, so a failure never leaves a page renamed with stale content
542
589
  * or the page saved without the site.
543
590
  */
@@ -574,7 +621,17 @@ async function postSave(request, context) {
574
621
  }
575
622
  }
576
623
  if (parsed.data.page !== void 0) {
577
- const planned = await planPageSave(context, parsed.data.page);
624
+ const { type: typeId, listing, from, document } = parsed.data.page;
625
+ const type = typeId === void 0 ? typesOf(context).pages : typesOf(context).get(typeId);
626
+ let planned;
627
+ if (type === void 0) planned = { response: problem(404, "not_found", `Unknown content type "${typeId}".`) };
628
+ else if (type.kind === "single") planned = await planFixedSave(context, singleDocument(context, type), document, type.slug);
629
+ else if (listing) planned = type.listing ? await planFixedSave(context, listingDocument(context, type), document) : { response: problem(404, "not_found", `${type.label} has no listing page (listing in its type options).`) };
630
+ else if (from === void 0) planned = { response: problem(400, "invalid_slug", "from is required to save an entry: the slug it is stored under.") };
631
+ else planned = await planPageSave(context, {
632
+ from,
633
+ document
634
+ }, type);
578
635
  if (planned.issues) failures.push(...tagIssues(planned.issues, "page"));
579
636
  else if (planned.response) {
580
637
  if (failures.length === 0) return planned.response;
@@ -591,33 +648,29 @@ async function postSave(request, context) {
591
648
  for (const step of after) await step();
592
649
  return json(200, result);
593
650
  }
594
- async function planPageSave(context, input) {
651
+ async function planPageSave(context, input, type) {
595
652
  const from = readSlug(input.from);
596
653
  if (from === null) return { response: badSlug() };
597
- const upgraded = context.migrator.upgrade(input.document, "page");
654
+ const upgraded = context.migrator.upgrade(input.document, "page", documentType(context, type, from).id);
598
655
  if (!upgraded.ok) return { issues: [{
599
656
  path: SCHEMA_VERSION_KEY,
600
657
  message: upgraded.message
601
658
  }] };
602
- const parsed = validateEditorPage(upgraded.value, context.sections);
659
+ const parsed = validateEntry(context, type, from, upgraded.value);
603
660
  if (!parsed.success) return { issues: fieldIssues(parsed.error) };
604
661
  const page = parsed.data;
605
662
  const target = page.slug;
606
663
  const missing = await missingAssets(context, page);
607
664
  if (missing.length > 0) return { issues: missing };
608
- const loaded = await loadStoredPages(context);
665
+ const loaded = await loadStoredPages(context, {}, type);
609
666
  if (loaded.response) return { response: loaded.response };
610
667
  const found = loaded.pages.find((entry) => entry.page.slug === from);
611
- if (!found) return { response: problem(404, "not_found", `No page with slug "${from}".`) };
612
- const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
613
- const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
614
- path: `sections.${index}.type`,
615
- message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
616
- }] : []);
668
+ if (!found) return { response: problem(404, "not_found", `No ${noun(type)} with slug "${from}".`) };
669
+ const added = addedOrphans(context, found.page.sections, page.sections);
617
670
  if (added.length > 0) return { issues: added };
618
671
  const after = async () => {
619
- await history(context).ensureBaseline("page", target, found.page);
620
- await history(context).write("page", target, page);
672
+ await history(context).ensureBaseline(...entryHistory(type, target), found.page);
673
+ await history(context).write(...entryHistory(type, target), page);
621
674
  };
622
675
  if (target === from) return {
623
676
  page,
@@ -625,45 +678,21 @@ async function planPageSave(context, input) {
625
678
  removals: [],
626
679
  after
627
680
  };
628
- if (!context.pageRules.rename) return { response: locked("rename") };
629
- if (from === "index") return { response: problem(409, "conflict", "The home page slug stays index. Set another page as home to move it.") };
630
- if (isSystemPage(from) || isSystemPage(target)) return { response: problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.") };
631
- if (target !== "index") {
632
- if (loaded.pages.some((entry) => entry.page.slug === target)) return { response: problem(409, "conflict", `A page with slug "${target}" already exists.`) };
633
- const nextKey = pageKey(target);
634
- if (await context.store.exists(nextKey)) return { response: problem(409, "conflict", `A file named ${target}.json already exists.`) };
635
- return {
636
- page,
637
- writes: [[nextKey, page]],
638
- removals: [found.key],
639
- after
640
- };
641
- }
642
- const indexKey = pageKey("index");
643
- const home = loaded.pages.find((entry) => entry.page.slug === "index");
644
- if (!home) {
645
- if (await context.store.exists(indexKey)) return { response: problem(409, "conflict", "A file named index.json already exists.") };
646
- return {
647
- page,
648
- writes: [[indexKey, page]],
649
- removals: [found.key],
650
- after
651
- };
652
- }
653
- const previousSlug = input.previousHomeSlug === void 0 ? null : readSlug(input.previousHomeSlug);
654
- if (previousSlug === null || previousSlug === "index" || isSystemPage(previousSlug)) return { response: problem(400, "invalid_slug", "previousHomeSlug is required to move the current home page.") };
655
- if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return { response: problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`) };
656
- const previousKey = pageKey(previousSlug);
657
- if (await context.store.exists(previousKey)) return { response: problem(409, "conflict", `A file named ${previousSlug}.json already exists.`) };
658
- const moved = validateEditorPage({
659
- ...home.page,
660
- slug: previousSlug
661
- }, context.sections);
662
- if (!moved.success) return { issues: fieldIssues(moved.error) };
681
+ if (!entryRules(context, type).rename) return { response: locked("rename", type) };
682
+ if (isPages(type)) {
683
+ if (from === "index") return { response: problem(409, "conflict", "The home page is served at / and keeps the slug index.") };
684
+ if (isSystemPage(from) || isSystemPage(target)) return { response: problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.") };
685
+ if (target === "index") return { response: homeIsFixed() };
686
+ }
687
+ const reserved = reservedSlug(context, type, target);
688
+ if (reserved) return { response: reserved };
689
+ if (loaded.pages.some((entry) => entry.page.slug === target)) return { response: problem(409, "conflict", `A ${noun(type)} with slug "${target}" already exists.`) };
690
+ const nextKey = entryKey(type, target);
691
+ if (await context.store.exists(nextKey)) return { response: problem(409, "conflict", `A file named ${target}.json already exists.`) };
663
692
  return {
664
693
  page,
665
- writes: [[previousKey, moved.data], [indexKey, page]],
666
- removals: [...home.key === indexKey ? [] : [home.key], found.key],
694
+ writes: [[nextKey, page]],
695
+ removals: [found.key],
667
696
  after
668
697
  };
669
698
  }
@@ -693,159 +722,412 @@ async function getHistory(context, scope, slug, id) {
693
722
  if (snapshot === null) return problem(404, "not_found", "No saved version with that id.");
694
723
  return json(200, snapshot);
695
724
  }
725
+ const sectionAnchors = (sections) => sections.flatMap((section) => typeof section === "object" && section !== null && "anchor" in section && typeof section.anchor === "string" && section.anchor !== "" ? [section.anchor] : []);
726
+ /** Draft, noindex and the time of the last change: what the listings show beside each document. */
727
+ async function listMeta(context, stored) {
728
+ const time = await context.store.modified?.(stored.key).catch(() => void 0);
729
+ return {
730
+ ...isDraft(stored.page) ? { draft: true } : {},
731
+ ...stored.page.seo.noindex === true ? { noindex: true } : {},
732
+ ...time === void 0 ? {} : { updatedAt: new Date(time).toISOString() }
733
+ };
734
+ }
696
735
  async function getPages(context) {
697
736
  const loaded = await loadStoredPages(context);
698
737
  if (loaded.response) return loaded.response;
699
- return json(200, { pages: loaded.pages.map((entry) => ({
738
+ return json(200, { pages: await Promise.all(loaded.pages.map(async (entry) => ({
700
739
  slug: entry.page.slug,
701
740
  title: entry.page.title,
702
741
  file: entry.fileName,
703
742
  system: isSystemPage(entry.page.slug),
704
- anchors: entry.page.sections.flatMap((section) => "anchor" in section && typeof section.anchor === "string" && section.anchor !== "" ? [section.anchor] : [])
743
+ anchors: sectionAnchors(entry.page.sections),
744
+ ...await listMeta(context, entry)
745
+ }))) });
746
+ }
747
+ /** The language strings are ordered in: the site's own (`site.json` `lang`), so a listing reads right to its visitors. */
748
+ async function siteLang(context) {
749
+ try {
750
+ const lang = (await readSite(context)).lang;
751
+ return typeof lang === "string" && lang !== "" ? lang : "en";
752
+ } catch {
753
+ return "en";
754
+ }
755
+ }
756
+ /** The entries of a declared type, in the type's sort order: what its listing page shows, drafts included. */
757
+ async function getEntries(context, type) {
758
+ const loaded = await loadStoredPages(context, {}, type);
759
+ if (loaded.response) return loaded.response;
760
+ const own = loaded.pages.filter((entry) => documentType(context, type, entry.page.slug) === type);
761
+ const files = new Map(own.map((entry) => [entry.page.slug, entry.fileName]));
762
+ const metas = new Map(await Promise.all(own.map(async (entry) => [entry.page.slug, await listMeta(context, entry)])));
763
+ const sorted = sortEntries(type, own.map((entry) => entry.page), await siteLang(context));
764
+ const by = type.sort && type.sort.by !== "title" ? type.sort.by : null;
765
+ return json(200, { entries: sorted.map((entry) => ({
766
+ slug: entry.slug,
767
+ title: entry.title,
768
+ file: files.get(entry.slug),
769
+ path: entryPath(type, entry.slug),
770
+ ...by === null ? {} : { sortValue: entry.fields?.[by] },
771
+ anchors: sectionAnchors(entry.sections),
772
+ ...metas.get(entry.slug)
705
773
  })) });
706
774
  }
707
- async function getPage(context, slug) {
708
- const loaded = await loadStoredPages(context);
775
+ async function getPage(context, slug, type) {
776
+ const loaded = await loadStoredPages(context, {}, type);
709
777
  if (loaded.response) return loaded.response;
710
778
  const found = loaded.pages.find((entry) => entry.page.slug === slug);
711
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
779
+ if (!found) return problem(404, "not_found", `No ${noun(type)} with slug "${slug}".`);
712
780
  return json(200, found.page);
713
781
  }
714
- async function putPage(request, context, slug) {
782
+ const orphanKey = (section) => `${section.id}:${section.type}`;
783
+ /** The editor may keep an orphaned section the stored document already has, but never add one. */
784
+ function addedOrphans(context, stored, sections) {
785
+ const kept = new Set(stored.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
786
+ return sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !kept.has(orphanKey(section)) ? [{
787
+ path: `sections.${index}.type`,
788
+ message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
789
+ }] : []);
790
+ }
791
+ async function putPage(request, context, slug, type) {
715
792
  const body = await readJsonBody(request);
716
793
  if (body.response) return body.response;
717
- const parsed = validateEditorPage(body.value, context.sections);
794
+ const parsed = validateEntry(context, type, slug, body.value);
718
795
  if (!parsed.success) return validation(fieldIssues(parsed.error));
719
796
  const page = parsed.data;
720
- if (page.slug !== slug) return problem(400, "slug_mismatch", `Slug in the body must be "${slug}". Rename the page with POST /pages/${slug}/rename.`);
797
+ if (page.slug !== slug) return problem(400, "slug_mismatch", `Slug in the body must be "${slug}". Rename the ${noun(type)} with POST ${entryRoute(type, slug)}/rename.`);
721
798
  const missing = await missingAssets(context, page);
722
799
  if (missing.length > 0) return validation(missing);
723
- const loaded = await loadStoredPages(context);
800
+ const loaded = await loadStoredPages(context, {}, type);
724
801
  if (loaded.response) return loaded.response;
725
802
  const found = loaded.pages.find((entry) => entry.page.slug === slug);
726
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
727
- const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
728
- const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
729
- path: `sections.${index}.type`,
730
- message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
731
- }] : []);
803
+ if (!found) return problem(404, "not_found", `No ${noun(type)} with slug "${slug}".`);
804
+ const added = addedOrphans(context, found.page.sections, page.sections);
732
805
  if (added.length > 0) return validation(added);
733
- await history(context).ensureBaseline("page", slug, found.page);
806
+ await history(context).ensureBaseline(...entryHistory(type, slug), found.page);
734
807
  await writeDocuments(context, [[found.key, page]]);
735
- await history(context).write("page", slug, page);
808
+ await history(context).write(...entryHistory(type, slug), page);
736
809
  return json(200, page);
737
810
  }
738
- const orphanKey = (section) => `${section.id}:${section.type}`;
739
- async function createPage(request, baseContext) {
811
+ async function createPage(request, baseContext, type) {
740
812
  const body = await readJsonBody(request);
741
813
  if (body.response) return body.response;
742
814
  const parsed = createPageSchema.safeParse(body.value);
743
815
  if (!parsed.success) return validation(fieldIssues(parsed.error));
744
- const context = scoped(baseContext, `page:${parsed.data.slug}`);
745
- if (isSystemPage(parsed.data.slug)) return problem(409, "reserved_slug", `"${parsed.data.slug}" is a system page and cannot be created.`);
746
- const loaded = await loadStoredPages(context, { allowMissing: true });
816
+ const slug = parsed.data.slug;
817
+ const context = scoped(baseContext, entryScope(type, slug));
818
+ if (isPages(type) && isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be created.`);
819
+ const reserved = reservedSlug(context, type, slug);
820
+ if (reserved) return reserved;
821
+ const loaded = await loadStoredPages(context, { allowMissing: true }, type);
747
822
  if (loaded.response) return loaded.response;
748
- if (loaded.pages.some((entry) => entry.page.slug === parsed.data.slug)) return problem(409, "conflict", `A page with slug "${parsed.data.slug}" already exists.`);
749
- const key = pageKey(parsed.data.slug);
750
- if (await context.store.exists(key)) return problem(409, "conflict", `A file named ${parsed.data.slug}.json already exists.`);
751
- const drafted = draftPage(parsed.data, loaded.pages, context.sections);
823
+ if (loaded.pages.some((entry) => entry.page.slug === slug)) return problem(409, "conflict", `A ${noun(type)} with slug "${slug}" already exists.`);
824
+ const key = entryKey(type, slug);
825
+ if (await context.store.exists(key)) return problem(409, "conflict", `A file named ${slug}.json already exists.`);
826
+ const drafted = draftPage(parsed.data, loaded.pages, context.sections, type);
752
827
  if (drafted.response) return drafted.response;
753
- const validated = validatePage(drafted.page, context.sections);
828
+ const validated = validateEntry(context, type, slug, drafted.page, true);
754
829
  if (!validated.success) return validation(fieldIssues(validated.error));
830
+ const missing = await missingAssets(context, validated.data);
831
+ if (missing.length > 0) return validation(missing);
755
832
  await writeDocuments(context, [[key, validated.data]]);
756
833
  return json(201, validated.data);
757
834
  }
758
- function locked(operation) {
759
- return problem(409, "operation_locked", `${operation === "rename" ? "Renaming pages" : "Deleting pages"} is turned off for this site (pages.${operation} in the bearminion() options).`);
835
+ /** The home page is its own fixed document: no other page can be moved onto its slug. A site without one creates it. */
836
+ function homeIsFixed() {
837
+ return problem(409, "reserved_slug", "The home page is fixed at /. Edit its content instead of moving another page there.");
760
838
  }
761
- async function deletePage(context, slug) {
762
- if (!context.pageRules.delete) return locked("delete");
763
- if (slug === "index") return problem(409, "conflict", "Refusing to delete the index page.");
764
- if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be deleted.`);
765
- const loaded = await loadStoredPages(context);
839
+ function locked(operation, type) {
840
+ const what = operation === "rename" ? "Renaming" : "Deleting";
841
+ return problem(409, "operation_locked", isPages(type) ? `${what} pages is turned off for this site (pages.${operation} in the bearminion() options).` : `${what} entries is turned off for ${type.label} (${operation}: false in its type options).`);
842
+ }
843
+ async function deletePage(context, slug, type) {
844
+ if (!entryRules(context, type).delete) return locked("delete", type);
845
+ if (isPages(type)) {
846
+ if (slug === "index") return problem(409, "conflict", "Refusing to delete the index page.");
847
+ if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be deleted.`);
848
+ }
849
+ const loaded = await loadStoredPages(context, {}, type);
766
850
  if (loaded.response) return loaded.response;
767
851
  const found = loaded.pages.find((entry) => entry.page.slug === slug);
768
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
852
+ if (!found) return problem(404, "not_found", `No ${noun(type)} with slug "${slug}".`);
769
853
  await writeDocuments(context, [], [found.key]);
770
854
  return json(200, {
771
855
  deleted: true,
772
856
  slug
773
857
  });
774
858
  }
775
- /**
776
- * Make `slug` the home page. The current home page moves to `previousSlug`, so the
777
- * site never has two pages at "/" and never loses its home page halfway.
778
- */
779
- async function setHome(request, context, slug) {
780
- const body = await readJsonBody(request);
781
- if (body.response) return body.response;
782
- const parsed = setHomeSchema.safeParse(body.value);
783
- if (!parsed.success) return validation(fieldIssues(parsed.error));
784
- if (!context.pageRules.rename) return locked("rename");
785
- if (slug === "index") return problem(409, "conflict", "That page is already the home page.");
786
- if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be the home page.`);
787
- const loaded = await loadStoredPages(context);
788
- if (loaded.response) return loaded.response;
789
- const target = loaded.pages.find((entry) => entry.page.slug === slug);
790
- if (!target) return problem(404, "not_found", `No page with slug "${slug}".`);
791
- const previous = loaded.pages.find((entry) => entry.page.slug === "index");
792
- const indexKey = pageKey("index");
793
- if (previous) {
794
- const previousSlug = parsed.data.previousSlug;
795
- if (previousSlug === void 0 || previousSlug === "index") return problem(400, "invalid_slug", "previousSlug is required to move the current home page.");
796
- if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`);
797
- const previousKey = pageKey(previousSlug);
798
- if (await context.store.exists(previousKey)) return problem(409, "conflict", `A file named ${previousSlug}.json already exists.`);
799
- const moved = validateEditorPage({
800
- ...previous.page,
801
- slug: previousSlug
802
- }, context.sections);
803
- if (!moved.success) return validation(fieldIssues(moved.error));
804
- const promoted = validateEditorPage({
805
- ...target.page,
806
- slug: "index"
807
- }, context.sections);
808
- if (!promoted.success) return validation(fieldIssues(promoted.error));
809
- await writeDocuments(context, [[previousKey, moved.data], [indexKey, promoted.data]], [...previous.key === indexKey ? [] : [previous.key], target.key]);
810
- return json(200, promoted.data);
811
- }
812
- if (await context.store.exists(indexKey)) return problem(409, "conflict", "A file named index.json already exists.");
813
- const promoted = validateEditorPage({
814
- ...target.page,
815
- slug: "index"
816
- }, context.sections);
817
- if (!promoted.success) return validation(fieldIssues(promoted.error));
818
- await writeDocuments(context, [[indexKey, promoted.data]], [target.key]);
819
- return json(200, promoted.data);
820
- }
821
- async function renamePage(request, context, slug) {
859
+ async function renamePage(request, context, slug, type) {
822
860
  const body = await readJsonBody(request);
823
861
  if (body.response) return body.response;
824
862
  const parsed = renameSchema.safeParse(body.value);
825
863
  if (!parsed.success) return validation(fieldIssues(parsed.error));
826
864
  const nextSlug = parsed.data.slug;
827
- if (!context.pageRules.rename) return locked("rename");
865
+ if (!entryRules(context, type).rename) return locked("rename", type);
828
866
  if (nextSlug === slug) return problem(400, "invalid_slug", "The new slug is the same as the current slug.");
829
- if (slug === "index") return problem(409, "conflict", "Refusing to rename the index page.");
830
- if (isSystemPage(slug) || isSystemPage(nextSlug)) return problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.");
831
- const loaded = await loadStoredPages(context);
867
+ if (isPages(type)) {
868
+ if (slug === "index") return problem(409, "conflict", "Refusing to rename the index page.");
869
+ if (isSystemPage(slug) || isSystemPage(nextSlug)) return problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.");
870
+ if (nextSlug === "index") return homeIsFixed();
871
+ }
872
+ const reserved = reservedSlug(context, type, nextSlug);
873
+ if (reserved) return reserved;
874
+ const loaded = await loadStoredPages(context, {}, type);
832
875
  if (loaded.response) return loaded.response;
833
876
  const found = loaded.pages.find((entry) => entry.page.slug === slug);
834
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
835
- if (loaded.pages.some((entry) => entry.page.slug === nextSlug)) return problem(409, "conflict", `A page with slug "${nextSlug}" already exists.`);
836
- const nextKey = pageKey(nextSlug);
877
+ if (!found) return problem(404, "not_found", `No ${noun(type)} with slug "${slug}".`);
878
+ if (loaded.pages.some((entry) => entry.page.slug === nextSlug)) return problem(409, "conflict", `A ${noun(type)} with slug "${nextSlug}" already exists.`);
879
+ const nextKey = entryKey(type, nextSlug);
837
880
  if (await context.store.exists(nextKey)) return problem(409, "conflict", `A file named ${nextSlug}.json already exists.`);
838
- const renamed = {
881
+ const validated = validateEntry(context, type, nextSlug, {
839
882
  ...found.page,
840
883
  slug: nextSlug
841
- };
842
- const validated = validateEditorPage(renamed, context.sections);
884
+ });
843
885
  if (!validated.success) return validation(fieldIssues(validated.error));
844
886
  await writeDocuments(context, [[nextKey, validated.data]], [found.key]);
845
887
  return json(200, validated.data);
846
888
  }
889
+ const SINGLE_HISTORY = "_single";
890
+ const LISTING_HISTORY = "_listing";
891
+ /** Where a single's undo history is kept. The home and 404 pages share theirs with the pages API. */
892
+ const singleHistory = (type) => type.builtIn ? ["page", type.slug] : ["entry", `${type.id}/${SINGLE_HISTORY}`];
893
+ const emptySeo = (title) => ({
894
+ title,
895
+ description: "",
896
+ noindex: false,
897
+ nofollow: false
898
+ });
899
+ /** What the editor and the API tell about each type: enough to draw its list, its form and its links. */
900
+ function describeTypes(context) {
901
+ const types = typesOf(context);
902
+ const shared = (type) => ({
903
+ id: type.id,
904
+ kind: type.kind,
905
+ label: type.label,
906
+ fields: type.fields ? fieldDefinitions(type.fields) : null,
907
+ sections: type.sections
908
+ });
909
+ return [...types.singles.map((type) => ({
910
+ ...shared(type),
911
+ path: type.path,
912
+ builtIn: type.builtIn
913
+ })), ...types.multi.map((type) => ({
914
+ ...shared(type),
915
+ path: entryPath(type, "{slug}"),
916
+ builtIn: isPages(type),
917
+ sort: type.sort,
918
+ listing: type.listing ? {
919
+ ...type.listing,
920
+ path: listingPath(type)
921
+ } : null,
922
+ rename: entryRules(context, type).rename,
923
+ delete: entryRules(context, type).delete
924
+ }))];
925
+ }
926
+ function singleDocument(context, type) {
927
+ return {
928
+ key: type.key,
929
+ schema: createEntrySchema(context.sections, type, { tolerateOrphans: true }),
930
+ migrateAs: type.id,
931
+ fallback: type.builtIn ? void 0 : {
932
+ slug: type.slug,
933
+ title: type.label,
934
+ seo: emptySeo(type.label),
935
+ sections: [],
936
+ ...type.fields ? { fields: {} } : {}
937
+ },
938
+ history: singleHistory(type)
939
+ };
940
+ }
941
+ function listingDocument(context, type) {
942
+ return {
943
+ key: listingKey(type),
944
+ schema: createListingSchema(context.sections, { tolerateOrphans: true }),
945
+ migrateAs: LISTING_MIGRATION_TYPE,
946
+ fallback: {
947
+ title: type.label,
948
+ seo: emptySeo(type.label),
949
+ sections: []
950
+ },
951
+ history: ["entry", `${type.id}/${LISTING_HISTORY}`]
952
+ };
953
+ }
954
+ async function readDocument(context, target) {
955
+ const text = await context.store.read(target.key);
956
+ if (text === void 0) {
957
+ if (target.fallback === void 0) return { response: problem(404, "not_found", `Content file not found: ${target.key}`) };
958
+ const parsed = target.schema.safeParse(target.fallback);
959
+ return {
960
+ document: parsed.success ? parsed.data : target.fallback,
961
+ stored: null
962
+ };
963
+ }
964
+ let raw;
965
+ try {
966
+ raw = JSON.parse(text);
967
+ } catch (error) {
968
+ return { response: problem(400, "invalid_json", `Invalid JSON in ${target.key}: ${error instanceof Error ? error.message : String(error)}`) };
969
+ }
970
+ const invalid = (issues) => ({ response: json(422, {
971
+ error: "validation",
972
+ message: `Invalid content in ${target.key}.`,
973
+ issues
974
+ }) });
975
+ const upgraded = context.migrator.upgrade(raw, "page", target.migrateAs);
976
+ if (!upgraded.ok) return invalid([{
977
+ path: SCHEMA_VERSION_KEY,
978
+ message: upgraded.message
979
+ }]);
980
+ const parsed = target.schema.safeParse(upgraded.value);
981
+ if (!parsed.success) return invalid(fieldIssues(parsed.error));
982
+ return {
983
+ document: parsed.data,
984
+ stored: parsed.data
985
+ };
986
+ }
987
+ async function getDocument(context, target) {
988
+ const read = await readDocument(context, target);
989
+ return read.response ?? json(200, read.document);
990
+ }
991
+ /** Plan the save of a document that has one fixed place: a single, or a type's listing page. The first save creates the file. */
992
+ async function planFixedSave(context, target, input, slug) {
993
+ const upgraded = context.migrator.upgrade(input, "page", target.migrateAs);
994
+ if (!upgraded.ok) return { issues: [{
995
+ path: SCHEMA_VERSION_KEY,
996
+ message: upgraded.message
997
+ }] };
998
+ const parsed = target.schema.safeParse(upgraded.value);
999
+ if (!parsed.success) return { issues: fieldIssues(parsed.error) };
1000
+ const document = parsed.data;
1001
+ if (slug !== void 0 && document.slug !== slug) return { response: problem(400, "slug_mismatch", `Slug in the body must be "${slug}": this document has a fixed address.`) };
1002
+ const missing = await missingAssets(context, document);
1003
+ if (missing.length > 0) return { issues: missing };
1004
+ const read = await readDocument(context, target);
1005
+ if (read.response) return { response: read.response };
1006
+ const added = addedOrphans(context, read.stored?.sections ?? [], document.sections);
1007
+ if (added.length > 0) return { issues: added };
1008
+ const stored = read.stored;
1009
+ return {
1010
+ page: document,
1011
+ writes: [[target.key, document]],
1012
+ removals: [],
1013
+ after: async () => {
1014
+ if (stored) await history(context).ensureBaseline(...target.history, stored);
1015
+ await history(context).write(...target.history, document);
1016
+ }
1017
+ };
1018
+ }
1019
+ async function putDocument(request, context, target, slug) {
1020
+ const body = await readJsonBody(request);
1021
+ if (body.response) return body.response;
1022
+ const planned = await planFixedSave(context, target, body.value, slug);
1023
+ if (planned.issues) return validation(planned.issues);
1024
+ if (planned.response) return planned.response;
1025
+ await writeDocuments(context, planned.writes);
1026
+ await planned.after();
1027
+ return json(200, planned.page);
1028
+ }
1029
+ /**
1030
+ * The document the address `path` shows, with what it is: `{ type, kind, slug, document }`. The editor opens with it,
1031
+ * so it need not know how addresses map to types. A listing answers the same document for each of its pages. The home
1032
+ * and 404 pages answer as entries of `pages`, where they are stored and edited.
1033
+ */
1034
+ async function getDocumentAt(context, pathname) {
1035
+ const types = typesOf(context);
1036
+ const match = pathname.startsWith("/") ? matchPath(types, pathname) : null;
1037
+ if (match === null) return problem(404, "not_found", `No content at "${pathname}".`);
1038
+ if (match.kind === "listing") {
1039
+ const { type } = match;
1040
+ const read = await readDocument(scoped(context, `${type.id}:${LISTING_HISTORY}`), listingDocument(context, type));
1041
+ if (read.response) return read.response;
1042
+ return json(200, {
1043
+ type: type.id,
1044
+ kind: "listing",
1045
+ slug: type.listing?.slug ?? type.prefix,
1046
+ page: match.page,
1047
+ document: read.document
1048
+ });
1049
+ }
1050
+ if (match.kind === "single" && !match.type.builtIn) {
1051
+ const { type } = match;
1052
+ const read = await readDocument(scoped(context, type.id), singleDocument(context, type));
1053
+ if (read.response) return read.response;
1054
+ return json(200, {
1055
+ type: type.id,
1056
+ kind: "single",
1057
+ slug: type.slug,
1058
+ document: read.document
1059
+ });
1060
+ }
1061
+ const type = match.kind === "entry" ? match.type : types.pages;
1062
+ const slug = match.kind === "entry" ? match.slug : match.type.slug;
1063
+ if (match.kind === "entry" && isPages(type) && slug === "index") return problem(404, "not_found", `No content at "${pathname}".`);
1064
+ const loaded = await loadStoredPages(scoped(context, entryScope(type, slug)), {}, type);
1065
+ if (loaded.response) return loaded.response;
1066
+ const found = loaded.pages.find((entry) => entry.page.slug === slug);
1067
+ if (!found) return problem(404, "not_found", `No ${noun(type)} with slug "${slug}".`);
1068
+ return json(200, {
1069
+ type: type.id,
1070
+ kind: "entry",
1071
+ slug,
1072
+ document: found.page
1073
+ });
1074
+ }
1075
+ /**
1076
+ * `/types`, `/types/<id>/document` (a single), `/types/<id>/listing`, `/types/<id>/entries`,
1077
+ * `/types/<id>/entries/<slug>` and `.../rename`. `/pages` is the same as `/types/pages/entries`, plus the home and 404 pages.
1078
+ */
1079
+ async function typeRoute(request, context, parts, method) {
1080
+ if (parts.length === 0) {
1081
+ if (method !== "GET") return methodNotAllowed(["GET"]);
1082
+ return json(200, { types: describeTypes(context) });
1083
+ }
1084
+ const type = typesOf(context).get(decodeSegment(parts[0] ?? ""));
1085
+ if (!type) return problem(404, "not_found", "Unknown content type.");
1086
+ if (type.kind === "single") {
1087
+ if (parts.length !== 2 || parts[1] !== "document") return problem(404, "not_found", "Unknown editor API route.");
1088
+ const entry = scoped(context, type.builtIn ? `page:${type.slug}` : type.id);
1089
+ const target = singleDocument(entry, type);
1090
+ if (method === "GET") return getDocument(entry, target);
1091
+ if (method === "PUT") return putDocument(request, entry, target, type.slug);
1092
+ return methodNotAllowed(["GET", "PUT"]);
1093
+ }
1094
+ if (parts.length === 2 && parts[1] === "listing") {
1095
+ if (!type.listing) return problem(404, "not_found", `${type.label} has no listing page (listing in its type options).`);
1096
+ const entry = scoped(context, `${type.id}:${LISTING_HISTORY}`);
1097
+ const target = listingDocument(entry, type);
1098
+ if (method === "GET") return getDocument(entry, target);
1099
+ if (method === "PUT") return putDocument(request, entry, target);
1100
+ return methodNotAllowed(["GET", "PUT"]);
1101
+ }
1102
+ if (parts[1] !== "entries") return problem(404, "not_found", "Unknown editor API route.");
1103
+ if (parts.length === 2) {
1104
+ if (method === "GET") return getEntries(context, type);
1105
+ if (method === "POST") return createPage(request, context, type);
1106
+ return methodNotAllowed(["GET", "POST"]);
1107
+ }
1108
+ const slug = readSlug(parts[2] ?? "");
1109
+ if (slug === null) return badSlug();
1110
+ const entry = scoped(context, entryScope(type, slug));
1111
+ if (parts.length === 3) {
1112
+ if (method === "GET") return getPage(entry, slug, type);
1113
+ if (method === "PUT") return putPage(request, entry, slug, type);
1114
+ if (method === "DELETE") return deletePage(entry, slug, type);
1115
+ return methodNotAllowed([
1116
+ "GET",
1117
+ "PUT",
1118
+ "DELETE"
1119
+ ]);
1120
+ }
1121
+ if (parts.length === 4 && parts[3] === "rename") {
1122
+ if (method === "POST") return renamePage(request, entry, slug, type);
1123
+ return methodNotAllowed(["POST"]);
1124
+ }
1125
+ return problem(404, "not_found", "Unknown editor API route.");
1126
+ }
847
1127
  const previewBodySchema = z.object({
848
1128
  page: z.unknown(),
1129
+ /** The id of the document's content type. Default `pages`. */
1130
+ type: z.string().optional(),
849
1131
  motion: z.boolean().optional()
850
1132
  }).strict();
851
1133
  async function postPreview(request, context, meta) {
@@ -854,7 +1136,9 @@ async function postPreview(request, context, meta) {
854
1136
  if (body.response) return body.response;
855
1137
  const payload = previewBodySchema.safeParse(body.value);
856
1138
  if (!payload.success) return validation(fieldIssues(payload.error));
857
- const parsed = validateEditorPage(payload.data.page, context.sections);
1139
+ const type = payload.data.type === void 0 ? null : typesOf(context).get(payload.data.type);
1140
+ if (type === void 0) return problem(404, "not_found", `Unknown content type "${payload.data.type}".`);
1141
+ const parsed = type ? createEntrySchema(context.sections, type, { tolerateOrphans: true }).safeParse(payload.data.page) : validateEditorPage(payload.data.page, context.sections);
858
1142
  if (!parsed.success) return validation(fieldIssues(parsed.error));
859
1143
  const renderable = withoutOrphanSections(parsed.data, context.sections);
860
1144
  try {
@@ -887,13 +1171,23 @@ async function postSitePreview(request, context, meta) {
887
1171
  return problem(500, "preview_failed", message);
888
1172
  }
889
1173
  }
890
- async function getImages(context) {
1174
+ /** The uploaded images and the upload rules. With `?usage=1`, each image also says where the saved content uses it. */
1175
+ async function getImages(context, withUsage = false) {
891
1176
  const limits = {
892
1177
  maxBytes: context.maxImageBytes,
893
1178
  convert: context.imageConvert
894
1179
  };
1180
+ const images = await context.store.uploads.list();
1181
+ if (!withUsage) return json(200, {
1182
+ images,
1183
+ limits
1184
+ });
1185
+ const usages = await allImageUsages(context);
895
1186
  return json(200, {
896
- images: await context.store.uploads.list(),
1187
+ images: images.map((image) => ({
1188
+ ...image,
1189
+ usages: usages.get(image.path) ?? []
1190
+ })),
897
1191
  limits
898
1192
  });
899
1193
  }
@@ -911,22 +1205,43 @@ async function missingAssets(context, document) {
911
1205
  return missingAssetIssues(document, (src) => store.assetExists?.(src) ?? Promise.resolve(true));
912
1206
  }
913
1207
  /**
1208
+ * Every stored document that is drawn as a page, read raw so one that fails validation still counts: the entries and
1209
+ * the listing page of each type, and the singles the site declares. The home and 404 pages are among the pages.
1210
+ */
1211
+ async function storedDocuments(context) {
1212
+ const types = typesOf(context);
1213
+ const keys = [];
1214
+ for (const type of types.multi) for (const file of await context.store.list(type.dir) ?? []) if (file.endsWith(".json") && !file.startsWith(".")) keys.push([`${type.dir}/${file}`, file.replace(/\.json$/, "")]);
1215
+ for (const type of types.singles) if (!type.builtIn) keys.push([type.key, type.label]);
1216
+ const found = [];
1217
+ for (const [key, name] of keys) {
1218
+ const document = await readStoredJson(context, key, "page");
1219
+ if (typeof document === "object" && document !== null) found.push({
1220
+ name,
1221
+ document
1222
+ });
1223
+ }
1224
+ return found;
1225
+ }
1226
+ /**
914
1227
  * Where the saved content uses the image at `src`: "Home page › Hero", "Site settings › brand logo". Read from the
915
1228
  * raw files, so a page that fails validation still counts. Unsaved drafts are not on disk: the editor checks its own
916
1229
  * drafts before it asks to delete, and saving a draft that still points at a deleted image fails validation.
917
1230
  */
918
1231
  async function imageUsages(context, src) {
1232
+ return (await allImageUsages(context)).get(src) ?? [];
1233
+ }
1234
+ /** Every image the saved content uses, with where: one pass over the files instead of one per image. */
1235
+ async function allImageUsages(context) {
919
1236
  const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
920
- const usages = [];
1237
+ const usages = /* @__PURE__ */ new Map();
1238
+ const add = (src, where) => usages.set(src, [...usages.get(src) ?? [], where]);
921
1239
  const site = await readStoredJson(context, SITE_KEY, "site");
922
- for (const ref of assetRefs(site)) if (ref.src === src) usages.push(describeSiteRef(ref));
923
- for (const name of await context.store.list("pages") ?? []) {
924
- if (!name.endsWith(".json") || name.startsWith(".")) continue;
925
- const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
926
- if (typeof page !== "object" || page === null) continue;
927
- const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
1240
+ for (const ref of assetRefs(site)) add(ref.src, describeSiteRef(ref));
1241
+ for (const { name, document: page } of await storedDocuments(context)) {
1242
+ const title = "title" in page && typeof page.title === "string" ? page.title : name;
928
1243
  const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
929
- for (const ref of assetRefs(page)) if (ref.src === src) usages.push(describePageRef(ref, {
1244
+ for (const ref of assetRefs(page)) add(ref.src, describePageRef(ref, {
930
1245
  title,
931
1246
  sections
932
1247
  }, labels));
@@ -970,13 +1285,11 @@ async function videoUsages(context, url) {
970
1285
  const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
971
1286
  const usages = [];
972
1287
  if ([...strings(await readStoredJson(context, "site.json", "site"))].includes(url)) usages.push("Site settings");
973
- for (const name of await context.store.list("pages") ?? []) {
974
- if (!name.endsWith(".json") || name.startsWith(".")) continue;
975
- const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
976
- if (typeof page !== "object" || page === null) continue;
977
- const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
1288
+ for (const { name, document: page } of await storedDocuments(context)) {
1289
+ const title = "title" in page && typeof page.title === "string" ? page.title : name;
978
1290
  const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
979
1291
  for (const section of sections) if ([...strings(section)].includes(url)) usages.push(`${title} › ${labels[section.type ?? ""] ?? section.type ?? "section"}`);
1292
+ if ("fields" in page && [...strings(page.fields)].includes(url)) usages.push(`${title} › fields`);
980
1293
  }
981
1294
  return usages;
982
1295
  }
@@ -1062,7 +1375,11 @@ async function postImage(request, context) {
1062
1375
  const createPageSchema = z.object({
1063
1376
  slug: z.string(),
1064
1377
  title: z.string(),
1065
- template: z.string().min(1).optional()
1378
+ template: z.string().min(1).optional(),
1379
+ /** The entry's own fields, for a type that declares them. */
1380
+ fields: z.record(z.string(), z.unknown()).optional(),
1381
+ /** `draft` starts the entry as a draft. Absent: published, as before. */
1382
+ status: z.enum(["published", "draft"]).optional()
1066
1383
  }).strict().superRefine((value, ctx) => {
1067
1384
  if (readSlug(value.slug) === null) ctx.addIssue({
1068
1385
  code: "custom",
@@ -1075,15 +1392,6 @@ const createPageSchema = z.object({
1075
1392
  path: ["title"]
1076
1393
  });
1077
1394
  });
1078
- const setHomeSchema = z.object({
1079
- /** Slug the current home page moves to. Required when a home page exists. */
1080
- previousSlug: z.string().optional() }).strict().superRefine((value, ctx) => {
1081
- if (value.previousSlug !== void 0 && readSlug(value.previousSlug) === null) ctx.addIssue({
1082
- code: "custom",
1083
- message: "Slug must be lowercase kebab-case",
1084
- path: ["previousSlug"]
1085
- });
1086
- });
1087
1395
  const renameSchema = z.object({ slug: z.string() }).strict().superRefine((value, ctx) => {
1088
1396
  if (readSlug(value.slug) === null) ctx.addIssue({
1089
1397
  code: "custom",
@@ -1108,7 +1416,7 @@ function pageFromSection(slug, title, seo, definition) {
1108
1416
  sections: [section]
1109
1417
  };
1110
1418
  }
1111
- function draftPage(input, pages, registry) {
1419
+ function draftPage(input, pages, registry, type) {
1112
1420
  const slug = readSlug(input.slug);
1113
1421
  if (slug === null) return { response: badSlug() };
1114
1422
  const seo = {
@@ -1117,41 +1425,77 @@ function draftPage(input, pages, registry) {
1117
1425
  noindex: false,
1118
1426
  nofollow: false
1119
1427
  };
1428
+ const status = input.status === "draft" ? { status: "draft" } : {};
1429
+ const fields = type.fields || input.fields ? { fields: {
1430
+ ...type.fields ? starterFields(type.fields) : {},
1431
+ ...input.fields
1432
+ } } : {};
1433
+ const allowed = (name) => type.sections === null || type.sections.includes(name);
1434
+ const drafted = (definition) => ({
1435
+ ...pageFromSection(slug, input.title, seo, definition),
1436
+ ...status,
1437
+ ...fields
1438
+ });
1120
1439
  if (input.template === void 0) {
1121
- const definition = registry.hero ?? Object.values(registry)[0];
1440
+ const definition = (registry.hero && allowed("hero") ? registry.hero : void 0) ?? Object.values(registry).find((item) => allowed(item.type));
1122
1441
  if (!definition) return { response: problem(400, "unknown_template", "No section types are registered.") };
1123
- return { page: pageFromSection(slug, input.title, seo, definition) };
1442
+ return { page: drafted(definition) };
1124
1443
  }
1125
1444
  const definition = registry[input.template];
1126
- if (definition) return { page: pageFromSection(slug, input.title, seo, definition) };
1445
+ if (definition) {
1446
+ if (!allowed(definition.type)) return { response: problem(400, "unknown_template", `Section type "${definition.type}" is not allowed in ${type.label}. Allowed: ${(type.sections ?? []).join(", ")}.`) };
1447
+ return { page: drafted(definition) };
1448
+ }
1127
1449
  const source = pages.find((entry) => entry.page.slug === input.template);
1128
- if (!source) return { response: problem(400, "unknown_template", `Unknown template "${input.template}". Use a section type or an existing page slug.`) };
1450
+ if (!source) return { response: problem(400, "unknown_template", `Unknown template "${input.template}". Use a section type or an existing ${noun(type)} slug.`) };
1129
1451
  return { page: {
1130
1452
  slug,
1131
1453
  title: input.title,
1454
+ ...status,
1132
1455
  seo,
1133
- sections: structuredClone(source.page.sections)
1456
+ sections: structuredClone(source.page.sections),
1457
+ ...input.fields === void 0 && source.page.fields ? { fields: structuredClone(source.page.fields) } : fields
1134
1458
  } };
1135
1459
  }
1460
+ /**
1461
+ * A first value for each required field that has no default of its own: today for a date, the first choice of an
1462
+ * enum, and the empty value of anything else simple. A field this cannot fill is left out, and validation names it.
1463
+ */
1464
+ function starterFields(schema) {
1465
+ const starter = {};
1466
+ for (const field of fieldDefinitions(schema) ?? []) {
1467
+ const described = field.schema;
1468
+ if (!field.required || described === null || "default" in described) continue;
1469
+ const choices = described.enum;
1470
+ if (Array.isArray(choices) && choices.length > 0) starter[field.name] = choices[0];
1471
+ else if (described.type === "string") {
1472
+ const today = (/* @__PURE__ */ new Date()).toISOString();
1473
+ starter[field.name] = described.format === "date" ? today.slice(0, 10) : described.format === "date-time" ? today : "";
1474
+ } else if (described.type === "number" || described.type === "integer") starter[field.name] = 0;
1475
+ else if (described.type === "boolean") starter[field.name] = false;
1476
+ else if (described.type === "array") starter[field.name] = [];
1477
+ }
1478
+ return starter;
1479
+ }
1136
1480
  function sectionId(type) {
1137
1481
  return type.replace(/[^A-Za-z0-9_-]+/g, "") || "section";
1138
1482
  }
1139
- async function loadStoredPages(context, options = {}) {
1483
+ async function loadStoredPages(context, options = {}, type = typesOf(context).pages) {
1140
1484
  let listed;
1141
1485
  try {
1142
- listed = await context.store.list(PAGES_DIR);
1486
+ listed = await context.store.list(type.dir);
1143
1487
  } catch (error) {
1144
1488
  return { response: contentFailure(error) };
1145
1489
  }
1146
1490
  if (listed === void 0) {
1147
- if (options.allowMissing) return { pages: [] };
1148
- return { response: problem(404, "not_found", `Pages directory not found: ${PAGES_DIR}`) };
1491
+ if (options.allowMissing || !isPages(type)) return { pages: [] };
1492
+ return { response: problem(404, "not_found", `Pages directory not found: ${type.dir}`) };
1149
1493
  }
1150
- const names = listed.filter((name) => name.endsWith(".json") && !name.startsWith("."));
1494
+ const names = listed.filter((name) => name.endsWith(".json") && !name.startsWith(".") && !name.startsWith("_"));
1151
1495
  const pages = [];
1152
1496
  const seen = /* @__PURE__ */ new Map();
1153
1497
  for (const name of names) {
1154
- const key = `${PAGES_DIR}/${name}`;
1498
+ const key = `${type.dir}/${name}`;
1155
1499
  let raw;
1156
1500
  try {
1157
1501
  raw = JSON.parse(await context.store.read(key) ?? "");
@@ -1160,7 +1504,8 @@ async function loadStoredPages(context, options = {}) {
1160
1504
  if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
1161
1505
  return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
1162
1506
  }
1163
- const upgraded = context.migrator.upgrade(raw, "page");
1507
+ const rawSlug = typeof raw === "object" && raw !== null && "slug" in raw && typeof raw.slug === "string" ? raw.slug : "";
1508
+ const upgraded = context.migrator.upgrade(raw, "page", documentType(context, type, rawSlug).id);
1164
1509
  if (!upgraded.ok) return { response: json(422, {
1165
1510
  error: "validation",
1166
1511
  message: `Invalid content in ${name}.`,
@@ -1169,7 +1514,7 @@ async function loadStoredPages(context, options = {}) {
1169
1514
  message: upgraded.message
1170
1515
  }]
1171
1516
  }) };
1172
- const parsed = validateEditorPage(upgraded.value, context.sections);
1517
+ const parsed = validateEntry(context, type, rawSlug, upgraded.value);
1173
1518
  if (!parsed.success) return { response: json(422, {
1174
1519
  error: "validation",
1175
1520
  message: `Invalid content in ${name}.`,