bearminion 1.9.3 → 1.10.1

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,20 @@
1
1
  # bearminion
2
2
 
3
+ ## 1.10.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 23f9084: New sites include an `AGENTS.md` (and a `CLAUDE.md` pointing to it) for AI assistants. It leads with the rules that keep secrets out of the chat and out of git, then walks through the Contact form: write the files with `add form`, run `check form`, and ask the person to confirm each step the assistant cannot see (the variables on the host, a verified domain, a redeploy, a real message).
8
+ - 88fae9e: `check form` now says when a `PUBLIC_` value such as the Turnstile site key sits under `vars` in the Wrangler config: that reaches the running Worker only, so the page has no widget; it has to be a Build variable. The Cloudflare guide adds the Turnstile secret to its settings and says a build variable needs a new build.
9
+ - 62e89bc: `npx bearminion add form <service>` now asks which host the site runs on, in a terminal, when nothing in the project names one (or two hosts do). It offers Vercel, Netlify and Cloudflare, and Enter writes the handler alone, as before. With `--host`, with `--json`, or without a terminal it does not ask.
10
+ - 88fae9e: The Cloudflare Wrangler config that `add form --host cloudflare` writes now uses `"run_worker_first": ["/api/*"]` instead of `true`, so page views are served from the built site without running the Worker, and only `/api/*` reaches the handler. A site that already has `true` keeps working. Tried on a real deploy: pages load, `/api/contact` answers, and a message arrives.
11
+
12
+ ## 1.10.0
13
+
14
+ ### Minor Changes
15
+
16
+ - a10e4a7: New command `npx bearminion check form`. It reads the site's files and environment and names what keeps the Contact form from working: a missing handler or glue file, an import without `.js`, a Netlify function in the wrong folder or without a path, a Wrangler config without `main`, with the placeholder name or without `CONTACT_FROM` and `CONTACT_TO` under `vars`. Each problem comes with its fix. It writes nothing and cannot see the host's own settings. `--host` and `--json` work as for `add form`.
17
+
3
18
  ## 1.9.3
4
19
 
5
20
  ### Patch Changes
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-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-gXystJjG.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-CA4iyFDS.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-4HWVEj9O.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
@@ -2,14 +2,16 @@ import { a as imageFields, c as ContentReadError, l as ContentValidationError, r
2
2
  import { t as defaultTheme } from "./theme-Dv7_7B56.js";
3
3
  import { i as isSystemPage, n as createPageSchema$1, r as createTolerantPageSchema, s as withoutOrphanSections, u as isOrphanSection } from "./page-X-WnOu7-.js";
4
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-Dkp3xC0l.js";
5
+ import { a as isInside, c as resolveDir, i as asDirectory, l as resolveInside, n as JSON_BODY_LIMIT, o as isLocalRequest, r as MULTIPART_BODY_LIMIT, s as readSlug, t as IMAGE_BYTE_LIMIT } from "./security-DOvoYZuQ.js";
6
+ import { a as resolveFormsConfig, n as formFile, r as formsAreLive, t as createFormsMiddleware } from "./forms-dev-CaxRmLhl.js";
6
7
  import { S as isAssetPath, b as describeSiteRef, c as projectId, v as assetRefs, y as describePageRef } from "./draft-store-1Y4-sn45.js";
8
+ import { n as contentReloadPlugin, r as dropEarlyReloadAfterSave } from "./reload-DA07O8cA.js";
7
9
  import { i as syncSections, r as staleSectionsMessage } from "./sections-manifest-CO9QfJPG.js";
8
10
  import { z } from "zod";
9
11
  import fs from "node:fs";
10
12
  import path from "node:path";
11
13
  import { fileURLToPath } from "node:url";
12
- import { parseEnv, promisify } from "node:util";
14
+ import { promisify } from "node:util";
13
15
  import { randomBytes } from "node:crypto";
14
16
  import { access, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
15
17
  import { execFile } from "node:child_process";
@@ -36,134 +38,6 @@ function editorClientPlugin() {
36
38
  };
37
39
  }
38
40
  //#endregion
39
- //#region src/forms-dev.ts
40
- /** Where the forms are and under which path, or `null` when the option turns them off. */
41
- function resolveFormsConfig(option, root) {
42
- if (option === false) return null;
43
- const prefix = (option?.prefix ?? "/api").replace(/\/+$/, "");
44
- return {
45
- dir: resolveDir(root, option?.dir, "src/forms"),
46
- prefix: prefix.startsWith("/") ? prefix : `/${prefix}`
47
- };
48
- }
49
- const FORM_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
50
- const EXTENSIONS = [
51
- ".ts",
52
- ".mts",
53
- ".js",
54
- ".mjs"
55
- ];
56
- const BODY_LIMIT = 1048576;
57
- /** The file behind `name`, or `null` when there is none. `name` is checked, so it cannot leave the folder. */
58
- function formFile(dir, name) {
59
- if (!FORM_FILE.test(name)) return null;
60
- for (const extension of EXTENSIONS) {
61
- const file = path.join(dir, `${name}${extension}`);
62
- if (fs.existsSync(file)) return file;
63
- }
64
- return null;
65
- }
66
- /** `.env`, `.env.local`, `.env.development` and `.env.development.local` of the project, later ones winning. */
67
- function readDotEnv(root) {
68
- const merged = {};
69
- for (const name of [
70
- ".env",
71
- ".env.local",
72
- ".env.development",
73
- ".env.development.local"
74
- ]) try {
75
- Object.assign(merged, parseEnv(fs.readFileSync(path.join(root, name), "utf8")));
76
- } catch {}
77
- return merged;
78
- }
79
- /** True when `BEARMINION_FORMS_LIVE=on` is in the environment or in the project's `.env` files. */
80
- function formsAreLive(root) {
81
- return (process.env.BEARMINION_FORMS_LIVE ?? readDotEnv(root).BEARMINION_FORMS_LIVE) === "on";
82
- }
83
- function isForm(value) {
84
- return typeof value === "object" && value !== null && typeof value.fetch === "function";
85
- }
86
- function createFormsMiddleware(options) {
87
- return (req, res, next) => {
88
- const pathname = (req.url ?? "/").split("?")[0]?.replace(/\/+$/, "") ?? "";
89
- if (!pathname.startsWith(`${options.prefix}/`)) {
90
- next();
91
- return;
92
- }
93
- const name = pathname.slice(options.prefix.length + 1);
94
- const file = formFile(options.dir, name);
95
- if (!file) {
96
- next();
97
- return;
98
- }
99
- answer(req, res, options, name, file).catch((error) => {
100
- options.log.error(`/${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
101
- if (!res.headersSent) fail(res, 500, error instanceof Error ? error.message : "The form failed.");
102
- });
103
- };
104
- }
105
- function fail(res, status, error) {
106
- res.statusCode = status;
107
- res.setHeader("content-type", "application/json; charset=utf-8");
108
- res.end(JSON.stringify({
109
- ok: false,
110
- error
111
- }));
112
- }
113
- async function answer(req, res, options, name, file) {
114
- const form = (await options.load(file))?.default;
115
- if (!isForm(form)) {
116
- const relative = path.relative(options.root, file).split(path.sep).join("/");
117
- options.log.error(`${relative} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
118
- return fail(res, 500, `${relative} must export default defineForm(...).`);
119
- }
120
- const headers = new Headers();
121
- for (const [key, value] of Object.entries(req.headers)) {
122
- if (value === void 0) continue;
123
- for (const item of Array.isArray(value) ? value : [value]) headers.append(key, item);
124
- }
125
- const method = (req.method ?? "GET").toUpperCase();
126
- const body = method === "GET" || method === "HEAD" ? void 0 : await readLimited(req, BODY_LIMIT);
127
- if (body === null) return fail(res, 413, "The message is too large.");
128
- const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
129
- method,
130
- headers,
131
- ...body ? { body } : {}
132
- });
133
- const env = {
134
- ...readDotEnv(options.root),
135
- ...process.env
136
- };
137
- const response = await form.fetch(request, env, {
138
- dev: true,
139
- ...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)}`) }
140
- });
141
- res.statusCode = response.status;
142
- response.headers.forEach((value, key) => {
143
- res.setHeader(key, value);
144
- });
145
- res.end(Buffer.from(await response.arrayBuffer()));
146
- }
147
- /** The body of the request, or `null` once it is over `limit` bytes. */
148
- function readLimited(req, limit) {
149
- return new Promise((resolve, reject) => {
150
- const chunks = [];
151
- let size = 0;
152
- req.on("data", (chunk) => {
153
- const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
154
- size += buffer.length;
155
- if (size > limit) {
156
- resolve(null);
157
- req.resume();
158
- return;
159
- }
160
- chunks.push(buffer);
161
- });
162
- req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
163
- req.on("error", reject);
164
- });
165
- }
166
- //#endregion
167
41
  //#region src/videos.ts
168
42
  const EXTENSION$1 = {
169
43
  mp4: ".mp4",
package/dist/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { i as readDotEnv } from "./forms-dev-CaxRmLhl.js";
2
3
  import { i as syncSections, r as staleSectionsMessage, t as SectionsError } from "./sections-manifest-CO9QfJPG.js";
3
4
  import { i as writeLock, n as readLock, r as recordFiles, t as hashContent } from "./hash-BeBymBO1.js";
4
5
  import fs from "node:fs";
@@ -215,7 +216,7 @@ export default {
215
216
  "wrangler.json",
216
217
  "wrangler.toml"
217
218
  ],
218
- skipNote: "This site already has a Wrangler config, so it was left alone. It needs \"main\": \"./worker.ts\", \"assets\" with \"binding\": \"ASSETS\" and \"run_worker_first\": true, and CONTACT_FROM and CONTACT_TO under \"vars\". See the Forms guide.",
219
+ skipNote: "This site already has a Wrangler config, so it was left alone. It needs \"main\": \"./worker.ts\", \"assets\" with \"binding\": \"ASSETS\" and \"run_worker_first\": [\"/api/*\"], and CONTACT_FROM and CONTACT_TO under \"vars\". See the Forms guide.",
219
220
  source: `// "name" has to be the name of your Worker in Cloudflare.
220
221
  // RESEND_API_KEY is a secret: set it in the Worker's Settings, not here. CONTACT_FROM and CONTACT_TO are plain values and
221
222
  // live under "vars", because a deploy replaces variables that exist only in the dashboard. Fill them in, and keep this
@@ -224,7 +225,7 @@ export default {
224
225
  "name": "my-site",
225
226
  "compatibility_date": "2026-10-27",
226
227
  "main": "./worker.ts",
227
- "assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": true },
228
+ "assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": ["/api/*"] },
228
229
  "observability": { "logs": { "enabled": true, "invocation_logs": true, "persist": true } },
229
230
  "vars": { "CONTACT_FROM": "", "CONTACT_TO": "" }
230
231
  }
@@ -317,6 +318,253 @@ function applyForm(root, plan, version, lock) {
317
318
  };
318
319
  }
