bearminion 1.15.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/content.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as ContentModel, d as SectionOf, t as Page } from "./page-FipdIFb5.js";
1
+ import { d as SectionOf, g as ContentModel, t as Page } from "./page-D1pdneYm.js";
2
2
  import { z } from "zod";
3
3
  //#region src/content.d.ts
4
4
  export interface ContentCollectionsOptions {
@@ -1,38 +1,3 @@
1
- //#region src/upload-rules.ts
2
- /**
3
- * Image upload rules shared by the dev server and the editor in the browser. No Node imports: the browser bundle
4
- * uses it too.
5
- */
6
- /** The default largest image the editor accepts: 5 MB. */
7
- const DEFAULT_IMAGE_BYTE_LIMIT = 5242880;
8
- const DEFAULT_CONVERT_QUALITY = .82;
9
- const MAX_CONVERT_WIDTH = 16384;
10
- /** Check `imageConvert` and fill in its defaults. `false` and `undefined` mean no conversion. */
11
- function resolveConvert(input) {
12
- if (input === void 0 || input === false) return null;
13
- if (input.to !== "webp") throw new Error(`bearminion(): imageConvert.to must be "webp", got "${String(input.to)}".`);
14
- const { maxWidth, quality = DEFAULT_CONVERT_QUALITY } = input;
15
- if (maxWidth !== void 0 && (!Number.isInteger(maxWidth) || maxWidth < 16 || maxWidth > 16384)) throw new Error(`bearminion(): imageConvert.maxWidth must be a whole number from 16 to ${MAX_CONVERT_WIDTH}.`);
16
- if (!Number.isFinite(quality) || quality < .1 || quality > 1) throw new Error("bearminion(): imageConvert.quality must be a number from 0.1 to 1.");
17
- return {
18
- to: "webp",
19
- maxWidth: maxWidth ?? null,
20
- quality
21
- };
22
- }
23
- /** Check `maxImageBytes`. */
24
- function resolveMaxImageBytes(input) {
25
- if (input === void 0) return DEFAULT_IMAGE_BYTE_LIMIT;
26
- if (!Number.isInteger(input) || input < 1024) throw new Error("bearminion(): maxImageBytes must be a whole number of bytes, at least 1024.");
27
- return input;
28
- }
29
- /** "4.2 MB", "310 KB", "512 B". */
30
- function formatBytes(bytes) {
31
- if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1).replace(/\.0$/, "")} MB`;
32
- if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
33
- return `${bytes} B`;
34
- }
35
- //#endregion
36
1
  //#region src/asset-paths.ts
37
2
  /** A project-relative image path that content may point at, such as `src/assets/uploads/hero-a1b2c3d4.png`. */
38
3
  function isAssetPath(src) {
@@ -277,4 +242,4 @@ function reloadDecision(input) {
277
242
  return "reload";
278
243
  }
279
244
  //#endregion
280
- export { missingAssetIssues as C, resolveMaxImageBytes as D, resolveConvert as E, isAssetPath as S, formatBytes as T, writeSaveNotice as _, localDraftStorage as a, describeSiteRef as b, projectId as c, removeDraft as d, savedNoticeFor as f, writeDraftRecord as g, sweepExpiredDrafts as h, isForeignSave as i, readDraftRecord as l, siteSavedKey as m, draftBannerText as n, pageDraftKey as o, siteDraftKey as p, hashText as r, pageSavedKey as s, assessStoredDraft as t, reloadDecision as u, assetRefs as v, DEFAULT_IMAGE_BYTE_LIMIT as w, draftImageUsages as x, describePageRef as y };
245
+ export { missingAssetIssues as C, isAssetPath as S, writeSaveNotice as _, localDraftStorage as a, describeSiteRef as b, projectId as c, removeDraft as d, savedNoticeFor as f, writeDraftRecord as g, sweepExpiredDrafts as h, isForeignSave as i, readDraftRecord as l, siteSavedKey as m, draftBannerText as n, pageDraftKey as o, siteDraftKey as p, hashText as r, pageSavedKey as s, assessStoredDraft as t, reloadDecision as u, assetRefs as v, draftImageUsages as x, describePageRef as y };
@@ -1,4 +1,5 @@
1
- import { N as ThemeDefinition, Y as SiteDefinition, j as SectionRegistry, n as PageRules, wt as ContentMigrator } from "./page-FipdIFb5.js";
1
+ import { _ as SectionRegistry, ht as SiteDefinition, n as PageRules, w as ContentMigrator, y as ThemeDefinition } from "./page-D1pdneYm.js";
2
+ import { ZodType, z } from "zod";
2
3
  //#region src/upload-names.d.ts
3
4
  type ImageKind = 'png' | 'jpeg' | 'webp' | 'gif' | 'avif';
4
5
  //#endregion
@@ -33,7 +34,9 @@ type ListedVideo = Omit<SavedVideo, 'bytes'> & {
33
34
  * place the files live is a choice: {@link createFileStore} uses the local project, and another
34
35
  * implementation (a Git host's API, say) can stand in without touching the API handlers.
35
36
  *
36
- * Keys are `/`-separated paths relative to the content directory: `site.json`, `pages/about.json`.
37
+ * Keys are `/`-separated paths relative to the content directory: `site.json`, `pages/about.json`. A key with a
38
+ * leading slash is relative to the project root instead (`/src/content/blog/en/post.md`), for files that live outside
39
+ * the content directory, such as Markdown collections. See {@link repoKey}.
37
40
  * Values are text. Parsing, validation and the JSON layout belong to the caller.
38
41
  *
39
42
  * Not part of the store: undo history (local editor state in `.editor/`), `Commit changes`
@@ -96,6 +99,39 @@ interface VideoStore {
96
99
  remove(filename: string): Promise<boolean>;
97
100
  }
98
101
  //#endregion
102
+ //#region src/collections.d.ts
103
+ /** What a collection's `schema` may be: a Zod schema, or Astro's factory form `({ image }) => schema`. */
104
+ type CollectionSchema = ZodType | ((helpers: {
105
+ image: () => ZodType;
106
+ }) => ZodType);
107
+ interface CollectionOptions {
108
+ /**
109
+ * The same schema the site's `content.config.ts` uses, imported from a plain module (no `astro:content`). A site that
110
+ * uses Astro's `image()` writes the factory form `({ image }) => z.object({ cover: image().optional() })`.
111
+ */
112
+ schema: CollectionSchema;
113
+ /** Where the files are, from the project root, with `{slug}` as the file name: `src/content/blog/en/{slug}.md`. */
114
+ path: string;
115
+ /** Shown in the editor. Default: the collection's id. */
116
+ label?: string;
117
+ /** Allow changing an entry's slug, which changes its address. Default false. */
118
+ rename?: boolean;
119
+ /** Allow deleting entries. Default false. */
120
+ delete?: boolean;
121
+ }
122
+ interface Collection {
123
+ id: string;
124
+ label: string;
125
+ /** The folder of the files, from the project root, without a trailing slash. */
126
+ dir: string;
127
+ ext: '.md' | '.mdx';
128
+ schema: ZodType;
129
+ rename: boolean;
130
+ delete: boolean;
131
+ }
132
+ /** Declares a collection. Checks the options now, so a typo fails when the config loads, not on the first save. */
133
+ declare function collection(options: CollectionOptions): CollectionOptions;
134
+ //#endregion
99
135
  //#region src/git-types.d.ts
100
136
  type ChangeStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked';
101
137
  interface ChangedFile {
@@ -256,6 +292,8 @@ interface EditorContext {
256
292
  migrator: ContentMigrator;
257
293
  /** Commit changes is enabled. */
258
294
  git: boolean;
295
+ /** Markdown collections the editor can edit, by id. Absent when the site has none. */
296
+ collections?: Record<string, Collection>;
259
297
  /** The folder with the site's form handlers, or `null` when the `forms` option turns them off. */
260
298
  formsDir?: string | null;
261
299
  /**
@@ -269,4 +307,4 @@ interface EditorContext {
269
307
  formFile?: (name: string) => string | null;
270
308
  }
271
309
  //#endregion
272
- export { ContentStore as _, CommitRequest as a, HistoryEntry as c, SaveResponse as d, SitePreview as f, GitInfo as g, ChangedFile as h, ApiProblem as i, PageListItem as l, UploadedVideo as m, ImageConvertOptions as n, CommitResult as o, UploadedImage as p, ApiIssue as r, CreatePageRequest as s, EditorContext as t, SaveRequest as u, StoreOperation as v, UploadStore as y };
310
+ export { CollectionOptions as _, CommitRequest as a, StoreOperation as b, HistoryEntry as c, SaveResponse as d, SitePreview as f, GitInfo as g, ChangedFile as h, ApiProblem as i, PageListItem as l, UploadedVideo as m, ImageConvertOptions as n, CommitResult as o, UploadedImage as p, ApiIssue as r, CreatePageRequest as s, EditorContext as t, SaveRequest as u, collection as v, UploadStore as x, ContentStore as y };
@@ -1,6 +1,6 @@
1
- import { _ as ContentStore } from "./editor-context-CTfxXtny.js";
1
+ import { y as ContentStore } from "./editor-context-BBsL5NFx.js";
2
2
  //#region src/store-error.d.ts
3
- /** A key that is empty, absolute or leaves the content directory. */
3
+ /** A key that is empty, has an empty or dot segment, or leaves its base directory. */
4
4
  declare class StoreKeyError extends Error {
5
5
  constructor(key: string);
6
6
  }
@@ -1,95 +1,10 @@
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";
1
+ import { D as ContentReadError, O as ContentValidationError, _ as parseKey, a as listEntries, b as PreviewUnavailableError, d as validateEditorPage, f as validatePage, g as pageKey, h as SITE_KEY, i as fieldDefinitions, l as updateEntry, m as PAGES_DIR, n as createEntry, o as readEntry, p as validateSite, r as deleteEntry, s as renameEntry, u as fieldIssues, v as StoreError, w as imageFields, y as StoreKeyError } from "./collections-BbL4_4jt.js";
2
+ import { c as withoutOrphanSections, d as isOrphanSection, i as isSystemPage } from "./page-wlcQJAA-.js";
3
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";
4
+ import { n as formatBytes, t as DEFAULT_IMAGE_BYTE_LIMIT } from "./upload-rules-Cao9uY5K.js";
5
+ import { i as readSlug, n as isLocalRequest, r as isSameOriginRequest } from "./request-guards-BcSUj8Gc.js";
6
+ import { C as missingAssetIssues, S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-DBEfw_Gq.js";
5
7
  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
8
  //#region src/video-sniff.ts
94
9
  const MIME_TO_KIND$1 = {
95
10
  "video/mp4": "mp4",
@@ -235,38 +150,6 @@ function ascii(bytes) {
235
150
  return text;
236
151
  }
237
152
  //#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
153
  //#region src/git-types.ts
271
154
  /** Longest commit message the editor sends. */
272
155
  const COMMIT_MESSAGE_LIMIT = 1e3;
@@ -312,28 +195,6 @@ const NO_HISTORY = {
312
195
  async ensureBaseline() {}
313
196
  };
314
197
  //#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
198
  //#region src/api.ts
338
199
  /**
339
200
  * Dev-server API. Returns null when the URL is not under {@link API_PREFIX}
@@ -373,6 +234,7 @@ async function route(request, context, meta) {
373
234
  if (method === "POST") return createPage(request, context);
374
235
  return methodNotAllowed(["GET", "POST"]);
375
236
  }
237
+ if (parts[0] === "collections") return collectionRoute(request, context, parts.slice(1), method);
376
238
  if (parts.length === 1 && parts[0] === "forms") {
377
239
  if (method === "GET") return getForms(context);
378
240
  return methodNotAllowed(["GET"]);
@@ -447,6 +309,91 @@ async function route(request, context, meta) {
447
309
  }
448
310
  return problem(404, "not_found", "Unknown editor API route.");
449
311
  }
312
+ function findCollection(context, id) {
313
+ const all = context.collections;
314
+ return all !== void 0 && Object.hasOwn(all, id) ? all[id] ?? null : null;
315
+ }
316
+ const entryPatchSchema = z.object({
317
+ set: z.record(z.string(), z.unknown()).optional(),
318
+ unset: z.array(z.string()).optional(),
319
+ blocks: z.array(z.object({
320
+ id: z.string().optional(),
321
+ markdown: z.string().optional()
322
+ }).strict().refine((block) => block.id !== void 0 || block.markdown !== void 0, "A block needs an id or markdown.")).optional()
323
+ }).strict();
324
+ const newEntrySchema = z.object({
325
+ slug: z.string(),
326
+ fields: z.record(z.string(), z.unknown()).optional(),
327
+ body: z.string().optional()
328
+ }).strict();
329
+ const renameEntrySchema = z.object({ slug: z.string() }).strict();
330
+ function outcomeResponse(result, status = 200) {
331
+ if (result.ok) return json(status, result.value);
332
+ if (result.issues) return validation(result.issues);
333
+ return problem(result.status, result.code, result.message);
334
+ }
335
+ /** `/collections`, `/collections/<id>/entries`, `/collections/<id>/entries/<slug>` and `.../rename`. */
336
+ async function collectionRoute(request, context, parts, method) {
337
+ if (parts.length === 0) {
338
+ if (method !== "GET") return methodNotAllowed(["GET"]);
339
+ return json(200, { collections: Object.values(context.collections ?? {}).map((item) => ({
340
+ id: item.id,
341
+ label: item.label,
342
+ path: `${item.dir}/{slug}${item.ext}`,
343
+ rename: item.rename,
344
+ delete: item.delete,
345
+ fields: fieldDefinitions(item.schema)
346
+ })) });
347
+ }
348
+ const found = findCollection(context, decodeSegment(parts[0] ?? ""));
349
+ if (found === null || parts[1] !== "entries") return problem(404, "not_found", "Unknown collection or route.");
350
+ if (parts.length === 2) {
351
+ if (method === "GET") {
352
+ const listed = await listEntries(context.store, found);
353
+ return json(200, {
354
+ entries: listed.slugs.map((slug) => ({ slug })),
355
+ skipped: listed.skipped
356
+ });
357
+ }
358
+ if (method === "POST") {
359
+ const body = await readJsonBody(request);
360
+ if (body.response) return body.response;
361
+ const parsed = newEntrySchema.safeParse(body.value);
362
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
363
+ const entry = scoped(context, `collection:${found.id}:${parsed.data.slug}`);
364
+ return outcomeResponse(await createEntry(entry.store, found, parsed.data), 201);
365
+ }
366
+ return methodNotAllowed(["GET", "POST"]);
367
+ }
368
+ const slug = readSlug(parts[2] ?? "");
369
+ if (slug === null) return badSlug();
370
+ const entry = scoped(context, `collection:${found.id}:${slug}`);
371
+ if (parts.length === 3) {
372
+ if (method === "GET") return outcomeResponse(await readEntry(entry.store, found, slug));
373
+ if (method === "PUT") {
374
+ const body = await readJsonBody(request);
375
+ if (body.response) return body.response;
376
+ const parsed = entryPatchSchema.safeParse(body.value);
377
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
378
+ return outcomeResponse(await updateEntry(entry.store, found, slug, parsed.data));
379
+ }
380
+ if (method === "DELETE") return outcomeResponse(await deleteEntry(entry.store, found, slug));
381
+ return methodNotAllowed([
382
+ "GET",
383
+ "PUT",
384
+ "DELETE"
385
+ ]);
386
+ }
387
+ if (parts.length === 4 && parts[3] === "rename") {
388
+ if (method !== "POST") return methodNotAllowed(["POST"]);
389
+ const body = await readJsonBody(request);
390
+ if (body.response) return body.response;
391
+ const parsed = renameEntrySchema.safeParse(body.value);
392
+ if (!parsed.success) return validation(fieldIssues(parsed.error));
393
+ return outcomeResponse(await renameEntry(entry.store, found, slug, parsed.data.slug));
394
+ }
395
+ return problem(404, "not_found", "Unknown editor API route.");
396
+ }
450
397
  /**
451
398
  * Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
452
399
  * created while `astro dev` runs shows up at once.
@@ -888,10 +835,11 @@ async function renamePage(request, context, slug) {
888
835
  if (loaded.pages.some((entry) => entry.page.slug === nextSlug)) return problem(409, "conflict", `A page with slug "${nextSlug}" already exists.`);
889
836
  const nextKey = pageKey(nextSlug);
890
837
  if (await context.store.exists(nextKey)) return problem(409, "conflict", `A file named ${nextSlug}.json already exists.`);
891
- const validated = validateEditorPage({
838
+ const renamed = {
892
839
  ...found.page,
893
840
  slug: nextSlug
894
- }, context.sections);
841
+ };
842
+ const validated = validateEditorPage(renamed, context.sections);
895
843
  if (!validated.success) return validation(fieldIssues(validated.error));
896
844
  await writeDocuments(context, [[nextKey, validated.data]], [found.key]);
897
845
  return json(200, validated.data);
@@ -1380,6 +1328,7 @@ function defaultMessage({ written, removed }) {
1380
1328
  return `Update ${written.length + removed.length} files`;
1381
1329
  }
1382
1330
  function branchStem(scope) {
1331
+ if (scope.startsWith("collection:")) return `bearminion/${scope.split(":").map((piece) => piece.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40)).filter((piece) => piece !== "").join("/")}`;
1383
1332
  const part = scope.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
1384
1333
  return `bearminion/${part === "" ? "edit" : part}`;
1385
1334
  }
@@ -1400,9 +1349,8 @@ function githubStore(options) {
1400
1349
  const inRepo = (...parts) => [rootDir, ...parts].filter((part) => part !== "").join("/");
1401
1350
  /** The repository path of a store key, checked the way the file store checks it. */
1402
1351
  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);
1352
+ const { base, parts } = parseKey(key);
1353
+ return base === "root" ? inRepo(...parts) : inRepo(contentDir, ...parts);
1406
1354
  }
1407
1355
  async function send(method, route, init = {}) {
1408
1356
  let response;
@@ -1420,7 +1368,8 @@ function githubStore(options) {
1420
1368
  body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
1421
1369
  });
1422
1370
  } catch (error) {
1423
- throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${error instanceof Error ? error.message : "the request failed"}.`);
1371
+ const reason = error instanceof Error ? error.message : "the request failed";
1372
+ throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${reason}.`);
1424
1373
  }
1425
1374
  return {
1426
1375
  status: response.status,
@@ -1679,7 +1628,8 @@ function githubStore(options) {
1679
1628
  const labelName = options.label === void 0 ? "bearminion" : options.label;
1680
1629
  async function openPullRequest(scope, name, change) {
1681
1630
  if (await pullState(name) === "open") return;
1682
- const kind = scope.replace(":", ": ");
1631
+ const [head, collectionId, entrySlug] = scope.split(":");
1632
+ const kind = head === "collection" && collectionId && entrySlug ? `${collectionId}: ${entrySlug}` : scope.replace(":", ": ");
1683
1633
  const files = [...change.written.map((path) => `- ${path}`), ...change.removed.map((path) => `- ${path} (removed)`)].join("\n");
1684
1634
  const text = options.pullRequest?.({
1685
1635
  scope,
@@ -1752,4 +1702,4 @@ function githubStore(options) {
1752
1702
  };
1753
1703
  }
1754
1704
  //#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 };
1705
+ export { COMMIT_MESSAGE_LIMIT as a, IMAGE_EXTENSION as c, DEFAULT_VIDEO_BYTE_LIMIT as d, videoBodyLimit as f, isHistoryId as i, uploadStem as l, handleEditorRequest as n, GitError as o, historyId as r, imageBodyLimit as s, githubStore as t, stableStringify as u };
@@ -0,0 +1,6 @@
1
+ //#region src/hosted-astro.d.ts
2
+ export declare const onRequest: (context: {
3
+ request: Request;
4
+ locals: object;
5
+ }, next: () => Promise<Response>) => Promise<Response>;
6
+ //#endregion
@@ -0,0 +1,15 @@
1
+ import { t as createHostedMiddleware } from "./hosted-middleware-DTnZoRsK.js";
2
+ import { editor, signIn } from "virtual:bearminion/editor";
3
+ //#region src/hosted-astro.ts
4
+ let ready;
5
+ const onRequest = async (context, next) => {
6
+ ready ??= Promise.resolve(typeof editor === "function" ? editor(context) : editor).then((built) => createHostedMiddleware(built, { signIn }));
7
+ try {
8
+ return await (await ready)(context, next);
9
+ } catch (error) {
10
+ ready = void 0;
11
+ throw error;
12
+ }
13
+ };
14
+ //#endregion
15
+ export { onRequest };