bearminion 1.13.0 → 1.15.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.
@@ -0,0 +1,1755 @@
1
+ import { a as imageFields, c as ContentReadError, l as ContentValidationError, t as PreviewUnavailableError } from "./preview-ImEm3T8k.js";
2
+ import { c as withoutOrphanSections, d as isOrphanSection, i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema, s as slugSchema } from "./page-wlcQJAA-.js";
3
+ import { r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
4
+ import { C as missingAssetIssues, S as isAssetPath, T as formatBytes, b as describeSiteRef, c as projectId, v as assetRefs, w as DEFAULT_IMAGE_BYTE_LIMIT, y as describePageRef } from "./draft-store-BaZYEe56.js";
5
+ import { z } from "zod";
6
+ //#region src/request-guards.ts
7
+ const JSON_BODY_LIMIT = 1048576;
8
+ DEFAULT_IMAGE_BYTE_LIMIT + 262144;
9
+ const LOCAL_HOSTS = /* @__PURE__ */ new Set([
10
+ "localhost",
11
+ "127.0.0.1",
12
+ "::1"
13
+ ]);
14
+ function hostnameFromHostHeader(host) {
15
+ if (host === null) return null;
16
+ const trimmed = host.trim().toLowerCase();
17
+ if (trimmed === "") return null;
18
+ if (trimmed.startsWith("[")) {
19
+ const end = trimmed.indexOf("]");
20
+ if (end <= 1) return null;
21
+ return trimmed.slice(1, end);
22
+ }
23
+ const colon = trimmed.lastIndexOf(":");
24
+ if (colon === -1) return trimmed;
25
+ const maybePort = trimmed.slice(colon + 1);
26
+ if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
27
+ return trimmed;
28
+ }
29
+ function isLocalHostname(hostname) {
30
+ return hostname !== null && LOCAL_HOSTS.has(hostname);
31
+ }
32
+ function isLocalAddress(address) {
33
+ if (!address) return false;
34
+ const normalized = address.toLowerCase().replace(/^::ffff:/, "");
35
+ return normalized === "127.0.0.1" || normalized === "::1";
36
+ }
37
+ /**
38
+ * Allow the request when Host is local and, if Origin is present, its host is local. When the browser sends
39
+ * `Sec-Fetch-Site`, it must be `same-origin` or `none` (typed in, or a tool such as curl), so a page on another
40
+ * site cannot even read-probe the API with a no-cors GET, which carries no Origin.
41
+ * When `remoteAddress` is provided it must be a loopback address. Omit it only in tests
42
+ * that do not model a socket; the dev middleware always passes it.
43
+ */
44
+ function isLocalRequest(headers, remoteAddress) {
45
+ if (!isLocalHostname(hostnameFromHostHeader(headers.get("host")))) return false;
46
+ const site = headers.get("sec-fetch-site");
47
+ if (site !== null && site !== "same-origin" && site !== "none") return false;
48
+ const origin = headers.get("origin");
49
+ if (origin !== null) {
50
+ let hostname;
51
+ try {
52
+ hostname = new URL(origin).hostname.toLowerCase();
53
+ } catch {
54
+ return false;
55
+ }
56
+ if (!isLocalHostname(hostname)) return false;
57
+ }
58
+ if (remoteAddress !== void 0 && !isLocalAddress(remoteAddress)) return false;
59
+ return true;
60
+ }
61
+ /**
62
+ * The check for a hosted editor, where the caller has already signed the person in: the request must come from this
63
+ * site's own pages. The browser's `Sec-Fetch-Site` must be `same-origin` or `none`, and an `Origin`, when sent, must
64
+ * name the host the request went to (its URL, or the Host header). That refuses a form or script on another site that rides on the person's cookie.
65
+ */
66
+ function isSameOriginRequest(headers, url) {
67
+ const site = headers.get("sec-fetch-site");
68
+ if (site !== null && site !== "same-origin" && site !== "none") return false;
69
+ const origin = headers.get("origin");
70
+ if (origin === null) return true;
71
+ try {
72
+ const hosts = /* @__PURE__ */ new Set([new URL(url).host.toLowerCase()]);
73
+ const header = headers.get("host");
74
+ if (header !== null) hosts.add(header.trim().toLowerCase());
75
+ return hosts.has(new URL(origin).host.toLowerCase());
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+ /** Decode one URL segment and accept it only when it is a content slug. */
81
+ function readSlug(segment) {
82
+ let decoded;
83
+ try {
84
+ decoded = decodeURIComponent(segment);
85
+ } catch {
86
+ return null;
87
+ }
88
+ if (decoded.includes("\0") || decoded.includes("/") || decoded.includes("\\") || decoded.includes("..")) return null;
89
+ const parsed = slugSchema.safeParse(decoded);
90
+ return parsed.success ? parsed.data : null;
91
+ }
92
+ //#endregion
93
+ //#region src/video-sniff.ts
94
+ const MIME_TO_KIND$1 = {
95
+ "video/mp4": "mp4",
96
+ "video/x-m4v": "mp4",
97
+ "video/quicktime": "mov",
98
+ "video/webm": "webm",
99
+ "video/ogg": "ogv"
100
+ };
101
+ /** Default cap for one uploaded video. */
102
+ const DEFAULT_VIDEO_BYTE_LIMIT = 52428800;
103
+ /** Room for multipart boundaries around a max-size video. */
104
+ function videoBodyLimit(maxVideoBytes) {
105
+ return maxVideoBytes + 262144;
106
+ }
107
+ /** The container a file really is, from its first bytes. The file's name and declared type are not trusted. */
108
+ function sniffVideo(bytes) {
109
+ if (bytes.length >= 12 && ascii$1(bytes, 4, 8) === "ftyp") {
110
+ const brand = ascii$1(bytes, 8, 12);
111
+ if (brand === "avif" || brand === "avis") return null;
112
+ return brand === "qt " ? "mov" : "mp4";
113
+ }
114
+ 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;
115
+ if (bytes.length >= 4 && ascii$1(bytes, 0, 4) === "OggS") return "ogv";
116
+ return null;
117
+ }
118
+ function videoKindFromMime(mime) {
119
+ const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
120
+ return MIME_TO_KIND$1[base] ?? null;
121
+ }
122
+ function ascii$1(bytes, from, to) {
123
+ let text = "";
124
+ for (const byte of bytes.subarray(from, to)) text += String.fromCharCode(byte);
125
+ return text;
126
+ }
127
+ //#endregion
128
+ //#region src/stable-json.ts
129
+ /**
130
+ * Pretty JSON with sorted object keys and a trailing newline.
131
+ * Arrays keep their order. Two writes of the same value match byte for byte.
132
+ */
133
+ function stableStringify(value) {
134
+ return `${JSON.stringify(sortKeys(value), null, 2)}\n`;
135
+ }
136
+ function sortKeys(value) {
137
+ if (Array.isArray(value)) return value.map((item) => sortKeys(item));
138
+ if (value !== null && typeof value === "object") {
139
+ const source = value;
140
+ const sorted = {};
141
+ for (const key of Object.keys(source).sort()) sorted[key] = sortKeys(source[key]);
142
+ return sorted;
143
+ }
144
+ return value;
145
+ }
146
+ //#endregion
147
+ //#region src/upload-names.ts
148
+ const IMAGE_EXTENSION = {
149
+ png: ".png",
150
+ jpeg: ".jpg",
151
+ webp: ".webp",
152
+ gif: ".gif",
153
+ avif: ".avif"
154
+ };
155
+ const EXTENSIONS = Object.values(IMAGE_EXTENSION);
156
+ /** True for a file name with an image extension the editor handles. */
157
+ function hasImageExtension(name) {
158
+ const dot = name.lastIndexOf(".");
159
+ return dot > 0 && EXTENSIONS.includes(name.slice(dot).toLowerCase());
160
+ }
161
+ /** A plain image file name: no folders, no leading dot, an extension the editor handles. */
162
+ function isUploadFilename(name) {
163
+ return name !== "" && !name.includes("/") && !name.includes("\\") && !name.startsWith(".") && hasImageExtension(name);
164
+ }
165
+ /** The readable part of an upload's name: the original file name, lowercase ASCII, at most 48 characters. */
166
+ const PLAIN_LETTERS = {
167
+ ł: "l",
168
+ đ: "d",
169
+ ø: "o",
170
+ ð: "d",
171
+ þ: "th",
172
+ ß: "ss",
173
+ æ: "ae",
174
+ œ: "oe",
175
+ ı: "i"
176
+ };
177
+ function uploadStem(originalName) {
178
+ 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";
179
+ }
180
+ /** `photo-1a2b3c4d.jpg`: the stem, eight random hex digits, the extension for the sniffed kind. */
181
+ function uploadFilename(originalName, kind) {
182
+ const random = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(4));
183
+ const suffix = Array.from(random, (byte) => byte.toString(16).padStart(2, "0")).join("");
184
+ return `${uploadStem(originalName)}-${suffix}${IMAGE_EXTENSION[kind]}`;
185
+ }
186
+ //#endregion
187
+ //#region src/image-sniff.ts
188
+ const MIME_TO_KIND = {
189
+ "image/png": "png",
190
+ "image/jpeg": "jpeg",
191
+ "image/webp": "webp",
192
+ "image/gif": "gif",
193
+ "image/avif": "avif"
194
+ };
195
+ function sniffImage(bytes) {
196
+ if (isPng(bytes)) return "png";
197
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpeg";
198
+ if (isGif(bytes)) return "gif";
199
+ if (isWebp(bytes)) return "webp";
200
+ if (isAvif(bytes)) return "avif";
201
+ return null;
202
+ }
203
+ function kindFromMime(mime) {
204
+ const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
205
+ return MIME_TO_KIND[base] ?? null;
206
+ }
207
+ function imageTooLarge(size, maxBytes = DEFAULT_IMAGE_BYTE_LIMIT) {
208
+ return size > maxBytes;
209
+ }
210
+ /** The largest request body an image upload may have: the file plus room for the multipart boundaries. */
211
+ function imageBodyLimit(maxBytes) {
212
+ return maxBytes + 262144;
213
+ }
214
+ function isPng(bytes) {
215
+ 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;
216
+ }
217
+ function isGif(bytes) {
218
+ if (bytes.length < 6) return false;
219
+ const header = ascii(bytes.subarray(0, 6));
220
+ return header === "GIF87a" || header === "GIF89a";
221
+ }
222
+ function isWebp(bytes) {
223
+ return bytes.length >= 12 && ascii(bytes.subarray(0, 4)) === "RIFF" && ascii(bytes.subarray(8, 12)) === "WEBP";
224
+ }
225
+ function isAvif(bytes) {
226
+ if (bytes.length < 12 || ascii(bytes.subarray(4, 8)) !== "ftyp") return false;
227
+ const brand = ascii(bytes.subarray(8, 12));
228
+ if (brand === "avif" || brand === "avis") return true;
229
+ return ascii(bytes.subarray(16)).includes("avif") || ascii(bytes.subarray(16)).includes("avis");
230
+ }
231
+ function ascii(bytes) {
232
+ const sample = bytes.byteLength > 64 ? bytes.subarray(0, 64) : bytes;
233
+ let text = "";
234
+ for (const byte of sample) text += String.fromCharCode(byte & 127);
235
+ return text;
236
+ }
237
+ //#endregion
238
+ //#region src/store-error.ts
239
+ /** A key that is empty, absolute or leaves the content directory. */
240
+ var StoreKeyError = class extends Error {
241
+ constructor(key) {
242
+ super(`"${key}" is not a path inside the content directory.`);
243
+ this.name = "StoreKeyError";
244
+ }
245
+ };
246
+ /**
247
+ * A store that could not do what was asked, for a reason the person editing can act on (a refused token, a protected
248
+ * branch, a branch that moved). The editor API answers it with `status` and `code`, so the message reaches the page
249
+ * instead of becoming a bare 500.
250
+ */
251
+ var StoreError = class extends Error {
252
+ status;
253
+ code;
254
+ constructor(status, code, message) {
255
+ super(message);
256
+ this.name = "StoreError";
257
+ this.status = status;
258
+ this.code = code;
259
+ }
260
+ };
261
+ //#endregion
262
+ //#region src/store-core.ts
263
+ const SITE_KEY = "site.json";
264
+ const PAGES_DIR = "pages";
265
+ /** The key of the page with this slug. The slug must already be validated (`readSlug`). */
266
+ function pageKey(slug) {
267
+ return `${PAGES_DIR}/${slug}.json`;
268
+ }
269
+ //#endregion
270
+ //#region src/git-types.ts
271
+ /** Longest commit message the editor sends. */
272
+ const COMMIT_MESSAGE_LIMIT = 1e3;
273
+ var GitError = class extends Error {
274
+ code;
275
+ constructor(code, message) {
276
+ super(message);
277
+ this.code = code;
278
+ }
279
+ };
280
+ /** The port of a context with none: Commit changes is off. */
281
+ const NO_GIT = {
282
+ async info() {
283
+ return {
284
+ enabled: false,
285
+ repo: false,
286
+ files: []
287
+ };
288
+ },
289
+ async commit() {
290
+ throw new GitError("disabled", "Git commits are off. Set `git: true` in the bearminion() options.");
291
+ }
292
+ };
293
+ //#endregion
294
+ //#region src/history-types.ts
295
+ const ID = /^\d{8}T\d{9}Z$/;
296
+ function isHistoryId(value) {
297
+ return ID.test(value);
298
+ }
299
+ /** `2026-10-13T12:55:30.123Z` → `20261013T125530123Z`. */
300
+ function historyId(date) {
301
+ return date.toISOString().replace(/[-:.]/g, "");
302
+ }
303
+ /** The port of a context with none (a hosted editor, where the repository is the history): nothing is kept. */
304
+ const NO_HISTORY = {
305
+ async list() {
306
+ return [];
307
+ },
308
+ async read() {
309
+ return null;
310
+ },
311
+ async write() {},
312
+ async ensureBaseline() {}
313
+ };
314
+ //#endregion
315
+ //#region src/validate.ts
316
+ function fieldIssues(error) {
317
+ return error.issues.map((issue) => ({
318
+ path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
319
+ message: issue.message
320
+ }));
321
+ }
322
+ function validateSite(input, site) {
323
+ return site.schema.safeParse(input);
324
+ }
325
+ /** Validate a page document: its own fields, and each section against the registry's schema for its type. */
326
+ function validatePage(input, registry) {
327
+ return createPageSchema$1(registry).safeParse(input);
328
+ }
329
+ /**
330
+ * Validate a page for the editor: like {@link validatePage}, but a section of a type the registry no longer
331
+ * defines is kept as it is. The site build still rejects such a page until the section is removed.
332
+ */
333
+ function validateEditorPage(input, registry) {
334
+ return createTolerantPageSchema(registry).safeParse(input);
335
+ }
336
+ //#endregion
337
+ //#region src/api.ts
338
+ /**
339
+ * Dev-server API. Returns null when the URL is not under {@link API_PREFIX}
340
+ * so other middleware can continue. Every write is schema-checked first.
341
+ */
342
+ async function handleEditorRequest(request, context, meta = {}) {
343
+ try {
344
+ return await route(request, context, meta);
345
+ } catch (error) {
346
+ if (error instanceof StoreError) return problem(error.status, error.code, error.message);
347
+ throw error;
348
+ }
349
+ }
350
+ async function route(request, context, meta) {
351
+ const pathname = stripTrailingSlash(new URL(request.url).pathname);
352
+ if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
353
+ if (meta.authenticated) {
354
+ if (!isSameOriginRequest(request.headers, request.url)) return problem(403, "forbidden", "The editor API refuses cross-site requests.");
355
+ } else if (!isLocalRequest(request.headers, meta.remoteAddress)) return problem(403, "forbidden", "The editor API only accepts requests from localhost.");
356
+ const parts = pathname.slice(API_PREFIX.length).replace(/^\//, "").split("/").filter((part) => part !== "");
357
+ const method = request.method.toUpperCase();
358
+ if (parts.length === 1 && parts[0] === "schema") {
359
+ if (method === "GET") return getSchema(context);
360
+ return methodNotAllowed(["GET"]);
361
+ }
362
+ if (parts.length === 1 && parts[0] === "site") {
363
+ if (method === "GET") return getSite(scoped(context, "site"));
364
+ if (method === "PUT") return putSite(request, scoped(context, "site"));
365
+ return methodNotAllowed(["GET", "PUT"]);
366
+ }
367
+ if (parts.length === 1 && parts[0] === "save") {
368
+ if (method === "POST") return postSave(request, scoped(context, "edits"));
369
+ return methodNotAllowed(["POST"]);
370
+ }
371
+ if (parts.length === 1 && parts[0] === "pages") {
372
+ if (method === "GET") return getPages(context);
373
+ if (method === "POST") return createPage(request, context);
374
+ return methodNotAllowed(["GET", "POST"]);
375
+ }
376
+ if (parts.length === 1 && parts[0] === "forms") {
377
+ if (method === "GET") return getForms(context);
378
+ return methodNotAllowed(["GET"]);
379
+ }
380
+ if (parts.length === 1 && parts[0] === "git") {
381
+ if (method === "GET") return getGit(context);
382
+ return methodNotAllowed(["GET"]);
383
+ }
384
+ if (parts.length === 2 && parts[0] === "git" && parts[1] === "commit") {
385
+ if (method === "POST") return postCommit(request, context);
386
+ return methodNotAllowed(["POST"]);
387
+ }
388
+ if (parts.length === 1 && parts[0] === "images") {
389
+ if (method === "GET") return getImages(scoped(context, "uploads"));
390
+ if (method === "POST") return postImage(request, scoped(context, "uploads"));
391
+ return methodNotAllowed(["GET", "POST"]);
392
+ }
393
+ if (parts.length === 2 && parts[0] === "images") {
394
+ if (method === "DELETE") return removeImage(scoped(context, "uploads"), decodeSegment(parts[1] ?? ""));
395
+ return methodNotAllowed(["DELETE"]);
396
+ }
397
+ if (parts.length === 1 && parts[0] === "videos") {
398
+ if (method === "GET") return getVideos(context);
399
+ if (method === "POST") return postVideo(request, context);
400
+ return methodNotAllowed(["GET", "POST"]);
401
+ }
402
+ if (parts.length === 2 && parts[0] === "videos") {
403
+ if (method === "DELETE") return removeVideo(context, decodeSegment(parts[1] ?? ""));
404
+ return methodNotAllowed(["DELETE"]);
405
+ }
406
+ if (parts.length === 1 && parts[0] === "preview") {
407
+ if (method === "POST") return postPreview(request, context, meta);
408
+ return methodNotAllowed(["POST"]);
409
+ }
410
+ if (parts.length === 2 && parts[0] === "preview" && parts[1] === "site") {
411
+ if (method === "POST") return postSitePreview(request, context, meta);
412
+ return methodNotAllowed(["POST"]);
413
+ }
414
+ if (parts[0] === "history" && (parts[1] === "site" || parts[1] === "pages")) {
415
+ if (method !== "GET") return methodNotAllowed(["GET"]);
416
+ if (parts[1] === "site" && parts.length <= 3) return getHistory(context, "site", "", parts[2]);
417
+ if (parts[1] === "pages" && parts.length >= 3 && parts.length <= 4) {
418
+ const slug = readSlug(parts[2] ?? "");
419
+ if (slug === null) return badSlug();
420
+ return getHistory(context, "page", slug, parts[3]);
421
+ }
422
+ }
423
+ if (parts.length === 2 && parts[0] === "pages") {
424
+ const slug = readSlug(parts[1] ?? "");
425
+ if (slug === null) return badSlug();
426
+ const entry = scoped(context, `page:${slug}`);
427
+ if (method === "GET") return getPage(entry, slug);
428
+ if (method === "PUT") return putPage(request, entry, slug);
429
+ if (method === "DELETE") return deletePage(entry, slug);
430
+ return methodNotAllowed([
431
+ "GET",
432
+ "PUT",
433
+ "DELETE"
434
+ ]);
435
+ }
436
+ if (parts.length === 3 && parts[0] === "pages" && parts[2] === "rename") {
437
+ const slug = readSlug(parts[1] ?? "");
438
+ if (slug === null) return badSlug();
439
+ if (method === "POST") return renamePage(request, scoped(context, `page:${slug}`), slug);
440
+ return methodNotAllowed(["POST"]);
441
+ }
442
+ if (parts.length === 3 && parts[0] === "pages" && parts[2] === "set-home") {
443
+ const slug = readSlug(parts[1] ?? "");
444
+ if (slug === null) return badSlug();
445
+ if (method === "POST") return setHome(request, scoped(context, `page:${slug}`), slug);
446
+ return methodNotAllowed(["POST"]);
447
+ }
448
+ return problem(404, "not_found", "Unknown editor API route.");
449
+ }
450
+ /**
451
+ * Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
452
+ * created while `astro dev` runs shows up at once.
453
+ */
454
+ async function getForms(context) {
455
+ const handlers = {};
456
+ for (const definition of Object.values(context.sections)) {
457
+ const name = definition.form;
458
+ if (!name || handlers[name]) continue;
459
+ const file = context.formFile?.(name) ?? null;
460
+ handlers[name] = { file: file ? relativeTo(context.root, file) : null };
461
+ }
462
+ return json(200, {
463
+ enabled: context.formsDir != null,
464
+ handlers
465
+ });
466
+ }
467
+ function relativeTo(root, file) {
468
+ const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
469
+ return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
470
+ }
471
+ /**
472
+ * The context for editing one entry. A store that keeps each entry's pending edits apart (`githubStore` in `pr` mode)
473
+ * hands out a view of its own; every other store is used as it is.
474
+ */
475
+ const history = (context) => context.history ?? NO_HISTORY;
476
+ function scoped(context, scope) {
477
+ const store = context.store.scoped?.(scope);
478
+ return store ? {
479
+ ...context,
480
+ store
481
+ } : context;
482
+ }
483
+ async function getSchema(context) {
484
+ const sectionDefaults = {};
485
+ const sectionLabels = {};
486
+ const sectionDescriptions = {};
487
+ const sectionWireframes = {};
488
+ const sectionOptions = {};
489
+ const optionalContent = {};
490
+ const contentCounts = { ...context.site.counts };
491
+ const fieldChoices = {};
492
+ const fieldIcons = {};
493
+ const showWhen = {};
494
+ const fieldImages = {};
495
+ const sectionForms = {};
496
+ for (const definition of Object.values(context.sections)) {
497
+ const type = definition.type;
498
+ if (definition.form) sectionForms[type] = definition.form;
499
+ sectionDefaults[type] = definition.defaults;
500
+ sectionLabels[type] = definition.label;
501
+ sectionDescriptions[type] = definition.description;
502
+ sectionWireframes[type] = definition.wireframe;
503
+ sectionOptions[type] = definition.options;
504
+ optionalContent[type] = definition.optional;
505
+ if (Object.keys(definition.counts).length > 0) contentCounts[type] = { ...definition.counts };
506
+ if (Object.keys(definition.choices).length > 0) fieldChoices[type] = definition.choices;
507
+ if (Object.keys(definition.icons).length > 0) fieldIcons[type] = definition.icons;
508
+ if (Object.keys(definition.showWhen).length > 0) showWhen[type] = definition.showWhen;
509
+ const images = imageFields(definition.schema);
510
+ if (images.length > 0) fieldImages[type] = images;
511
+ }
512
+ return json(200, {
513
+ sectionOptions,
514
+ siteOptions: context.site.options,
515
+ siteLimits: context.site.limits,
516
+ theme: context.theme,
517
+ contentCounts,
518
+ optionalContent,
519
+ fieldChoices,
520
+ fieldIcons,
521
+ fieldImages,
522
+ showWhen,
523
+ sectionForms,
524
+ pageRules: context.pageRules,
525
+ sectionDefaults,
526
+ sectionLabels,
527
+ sectionDescriptions,
528
+ sectionWireframes,
529
+ projectId: projectId(context.root, await siteName(context))
530
+ });
531
+ }
532
+ async function siteName(context) {
533
+ try {
534
+ return (await readSite(context)).name;
535
+ } catch {
536
+ return "";
537
+ }
538
+ }
539
+ async function getSite(context) {
540
+ try {
541
+ return json(200, await readSite(context));
542
+ } catch (error) {
543
+ return contentFailure(error);
544
+ }
545
+ }
546
+ async function putSite(request, context) {
547
+ const body = await readJsonBody(request);
548
+ if (body.response) return body.response;
549
+ const parsed = validateSite(body.value, context.site);
550
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
551
+ const missing = await missingAssets(context, parsed.data);
552
+ if (missing.length > 0) return validation(missing);
553
+ await history(context).ensureBaseline("site", "", await readStoredJson(context, SITE_KEY, "site"));
554
+ await writeDocuments(context, [[SITE_KEY, parsed.data]]);
555
+ await history(context).write("site", "", parsed.data);
556
+ return json(200, parsed.data);
557
+ }
558
+ /** The parsed document at `key`, upgraded to the current version, or undefined when it is missing or not JSON. */
559
+ async function readStoredJson(context, key, kind) {
560
+ try {
561
+ const text = await context.store.read(key);
562
+ if (text === void 0) return void 0;
563
+ const upgraded = context.migrator.upgrade(JSON.parse(text), kind);
564
+ return upgraded.ok ? upgraded.value : void 0;
565
+ } catch (error) {
566
+ if (error instanceof StoreError) throw error;
567
+ return;
568
+ }
569
+ }
570
+ /** Write documents in the layout every file uses (sorted keys, two spaces, trailing newline). */
571
+ async function writeDocuments(context, documents, removals = []) {
572
+ await context.store.apply([...documents.map(([key, value]) => ({
573
+ type: "write",
574
+ key,
575
+ text: stableStringify(context.migrator.stamp(value))
576
+ })), ...removals.map((key) => ({
577
+ type: "remove",
578
+ key
579
+ }))]);
580
+ }
581
+ const saveSchema = z.object({
582
+ page: z.object({
583
+ /** The slug the page is stored under now. The document's own `slug` is where it goes. */
584
+ from: z.string(),
585
+ document: z.unknown(),
586
+ /** Where the current home page moves when this page becomes `index`. */
587
+ previousHomeSlug: z.string().optional()
588
+ }).strict().optional(),
589
+ site: z.unknown().optional()
590
+ }).strict().refine((value) => value.page !== void 0 || value.site !== void 0, { message: "Nothing to save." });
591
+ /**
592
+ * Save the editor draft in one request: a page (with its rename or promotion to home, when the slug
593
+ * changed) and the site. Every document is validated before anything is written, and all writes and
594
+ * removals go to the store as one `apply`, so a failure never leaves a page renamed with stale content
595
+ * or the page saved without the site.
596
+ */
597
+ async function postSave(request, context) {
598
+ const body = await readJsonBody(request);
599
+ if (body.response) return body.response;
600
+ const parsed = saveSchema.safeParse(body.value);
601
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
602
+ const writes = [];
603
+ const removals = [];
604
+ const after = [];
605
+ const result = {};
606
+ const failures = [];
607
+ if (parsed.data.site !== void 0) {
608
+ const upgraded = context.migrator.upgrade(parsed.data.site, "site");
609
+ if (!upgraded.ok) failures.push(...tagIssues([{
610
+ path: SCHEMA_VERSION_KEY,
611
+ message: upgraded.message
612
+ }], "site"));
613
+ else {
614
+ const site = validateSite(upgraded.value, context.site);
615
+ const missing = site.success ? await missingAssets(context, site.data) : [];
616
+ if (!site.success) failures.push(...tagIssues(fieldIssues(site.error), "site"));
617
+ else if (missing.length > 0) failures.push(...tagIssues(missing, "site"));
618
+ else {
619
+ const stored = await readStoredJson(context, SITE_KEY, "site");
620
+ writes.push([SITE_KEY, site.data]);
621
+ after.push(async () => {
622
+ await history(context).ensureBaseline("site", "", stored);
623
+ await history(context).write("site", "", site.data);
624
+ });
625
+ result.site = site.data;
626
+ }
627
+ }
628
+ }
629
+ if (parsed.data.page !== void 0) {
630
+ const planned = await planPageSave(context, parsed.data.page);
631
+ if (planned.issues) failures.push(...tagIssues(planned.issues, "page"));
632
+ else if (planned.response) {
633
+ if (failures.length === 0) return planned.response;
634
+ } else {
635
+ writes.push(...planned.writes);
636
+ removals.push(...planned.removals);
637
+ after.push(planned.after);
638
+ result.page = planned.page;
639
+ }
640
+ }
641
+ if (failures.length > 0) return validation(failures);
642
+ const written = new Set(writes.map(([key]) => key));
643
+ await writeDocuments(context, writes, removals.filter((key) => !written.has(key)));
644
+ for (const step of after) await step();
645
+ return json(200, result);
646
+ }
647
+ async function planPageSave(context, input) {
648
+ const from = readSlug(input.from);
649
+ if (from === null) return { response: badSlug() };
650
+ const upgraded = context.migrator.upgrade(input.document, "page");
651
+ if (!upgraded.ok) return { issues: [{
652
+ path: SCHEMA_VERSION_KEY,
653
+ message: upgraded.message
654
+ }] };
655
+ const parsed = validateEditorPage(upgraded.value, context.sections);
656
+ if (!parsed.success) return { issues: fieldIssues(parsed.error) };
657
+ const page = parsed.data;
658
+ const target = page.slug;
659
+ const missing = await missingAssets(context, page);
660
+ if (missing.length > 0) return { issues: missing };
661
+ const loaded = await loadStoredPages(context);
662
+ if (loaded.response) return { response: loaded.response };
663
+ const found = loaded.pages.find((entry) => entry.page.slug === from);
664
+ if (!found) return { response: problem(404, "not_found", `No page with slug "${from}".`) };
665
+ const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
666
+ const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
667
+ path: `sections.${index}.type`,
668
+ message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
669
+ }] : []);
670
+ if (added.length > 0) return { issues: added };
671
+ const after = async () => {
672
+ await history(context).ensureBaseline("page", target, found.page);
673
+ await history(context).write("page", target, page);
674
+ };
675
+ if (target === from) return {
676
+ page,
677
+ writes: [[found.key, page]],
678
+ removals: [],
679
+ after
680
+ };
681
+ if (!context.pageRules.rename) return { response: locked("rename") };
682
+ if (from === "index") return { response: problem(409, "conflict", "The home page slug stays index. Set another page as home to move it.") };
683
+ if (isSystemPage(from) || isSystemPage(target)) return { response: problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.") };
684
+ if (target !== "index") {
685
+ if (loaded.pages.some((entry) => entry.page.slug === target)) return { response: problem(409, "conflict", `A page with slug "${target}" already exists.`) };
686
+ const nextKey = pageKey(target);
687
+ if (await context.store.exists(nextKey)) return { response: problem(409, "conflict", `A file named ${target}.json already exists.`) };
688
+ return {
689
+ page,
690
+ writes: [[nextKey, page]],
691
+ removals: [found.key],
692
+ after
693
+ };
694
+ }
695
+ const indexKey = pageKey("index");
696
+ const home = loaded.pages.find((entry) => entry.page.slug === "index");
697
+ if (!home) {
698
+ if (await context.store.exists(indexKey)) return { response: problem(409, "conflict", "A file named index.json already exists.") };
699
+ return {
700
+ page,
701
+ writes: [[indexKey, page]],
702
+ removals: [found.key],
703
+ after
704
+ };
705
+ }
706
+ const previousSlug = input.previousHomeSlug === void 0 ? null : readSlug(input.previousHomeSlug);
707
+ if (previousSlug === null || previousSlug === "index" || isSystemPage(previousSlug)) return { response: problem(400, "invalid_slug", "previousHomeSlug is required to move the current home page.") };
708
+ if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return { response: problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`) };
709
+ const previousKey = pageKey(previousSlug);
710
+ if (await context.store.exists(previousKey)) return { response: problem(409, "conflict", `A file named ${previousSlug}.json already exists.`) };
711
+ const moved = validateEditorPage({
712
+ ...home.page,
713
+ slug: previousSlug
714
+ }, context.sections);
715
+ if (!moved.success) return { issues: fieldIssues(moved.error) };
716
+ return {
717
+ page,
718
+ writes: [[previousKey, moved.data], [indexKey, page]],
719
+ removals: [...home.key === indexKey ? [] : [home.key], found.key],
720
+ after
721
+ };
722
+ }
723
+ const commitSchema = z.object({
724
+ message: z.string().max(COMMIT_MESSAGE_LIMIT),
725
+ paths: z.array(z.string().min(1).max(512)).max(500).optional()
726
+ }).strict();
727
+ async function getGit(context) {
728
+ return json(200, await (context.commits ?? NO_GIT).info());
729
+ }
730
+ async function postCommit(request, context) {
731
+ const body = await readJsonBody(request);
732
+ if (body.response) return body.response;
733
+ const parsed = commitSchema.safeParse(body.value);
734
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
735
+ try {
736
+ return json(201, await (context.commits ?? NO_GIT).commit(parsed.data.message, parsed.data.paths));
737
+ } catch (error) {
738
+ if (!(error instanceof GitError)) throw error;
739
+ return problem(error.code === "failed" ? 500 : error.code === "invalid" ? 400 : 409, `git_${error.code}`, error.message);
740
+ }
741
+ }
742
+ async function getHistory(context, scope, slug, id) {
743
+ if (id === void 0) return json(200, { entries: await history(context).list(scope, slug) });
744
+ if (!isHistoryId(id)) return problem(400, "invalid_id", "Not a history id.");
745
+ const snapshot = await history(context).read(scope, slug, id);
746
+ if (snapshot === null) return problem(404, "not_found", "No saved version with that id.");
747
+ return json(200, snapshot);
748
+ }
749
+ async function getPages(context) {
750
+ const loaded = await loadStoredPages(context);
751
+ if (loaded.response) return loaded.response;
752
+ return json(200, { pages: loaded.pages.map((entry) => ({
753
+ slug: entry.page.slug,
754
+ title: entry.page.title,
755
+ file: entry.fileName,
756
+ system: isSystemPage(entry.page.slug),
757
+ anchors: entry.page.sections.flatMap((section) => "anchor" in section && typeof section.anchor === "string" && section.anchor !== "" ? [section.anchor] : [])
758
+ })) });
759
+ }
760
+ async function getPage(context, slug) {
761
+ const loaded = await loadStoredPages(context);
762
+ if (loaded.response) return loaded.response;
763
+ const found = loaded.pages.find((entry) => entry.page.slug === slug);
764
+ if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
765
+ return json(200, found.page);
766
+ }
767
+ async function putPage(request, context, slug) {
768
+ const body = await readJsonBody(request);
769
+ if (body.response) return body.response;
770
+ const parsed = validateEditorPage(body.value, context.sections);
771
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
772
+ const page = parsed.data;
773
+ if (page.slug !== slug) return problem(400, "slug_mismatch", `Slug in the body must be "${slug}". Rename the page with POST /pages/${slug}/rename.`);
774
+ const missing = await missingAssets(context, page);
775
+ if (missing.length > 0) return validation(missing);
776
+ const loaded = await loadStoredPages(context);
777
+ if (loaded.response) return loaded.response;
778
+ const found = loaded.pages.find((entry) => entry.page.slug === slug);
779
+ if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
780
+ const stored = new Set(found.page.sections.filter((section) => isOrphanSection(context.sections, section)).map(orphanKey));
781
+ const added = page.sections.flatMap((section, index) => isOrphanSection(context.sections, section) && !stored.has(orphanKey(section)) ? [{
782
+ path: `sections.${index}.type`,
783
+ message: `Unknown section type "${section.type}". Expected one of: ${Object.keys(context.sections).join(", ")}.`
784
+ }] : []);
785
+ if (added.length > 0) return validation(added);
786
+ await history(context).ensureBaseline("page", slug, found.page);
787
+ await writeDocuments(context, [[found.key, page]]);
788
+ await history(context).write("page", slug, page);
789
+ return json(200, page);
790
+ }
791
+ const orphanKey = (section) => `${section.id}:${section.type}`;
792
+ async function createPage(request, baseContext) {
793
+ const body = await readJsonBody(request);
794
+ if (body.response) return body.response;
795
+ const parsed = createPageSchema.safeParse(body.value);
796
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
797
+ const context = scoped(baseContext, `page:${parsed.data.slug}`);
798
+ if (isSystemPage(parsed.data.slug)) return problem(409, "reserved_slug", `"${parsed.data.slug}" is a system page and cannot be created.`);
799
+ const loaded = await loadStoredPages(context, { allowMissing: true });
800
+ if (loaded.response) return loaded.response;
801
+ if (loaded.pages.some((entry) => entry.page.slug === parsed.data.slug)) return problem(409, "conflict", `A page with slug "${parsed.data.slug}" already exists.`);
802
+ const key = pageKey(parsed.data.slug);
803
+ if (await context.store.exists(key)) return problem(409, "conflict", `A file named ${parsed.data.slug}.json already exists.`);
804
+ const drafted = draftPage(parsed.data, loaded.pages, context.sections);
805
+ if (drafted.response) return drafted.response;
806
+ const validated = validatePage(drafted.page, context.sections);
807
+ if (!validated.success) return validation(fieldIssues(validated.error));
808
+ await writeDocuments(context, [[key, validated.data]]);
809
+ return json(201, validated.data);
810
+ }
811
+ function locked(operation) {
812
+ return problem(409, "operation_locked", `${operation === "rename" ? "Renaming pages" : "Deleting pages"} is turned off for this site (pages.${operation} in the bearminion() options).`);
813
+ }
814
+ async function deletePage(context, slug) {
815
+ if (!context.pageRules.delete) return locked("delete");
816
+ if (slug === "index") return problem(409, "conflict", "Refusing to delete the index page.");
817
+ if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be deleted.`);
818
+ const loaded = await loadStoredPages(context);
819
+ if (loaded.response) return loaded.response;
820
+ const found = loaded.pages.find((entry) => entry.page.slug === slug);
821
+ if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
822
+ await writeDocuments(context, [], [found.key]);
823
+ return json(200, {
824
+ deleted: true,
825
+ slug
826
+ });
827
+ }
828
+ /**
829
+ * Make `slug` the home page. The current home page moves to `previousSlug`, so the
830
+ * site never has two pages at "/" and never loses its home page halfway.
831
+ */
832
+ async function setHome(request, context, slug) {
833
+ const body = await readJsonBody(request);
834
+ if (body.response) return body.response;
835
+ const parsed = setHomeSchema.safeParse(body.value);
836
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
837
+ if (!context.pageRules.rename) return locked("rename");
838
+ if (slug === "index") return problem(409, "conflict", "That page is already the home page.");
839
+ if (isSystemPage(slug)) return problem(409, "reserved_slug", `"${slug}" is a system page and cannot be the home page.`);
840
+ const loaded = await loadStoredPages(context);
841
+ if (loaded.response) return loaded.response;
842
+ const target = loaded.pages.find((entry) => entry.page.slug === slug);
843
+ if (!target) return problem(404, "not_found", `No page with slug "${slug}".`);
844
+ const previous = loaded.pages.find((entry) => entry.page.slug === "index");
845
+ const indexKey = pageKey("index");
846
+ if (previous) {
847
+ const previousSlug = parsed.data.previousSlug;
848
+ if (previousSlug === void 0 || previousSlug === "index") return problem(400, "invalid_slug", "previousSlug is required to move the current home page.");
849
+ if (loaded.pages.some((entry) => entry.page.slug === previousSlug)) return problem(409, "conflict", `A page with slug "${previousSlug}" already exists.`);
850
+ const previousKey = pageKey(previousSlug);
851
+ if (await context.store.exists(previousKey)) return problem(409, "conflict", `A file named ${previousSlug}.json already exists.`);
852
+ const moved = validateEditorPage({
853
+ ...previous.page,
854
+ slug: previousSlug
855
+ }, context.sections);
856
+ if (!moved.success) return validation(fieldIssues(moved.error));
857
+ const promoted = validateEditorPage({
858
+ ...target.page,
859
+ slug: "index"
860
+ }, context.sections);
861
+ if (!promoted.success) return validation(fieldIssues(promoted.error));
862
+ await writeDocuments(context, [[previousKey, moved.data], [indexKey, promoted.data]], [...previous.key === indexKey ? [] : [previous.key], target.key]);
863
+ return json(200, promoted.data);
864
+ }
865
+ if (await context.store.exists(indexKey)) return problem(409, "conflict", "A file named index.json already exists.");
866
+ const promoted = validateEditorPage({
867
+ ...target.page,
868
+ slug: "index"
869
+ }, context.sections);
870
+ if (!promoted.success) return validation(fieldIssues(promoted.error));
871
+ await writeDocuments(context, [[indexKey, promoted.data]], [target.key]);
872
+ return json(200, promoted.data);
873
+ }
874
+ async function renamePage(request, context, slug) {
875
+ const body = await readJsonBody(request);
876
+ if (body.response) return body.response;
877
+ const parsed = renameSchema.safeParse(body.value);
878
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
879
+ const nextSlug = parsed.data.slug;
880
+ if (!context.pageRules.rename) return locked("rename");
881
+ if (nextSlug === slug) return problem(400, "invalid_slug", "The new slug is the same as the current slug.");
882
+ if (slug === "index") return problem(409, "conflict", "Refusing to rename the index page.");
883
+ if (isSystemPage(slug) || isSystemPage(nextSlug)) return problem(409, "reserved_slug", "System pages cannot be renamed, and no page can take their slug.");
884
+ const loaded = await loadStoredPages(context);
885
+ if (loaded.response) return loaded.response;
886
+ const found = loaded.pages.find((entry) => entry.page.slug === slug);
887
+ if (!found) return problem(404, "not_found", `No page with slug "${slug}".`);
888
+ if (loaded.pages.some((entry) => entry.page.slug === nextSlug)) return problem(409, "conflict", `A page with slug "${nextSlug}" already exists.`);
889
+ const nextKey = pageKey(nextSlug);
890
+ if (await context.store.exists(nextKey)) return problem(409, "conflict", `A file named ${nextSlug}.json already exists.`);
891
+ const validated = validateEditorPage({
892
+ ...found.page,
893
+ slug: nextSlug
894
+ }, context.sections);
895
+ if (!validated.success) return validation(fieldIssues(validated.error));
896
+ await writeDocuments(context, [[nextKey, validated.data]], [found.key]);
897
+ return json(200, validated.data);
898
+ }
899
+ const previewBodySchema = z.object({
900
+ page: z.unknown(),
901
+ motion: z.boolean().optional()
902
+ }).strict();
903
+ async function postPreview(request, context, meta) {
904
+ if (!meta.renderPreview) return problem(501, "preview_unavailable", "Live preview is only available while astro dev is running.");
905
+ const body = await readJsonBody(request);
906
+ if (body.response) return body.response;
907
+ const payload = previewBodySchema.safeParse(body.value);
908
+ if (!payload.success) return validation(fieldIssues(payload.error));
909
+ const parsed = validateEditorPage(payload.data.page, context.sections);
910
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
911
+ const renderable = withoutOrphanSections(parsed.data, context.sections);
912
+ try {
913
+ return json(200, { html: await meta.renderPreview(renderable, payload.data.motion ?? true) });
914
+ } catch (error) {
915
+ if (error instanceof PreviewUnavailableError) return problem(501, "preview_unavailable", error.message);
916
+ const message = error instanceof Error ? error.message : "Preview failed.";
917
+ console.error("[bearminion] preview failed", error);
918
+ return problem(500, "preview_failed", message);
919
+ }
920
+ }
921
+ const sitePreviewBodySchema = z.object({
922
+ site: z.unknown(),
923
+ pathname: z.string().max(2048)
924
+ }).strict();
925
+ async function postSitePreview(request, context, meta) {
926
+ if (!meta.renderSitePreview) return problem(501, "preview_unavailable", "Live site preview is not available in this project.");
927
+ const body = await readJsonBody(request);
928
+ if (body.response) return body.response;
929
+ const payload = sitePreviewBodySchema.safeParse(body.value);
930
+ if (!payload.success) return validation(fieldIssues(payload.error));
931
+ const parsed = validateSite(payload.data.site, context.site);
932
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
933
+ try {
934
+ return json(200, await meta.renderSitePreview(parsed.data, payload.data.pathname));
935
+ } catch (error) {
936
+ if (error instanceof PreviewUnavailableError) return problem(501, "preview_unavailable", error.message);
937
+ const message = error instanceof Error ? error.message : "Preview failed.";
938
+ console.error("[bearminion] site preview failed", error);
939
+ return problem(500, "preview_failed", message);
940
+ }
941
+ }
942
+ async function getImages(context) {
943
+ const limits = {
944
+ maxBytes: context.maxImageBytes,
945
+ convert: context.imageConvert
946
+ };
947
+ return json(200, {
948
+ images: await context.store.uploads.list(),
949
+ limits
950
+ });
951
+ }
952
+ function decodeSegment(segment) {
953
+ try {
954
+ return decodeURIComponent(segment);
955
+ } catch {
956
+ return "";
957
+ }
958
+ }
959
+ /** Image paths that a saved file must not point at, because the file is not there. */
960
+ async function missingAssets(context, document) {
961
+ const { store } = context;
962
+ if (!store.assetExists) return [];
963
+ return missingAssetIssues(document, (src) => store.assetExists?.(src) ?? Promise.resolve(true));
964
+ }
965
+ /**
966
+ * Where the saved content uses the image at `src`: "Home page › Hero", "Site settings › brand logo". Read from the
967
+ * raw files, so a page that fails validation still counts. Unsaved drafts are not on disk: the editor checks its own
968
+ * drafts before it asks to delete, and saving a draft that still points at a deleted image fails validation.
969
+ */
970
+ async function imageUsages(context, src) {
971
+ const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
972
+ const usages = [];
973
+ const site = await readStoredJson(context, SITE_KEY, "site");
974
+ for (const ref of assetRefs(site)) if (ref.src === src) usages.push(describeSiteRef(ref));
975
+ for (const name of await context.store.list("pages") ?? []) {
976
+ if (!name.endsWith(".json") || name.startsWith(".")) continue;
977
+ const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
978
+ if (typeof page !== "object" || page === null) continue;
979
+ const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
980
+ const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
981
+ for (const ref of assetRefs(page)) if (ref.src === src) usages.push(describePageRef(ref, {
982
+ title,
983
+ sections
984
+ }, labels));
985
+ }
986
+ return usages;
987
+ }
988
+ async function removeImage(context, filename) {
989
+ const image = (await context.store.uploads.list()).find((item) => item.filename === filename);
990
+ if (!image) return problem(404, "not_found", "No uploaded image has that name.");
991
+ const usages = await imageUsages(context, image.path);
992
+ if (usages.length > 0) return json(409, {
993
+ error: "in_use",
994
+ message: `${filename} is still used: ${usages.join("; ")}. Choose another image there and save, then delete it.`,
995
+ usages
996
+ });
997
+ if (!await context.store.uploads.remove(filename)) return problem(404, "not_found", "No uploaded image has that name.");
998
+ return json(200, {
999
+ deleted: true,
1000
+ filename
1001
+ });
1002
+ }
1003
+ const NO_VIDEOS = "This content store does not take video uploads.";
1004
+ async function getVideos(context) {
1005
+ if (!context.store.videos) return json(200, {
1006
+ videos: [],
1007
+ maxBytes: context.maxVideoBytes
1008
+ });
1009
+ return json(200, {
1010
+ videos: await context.store.videos.list(),
1011
+ maxBytes: context.maxVideoBytes
1012
+ });
1013
+ }
1014
+ /** Every string in a JSON value. */
1015
+ function* strings(value) {
1016
+ if (typeof value === "string") yield value;
1017
+ else if (Array.isArray(value)) for (const item of value) yield* strings(item);
1018
+ else if (typeof value === "object" && value !== null) for (const item of Object.values(value)) yield* strings(item);
1019
+ }
1020
+ /** Where saved content links the video at `url`, named like the image usages: "Home page › Media". */
1021
+ async function videoUsages(context, url) {
1022
+ const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
1023
+ const usages = [];
1024
+ if ([...strings(await readStoredJson(context, "site.json", "site"))].includes(url)) usages.push("Site settings");
1025
+ for (const name of await context.store.list("pages") ?? []) {
1026
+ if (!name.endsWith(".json") || name.startsWith(".")) continue;
1027
+ const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
1028
+ if (typeof page !== "object" || page === null) continue;
1029
+ const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
1030
+ const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
1031
+ for (const section of sections) if ([...strings(section)].includes(url)) usages.push(`${title} › ${labels[section.type ?? ""] ?? section.type ?? "section"}`);
1032
+ }
1033
+ return usages;
1034
+ }
1035
+ async function removeVideo(context, filename) {
1036
+ const videos = context.store.videos;
1037
+ if (!videos) return problem(404, "not_found", NO_VIDEOS);
1038
+ const video = (await videos.list()).find((item) => item.filename === filename);
1039
+ if (!video) return problem(404, "not_found", "No uploaded video has that name.");
1040
+ const usages = await videoUsages(context, video.url);
1041
+ if (usages.length > 0) return json(409, {
1042
+ error: "in_use",
1043
+ message: `${filename} is still used: ${usages.join("; ")}. Choose another video there and save, then delete it.`,
1044
+ usages
1045
+ });
1046
+ if (!await videos.remove(filename)) return problem(404, "not_found", "No uploaded video has that name.");
1047
+ return json(200, {
1048
+ deleted: true,
1049
+ filename
1050
+ });
1051
+ }
1052
+ async function postVideo(request, context) {
1053
+ const videos = context.store.videos;
1054
+ if (!videos) return problem(404, "not_found", NO_VIDEOS);
1055
+ const limitMb = Math.round(context.maxVideoBytes / 1048576);
1056
+ const tooLarge = () => problem(413, "too_large", `Videos must be ${limitMb}MB or smaller. Link a hosted video instead, or compress this one.`);
1057
+ const length = contentLength(request);
1058
+ if (length !== null && length > videoBodyLimit(context.maxVideoBytes)) return tooLarge();
1059
+ if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the video as multipart/form-data.");
1060
+ let form;
1061
+ try {
1062
+ form = await request.formData();
1063
+ } catch {
1064
+ return problem(400, "invalid_upload", "The upload body could not be read.");
1065
+ }
1066
+ const entry = form.get("file");
1067
+ if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
1068
+ if (entry.size > context.maxVideoBytes) return tooLarge();
1069
+ const bytes = new Uint8Array(await entry.arrayBuffer());
1070
+ if (bytes.byteLength > context.maxVideoBytes) return tooLarge();
1071
+ const declared = videoKindFromMime(entry.type);
1072
+ const sniffed = sniffVideo(bytes);
1073
+ 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.");
1074
+ try {
1075
+ return json(201, await videos.save({
1076
+ originalName: entry.name,
1077
+ bytes,
1078
+ kind: sniffed
1079
+ }));
1080
+ } catch (error) {
1081
+ return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
1082
+ }
1083
+ }
1084
+ async function postImage(request, context) {
1085
+ const tooLarge = () => problem(413, "too_large", `Images must be ${formatBytes(context.maxImageBytes)} or smaller.`);
1086
+ const length = contentLength(request);
1087
+ if (length !== null && length > imageBodyLimit(context.maxImageBytes)) return tooLarge();
1088
+ if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the image as multipart/form-data.");
1089
+ let form;
1090
+ try {
1091
+ form = await request.formData();
1092
+ } catch {
1093
+ return problem(400, "invalid_upload", "The upload body could not be read.");
1094
+ }
1095
+ const entry = form.get("file");
1096
+ if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
1097
+ if (imageTooLarge(entry.size, context.maxImageBytes)) return tooLarge();
1098
+ const bytes = new Uint8Array(await entry.arrayBuffer());
1099
+ if (imageTooLarge(bytes.byteLength, context.maxImageBytes)) return tooLarge();
1100
+ const declared = kindFromMime(entry.type);
1101
+ const sniffed = sniffImage(bytes);
1102
+ 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.");
1103
+ try {
1104
+ return json(201, await context.store.uploads.save({
1105
+ originalName: entry.name,
1106
+ bytes,
1107
+ kind: sniffed
1108
+ }));
1109
+ } catch (error) {
1110
+ if (error instanceof StoreError) throw error;
1111
+ return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
1112
+ }
1113
+ }
1114
+ const createPageSchema = z.object({
1115
+ slug: z.string(),
1116
+ title: z.string(),
1117
+ template: z.string().min(1).optional()
1118
+ }).strict().superRefine((value, ctx) => {
1119
+ if (readSlug(value.slug) === null) ctx.addIssue({
1120
+ code: "custom",
1121
+ message: "Slug must be lowercase kebab-case (the home page uses \"index\")",
1122
+ path: ["slug"]
1123
+ });
1124
+ if (value.title.trim() === "") ctx.addIssue({
1125
+ code: "custom",
1126
+ message: "Title is required",
1127
+ path: ["title"]
1128
+ });
1129
+ });
1130
+ const setHomeSchema = z.object({
1131
+ /** Slug the current home page moves to. Required when a home page exists. */
1132
+ previousSlug: z.string().optional() }).strict().superRefine((value, ctx) => {
1133
+ if (value.previousSlug !== void 0 && readSlug(value.previousSlug) === null) ctx.addIssue({
1134
+ code: "custom",
1135
+ message: "Slug must be lowercase kebab-case",
1136
+ path: ["previousSlug"]
1137
+ });
1138
+ });
1139
+ const renameSchema = z.object({ slug: z.string() }).strict().superRefine((value, ctx) => {
1140
+ if (readSlug(value.slug) === null) ctx.addIssue({
1141
+ code: "custom",
1142
+ message: "Slug must be lowercase kebab-case (the home page uses \"index\")",
1143
+ path: ["slug"]
1144
+ });
1145
+ });
1146
+ function pageFromSection(slug, title, seo, definition) {
1147
+ const section = {
1148
+ id: sectionId(definition.type),
1149
+ type: definition.type,
1150
+ props: structuredClone(definition.defaults)
1151
+ };
1152
+ const variant = definition.options.find((option) => option.name === "variant");
1153
+ const tone = definition.options.find((option) => option.name === "tone");
1154
+ if (variant?.type === "enum") section.variant = variant.default;
1155
+ if (tone?.type === "enum") section.tone = tone.default;
1156
+ return {
1157
+ slug,
1158
+ title,
1159
+ seo,
1160
+ sections: [section]
1161
+ };
1162
+ }
1163
+ function draftPage(input, pages, registry) {
1164
+ const slug = readSlug(input.slug);
1165
+ if (slug === null) return { response: badSlug() };
1166
+ const seo = {
1167
+ title: input.title,
1168
+ description: "",
1169
+ noindex: false,
1170
+ nofollow: false
1171
+ };
1172
+ if (input.template === void 0) {
1173
+ const definition = registry.hero ?? Object.values(registry)[0];
1174
+ if (!definition) return { response: problem(400, "unknown_template", "No section types are registered.") };
1175
+ return { page: pageFromSection(slug, input.title, seo, definition) };
1176
+ }
1177
+ const definition = registry[input.template];
1178
+ if (definition) return { page: pageFromSection(slug, input.title, seo, definition) };
1179
+ const source = pages.find((entry) => entry.page.slug === input.template);
1180
+ if (!source) return { response: problem(400, "unknown_template", `Unknown template "${input.template}". Use a section type or an existing page slug.`) };
1181
+ return { page: {
1182
+ slug,
1183
+ title: input.title,
1184
+ seo,
1185
+ sections: structuredClone(source.page.sections)
1186
+ } };
1187
+ }
1188
+ function sectionId(type) {
1189
+ return type.replace(/[^A-Za-z0-9_-]+/g, "") || "section";
1190
+ }
1191
+ async function loadStoredPages(context, options = {}) {
1192
+ let listed;
1193
+ try {
1194
+ listed = await context.store.list(PAGES_DIR);
1195
+ } catch (error) {
1196
+ return { response: contentFailure(error) };
1197
+ }
1198
+ if (listed === void 0) {
1199
+ if (options.allowMissing) return { pages: [] };
1200
+ return { response: problem(404, "not_found", `Pages directory not found: ${PAGES_DIR}`) };
1201
+ }
1202
+ const names = listed.filter((name) => name.endsWith(".json") && !name.startsWith("."));
1203
+ const pages = [];
1204
+ const seen = /* @__PURE__ */ new Map();
1205
+ for (const name of names) {
1206
+ const key = `${PAGES_DIR}/${name}`;
1207
+ let raw;
1208
+ try {
1209
+ raw = JSON.parse(await context.store.read(key) ?? "");
1210
+ } catch (error) {
1211
+ if (error instanceof StoreError) throw error;
1212
+ if (error instanceof StoreKeyError) return { response: problem(400, "invalid_path", `Refusing to read ${name}.`) };
1213
+ return { response: problem(400, "invalid_json", `Invalid JSON in ${name}: ${error instanceof Error ? error.message : String(error)}`) };
1214
+ }
1215
+ const upgraded = context.migrator.upgrade(raw, "page");
1216
+ if (!upgraded.ok) return { response: json(422, {
1217
+ error: "validation",
1218
+ message: `Invalid content in ${name}.`,
1219
+ issues: [{
1220
+ path: SCHEMA_VERSION_KEY,
1221
+ message: upgraded.message
1222
+ }]
1223
+ }) };
1224
+ const parsed = validateEditorPage(upgraded.value, context.sections);
1225
+ if (!parsed.success) return { response: json(422, {
1226
+ error: "validation",
1227
+ message: `Invalid content in ${name}.`,
1228
+ issues: fieldIssues(parsed.error)
1229
+ }) };
1230
+ const page = parsed.data;
1231
+ const previous = seen.get(page.slug);
1232
+ if (previous !== void 0) return { response: problem(409, "conflict", `Duplicate slug "${page.slug}" in ${name} (also defined in ${previous}).`) };
1233
+ seen.set(page.slug, name);
1234
+ pages.push({
1235
+ key,
1236
+ fileName: name,
1237
+ page
1238
+ });
1239
+ }
1240
+ return { pages };
1241
+ }
1242
+ async function readSite(context) {
1243
+ const raw = await context.store.read(SITE_KEY);
1244
+ if (raw === void 0) throw new ContentReadError(SITE_KEY, `Content file not found: ${SITE_KEY}`);
1245
+ let parsed;
1246
+ try {
1247
+ parsed = JSON.parse(raw);
1248
+ } catch (error) {
1249
+ const message = error instanceof Error ? error.message : String(error);
1250
+ throw new ContentReadError(SITE_KEY, `Invalid JSON in ${SITE_KEY}: ${message}`);
1251
+ }
1252
+ const upgraded = context.migrator.upgrade(parsed, "site");
1253
+ if (!upgraded.ok) throw new ContentValidationError(SITE_KEY, [{
1254
+ path: [SCHEMA_VERSION_KEY],
1255
+ message: upgraded.message
1256
+ }]);
1257
+ const result = validateSite(upgraded.value, context.site);
1258
+ if (!result.success) {
1259
+ const issues = result.error.issues.map((issue) => ({
1260
+ path: [...issue.path],
1261
+ message: issue.message
1262
+ }));
1263
+ throw new ContentValidationError(SITE_KEY, issues);
1264
+ }
1265
+ return result.data;
1266
+ }
1267
+ async function readJsonBody(request) {
1268
+ const length = contentLength(request);
1269
+ if (length !== null && length > 1048576) return { response: problem(413, "too_large", "JSON body exceeds 1MB.") };
1270
+ if ((request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return { response: problem(415, "unsupported_media_type", "This route expects a JSON body.") };
1271
+ let text;
1272
+ try {
1273
+ text = await request.text();
1274
+ } catch {
1275
+ return { response: problem(400, "invalid_json", "The request body could not be read.") };
1276
+ }
1277
+ if (new TextEncoder().encode(text).byteLength > 1048576) return { response: problem(413, "too_large", "JSON body exceeds 1MB.") };
1278
+ try {
1279
+ return { value: JSON.parse(text) };
1280
+ } catch {
1281
+ return { response: problem(400, "invalid_json", "Request body is not valid JSON.") };
1282
+ }
1283
+ }
1284
+ function contentLength(request) {
1285
+ const header = request.headers.get("content-length");
1286
+ if (header === null || header === "") return null;
1287
+ const value = Number(header);
1288
+ if (!Number.isFinite(value) || value < 0) return null;
1289
+ return value;
1290
+ }
1291
+ function contentFailure(error) {
1292
+ if (error instanceof StoreError) throw error;
1293
+ if (error instanceof ContentValidationError) return json(422, {
1294
+ error: "validation",
1295
+ message: error.message,
1296
+ issues: error.issues.map((issue) => ({
1297
+ path: issue.path.length > 0 ? issue.path.map((part) => String(part)).join(".") : "(root)",
1298
+ message: issue.message
1299
+ }))
1300
+ });
1301
+ if (error instanceof ContentReadError) {
1302
+ const missing = /not found/i.test(error.message);
1303
+ return problem(missing ? 404 : 400, missing ? "not_found" : "invalid_json", error.message);
1304
+ }
1305
+ return problem(500, "write_failed", error instanceof Error ? error.message : "Unexpected error.");
1306
+ }
1307
+ /** Name the document an issue belongs to, for the save route that validates a page and the site together. */
1308
+ function tagIssues(issues, file) {
1309
+ return issues.map((issue) => ({
1310
+ ...issue,
1311
+ file
1312
+ }));
1313
+ }
1314
+ function validation(issues) {
1315
+ return json(400, {
1316
+ error: "validation",
1317
+ message: "The document failed schema validation.",
1318
+ issues
1319
+ });
1320
+ }
1321
+ function badSlug() {
1322
+ return problem(400, "invalid_slug", "Slug must be lowercase kebab-case and must not contain a path.");
1323
+ }
1324
+ function methodNotAllowed(allow) {
1325
+ return json(405, {
1326
+ error: "method_not_allowed",
1327
+ message: `Allowed: ${allow.join(", ")}.`
1328
+ }, { allow: allow.join(", ") });
1329
+ }
1330
+ function problem(status, error, message) {
1331
+ return json(status, {
1332
+ error,
1333
+ message
1334
+ });
1335
+ }
1336
+ function json(status, body, extra) {
1337
+ const headers = new Headers({
1338
+ "content-type": "application/json; charset=utf-8",
1339
+ "cache-control": "no-store",
1340
+ "x-content-type-options": "nosniff"
1341
+ });
1342
+ if (extra) for (const [key, value] of Object.entries(extra)) headers.set(key, value);
1343
+ return new Response(JSON.stringify(body), {
1344
+ status,
1345
+ headers
1346
+ });
1347
+ }
1348
+ function stripTrailingSlash(pathname) {
1349
+ if (pathname.length > 1 && pathname.endsWith("/")) return pathname.replace(/\/+$/, "");
1350
+ return pathname;
1351
+ }
1352
+ //#endregion
1353
+ //#region src/github-store.ts
1354
+ const API_VERSION = "2022-11-28";
1355
+ const RAW = "application/vnd.github.raw+json";
1356
+ const JSON_TYPE = "application/vnd.github+json";
1357
+ /** GitHub's messages for a push that a branch rule refuses. */
1358
+ const PROTECTED = /protected branch|must be made through a pull request|repository rule violation|required status check/i;
1359
+ function folder(value, name) {
1360
+ const parts = value.split("/").filter((part) => part !== "");
1361
+ if (parts.some((part) => part === "." || part === "..")) throw new Error(`githubStore(): ${name} must stay inside the repository, got "${value}".`);
1362
+ return parts.join("/");
1363
+ }
1364
+ const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
1365
+ function toBase64(bytes) {
1366
+ let binary = "";
1367
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
1368
+ return btoa(binary);
1369
+ }
1370
+ function messageOf(text) {
1371
+ try {
1372
+ const body = JSON.parse(text);
1373
+ return typeof body.message === "string" ? body.message : "";
1374
+ } catch {
1375
+ return "";
1376
+ }
1377
+ }
1378
+ function defaultMessage({ written, removed }) {
1379
+ if (written.length + removed.length === 1) return written.length === 1 ? `Update ${written[0]}` : `Remove ${removed[0]}`;
1380
+ return `Update ${written.length + removed.length} files`;
1381
+ }
1382
+ function branchStem(scope) {
1383
+ const part = scope.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
1384
+ return `bearminion/${part === "" ? "edit" : part}`;
1385
+ }
1386
+ const MAX_BRANCHES_PER_SCOPE = 20;
1387
+ function githubStore(options) {
1388
+ const match = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(options.repo);
1389
+ if (!match) throw new Error(`githubStore(): repo must be "owner/name", got "${options.repo}".`);
1390
+ 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.");
1391
+ const repo = `${match[1]}/${match[2]}`;
1392
+ const api = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
1393
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
1394
+ const rootDir = folder(options.rootDir ?? "", "rootDir");
1395
+ const contentDir = folder(options.contentDir ?? "content", "contentDir");
1396
+ const uploadsDir = folder(options.uploadsDir ?? "src/assets/uploads", "uploadsDir");
1397
+ const message = options.message ?? defaultMessage;
1398
+ const prMode = options.mode === "pr";
1399
+ 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)}".`);
1400
+ const inRepo = (...parts) => [rootDir, ...parts].filter((part) => part !== "").join("/");
1401
+ /** The repository path of a store key, checked the way the file store checks it. */
1402
+ function contentPath(key) {
1403
+ const parts = key.split("/");
1404
+ if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
1405
+ return inRepo(contentDir, key);
1406
+ }
1407
+ async function send(method, route, init = {}) {
1408
+ let response;
1409
+ try {
1410
+ response = await doFetch(`${api}${route}`, {
1411
+ method,
1412
+ headers: {
1413
+ accept: init.accept ?? JSON_TYPE,
1414
+ authorization: `Bearer ${options.token}`,
1415
+ "x-github-api-version": API_VERSION,
1416
+ "user-agent": "bearminion",
1417
+ ...init.body === void 0 ? {} : { "content-type": "application/json" },
1418
+ ...init.headers
1419
+ },
1420
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
1421
+ });
1422
+ } catch (error) {
1423
+ throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${error instanceof Error ? error.message : "the request failed"}.`);
1424
+ }
1425
+ return {
1426
+ status: response.status,
1427
+ headers: response.headers,
1428
+ text: await response.text()
1429
+ };
1430
+ }
1431
+ /** What went wrong, in words the person editing can act on. */
1432
+ function failure(reply, action) {
1433
+ const detail = messageOf(reply.text);
1434
+ if (reply.status === 401) return new StoreError(502, "github_auth", "GitHub refused the token. Check that it is valid and has not expired.");
1435
+ if (reply.status === 403 || reply.status === 429) {
1436
+ 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.");
1437
+ return new StoreError(502, "github_forbidden", `GitHub refused to ${action}. The token needs "Contents: Read and write" on ${repo}.`);
1438
+ }
1439
+ 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.`);
1440
+ return new StoreError(502, "github_error", `GitHub could not ${action}: ${detail || `HTTP ${reply.status}`}.`);
1441
+ }
1442
+ async function json(reply, action, ok = [200, 201]) {
1443
+ const settled = await reply;
1444
+ if (!ok.includes(settled.status)) throw failure(settled, action);
1445
+ return JSON.parse(settled.text);
1446
+ }
1447
+ let branchName;
1448
+ /** The branch edits are based on: the configured one, or the repository's default. */
1449
+ function baseBranch() {
1450
+ if (options.branch) return Promise.resolve(options.branch);
1451
+ branchName ??= json(send("GET", `/repos/${repo}`), "read the repository").then((info) => info.default_branch, (error) => {
1452
+ branchName = void 0;
1453
+ throw error;
1454
+ });
1455
+ return branchName;
1456
+ }
1457
+ /** GETs that GitHub can answer with 304 Not Modified, which costs no rate limit. */
1458
+ const cache = /* @__PURE__ */ new Map();
1459
+ async function cached(route, accept) {
1460
+ const key = `${accept} ${route}`;
1461
+ const known = cache.get(key);
1462
+ const reply = await send("GET", route, {
1463
+ accept,
1464
+ headers: known ? { "if-none-match": known.etag } : {}
1465
+ });
1466
+ if (reply.status === 304 && known) return {
1467
+ ...reply,
1468
+ status: 200,
1469
+ text: known.text
1470
+ };
1471
+ const etag = reply.headers.get("etag");
1472
+ if (reply.status === 200 && etag) cache.set(key, {
1473
+ etag,
1474
+ text: reply.text
1475
+ });
1476
+ return reply;
1477
+ }
1478
+ const contentsRoute = (path, ref) => `/repos/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`;
1479
+ async function readFileAt(path, ref) {
1480
+ const reply = await cached(contentsRoute(path, ref), RAW);
1481
+ if (reply.status === 404) return void 0;
1482
+ if (reply.status !== 200) throw failure(reply, `read ${path}`);
1483
+ return reply.text;
1484
+ }
1485
+ /** The names of the files directly inside `path`, or `undefined` when there is no such folder. */
1486
+ async function listFilesAt(path, ref) {
1487
+ const reply = await cached(contentsRoute(path, ref), JSON_TYPE);
1488
+ if (reply.status === 404) return void 0;
1489
+ if (reply.status !== 200) throw failure(reply, `list ${path}`);
1490
+ const entries = JSON.parse(reply.text);
1491
+ if (!Array.isArray(entries)) return void 0;
1492
+ 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));
1493
+ }
1494
+ async function branchHead(name) {
1495
+ const reply = await send("GET", `/repos/${repo}/git/ref/heads/${encodePath(name)}`);
1496
+ if (reply.status === 404) return void 0;
1497
+ if (reply.status !== 200) throw failure(reply, `read the branch "${name}"`);
1498
+ return JSON.parse(reply.text).object.sha;
1499
+ }
1500
+ /** The state of the pull requests whose head is `name`: any open one wins, then closed or merged ones. */
1501
+ async function pullState(name) {
1502
+ const head = encodeURIComponent(`${match?.[1] ?? ""}:${name}`);
1503
+ const pulls = await json(send("GET", `/repos/${repo}/pulls?head=${head}&state=all&per_page=100`), "look up pull requests");
1504
+ if (pulls.some((pull) => pull.state === "open")) return "open";
1505
+ return pulls.length > 0 ? "closed" : "none";
1506
+ }
1507
+ /** One commit on the target's branch holding all of `changes`. Goes through the Git Data API so the files land together. */
1508
+ function view(target) {
1509
+ async function readFile(path) {
1510
+ return readFileAt(path, await target.readRef());
1511
+ }
1512
+ async function listFile(path) {
1513
+ return listFilesAt(path, await target.readRef());
1514
+ }
1515
+ async function listAcross(path) {
1516
+ const names = /* @__PURE__ */ new Set();
1517
+ for (const ref of await target.refs()) for (const name of await listFilesAt(path, ref) ?? []) names.add(name);
1518
+ return [...names].sort((a, b) => a.localeCompare(b));
1519
+ }
1520
+ async function commit(changes, describe) {
1521
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1522
+ const name = await target.writeBranch();
1523
+ const headSha = await branchHead(name);
1524
+ if (headSha === void 0) throw failure({
1525
+ status: 404,
1526
+ headers: new Headers(),
1527
+ text: ""
1528
+ }, `read the branch "${name}"`);
1529
+ const parent = await json(send("GET", `/repos/${repo}/git/commits/${headSha}`), "read the latest commit");
1530
+ const entries = [];
1531
+ const applied = [];
1532
+ for (const change of changes) if ("remove" in change) {
1533
+ if (await readFileAt(change.path, headSha) === void 0) continue;
1534
+ entries.push({
1535
+ path: change.path,
1536
+ mode: "100644",
1537
+ type: "blob",
1538
+ sha: null
1539
+ });
1540
+ applied.push(change);
1541
+ } else if ("text" in change) {
1542
+ entries.push({
1543
+ path: change.path,
1544
+ mode: "100644",
1545
+ type: "blob",
1546
+ content: change.text
1547
+ });
1548
+ applied.push(change);
1549
+ } else {
1550
+ const blob = await json(send("POST", `/repos/${repo}/git/blobs`, { body: {
1551
+ content: toBase64(change.bytes),
1552
+ encoding: "base64"
1553
+ } }), `upload ${change.path}`);
1554
+ entries.push({
1555
+ path: change.path,
1556
+ mode: "100644",
1557
+ type: "blob",
1558
+ sha: blob.sha
1559
+ });
1560
+ applied.push(change);
1561
+ }
1562
+ if (entries.length === 0) return;
1563
+ const tree = await json(send("POST", `/repos/${repo}/git/trees`, { body: {
1564
+ base_tree: parent.tree.sha,
1565
+ tree: entries
1566
+ } }), "write the files");
1567
+ const created = await json(send("POST", `/repos/${repo}/git/commits`, { body: {
1568
+ message: describe(applied),
1569
+ tree: tree.sha,
1570
+ parents: [headSha]
1571
+ } }), "create the commit");
1572
+ const update = await send("PATCH", `/repos/${repo}/git/refs/heads/${encodePath(name)}`, { body: {
1573
+ sha: created.sha,
1574
+ force: false
1575
+ } });
1576
+ if (update.status === 200) {
1577
+ await target.committed?.(name, {
1578
+ written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
1579
+ removed: applied.filter((change) => "remove" in change).map((change) => change.path)
1580
+ });
1581
+ return;
1582
+ }
1583
+ 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'.`);
1584
+ if (update.status === 422 && attempt === 0) continue;
1585
+ if (update.status === 422) throw new StoreError(409, "branch_moved", "The branch changed while saving. Reload the editor and try again.");
1586
+ throw failure(update, `update the branch "${name}"`);
1587
+ }
1588
+ }
1589
+ return {
1590
+ async read(key) {
1591
+ return readFile(contentPath(key));
1592
+ },
1593
+ async exists(key) {
1594
+ return await readFile(contentPath(key)) !== void 0;
1595
+ },
1596
+ async list(dir) {
1597
+ return listFile(contentPath(dir));
1598
+ },
1599
+ async apply(operations) {
1600
+ const changes = operations.map((operation) => operation.type === "write" ? {
1601
+ path: contentPath(operation.key),
1602
+ text: operation.text
1603
+ } : {
1604
+ path: contentPath(operation.key),
1605
+ remove: true
1606
+ });
1607
+ if (changes.length === 0) return;
1608
+ await commit(changes, (applied) => message({
1609
+ written: applied.filter((change) => !("remove" in change)).map((change) => change.path),
1610
+ removed: applied.filter((change) => "remove" in change).map((change) => change.path)
1611
+ }));
1612
+ },
1613
+ uploads: {
1614
+ async list() {
1615
+ return (await listAcross(inRepo(uploadsDir))).filter((name) => !name.startsWith(".") && hasImageExtension(name)).map((filename) => ({
1616
+ filename,
1617
+ path: `${uploadsDir}/${filename}`
1618
+ }));
1619
+ },
1620
+ async save({ originalName, bytes, kind }) {
1621
+ const taken = new Set(await listAcross(inRepo(uploadsDir)));
1622
+ for (let attempt = 0; attempt < 8; attempt += 1) {
1623
+ const filename = uploadFilename(originalName, kind);
1624
+ if (taken.has(filename)) continue;
1625
+ await commit([{
1626
+ path: inRepo(uploadsDir, filename),
1627
+ bytes
1628
+ }], () => `Upload ${filename}`);
1629
+ return {
1630
+ filename,
1631
+ path: `${uploadsDir}/${filename}`,
1632
+ bytes: bytes.byteLength
1633
+ };
1634
+ }
1635
+ throw new Error("Unable to allocate a unique upload filename.");
1636
+ },
1637
+ async remove(filename) {
1638
+ if (!isUploadFilename(filename)) return false;
1639
+ if (!(await listAcross(inRepo(uploadsDir))).includes(filename)) return false;
1640
+ await commit([{
1641
+ path: inRepo(uploadsDir, filename),
1642
+ remove: true
1643
+ }], () => `Remove ${filename}`);
1644
+ return true;
1645
+ }
1646
+ },
1647
+ async assetExists(src) {
1648
+ if (!isAssetPath(src)) return false;
1649
+ const slash = src.lastIndexOf("/");
1650
+ const folder = inRepo(src.slice(0, slash));
1651
+ const name = src.slice(slash + 1);
1652
+ for (const ref of await target.refs()) if ((await listFilesAt(folder, ref))?.includes(name)) return true;
1653
+ return false;
1654
+ }
1655
+ };
1656
+ }
1657
+ const direct = {
1658
+ readRef: baseBranch,
1659
+ refs: async () => [await baseBranch()],
1660
+ writeBranch: baseBranch
1661
+ };
1662
+ if (!prMode) return view(direct);
1663
+ /** The branch of one entry's pull request: `bearminion/<scope>`, then `-2`, `-3` once earlier pull requests are closed. */
1664
+ async function activeBranch(scope) {
1665
+ const stem = branchStem(scope);
1666
+ for (let index = 1; index <= MAX_BRANCHES_PER_SCOPE; index += 1) {
1667
+ const name = index === 1 ? stem : `${stem}-${index}`;
1668
+ if (await branchHead(name) === void 0) return {
1669
+ name,
1670
+ exists: false
1671
+ };
1672
+ if (await pullState(name) !== "closed") return {
1673
+ name,
1674
+ exists: true
1675
+ };
1676
+ }
1677
+ throw new StoreError(409, "branch_exhausted", `There are already ${MAX_BRANCHES_PER_SCOPE} closed pull requests for "${scope}". Delete some of the bearminion/ branches.`);
1678
+ }
1679
+ const labelName = options.label === void 0 ? "bearminion" : options.label;
1680
+ async function openPullRequest(scope, name, change) {
1681
+ if (await pullState(name) === "open") return;
1682
+ const kind = scope.replace(":", ": ");
1683
+ const files = [...change.written.map((path) => `- ${path}`), ...change.removed.map((path) => `- ${path} (removed)`)].join("\n");
1684
+ const text = options.pullRequest?.({
1685
+ scope,
1686
+ ...change
1687
+ }) ?? {
1688
+ title: `Edit ${kind}`,
1689
+ 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.`
1690
+ };
1691
+ const reply = await send("POST", `/repos/${repo}/pulls`, { body: {
1692
+ title: text.title,
1693
+ head: name,
1694
+ base: await baseBranch(),
1695
+ body: text.body
1696
+ } });
1697
+ if (reply.status === 422 && /already exists/i.test(messageOf(reply.text))) return;
1698
+ if (reply.status !== 201) throw failure(reply, "open the pull request");
1699
+ if (labelName === false) return;
1700
+ const { number } = JSON.parse(reply.text);
1701
+ await send("POST", `/repos/${repo}/issues/${number}/labels`, { body: { labels: [labelName] } });
1702
+ }
1703
+ function scopeTarget(scope) {
1704
+ const readRef = async () => {
1705
+ const active = await activeBranch(scope);
1706
+ return active.exists ? active.name : baseBranch();
1707
+ };
1708
+ return {
1709
+ readRef,
1710
+ refs: async () => {
1711
+ const refs = [await readRef()];
1712
+ if (scope !== "uploads") {
1713
+ const uploads = await activeBranch("uploads");
1714
+ if (uploads.exists) refs.push(uploads.name);
1715
+ }
1716
+ const base = await baseBranch();
1717
+ if (!refs.includes(base)) refs.push(base);
1718
+ return refs;
1719
+ },
1720
+ async writeBranch() {
1721
+ const active = await activeBranch(scope);
1722
+ if (active.exists) return active.name;
1723
+ const base = await baseBranch();
1724
+ const sha = await branchHead(base);
1725
+ if (sha === void 0) throw failure({
1726
+ status: 404,
1727
+ headers: new Headers(),
1728
+ text: ""
1729
+ }, `read the branch "${base}"`);
1730
+ const created = await send("POST", `/repos/${repo}/git/refs`, { body: {
1731
+ ref: `refs/heads/${active.name}`,
1732
+ sha
1733
+ } });
1734
+ if (created.status !== 201 && created.status !== 422) throw failure(created, `create the branch "${active.name}"`);
1735
+ return active.name;
1736
+ },
1737
+ committed: (name, change) => openPullRequest(scope, name, change)
1738
+ };
1739
+ }
1740
+ const scoped = (scope) => view(scopeTarget(scope));
1741
+ const base = view(direct);
1742
+ const edits = scoped("edits");
1743
+ const uploadScope = scoped("uploads");
1744
+ return {
1745
+ read: base.read,
1746
+ exists: base.exists,
1747
+ list: base.list,
1748
+ apply: edits.apply,
1749
+ uploads: uploadScope.uploads,
1750
+ assetExists: base.assetExists,
1751
+ scoped
1752
+ };
1753
+ }
1754
+ //#endregion
1755
+ export { COMMIT_MESSAGE_LIMIT as a, StoreKeyError as c, uploadStem as d, stableStringify as f, isLocalRequest as g, JSON_BODY_LIMIT as h, isHistoryId as i, imageBodyLimit as l, videoBodyLimit as m, handleEditorRequest as n, GitError as o, DEFAULT_VIDEO_BYTE_LIMIT as p, historyId as r, StoreError as s, githubStore as t, IMAGE_EXTENSION as u };