bearminion 1.16.0 → 1.16.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.16.2
4
+
5
+ ### Patch Changes
6
+
7
+ - a851229: Hosted editor: a page that uses an image uploaded after the last build no longer answers 500. The template's `Seo` (share image) and `LogoStrip` components threw for a file the build does not hold; on the hosted editor they now draw it from the editor's image route or leave it out. A page that cannot be drawn shows the signed-in person the reason, with the editor script on it, instead of a blank 500.
8
+
9
+ ## 1.16.1
10
+
11
+ ### Patch Changes
12
+
13
+ - fd6947c: Hosted editor: images no longer wait for a build. `/__bearminion/assets` serves an image from the repository to signed-in people, so previews in the editor and pages that use a file uploaded after the last build draw it at once instead of showing alt text or failing. The default template's components show the editor's empty-slot hints on the hosted editor deployment too (`src/lib/editing.ts`). Requests that arrive together when the GitHub token is about to expire now share one renewal, and one that loses the race keeps the old token while it works, so a page load no longer signs the person out.
14
+
3
15
  ## 1.16.0
4
16
 
5
17
  ### Minor Changes
package/dist/astro.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as CollectionOptions, b as StoreOperation, n as ImageConvertOptions, t as EditorContext, x as UploadStore, y as ContentStore } from "./editor-context-BBsL5NFx.js";
2
- import { i as StoreKeyError, n as githubStore, r as StoreError, t as GithubStoreOptions } from "./github-store-DLQazToO.js";
1
+ import { _ as CollectionOptions, b as StoreOperation, n as ImageConvertOptions, t as EditorContext, x as UploadStore, y as ContentStore } from "./editor-context-ESJwMFpS.js";
2
+ import { i as StoreKeyError, n as githubStore, r as StoreError, t as GithubStoreOptions } from "./github-store-CDQNvoKQ.js";
3
3
  import { _ as SectionRegistry, d as SectionOf, g as ContentModel, gt as SiteOf, ht as SiteDefinition, n as PageRules, t as Page, w as ContentMigrator } from "./page-D1pdneYm.js";
4
4
  import { AstroIntegration } from "astro";
5
5
  //#region src/store.d.ts
package/dist/astro.js CHANGED
@@ -6,7 +6,7 @@ import { i as resolveMaxImageBytes, n as formatBytes, r as resolveConvert } from
6
6
  import { n as isLocalRequest, t as JSON_BODY_LIMIT } from "./request-guards-BcSUj8Gc.js";
7
7
  import { i as resolveInside, n as isInside, r as resolveDir, t as asDirectory } from "./security-CBiOYdVE.js";
8
8
  import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CzUHR7oS.js";
9
- import { a as COMMIT_MESSAGE_LIMIT, c as IMAGE_EXTENSION, f as videoBodyLimit, i as isHistoryId, l as uploadStem, n as handleEditorRequest, o as GitError, r as historyId, s as imageBodyLimit, t as githubStore, u as stableStringify } from "./github-store-DUf07ODw.js";
9
+ import { a as isHistoryId, c as imageBodyLimit, d as stableStringify, i as historyId, l as IMAGE_EXTENSION, n as missingImageSvg, o as COMMIT_MESSAGE_LIMIT, p as videoBodyLimit, r as handleEditorRequest, s as GitError, t as githubStore, u as uploadStem } from "./github-store-D3LEUhcM.js";
10
10
  import { S as isAssetPath } from "./draft-store-DBEfw_Gq.js";
11
11
  import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-BzVw721A.js";
12
12
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
@@ -739,20 +739,6 @@ function serveAsset(req, res, context, rawUrl) {
739
739
  }
740
740
  fs.createReadStream(absolute).pipe(res);
741
741
  }
