bearminion 1.5.0 → 1.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2978aaf: Run your own code behind the Contact form, with its keys on the server and in the environment. The new `bearminion/forms` entry has `defineForm(handler, options)`: put it in `src/forms/contact.ts` and add a few lines of glue for Vercel, Netlify, Cloudflare or an Astro endpoint (all in the Forms guide). The form always posts to `/api/contact`; nothing about it is stored in the content files. The handler receives the message and your environment, and returns nothing, `{ ok: true, message }`, `{ ok: false, error, fieldErrors }`, or throws a `FormError`; any other error becomes a plain "could not be delivered" for the visitor and goes to your log. It answers `POST` only, reads JSON, multipart and urlencoded posts, refuses posts over 64 KB and posts from other sites (`origins` lists the exceptions), and drops a filled trap field on the server too. It uses only `Request` and `Response`, so one file runs on every host. `astro dev` serves each file in `src/forms` at `/api/<name>`: a dry run that prints the message by default, and your handler for real with `BEARMINION_FORMS_LIVE=on` in `.env.local` (turn the route off with the `forms: false` option). Cloudflare Turnstile: set the public site key as `PUBLIC_TURNSTILE_SITE_KEY` where the site is built, and `defineForm(handler, { turnstile: true })` checks the token with `TURNSTILE_SECRET_KEY`; `verifyTurnstile` is exported too. A failed send now shows its error in a message at the bottom of the screen that stays until the visitor closes it. A handler's `{ ok: true, message }` replaces the thank-you text. The starter gets a `.env.example` listing those variables. The Forms guide is rewritten so you can set all of it up yourself.
8
+ - 2978aaf: The Contact form no longer says "Message sent." for a message that went nowhere. It posts with `fetch` to `/api/contact` and shows the states: sending, sent, an error from the handler, field errors under their fields, and no connection. A trap field and a 1.5 second minimum time drop what a script sends. While `src/forms/contact.ts` does not exist, `astro dev` and `astro build` print a warning (never an error), the section's settings in the editor show the same warning, and a visitor who sends the form gets an error. `bearminion` exports the types `FormSubmission` and `FormResult` for handlers you write yourself. `defineSection` takes a `form` option: the handler a section posts to, which the editor's sidebar reports on, and a new editor route `GET /forms` says whether its file exists. **Breaking for sites that set an endpoint:** the Contact section no longer has an `action` prop. Content version 3 drops `action` (and `format` and `turnstile`) from every Contact section, and the file is rewritten the next time it is saved. Copy a form service's address into a handler first: the Forms guide has complete files for Formspree and Web3Forms. New guide: Forms.
9
+
10
+ ### Patch Changes
11
+
12
+ - 2978aaf: Fixed an error in the browser console, "Cannot read properties of undefined (reading 'toLowerCase')", when the browser autofilled a form on a page with the editor. Autofill sends key events without a `key`, and the editor's keyboard shortcuts assumed one.
13
+ - 60cfb70: The Contact form works with JavaScript off. A browser that posts the form itself is no longer left on the raw JSON answer: `defineForm` redirects it back to the page, to a "Message sent." block or a "not sent" line (only when the `Referer` is on the same site; otherwise the JSON answer stays). Pages with section motion were also invisible without JavaScript, because sections start transparent and a script reveals them; they now show.
14
+ - 2978aaf: Fix: a video uploaded in the editor now plays in the dev site straight away. Vite learns which files `public/` holds from its file watcher, and the editor keeps the videos folder out of that watcher so uploads do not reload the page, so a new video answered 404 until `astro dev` was restarted. The editor now tells Vite about the one file that was added or removed. The template's `astro.config.ts` also reads `BEARMINION_VIDEOS_DIR` (used by the tests, like the content and uploads overrides).
15
+
16
+ ## 1.6.0
17
+
18
+ ### Minor Changes
19
+
20
+ - eec6f3d: New starter sections and editor features.
21
+
22
+ - **Gallery** section: grid, masonry and featured layouts, a keyboard-friendly lightbox, an optional box around each picture, and required alt text.
23
+ - **Text** section: long-form rich text for an About or policy page, with a narrow, readable column on by default. Rich-text fields can opt into **H2** and **H3** (`data-rich-headings`); `renderRichText`, `sanitizeRichHtml` and `stripPlainRich` take a `{ headings }` option.
24
+ - **Media** now covers video: the separate Video section is gone, and Media gains `playback` (`controls` or `loop`). Content `schemaVersion` 2 migrates existing Video sections to Media automatically.
25
+ - **Video uploads**: upload an mp4, webm, mov or ogv to `public/videos` from the editor (`videosDir`, `maxVideoBytes`, default 50 MB), pick an uploaded one, and see what a pasted link is or why it will not play. New API routes `GET`/`POST /videos` and `DELETE /videos/:filename`.
26
+ - `parseMediaSource` and `VIDEO_FILE` are exported from `bearminion`.
27
+
28
+ ### Patch Changes
29
+
30
+ - eec6f3d: Clearer package descriptions and READMEs: what BearMinion is, who it is for, and what `create-bearminion` refuses (a folder that is not new or empty).
31
+
3
32
  ## 1.5.0
