bearminion 1.14.0 → 1.16.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.
package/dist/astro.js CHANGED
@@ -1,14 +1,15 @@
1
- import { a as imageFields, c as ContentReadError, l as ContentValidationError, r as loadThemePreview, t as PreviewUnavailableError } from "./preview-ImEm3T8k.js";
1
+ import { D as ContentReadError, O as ContentValidationError, S as loadThemePreview, _ as parseKey, b as PreviewUnavailableError, c as resolveCollections, v as StoreError, y as StoreKeyError } from "./collections-BbL4_4jt.js";
2
2
  import { t as defaultTheme } from "./theme-BvqJ8UnS.js";
3
- import { a as resolvePageRules, c as withoutOrphanSections, d as isOrphanSection, i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
4
- import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
3
+ import { a as resolvePageRules, n as createPageSchema, r as createTolerantPageSchema } from "./page-wlcQJAA-.js";
4
+ import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
5
5
  import { i as resolveMaxImageBytes, n as formatBytes, r as resolveConvert } from "./upload-rules-Cao9uY5K.js";
6
- import { a as isLocalRequest, c as resolveInside, i as isInside, n as JSON_BODY_LIMIT, o as readSlug, r as asDirectory, s as resolveDir, t as IMAGE_BYTE_LIMIT } from "./security-FLvgc2jD.js";
7
- import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CEab55ss.js";
8
- import { S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-1Y4-sn45.js";
9
- import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-BIIa7pej.js";
6
+ import { n as isLocalRequest, t as JSON_BODY_LIMIT } from "./request-guards-BcSUj8Gc.js";
7
+ import { i as resolveInside, n as isInside, r as resolveDir, t as asDirectory } from "./security-CBiOYdVE.js";
8
+ import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CzUHR7oS.js";
9
+ import { a as COMMIT_MESSAGE_LIMIT, c as IMAGE_EXTENSION, f as videoBodyLimit, i as isHistoryId, l as uploadStem, n as handleEditorRequest, o as GitError, r as historyId, s as imageBodyLimit, t as githubStore, u as stableStringify } from "./github-store-DUf07ODw.js";
10
+ import { S as isAssetPath } from "./draft-store-DBEfw_Gq.js";
11
+ import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-BzVw721A.js";
10
12
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
11
- import { z } from "zod";
12
13
  import fs from "node:fs";
13
14
  import path from "node:path";
14
15
  import { fileURLToPath } from "node:url";
@@ -17,8 +18,8 @@ import { randomBytes } from "node:crypto";
17
18
  import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
18
19
  import { execFile } from "node:child_process";
19
20
  //#region src/editor-client.ts
20
- const VIRTUAL_ID = "virtual:bearminion-editor";
21
- const RESOLVED_ID = `\0${VIRTUAL_ID}`;
21
+ const VIRTUAL_ID$1 = "virtual:bearminion-editor";
22
+ const RESOLVED_ID$1 = `\0${VIRTUAL_ID$1}`;
22
23
  /**
23
24
  * Serves the editor overlay only while Vite is in serve mode.
24
25
  * `astro build` never adds this plugin, so the client is absent from production.
@@ -30,10 +31,10 @@ function editorClientPlugin() {
30
31
  name: "bearminion-editor-client",
31
32
  apply: "serve",
32
33
  resolveId(id) {
33
- if (id === VIRTUAL_ID) return RESOLVED_ID;
34
+ if (id === VIRTUAL_ID$1) return RESOLVED_ID$1;
34
35
  },
35
36
  load(id) {
36
- if (id !== RESOLVED_ID) return void 0;
37
+ if (id !== RESOLVED_ID$1) return void 0;
37
38
  return `import { mountEditor } from ${JSON.stringify(entry)};\nmountEditor();\n`;
38
39
  }
39
40
  };
@@ -46,32 +47,6 @@ const EXTENSION = {
46
47
  webm: ".webm",
47
48
  ogv: ".ogv"
48
49
  };
49
- const MIME_TO_KIND$1 = {
50
- "video/mp4": "mp4",
51
- "video/x-m4v": "mp4",
52
- "video/quicktime": "mov",
53
- "video/webm": "webm",
54
- "video/ogg": "ogv"
55
- };
56
- /** Room for multipart boundaries around a max-size video. */
57
- function videoBodyLimit(maxVideoBytes) {
58
- return maxVideoBytes + 262144;
59
- }
60
- /** The container a file really is, from its first bytes. The file's name and declared type are not trusted. */
61
- function sniffVideo(bytes) {
62
- if (bytes.length >= 12 && ascii$1(bytes, 4, 8) === "ftyp") {
63
- const brand = ascii$1(bytes, 8, 12);
64
- if (brand === "avif" || brand === "avis") return null;
65
- return brand === "qt " ? "mov" : "mp4";
66
- }
67
- if (bytes.length >= 4 && bytes[0] === 26 && bytes[1] === 69 && bytes[2] === 223 && bytes[3] === 163) return ascii$1(bytes, 0, Math.min(bytes.length, 64)).includes("webm") ? "webm" : null;
68
- if (bytes.length >= 4 && ascii$1(bytes, 0, 4) === "OggS") return "ogv";
69
- return null;
70
- }
71
- function videoKindFromMime(mime) {
72
- const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
73
- return MIME_TO_KIND$1[base] ?? null;
74
- }
75
50
  /** The address a file in `public/` is served at. */
76
51
  function publicUrl(root, filePath) {
77
52
  return `/${path.relative(path.resolve(root, "public"), filePath).split(path.sep).join("/")}`;
@@ -141,9 +116,6 @@ async function deleteVideo(videosDir, filename) {
141
116
  function safeStem(originalName) {
142
117
  return path.win32.basename(path.basename(originalName)).replace(/\.[^.]+$/, "").normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "video";
143
118
  }
144
- function ascii$1(bytes, from, to) {
145
- return Buffer.from(bytes.subarray(from, to)).toString("latin1");
146
- }
147
119
  //#endregion
148
120
  //#region src/asset-refs.ts
149
121
  /**
@@ -155,34 +127,6 @@ function assetFile(root, uploadsDir, src) {
155
127
  const absolute = path.resolve(root, src);
156
128
  return isInside(path.resolve(root, "src/assets"), absolute) || isInside(uploadsDir, absolute) ? absolute : null;
157
129
  }
158
- /** One validation issue per image path in `document` whose file does not exist. */
159
- async function missingAssetIssues(document, exists) {
160
- const refs = assetRefs(document);
161
- const present = await Promise.all(refs.map((ref) => exists(ref.src)));
162
- return refs.flatMap((ref, index) => present[index] ? [] : [{
163
- path: ref.path,
164
- message: `Image file not found: ${ref.src}. Choose another image or upload it again.`
165
- }]);
166
- }
167
- //#endregion
168
- //#region src/stable-json.ts
169
- /**
170
- * Pretty JSON with sorted object keys and a trailing newline.
171
- * Arrays keep their order. Two writes of the same value match byte for byte.
172
- */
173
- function stableStringify(value) {
174
- return `${JSON.stringify(sortKeys(value), null, 2)}\n`;
175
- }
176
- function sortKeys(value) {
177
- if (Array.isArray(value)) return value.map((item) => sortKeys(item));
178
- if (value !== null && typeof value === "object") {
179
- const source = value;
180
- const sorted = {};
181
- for (const key of Object.keys(source).sort()) sorted[key] = sortKeys(source[key]);
182
- return sorted;
183
- }
184
- return value;
185
- }
186
130
  //#endregion
187
131
  //#region src/atomic-write.ts
188
132
  /**
@@ -206,66 +150,7 @@ function writeJsonAtomic(filePath, value) {
206
150
  return writeTextAtomic(filePath, stableStringify(value));
207
151
  }
208
152
  //#endregion
209
- //#region src/upload-names.ts
210
- const IMAGE_EXTENSION = {
211
- png: ".png",
212
- jpeg: ".jpg",
213
- webp: ".webp",
214
- gif: ".gif",
215
- avif: ".avif"
216
- };
217
- const EXTENSIONS = Object.values(IMAGE_EXTENSION);
218
- /** True for a file name with an image extension the editor handles. */
219
- function hasImageExtension(name) {
220
- const dot = name.lastIndexOf(".");
221
- return dot > 0 && EXTENSIONS.includes(name.slice(dot).toLowerCase());
222
- }
223
- /** A plain image file name: no folders, no leading dot, an extension the editor handles. */
224
- function isUploadFilename(name) {
225
- return name !== "" && !name.includes("/") && !name.includes("\\") && !name.startsWith(".") && hasImageExtension(name);
226
- }
227
- /** The readable part of an upload's name: the original file name, lowercase ASCII, at most 48 characters. */
228
- const PLAIN_LETTERS = {
229
- ł: "l",
230
- đ: "d",
231
- ø: "o",
232
- ð: "d",
233
- þ: "th",
234
- ß: "ss",
235
- æ: "ae",
236
- œ: "oe",
237
- ı: "i"
238
- };
239
- function uploadStem(originalName) {
240
- return (originalName.split(/[\\/]/).pop() ?? "").replace(/\.[^.]+$/, "").normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase().replace(/[łđøðþßæœı]/g, (letter) => PLAIN_LETTERS[letter] ?? letter).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "image";
241
- }
242
- /** `photo-1a2b3c4d.jpg`: the stem, eight random hex digits, the extension for the sniffed kind. */
243
- function uploadFilename(originalName, kind) {
244
- const random = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(4));
245
- const suffix = Array.from(random, (byte) => byte.toString(16).padStart(2, "0")).join("");
246
- return `${uploadStem(originalName)}-${suffix}${IMAGE_EXTENSION[kind]}`;
247
- }
248
- //#endregion
249
153
  //#region src/images.ts
250
- const MIME_TO_KIND = {
251
- "image/png": "png",
252
- "image/jpeg": "jpeg",
253
- "image/webp": "webp",
254
- "image/gif": "gif",
255
- "image/avif": "avif"
256
- };
257
- function sniffImage(bytes) {
258
- if (isPng(bytes)) return "png";
259
- if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpeg";
260
- if (isGif(bytes)) return "gif";
261
- if (isWebp(bytes)) return "webp";
262
- if (isAvif(bytes)) return "avif";
263
- return null;
264
- }
265
- function kindFromMime(mime) {
266
- const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
267
- return MIME_TO_KIND[base] ?? null;
268
- }
269
154
  /** Write image bytes under `uploadsDir` using a sniffed extension and a unique name. */
270
155
  async function saveImage(options) {
271
156
  await mkdir(options.uploadsDir, { recursive: true });
@@ -329,80 +214,21 @@ async function deleteImage(uploadsDir, filename) {
329
214
  return false;
330
215
  }
331
216
  }
332
- function imageTooLarge(size, maxBytes = IMAGE_BYTE_LIMIT) {
333
- return size > maxBytes;
334
- }
335
- /** The largest request body an image upload may have: the file plus room for the multipart boundaries. */
336
- function imageBodyLimit(maxBytes) {
337
- return maxBytes + 262144;
338
- }
339
217
  function projectRelative(root, filePath) {
340
218
  const relative = path.relative(root, filePath);
341
219
  if (!isInside(root, filePath)) throw new Error("Upload path is outside the project root.");
342
220
  return relative.split(path.sep).join("/");
343
221
  }
344
- function isPng(bytes) {
345
- return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10;
346
- }
347
- function isGif(bytes) {
348
- if (bytes.length < 6) return false;
349
- const header = ascii(bytes.subarray(0, 6));
350
- return header === "GIF87a" || header === "GIF89a";
351
- }
352
- function isWebp(bytes) {
353
- return bytes.length >= 12 && ascii(bytes.subarray(0, 4)) === "RIFF" && ascii(bytes.subarray(8, 12)) === "WEBP";
354
- }
355
- function isAvif(bytes) {
356
- if (bytes.length < 12 || ascii(bytes.subarray(4, 8)) !== "ftyp") return false;
357
- const brand = ascii(bytes.subarray(8, 12));
358
- if (brand === "avif" || brand === "avis") return true;
359
- return ascii(bytes.subarray(16)).includes("avif") || ascii(bytes.subarray(16)).includes("avis");
360
- }
361
- function ascii(bytes) {
362
- const sample = bytes.byteLength > 64 ? bytes.subarray(0, 64) : bytes;
363
- return Buffer.from(sample).toString("ascii");
364
- }
365
222
  function isErrno$2(error) {
366
223
  return error instanceof Error && "code" in error;
367
224
  }
368
225
  //#endregion
369
- //#region src/store-error.ts
370
- /** A key that is empty, absolute or leaves the content directory. */
371
- var StoreKeyError = class extends Error {
372
- constructor(key) {
373
- super(`"${key}" is not a path inside the content directory.`);
374
- this.name = "StoreKeyError";
375
- }
376
- };
377
- /**
378
- * A store that could not do what was asked, for a reason the person editing can act on (a refused token, a protected
379
- * branch, a branch that moved). The editor API answers it with `status` and `code`, so the message reaches the page
380
- * instead of becoming a bare 500.
381
- */
382
- var StoreError = class extends Error {
383
- status;
384
- code;
385
- constructor(status, code, message) {
386
- super(message);
387
- this.name = "StoreError";
388
- this.status = status;
389
- this.code = code;
390
- }
391
- };
392
- //#endregion
393
226
  //#region src/store.ts
394
- const SITE_KEY = "site.json";
395
- const PAGES_DIR = "pages";
396
- /** The key of the page with this slug. The slug must already be validated (`readSlug`). */
397
- function pageKey(slug) {
398
- return `${PAGES_DIR}/${slug}.json`;
399
- }
400
227
  /** The content store for a local project: content as JSON files, uploads in a folder. */
401
228
  function createFileStore({ root, contentDir, uploadsDir, videosDir }) {
402
229
  function resolve(key) {
403
- const parts = key.split("/");
404
- if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
405
- const resolved = resolveInside(contentDir, ...parts);
230
+ const { base, parts } = parseKey(key);
231
+ const resolved = resolveInside(base === "root" ? root : contentDir, ...parts);
406
232
  if (resolved === null) throw new StoreKeyError(key);
407
233
  return resolved;
408
234
  }
@@ -477,143 +303,8 @@ function isErrno$1(error) {
477
303
  return error instanceof Error && "code" in error;
478
304
  }
479
305
  //#endregion
480
- //#region src/options.ts
481
- function resolveEditorContext(options, rootInput) {
482
- if (!options?.sections) throw new Error("bearminion() needs the `sections` option: the site's section definitions.");
483
- if (!options.site) throw new Error("bearminion() needs the `site` option: the site's header and footer definition from defineSite().");
484
- const root = asDirectory(rootInput);
485
- const contentDir = resolveDir(root, options?.contentDir, DEFAULT_CONTENT_DIR);
486
- const uploadsDir = resolveDir(root, options?.uploadsDir, DEFAULT_UPLOADS_DIR);
487
- const videosDir = resolveDir(root, options?.videosDir, DEFAULT_VIDEOS_DIR);
488
- return {
489
- root,
490
- contentDir,
491
- uploadsDir,
492
- videosDir,
493
- maxVideoBytes: options?.maxVideoBytes ?? 52428800,
494
- maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
495
- pageRules: resolvePageRules(options?.pages),
496
- imageConvert: resolveConvert(options?.imageConvert),
497
- sections: options.sections,
498
- site: options.site,
499
- theme: options.theme ?? defaultTheme,
500
- store: options.store ?? createFileStore({
501
- root,
502
- contentDir,
503
- uploadsDir,
504
- videosDir
505
- }),
506
- migrator: createMigrator(options),
507
- git: options?.git === true,
508
- formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
509
- };
510
- }
511
- //#endregion
512
- //#region src/history.ts
513
- /**
514
- * Local copies of what was saved, in `<project>/.editor/history/`, so an earlier version of a page or of the
515
- * site can be loaded back into the draft. Dev-only and untracked: the folder belongs in `.gitignore`.
516
- */
517
- const HISTORY_DIR = ".editor/history";
518
- const ID = /^\d{8}T\d{9}Z$/;
519
- function isHistoryId(value) {
520
- return ID.test(value);
521
- }
522
- /** `2026-10-13T12:55:30.123Z` → `20261013T125530123Z`. */
523
- function historyId(date) {
524
- return date.toISOString().replace(/[-:.]/g, "");
525
- }
526
- function idToIso(id) {
527
- return `${id.slice(0, 4)}-${id.slice(4, 6)}-${id.slice(6, 8)}T${id.slice(9, 11)}:${id.slice(11, 13)}:${id.slice(13, 15)}.${id.slice(15, 18)}Z`;
528
- }
529
- function directory(context, scope, slug) {
530
- return scope === "site" ? path.join(context.root, HISTORY_DIR, "site") : path.join(context.root, HISTORY_DIR, "pages", slug);
531
- }
532
- async function ids(dir) {
533
- try {
534
- return (await readdir(dir)).filter((name) => name.endsWith(".json") && isHistoryId(name.slice(0, -5))).map((name) => name.slice(0, -5)).sort();
535
- } catch {
536
- return [];
537
- }
538
- }
539
- /** Newest first. */
540
- async function listHistory(context, scope, slug = "") {
541
- return (await ids(directory(context, scope, slug))).reverse().map((id) => ({
542
- id,
543
- at: idToIso(id)
544
- }));
545
- }
546
- async function readHistory(context, scope, slug, id) {
547
- if (!isHistoryId(id)) return null;
548
- try {
549
- return JSON.parse(await readFile(path.join(directory(context, scope, slug), `${id}.json`), "utf8"));
550
- } catch {
551
- return null;
552
- }
553
- }
554
- /**
555
- * Keep a copy of `value`. A value equal to the newest copy is skipped, and only the newest {@link HISTORY_KEEP}
556
- * copies stay. Returns the new entry, or null when nothing was written. Never throws: history must not block a save.
557
- */
558
- async function writeHistory(context, scope, slug, value, now = /* @__PURE__ */ new Date()) {
559
- try {
560
- const dir = directory(context, scope, slug);
561
- const existing = await ids(dir);
562
- const newest = existing[existing.length - 1];
563
- if (newest !== void 0) {
564
- if (await readFile(path.join(dir, `${newest}.json`), "utf8") === stableStringify(value)) return null;
565
- }
566
- let id = historyId(now);
567
- while (existing.includes(id)) id = historyId(new Date(Date.parse(idToIso(id)) + 1));
568
- await writeJsonAtomic(path.join(dir, `${id}.json`), value);
569
- for (const old of [...existing, id].slice(0, -50)) await rm(path.join(dir, `${old}.json`), { force: true });
570
- return {
571
- id,
572
- at: idToIso(id)
573
- };
574
- } catch {
575
- return null;
576
- }
577
- }
578
- /** Before the first save of a page or the site, keep the file as it was so even that first save can be undone. */
579
- async function ensureBaseline(context, scope, slug, current) {
580
- if ((await listHistory(context, scope, slug)).length > 0) return;
581
- await writeHistory(context, scope, slug, current, /* @__PURE__ */ new Date(Date.now() - 1));
582
- }
583
- //#endregion
584
- //#region src/validate.ts
585
- function fieldIssues(error) {
586
- return error.issues.map((issue) => ({
587
- path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
588
- message: issue.message
589
- }));
590
- }
591
- function validateSite(input, site) {
592
- return site.schema.safeParse(input);
593
- }
594
- /** Validate a page document: its own fields, and each section against the registry's schema for its type. */
595
- function validatePage(input, registry) {
596
- return createPageSchema$1(registry).safeParse(input);
597
- }
598
- /**
599
- * Validate a page for the editor: like {@link validatePage}, but a section of a type the registry no longer
600
- * defines is kept as it is. The site build still rejects such a page until the section is removed.
601
- */
602
- function validateEditorPage(input, registry) {
603
- return createTolerantPageSchema(registry).safeParse(input);
604
- }
605
- //#endregion
606
306
  //#region src/git.ts
607
307
  const run = promisify(execFile);
608
- /** Longest commit message the editor sends. */
609
- const COMMIT_MESSAGE_LIMIT = 1e3;
610
- var GitError = class extends Error {
611
- code;
612
- constructor(code, message) {
613
- super(message);
614
- this.code = code;
615
- }
616
- };
617
308
  async function git(root, args) {
618
309
  try {
619
310
  const { stdout } = await run("git", args, {
@@ -627,7 +318,8 @@ async function git(root, args) {
627
318
  return stdout;
628
319
  } catch (error) {
629
320
  const failure = error;
630
- throw new GitError("failed", (failure.stderr || failure.stdout || failure.message).trim().split("\n").slice(-3).join("\n") || "git failed.");
321
+ const detail = (failure.stderr || failure.stdout || failure.message).trim().split("\n").slice(-3).join("\n");
322
+ throw new GitError("failed", detail || "git failed.");
631
323
  }
632
324
  }
633
325
  /** The folders a commit may touch: the content and the uploads. Relative to the project root. */
@@ -743,1018 +435,125 @@ async function commitChanges(context, message, paths) {
743
435
  files: chosen.length
744
436
  };
745
437
  }
746
- //#endregion
747
- //#region src/api.ts
748
- /**
749
- * Dev-server API. Returns null when the URL is not under {@link API_PREFIX}
750
- * so other middleware can continue. Every write is schema-checked first.
751
- */
752
- async function handleEditorRequest(request, context, meta = {}) {
753
- try {
754
- return await route(request, context, meta);
755
- } catch (error) {
756
- if (error instanceof StoreError) return problem(error.status, error.code, error.message);
757
- throw error;
758
- }
759
- }
760
- async function route(request, context, meta) {
761
- const pathname = stripTrailingSlash$1(new URL(request.url).pathname);
762
- if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
763
- if (!isLocalRequest(request.headers, meta.remoteAddress)) return problem(403, "forbidden", "The editor API only accepts requests from localhost.");
764
- const parts = pathname.slice(API_PREFIX.length).replace(/^\//, "").split("/").filter((part) => part !== "");
765
- const method = request.method.toUpperCase();
766
- if (parts.length === 1 && parts[0] === "schema") {
767
- if (method === "GET") return getSchema(context);
768
- return methodNotAllowed(["GET"]);
769
- }
770
- if (parts.length === 1 && parts[0] === "site") {
771
- if (method === "GET") return getSite(scoped(context, "site"));
772
- if (method === "PUT") return putSite(request, scoped(context, "site"));
773
- return methodNotAllowed(["GET", "PUT"]);
774
- }
775
- if (parts.length === 1 && parts[0] === "save") {
776
- if (method === "POST") return postSave(request, scoped(context, "edits"));
777
- return methodNotAllowed(["POST"]);
778
- }
779
- if (parts.length === 1 && parts[0] === "pages") {
780
- if (method === "GET") return getPages(context);
781
- if (method === "POST") return createPage(request, context);
782
- return methodNotAllowed(["GET", "POST"]);
783
- }
784
- if (parts.length === 1 && parts[0] === "forms") {
785
- if (method === "GET") return getForms(context);
786
- return methodNotAllowed(["GET"]);
787
- }
788
- if (parts.length === 1 && parts[0] === "git") {
789
- if (method === "GET") return getGit(context);
790
- return methodNotAllowed(["GET"]);
791
- }
792
- if (parts.length === 2 && parts[0] === "git" && parts[1] === "commit") {
793
- if (method === "POST") return postCommit(request, context);
794
- return methodNotAllowed(["POST"]);
795
- }
796
- if (parts.length === 1 && parts[0] === "images") {
797
- if (method === "GET") return getImages(scoped(context, "uploads"));
798
- if (method === "POST") return postImage(request, scoped(context, "uploads"));
799
- return methodNotAllowed(["GET", "POST"]);
800
- }
801
- if (parts.length === 2 && parts[0] === "images") {
802
- if (method === "DELETE") return removeImage(scoped(context, "uploads"), decodeSegment(parts[1] ?? ""));
803
- return methodNotAllowed(["DELETE"]);
804
- }
805
- if (parts.length === 1 && parts[0] === "videos") {
806
- if (method === "GET") return getVideos(context);
807
- if (method === "POST") return postVideo(request, context);
808
- return methodNotAllowed(["GET", "POST"]);
809
- }
810
- if (parts.length === 2 && parts[0] === "videos") {
811
- if (method === "DELETE") return removeVideo(context, decodeSegment(parts[1] ?? ""));
812
- return methodNotAllowed(["DELETE"]);
813
- }
814
- if (parts.length === 1 && parts[0] === "preview") {
815
- if (method === "POST") return postPreview(request, context, meta);
816
- return methodNotAllowed(["POST"]);
817
- }
818
- if (parts.length === 2 && parts[0] === "preview" && parts[1] === "site") {
819
- if (method === "POST") return postSitePreview(request, context, meta);
820
- return methodNotAllowed(["POST"]);
821
- }
822
- if (parts[0] === "history" && (parts[1] === "site" || parts[1] === "pages")) {
823
- if (method !== "GET") return methodNotAllowed(["GET"]);
824
- if (parts[1] === "site" && parts.length <= 3) return getHistory(context, "site", "", parts[2]);
825
- if (parts[1] === "pages" && parts.length >= 3 && parts.length <= 4) {
826
- const slug = readSlug(parts[2] ?? "");
827
- if (slug === null) return badSlug();
828
- return getHistory(context, "page", slug, parts[3]);
829
- }
830
- }
831
- if (parts.length === 2 && parts[0] === "pages") {
832
- const slug = readSlug(parts[1] ?? "");
833
- if (slug === null) return badSlug();
834
- const entry = scoped(context, `page:${slug}`);
835
- if (method === "GET") return getPage(entry, slug);
836
- if (method === "PUT") return putPage(request, entry, slug);
837
- if (method === "DELETE") return deletePage(entry, slug);
838
- return methodNotAllowed([
839
- "GET",
840
- "PUT",
841
- "DELETE"
842
- ]);
843
- }
844
- if (parts.length === 3 && parts[0] === "pages" && parts[2] === "rename") {
845
- const slug = readSlug(parts[1] ?? "");
846
- if (slug === null) return badSlug();
847
- if (method === "POST") return renamePage(request, scoped(context, `page:${slug}`), slug);
848
- return methodNotAllowed(["POST"]);
849
- }
850
- if (parts.length === 3 && parts[0] === "pages" && parts[2] === "set-home") {
851
- const slug = readSlug(parts[1] ?? "");
852
- if (slug === null) return badSlug();
853
- if (method === "POST") return setHome(request, scoped(context, `page:${slug}`), slug);
854
- return methodNotAllowed(["POST"]);
855
- }
856
- return problem(404, "not_found", "Unknown editor API route.");
857
- }
858
- /**
859
- * Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
860
- * created while `astro dev` runs shows up at once.
861
- */
862
- async function getForms(context) {
863
- const handlers = {};
864
- for (const definition of Object.values(context.sections)) {
865
- const name = definition.form;
866
- if (!name || handlers[name]) continue;
867
- const file = context.formsDir ? formFile(context.formsDir, name) : null;
868
- handlers[name] = { file: file ? relativeTo(context.root, file) : null };
869
- }
870
- return json(200, {
871
- enabled: context.formsDir != null,
872
- handlers
873
- });
874
- }
875
- function relativeTo(root, file) {
876
- const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
877
- return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
878
- }
879
- /**
880
- * The context for editing one entry. A store that keeps each entry's pending edits apart (`githubStore` in `pr` mode)
881
- * hands out a view of its own; every other store is used as it is.
882
- */
883
- function scoped(context, scope) {
884
- const store = context.store.scoped?.(scope);
885
- return store ? {
886
- ...context,
887
- store
888
- } : context;
889
- }
890
- async function getSchema(context) {
891
- const sectionDefaults = {};
892
- const sectionLabels = {};
893
- const sectionDescriptions = {};
894
- const sectionWireframes = {};
895
- const sectionOptions = {};
896
- const optionalContent = {};
897
- const contentCounts = { ...context.site.counts };
898
- const fieldChoices = {};
899
- const fieldIcons = {};
900
- const showWhen = {};
901
- const fieldImages = {};
902
- const sectionForms = {};
903
- for (const definition of Object.values(context.sections)) {
904
- const type = definition.type;
905
- if (definition.form) sectionForms[type] = definition.form;
906
- sectionDefaults[type] = definition.defaults;
907
- sectionLabels[type] = definition.label;
908
- sectionDescriptions[type] = definition.description;
909
- sectionWireframes[type] = definition.wireframe;
910
- sectionOptions[type] = definition.options;
911
- optionalContent[type] = definition.optional;
912
- if (Object.keys(definition.counts).length > 0) contentCounts[type] = { ...definition.counts };
913
- if (Object.keys(definition.choices).length > 0) fieldChoices[type] = definition.choices;
914
- if (Object.keys(definition.icons).length > 0) fieldIcons[type] = definition.icons;
915
- if (Object.keys(definition.showWhen).length > 0) showWhen[type] = definition.showWhen;
916
- const images = imageFields(definition.schema);
917
- if (images.length > 0) fieldImages[type] = images;
918
- }
919
- return json(200, {
920
- sectionOptions,
921
- siteOptions: context.site.options,
922
- siteLimits: context.site.limits,
923
- theme: context.theme,
924
- contentCounts,
925
- optionalContent,
926
- fieldChoices,
927
- fieldIcons,
928
- fieldImages,
929
- showWhen,
930
- sectionForms,
931
- pageRules: context.pageRules,
932
- sectionDefaults,
933
- sectionLabels,
934
- sectionDescriptions,
935
- sectionWireframes,
936
- projectId: projectId(context.root, await siteName(context))
937
- });
938
- }
939
- async function siteName(context) {
940
- try {
941
- return (await readSite(context)).name;
942
- } catch {
943
- return "";
944
- }
945
- }
946
- async function getSite(context) {
947
- try {
948
- return json(200, await readSite(context));
949
- } catch (error) {
950
- return contentFailure(error);
951
- }
952
- }
953
- async function putSite(request, context) {
954
- const body = await readJsonBody(request);
955
- if (body.response) return body.response;
956
- const parsed = validateSite(body.value, context.site);
957
- if (!parsed.success) return validation(fieldIssues(parsed.error));
958
- const missing = await missingAssets(context, parsed.data);
959
- if (missing.length > 0) return validation(missing);
960
- await ensureBaseline(context, "site", "", await readStoredJson(context, SITE_KEY, "site"));
961
- await writeDocuments(context, [[SITE_KEY, parsed.data]]);
962
- await writeHistory(context, "site", "", parsed.data);
963
- return json(200, parsed.data);
964
- }
965
- /** The parsed document at `key`, upgraded to the current version, or undefined when it is missing or not JSON. */
966
- async function readStoredJson(context, key, kind) {
967
- try {
968
- const text = await context.store.read(key);
969
- if (text === void 0) return void 0;
970
- const upgraded = context.migrator.upgrade(JSON.parse(text), kind);
971
- return upgraded.ok ? upgraded.value : void 0;
972
- } catch (error) {
973
- if (error instanceof StoreError) throw error;
974
- return;
975
- }
976
- }
977
- /** Write documents in the layout every file uses (sorted keys, two spaces, trailing newline). */
978
- async function writeDocuments(context, documents, removals = []) {
979
- await context.store.apply([...documents.map(([key, value]) => ({
980
- type: "write",
981
- key,
982
- text: stableStringify(context.migrator.stamp(value))
983
- })), ...removals.map((key) => ({
984
- type: "remove",
985
- key
986
- }))]);
987
- }
988
- const saveSchema = z.object({
989
- page: z.object({
990
- /** The slug the page is stored under now. The document's own `slug` is where it goes. */
991
- from: z.string(),
992
- document: z.unknown(),
993
- /** Where the current home page moves when this page becomes `index`. */
994
- previousHomeSlug: z.string().optional()
995
- }).strict().optional(),
996
- site: z.unknown().optional()
997
- }).strict().refine((value) => value.page !== void 0 || value.site !== void 0, { message: "Nothing to save." });
998
- /**
999
- * Save the editor draft in one request: a page (with its rename or promotion to home, when the slug
1000
- * changed) and the site. Every document is validated before anything is written, and all writes and
1001
- * removals go to the store as one `apply`, so a failure never leaves a page renamed with stale content
1002
- * or the page saved without the site.
1003
- */
1004
- async function postSave(request, context) {
1005
- const body = await readJsonBody(request);
1006
- if (body.response) return body.response;
1007
- const parsed = saveSchema.safeParse(body.value);
1008
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1009
- const writes = [];
1010
- const removals = [];
1011
- const after = [];
1012
- const result = {};
1013
- const failures = [];
1014
- if (parsed.data.site !== void 0) {
1015
- const upgraded = context.migrator.upgrade(parsed.data.site, "site");
1016
- if (!upgraded.ok) failures.push(...tagIssues([{
1017
- path: SCHEMA_VERSION_KEY,
1018
- message: upgraded.message
1019
- }], "site"));
1020
- else {
1021
- const site = validateSite(upgraded.value, context.site);
1022
- const missing = site.success ? await missingAssets(context, site.data) : [];
1023
- if (!site.success) failures.push(...tagIssues(fieldIssues(site.error), "site"));
1024
- else if (missing.length > 0) failures.push(...tagIssues(missing, "site"));
1025
- else {
1026
- const stored = await readStoredJson(context, SITE_KEY, "site");
1027
- writes.push([SITE_KEY, site.data]);
1028
- after.push(async () => {
1029
- await ensureBaseline(context, "site", "", stored);
1030
- await writeHistory(context, "site", "", site.data);
1031
- });
1032
- result.site = site.data;
1033
- }
1034
- }
1035
- }
1036
- if (parsed.data.page !== void 0) {
1037
- const planned = await planPageSave(context, parsed.data.page);
1038
- if (planned.issues) failures.push(...tagIssues(planned.issues, "page"));
1039
- else if (planned.response) {
1040
- if (failures.length === 0) return planned.response;
1041
- } else {
1042
- writes.push(...planned.writes);
1043
- removals.push(...planned.removals);
1044
- after.push(planned.after);
1045
- result.page = planned.page;
1046
- }
1047
- }
1048
- if (failures.length > 0) return validation(failures);
1049
- const written = new Set(writes.map(([key]) => key));
1050
- await writeDocuments(context, writes, removals.filter((key) => !written.has(key)));
1051
- for (const step of after) await step();
1052
- return json(200, result);
1053
- }
1054
- async function planPageSave(context, input) {
1055
- const from = readSlug(input.from);
1056
- if (from === null) return { response: badSlug() };
1057
- const upgraded = context.migrator.upgrade(input.document, "page");
1058
- if (!upgraded.ok) return { issues: [{
1059
- path: SCHEMA_VERSION_KEY,
1060
- message: upgraded.message
1061
- }] };
1062
- const parsed = validateEditorPage(upgraded.value, context.sections);
1063
- if (!parsed.success) return { issues: fieldIssues(parsed.error) };
1064
- const page = parsed.data;
1065
- const target = page.slug;
1066
- const missing = await missingAssets(context, page);
1067
- if (missing.length > 0) return { issues: missing };
1068
- const loaded = await loadStoredPages(context);
1069
- if (loaded.response) return { response: loaded.response };
1070
- const found = loaded.pages.find((entry) => entry.page.slug === from);
1071
- if (!found) return { response: problem(404, "not_found", `No page with slug "${from}".`) };
1072
- const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
1073
- const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
1074
- path: `sections.${index}.type`,
1075
- message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
1076
- }] : []);
1077
- if (added.length > 0) return { issues: added };
1078
- const after = async () => {
1079
- await ensureBaseline(context, "page", target, found.page);
1080
- await writeHistory(context, "page", target, page);
1081
- };
1082
- if (target === from) return {
1083
- page,
1084
- writes: [[found.key, page]],
1085
- removals: [],
1086
- after
1087
- };
1088
- if (!context.pageRules.rename) return { response: locked("rename") };
1089
- if (from === "index") return { response: problem(409, "conflict", "The home page slug stays index. Set another page as home to move it.") };
1090
- if (isSystemPage(from) || isSystemPage(target)) return { response: problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.") };
1091
- if (target !== "index") {
1092
- if (loaded.pages.some((entry) => entry.page.slug === target)) return { response: problem(409, "conflict", `A page with slug "${target}" already exists.`) };
1093
- const nextKey = pageKey(target);
1094
- if (await context.store.exists(nextKey)) return { response: problem(409, "conflict", `A file named ${target}.json already exists.`) };
1095
- return {
1096
- page,
1097
- writes: [[nextKey, page]],
1098
- removals: [found.key],
1099
- after
1100
- };
1101
- }
1102
- const indexKey = pageKey("index");
1103
- const home = loaded.pages.find((entry) => entry.page.slug === "index");
1104
- if (!home) {
1105
- if (await context.store.exists(indexKey)) return { response: problem(409, "conflict", "A file named index.json already exists.") };
1106
- return {
1107
- page,
1108
- writes: [[indexKey, page]],
1109
- removals: [found.key],
1110
- after
1111
- };
1112
- }
1113
- const previousSlug = input.previousHomeSlug === void 0 ? null : readSlug(input.previousHomeSlug);
1114
- if (previousSlug === null || previousSlug === "index" || isSystemPage(previousSlug)) return { response: problem(400, "invalid_slug", "previousHomeSlug is required to move the current home page.") };
1115
- if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return { response: problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`) };
1116
- const previousKey = pageKey(previousSlug);
1117
- if (await context.store.exists(previousKey)) return { response: problem(409, "conflict", `A file named ${previousSlug}.json already exists.`) };
1118
- const moved = validateEditorPage({
1119
- ...home.page,
1120
- slug: previousSlug
1121
- }, context.sections);
1122
- if (!moved.success) return { issues: fieldIssues(moved.error) };
438
+ /** Commit changes on the local git work tree of the project. */
439
+ function fileGit(context) {
1123
440
  return {
1124
- page,
1125
- writes: [[previousKey, moved.data], [indexKey, page]],
1126
- removals: [...home.key === indexKey ? [] : [home.key], found.key],
1127
- after
441
+ info: () => gitInfo(context),
442
+ commit: (message, paths) => commitChanges(context, message, paths)
1128
443
  };
1129
444
  }
1130
- const commitSchema = z.object({
1131
- message: z.string().max(COMMIT_MESSAGE_LIMIT),
1132
- paths: z.array(z.string().min(1).max(512)).max(500).optional()
1133
- }).strict();
1134
- async function getGit(context) {
1135
- return json(200, await gitInfo(context));
1136
- }
1137
- async function postCommit(request, context) {
1138
- const body = await readJsonBody(request);
1139
- if (body.response) return body.response;
1140
- const parsed = commitSchema.safeParse(body.value);
1141
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1142
- try {
1143
- return json(201, await commitChanges(context, parsed.data.message, parsed.data.paths));
1144
- } catch (error) {
1145
- if (!(error instanceof GitError)) throw error;
1146
- return problem(error.code === "failed" ? 500 : error.code === "invalid" ? 400 : 409, `git_${error.code}`, error.message);
1147
- }
1148
- }
1149
- async function getHistory(context, scope, slug, id) {
1150
- if (id === void 0) return json(200, { entries: await listHistory(context, scope, slug) });
1151
- if (!isHistoryId(id)) return problem(400, "invalid_id", "Not a history id.");
1152
- const snapshot = await readHistory(context, scope, slug, id);
1153
- if (snapshot === null) return problem(404, "not_found", "No saved version with that id.");
1154
- return json(200, snapshot);
1155
- }
1156
- async function getPages(context) {
1157
- const loaded = await loadStoredPages(context);
1158
- if (loaded.response) return loaded.response;
1159
- return json(200, { pages: loaded.pages.map((entry) => ({
1160
- slug: entry.page.slug,
1161
- title: entry.page.title,
1162
- file: entry.fileName,
1163
- system: isSystemPage(entry.page.slug),
1164
- anchors: entry.page.sections.flatMap((section) => "anchor" in section && typeof section.anchor === "string" && section.anchor !== "" ? [section.anchor] : [])
1165
- })) });
1166
- }
1167
- async function getPage(context, slug) {
1168
- const loaded = await loadStoredPages(context);
1169
- if (loaded.response) return loaded.response;
1170
- const found = loaded.pages.find((entry) => entry.page.slug === slug);
1171
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
1172
- return json(200, found.page);
1173
- }
1174
- async function putPage(request, context, slug) {
1175
- const body = await readJsonBody(request);
1176
- if (body.response) return body.response;
1177
- const parsed = validateEditorPage(body.value, context.sections);
1178
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1179
- const page = parsed.data;
1180
- if (page.slug !== slug) return problem(400, "slug_mismatch", `Slug in the body must be "${slug}". Rename the page with POST /pages/${slug}/rename.`);
1181
- const missing = await missingAssets(context, page);
1182
- if (missing.length > 0) return validation(missing);
1183
- const loaded = await loadStoredPages(context);
1184
- if (loaded.response) return loaded.response;
1185
- const found = loaded.pages.find((entry) => entry.page.slug === slug);
1186
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
1187
- const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
1188
- const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
1189
- path: `sections.${index}.type`,
1190
- message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
1191
- }] : []);
1192
- if (added.length > 0) return validation(added);
1193
- await ensureBaseline(context, "page", slug, found.page);
1194
- await writeDocuments(context, [[found.key, page]]);
1195
- await writeHistory(context, "page", slug, page);
1196
- return json(200, page);
1197
- }
1198
- const orphanKey = (section) => `${section.id}:${section.type}`;
1199
- async function createPage(request, baseContext) {
1200
- const body = await readJsonBody(request);
1201
- if (body.response) return body.response;
1202
- const parsed = createPageSchema.safeParse(body.value);
1203
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1204
- const context = scoped(baseContext, `page:${parsed.data.slug}`);
1205
- if (isSystemPage(parsed.data.slug)) return problem(409, "reserved_slug", `"${parsed.data.slug}" is a system page and cannot be created.`);
1206
- const loaded = await loadStoredPages(context, { allowMissing: true });
1207
- if (loaded.response) return loaded.response;
1208
- if (loaded.pages.some((entry) => entry.page.slug === parsed.data.slug)) return problem(409, "conflict", `A page with slug "${parsed.data.slug}" already exists.`);
1209
- const key = pageKey(parsed.data.slug);
1210
- if (await context.store.exists(key)) return problem(409, "conflict", `A file named ${parsed.data.slug}.json already exists.`);
1211
- const drafted = draftPage(parsed.data, loaded.pages, context.sections);
1212
- if (drafted.response) return drafted.response;
1213
- const validated = validatePage(drafted.page, context.sections);
1214
- if (!validated.success) return validation(fieldIssues(validated.error));
1215
- await writeDocuments(context, [[key, validated.data]]);
1216
- return json(201, validated.data);
1217
- }
1218
- function locked(operation) {
1219
- return problem(409, "operation_locked", `${operation === "rename" ? "Renaming pages" : "Deleting pages"} is turned off for this site (pages.${operation} in the bearminion() options).`);
1220
- }
1221
- async function deletePage(context, slug) {
1222
- if (!context.pageRules.delete) return locked("delete");
1223
- if (slug === "index") return problem(409, "conflict", "Refusing to delete the index page.");
1224
- if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be deleted.`);
1225
- const loaded = await loadStoredPages(context);
1226
- if (loaded.response) return loaded.response;
1227
- const found = loaded.pages.find((entry) => entry.page.slug === slug);
1228
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
1229
- await writeDocuments(context, [], [found.key]);
1230
- return json(200, {
1231
- deleted: true,
1232
- slug
1233
- });
1234
- }
445
+ //#endregion
446
+ //#region src/history.ts
1235
447
  /**
1236
- * Make `slug` the home page. The current home page moves to `previousSlug`, so the
1237
- * site never has two pages at "/" and never loses its home page halfway.
448
+ * Local copies of what was saved, in `<project>/.editor/history/`, so an earlier version of a page or of the
449
+ * site can be loaded back into the draft. Dev-only and untracked: the folder belongs in `.gitignore`.
1238
450
  */
1239
- async function setHome(request, context, slug) {
1240
- const body = await readJsonBody(request);
1241
- if (body.response) return body.response;
1242
- const parsed = setHomeSchema.safeParse(body.value);
1243
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1244
- if (!context.pageRules.rename) return locked("rename");
1245
- if (slug === "index") return problem(409, "conflict", "That page is already the home page.");
1246
- if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be the home page.`);
1247
- const loaded = await loadStoredPages(context);
1248
- if (loaded.response) return loaded.response;
1249
- const target = loaded.pages.find((entry) => entry.page.slug === slug);
1250
- if (!target) return problem(404, "not_found", `No page with slug "${slug}".`);
1251
- const previous = loaded.pages.find((entry) => entry.page.slug === "index");
1252
- const indexKey = pageKey("index");
1253
- if (previous) {
1254
- const previousSlug = parsed.data.previousSlug;
1255
- if (previousSlug === void 0 || previousSlug === "index") return problem(400, "invalid_slug", "previousSlug is required to move the current home page.");
1256
- if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`);
1257
- const previousKey = pageKey(previousSlug);
1258
- if (await context.store.exists(previousKey)) return problem(409, "conflict", `A file named ${previousSlug}.json already exists.`);
1259
- const moved = validateEditorPage({
1260
- ...previous.page,
1261
- slug: previousSlug
1262
- }, context.sections);
1263
- if (!moved.success) return validation(fieldIssues(moved.error));
1264
- const promoted = validateEditorPage({
1265
- ...target.page,
1266
- slug: "index"
1267
- }, context.sections);
1268
- if (!promoted.success) return validation(fieldIssues(promoted.error));
1269
- await writeDocuments(context, [[previousKey, moved.data], [indexKey, promoted.data]], [...previous.key === indexKey ? [] : [previous.key], target.key]);
1270
- return json(200, promoted.data);
1271
- }
1272
- if (await context.store.exists(indexKey)) return problem(409, "conflict", "A file named index.json already exists.");
1273
- const promoted = validateEditorPage({
1274
- ...target.page,
1275
- slug: "index"
1276
- }, context.sections);
1277
- if (!promoted.success) return validation(fieldIssues(promoted.error));
1278
- await writeDocuments(context, [[indexKey, promoted.data]], [target.key]);
1279
- return json(200, promoted.data);
1280
- }
1281
- async function renamePage(request, context, slug) {
1282
- const body = await readJsonBody(request);
1283
- if (body.response) return body.response;
1284
- const parsed = renameSchema.safeParse(body.value);
1285
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1286
- const nextSlug = parsed.data.slug;
1287
- if (!context.pageRules.rename) return locked("rename");
1288
- if (nextSlug === slug) return problem(400, "invalid_slug", "The new slug is the same as the current slug.");
1289
- if (slug === "index") return problem(409, "conflict", "Refusing to rename the index page.");
1290
- if (isSystemPage(slug) || isSystemPage(nextSlug)) return problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.");
1291
- const loaded = await loadStoredPages(context);
1292
- if (loaded.response) return loaded.response;
1293
- const found = loaded.pages.find((entry) => entry.page.slug === slug);
1294
- if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
1295
- if (loaded.pages.some((entry) => entry.page.slug === nextSlug)) return problem(409, "conflict", `A page with slug "${nextSlug}" already exists.`);
1296
- const nextKey = pageKey(nextSlug);
1297
- if (await context.store.exists(nextKey)) return problem(409, "conflict", `A file named ${nextSlug}.json already exists.`);
1298
- const validated = validateEditorPage({
1299
- ...found.page,
1300
- slug: nextSlug
1301
- }, context.sections);
1302
- if (!validated.success) return validation(fieldIssues(validated.error));
1303
- await writeDocuments(context, [[nextKey, validated.data]], [found.key]);
1304
- return json(200, validated.data);
451
+ const HISTORY_DIR = ".editor/history";
452
+ function idToIso(id) {
453
+ return `${id.slice(0, 4)}-${id.slice(4, 6)}-${id.slice(6, 8)}T${id.slice(9, 11)}:${id.slice(11, 13)}:${id.slice(13, 15)}.${id.slice(15, 18)}Z`;
1305
454
  }
1306
- const previewBodySchema = z.object({
1307
- page: z.unknown(),
1308
- motion: z.boolean().optional()
1309
- }).strict();
1310
- async function postPreview(request, context, meta) {
1311
- if (!meta.renderPreview) return problem(501, "preview_unavailable", "Live preview is only available while astro dev is running.");
1312
- const body = await readJsonBody(request);
1313
- if (body.response) return body.response;
1314
- const payload = previewBodySchema.safeParse(body.value);
1315
- if (!payload.success) return validation(fieldIssues(payload.error));
1316
- const parsed = validateEditorPage(payload.data.page, context.sections);
1317
- if (!parsed.success) return validation(fieldIssues(parsed.error));
1318
- const renderable = withoutOrphanSections(parsed.data, context.sections);
1319
- try {
1320
- return json(200, { html: await meta.renderPreview(renderable, payload.data.motion ?? true) });
1321
- } catch (error) {
1322
- if (error instanceof PreviewUnavailableError) return problem(501, "preview_unavailable", error.message);
1323
- const message = error instanceof Error ? error.message : "Preview failed.";
1324
- console.error("[bearminion] preview failed", error);
1325
- return problem(500, "preview_failed", message);
1326
- }
455
+ function directory(context, scope, slug) {
456
+ return scope === "site" ? path.join(context.root, HISTORY_DIR, "site") : path.join(context.root, HISTORY_DIR, "pages", slug);
1327
457
  }
1328
- const sitePreviewBodySchema = z.object({
1329
- site: z.unknown(),
1330
- pathname: z.string().max(2048)
1331
- }).strict();
1332
- async function postSitePreview(request, context, meta) {
1333
- if (!meta.renderSitePreview) return problem(501, "preview_unavailable", "Live site preview is not available in this project.");
1334
- const body = await readJsonBody(request);
1335
- if (body.response) return body.response;
1336
- const payload = sitePreviewBodySchema.safeParse(body.value);
1337
- if (!payload.success) return validation(fieldIssues(payload.error));
1338
- const parsed = validateSite(payload.data.site, context.site);
1339
- if (!parsed.success) return validation(fieldIssues(parsed.error));
458
+ async function ids(dir) {
1340
459
  try {
1341
- return json(200, await meta.renderSitePreview(parsed.data, payload.data.pathname));
1342
- } catch (error) {
1343
- if (error instanceof PreviewUnavailableError) return problem(501, "preview_unavailable", error.message);
1344
- const message = error instanceof Error ? error.message : "Preview failed.";
1345
- console.error("[bearminion] site preview failed", error);
1346
- return problem(500, "preview_failed", message);
460
+ return (await readdir(dir)).filter((name) => name.endsWith(".json") && isHistoryId(name.slice(0, -5))).map((name) => name.slice(0, -5)).sort();
461
+ } catch {
462
+ return [];
1347
463
  }
1348
464
  }
1349
- async function getImages(context) {
1350
- const limits = {
1351
- maxBytes: context.maxImageBytes,
1352
- convert: context.imageConvert
1353
- };
1354
- return json(200, {
1355
- images: await context.store.uploads.list(),
1356
- limits
1357
- });
465
+ /** Newest first. */
466
+ async function listHistory(context, scope, slug = "") {
467
+ return (await ids(directory(context, scope, slug))).reverse().map((id) => ({
468
+ id,
469
+ at: idToIso(id)
470
+ }));
1358
471
  }
1359
- function decodeSegment(segment) {
472
+ async function readHistory(context, scope, slug, id) {
473
+ if (!isHistoryId(id)) return null;
1360
474
  try {
1361
- return decodeURIComponent(segment);
475
+ return JSON.parse(await readFile(path.join(directory(context, scope, slug), `${id}.json`), "utf8"));
1362
476
  } catch {
1363
- return "";
477
+ return null;
1364
478
  }
1365
479
  }
1366
- /** Image paths that a saved file must not point at, because the file is not there. */
1367
- async function missingAssets(context, document) {
1368
- const { store } = context;
1369
- if (!store.assetExists) return [];
1370
- return missingAssetIssues(document, (src) => store.assetExists?.(src) ?? Promise.resolve(true));
1371
- }
1372
480
  /**
1373
- * Where the saved content uses the image at `src`: "Home page › Hero", "Site settings › brand logo". Read from the
1374
- * raw files, so a page that fails validation still counts. Unsaved drafts are not on disk: the editor checks its own
1375
- * drafts before it asks to delete, and saving a draft that still points at a deleted image fails validation.
481
+ * Keep a copy of `value`. A value equal to the newest copy is skipped, and only the newest {@link HISTORY_KEEP}
482
+ * copies stay. Returns the new entry, or null when nothing was written. Never throws: history must not block a save.
1376
483
  */
1377
- async function imageUsages(context, src) {
1378
- const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
1379
- const usages = [];
1380
- const site = await readStoredJson(context, SITE_KEY, "site");
1381
- for (const ref of assetRefs(site)) if (ref.src === src) usages.push(describeSiteRef(ref));
1382
- for (const name of await context.store.list("pages") ?? []) {
1383
- if (!name.endsWith(".json") || name.startsWith(".")) continue;
1384
- const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
1385
- if (typeof page !== "object" || page === null) continue;
1386
- const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
1387
- const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
1388
- for (const ref of assetRefs(page)) if (ref.src === src) usages.push(describePageRef(ref, {
1389
- title,
1390
- sections
1391
- }, labels));
1392
- }
1393
- return usages;
1394
- }
1395
- async function removeImage(context, filename) {
1396
- const image = (await context.store.uploads.list()).find((item) => item.filename === filename);
1397
- if (!image) return problem(404, "not_found", "No uploaded image has that name.");
1398
- const usages = await imageUsages(context, image.path);
1399
- if (usages.length > 0) return json(409, {
1400
- error: "in_use",
1401
- message: `${filename} is still used: ${usages.join("; ")}. Choose another image there and save, then delete it.`,
1402
- usages
1403
- });
1404
- if (!await context.store.uploads.remove(filename)) return problem(404, "not_found", "No uploaded image has that name.");
1405
- return json(200, {
1406
- deleted: true,
1407
- filename
1408
- });
1409
- }
1410
- const NO_VIDEOS = "This content store does not take video uploads.";
1411
- async function getVideos(context) {
1412
- if (!context.store.videos) return json(200, {
1413
- videos: [],
1414
- maxBytes: context.maxVideoBytes
1415
- });
1416
- return json(200, {
1417
- videos: await context.store.videos.list(),
1418
- maxBytes: context.maxVideoBytes
1419
- });
1420
- }
1421
- /** Every string in a JSON value. */
1422
- function* strings(value) {
1423
- if (typeof value === "string") yield value;
1424
- else if (Array.isArray(value)) for (const item of value) yield* strings(item);
1425
- else if (typeof value === "object" && value !== null) for (const item of Object.values(value)) yield* strings(item);
1426
- }
1427
- /** Where saved content links the video at `url`, named like the image usages: "Home page › Media". */
1428
- async function videoUsages(context, url) {
1429
- const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
1430
- const usages = [];
1431
- if ([...strings(await readStoredJson(context, "site.json", "site"))].includes(url)) usages.push("Site settings");
1432
- for (const name of await context.store.list("pages") ?? []) {
1433
- if (!name.endsWith(".json") || name.startsWith(".")) continue;
1434
- const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
1435
- if (typeof page !== "object" || page === null) continue;
1436
- const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
1437
- const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
1438
- for (const section of sections) if ([...strings(section)].includes(url)) usages.push(`${title} › ${labels[section.type ?? ""] ?? section.type ?? "section"}`);
1439
- }
1440
- return usages;
1441
- }
1442
- async function removeVideo(context, filename) {
1443
- const videos = context.store.videos;
1444
- if (!videos) return problem(404, "not_found", NO_VIDEOS);
1445
- const video = (await videos.list()).find((item) => item.filename === filename);
1446
- if (!video) return problem(404, "not_found", "No uploaded video has that name.");
1447
- const usages = await videoUsages(context, video.url);
1448
- if (usages.length > 0) return json(409, {
1449
- error: "in_use",
1450
- message: `${filename} is still used: ${usages.join("; ")}. Choose another video there and save, then delete it.`,
1451
- usages
1452
- });
1453
- if (!await videos.remove(filename)) return problem(404, "not_found", "No uploaded video has that name.");
1454
- return json(200, {
1455
- deleted: true,
1456
- filename
1457
- });
1458
- }
1459
- async function postVideo(request, context) {
1460
- const videos = context.store.videos;
1461
- if (!videos) return problem(404, "not_found", NO_VIDEOS);
1462
- const limitMb = Math.round(context.maxVideoBytes / 1048576);
1463
- const tooLarge = () => problem(413, "too_large", `Videos must be ${limitMb}MB or smaller. Link a hosted video instead, or compress this one.`);
1464
- const length = contentLength(request);
1465
- if (length !== null && length > videoBodyLimit(context.maxVideoBytes)) return tooLarge();
1466
- if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the video as multipart/form-data.");
1467
- let form;
484
+ async function writeHistory(context, scope, slug, value, now = /* @__PURE__ */ new Date()) {
1468
485
  try {
1469
- form = await request.formData();
486
+ const dir = directory(context, scope, slug);
487
+ const existing = await ids(dir);
488
+ const newest = existing[existing.length - 1];
489
+ if (newest !== void 0) {
490
+ if (await readFile(path.join(dir, `${newest}.json`), "utf8") === stableStringify(value)) return null;
491
+ }
492
+ let id = historyId(now);
493
+ while (existing.includes(id)) id = historyId(new Date(Date.parse(idToIso(id)) + 1));
494
+ await writeJsonAtomic(path.join(dir, `${id}.json`), value);
495
+ for (const old of [...existing, id].slice(0, -50)) await rm(path.join(dir, `${old}.json`), { force: true });
496
+ return {
497
+ id,
498
+ at: idToIso(id)
499
+ };
1470
500
  } catch {
1471
- return problem(400, "invalid_upload", "The upload body could not be read.");
1472
- }
1473
- const entry = form.get("file");
1474
- if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
1475
- if (entry.size > context.maxVideoBytes) return tooLarge();
1476
- const bytes = new Uint8Array(await entry.arrayBuffer());
1477
- if (bytes.byteLength > context.maxVideoBytes) return tooLarge();
1478
- const declared = videoKindFromMime(entry.type);
1479
- const sniffed = sniffVideo(bytes);
1480
- if (declared === null || sniffed === null || declared !== sniffed) return problem(415, "unsupported_media_type", "Upload an mp4, webm, mov or ogv video whose contents match the declared type.");
1481
- try {
1482
- return json(201, await videos.save({
1483
- originalName: entry.name,
1484
- bytes,
1485
- kind: sniffed
1486
- }));
1487
- } catch (error) {
1488
- return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
501
+ return null;
1489
502
  }
1490
503
  }
1491
- async function postImage(request, context) {
1492
- const tooLarge = () => problem(413, "too_large", `Images must be ${formatBytes(context.maxImageBytes)} or smaller.`);
1493
- const length = contentLength(request);
1494
- if (length !== null && length > imageBodyLimit(context.maxImageBytes)) return tooLarge();
1495
- if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the image as multipart/form-data.");
1496
- let form;
1497
- try {
1498
- form = await request.formData();
1499
- } catch {
1500
- return problem(400, "invalid_upload", "The upload body could not be read.");
1501
- }
1502
- const entry = form.get("file");
1503
- if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
1504
- if (imageTooLarge(entry.size, context.maxImageBytes)) return tooLarge();
1505
- const bytes = new Uint8Array(await entry.arrayBuffer());
1506
- if (imageTooLarge(bytes.byteLength, context.maxImageBytes)) return tooLarge();
1507
- const declared = kindFromMime(entry.type);
1508
- const sniffed = sniffImage(bytes);
1509
- if (declared === null || sniffed === null || declared !== sniffed) return problem(415, "unsupported_media_type", "Upload a png, jpeg, webp, gif, or avif file whose contents match the declared type.");
1510
- try {
1511
- return json(201, await context.store.uploads.save({
1512
- originalName: entry.name,
1513
- bytes,
1514
- kind: sniffed
1515
- }));
1516
- } catch (error) {
1517
- if (error instanceof StoreError) throw error;
1518
- return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
1519
- }
504
+ /** Before the first save of a page or the site, keep the file as it was so even that first save can be undone. */
505
+ async function ensureBaseline(context, scope, slug, current) {
506
+ if ((await listHistory(context, scope, slug)).length > 0) return;
507
+ await writeHistory(context, scope, slug, current, /* @__PURE__ */ new Date(Date.now() - 1));
1520
508
  }
1521
- const createPageSchema = z.object({
1522
- slug: z.string(),
1523
- title: z.string(),
1524
- template: z.string().min(1).optional()
1525
- }).strict().superRefine((value, ctx) => {
1526
- if (readSlug(value.slug) === null) ctx.addIssue({
1527
- code: "custom",
1528
- message: "Slug must be lowercase kebab-case (the home page uses \"index\")",
1529
- path: ["slug"]
1530
- });
1531
- if (value.title.trim() === "") ctx.addIssue({
1532
- code: "custom",
1533
- message: "Title is required",
1534
- path: ["title"]
1535
- });
1536
- });
1537
- const setHomeSchema = z.object({
1538
- /** Slug the current home page moves to. Required when a home page exists. */
1539
- previousSlug: z.string().optional() }).strict().superRefine((value, ctx) => {
1540
- if (value.previousSlug !== void 0 && readSlug(value.previousSlug) === null) ctx.addIssue({
1541
- code: "custom",
1542
- message: "Slug must be lowercase kebab-case",
1543
- path: ["previousSlug"]
1544
- });
1545
- });
1546
- const renameSchema = z.object({ slug: z.string() }).strict().superRefine((value, ctx) => {
1547
- if (readSlug(value.slug) === null) ctx.addIssue({
1548
- code: "custom",
1549
- message: "Slug must be lowercase kebab-case (the home page uses \"index\")",
1550
- path: ["slug"]
1551
- });
1552
- });
1553
- function pageFromSection(slug, title, seo, definition) {
1554
- const section = {
1555
- id: sectionId(definition.type),
1556
- type: definition.type,
1557
- props: structuredClone(definition.defaults)
1558
- };
1559
- const variant = definition.options.find((option) => option.name === "variant");
1560
- const tone = definition.options.find((option) => option.name === "tone");
1561
- if (variant?.type === "enum") section.variant = variant.default;
1562
- if (tone?.type === "enum") section.tone = tone.default;
509
+ /** The undo history of the local project, in `.editor/history/`. */
510
+ function fileHistory(context) {
1563
511
  return {
1564
- slug,
1565
- title,
1566
- seo,
1567
- sections: [section]
512
+ list: (scope, slug) => listHistory(context, scope, slug),
513
+ read: (scope, slug, id) => readHistory(context, scope, slug, id),
514
+ async write(scope, slug, value) {
515
+ await writeHistory(context, scope, slug, value);
516
+ },
517
+ ensureBaseline: (scope, slug, current) => ensureBaseline(context, scope, slug, current)
1568
518
  };
1569
519
  }
1570
- function draftPage(input, pages, registry) {
1571
- const slug = readSlug(input.slug);
1572
- if (slug === null) return { response: badSlug() };
1573
- const seo = {
1574
- title: input.title,
1575
- description: "",
1576
- noindex: false,
1577
- nofollow: false
520
+ //#endregion
521
+ //#region src/options.ts
522
+ function resolveEditorContext(options, rootInput) {
523
+ if (!options?.sections) throw new Error("bearminion() needs the `sections` option: the site's section definitions.");
524
+ if (!options.site) throw new Error("bearminion() needs the `site` option: the site's header and footer definition from defineSite().");
525
+ const root = asDirectory(rootInput);
526
+ const contentDir = resolveDir(root, options?.contentDir, DEFAULT_CONTENT_DIR);
527
+ const uploadsDir = resolveDir(root, options?.uploadsDir, DEFAULT_UPLOADS_DIR);
528
+ const videosDir = resolveDir(root, options?.videosDir, DEFAULT_VIDEOS_DIR);
529
+ const context = {
530
+ root,
531
+ contentDir,
532
+ uploadsDir,
533
+ videosDir,
534
+ maxVideoBytes: options?.maxVideoBytes ?? 52428800,
535
+ maxImageBytes: resolveMaxImageBytes(options?.maxImageBytes),
536
+ pageRules: resolvePageRules(options?.pages),
537
+ imageConvert: resolveConvert(options?.imageConvert),
538
+ sections: options.sections,
539
+ site: options.site,
540
+ theme: options.theme ?? defaultTheme,
541
+ store: options.store ?? createFileStore({
542
+ root,
543
+ contentDir,
544
+ uploadsDir,
545
+ videosDir
546
+ }),
547
+ migrator: createMigrator(options),
548
+ git: options?.git === true,
549
+ formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
1578
550
  };
1579
- if (input.template === void 0) {
1580
- const definition = registry.hero ?? Object.values(registry)[0];
1581
- if (!definition) return { response: problem(400, "unknown_template", "No section types are registered.") };
1582
- return { page: pageFromSection(slug, input.title, seo, definition) };
1583
- }
1584
- const definition = registry[input.template];
1585
- if (definition) return { page: pageFromSection(slug, input.title, seo, definition) };
1586
- const source = pages.find((entry) => entry.page.slug === input.template);
1587
- if (!source) return { response: problem(400, "unknown_template", `Unknown template "${input.template}". Use a section type or an existing page slug.`) };
1588
- return { page: {
1589
- slug,
1590
- title: input.title,
1591
- seo,
1592
- sections: structuredClone(source.page.sections)
1593
- } };
1594
- }
1595
- function sectionId(type) {
1596
- return type.replace(/[^A-Za-z0-9_-]+/g, "") || "section";
1597
- }
1598
- async function loadStoredPages(context, options = {}) {
1599
- let listed;
1600
- try {
1601
- listed = await context.store.list(PAGES_DIR);
1602
- } catch (error) {
1603
- return { response: contentFailure(error) };
1604
- }
1605
- if (listed === void 0) {
1606
- if (options.allowMissing) return { pages: [] };
1607
- return { response: problem(404, "not_found", `Pages directory not found: ${PAGES_DIR}`) };
1608
- }
1609
- const names = listed.filter((name) => name.endsWith(".json") && !name.startsWith("."));
1610
- const pages = [];
1611
- const seen = /* @__PURE__ */ new Map();
1612
- for (const name of names) {
1613
- const key = `${PAGES_DIR}/${name}`;
1614
- let raw;
1615
- try {
1616
- raw = JSON.parse(await context.store.read(key) ?? "");
1617
- } catch (error) {
1618
- if (error instanceof StoreError) throw error;
1619
- if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
1620
- return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
1621
- }
1622
- const upgraded = context.migrator.upgrade(raw, "page");
1623
- if (!upgraded.ok) return { response: json(422, {
1624
- error: "validation",
1625
- message: `Invalid content in ${name}.`,
1626
- issues: [{
1627
- path: SCHEMA_VERSION_KEY,
1628
- message: upgraded.message
1629
- }]
1630
- }) };
1631
- const parsed = validateEditorPage(upgraded.value, context.sections);
1632
- if (!parsed.success) return { response: json(422, {
1633
- error: "validation",
1634
- message: `Invalid content in ${name}.`,
1635
- issues: fieldIssues(parsed.error)
1636
- }) };
1637
- const page = parsed.data;
1638
- const previous = seen.get(page.slug);
1639
- if (previous !== void 0) return { response: problem(409, "conflict", `Duplicate slug "${page.slug}" in ${name} (also defined in ${previous}).`) };
1640
- seen.set(page.slug, name);
1641
- pages.push({
1642
- key,
1643
- fileName: name,
1644
- page
1645
- });
1646
- }
1647
- return { pages };
1648
- }
1649
- async function readSite(context) {
1650
- const raw = await context.store.read(SITE_KEY);
1651
- if (raw === void 0) throw new ContentReadError(SITE_KEY, `Content file not found: ${SITE_KEY}`);
1652
- let parsed;
1653
- try {
1654
- parsed = JSON.parse(raw);
1655
- } catch (error) {
1656
- const message = error instanceof Error ? error.message : String(error);
1657
- throw new ContentReadError(SITE_KEY, `Invalid JSON in ${SITE_KEY}: ${message}`);
1658
- }
1659
- const upgraded = context.migrator.upgrade(parsed, "site");
1660
- if (!upgraded.ok) throw new ContentValidationError(SITE_KEY, [{
1661
- path: [SCHEMA_VERSION_KEY],
1662
- message: upgraded.message
1663
- }]);
1664
- const result = validateSite(upgraded.value, context.site);
1665
- if (!result.success) {
1666
- const issues = result.error.issues.map((issue) => ({
1667
- path: [...issue.path],
1668
- message: issue.message
1669
- }));
1670
- throw new ContentValidationError(SITE_KEY, issues);
1671
- }
1672
- return result.data;
1673
- }
1674
- async function readJsonBody(request) {
1675
- const length = contentLength(request);
1676
- if (length !== null && length > 1048576) return { response: problem(413, "too_large", "JSON body exceeds 1MB.") };
1677
- if ((request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return { response: problem(415, "unsupported_media_type", "This route expects a JSON body.") };
1678
- let text;
1679
- try {
1680
- text = await request.text();
1681
- } catch {
1682
- return { response: problem(400, "invalid_json", "The request body could not be read.") };
1683
- }
1684
- if (Buffer.byteLength(text) > 1048576) return { response: problem(413, "too_large", "JSON body exceeds 1MB.") };
1685
- try {
1686
- return { value: JSON.parse(text) };
1687
- } catch {
1688
- return { response: problem(400, "invalid_json", "Request body is not valid JSON.") };
1689
- }
1690
- }
1691
- function contentLength(request) {
1692
- const header = request.headers.get("content-length");
1693
- if (header === null || header === "") return null;
1694
- const value = Number(header);
1695
- if (!Number.isFinite(value) || value < 0) return null;
1696
- return value;
1697
- }
1698
- function contentFailure(error) {
1699
- if (error instanceof StoreError) throw error;
1700
- if (error instanceof ContentValidationError) return json(422, {
1701
- error: "validation",
1702
- message: error.message,
1703
- issues: error.issues.map((issue) => ({
1704
- path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
1705
- message: issue.message
1706
- }))
1707
- });
1708
- if (error instanceof ContentReadError) {
1709
- const missing = /not found/i.test(error.message);
1710
- return problem(missing ? 404 : 400, missing ? "not_found" : "invalid_json", error.message);
1711
- }
1712
- return problem(500, "write_failed", error instanceof Error ? error.message : "Unexpected error.");
1713
- }
1714
- /** Name the document an issue belongs to, for the save route that validates a page and the site together. */
1715
- function tagIssues(issues, file) {
1716
- return issues.map((issue) => ({
1717
- ...issue,
1718
- file
1719
- }));
1720
- }
1721
- function validation(issues) {
1722
- return json(400, {
1723
- error: "validation",
1724
- message: "The document failed schema validation.",
1725
- issues
1726
- });
1727
- }
1728
- function badSlug() {
1729
- return problem(400, "invalid_slug", "Slug must be lowercase kebab-case and must not contain a path.");
1730
- }
1731
- function methodNotAllowed(allow) {
1732
- return json(405, {
1733
- error: "method_not_allowed",
1734
- message: `Allowed: ${allow.join(", ")}.`
1735
- }, { allow: allow.join(", ") });
1736
- }
1737
- function problem(status, error, message) {
1738
- return json(status, {
1739
- error,
1740
- message
1741
- });
1742
- }
1743
- function json(status, body, extra) {
1744
- const headers = new Headers({
1745
- "content-type": "application/json; charset=utf-8",
1746
- "cache-control": "no-store",
1747
- "x-content-type-options": "nosniff"
1748
- });
1749
- if (extra) for (const [key, value] of Object.entries(extra)) headers.set(key, value);
1750
- return new Response(JSON.stringify(body), {
1751
- status,
1752
- headers
1753
- });
1754
- }
1755
- function stripTrailingSlash$1(pathname) {
1756
- if (pathname.length > 1 && pathname.endsWith("/")) return pathname.replace(/\/+$/, "");
1757
- return pathname;
551
+ if (options.collections) context.collections = resolveCollections(options.collections);
552
+ context.history = fileHistory(context);
553
+ context.commits = fileGit(context);
554
+ const formsDir = context.formsDir;
555
+ if (formsDir) context.formFile = (name) => formFile(formsDir, name);
556
+ return context;
1758
557
  }
1759
558
  const ASSET_TYPES = {
1760
559
  ".png": "image/png",
@@ -1818,11 +617,12 @@ async function dispatch(req, res, context, rawUrl, hooks) {
1818
617
  } catch {
1819
618
  requestUrl = new URL(rawUrl, "http://127.0.0.1").toString();
1820
619
  }
1821
- await send(res, await handleEditorRequest(new Request(requestUrl, {
620
+ const request = new Request(requestUrl, {
1822
621
  method,
1823
622
  headers,
1824
623
  body: body === void 0 ? void 0 : body
1825
- }), context, {
624
+ });
625
+ await send(res, await handleEditorRequest(request, context, {
1826
626
  remoteAddress: req.socket?.remoteAddress ?? null,
1827
627
  renderPreview: hooks.renderPreview,
1828
628
  renderSitePreview: hooks.renderSitePreview
@@ -2074,408 +874,6 @@ function rootInput(root) {
2074
874
  return process.cwd();
2075
875
  }
2076
876
  //#endregion
2077
- //#region src/github-store.ts
2078
- const API_VERSION = "2022-11-28";
2079
- const RAW = "application/vnd.github.raw+json";
2080
- const JSON_TYPE = "application/vnd.github+json";
2081
- /** GitHub's messages for a push that a branch rule refuses. */
2082
- const PROTECTED = /protected branch|must be made through a pull request|repository rule violation|required status check/i;
2083
- function folder(value, name) {
2084
- const parts = value.split("/").filter((part) => part !== "");
2085
- if (parts.some((part) => part === "." || part === "..")) throw new Error(`githubStore(): ${name} must stay inside the repository, got "${value}".`);
2086
- return parts.join("/");
2087
- }
2088
- const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
2089
- function toBase64(bytes) {
2090
- let binary = "";
2091
- for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
2092
- return btoa(binary);
2093
- }
2094
- function messageOf(text) {
2095
- try {
2096
- const body = JSON.parse(text);
2097
- return typeof body.message === "string" ? body.message : "";
2098
- } catch {
2099
- return "";
2100
- }
2101
- }
2102
- function defaultMessage({ written, removed }) {
2103
- if (written.length + removed.length === 1) return written.length === 1 ? `Update ${written[0]}` : `Remove ${removed[0]}`;
2104
- return `Update ${written.length + removed.length} files`;
2105
- }
2106
- function branchStem(scope) {
2107
- const part = scope.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
2108
- return `bearminion/${part === "" ? "edit" : part}`;
2109
- }
2110
- const MAX_BRANCHES_PER_SCOPE = 20;
2111
- function githubStore(options) {
2112
- const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(options.repo);
2113
- if (!match) throw new Error(`githubStore(): repo must be "owner/name", got "${options.repo}".`);
2114
- if (typeof options.token !== "string" || options.token === "") throw new Error("githubStore(): token is required. Use a fine-grained token with \"Contents: Read and write\" on this repository.");
2115
- const repo = `${match[1]}/${match[2]}`;
2116
- const api = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
2117
- const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
2118
- const rootDir = folder(options.rootDir ?? "", "rootDir");
2119
- const contentDir = folder(options.contentDir ?? "content", "contentDir");
2120
- const uploadsDir = folder(options.uploadsDir ?? "src/assets/uploads", "uploadsDir");
2121
- const message = options.message ?? defaultMessage;
2122
- const prMode = options.mode === "pr";
2123
- if (options.mode !== void 0 && options.mode !== "direct" && options.mode !== "pr") throw new Error(`githubStore(): mode must be "direct" or "pr", got "${String(options.mode)}".`);
2124
- const inRepo = (...parts) => [rootDir, ...parts].filter((part) => part !== "").join("/");
2125
- /** The repository path of a store key, checked the way the file store checks it. */
2126
- function contentPath(key) {
2127
- const parts = key.split("/");
2128
- if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
2129
- return inRepo(contentDir, key);
2130
- }
2131
- async function send(method, route, init = {}) {
2132
- let response;
2133
- try {
2134
- response = await doFetch(`${api}${route}`, {
2135
- method,
2136
- headers: {
2137
- accept: init.accept ?? JSON_TYPE,
2138
- authorization: `Bearer ${options.token}`,
2139
- "x-github-api-version": API_VERSION,
2140
- "user-agent": "bearminion",
2141
- ...init.body === void 0 ? {} : { "content-type": "application/json" },
2142
- ...init.headers
2143
- },
2144
- body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
2145
- });
2146
- } catch (error) {
2147
- throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${error instanceof Error ? error.message : "the request failed"}.`);
2148
- }
2149
- return {
2150
- status: response.status,
2151
- headers: response.headers,
2152
- text: await response.text()
2153
- };
2154
- }
2155
- /** What went wrong, in words the person editing can act on. */
2156
- function failure(reply, action) {
2157
- const detail = messageOf(reply.text);
2158
- if (reply.status === 401) return new StoreError(502, "github_auth", "GitHub refused the token. Check that it is valid and has not expired.");
2159
- if (reply.status === 403 || reply.status === 429) {
2160
- if (reply.headers.get("x-ratelimit-remaining") === "0" || /rate limit/i.test(detail)) return new StoreError(429, "github_rate_limited", "GitHub is rate limiting this token. Wait a few minutes and try again.");
2161
- return new StoreError(502, "github_forbidden", `GitHub refused to ${action}. The token needs "Contents: Read and write" on ${repo}.`);
2162
- }
2163
- if (reply.status === 404) return new StoreError(502, "github_not_found", `GitHub could not find ${repo} or the branch. Check the name, and that the token can see this repository.`);
2164
- return new StoreError(502, "github_error", `GitHub could not ${action}: ${detail || `HTTP ${reply.status}`}.`);
2165
- }
2166
- async function json(reply, action, ok = [200, 201]) {
2167
- const settled = await reply;
2168
- if (!ok.includes(settled.status)) throw failure(settled, action);
2169
- return JSON.parse(settled.text);
2170
- }
2171
- let branchName;
2172
- /** The branch edits are based on: the configured one, or the repository's default. */
2173
- function baseBranch() {
2174
- if (options.branch) return Promise.resolve(options.branch);
2175
- branchName ??= json(send("GET", `/repos/${repo}`), "read the repository").then((info) => info.default_branch, (error) => {
2176
- branchName = void 0;
2177
- throw error;
2178
- });
2179
- return branchName;
2180
- }
2181
- /** GETs that GitHub can answer with 304 Not Modified, which costs no rate limit. */
2182
- const cache = /* @__PURE__ */ new Map();
2183
- async function cached(route, accept) {
2184
- const key = `${accept} ${route}`;
2185
- const known = cache.get(key);
2186
- const reply = await send("GET", route, {
2187
- accept,
2188
- headers: known ? { "if-none-match": known.etag } : {}
2189
- });
2190
- if (reply.status === 304 && known) return {
2191
- ...reply,
2192
- status: 200,
2193
- text: known.text
2194
- };
2195
- const etag = reply.headers.get("etag");
2196
- if (reply.status === 200 && etag) cache.set(key, {
2197
- etag,
2198
- text: reply.text
2199
- });
2200
- return reply;
2201
- }
2202
- const contentsRoute = (path, ref) => `/repos/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`;
2203
- async function readFileAt(path, ref) {
2204
- const reply = await cached(contentsRoute(path, ref), RAW);
2205
- if (reply.status === 404) return void 0;
2206
- if (reply.status !== 200) throw failure(reply, `read ${path}`);
2207
- return reply.text;
2208
- }
2209
- /** The names of the files directly inside `path`, or `undefined` when there is no such folder. */
2210
- async function listFilesAt(path, ref) {
2211
- const reply = await cached(contentsRoute(path, ref), JSON_TYPE);
2212
- if (reply.status === 404) return void 0;
2213
- if (reply.status !== 200) throw failure(reply, `list ${path}`);
2214
- const entries = JSON.parse(reply.text);
2215
- if (!Array.isArray(entries)) return void 0;
2216
- return entries.filter((entry) => typeof entry === "object" && entry !== null && "name" in entry).filter((entry) => entry.type === "file").map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
2217
- }
2218
- async function branchHead(name) {
2219
- const reply = await send("GET", `/repos/${repo}/git/ref/heads/${encodePath(name)}`);
2220
- if (reply.status === 404) return void 0;
2221
- if (reply.status !== 200) throw failure(reply, `read the branch "${name}"`);
2222
- return JSON.parse(reply.text).object.sha;
2223
- }
2224
- /** The state of the pull requests whose head is `name`: any open one wins, then closed or merged ones. */
2225
- async function pullState(name) {
2226
- const head = encodeURIComponent(`${match?.[1] ?? ""}:${name}`);
2227
- const pulls = await json(send("GET", `/repos/${repo}/pulls?head=${head}&state=all&per_page=100`), "look up pull requests");
2228
- if (pulls.some((pull) => pull.state === "open")) return "open";
2229
- return pulls.length > 0 ? "closed" : "none";
2230
- }
2231
- /** One commit on the target's branch holding all of `changes`. Goes through the Git Data API so the files land together. */
2232
- function view(target) {
2233
- async function readFile(path) {
2234
- return readFileAt(path, await target.readRef());
2235
- }
2236
- async function listFile(path) {
2237
- return listFilesAt(path, await target.readRef());
2238
- }
2239
- async function listAcross(path) {
2240
- const names = /* @__PURE__ */ new Set();
2241
- for (const ref of await target.refs()) for (const name of await listFilesAt(path, ref) ?? []) names.add(name);
2242
- return [...names].sort((a, b) => a.localeCompare(b));
2243
- }
2244
- async function commit(changes, describe) {
2245
- for (let attempt = 0; attempt < 2; attempt += 1) {
2246
- const name = await target.writeBranch();
2247
- const headSha = await branchHead(name);
2248
- if (headSha === void 0) throw failure({
2249
- status: 404,
2250
- headers: new Headers(),
2251
- text: ""
2252
- }, `read the branch "${name}"`);
2253
- const parent = await json(send("GET", `/repos/${repo}/git/commits/${headSha}`), "read the latest commit");
2254
- const entries = [];
2255
- const applied = [];
2256
- for (const change of changes) if ("remove" in change) {
2257
- if (await readFileAt(change.path, headSha) === void 0) continue;
2258
- entries.push({
2259
- path: change.path,
2260
- mode: "100644",
2261
- type: "blob",
2262
- sha: null
2263
- });
2264
- applied.push(change);
2265
- } else if ("text" in change) {
2266
- entries.push({
2267
- path: change.path,
2268
- mode: "100644",
2269
- type: "blob",
2270
- content: change.text
2271
- });
2272
- applied.push(change);
2273
- } else {
2274
- const blob = await json(send("POST", `/repos/${repo}/git/blobs`, { body: {
2275
- content: toBase64(change.bytes),
2276
- encoding: "base64"
2277
- } }), `upload ${change.path}`);
2278
- entries.push({
2279
- path: change.path,
2280
- mode: "100644",
2281
- type: "blob",
2282
- sha: blob.sha
2283
- });
2284
- applied.push(change);
2285
- }
2286
- if (entries.length === 0) return;
2287
- const tree = await json(send("POST", `/repos/${repo}/git/trees`, { body: {
2288
- base_tree: parent.tree.sha,
2289
- tree: entries
2290
- } }), "write the files");
2291
- const created = await json(send("POST", `/repos/${repo}/git/commits`, { body: {
2292
- message: describe(applied),
2293
- tree: tree.sha,
2294
- parents: [headSha]
2295
- } }), "create the commit");
2296
- const update = await send("PATCH", `/repos/${repo}/git/refs/heads/${encodePath(name)}`, { body: {
2297
- sha: created.sha,
2298
- force: false
2299
- } });
2300
- if (update.status === 200) {
2301
- await target.committed?.(name, {
2302
- written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
2303
- removed: applied.filter((change) => "remove" in change).map((change) => change.path)
2304
- });
2305
- return;
2306
- }
2307
- if ((update.status === 403 || update.status === 422) && PROTECTED.test(messageOf(update.text))) throw new StoreError(409, "branch_protected", `The branch "${name}" is protected, so edits cannot be committed to it directly. Allow this token to push to it, use another branch, or set mode: 'pr'.`);
2308
- if (update.status === 422 && attempt === 0) continue;
2309
- if (update.status === 422) throw new StoreError(409, "branch_moved", "The branch changed while saving. Reload the editor and try again.");
2310
- throw failure(update, `update the branch "${name}"`);
2311
- }
2312
- }
2313
- return {
2314
- async read(key) {
2315
- return readFile(contentPath(key));
2316
- },
2317
- async exists(key) {
2318
- return await readFile(contentPath(key)) !== void 0;
2319
- },
2320
- async list(dir) {
2321
- return listFile(contentPath(dir));
2322
- },
2323
- async apply(operations) {
2324
- const changes = operations.map((operation) => operation.type === "write" ? {
2325
- path: contentPath(operation.key),
2326
- text: operation.text
2327
- } : {
2328
- path: contentPath(operation.key),
2329
- remove: true
2330
- });
2331
- if (changes.length === 0) return;
2332
- await commit(changes, (applied) => message({
2333
- written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
2334
- removed: applied.filter((change) => "remove" in change).map((change) => change.path)
2335
- }));
2336
- },
2337
- uploads: {
2338
- async list() {
2339
- return (await listAcross(inRepo(uploadsDir))).filter((name) => !name.startsWith(".") && hasImageExtension(name)).map((filename) => ({
2340
- filename,
2341
- path: `${uploadsDir}/${filename}`
2342
- }));
2343
- },
2344
- async save({ originalName, bytes, kind }) {
2345
- const taken = new Set(await listAcross(inRepo(uploadsDir)));
2346
- for (let attempt = 0; attempt < 8; attempt += 1) {
2347
- const filename = uploadFilename(originalName, kind);
2348
- if (taken.has(filename)) continue;
2349
- await commit([{
2350
- path: inRepo(uploadsDir, filename),
2351
- bytes
2352
- }], () => `Upload ${filename}`);
2353
- return {
2354
- filename,
2355
- path: `${uploadsDir}/${filename}`,
2356
- bytes: bytes.byteLength
2357
- };
2358
- }
2359
- throw new Error("Unable to allocate a unique upload filename.");
2360
- },
2361
- async remove(filename) {
2362
- if (!isUploadFilename(filename)) return false;
2363
- if (!(await listAcross(inRepo(uploadsDir))).includes(filename)) return false;
2364
- await commit([{
2365
- path: inRepo(uploadsDir, filename),
2366
- remove: true
2367
- }], () => `Remove ${filename}`);
2368
- return true;
2369
- }
2370
- },
2371
- async assetExists(src) {
2372
- if (!isAssetPath(src)) return false;
2373
- const slash = src.lastIndexOf("/");
2374
- const folder = inRepo(src.slice(0, slash));
2375
- const name = src.slice(slash + 1);
2376
- for (const ref of await target.refs()) if ((await listFilesAt(folder, ref))?.includes(name)) return true;
2377
- return false;
2378
- }
2379
- };
2380
- }
2381
- const direct = {
2382
- readRef: baseBranch,
2383
- refs: async () => [await baseBranch()],
2384
- writeBranch: baseBranch
2385
- };
2386
- if (!prMode) return view(direct);
2387
- /** The branch of one entry's pull request: `bearminion/<scope>`, then `-2`, `-3` once earlier pull requests are closed. */
2388
- async function activeBranch(scope) {
2389
- const stem = branchStem(scope);
2390
- for (let index = 1; index <= MAX_BRANCHES_PER_SCOPE; index += 1) {
2391
- const name = index === 1 ? stem : `${stem}-${index}`;
2392
- if (await branchHead(name) === void 0) return {
2393
- name,
2394
- exists: false
2395
- };
2396
- if (await pullState(name) !== "closed") return {
2397
- name,
2398
- exists: true
2399
- };
2400
- }
2401
- throw new StoreError(409, "branch_exhausted", `There are already ${MAX_BRANCHES_PER_SCOPE} closed pull requests for "${scope}". Delete some of the bearminion/ branches.`);
2402
- }
2403
- const labelName = options.label === void 0 ? "bearminion" : options.label;
2404
- async function openPullRequest(scope, name, change) {
2405
- if (await pullState(name) === "open") return;
2406
- const kind = scope.replace(":", ": ");
2407
- const files = [...change.written.map((path) => `- ${path}`), ...change.removed.map((path) => `- ${path} (removed)`)].join("\n");
2408
- const text = options.pullRequest?.({
2409
- scope,
2410
- ...change
2411
- }) ?? {
2412
- title: `Edit ${kind}`,
2413
- body: `Opened by the BearMinion editor. Merge it to publish the change.\n\nFirst save changed:\n${files}\n\nLater saves of the same entry are added to this pull request.`
2414
- };
2415
- const reply = await send("POST", `/repos/${repo}/pulls`, { body: {
2416
- title: text.title,
2417
- head: name,
2418
- base: await baseBranch(),
2419
- body: text.body
2420
- } });
2421
- if (reply.status === 422 && /already exists/i.test(messageOf(reply.text))) return;
2422
- if (reply.status !== 201) throw failure(reply, "open the pull request");
2423
- if (labelName === false) return;
2424
- const { number } = JSON.parse(reply.text);
2425
- await send("POST", `/repos/${repo}/issues/${number}/labels`, { body: { labels: [labelName] } });
2426
- }
2427
- function scopeTarget(scope) {
2428
- const readRef = async () => {
2429
- const active = await activeBranch(scope);
2430
- return active.exists ? active.name : baseBranch();
2431
- };
2432
- return {
2433
- readRef,
2434
- refs: async () => {
2435
- const refs = [await readRef()];
2436
- if (scope !== "uploads") {
2437
- const uploads = await activeBranch("uploads");
2438
- if (uploads.exists) refs.push(uploads.name);
2439
- }
2440
- const base = await baseBranch();
2441
- if (!refs.includes(base)) refs.push(base);
2442
- return refs;
2443
- },
2444
- async writeBranch() {
2445
- const active = await activeBranch(scope);
2446
- if (active.exists) return active.name;
2447
- const base = await baseBranch();
2448
- const sha = await branchHead(base);
2449
- if (sha === void 0) throw failure({
2450
- status: 404,
2451
- headers: new Headers(),
2452
- text: ""
2453
- }, `read the branch "${base}"`);
2454
- const created = await send("POST", `/repos/${repo}/git/refs`, { body: {
2455
- ref: `refs/heads/${active.name}`,
2456
- sha
2457
- } });
2458
- if (created.status !== 201 && created.status !== 422) throw failure(created, `create the branch "${active.name}"`);
2459
- return active.name;
2460
- },
2461
- committed: (name, change) => openPullRequest(scope, name, change)
2462
- };
2463
- }
2464
- const scoped = (scope) => view(scopeTarget(scope));
2465
- const base = view(direct);
2466
- const edits = scoped("edits");
2467
- const uploadScope = scoped("uploads");
2468
- return {
2469
- read: base.read,
2470
- exists: base.exists,
2471
- list: base.list,
2472
- apply: edits.apply,
2473
- uploads: uploadScope.uploads,
2474
- assetExists: base.assetExists,
2475
- scoped
2476
- };
2477
- }
2478
- //#endregion
2479
877
  //#region src/load.ts
2480
878
  /**
2481
879
  * Load `site.json` and `pages/*.json` from a content directory.
@@ -2510,7 +908,7 @@ function loadPages(contentDir, registry, { migrator = createMigrator(), tolerate
2510
908
  throw new ContentReadError(pagesDir, `Unable to read pages directory ${pagesDir}: ${message}`);
2511
909
  }
2512
910
  const files = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
2513
- const pageSchema = tolerateOrphans ? createTolerantPageSchema(registry) : createPageSchema$1(registry);
911
+ const pageSchema = tolerateOrphans ? createTolerantPageSchema(registry) : createPageSchema(registry);
2514
912
  const pages = files.map((name) => parseFile(path.join(pagesDir, name), pageSchema, migrator, "page"));
2515
913
  const seen = /* @__PURE__ */ new Map();
2516
914
  for (const [index, page] of pages.entries()) {
@@ -2560,6 +958,42 @@ function isErrno(error) {
2560
958
  return error instanceof Error && "code" in error;
2561
959
  }
2562
960
  //#endregion
961
+ //#region src/hosted-integration.ts
962
+ const VIRTUAL_ID = "virtual:bearminion/editor";
963
+ const RESOLVED_ID = `\0${VIRTUAL_ID}`;
964
+ /**
965
+ * Turns an Astro project into the hosted editor: server rendering, the sign-in middleware, and pages that draw from the
966
+ * repository's current content (`Astro.locals.bearminion`). Add it to the editor deployment's build only: the public
967
+ * static site must not use it. Needs an adapter (`@astrojs/cloudflare`, `@astrojs/vercel`, …).
968
+ */
969
+ function bearminionHostedEditor(options) {
970
+ const signIn = options.signIn ?? "required";
971
+ if (signIn !== "required" && signIn !== "optional") throw new Error(`signIn must be "required" or "optional", got ${String(signIn)}.`);
972
+ if (!options.module) throw new Error("bearminionHostedEditor needs `module`: the file that exports your hosted editor.");
973
+ return {
974
+ name: "bearminion:hosted-editor",
975
+ hooks: { "astro:config:setup"({ config, updateConfig, addMiddleware }) {
976
+ if (!config.adapter) throw new Error("bearminionHostedEditor renders on a server, so the project needs an adapter (for example @astrojs/cloudflare or @astrojs/vercel). Add it to the editor build only.");
977
+ const editorModule = path.resolve(fileURLToPath(config.root), options.module);
978
+ updateConfig({
979
+ ...config.output === "static" ? { output: "server" } : {},
980
+ vite: {
981
+ ssr: { noExternal: ["bearminion", config.adapter.name] },
982
+ plugins: [{
983
+ name: "bearminion:hosted-editor-module",
984
+ resolveId: (id) => id === VIRTUAL_ID ? RESOLVED_ID : null,
985
+ load: (id) => id === RESOLVED_ID ? `export { default as editor } from ${JSON.stringify(editorModule)}\nexport const signIn = ${JSON.stringify(signIn)}\n` : null
986
+ }]
987
+ }
988
+ });
989
+ addMiddleware({
990
+ entrypoint: "bearminion/hosted-astro",
991
+ order: "pre"
992
+ });
993
+ } }
994
+ };
995
+ }
996
+ //#endregion
2563
997
  //#region src/astro.ts
2564
998
  /**
2565
999
  * `bearminion/astro`: the server side. The dev-only Astro integration, the content store it writes through, and the
@@ -2571,4 +1005,4 @@ function isErrno(error) {
2571
1005
  */
2572
1006
  var astro_default = bearminion;
2573
1007
  //#endregion
2574
- export { StoreError, StoreKeyError, bearminion, createFileStore, astro_default as default, githubStore, loadContent, loadPages, loadSite };
1008
+ export { StoreError, StoreKeyError, bearminion, bearminionHostedEditor, createFileStore, astro_default as default, githubStore, loadContent, loadPages, loadSite };