742
- function escapeXml(text) {
743
- return text.replace(/[<>&"']/g, (char) => `&#${char.charCodeAt(0)};`);
744
- }
745
- /** Striped frame with "Missing image" and the file name. Scales to any box. */
746
- function missingImageSvg(src) {
747
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 300" preserveAspectRatio="xMidYMid slice">
748
- <defs><pattern id="s" width="12" height="12" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="12" height="12" fill="#f4f1ec"/><rect width="5" height="12" fill="#ebe5dc"/></pattern></defs>
749
- <rect width="480" height="300" fill="url(#s)"/>
750
- <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" text-anchor="middle">
751
- <text x="240" y="146" font-size="18" font-weight="600" fill="#b42318">Missing image</text>
752
- <text x="240" y="172" font-size="13" fill="#6b6459">${escapeXml(path.basename(src))}</text>
753
- </g>
754
- </svg>`;
755
- }
756
742
  function stripTrailingSlash(pathname) {
757
743
  if (pathname.length > 1 && pathname.endsWith("/")) return pathname.replace(/\/+$/, "");
758
744
  return pathname;
@@ -979,6 +965,7 @@ function bearminionHostedEditor(options) {
979
965
  ...config.output === "static" ? { output: "server" } : {},
980
966
  vite: {
981
967
  ssr: { noExternal: ["bearminion", config.adapter.name] },
968
+ define: { "import.meta.env.BEARMINION_HOSTED": "true" },
982
969
  plugins: [{
983
970
  name: "bearminion:hosted-editor-module",
984
971
  resolveId: (id) => id === VIRTUAL_ID ? RESOLVED_ID : null,
@@ -63,6 +63,15 @@ interface ContentStore {
63
63
  * fail validation. A store without it skips that check.
64
64
  */
65
65
  assetExists?(src: string): Promise<boolean>;
66
+ /**
67
+ * The bytes of an image that content points at (`src/assets/...`), for the hosted editor to show it before the site
68
+ * has been built again. `undefined` when there is no such file. With `ifNoneMatch` (a validator from an earlier answer)
69
+ * a store that can tell answers `{ notModified: true }` without the bytes. A store that only serves files from a
70
+ * folder the site is built from (the local file store) leaves it out.
71
+ */
72
+ readAsset?(src: string, options?: {
73
+ ifNoneMatch?: string;
74
+ }): Promise<StoredAsset | undefined>;
66
75
  /**
67
76
  * A view of the store for editing one entry (`page:about`, `site`), for stores that keep each entry's pending edits
68
77
  * apart, such as `githubStore` in `pr` mode, where every scope is a branch and a pull request. Reads see the entry's
@@ -70,6 +79,13 @@ interface ContentStore {
70
79
  */
71
80
  scoped?(scope: string): ContentStore;
72
81
  }
82
+ type StoredAsset = {
83
+ notModified: true;
84
+ etag: string;
85
+ } | {
86
+ bytes: Uint8Array;
87
+ etag?: string;
88
+ };
73
89
  type StoreOperation = {
74
90
  type: 'write';
75
91
  key: string;
@@ -1,4 +1,4 @@
1
- import { y as ContentStore } from "./editor-context-BBsL5NFx.js";
1
+ import { y as ContentStore } from "./editor-context-ESJwMFpS.js";
2
2
  //#region src/store-error.d.ts
3
3
  /** A key that is empty, has an empty or dot segment, or leaves its base directory. */
4
4
  declare class StoreKeyError extends Error {
@@ -1298,6 +1298,22 @@ function stripTrailingSlash(pathname) {
1298
1298
  return pathname;
1299
1299
  }
1300
1300
  //#endregion
1301
+ //#region src/missing-image.ts
1302
+ function escapeXml(text) {
1303
+ return text.replace(/[<>&"']/g, (char) => `&#${char.charCodeAt(0)};`);
1304
+ }
1305
+ /** Striped frame with "Missing image" and the file name. Scales to any box. */
1306
+ function missingImageSvg(src) {
1307
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 300" preserveAspectRatio="xMidYMid slice">
1308
+ <defs><pattern id="s" width="12" height="12" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="12" height="12" fill="#f4f1ec"/><rect width="5" height="12" fill="#ebe5dc"/></pattern></defs>
1309
+ <rect width="480" height="300" fill="url(#s)"/>
1310
+ <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" text-anchor="middle">
1311
+ <text x="240" y="146" font-size="18" font-weight="600" fill="#b42318">Missing image</text>
1312
+ <text x="240" y="172" font-size="13" fill="#6b6459">${escapeXml(src.split("/").pop() ?? src)}</text>
1313
+ </g>
1314
+ </svg>`;
1315
+ }
1316
+ //#endregion
1301
1317
  //#region src/github-store.ts
1302
1318
  const API_VERSION = "2022-11-28";
1303
1319
  const RAW = "application/vnd.github.raw+json";
@@ -1377,6 +1393,33 @@ function githubStore(options) {
1377
1393
  text: await response.text()
1378
1394
  };
1379
1395
  }
1396
+ /** A GET whose answer is bytes (an image), which `send` would turn into text. 304 is passed on, as are 404 and other answers. */
1397
+ async function fetchBytes(route, ifNoneMatch) {
1398
+ let response;
1399
+ try {
1400
+ response = await doFetch(`${api}${route}`, {
1401
+ method: "GET",
1402
+ headers: {
1403
+ accept: RAW,
1404
+ authorization: `Bearer ${options.token}`,
1405
+ "x-github-api-version": API_VERSION,
1406
+ "user-agent": "bearminion",
1407
+ ...ifNoneMatch ? { "if-none-match": ifNoneMatch } : {}
1408
+ }
1409
+ });
1410
+ } catch (error) {
1411
+ const reason = error instanceof Error ? error.message : "the request failed";
1412
+ throw new StoreError(502, "github_unreachable", `Could not reach GitHub: ${reason}.`);
1413
+ }
1414
+ const bytes = new Uint8Array(await response.arrayBuffer());
1415
+ const ok = response.status === 200;
1416
+ return {
1417
+ status: response.status,
1418
+ etag: response.headers.get("etag"),
1419
+ bytes,
1420
+ text: ok ? "" : new TextDecoder().decode(bytes)
1421
+ };
1422
+ }
1380
1423
  /** What went wrong, in words the person editing can act on. */
1381
1424
  function failure(reply, action) {
1382
1425
  const detail = messageOf(reply.text);
@@ -1593,6 +1636,28 @@ function githubStore(options) {
1593
1636
  return true;
1594
1637
  }
1595
1638
  },
1639
+ async readAsset(src, readOptions = {}) {
1640
+ if (!isAssetPath(src)) return void 0;
1641
+ const path = inRepo(src);
1642
+ const refs = await target.refs();
1643
+ for (const ref of refs) {
1644
+ const reply = await fetchBytes(contentsRoute(path, ref), refs.length === 1 ? readOptions.ifNoneMatch : void 0);
1645
+ if (reply.status === 404) continue;
1646
+ if (reply.status === 304 && readOptions.ifNoneMatch) return {
1647
+ notModified: true,
1648
+ etag: readOptions.ifNoneMatch
1649
+ };
1650
+ if (reply.status !== 200) throw failure({
1651
+ status: reply.status,
1652
+ headers: new Headers(),
1653
+ text: reply.text
1654
+ }, `read ${path}`);
1655
+ return {
1656
+ bytes: reply.bytes,
1657
+ ...reply.etag ? { etag: reply.etag } : {}
1658
+ };
1659
+ }
1660
+ },
1596
1661
  async assetExists(src) {
1597
1662
  if (!isAssetPath(src)) return false;
1598
1663
  const slash = src.lastIndexOf("/");
@@ -1698,8 +1763,9 @@ function githubStore(options) {
1698
1763
  apply: edits.apply,
1699
1764
  uploads: uploadScope.uploads,
1700
1765
  assetExists: base.assetExists,
1766
+ readAsset: uploadScope.readAsset,
1701
1767
  scoped
1702
1768
  };
1703
1769
  }
1704
1770
  //#endregion
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 };
1771
+ export { isHistoryId as a, imageBodyLimit as c, stableStringify as d, DEFAULT_VIDEO_BYTE_LIMIT as f, historyId as i, IMAGE_EXTENSION as l, missingImageSvg as n, COMMIT_MESSAGE_LIMIT as o, videoBodyLimit as p, handleEditorRequest as r, GitError as s, githubStore as t, uploadStem as u };
@@ -1,4 +1,4 @@
1
- import { t as createHostedMiddleware } from "./hosted-middleware-DTnZoRsK.js";
1
+ import { t as createHostedMiddleware } from "./hosted-middleware-BQPW2YiB.js";
2
2
  import { editor, signIn } from "virtual:bearminion/editor";
3
3
  //#region src/hosted-astro.ts
4
4
  let ready;
@@ -60,7 +60,7 @@ function readCookies(header) {
60
60
  }
61
61
  return cookies;
62
62
  }
63
- function escapeHtml(text) {
63
+ function escapeHtml$1(text) {
64
64
  return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
65
65
  }
66
66
  /** Only a path on this site: no other origin, no protocol-relative `//host`, no backslash tricks. */
@@ -69,7 +69,7 @@ function safeReturnTo(value) {
69
69
  return value;
70
70
  }
71
71
  function page(status, title, message, extra) {
72
- const body = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title><body style="font:16px system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1 style="font-size:1.25rem">${escapeHtml(title)}</h1><p>${escapeHtml(message)}</p>`;
72
+ const body = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml$1(title)}</title><body style="font:16px system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1 style="font-size:1.25rem">${escapeHtml$1(title)}</h1><p>${escapeHtml$1(message)}</p>`;
73
73
  return new Response(body, {
74
74
  status,
75
75
  headers: {
@@ -168,24 +168,39 @@ function createHostedAuth(options) {
168
168
  const maxAge = Math.max(1, Math.floor((session.issuedAt + sessionMs - now()) / 1e3));
169
169
  return cookie(request, names(request).session, await seal(await keyPromise, "session", session), maxAge);
170
170
  }
171
- async function authenticate(request) {
172
- const stored = await open(await keyPromise, "session", readCookies(request.headers.get("cookie")).get(names(request).session));
173
- if (!stored || typeof stored.token !== "string" || typeof stored.login !== "string") return null;
174
- const at = now();
175
- if (at >= stored.issuedAt + sessionMs) return null;
176
- if (at < stored.expiresAt - REFRESH_MARGIN_MS) return { session: stored };
177
- if (!stored.refreshToken || !stored.refreshExpiresAt || at >= stored.refreshExpiresAt) return null;
171
+ const renewing = /* @__PURE__ */ new Map();
172
+ async function renew(request, stored, refreshToken) {
178
173
  const reply = await tokenRequest({
179
174
  grant_type: "refresh_token",
180
- refresh_token: stored.refreshToken
175
+ refresh_token: refreshToken
181
176
  });
182
- if (!reply || !await hasPushAccess(reply.access_token)) return null;
177
+ if (!reply) return null;
178
+ if (!await hasPushAccess(reply.access_token)) return "denied";
183
179
  const session = sessionFrom(reply, stored, stored.issuedAt);
184
180
  return {
185
181
  session,
186
182
  cookie: await sessionCookie(request, session)
187
183
  };
188
184
  }
185
+ async function authenticate(request) {
186
+ const stored = await open(await keyPromise, "session", readCookies(request.headers.get("cookie")).get(names(request).session));
187
+ if (!stored || typeof stored.token !== "string" || typeof stored.login !== "string") return null;
188
+ const at = now();
189
+ if (at >= stored.issuedAt + sessionMs) return null;
190
+ if (at < stored.expiresAt - REFRESH_MARGIN_MS) return { session: stored };
191
+ if (!stored.refreshToken || !stored.refreshExpiresAt || at >= stored.refreshExpiresAt) return null;
192
+ let pending = renewing.get(stored.refreshToken);
193
+ if (!pending) {
194
+ const token = stored.refreshToken;
195
+ pending = renew(request, stored, token).catch(() => null);
196
+ renewing.set(token, pending);
197
+ pending.finally(() => renewing.delete(token));
198
+ }
199
+ const renewed = await pending;
200
+ if (renewed === "denied") return null;
201
+ if (renewed) return renewed;
202
+ return at < stored.expiresAt ? { session: stored } : null;
203
+ }
189
204
  async function login(request) {
190
205
  const url = new URL(request.url);
191
206
  const state = randomToken(16);
@@ -318,6 +333,15 @@ function redirectToSignIn(request) {
318
333
  }
319
334
  });
320
335
  }
336
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
337
+ /**
338
+ * What a signed-in person sees when their page could not be drawn: the reason, in words, instead of a blank 500. Only
339
+ * people with push access to the repository get here, so the message may name files and fields.
340
+ */
341
+ function failedPage(error) {
342
+ const reason = error instanceof Error ? error.message : String(error);
343
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>This page could not be drawn</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:42rem;margin:12vh auto;padding:0 1.25rem;color:#1d1b18}pre{white-space:pre-wrap;background:#f4f1ec;padding:1rem;border-radius:.5rem;font-size:.875rem}</style></head><body><h1>This page could not be drawn</h1><p>The content in the repository does not render. Fix it in the editor, or in the repository, and reload.</p><pre>${escapeHtml(reason)}</pre></body></html>`;
344
+ }
321
345
  function createHostedMiddleware(editor, options = {}) {
322
346
  const required = options.signIn !== "optional";
323
347
  return async ({ request, locals }, next) => {
@@ -336,7 +360,24 @@ function createHostedMiddleware(editor, options = {}) {
336
360
  });
337
361
  }
338
362
  locals.bearminion = scope;
339
- return editor.inject(request, await next());
363
+ let response;
364
+ try {
365
+ response = await next();
366
+ } catch (error) {
367
+ if (!isPageLoad(request)) throw error;
368
+ const page = new Response(failedPage(error), {
369
+ status: 200,
370
+ headers: { "content-type": "text/html; charset=utf-8" }
371
+ });
372
+ const withOverlay = await editor.inject(request, page);
373
+ const headers = new Headers(withOverlay.headers);
374
+ headers.set("cache-control", "private, no-store");
375
+ return new Response(withOverlay.body, {
376
+ status: 500,
377
+ headers
378
+ });
379
+ }
380
+ return editor.inject(request, response);
340
381
  };
341
382
  }
342
383
  //#endregion
package/dist/hosted.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as CollectionOptions, n as ImageConvertOptions, t as EditorContext, v as collection, y as ContentStore } from "./editor-context-BBsL5NFx.js";
2
- import { i as StoreKeyError, n as githubStore, r as StoreError, t as GithubStoreOptions } from "./github-store-DLQazToO.js";
1
+ import { _ as CollectionOptions, n as ImageConvertOptions, t as EditorContext, v as collection, y as ContentStore } from "./editor-context-ESJwMFpS.js";
2
+ import { i as StoreKeyError, n as githubStore, r as StoreError, t as GithubStoreOptions } from "./github-store-CDQNvoKQ.js";
3
3
  import { g as ContentModel, n as PageRules, t as Page } from "./page-D1pdneYm.js";
4
4
  //#region src/api.d.ts
5
5
  interface HandleMeta {
package/dist/hosted.js CHANGED
@@ -3,8 +3,9 @@ import { t as defaultTheme } from "./theme-BvqJ8UnS.js";
3
3
  import { a as resolvePageRules, c as withoutOrphanSections, n as createPageSchema, r as createTolerantPageSchema, s as slugSchema } from "./page-wlcQJAA-.js";
4
4
  import { n as createMigrator } from "./migrate-b408EaLp.js";
5
5
  import { i as resolveMaxImageBytes, r as resolveConvert } from "./upload-rules-Cao9uY5K.js";
6
- import { d as DEFAULT_VIDEO_BYTE_LIMIT, n as handleEditorRequest, t as githubStore } from "./github-store-DUf07ODw.js";
7
- import { n as AUTH_PREFIX, r as createHostedAuth, t as createHostedMiddleware } from "./hosted-middleware-DTnZoRsK.js";
6
+ import { f as DEFAULT_VIDEO_BYTE_LIMIT, n as missingImageSvg, r as handleEditorRequest, t as githubStore } from "./github-store-D3LEUhcM.js";
7
+ import { S as isAssetPath } from "./draft-store-DBEfw_Gq.js";
8
+ import { n as AUTH_PREFIX, r as createHostedAuth, t as createHostedMiddleware } from "./hosted-middleware-BQPW2YiB.js";
8
9
  //#region src/hosted-context.ts
9
10
  /** The context for `handleEditorRequest`. */
10
11
  function createHostedContext(options) {
@@ -36,6 +37,73 @@ function handleHostedRequest(request, context, meta = {}) {
36
37
  authenticated: true
37
38
  });
38
39
  }
40
+ const TYPES = {
41
+ png: "image/png",
42
+ jpg: "image/jpeg",
43
+ jpeg: "image/jpeg",
44
+ webp: "image/webp",
45
+ gif: "image/gif",
46
+ avif: "image/avif"
47
+ };
48
+ const headers = (extra = {}) => ({
49
+ "cache-control": "private, max-age=300",
50
+ "x-content-type-options": "nosniff",
51
+ ...extra
52
+ });
53
+ async function serveStoreAsset(request, store) {
54
+ const method = request.method.toUpperCase();
55
+ if (method !== "GET" && method !== "HEAD") return new Response("Method not allowed", {
56
+ status: 405,
57
+ headers: { allow: "GET, HEAD" }
58
+ });
59
+ const src = new URL(request.url).searchParams.get("src") ?? "";
60
+ const type = TYPES[src.slice(src.lastIndexOf(".") + 1).toLowerCase()];
61
+ if (!isAssetPath(src) || !type) return new Response("not found", {
62
+ status: 404,
63
+ headers: { "cache-control": "no-store" }
64
+ });
65
+ if (!store.readAsset) return new Response("This store does not serve images.", {
66
+ status: 501,
67
+ headers: { "cache-control": "no-store" }
68
+ });
69
+ let asset;
70
+ try {
71
+ const ifNoneMatch = request.headers.get("if-none-match");
72
+ asset = await store.readAsset(src, ifNoneMatch ? { ifNoneMatch } : {});
73
+ } catch (error) {
74
+ if (error instanceof StoreError) return new Response(JSON.stringify({
75
+ error: error.code,
76
+ message: error.message
77
+ }), {
78
+ status: error.status,
79
+ headers: {
80
+ "content-type": "application/json; charset=utf-8",
81
+ "cache-control": "no-store"
82
+ }
83
+ });
84
+ throw error;
85
+ }
86
+ if (!asset) return new Response(method === "HEAD" ? null : missingImageSvg(src), {
87
+ status: 404,
88
+ headers: {
89
+ "content-type": "image/svg+xml",
90
+ "cache-control": "no-store",
91
+ "x-content-type-options": "nosniff"
92
+ }
93
+ });
94
+ if ("notModified" in asset) return new Response(null, {
95
+ status: 304,
96
+ headers: headers({ etag: asset.etag })
97
+ });
98
+ return new Response(method === "HEAD" ? null : asset.bytes, {
99
+ status: 200,
100
+ headers: headers({
101
+ "content-type": type,
102
+ "content-length": String(asset.bytes.byteLength),
103
+ ...asset.etag ? { etag: asset.etag } : {}
104
+ })
105
+ });
106
+ }
39
107
  //#endregion
40
108
  //#region src/store-content.ts
41
109
  function createStoreContent(model, store, options = {}) {
@@ -151,6 +219,13 @@ function createHostedEditor(config) {
151
219
  if (signedIn.cookie) script.headers.append("set-cookie", signedIn.cookie);
152
220
  return script;
153
221
  }
222
+ if (pathname === "/__bearminion/assets") {
223
+ const signedIn = await authenticate(request);
224
+ if (!signedIn) return unauthenticated();
225
+ const image = await serveStoreAsset(request, storeFor(signedIn.session.token));
226
+ if (signedIn.cookie) image.headers.append("set-cookie", signedIn.cookie);
227
+ return image;
228
+ }
154
229
  if (pathname !== "/__bearminion/api" && !pathname.startsWith(`/__bearminion/api/`)) return null;
155
230
  const found = await authenticate(request);
156
231
  if (!found) return unauthenticated();
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as CollectionOptions, a as CommitRequest, c as HistoryEntry, d as SaveResponse, f as SitePreview, g as GitInfo, h as ChangedFile, i as ApiProblem, l as PageListItem, m as UploadedVideo, o as CommitResult, p as UploadedImage, r as ApiIssue, s as CreatePageRequest, u as SaveRequest, v as collection } from "./editor-context-BBsL5NFx.js";
1
+ import { _ as CollectionOptions, a as CommitRequest, c as HistoryEntry, d as SaveResponse, f as SitePreview, g as GitInfo, h as ChangedFile, i as ApiProblem, l as PageListItem, m as UploadedVideo, o as CommitResult, p as UploadedImage, r as ApiIssue, s as CreatePageRequest, u as SaveRequest, v as collection } from "./editor-context-ESJwMFpS.js";
2
2
  import { _ as renderMarkedHtml, a as WeightMark, f as markClass, g as reconcileMarks, i as TextRun, l as fontMarks, m as marksFromEmphasis, o as applyTextMark, r as TextMark, t as FontMark, v as splitMarkedText, y as weightMarks } from "./marks-BzLa48Y9.js";
3
3
  import { $ as mergeJsonLd, $t as tones, A as SectionDefinition, At as MAX_NAV_DEPTH, B as FieldIcons, Bt as toneSchema, C as ContentMigration, Ct as siteConsentSchema, D as SCHEMA_VERSION_KEY, Dt as ButtonStyle, E as DocumentKind, Et as themeSchema, F as defineWireframe, Ft as imageSchema, G as SiteJsonLdIds, Gt as EnumOption, H as ShowWhen, Ht as withEmphasis, I as wireKinds, It as linkSchema, J as generateSiteJsonLd, Jt as StringOption, K as SiteJsonLdSource, Kt as NumberOption, L as wireframeIssues, Lt as richTextSchema, M as WireKind, Mt as Text, N as WireRect, Nt as Tone, O as createMigrator, Ot as Image, P as Wireframe, Pt as htmlIdSchema, Q as jsonLdWarnings, Qt as toneOption, R as OptionalContent, Rt as textMarkSchema, S as defineTheme, St as siteAnalyticsSchema, T as ContentVersioning, Tt as themeColorsSchema, U as JsonLdBlock, Ut as BooleanOption, V as ShowCondition, Vt as trackingIdSchema, W as JsonLdResult, Wt as CountRule, X as isPlaceholderSiteUrl, Xt as motionOption, Y as hasJsonLdId, Yt as buttonStyles, Z as jsonLdSchema, Zt as themeModes, _ as SectionRegistry, _t as SiteSeo, a as createPageSchema, at as DEFAULT_MAX_HEADER_ACTIONS, b as ThemeFont, bt as brandLogoSchema, c as withoutOrphanSections, ct as FooterConfig, d as SectionOf, dt as Site, en as variantOption, et as parseJsonLdInput, f as anchorSchema, ft as SiteAnalytics, g as ContentModel, gt as SiteOf, h as API_PREFIX, ht as SiteDefinition, i as Seo, it as DEFAULT_MAX_FOOTER_COLUMNS, j as defineSection, jt as RichText, k as SectionConfig, kt as Link, l as BaseSection, lt as Header, m as sectionIdSchema, mt as SiteConsent, nt as upsertJsonLd, o as isSystemPage, ot as Footer, p as createSectionSchema, pt as SiteConfig, q as formatJsonLd, qt as Option, r as SYSTEM_PAGES, rt as BRAND_LOGO_HEIGHT, s as seoSchema, st as FooterColumn, t as Page, tt as siteJsonLdIds, u as PropsOf, ut as HeaderConfig, v as ThemeConfig, vt as SiteWith, w as ContentMigrator, wt as siteSeoSchema, x as defaultTheme, xt as defineSite, y as ThemeDefinition, yt as Theme, z as FieldChoices, zt as textSchema } from "./page-D1pdneYm.js";
4
4
  import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bearminion",
3
- "version": "1.16.0",
3
+ "version": "1.16.2",
4
4
  "description": "A git-based CMS for Astro with no database and no server: JSON content in your repo, edited by clicking on the page during astro dev.",
5
5
  "license": "MIT",
6
6
  "author": "Jakub Lange",
@@ -2,6 +2,7 @@
2
2
  import { Image as AssetImage } from 'astro:assets'
3
3
  import { isRemote, resolveLocalAsset } from '../../lib/assets'
4
4
  import { cn } from '../../lib/cn'
5
+ import { editing } from '../../lib/editing'
5
6
  import { image, type ImageVariants } from './image'
6
7
 
7
8
  interface Props {
@@ -39,7 +40,7 @@ const remote = isRemote(src)
39
40
  const asset = remote ? undefined : resolveLocalAsset(src)
40
41
  const looksLocal = src.replace(/^\//, '').startsWith('src/assets/')
41
42
  let devSrc: string | undefined
42
- if (import.meta.env.DEV && looksLocal && !asset) {
43
+ if (editing && looksLocal && !asset) {
43
44
  devSrc = `/__bearminion/assets?src=${encodeURIComponent(src.replace(/^\//, ''))}`
44
45
  }
45
46
 
@@ -2,6 +2,7 @@
2
2
  import Image from '../atoms/Image.astro'
3
3
  import { isRemote, resolveLocalAsset } from '../../lib/assets'
4
4
  import { cn } from '../../lib/cn'
5
+ import { editing } from '../../lib/editing'
5
6
 
6
7
  interface Props {
7
8
  src?: string
@@ -31,7 +32,7 @@ const {
31
32
  const looksLocal = Boolean(src && src.replace(/^\//, '').startsWith('src/assets/'))
32
33
  const asset = src && !isRemote(src) ? resolveLocalAsset(src) : undefined
33
34
  let devSrc: string | undefined
34
- if (import.meta.env.DEV && looksLocal && !asset && src) {
35
+ if (editing && looksLocal && !asset && src) {
35
36
  devSrc = `/__bearminion/assets?src=${encodeURIComponent(src.replace(/^\//, ''))}`
36
37
  }
37
38
  if (looksLocal && !asset && !devSrc) {
@@ -2,6 +2,7 @@
2
2
  import type { Section } from '../definitions'
3
3
  import Image from '../../atoms/Image.astro'
4
4
  import { isRemote, resolveLocalAsset } from '../../../lib/assets'
5
+ import { editing } from '../../../lib/editing'
5
6
  import SectionShell from '../../molecules/SectionShell.astro'
6
7
 
7
8
  interface Props {
@@ -19,6 +20,8 @@ function showImage(src: string) {
19
20
  if (src === 'placeholder') return false
20
21
  if (isRemote(src)) return true
21
22
  if (src.replace(/^\//, '').startsWith('src/assets/') && !resolveLocalAsset(src)) {
23
+ // Just uploaded in the hosted editor: <Image> draws it from the editor's route.
24
+ if (editing) return true
22
25
  throw new Error(`No file in src/assets for image path "${src}". Restore the file, or choose another image in the editor and save.`)
23
26
  }
24
27
  return Boolean(resolveLocalAsset(src))
@@ -4,6 +4,7 @@ import Typography from '../../atoms/Typography.astro'
4
4
  import SectionHeader from '../../molecules/SectionHeader.astro'
5
5
  import SectionShell from '../../molecules/SectionShell.astro'
6
6
  import MediaPlayer from './MediaPlayer.astro'
7
+ import { editing } from '../../../lib/editing'
7
8
  import { parseMediaSource } from './source'
8
9
 
9
10
  interface Props {
@@ -19,7 +20,7 @@ const reveal = section.motion ?? motion
19
20
  const intro = props.intro && Boolean(props.eyebrow || props.heading || props.body)
20
21
  const filled = props.kind === 'video' ? Boolean(props.video && parseMediaSource(props.video)) : Boolean(props.image?.src && props.image.src !== 'placeholder' && !props.image.hidden)
21
22
  // A built site leaves out an empty frame, and with no heading either, the whole section.
22
- const showFrame = filled || import.meta.env.DEV
23
+ const showFrame = filled || editing
23
24
  const rendered = showFrame || intro
24
25
  const player = {
25
26
  kind: props.kind,
@@ -2,6 +2,7 @@
2
2
  import type { Image } from 'bearminion'
3
3
  import { imageSrcset, imageUrl } from '../../../lib/image-url'
4
4
  import { cn } from '../../../lib/cn'
5
+ import { editing } from '../../../lib/editing'
5
6
  import MediaFrame from '../../molecules/MediaFrame.astro'
6
7
  import type { MediaProps } from './definition'
7
8
  import { parseMediaSource } from './source'
@@ -44,7 +45,7 @@ const looping = source?.kind === 'file' && playback === 'loop'
44
45
  {
45
46
  empty ? (
46
47
  // The empty frame is an editor hint, so a built site leaves it out.
47
- import.meta.env.DEV && (
48
+ editing && (
48
49
  <div class={cn(frame, 'placeholder-stripes flex flex-col items-center justify-center gap-4 p-6 text-center')} data-field={kind === 'image' ? imageField : undefined}>
49
50
  {kind === 'video' && (
50
51
  <span class="flex size-14 items-center justify-center rounded-full bg-fg text-bg" aria-hidden="true">
@@ -0,0 +1,5 @@
1
+ /**
2
+ * True while someone is editing: on the dev server, and on the hosted editor's own deployment (its build sets
3
+ * BEARMINION_HOSTED). A built public site is neither, so editor hints and editor-only image routes stay out of it.
4
+ */
5
+ export const editing = Boolean(import.meta.env.DEV || import.meta.env.BEARMINION_HOSTED)
@@ -1,6 +1,7 @@
1
1
  import { getImage } from 'astro:assets'
2
2
  import type { Image } from 'bearminion'
3
3
  import { isRemote, resolveLocalAsset } from './assets'
4
+ import { editing } from './editing'
4
5
 
5
6
  /**
6
7
  * An image as a plain URL, for attributes that take no `<img>`, such as a video's `poster`. A file in `src/assets` is
@@ -31,7 +32,7 @@ export async function imageUrl(image: Image | undefined, maxWidth = 1920): Promi
31
32
  const asset = resolveLocalAsset(path)
32
33
  if (asset) return (await getImage({ src: asset, width: Math.min(asset.width, maxWidth), format: 'webp' })).src
33
34
  if (path.startsWith('src/assets/')) {
34
- if (import.meta.env.DEV) return `/__bearminion/assets?src=${encodeURIComponent(path)}`
35
+ if (editing) return `/__bearminion/assets?src=${encodeURIComponent(path)}`
35
36
  throw new Error(`No file in src/assets for the image "${image.src}". Restore the file, or choose another image in the editor and save.`)
36
37
  }
37
38
  return image.src
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "template": "default",
4
- "version": "1.16.0",
4
+ "version": "1.16.2",
5
5
  "files": {
6
6
  "src/components/atoms/Button.astro": {
7
7
  "hash": "7be42b3dc3a3b59bec169de32a9d801904689e2705473d1945724658dc799043",
@@ -12,8 +12,10 @@
12
12
  "history": []
13
13
  },
14
14
  "src/components/atoms/Image.astro": {
15
- "hash": "015e7e24d250e4bec58e1699eaf115dc1a92a713bdc317cc1a3f31fae163f09d",
16
- "history": []
15
+ "hash": "270f92dd48d0ac705053993f4e18f9c8acd09dd255c955218ba4a064b4507176",
16
+ "history": [
17
+ "015e7e24d250e4bec58e1699eaf115dc1a92a713bdc317cc1a3f31fae163f09d"
18
+ ]
17
19
  },
18
20
  "src/components/atoms/Typography.astro": {
19
21
  "hash": "56e7ea3cf08ef4159d6b72c97761d13334b5468476e0226d62b42effd1368fd2",
@@ -40,8 +42,10 @@
40
42
  "history": []
41
43
  },
42
44
  "src/components/molecules/MediaFrame.astro": {
43
- "hash": "f57a20d18beacb9f28acd9efe9eeb3487c594735239f47c7bb4311f1a4140886",
44
- "history": []
45
+ "hash": "4ee34a12f403e8f55d0b63340fc88e176ec71cf278c503bd508bbf99a85a34d2",
46
+ "history": [
47
+ "f57a20d18beacb9f28acd9efe9eeb3487c594735239f47c7bb4311f1a4140886"
48
+ ]
45
49
  },
46
50
  "src/components/molecules/Pill.astro": {
47
51
  "hash": "b7b32e8de70084159003552f61dbccaf8aa13d338f231183ca9443efa72c7644",
@@ -140,8 +144,10 @@
140
144
  "history": []
141
145
  },
142
146
  "src/components/sections/logo-strip/LogoStrip.astro": {
143
- "hash": "0bb887f0282bf9d7d0ae65a3afc7f3813c58247c0aa70a4962a6a5e35b8e1c71",
144
- "history": []
147
+ "hash": "b647d634c1a382779dc22550c84af65a88afbec8119a5b51ee058c521b7b95b5",
148
+ "history": [
149
+ "0bb887f0282bf9d7d0ae65a3afc7f3813c58247c0aa70a4962a6a5e35b8e1c71"
150
+ ]
145
151
  },
146
152
  "src/components/sections/logo-strip/definition.ts": {
147
153
  "hash": "de761c20c0ce0b5f4fcc1ad96535addf6f7fb668abd1954709d2f68f72ccffdd",
@@ -152,12 +158,16 @@
152
158
  "history": []
153
159
  },
154
160
  "src/components/sections/media/Media.astro": {
155
- "hash": "1df9f736daf07b6a4a2768463896b477197d1baa68a445e4ee1de92080b227c2",
156
- "history": []
161
+ "hash": "8277c9c2ef089b437c5ccaa93b80d9f9c0020bfb9c4a29526264c29c25d6fcf0",
162
+ "history": [
163
+ "1df9f736daf07b6a4a2768463896b477197d1baa68a445e4ee1de92080b227c2"
164
+ ]
157
165
  },
158
166
  "src/components/sections/media/MediaPlayer.astro": {
159
- "hash": "e2444c6ff067276b4aeb5a7f6da368a0ce7e6db4feaac7303d508f3df28eadad",
160
- "history": []
167
+ "hash": "e5b8e9800c43e0a276ef763fddfb62e99cbb120f22a31928b81277d85a4626a8",
168
+ "history": [
169
+ "e2444c6ff067276b4aeb5a7f6da368a0ce7e6db4feaac7303d508f3df28eadad"
170
+ ]
161
171
  },
162
172
  "src/components/sections/media/definition.ts": {
163
173
  "hash": "520d1d78d234c8a005abeffe99fdfe12201cc78e56023bf627869b562974aa3c",
@@ -263,13 +273,19 @@
263
273
  "hash": "b52d5520d87e37f6c5f33128637aca671f744ede65588d751b2d69b3fcef849d",
264
274
  "history": []
265
275
  },
276
+ "src/lib/editing.ts": {
277
+ "hash": "4d6a29a5a881d6a02e9fdac43b57a0a1d8d54b0749a6beec39f124c4a75f1c69",
278
+ "history": []
279
+ },
266
280
  "src/lib/hidden-text.ts": {
267
281
  "hash": "44ae57dcbfaa71586589b212fe9a3eefcc5c5763d219e8d175095ea2b6722dcf",
268
282
  "history": []
269
283
  },
270
284
  "src/lib/image-url.ts": {
271
- "hash": "47e51f06b5bfc3c0fc595bd18d13d71f9f68d063c3d12e5514ecb8098a114131",
272
- "history": []
285
+ "hash": "deb9afab379804204634f3eeb0496dce6b923496c6f2bf33227d64e40fa5809f",
286
+ "history": [
287
+ "47e51f06b5bfc3c0fc595bd18d13d71f9f68d063c3d12e5514ecb8098a114131"
288
+ ]
273
289
  },
274
290
  "src/lib/link-attrs.ts": {
275
291
  "hash": "648802476e4dfaaeab6c4172313c683420c1fb66898de8f8c74ca4adf876cd37",
@@ -379,6 +395,7 @@
379
395
  "src/components/sections/shared.ts",
380
396
  "src/lib/assets.ts",
381
397
  "src/lib/cn.ts",
398
+ "src/lib/editing.ts",
382
399
  "src/lib/link-attrs.ts"
383
400
  ],
384
401
  "npm": {
@@ -409,6 +426,7 @@
409
426
  "src/components/sections/shared.ts",
410
427
  "src/lib/assets.ts",
411
428
  "src/lib/cn.ts",
429
+ "src/lib/editing.ts",
412
430
  "src/lib/image-url.ts"
413
431
  ],
414
432
  "npm": {
@@ -443,6 +461,7 @@
443
461
  "src/components/sections/shared.ts",
444
462
  "src/lib/assets.ts",
445
463
  "src/lib/cn.ts",
464
+ "src/lib/editing.ts",
446
465
  "src/lib/link-attrs.ts"
447
466
  ],
448
467
  "npm": {
@@ -465,7 +484,8 @@
465
484
  "src/components/sections/logo-strip/definition.ts",
466
485
  "src/components/sections/logo-strip/wireframe.ts",
467
486
  "src/lib/assets.ts",
468
- "src/lib/cn.ts"
487
+ "src/lib/cn.ts",
488
+ "src/lib/editing.ts"
469
489
  ],
470
490
  "npm": {
471
491
  "astro": "^7.4.1",
@@ -496,6 +516,7 @@
496
516
  "src/components/sections/shared.ts",
497
517
  "src/lib/assets.ts",
498
518
  "src/lib/cn.ts",
519
+ "src/lib/editing.ts",
499
520
  "src/lib/image-url.ts"
500
521
  ],
501
522
  "npm": {
@@ -602,7 +623,8 @@
602
623
  "src/components/sections/testimonials/definition.ts",
603
624
  "src/components/sections/testimonials/wireframe.ts",
604
625
  "src/lib/assets.ts",
605
- "src/lib/cn.ts"
626
+ "src/lib/cn.ts",
627
+ "src/lib/editing.ts"
606
628
  ],
607
629
  "npm": {
608
630
  "astro": "^7.4.1",
@@ -657,6 +679,7 @@
657
679
  "src/components/sections/text-image/wireframe.ts",
658
680
  "src/lib/assets.ts",
659
681
  "src/lib/cn.ts",
682
+ "src/lib/editing.ts",
660
683
  "src/lib/link-attrs.ts"
661
684
  ],
662
685
  "npm": {