4
33
 
5
34
  ### Minor Changes
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  </p>
4
4
 
5
5
  <p align="center">
6
- A website you edit by clicking on it. No database, no admin panel, no server.<br />
6
+ The BearMinion for the bare minimum. A website you edit by clicking on it: no database to patch at 3 AM, no admin panel, no server.<br />
7
7
  Built on <a href="https://astro.build">Astro</a>.
8
8
  </p>
9
9
 
@@ -34,7 +34,7 @@ It asks for the site's name and web address. Open the address `npm run dev` prin
34
34
  ## What you can change
35
35
 
36
36
  - **Text** right on the page, with bold, italic, code, links and lists
37
- - **Sections**: thirteen ready-made types, each with three layouts, added from a visual picker
37
+ - **Sections**: fourteen ready-made types, each with two or three layouts, added from a visual picker
38
38
  - **Pages, menus and footer**, with titles and descriptions for search and sharing
39
39
  - **Images**: upload, choose how they fill their frame and which part stays in view
40
40
  - **Colors**: pick three, and the editor builds a full light and dark palette that stays readable
package/dist/astro.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as SectionRegistry, J as SiteDefinition, Y as SiteOf, Yt as ContentMigrator, k as ContentModel, t as Page, u as SectionOf } from "./page-B5NoN74Q.js";
2
- import { a as StoreKeyError, c as createFileStore, i as FileStoreOptions, n as EditorContext, o as StoreOperation, r as ContentStore, s as UploadStore, t as BearminionOptions } from "./options-DBfoi9D1.js";
1
+ import { A as SectionRegistry, J as SiteDefinition, Y as SiteOf, Yt as ContentMigrator, k as ContentModel, t as Page, u as SectionOf } from "./page-BfI9cD8g.js";
2
+ import { a as StoreKeyError, c as createFileStore, i as FileStoreOptions, n as EditorContext, o as StoreOperation, r as ContentStore, s as UploadStore, t as BearminionOptions } from "./options-BeJQnsZM.js";
3
3
  import { AstroIntegration } from "astro";
4
4
  //#region src/integration.d.ts