319
320
  //#endregion
321
+ //#region src/add/check-form.ts
322
+ const SECRET_NAME = /KEY|SECRET|TOKEN|PASSWORD/;
323
+ const HOSTS_TEXT = GLUE.map((glue) => glue.name).join(", ");
324
+ function read(root, file) {
325
+ try {
326
+ return fs.readFileSync(path.join(root, file), "utf8");
327
+ } catch {
328
+ return;
329
+ }
330
+ }
331
+ /** The first of `candidates` that exists in `dir` (relative to `root`), as a path relative to `root`. */
332
+ function firstExisting(root, dir, base, extensions) {
333
+ return extensions.map((extension) => path.posix.join(dir, `${base}${extension}`)).find((file) => fs.existsSync(path.join(root, file)));
334
+ }
335
+ /** JSON with comments and trailing commas, the way Wrangler reads `wrangler.jsonc`. Undefined when it does not parse. */
336
+ function parseJsonc(text) {
337
+ const clean = scan(scan(text, (source, i) => {
338
+ if (source[i] === "/" && source[i + 1] === "/") {
339
+ const end = source.indexOf("\n", i);
340
+ return {
341
+ text: "",
342
+ resume: end === -1 ? source.length : end
343
+ };
344
+ }
345
+ if (source[i] === "/" && source[i + 1] === "*") {
346
+ const end = source.indexOf("*/", i + 2);
347
+ return {
348
+ text: "",
349
+ resume: end === -1 ? source.length : end + 2
350
+ };
351
+ }
352
+ }), (source, i) => {
353
+ if (source[i] !== ",") return void 0;
354
+ const next = /\S/.exec(source.slice(i + 1));
355
+ const following = next === null ? void 0 : source[i + 1 + next.index];
356
+ return following === "}" || following === "]" ? {
357
+ text: "",
358
+ resume: i + 1
359
+ } : void 0;
360
+ });
361
+ try {
362
+ const value = JSON.parse(clean);
363
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
364
+ } catch {
365
+ return;
366
+ }
367
+ }
368
+ /**
369
+ * Walks `text` outside of string literals. `replace` may answer a replacement and the index to carry on from; strings
370
+ * and everything it leaves alone are copied as they are.
371
+ */
372
+ function scan(text, replace) {
373
+ let out = "";
374
+ let inString = false;
375
+ let i = 0;
376
+ while (i < text.length) {
377
+ const c = text[i];
378
+ if (inString) {
379
+ out += c;
380
+ if (c === "\\") out += text[i + 1] ?? "";
381
+ else if (c === "\"") inString = false;
382
+ i += c === "\\" ? 2 : 1;
383
+ continue;
384
+ }
385
+ if (c === "\"") inString = true;
386
+ const replacement = c === "\"" ? void 0 : replace(text, i);
387
+ out += replacement?.text ?? c;
388
+ i = replacement?.resume ?? i + 1;
389
+ }
390
+ return out;
391
+ }
392
+ /** The environment names a handler reads from `env`. */
393
+ function envNamesOf(source) {
394
+ const names = /* @__PURE__ */ new Set();
395
+ for (const match of source.matchAll(/\benv\.([A-Z][A-Z0-9_]*)/g)) names.add(match[1]);
396
+ for (const match of source.matchAll(/\benv\[\s*['"]([A-Z][A-Z0-9_]*)['"]\s*\]/g)) names.add(match[1]);
397
+ return [...names];
398
+ }
399
+ /** What a glue file imports from `src/forms/contact`, and whether the specifier will resolve as an ES module. */
400
+ function checkImport(add, file, source) {
401
+ const specifier = /from\s+['"]([^'"]*forms\/contact[^'"]*)['"]/.exec(source)?.[1];
402
+ if (specifier === void 0) add("problem", `${file} does not import ${HANDLER_PATH}, so the request never reaches your handler.`, "Run `npx bearminion add form <service> --overwrite` (git keeps your version).");
403
+ else if (specifier.endsWith(".js")) add("ok", `${file} imports the handler with the ".js" an ES module needs.`);
404
+ else if (/\.[cm]?ts$/.test(specifier)) add("note", `${file} imports "${specifier}". The recipe uses ".js" (the file is contact.ts), which every host here ran; this has not been tried.`);
405
+ else add("problem", `${file} imports "${specifier}" without an extension. The host runs it as an ES module, which does not guess extensions (ERR_MODULE_NOT_FOUND).`, `Write "${specifier}.js". The file is contact.ts; the ".js" is what the module resolver needs.`);
406
+ }
407
+ function checkVercel(root, add) {
408
+ const file = firstExisting(root, "api", "contact", [
409
+ ".ts",
410
+ ".mts",
411
+ ".js",
412
+ ".mjs"
413
+ ]);
414
+ if (file === void 0) {
415
+ add("problem", "api/contact.ts is missing, so /api/contact has no function on Vercel.", "npx bearminion add form <service> --host vercel");
416
+ return;
417
+ }
418
+ const source = read(root, file) ?? "";
419
+ add("ok", `${file} exists.`);
420
+ checkImport(add, file, source);
421
+ if (/export\s+(const|function|async function)\s+POST\b|export\s+default\b/.test(source)) add("ok", `${file} exports the function Vercel calls.`);
422
+ else add("problem", `${file} exports neither POST nor a default function, so Vercel has nothing to call.`, "export const POST = (request: Request) => form.fetch(request, process.env)");
423
+ }
424
+ function checkNetlify(root, add) {
425
+ const toml = read(root, "netlify.toml");
426
+ const dir = ((toml === void 0 ? void 0 : /\[functions\][^[]*?\bdirectory\s*=\s*"([^"]+)"/.exec(toml)?.[1]) ?? "netlify/functions").replace(/^\.?\//, "").replace(/\/$/, "");
427
+ const file = firstExisting(root, dir, "contact", [
428
+ ".mts",
429
+ ".ts",
430
+ ".mjs",
431
+ ".js"
432
+ ]);
433
+ if (file === void 0) {
434
+ const elsewhere = readDirs(root, "netlify").filter((other) => other !== dir).map((other) => firstExisting(root, other, "contact", [
435
+ ".mts",
436
+ ".ts",
437
+ ".mjs",
438
+ ".js"
439
+ ])).find((found) => found !== void 0);
440
+ if (elsewhere !== void 0) add("problem", `The function is at ${elsewhere}, but Netlify reads ${dir}/. It is not deployed (the deploy log says "0 new function(s) to upload").`, `Move it to ${dir}/contact${path.extname(elsewhere)}.`);
441
+ else add("problem", `${dir}/contact.mts is missing, so /api/contact has no function on Netlify.`, "npx bearminion add form <service> --host netlify");
442
+ return;
443
+ }
444
+ const source = read(root, file) ?? "";
445
+ add("ok", `${file} exists in the folder Netlify reads.`);
446
+ checkImport(add, file, source);
447
+ if (/export\s+default\b/.test(source)) add("ok", `${file} has the default export Netlify calls.`);
448
+ else add("problem", `${file} has no default export, so Netlify has nothing to call.`, "export default (request: Request) => form.fetch(request, process.env)");
449
+ if (/\bpath\s*:\s*['"]\/api\/contact['"]/.test(source)) add("ok", `${file} answers at /api/contact.`);
450
+ else add("problem", `${file} does not set path "/api/contact". Netlify then serves it at /.netlify/functions/contact, and the form posts to /api/contact (404).`, "export const config = { path: '/api/contact' }");
451
+ }
452
+ function readDirs(root, dir) {
453
+ try {
454
+ return fs.readdirSync(path.join(root, dir), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path.posix.join(dir, entry.name));
455
+ } catch {
456
+ return [];
457
+ }
458
+ }
459
+ function checkCloudflare(root, add, plainNames, secretNames) {
460
+ const configFile = [
461
+ "wrangler.jsonc",
462
+ "wrangler.json",
463
+ "wrangler.toml"
464
+ ].find((name) => fs.existsSync(path.join(root, name)));
465
+ if (configFile === void 0) {
466
+ add("problem", "There is no wrangler.jsonc, so there is nothing to deploy as a Worker.", "npx bearminion add form <service> --host cloudflare");
467
+ return;
468
+ }
469
+ const text = read(root, configFile) ?? "";
470
+ let main;
471
+ let name;
472
+ let binding;
473
+ let vars = {};
474
+ let logs;
475
+ if (configFile.endsWith(".toml")) {
476
+ main = /^\s*main\s*=\s*"([^"]+)"/m.exec(text)?.[1];
477
+ name = /^\s*name\s*=\s*"([^"]+)"/m.exec(text)?.[1];
478
+ binding = /^\s*binding\s*=\s*"([^"]+)"/m.exec(text)?.[1];
479
+ vars = Object.fromEntries(plainNames.map((variable) => [variable, new RegExp(`^\\s*${variable}\\s*=\\s*"([^"]*)"`, "m").exec(text)?.[1]]).filter(([, value]) => value !== void 0));
480
+ logs = /^\s*\[observability\]/m.test(text) ? /^\s*enabled\s*=\s*true/m.test(text) : void 0;
481
+ } else {
482
+ const config = parseJsonc(text);
483
+ if (config === void 0) {
484
+ add("problem", `${configFile} does not parse as JSON with comments, so I cannot read it.`);
485
+ return;
486
+ }
487
+ main = typeof config.main === "string" ? config.main : void 0;
488
+ name = typeof config.name === "string" ? config.name : void 0;
489
+ const assets = config.assets;
490
+ binding = typeof assets?.binding === "string" ? assets.binding : void 0;
491
+ vars = config.vars ?? {};
492
+ const observability = config.observability;
493
+ logs = observability === void 0 ? void 0 : observability.enabled === true || observability.logs?.enabled === true;
494
+ }
495
+ add("ok", `${configFile} exists.`);
496
+ if (name === "my-site") add("problem", `${configFile} still has the placeholder name "my-site". The deploy would create a Worker with that name.`, "Set \"name\" to the name of your Worker in Cloudflare.");
497
+ if (main === void 0) add("problem", `${configFile} has no "main", so no Worker runs and /api/contact is a 404.`, "Set \"main\": \"./worker.ts\".");
498
+ else if (!fs.existsSync(path.join(root, main))) add("problem", `"main" is ${main}, which does not exist.`, "Point \"main\" at your Worker file, or run `npx bearminion add form <service> --host cloudflare`.");
499
+ else {
500
+ const source = read(root, main) ?? "";
501
+ add("ok", `${main} is the Worker.`);
502
+ checkImport(add, main, source);
503
+ if (source.includes("/api/contact")) add("ok", `${main} routes /api/contact.`);
504
+ else add("problem", `${main} does not mention /api/contact, so the form's request goes to the static files.`);
505
+ if (/\benv\.ASSETS\b/.test(source) && binding !== "ASSETS") add("problem", `${main} serves the site through env.ASSETS, but ${configFile} has no assets binding named "ASSETS".`, "Add \"binding\": \"ASSETS\" to \"assets\".");
506
+ }
507
+ for (const variable of plainNames) {
508
+ const value = vars[variable];
509
+ if (typeof value === "string" && value.trim() !== "") add("ok", `${variable} is set under "vars".`);
510
+ else add("problem", `${variable} is not set under "vars" in ${configFile}. A variable that exists only in the dashboard is replaced on the next deploy.`, `Put ${variable} under "vars" (plain values, so keep the repository private if they should not be public).`);
511
+ }
512
+ const publicNames = configFile.endsWith(".toml") ? [...text.matchAll(/^\s*(PUBLIC_[A-Z0-9_]+)\s*=/gm)].map((match) => match[1]) : Object.keys(vars).filter((variable) => variable.startsWith("PUBLIC_"));
513
+ if (publicNames.length > 0) {
514
+ const one = publicNames.length === 1;
515
+ add("note", `${publicNames.join(", ")} ${one ? "is" : "are"} in ${configFile}. Those reach the running Worker only; Astro reads PUBLIC_ values when the site is built, so set ${one ? "it" : "them"} as Build variables in the dashboard (then push or retry the build). Under "vars" the page has no Turnstile widget.`);
516
+ }
517
+ if (secretNames.length > 0) {
518
+ const many = secretNames.length > 1;
519
+ add("note", `Set ${secretNames.join(", ")} as ${many ? "Secrets" : "a Secret"} in the Worker's Settings. I cannot read ${many ? "them" : "it"} from here.`);
520
+ }
521
+ if (logs !== true) add("note", "Logs are not turned on in the Wrangler config (\"observability\"), so a failing handler leaves no trace in the dashboard.");
522
+ }
523
+ /**
524
+ * Looks at the files and environment that make the Contact form work and says what is missing. It reads the project and
525
+ * writes nothing; the host's own settings (Vercel and Netlify environment variables, Cloudflare secrets) are out of
526
+ * reach, and the result says so.
527
+ */
528
+ function checkForm(root, requestedHost) {
529
+ const findings = [];
530
+ const add = (level, message, fix) => findings.push({
531
+ level,
532
+ message,
533
+ ...fix === void 0 ? {} : { fix }
534
+ });
535
+ const host = requestedHost ?? detectHost(root);
536
+ const known = GLUE.some((glue) => glue.name === host);
537
+ const handler = read(root, HANDLER_PATH);
538
+ let names = [];
539
+ if (handler === void 0) add("problem", `${HANDLER_PATH} is missing. The Contact form posts to /api/contact and nothing answers.`, "npx bearminion add form resend --host <host>");
540
+ else if (/\bdefineForm\b/.test(handler) && /export\s+default\b/.test(handler)) {
541
+ add("ok", `${HANDLER_PATH} exports a defineForm handler.`);
542
+ names = envNamesOf(handler);
543
+ } else {
544
+ add("problem", `${HANDLER_PATH} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
545
+ names = envNamesOf(handler);
546
+ }
547
+ const plainNames = names.filter((variable) => !SECRET_NAME.test(variable));
548
+ const secretNames = names.filter((variable) => SECRET_NAME.test(variable));
549
+ if (host === void 0) add("note", `I cannot tell where this site runs. Name the host to check its glue: --host ${GLUE.map((glue) => glue.name).join(" | ")}.`);
550
+ else if (host === "astro") add("note", "This site has an Astro adapter, so the endpoint is an Astro route. I only check the glue for the hosts the command writes.");
551
+ else if (!known) add("problem", `There is no host called "${host}". The hosts are: ${HOSTS_TEXT}.`);
552
+ else if (host === "vercel") checkVercel(root, add);
553
+ else if (host === "netlify") checkNetlify(root, add);
554
+ else if (host === "cloudflare") checkCloudflare(root, add, plainNames, secretNames);
555
+ if (host === "vercel" || host === "netlify") {
556
+ if (names.length > 0) add("note", `Set ${names.join(", ")} in ${host === "vercel" ? "the project's Environment Variables" : "the site's Environment variables"} (Production and Preview). I cannot read them from here.`);
557
+ }
558
+ const dotEnv = { ...readDotEnv(root) };
559
+ const missingLocally = names.filter((variable) => dotEnv[variable] === void 0 && process.env[variable] === void 0);
560
+ if (missingLocally.length > 0) add("note", `Not in .env: ${missingLocally.join(", ")}. \`astro dev\` with BEARMINION_FORMS_LIVE=on needs them; without it the form is a dry run.`);
561
+ if ((dotEnv.PUBLIC_TURNSTILE_SITE_KEY ?? process.env.PUBLIC_TURNSTILE_SITE_KEY) !== void 0 && dotEnv.TURNSTILE_SECRET_KEY === void 0 && process.env.TURNSTILE_SECRET_KEY === void 0) add("note", "PUBLIC_TURNSTILE_SITE_KEY shows the widget. The server checks the token only where TURNSTILE_SECRET_KEY is set, so set it on the host too.");
562
+ return {
563
+ host,
564
+ findings
565
+ };
566
+ }
567
+ //#endregion
320
568
  //#region src/add/status.ts
321
569
  /** Decides the state of one file from its hash in the site, in the release, and in the lock. */
322
570
  function classify(siteHash, release, lockHash) {
@@ -381,11 +629,13 @@ Usage
381
629
  npx bearminion add --list
382
630
  npx bearminion add form [<service>] [--host <host>]
383
631
  npx bearminion status [--json]
632
+ npx bearminion check form [--host <host>] [--json]
384
633
  npx bearminion sync [options]
385
634
 
386
635
  Commands
387
636
  add Copy sections into this site, with the files they need
388
637
  status Show which sections are in this site and whether their files match this release
638
+ check form Look for what keeps the Contact form from working: missing files, wrong names, unset variables
389
639
  sync Rewrite sections/definitions.gen.ts and components.gen.ts from the section directories
390
640
 
391
641
  Options for add
@@ -401,6 +651,10 @@ Options for add form
401
651
  --host <host> Where the site runs (found from the project when omitted). See --list
402
652
  --list List the services and hosts
403
653
 
654
+ Options for check form
655
+ --host <host> Where the site runs (found from the project when omitted)
656
+ --json Print one JSON document instead of text
657
+
404
658
  Options for sync
405
659
  --check Write nothing; exit 1 when the generated files are stale
406
660
  --sections <dir> The sections folder (default: ${DEFAULT_SECTIONS_DIR})
@@ -434,6 +688,7 @@ async function run(argv, io = {}) {
434
688
  const root = path.resolve(values.cwd ?? process.cwd());
435
689
  if (command === "sync" && rest.length === 0) return runSync(root, values, log);
436
690
  if (command === "add") return runAdd(root, rest, values, surroundings);
691
+ if (command === "check" && rest[0] === "form" && rest.length === 1) return runCheckForm(root, values, surroundings);
437
692
  if (command === "status" && rest.length === 0) return runStatus(root, values, surroundings);
438
693
  log(`I do not know "${positionals.join(" ")}". Run \`npx bearminion --help\` for the commands.`);
439
694
  return 2;
@@ -684,6 +939,32 @@ async function runAdd(root, names, values, io) {
684
939
  }
685
940
  return installed === "failed" ? 1 : 0;
686
941
  }
942
+ const LEVEL_TEXT = {
943
+ ok: "ok",
944
+ problem: "problem",
945
+ note: "note"
946
+ };
947
+ function runCheckForm(root, values, io) {
948
+ const { host, findings } = checkForm(root, values.host);
949
+ const problems = findings.filter((finding) => finding.level === "problem").length;
950
+ if (values.json) {
951
+ io.log(JSON.stringify({
952
+ ok: problems === 0,
953
+ host: host ?? null,
954
+ findings
955
+ }, null, 2));
956
+ return problems === 0 ? 0 : 1;
957
+ }
958
+ io.log(`Checking the Contact form${host === void 0 ? "" : ` (host: ${host})`}`);
959
+ io.log("");
960
+ for (const finding of findings) {
961
+ io.log(` ${LEVEL_TEXT[finding.level].padEnd(8)} ${finding.message}`);
962
+ if (finding.fix !== void 0) io.log(` ${"".padEnd(8)} fix: ${finding.fix}`);
963
+ }
964
+ io.log("");
965
+ io.log(problems === 0 ? "No problems found in the files. The host's own settings and a real message are still yours to check." : `${problems} problem${problems === 1 ? "" : "s"} found.`);
966
+ return problems === 0 ? 0 : 1;
967
+ }
687
968
  const STATE_TEXT = {
688
969
  current: "current",
689
970
  outdated: "outdated (you did not change it; `add` replaces it)",
@@ -777,7 +1058,18 @@ async function runAddForm(root, names, values, io) {
777
1058
  const handler = names[0] === void 0 ? void 0 : HANDLERS.find((candidate) => candidate.name === names[0]);
778
1059
  if (names[0] !== void 0 && handler === void 0) return fail(`There is no form service called "${names[0]}". The services are: ${HANDLERS.map((candidate) => candidate.name).join(", ")}.`);
779
1060
  const detected = values.host === void 0 ? detectHost(root) : void 0;
780
- const hostName = values.host ?? detected;
1061
+ let chosen;
1062
+ if (values.host === void 0 && detected === void 0 && handler !== void 0 && !json && io.choose !== void 0) {
1063
+ chosen = await io.choose("Where does this site run? The project does not say.", [...GLUE.map((candidate) => ({
1064
+ value: candidate.name,
1065
+ label: candidate.description
1066
+ })), {
1067
+ value: "",
1068
+ label: "Somewhere else: write the handler only"
1069
+ }]);
1070
+ if (chosen === "") chosen = void 0;
1071
+ }
1072
+ const hostName = values.host ?? detected ?? chosen;
781
1073
  const glue = hostName === void 0 ? void 0 : GLUE.find((candidate) => candidate.name === hostName);
782
1074
  if (values.host !== void 0 && glue === void 0) return fail(`There is no host called "${hostName}". The hosts are: ${GLUE.map((candidate) => candidate.name).join(", ")}.`);
783
1075
  if (handler === void 0 && glue === void 0) return fail("Name a service, a host, or both. For example: npx bearminion add form resend --host vercel. Use --list to see them.", 2);
@@ -805,7 +1097,7 @@ async function runAddForm(root, names, values, io) {
805
1097
  ...extra
806
1098
  }, null, 2);
807
1099
  if (!json) {
808
- log(`${values["dry-run"] ? "Would add" : "Adding"} the form recipe${glue ? ` for ${glue.name}${detected ? " (found from the project)" : ""}` : ""}${handler ? ` with ${handler.name}` : ""}`);
1100
+ log(`${values["dry-run"] ? "Would add" : "Adding"} the form recipe${glue ? ` for ${glue.name}${detected ? " (found from the project)" : chosen ? " (your choice)" : ""}` : ""}${handler ? ` with ${handler.name}` : ""}`);
809
1101
  log("");
810
1102
  for (const file of changes) log(` ${LABELS[file.action].padEnd(9)} ${file.path}`);
811
1103
  const same = plan.files.length - changes.length;
@@ -883,8 +1175,26 @@ async function confirm(question) {
883
1175
  rl.close();
884
1176
  }
885
1177
  }
1178
+ /** A numbered list; Enter, or a number that is not on the list, picks nothing. */
1179
+ async function choose(question, options) {
1180
+ const rl = createInterface({
1181
+ input: process.stdin,
1182
+ output: process.stdout
1183
+ });
1184
+ try {
1185
+ console.log(question);
1186
+ for (const [index, option] of options.entries()) console.log(` ${index + 1}. ${option.label}`);
1187
+ const answer = Number((await rl.question("Number: ")).trim());
1188
+ return Number.isInteger(answer) ? options[answer - 1]?.value : void 0;
1189
+ } finally {
1190
+ rl.close();
1191
+ }
1192
+ }
886
1193
  process.exitCode = await run(process.argv.slice(2), {
887
1194
  registryDir,
888
- ...process.stdin.isTTY ? { confirm } : {}
1195
+ ...process.stdin.isTTY ? {
1196
+ confirm,
1197
+ choose
1198
+ } : {}
889
1199
  });
890
1200
  //#endregion
package/dist/content.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { k as ContentModel, t as Page, u as SectionOf } from "./page-BfI9cD8g.js";
1
+ import { k as ContentModel, t as Page, u as SectionOf } from "./page-CA4iyFDS.js";
2
2
  import { z } from "zod";
3
3
  //#region src/content.d.ts
4
4
  export interface ContentCollectionsOptions {
package/dist/content.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as createPageSchema, r as createTolerantPageSchema } from "./page-X-WnOu7-.js";
2
2
  import { n as createMigrator } from "./migrate-b408EaLp.js";
3
- import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-Dkp3xC0l.js";
3
+ import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-DA07O8cA.js";
4
4
  import { z } from "zod";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
@@ -0,0 +1,133 @@
1
+ import { c as resolveDir } from "./security-DOvoYZuQ.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { parseEnv } from "node:util";
5
+ //#region src/forms-dev.ts
6
+ /** Where the forms are and under which path, or `null` when the option turns them off. */
7
+ function resolveFormsConfig(option, root) {
8
+ if (option === false) return null;
9
+ const prefix = (option?.prefix ?? "/api").replace(/\/+$/, "");
10
+ return {
11
+ dir: resolveDir(root, option?.dir, "src/forms"),
12
+ prefix: prefix.startsWith("/") ? prefix : `/${prefix}`
13
+ };
14
+ }
15
+ const FORM_FILE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
16
+ const EXTENSIONS = [
17
+ ".ts",
18
+ ".mts",
19
+ ".js",
20
+ ".mjs"
21
+ ];
22
+ const BODY_LIMIT = 1048576;
23
+ /** The file behind `name`, or `null` when there is none. `name` is checked, so it cannot leave the folder. */
24
+ function formFile(dir, name) {
25
+ if (!FORM_FILE.test(name)) return null;
26
+ for (const extension of EXTENSIONS) {
27
+ const file = path.join(dir, `${name}${extension}`);
28
+ if (fs.existsSync(file)) return file;
29
+ }
30
+ return null;
31
+ }
32
+ /** `.env`, `.env.local`, `.env.development` and `.env.development.local` of the project, later ones winning. */
33
+ function readDotEnv(root) {
34
+ const merged = {};
35
+ for (const name of [
36
+ ".env",
37
+ ".env.local",
38
+ ".env.development",
39
+ ".env.development.local"
40
+ ]) try {
41
+ Object.assign(merged, parseEnv(fs.readFileSync(path.join(root, name), "utf8")));
42
+ } catch {}
43
+ return merged;
44
+ }
45
+ /** True when `BEARMINION_FORMS_LIVE=on` is in the environment or in the project's `.env` files. */
46
+ function formsAreLive(root) {
47
+ return (process.env.BEARMINION_FORMS_LIVE ?? readDotEnv(root).BEARMINION_FORMS_LIVE) === "on";
48
+ }
49
+ function isForm(value) {
50
+ return typeof value === "object" && value !== null && typeof value.fetch === "function";
51
+ }
52
+ function createFormsMiddleware(options) {
53
+ return (req, res, next) => {
54
+ const pathname = (req.url ?? "/").split("?")[0]?.replace(/\/+$/, "") ?? "";
55
+ if (!pathname.startsWith(`${options.prefix}/`)) {
56
+ next();
57
+ return;
58
+ }
59
+ const name = pathname.slice(options.prefix.length + 1);
60
+ const file = formFile(options.dir, name);
61
+ if (!file) {
62
+ next();
63
+ return;
64
+ }
65
+ answer(req, res, options, name, file).catch((error) => {
66
+ options.log.error(`/${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
67
+ if (!res.headersSent) fail(res, 500, error instanceof Error ? error.message : "The form failed.");
68
+ });
69
+ };
70
+ }
71
+ function fail(res, status, error) {
72
+ res.statusCode = status;
73
+ res.setHeader("content-type", "application/json; charset=utf-8");
74
+ res.end(JSON.stringify({
75
+ ok: false,
76
+ error
77
+ }));
78
+ }
79
+ async function answer(req, res, options, name, file) {
80
+ const form = (await options.load(file))?.default;
81
+ if (!isForm(form)) {
82
+ const relative = path.relative(options.root, file).split(path.sep).join("/");
83
+ options.log.error(`${relative} must \`export default defineForm(...)\` from 'bearminion/forms'.`);
84
+ return fail(res, 500, `${relative} must export default defineForm(...).`);
85
+ }
86
+ const headers = new Headers();
87
+ for (const [key, value] of Object.entries(req.headers)) {
88
+ if (value === void 0) continue;
89
+ for (const item of Array.isArray(value) ? value : [value]) headers.append(key, item);
90
+ }
91
+ const method = (req.method ?? "GET").toUpperCase();
92
+ const body = method === "GET" || method === "HEAD" ? void 0 : await readLimited(req, BODY_LIMIT);
93
+ if (body === null) return fail(res, 413, "The message is too large.");
94
+ const request = new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
95
+ method,
96
+ headers,
97
+ ...body ? { body } : {}
98
+ });
99
+ const env = {
100
+ ...readDotEnv(options.root),
101
+ ...process.env
102
+ };
103
+ const response = await form.fetch(request, env, {
104
+ dev: true,
105
+ ...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)}`) }
106
+ });
107
+ res.statusCode = response.status;
108
+ response.headers.forEach((value, key) => {
109
+ res.setHeader(key, value);
110
+ });
111
+ res.end(Buffer.from(await response.arrayBuffer()));
112
+ }
113
+ /** The body of the request, or `null` once it is over `limit` bytes. */
114
+ function readLimited(req, limit) {
115
+ return new Promise((resolve, reject) => {
116
+ const chunks = [];
117
+ let size = 0;
118
+ req.on("data", (chunk) => {
119
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
120
+ size += buffer.length;
121
+ if (size > limit) {
122
+ resolve(null);
123
+ req.resume();
124
+ return;
125
+ }
126
+ chunks.push(buffer);
127
+ });
128
+ req.on("end", () => resolve(new Uint8Array(Buffer.concat(chunks))));
129
+ req.on("error", reject);
130
+ });
131
+ }
132
+ //#endregion
133
+ export { resolveFormsConfig as a, readDotEnv as i, formFile as n, formsAreLive as r, createFormsMiddleware as t };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as brandLogoSchema, $t as createMigrator, A as SectionRegistry, At as wireframeIssues, B as FooterColumn, Bt as themeModes, C as jsonLdWarnings, Ct as SectionDefinition, D as upsertJsonLd, Dt as Wireframe, E as siteJsonLdIds, Et as WireRect, F as defineTheme, Ft as NumberOption, G as SiteAnalytics, Gt as FieldIcons, H as Header, Ht as tones, I as BRAND_LOGO_HEIGHT, It as Option, J as SiteDefinition, Jt as ContentMigration, K as SiteConfig, Kt as ShowCondition, L as DEFAULT_MAX_FOOTER_COLUMNS, Lt as StringOption, M as ThemeDefinition, Mt as BooleanOption, N as ThemeFont, Nt as CountRule, O as API_PREFIX, Ot as defineWireframe, P as defaultTheme, Pt as EnumOption, Q as Theme, Qt as SCHEMA_VERSION_KEY, R as DEFAULT_MAX_HEADER_ACTIONS, Rt as buttonStyles, S as jsonLdSchema, St as SectionConfig, T as parseJsonLdInput, Tt as WireKind, U as HeaderConfig, Ut as variantOption, V as FooterConfig, Vt as toneOption, W as Site, Wt as FieldChoices, X as SiteSeo, Xt as ContentVersioning, Y as SiteOf, Yt as ContentMigrator, Z as SiteWith, Zt as DocumentKind, _ as SiteJsonLdSource, _t as textMarkSchema, a as isSystemPage, at as themeSchema, b as hasJsonLdId, bt as trackingIdSchema, c as BaseSection, ct as Link, d as anchorSchema, dt as Text, et as defineSite, f as createSectionSchema, ft as Tone, g as SiteJsonLdIds, gt as richTextSchema, h as JsonLdResult, ht as linkSchema, i as createPageSchema, it as themeColorsSchema, j as ThemeConfig, jt as OptionalContent, k as ContentModel, kt as wireKinds, l as PropsOf, lt as MAX_NAV_DEPTH, m as JsonLdBlock, mt as imageSchema, n as SYSTEM_PAGES, nt as siteConsentSchema, o as seoSchema, ot as ButtonStyle, p as sectionIdSchema, pt as htmlIdSchema, q as SiteConsent, qt as ShowWhen, r as Seo, rt as siteSeoSchema, s as withoutOrphanSections, st as Image, t as Page, tt as siteAnalyticsSchema, u as SectionOf, ut as RichText, v as formatJsonLd, vt as textSchema, w as mergeJsonLd, wt as defineSection, x as isPlaceholderSiteUrl, xt as withEmphasis, y as generateSiteJsonLd, yt as toneSchema, z as Footer, zt as motionOption } from "./page-BfI9cD8g.js";
1
+ import { $ as brandLogoSchema, $t as createMigrator, A as SectionRegistry, At as wireframeIssues, B as FooterColumn, Bt as themeModes, C as jsonLdWarnings, Ct as SectionDefinition, D as upsertJsonLd, Dt as Wireframe, E as siteJsonLdIds, Et as WireRect, F as defineTheme, Ft as NumberOption, G as SiteAnalytics, Gt as FieldIcons, H as Header, Ht as tones, I as BRAND_LOGO_HEIGHT, It as Option, J as SiteDefinition, Jt as ContentMigration, K as SiteConfig, Kt as ShowCondition, L as DEFAULT_MAX_FOOTER_COLUMNS, Lt as StringOption, M as ThemeDefinition, Mt as BooleanOption, N as ThemeFont, Nt as CountRule, O as API_PREFIX, Ot as defineWireframe, P as defaultTheme, Pt as EnumOption, Q as Theme, Qt as SCHEMA_VERSION_KEY, R as DEFAULT_MAX_HEADER_ACTIONS, Rt as buttonStyles, S as jsonLdSchema, St as SectionConfig, T as parseJsonLdInput, Tt as WireKind, U as HeaderConfig, Ut as variantOption, V as FooterConfig, Vt as toneOption, W as Site, Wt as FieldChoices, X as SiteSeo, Xt as ContentVersioning, Y as SiteOf, Yt as ContentMigrator, Z as SiteWith, Zt as DocumentKind, _ as SiteJsonLdSource, _t as textMarkSchema, a as isSystemPage, at as themeSchema, b as hasJsonLdId, bt as trackingIdSchema, c as BaseSection, ct as Link, d as anchorSchema, dt as Text, et as defineSite, f as createSectionSchema, ft as Tone, g as SiteJsonLdIds, gt as richTextSchema, h as JsonLdResult, ht as linkSchema, i as createPageSchema, it as themeColorsSchema, j as ThemeConfig, jt as OptionalContent, k as ContentModel, kt as wireKinds, l as PropsOf, lt as MAX_NAV_DEPTH, m as JsonLdBlock, mt as imageSchema, n as SYSTEM_PAGES, nt as siteConsentSchema, o as seoSchema, ot as ButtonStyle, p as sectionIdSchema, pt as htmlIdSchema, q as SiteConsent, qt as ShowWhen, r as Seo, rt as siteSeoSchema, s as withoutOrphanSections, st as Image, t as Page, tt as siteAnalyticsSchema, u as SectionOf, ut as RichText, v as formatJsonLd, vt as textSchema, w as mergeJsonLd, wt as defineSection, x as isPlaceholderSiteUrl, xt as withEmphasis, y as generateSiteJsonLd, yt as toneSchema, z as Footer, zt as motionOption } from "./page-CA4iyFDS.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
- import "./options-gXystJjG.js";
3
+ import "./options-4HWVEj9O.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";
5
5
  //#region src/errors.d.ts
6
6
  /** One schema problem, addressed by a dot path such as `sections.0.props.heading`. */
@@ -1,4 +1,4 @@
1
- import { A as SectionRegistry, J as SiteDefinition, M as ThemeDefinition, Yt as ContentMigrator, k as ContentModel } from "./page-BfI9cD8g.js";
1
+ import { A as SectionRegistry, J as SiteDefinition, M as ThemeDefinition, Yt as ContentMigrator, k as ContentModel } from "./page-CA4iyFDS.js";
2
2
  //#region src/images.d.ts
3
3
  type ImageKind = 'png' | 'jpeg' | 'webp' | 'gif' | 'avif';
4
4
  interface SavedImage {
@@ -275,10 +275,10 @@ declare const textMarkSchema: z.ZodObject<{
275
275
  start: z.ZodNumber;
276
276
  end: z.ZodNumber;
277
277
  weight: z.ZodOptional<z.ZodEnum<{
278
+ bold: "bold";
278
279
  regular: "regular";
279
280
  medium: "medium";
280
281
  semibold: "semibold";
281
- bold: "bold";
282
282
  }>>;
283
283
  italic: z.ZodOptional<z.ZodBoolean>;
284
284
  font: z.ZodOptional<z.ZodEnum<{
@@ -319,10 +319,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
319
319
  start: z.ZodNumber;
320
320
  end: z.ZodNumber;
321
321
  weight: z.ZodOptional<z.ZodEnum<{
322
+ bold: "bold";
322
323
  regular: "regular";
323
324
  medium: "medium";
324
325
  semibold: "semibold";
325
- bold: "bold";
326
326
  }>>;
327
327
  italic: z.ZodOptional<z.ZodBoolean>;
328
328
  font: z.ZodOptional<z.ZodEnum<{
@@ -337,10 +337,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
337
337
  start: z.ZodNumber;
338
338
  end: z.ZodNumber;
339
339
  weight: z.ZodOptional<z.ZodEnum<{
340
+ bold: "bold";
340
341
  regular: "regular";
341
342
  medium: "medium";
342
343
  semibold: "semibold";
343
- bold: "bold";
344
344
  }>>;
345
345
  italic: z.ZodOptional<z.ZodBoolean>;
346
346
  font: z.ZodOptional<z.ZodEnum<{
@@ -357,10 +357,10 @@ declare function withEmphasis<T extends z.ZodRawShape>(shape: T): z.ZodPipe<z.Zo
357
357
  start: z.ZodNumber;
358
358
  end: z.ZodNumber;
359
359
  weight: z.ZodOptional<z.ZodEnum<{
360
+ bold: "bold";
360
361
  regular: "regular";
361
362
  medium: "medium";
362
363
  semibold: "semibold";
363
- bold: "bold";
364
364
  }>>;
365
365
  italic: z.ZodOptional<z.ZodBoolean>;
366
366
  font: z.ZodOptional<z.ZodEnum<{
@@ -617,10 +617,10 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
617
617
  start: z.ZodNumber;
618
618
  end: z.ZodNumber;
619
619
  weight: z.ZodOptional<z.ZodEnum<{
620
+ bold: "bold";
620
621
  regular: "regular";
621
622
  medium: "medium";
622
623
  semibold: "semibold";
623
- bold: "bold";
624
624
  }>>;
625
625
  italic: z.ZodOptional<z.ZodBoolean>;
626
626
  font: z.ZodOptional<z.ZodEnum<{
@@ -852,7 +852,7 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
852
852
  nameMarks: {
853
853
  start: number;
854
854
  end: number;
855
- weight?: "regular" | "medium" | "semibold" | "bold" | undefined;
855
+ weight?: "bold" | "regular" | "medium" | "semibold" | undefined;
856
856
  italic?: boolean | undefined;
857
857
  font?: "sans" | "serif" | "mono" | undefined;
858
858
  }[] | undefined;
@@ -1110,7 +1110,7 @@ declare function createSiteSchema(header: HeaderParts, footer: FooterParts): z.Z
1110
1110
  nameMarks?: {
1111
1111
  start: number;
1112
1112
  end: number;
1113
- weight?: "regular" | "medium" | "semibold" | "bold" | undefined;
1113
+ weight?: "bold" | "regular" | "medium" | "semibold" | undefined;
1114
1114
  italic?: boolean | undefined;
1115
1115
  font?: "sans" | "serif" | "mono" | undefined;
1116
1116
  }[] | undefined;
@@ -1,95 +1,5 @@
1
- import { o as slugSchema } from "./page-X-WnOu7-.js";
1
+ import { a as isInside } from "./security-DOvoYZuQ.js";
2
2
  import path from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- //#region src/security.ts
5
- const JSON_BODY_LIMIT = 1048576;
6
- const IMAGE_BYTE_LIMIT = 5242880;
7
- /** Room for multipart boundaries around a max-size image. */
8
- const MULTIPART_BODY_LIMIT = 5505024;
9
- const LOCAL_HOSTS = /* @__PURE__ */ new Set([
10
- "localhost",
11
- "127.0.0.1",
12
- "::1"
13
- ]);
14
- function asDirectory(root) {
15
- if (root instanceof URL) return fileURLToPath(root);
16
- if (root.startsWith("file:")) return fileURLToPath(root);
17
- return path.resolve(root);
18
- }
19
- function resolveDir(root, value, fallback) {
20
- const chosen = value ?? fallback;
21
- return path.isAbsolute(chosen) ? path.resolve(chosen) : path.resolve(root, chosen);
22
- }
23
- /** True when `candidate` is `root` or a path inside it. */
24
- function isInside(root, candidate) {
25
- const relative = path.relative(path.resolve(root), path.resolve(candidate));
26
- return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
27
- }
28
- /** Resolve `parts` under `root`, or return null when the result escapes `root`. */
29
- function resolveInside(root, ...parts) {
30
- const target = path.resolve(root, ...parts);
31
- return isInside(root, target) ? target : null;
32
- }
33
- function hostnameFromHostHeader(host) {
34
- if (host === null) return null;
35
- const trimmed = host.trim().toLowerCase();
36
- if (trimmed === "") return null;
37
- if (trimmed.startsWith("[")) {
38
- const end = trimmed.indexOf("]");
39
- if (end <= 1) return null;
40
- return trimmed.slice(1, end);
41
- }
42
- const colon = trimmed.lastIndexOf(":");
43
- if (colon === -1) return trimmed;
44
- const maybePort = trimmed.slice(colon + 1);
45
- if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
46
- return trimmed;
47
- }
48
- function isLocalHostname(hostname) {
49
- return hostname !== null && LOCAL_HOSTS.has(hostname);
50
- }
51
- function isLocalAddress(address) {
52
- if (!address) return false;
53
- const normalized = address.toLowerCase().replace(/^::ffff:/, "");
54
- return normalized === "127.0.0.1" || normalized === "::1";
55
- }
56
- /**
57
- * Allow the request when Host is local and, if Origin is present, its host is local. When the browser sends
58
- * `Sec-Fetch-Site`, it must be `same-origin` or `none` (typed in, or a tool such as curl), so a page on another
59
- * site cannot even read-probe the API with a no-cors GET, which carries no Origin.
60
- * When `remoteAddress` is provided it must be a loopback address. Omit it only in tests
61
- * that do not model a socket; the dev middleware always passes it.
62
- */
63
- function isLocalRequest(headers, remoteAddress) {
64
- if (!isLocalHostname(hostnameFromHostHeader(headers.get("host")))) return false;
65
- const site = headers.get("sec-fetch-site");
66
- if (site !== null && site !== "same-origin" && site !== "none") return false;
67
- const origin = headers.get("origin");
68
- if (origin !== null) {
69
- let hostname;
70
- try {
71
- hostname = new URL(origin).hostname.toLowerCase();
72
- } catch {
73
- return false;
74
- }
75
- if (!isLocalHostname(hostname)) return false;
76
- }
77
- if (remoteAddress !== void 0 && !isLocalAddress(remoteAddress)) return false;
78
- return true;
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
3
  //#region src/reload.ts
94
4
  const RELOAD_DELAY_MS = 50;
95
5
  /** Ignore the watcher's initial scan so opening `astro dev` does not reload immediately. */
@@ -198,4 +108,4 @@ function evaluatedModules(environment) {
198
108
  return modules;
199
109
  }
200
110
  //#endregion
201
- export { JSON_BODY_LIMIT as a, isInside as c, resolveDir as d, resolveInside as f, IMAGE_BYTE_LIMIT as i, isLocalRequest as l, contentReloadPlugin as n, MULTIPART_BODY_LIMIT as o, dropEarlyReloadAfterSave as r, asDirectory as s, CONTENT_COLLECTIONS_MARKER as t, readSlug as u };
111
+ export { contentReloadPlugin as n, dropEarlyReloadAfterSave as r, CONTENT_COLLECTIONS_MARKER as t };
@@ -0,0 +1,93 @@
1
+ import { o as slugSchema } from "./page-X-WnOu7-.js";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region src/security.ts
5
+ const JSON_BODY_LIMIT = 1048576;
6
+ const IMAGE_BYTE_LIMIT = 5242880;
7
+ /** Room for multipart boundaries around a max-size image. */
8
+ const MULTIPART_BODY_LIMIT = 5505024;
9
+ const LOCAL_HOSTS = /* @__PURE__ */ new Set([
10
+ "localhost",
11
+ "127.0.0.1",
12
+ "::1"
13
+ ]);
14
+ function asDirectory(root) {
15
+ if (root instanceof URL) return fileURLToPath(root);
16
+ if (root.startsWith("file:")) return fileURLToPath(root);
17
+ return path.resolve(root);
18
+ }
19
+ function resolveDir(root, value, fallback) {
20
+ const chosen = value ?? fallback;
21
+ return path.isAbsolute(chosen) ? path.resolve(chosen) : path.resolve(root, chosen);
22
+ }
23
+ /** True when `candidate` is `root` or a path inside it. */
24
+ function isInside(root, candidate) {
25
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
26
+ return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
27
+ }
28
+ /** Resolve `parts` under `root`, or return null when the result escapes `root`. */
29
+ function resolveInside(root, ...parts) {
30
+ const target = path.resolve(root, ...parts);
31
+ return isInside(root, target) ? target : null;
32
+ }
33
+ function hostnameFromHostHeader(host) {
34
+ if (host === null) return null;
35
+ const trimmed = host.trim().toLowerCase();
36
+ if (trimmed === "") return null;
37
+ if (trimmed.startsWith("[")) {
38
+ const end = trimmed.indexOf("]");
39
+ if (end <= 1) return null;
40
+ return trimmed.slice(1, end);
41
+ }
42
+ const colon = trimmed.lastIndexOf(":");
43
+ if (colon === -1) return trimmed;
44
+ const maybePort = trimmed.slice(colon + 1);
45
+ if (/^\d+$/.test(maybePort)) return trimmed.slice(0, colon);
46
+ return trimmed;
47
+ }
48
+ function isLocalHostname(hostname) {
49
+ return hostname !== null && LOCAL_HOSTS.has(hostname);
50
+ }
51
+ function isLocalAddress(address) {
52
+ if (!address) return false;
53
+ const normalized = address.toLowerCase().replace(/^::ffff:/, "");
54
+ return normalized === "127.0.0.1" || normalized === "::1";
55
+ }
56
+ /**
57
+ * Allow the request when Host is local and, if Origin is present, its host is local. When the browser sends
58
+ * `Sec-Fetch-Site`, it must be `same-origin` or `none` (typed in, or a tool such as curl), so a page on another
59
+ * site cannot even read-probe the API with a no-cors GET, which carries no Origin.
60
+ * When `remoteAddress` is provided it must be a loopback address. Omit it only in tests
61
+ * that do not model a socket; the dev middleware always passes it.
62
+ */
63
+ function isLocalRequest(headers, remoteAddress) {
64
+ if (!isLocalHostname(hostnameFromHostHeader(headers.get("host")))) return false;
65
+ const site = headers.get("sec-fetch-site");
66
+ if (site !== null && site !== "same-origin" && site !== "none") return false;
67
+ const origin = headers.get("origin");
68
+ if (origin !== null) {
69
+ let hostname;
70
+ try {
71
+ hostname = new URL(origin).hostname.toLowerCase();
72
+ } catch {
73
+ return false;
74
+ }
75
+ if (!isLocalHostname(hostname)) return false;
76
+ }
77
+ if (remoteAddress !== void 0 && !isLocalAddress(remoteAddress)) return false;
78
+ return true;
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
+ export { isInside as a, resolveDir as c, asDirectory as i, resolveInside as l, JSON_BODY_LIMIT as n, isLocalRequest as o, MULTIPART_BODY_LIMIT as r, readSlug as s, IMAGE_BYTE_LIMIT as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bearminion",
3
- "version": "1.9.3",
3
+ "version": "1.10.1",
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",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "template": "default",
4
- "version": "1.9.3",
4
+ "version": "1.10.1",
5
5
  "files": {
6
6
  "src/components/atoms/Button.astro": {
7
7
  "hash": "7be42b3dc3a3b59bec169de32a9d801904689e2705473d1945724658dc799043",