5
5
  interface BearminionIntegration extends AstroIntegration {
package/dist/astro.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import { a as imageFields, c as ContentReadError, l as ContentValidationError, r as loadThemePreview, t as PreviewUnavailableError } from "./preview--S1QUrMM.js";
2
2
  import { t as defaultTheme } from "./theme-DFjHjgFO.js";
3
3
  import { i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema, s as withoutOrphanSections, u as isOrphanSection } from "./page-NOFVEqn1.js";
4
- import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-B56wxCiC.js";
5
- import { a as JSON_BODY_LIMIT, c as isInside, d as resolveDir, f as resolveInside, i as IMAGE_BYTE_LIMIT, l as isLocalRequest, n as contentReloadPlugin, o as MULTIPART_BODY_LIMIT, r as dropEarlyReloadAfterSave, s as asDirectory, u as readSlug } from "./reload-D0vwI0OT.js";
4
+ import { a as DEFAULT_UPLOADS_DIR, i as DEFAULT_CONTENT_DIR, n as createMigrator, o as DEFAULT_VIDEOS_DIR, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
5
+ import { a as JSON_BODY_LIMIT, c as isInside, d as resolveDir, f as resolveInside, i as IMAGE_BYTE_LIMIT, l as isLocalRequest, n as contentReloadPlugin, o as MULTIPART_BODY_LIMIT, r as dropEarlyReloadAfterSave, s as asDirectory, u as readSlug } from "./reload-BPkPoQ-P.js";
6
6
  import { S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-1Y4-sn45.js";
7
7
  import { z } from "zod";
8
8
  import fs from "node:fs";
9
- import { fileURLToPath } from "node:url";
10
9
  import path from "node:path";
11
- import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
10
+ import { fileURLToPath } from "node:url";
11
+ import { parseEnv, promisify } from "node:util";
12
12
  import { randomBytes } from "node:crypto";
13
+ import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
13
14
  import { execFile } from "node:child_process";
14
- import { promisify } from "node:util";
15
15
  //#region src/editor-client.ts
16
16
  const VIRTUAL_ID = "virtual:bearminion-editor";
17
17
  const RESOLVED_ID = `\0${VIRTUAL_ID}`;
@@ -35,6 +35,240 @@ function editorClientPlugin() {
35
35
  };
36
36
  }
37
37
  //#endregion
38
+ //#region src/forms-dev.ts
39
+ /** Where the forms are and under which path, or `null` when the option turns them off. */
40
+ function resolveFormsConfig(option, root) {
41
+ if (option === false) return null;
42
+ const prefix = (option?.prefix ?? "/api").replace(/\/+$/, "");
43
+ return {
44
+ dir: resolveDir(root, option?.dir, "src/forms"),
45
+ prefix: prefix.startsWith("/") ? prefix : `/${prefix}`
46
+ };
47
+ }
48
+ const FORM_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
49
+ const EXTENSIONS = [
50
+ ".ts",
51
+ ".mts",
52
+ ".js",
53
+ ".mjs"
54
+ ];
55
+ const BODY_LIMIT = 1048576;
56
+ /** The file behind `name`, or `null` when there is none. `name` is checked, so it cannot leave the folder. */
57
+ function formFile(dir, name) {
58
+ if (!FORM_FILE.test(name)) return null;
59
+ for (const extension of EXTENSIONS) {
60
+ const file = path.join(dir, `${name}${extension}`);
61
+ if (fs.existsSync(file)) return file;
62
+ }
63
+ return null;
64
+ }
65
+ /** `.env`, `.env.local`, `.env.development` and `.env.development.local` of the project, later ones winning. */
66
+ function readDotEnv(root) {
67
+ const merged = {};
68
+ for (const name of [
69
+ ".env",
70
+ ".env.local",
71
+ ".env.development",
72
+ ".env.development.local"
73
+ ]) try {
74
+ Object.assign(merged, parseEnv(fs.readFileSync(path.join(root, name), "utf8")));
75
+ } catch {}
76
+ return merged;
77
+ }
78
+ /** True when `BEARMINION_FORMS_LIVE=on` is in the environment or in the project's `.env` files. */
79
+ function formsAreLive(root) {
80
+ return (process.env.BEARMINION_FORMS_LIVE ?? readDotEnv(root).BEARMINION_FORMS_LIVE) === "on";
81
+ }
82
+ function isForm(value) {
83
+ return typeof value === "object" && value !== null && typeof value.fetch === "function";
84
+ }
85
+ function createFormsMiddleware(options) {
86
+ return (req, res, next) => {
87
+ const pathname = (req.url ?? "/").split("?")[0]?.replace(/\/+$/, "") ?? "";
88
+ if (!pathname.startsWith(`${options.prefix}/`)) {
89
+ next();
90
+ return;
91
+ }
92
+ const name = pathname.slice(options.prefix.length + 1);
93
+ const file = formFile(options.dir, name);
94
+ if (!file) {
95
+ next();
96
+ return;
97
+ }
98
+ answer(req, res, options, name, file).catch((error) => {
99
+ options.log.error(`/${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
100
+ if (!res.headersSent) fail(res, 500, error instanceof Error ? error.message : "The form failed.");
101
+ });
102
+ };
103
+ }
104
+ function fail(res, status, error) {
105
+ res.statusCode = status;
106
+ res.setHeader("content-type", "application/json; charset=utf-8");
107
+ res.end(JSON.stringify({
108
+ ok: false,
109
+ error
110
+ }));
111
+ }
112
+ async function answer(req, res, options, name, file) {
113
+ const form = (await options.load(file))?.default;
114
+ if (!isForm(form)) {
115
+ const relative = path.relative(options.root, file).split(path.sep).join("/");
116
+ options.log.error(`${relative} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
117
+ return fail(res, 500, `${relative} must export default defineForm(...).`);
118
+ }
119
+ const headers = new Headers();
120
+ for (const [key, value] of Object.entries(req.headers)) {
121
+ if (value === void 0) continue;
122
+ for (const item of Array.isArray(value) ? value : [value]) headers.append(key, item);
123
+ }
124
+ const method = (req.method ?? "GET").toUpperCase();
125
+ const body = method === "GET" || method === "HEAD" ? void 0 : await readLimited(req, BODY_LIMIT);
126
+ if (body === null) return fail(res, 413, "The message is too large.");
127
+ const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
128
+ method,
129
+ headers,
130
+ ...body ? { body } : {}
131
+ });
132
+ const env = {
133
+ ...readDotEnv(options.root),
134
+ ...process.env
135
+ };
136
+ const response = await form.fetch(request, env, {
137
+ dev: true,
138
+ ...options.live ? {} : { dryRun: (submission) => options.log.info(`/${name} received a message. Dry run: nothing was sent. Start the dev server with BEARMINION_FORMS_LIVE=on to run your handler.\n${JSON.stringify(submission, null, 2)}`) }
139
+ });
140
+ res.statusCode = response.status;
141
+ response.headers.forEach((value, key) => {
142
+ res.setHeader(key, value);
143
+ });
144
+ res.end(Buffer.from(await response.arrayBuffer()));
145
+ }
146
+ /** The body of the request, or `null` once it is over `limit` bytes. */
147
+ function readLimited(req, limit) {
148
+ return new Promise((resolve, reject) => {
149
+ const chunks = [];
150
+ let size = 0;
151
+ req.on("data", (chunk) => {
152
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
153
+ size += buffer.length;
154
+ if (size > limit) {
155
+ resolve(null);
156
+ req.resume();
157
+ return;
158
+ }
159
+ chunks.push(buffer);
160
+ });
161
+ req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
162
+ req.on("error", reject);
163
+ });
164
+ }
165
+ //#endregion
166
+ //#region src/videos.ts
167
+ const EXTENSION$1 = {
168
+ mp4: ".mp4",
169
+ mov: ".mov",
170
+ webm: ".webm",
171
+ ogv: ".ogv"
172
+ };
173
+ const MIME_TO_KIND$1 = {
174
+ "video/mp4": "mp4",
175
+ "video/x-m4v": "mp4",
176
+ "video/quicktime": "mov",
177
+ "video/webm": "webm",
178
+ "video/ogg": "ogv"
179
+ };
180
+ /** Room for multipart boundaries around a max-size video. */
181
+ function videoBodyLimit(maxVideoBytes) {
182
+ return maxVideoBytes + 262144;
183
+ }
184
+ /** The container a file really is, from its first bytes. The file's name and declared type are not trusted. */
185
+ function sniffVideo(bytes) {
186
+ if (bytes.length >= 12 && ascii$1(bytes, 4, 8) === "ftyp") {
187
+ const brand = ascii$1(bytes, 8, 12);
188
+ if (brand === "avif" || brand === "avis") return null;
189
+ return brand === "qt " ? "mov" : "mp4";
190
+ }
191
+ 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;
192
+ if (bytes.length >= 4 && ascii$1(bytes, 0, 4) === "OggS") return "ogv";
193
+ return null;
194
+ }
195
+ function videoKindFromMime(mime) {
196
+ const base = mime.split(";", 1)[0]?.trim().toLowerCase() ?? "";
197
+ return MIME_TO_KIND$1[base] ?? null;
198
+ }
199
+ /** The address a file in `public/` is served at. */
200
+ function publicUrl(root, filePath) {
201
+ return `/${path.relative(path.resolve(root, "public"), filePath).split(path.sep).join("/")}`;
202
+ }
203
+ async function saveVideo(options) {
204
+ await mkdir(options.videosDir, { recursive: true });
205
+ const extension = EXTENSION$1[options.kind];
206
+ const stem = safeStem$1(options.originalName);
207
+ for (let attempt = 0; attempt < 8; attempt += 1) {
208
+ const filename = `${stem}-${randomBytes(4).toString("hex")}${extension}`;
209
+ const filePath = resolveInside(options.videosDir, filename);
210
+ if (filePath === null) throw new Error("Resolved upload path escaped the videos directory.");
211
+ try {
212
+ await writeFile(filePath, options.bytes, { flag: "wx" });
213
+ } catch (error) {
214
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") continue;
215
+ throw error;
216
+ }
217
+ if (!isInside(options.root, filePath)) throw new Error("Upload path is outside the project root.");
218
+ return {
219
+ filename,
220
+ path: path.relative(options.root, filePath).split(path.sep).join("/"),
221
+ url: publicUrl(options.root, filePath),
222
+ bytes: options.bytes.byteLength
223
+ };
224
+ }
225
+ throw new Error("Unable to allocate a unique upload filename.");
226
+ }
227
+ async function listVideos(root, videosDir) {
228
+ let entries;
229
+ try {
230
+ entries = await readdir(videosDir, { withFileTypes: true });
231
+ } catch {
232
+ return [];
233
+ }
234
+ const videos = [];
235
+ for (const entry of entries) {
236
+ if (!entry.isFile() || entry.name.startsWith(".")) continue;
237
+ if (!Object.values(EXTENSION$1).includes(path.extname(entry.name).toLowerCase())) continue;
238
+ const filePath = resolveInside(videosDir, entry.name);
239
+ if (filePath === null) continue;
240
+ const info = await stat(filePath).catch(() => null);
241
+ videos.push({
242
+ filename: entry.name,
243
+ path: path.relative(root, filePath).split(path.sep).join("/"),
244
+ url: publicUrl(root, filePath),
245
+ ...info ? { bytes: info.size } : {}
246
+ });
247
+ }
248
+ videos.sort((a, b) => a.filename.localeCompare(b.filename));
249
+ return videos;
250
+ }
251
+ /** Delete one uploaded video by file name. False when there is no such file or the name is not a plain video file name. */
252
+ async function deleteVideo(videosDir, filename) {
253
+ if (filename !== path.basename(filename) || filename.startsWith(".")) return false;
254
+ if (!Object.values(EXTENSION$1).includes(path.extname(filename).toLowerCase())) return false;
255
+ const filePath = resolveInside(videosDir, filename);
256
+ if (filePath === null) return false;
257
+ try {
258
+ if (!(await stat(filePath)).isFile()) return false;
259
+ await unlink(filePath);
260
+ return true;
261
+ } catch {
262
+ return false;
263
+ }
264
+ }
265
+ function safeStem$1(originalName) {
266
+ return path.win32.basename(path.basename(originalName)).replace(/\.[^.]+$/, "").normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "video";
267
+ }
268
+ function ascii$1(bytes, from, to) {
269
+ return Buffer.from(bytes.subarray(from, to)).toString("latin1");
270
+ }
271
+ //#endregion
38
272
  //#region src/asset-refs.ts
39
273
  /**
40
274
  * Where an image path may live on disk: under `src/assets` or the uploads directory. The absolute path, or null
@@ -237,7 +471,7 @@ function pageKey(slug) {
237
471
  return `${PAGES_DIR}/${slug}.json`;
238
472
  }
239
473
  /** The content store for a local project: content as JSON files, uploads in a folder. */
240
- function createFileStore({ root, contentDir, uploadsDir }) {
474
+ function createFileStore({ root, contentDir, uploadsDir, videosDir }) {
241
475
  function resolve(key) {
242
476
  const parts = key.split("/");
243
477
  if (key === "" || parts.some((part) => part === "" || part === "." || part === "..")) throw new StoreKeyError(key);
@@ -282,6 +516,17 @@ function createFileStore({ root, contentDir, uploadsDir }) {
282
516
  if (filePath === null) return false;
283
517
  return stat(filePath).then((info) => info.isFile(), () => false);
284
518
  },
519
+ ...videosDir === void 0 ? {} : { videos: {
520
+ list: () => listVideos(root, videosDir),
521
+ save: ({ originalName, bytes, kind }) => saveVideo({
522
+ root,
523
+ videosDir,
524
+ originalName,
525
+ bytes,
526
+ kind
527
+ }),
528
+ remove: (filename) => deleteVideo(videosDir, filename)
529
+ } },
285
530
  uploads: {
286
531
  async list() {
287
532
  return listImages(root, uploadsDir);
@@ -312,20 +557,25 @@ function resolveEditorContext(options, rootInput) {
312
557
  const root = asDirectory(rootInput);
313
558
  const contentDir = resolveDir(root, options?.contentDir, DEFAULT_CONTENT_DIR);
314
559
  const uploadsDir = resolveDir(root, options?.uploadsDir, DEFAULT_UPLOADS_DIR);
560
+ const videosDir = resolveDir(root, options?.videosDir, DEFAULT_VIDEOS_DIR);
315
561
  return {
316
562
  root,
317
563
  contentDir,
318
564
  uploadsDir,
565
+ videosDir,
566
+ maxVideoBytes: options?.maxVideoBytes ?? 52428800,
319
567
  sections: options.sections,
320
568
  site: options.site,
321
569
  theme: options.theme ?? defaultTheme,
322
570
  store: options.store ?? createFileStore({
323
571
  root,
324
572
  contentDir,
325
- uploadsDir
573
+ uploadsDir,
574
+ videosDir
326
575
  }),
327
576
  migrator: createMigrator(options),
328
- git: options?.git === true
577
+ git: options?.git === true,
578
+ formsDir: resolveFormsConfig(options?.forms, root)?.dir ?? null
329
579
  };
330
580
  }
331
581
  //#endregion
@@ -452,7 +702,11 @@ async function git(root, args) {
452
702
  }
453
703
  /** The folders a commit may touch: the content and the uploads. Relative to the project root. */
454
704
  function trackedPaths(context) {
455
- return [context.contentDir, context.uploadsDir].filter((dir) => isInside(context.root, dir)).map((dir) => path.relative(context.root, dir).split(path.sep).join("/") || ".");
705
+ return [
706
+ context.contentDir,
707
+ context.uploadsDir,
708
+ context.videosDir
709
+ ].filter((dir) => isInside(context.root, dir)).map((dir) => path.relative(context.root, dir).split(path.sep).join("/") || ".");
456
710
  }
457
711
  function statusOf(code) {
458
712
  if (code === "??") return "untracked";
@@ -589,6 +843,10 @@ async function handleEditorRequest(request, context, meta = {}) {
589
843
  if (method === "POST") return createPage(request, context);
590
844
  return methodNotAllowed(["GET", "POST"]);
591
845
  }
846
+ if (parts.length === 1 && parts[0] === "forms") {
847
+ if (method === "GET") return getForms(context);
848
+ return methodNotAllowed(["GET"]);
849
+ }
592
850
  if (parts.length === 1 && parts[0] === "git") {
593
851
  if (method === "GET") return getGit(context);
594
852
  return methodNotAllowed(["GET"]);
@@ -606,6 +864,15 @@ async function handleEditorRequest(request, context, meta = {}) {
606
864
  if (method === "DELETE") return removeImage(context, decodeSegment(parts[1] ?? ""));
607
865
  return methodNotAllowed(["DELETE"]);
608
866
  }
867
+ if (parts.length === 1 && parts[0] === "videos") {
868
+ if (method === "GET") return getVideos(context);
869
+ if (method === "POST") return postVideo(request, context);
870
+ return methodNotAllowed(["GET", "POST"]);
871
+ }
872
+ if (parts.length === 2 && parts[0] === "videos") {
873
+ if (method === "DELETE") return removeVideo(context, decodeSegment(parts[1] ?? ""));
874
+ return methodNotAllowed(["DELETE"]);
875
+ }
609
876
  if (parts.length === 1 && parts[0] === "preview") {
610
877
  if (method === "POST") return postPreview(request, context, meta);
611
878
  return methodNotAllowed(["POST"]);
@@ -649,6 +916,27 @@ async function handleEditorRequest(request, context, meta = {}) {
649
916
  }
650
917
  return problem(404, "not_found", "Unknown editor API route.");
651
918
  }
919
+ /**
920
+ * Which form handlers the sections post to, and whether their files exist right now. Read on every call, so a handler
921
+ * created while `astro dev` runs shows up at once.
922
+ */
923
+ async function getForms(context) {
924
+ const handlers = {};
925
+ for (const definition of Object.values(context.sections)) {
926
+ const name = definition.form;
927
+ if (!name || handlers[name]) continue;
928
+ const file = context.formsDir ? formFile(context.formsDir, name) : null;
929
+ handlers[name] = { file: file ? relativeTo(context.root, file) : null };
930
+ }
931
+ return json(200, {
932
+ enabled: context.formsDir != null,
933
+ handlers
934
+ });
935
+ }
936
+ function relativeTo(root, file) {
937
+ const prefix = root.endsWith("/") || root.endsWith("\\") ? root : `${root}/`;
938
+ return file.startsWith(prefix) ? file.slice(prefix.length).replaceAll("\\", "/") : file;
939
+ }
652
940
  async function getSchema(context) {
653
941
  const sectionDefaults = {};
654
942
  const sectionLabels = {};
@@ -661,8 +949,10 @@ async function getSchema(context) {
661
949
  const fieldIcons = {};
662
950
  const showWhen = {};
663
951
  const fieldImages = {};
952
+ const sectionForms = {};
664
953
  for (const definition of Object.values(context.sections)) {
665
954
  const type = definition.type;
955
+ if (definition.form) sectionForms[type] = definition.form;
666
956
  sectionDefaults[type] = definition.defaults;
667
957
  sectionLabels[type] = definition.label;
668
958
  sectionDescriptions[type] = definition.description;
@@ -687,6 +977,7 @@ async function getSchema(context) {
687
977
  fieldIcons,
688
978
  fieldImages,
689
979
  showWhen,
980
+ sectionForms,
690
981
  sectionDefaults,
691
982
  sectionLabels,
692
983
  sectionDescriptions,
@@ -1149,6 +1440,87 @@ async function removeImage(context, filename) {
1149
1440
  filename
1150
1441
  });
1151
1442
  }
1443
+ const NO_VIDEOS = "This content store does not take video uploads.";
1444
+ async function getVideos(context) {
1445
+ if (!context.store.videos) return json(200, {
1446
+ videos: [],
1447
+ maxBytes: context.maxVideoBytes
1448
+ });
1449
+ return json(200, {
1450
+ videos: await context.store.videos.list(),
1451
+ maxBytes: context.maxVideoBytes
1452
+ });
1453
+ }
1454
+ /** Every string in a JSON value. */
1455
+ function* strings(value) {
1456
+ if (typeof value === "string") yield value;
1457
+ else if (Array.isArray(value)) for (const item of value) yield* strings(item);
1458
+ else if (typeof value === "object" && value !== null) for (const item of Object.values(value)) yield* strings(item);
1459
+ }
1460
+ /** Where saved content links the video at `url`, named like the image usages: "Home page › Media". */
1461
+ async function videoUsages(context, url) {
1462
+ const labels = Object.fromEntries(Object.values(context.sections).map((definition) => [definition.type, definition.label]));
1463
+ const usages = [];
1464
+ if ([...strings(await readStoredJson(context, "site.json", "site"))].includes(url)) usages.push("Site settings");
1465
+ for (const name of await context.store.list("pages") ?? []) {
1466
+ if (!name.endsWith(".json") || name.startsWith(".")) continue;
1467
+ const page = await readStoredJson(context, `${PAGES_DIR}/${name}`, "page");
1468
+ if (typeof page !== "object" || page === null) continue;
1469
+ const title = "title" in page && typeof page.title === "string" ? page.title : name.replace(/\.json$/, "");
1470
+ const sections = "sections" in page && Array.isArray(page.sections) ? page.sections : [];
1471
+ for (const section of sections) if ([...strings(section)].includes(url)) usages.push(`${title} › ${labels[section.type ?? ""] ?? section.type ?? "section"}`);
1472
+ }
1473
+ return usages;
1474
+ }
1475
+ async function removeVideo(context, filename) {
1476
+ const videos = context.store.videos;
1477
+ if (!videos) return problem(404, "not_found", NO_VIDEOS);
1478
+ const video = (await videos.list()).find((item) => item.filename === filename);
1479
+ if (!video) return problem(404, "not_found", "No uploaded video has that name.");
1480
+ const usages = await videoUsages(context, video.url);
1481
+ if (usages.length > 0) return json(409, {
1482
+ error: "in_use",
1483
+ message: `${filename} is still used: ${usages.join("; ")}. Choose another video there and save, then delete it.`,
1484
+ usages
1485
+ });
1486
+ if (!await videos.remove(filename)) return problem(404, "not_found", "No uploaded video has that name.");
1487
+ return json(200, {
1488
+ deleted: true,
1489
+ filename
1490
+ });
1491
+ }
1492
+ async function postVideo(request, context) {
1493
+ const videos = context.store.videos;
1494
+ if (!videos) return problem(404, "not_found", NO_VIDEOS);
1495
+ const limitMb = Math.round(context.maxVideoBytes / 1048576);
1496
+ const tooLarge = () => problem(413, "too_large", `Videos must be ${limitMb}MB or smaller. Link a hosted video instead, or compress this one.`);
1497
+ const length = contentLength(request);
1498
+ if (length !== null && length > videoBodyLimit(context.maxVideoBytes)) return tooLarge();
1499
+ if (!(request.headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data")) return problem(415, "unsupported_media_type", "Upload the video as multipart/form-data.");
1500
+ let form;
1501
+ try {
1502
+ form = await request.formData();
1503
+ } catch {
1504
+ return problem(400, "invalid_upload", "The upload body could not be read.");
1505
+ }
1506
+ const entry = form.get("file");
1507
+ if (!(entry instanceof File)) return problem(400, "invalid_upload", "Expected a multipart file field named \"file\".");
1508
+ if (entry.size > context.maxVideoBytes) return tooLarge();
1509
+ const bytes = new Uint8Array(await entry.arrayBuffer());
1510
+ if (bytes.byteLength > context.maxVideoBytes) return tooLarge();
1511
+ const declared = videoKindFromMime(entry.type);
1512
+ const sniffed = sniffVideo(bytes);
1513
+ 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.");
1514
+ try {
1515
+ return json(201, await videos.save({
1516
+ originalName: entry.name,
1517
+ bytes,
1518
+ kind: sniffed
1519
+ }));
1520
+ } catch (error) {
1521
+ return problem(500, "write_failed", error instanceof Error ? error.message : "Upload failed.");
1522
+ }
1523
+ }
1152
1524
  async function postImage(request, context) {
1153
1525
  const length = contentLength(request);
1154
1526
  if (length !== null && length > 5505024) return problem(413, "too_large", "Upload exceeds the 5MB image limit.");
@@ -1450,10 +1822,12 @@ async function dispatch(req, res, context, rawUrl, hooks) {
1450
1822
  const headers = headersFrom(req);
1451
1823
  const method = (req.method ?? "GET").toUpperCase();
1452
1824
  const multipart = (headers.get("content-type") ?? "").toLowerCase().includes("multipart/form-data");
1453
- const limit = multipart ? MULTIPART_BODY_LIMIT : JSON_BODY_LIMIT;
1825
+ const videoUpload = multipart && stripTrailingSlash(rawUrl.split("?")[0] ?? "") === `/__bearminion/api/videos`;
1826
+ const limit = videoUpload ? videoBodyLimit(context.maxVideoBytes) : multipart ? MULTIPART_BODY_LIMIT : JSON_BODY_LIMIT;
1827
+ const tooLargeMessage = videoUpload ? "Upload exceeds the video size limit." : multipart ? "Upload exceeds the 5MB image limit." : "JSON body exceeds 1MB.";
1454
1828
  const advertised = Number(headers.get("content-length") ?? "");
1455
1829
  if (Number.isFinite(advertised) && advertised > limit) {
1456
- await send(res, jsonProblem(413, "too_large", multipart ? "Upload exceeds the 5MB image limit." : "JSON body exceeds 1MB."));
1830
+ await send(res, jsonProblem(413, "too_large", tooLargeMessage));
1457
1831
  return;
1458
1832
  }
1459
1833
  let body;
@@ -1461,7 +1835,7 @@ async function dispatch(req, res, context, rawUrl, hooks) {
1461
1835
  body = await readBody(req, limit);
1462
1836
  } catch (error) {
1463
1837
  if (error instanceof PayloadTooLargeError) {
1464
- await send(res, jsonProblem(413, "too_large", multipart ? "Upload exceeds the 5MB image limit." : "JSON body exceeds 1MB."));
1838
+ await send(res, jsonProblem(413, "too_large", tooLargeMessage));
1465
1839
  return;
1466
1840
  }
1467
1841
  throw error;
@@ -1627,15 +2001,31 @@ function bearminion(options) {
1627
2001
  if (command !== "dev") return;
1628
2002
  const context = resolveEditorContext(options, rootInput(config.root));
1629
2003
  updateConfig({ vite: {
1630
- server: { watch: { ignored: [`${context.uploadsDir.replaceAll("\\", "/")}/**`, `${context.root.replaceAll("\\", "/")}/.editor/**`] } },
2004
+ server: { watch: { ignored: [
2005
+ `${context.uploadsDir.replaceAll("\\", "/")}/**`,
2006
+ `${context.videosDir.replaceAll("\\", "/")}/**`,
2007
+ `${context.root.replaceAll("\\", "/")}/.editor/**`
2008
+ ] } },
1631
2009
  plugins: [contentReloadPlugin([context.contentDir]), editorClientPlugin()]
1632
2010
  } });
1633
2011
  injectScript("page", "import \"virtual:bearminion-editor\"");
1634
2012
  },
1635
- "astro:server:setup"({ server }) {
2013
+ "astro:server:setup"({ server, logger }) {
1636
2014
  const context = resolveEditorContext(options, server.config.root);
1637
2015
  const previewModule = options.previewModule ?? "/src/lib/render-preview.ts";
1638
2016
  const reloads = dropEarlyReloadAfterSave(server);
2017
+ server.middlewares.use(announceVideoChanges(server, context.videosDir));
2018
+ const forms = resolveFormsConfig(options.forms, context.root);
2019
+ if (forms) server.middlewares.use(createFormsMiddleware({
2020
+ ...forms,
2021
+ root: context.root,
2022
+ live: formsAreLive(context.root),
2023
+ load: (file) => loadModule(server.environments.ssr, file),
2024
+ log: {
2025
+ info: (message) => logger.info(message),
2026
+ error: (message) => logger.error(message)
2027
+ }
2028
+ }));
1639
2029
  server.middlewares.use((req, _res, next) => {
1640
2030
  if (req.method === "POST" && (req.url ?? "").split("?")[0]?.replace(/\/$/, "") === `/__bearminion/api/save`) reloads.saving();
1641
2031
  next();
@@ -1648,6 +2038,39 @@ function bearminion(options) {
1648
2038
  }
1649
2039
  };
1650
2040
  }
2041
+ /**
2042
+ * The videos folder is ignored by the file watcher (see above), but Vite learns which files `public/` holds from that
2043
+ * watcher, and answers 404 for any other path. So a video uploaded in the editor would not play in the dev site until
2044
+ * the server restarted. After an upload or delete, tell Vite about exactly the files that appeared or went away.
2045
+ * The event only refreshes Vite's list of public files; it does not reload the page, so the draft stays.
2046
+ */
2047
+ function announceVideoChanges(server, videosDir) {
2048
+ const list = () => {
2049
+ try {
2050
+ return new Set(fs.readdirSync(videosDir));
2051
+ } catch {
2052
+ return /* @__PURE__ */ new Set();
2053
+ }
2054
+ };
2055
+ return (req, res, next) => {
2056
+ const route = (req.url ?? "").split("?")[0]?.replace(/\/$/, "") ?? "";
2057
+ if ((req.method === "POST" || req.method === "DELETE") && (route === `/__bearminion/api/videos` || route.startsWith(`/__bearminion/api/videos/`))) {
2058
+ const before = list();
2059
+ res.once("finish", () => {
2060
+ const after = list();
2061
+ for (const name of after) if (!before.has(name)) server.watcher.emit("add", path.join(videosDir, name));
2062
+ for (const name of before) if (!after.has(name)) server.watcher.emit("unlink", path.join(videosDir, name));
2063
+ });
2064
+ }
2065
+ next();
2066
+ };
2067
+ }
2068
+ /** Loads a module through the dev server's SSR runner, so TypeScript works and an edit is picked up on the next call. */
2069
+ async function loadModule(environment, file) {
2070
+ const runner = environment.runner;
2071
+ if (!runner?.import) throw new Error("The SSR dev environment cannot load a form.");
2072
+ return runner.import(file);
2073
+ }
1651
2074
  async function renderPreview(environment, previewModule, page, motion) {
1652
2075
  const preview = await loadThemePreview(environment, previewModule);
1653
2076
  const sections = typeof page === "object" && page !== null && "sections" in page && Array.isArray(page.sections) ? page.sections : [];
package/dist/content.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { k as ContentModel, t as Page, u as SectionOf } from "./page-B5NoN74Q.js";
1
+ import { k as ContentModel, t as Page, u as SectionOf } from "./page-BfI9cD8g.js";
2
2
  import { z } from "zod";
3
3
  //#region src/content.d.ts
4
4
  export interface ContentCollectionsOptions {