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/dist/content.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { n as createPageSchema, r as createTolerantPageSchema } from "./page-NOFVEqn1.js";
2
- import { n as createMigrator } from "./migrate-B56wxCiC.js";
3
- import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-D0vwI0OT.js";
2
+ import { n as createMigrator } from "./migrate-b408EaLp.js";
3
+ import { t as CONTENT_COLLECTIONS_MARKER } from "./reload-BPkPoQ-P.js";
4
4
  import { z } from "zod";
5
- import { pathToFileURL } from "node:url";
6
5
  import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
7
  import { glob } from "astro/loaders";
8
8
  //#region src/content.ts
9
9
  /**
@@ -0,0 +1,48 @@
1
+ //#region src/form-contract.d.ts
2
+ /**
3
+ * What a Contact form sends and what it expects back, for anyone who writes the handler behind it (a Vercel,
4
+ * Netlify or Cloudflare function, or a plain Astro endpoint). Types only: nothing here runs in the browser.
5
+ *
6
+ * To run code of your own behind the form, with your keys kept on the server, use `defineForm` from `bearminion/forms`.
7
+ *
8
+ * ```ts
9
+ * import type { FormResult, FormSubmission } from 'bearminion'
10
+ *
11
+ * export async function handle(submission: FormSubmission): Promise<FormResult> {
12
+ * // ...send it somewhere
13
+ * return { ok: true }
14
+ * }
15
+ * ```
16
+ */
17
+ /**
18
+ * The request. The form's fields by name (`name`, `email`, `topic` when the section lists topics, and `message`),
19
+ * plus where it came from. The form posts it to `/api/contact` as a JSON object. The spam trap field is never part of it.
20
+ */
21
+ interface FormSubmission {
22
+ /** The id of the Contact section that sent it. */
23
+ formId: string;
24
+ /** The path of the page the form is on, such as `/contact`. */
25
+ page: string;
26
+ [field: string]: string;
27
+ }
28
+ /** Field name → what is wrong with it. Shown under that field on the page. */
29
+ type FormFieldErrors = Readonly<Record<string, string>>;
30
+ /**
31
+ * The answer. `{ ok: true }` with a 2xx status shows the thank-you message; an optional `message` (plain text) is shown
32
+ * in its place. `{ ok: false }` needs a matching 4xx or 5xx status; `error` is shown in a message the visitor closes
33
+ * themselves, and `fieldErrors` under the fields they name.
34
+ */
35
+ type FormResult = {
36
+ ok: true;
37
+ message?: string;
38
+ } | {
39
+ ok: false;
40
+ error: string;
41
+ fieldErrors?: FormFieldErrors;
42
+ };
43
+ /** The spam-trap field. People never see it; many bots fill every field they find. Formspree uses the same name. */
44
+ declare const HONEYPOT_FIELD = "_gotcha";
45
+ /** The field Cloudflare Turnstile's widget fills with its token. The form sends it; `defineForm` checks and removes it. */
46
+ declare const TURNSTILE_FIELD = "cf-turnstile-response";
47
+ //#endregion
48
+ export { TURNSTILE_FIELD as a, HONEYPOT_FIELD as i, FormResult as n, FormSubmission as r, FormFieldErrors as t };
@@ -0,0 +1,7 @@
1
+ //#region src/form-contract.ts
2
+ /** The spam-trap field. People never see it; many bots fill every field they find. Formspree uses the same name. */
3
+ const HONEYPOT_FIELD = "_gotcha";
4
+ /** The field Cloudflare Turnstile's widget fills with its token. The form sends it; `defineForm` checks and removes it. */
5
+ const TURNSTILE_FIELD = "cf-turnstile-response";
6
+ //#endregion
7
+ export { TURNSTILE_FIELD as n, HONEYPOT_FIELD as t };
@@ -0,0 +1,119 @@
1
+ import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
2
+ //#region src/forms/define-form.d.ts
3
+ /** Environment variables by name: `process.env`, Cloudflare's `env`, `Netlify.env.toObject()`. */
4
+ type FormEnv = Readonly<Record<string, string | undefined>>;
5
+ /** What a handler is given besides the message. */
6
+ interface FormContext {
7
+ /** Your secrets and settings. Pass the host's environment to `form.fetch`; the glue files in the guide do. */
8
+ env: FormEnv;
9
+ /** The incoming request without its body (already read): its headers and URL, for the visitor's address or language. */
10
+ request: Request;
11
+ /** True while `astro dev` runs the handler. */
12
+ dev: boolean;
13
+ }
14
+ /**
15
+ * What a handler may return. Nothing, or `{ ok: true }`, is a success; `message` replaces the thank-you text on the
16
+ * page (plain text). `{ ok: false, error }` is a refusal the visitor sees. To fail with another status, throw a `FormError`.
17
+ */
18
+ type FormHandlerResult = void | FormResult;
19
+ type FormHandler = (submission: FormSubmission, context: FormContext) => FormHandlerResult | Promise<FormHandlerResult>;
20
+ interface FormOptions {
21
+ /**
22
+ * Check a Cloudflare Turnstile token before the handler runs. `true` reads the secret key from the environment
23
+ * variable `TURNSTILE_SECRET_KEY`; `{ secretEnv }` names another one. The page needs the matching site key in the
24
+ * Contact section's settings.
25
+ */
26
+ turnstile?: boolean | {
27
+ secretEnv?: string;
28
+ };
29
+ /**
30
+ * Other sites allowed to post here, such as `https://www.example.com`, or `'*'` for any. Posts from the form's own
31
+ * site are always allowed. Needed only when the page and the function live on different addresses.
32
+ */
33
+ origins?: readonly string[];
34
+ /** Largest post accepted, in bytes. Default 64 KB. */
35
+ maxBytes?: number;
36
+ }
37
+ /** How one request is run. The dev server uses this; hosts do not need it. */
38
+ interface FormRunOptions {
39
+ dev?: boolean;
40
+ /** Receive the message and answer success without calling the handler or Turnstile. */
41
+ dryRun?: (submission: FormSubmission) => void;
42
+ }
43
+ interface Form {
44
+ /** Answers one request. Give it the host's environment as `env`. */
45
+ fetch(request: Request, env?: FormEnv, run?: FormRunOptions): Promise<Response>;
46
+ }
47
+ /**
48
+ * Throw this from a handler to refuse the message with a text the visitor sees, instead of the generic "could not be
49
+ * delivered". `fieldErrors` mark fields. The status is 422 with `fieldErrors` and 400 without, unless you give one.
50
+ */
51
+ export declare class FormError extends Error {
52
+ readonly status: number;
53
+ readonly fieldErrors: FormFieldErrors | undefined;
54
+ constructor(message: string, options?: {
55
+ fieldErrors?: FormFieldErrors;
56
+ status?: number;
57
+ });
58
+ }
59
+ /**
60
+ * Puts your function behind a form. It runs on your server with your keys, so a service's token never reaches the
61
+ * browser. It gets the message the Contact form sent and returns what the visitor should see.
62
+ *
63
+ * ```ts
64
+ * // src/forms/contact.ts
65
+ * import { defineForm, FormError } from 'bearminion/forms'
66
+ *
67
+ * export default defineForm(async (submission, { env }) => {
68
+ * const response = await fetch('https://api.example.com/send', {
69
+ * method: 'POST',
70
+ * headers: { Authorization: `Bearer ${env.EXAMPLE_API_KEY}` },
71
+ * body: JSON.stringify({ from: submission.email, text: submission.message }),
72
+ * })
73
+ * if (!response.ok) throw new FormError('The message could not be sent.', { status: 502 })
74
+ * })
75
+ * ```
76
+ *
77
+ * What it does around your function, whatever the host: answers only `POST` (and the CORS preflight), accepts JSON,
78
+ * `multipart/form-data` and `application/x-www-form-urlencoded`, refuses a post over `maxBytes` and a post from another
79
+ * site, drops a message whose trap field is filled (without calling you), checks Turnstile when asked, and turns what
80
+ * you return or throw into the `{ ok, error, fieldErrors }` answer the page understands. It does not validate the
81
+ * fields: the Contact form already does in the browser.
82
+ */
83
+ export declare function defineForm(handler: FormHandler, options?: FormOptions): Form;
84
+ //#endregion
85
+ //#region src/forms/turnstile.d.ts
86
+ /**
87
+ * Server side of Cloudflare Turnstile: the widget in the page gives the visitor a token; this asks Cloudflare whether
88
+ * it is genuine. A token works once, so call it once per submission.
89
+ */
90
+ export declare const TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
91
+ /** Turnstile could not be asked: Cloudflare was unreachable or answered something unreadable. */
92
+ export declare class TurnstileUnavailableError extends Error {
93
+ constructor(message: string, options?: {
94
+ cause?: unknown;
95
+ });
96
+ }
97
+ type TurnstileOutcome =
98
+ /** The token is genuine. */
99
+ {
100
+ success: true;
101
+ } |
102
+ /** `misconfigured` is true when the secret key is missing or wrong: a mistake on your side, not the visitor's. */
103
+ {
104
+ success: false;
105
+ codes: string[];
106
+ misconfigured: boolean;
107
+ };
108
+ interface VerifyTurnstileInput {
109
+ secret: string;
110
+ token: string;
111
+ /** The visitor's address. Optional; Cloudflare uses it as an extra signal. */
112
+ remoteIp?: string;
113
+ /** For tests. Defaults to the platform's `fetch`. */
114
+ fetch?: typeof fetch;
115
+ }
116
+ /** Asks Cloudflare whether `token` is a genuine, unused Turnstile token for your secret key. */
117
+ export declare function verifyTurnstile({ secret, token, remoteIp, fetch: send }: VerifyTurnstileInput): Promise<TurnstileOutcome>;
118
+ //#endregion
119
+ export { type Form, type FormContext, type FormEnv, type FormFieldErrors, type FormHandler, type FormHandlerResult, type FormOptions, type FormResult, type FormRunOptions, type FormSubmission, HONEYPOT_FIELD, TURNSTILE_FIELD, type TurnstileOutcome, type VerifyTurnstileInput };
package/dist/forms.js ADDED
@@ -0,0 +1,358 @@
1
+ import { n as TURNSTILE_FIELD, t as HONEYPOT_FIELD } from "./form-contract-CIDTNab-.js";
2
+ /** A post that cannot be used, with the HTTP status that says why. */
3
+ var BodyError = class extends Error {
4
+ status;
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.name = "BodyError";
8
+ this.status = status;
9
+ }
10
+ };
11
+ /** The request body, or a 413 as soon as it is known to be over `maxBytes`. */
12
+ async function readBody(request, maxBytes) {
13
+ const advertised = Number(request.headers.get("content-length") ?? "");
14
+ if (Number.isFinite(advertised) && advertised > maxBytes) throw new BodyError(413, "The message is too large.");
15
+ const reader = request.body?.getReader();
16
+ if (!reader) return /* @__PURE__ */ new Uint8Array();
17
+ const chunks = [];
18
+ let size = 0;
19
+ for (;;) {
20
+ const { done, value } = await reader.read();
21
+ if (done) break;
22
+ size += value.byteLength;
23
+ if (size > maxBytes) {
24
+ await reader.cancel().catch(() => void 0);
25
+ throw new BodyError(413, "The message is too large.");
26
+ }
27
+ chunks.push(value);
28
+ }
29
+ const bytes = new Uint8Array(size);
30
+ let offset = 0;
31
+ for (const chunk of chunks) {
32
+ bytes.set(chunk, offset);
33
+ offset += chunk.byteLength;
34
+ }
35
+ return bytes;
36
+ }
37
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
38
+ /**
39
+ * The text fields of a post: JSON, `multipart/form-data` or `application/x-www-form-urlencoded`. Anything that is not
40
+ * text (a file, a number, a nested object) is left out, so a handler only ever sees strings.
41
+ */
42
+ async function parseFields(contentType, bytes) {
43
+ const type = (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
44
+ const fields = {};
45
+ const add = (name, value) => {
46
+ if (name === "__proto__" || typeof value !== "string") return;
47
+ fields[name] = value;
48
+ };
49
+ if (type === "application/json") {
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(new TextDecoder().decode(bytes));
53
+ } catch {
54
+ throw new BodyError(400, "The message could not be read.");
55
+ }
56
+ if (!isRecord(parsed)) throw new BodyError(400, "The message could not be read.");
57
+ for (const [name, value] of Object.entries(parsed)) add(name, value);
58
+ return fields;
59
+ }
60
+ if (type === "multipart/form-data" || type === "application/x-www-form-urlencoded") {
61
+ let data;
62
+ try {
63
+ data = await new Response(bytes, { headers: { "content-type": contentType ?? type } }).formData();
64
+ } catch {
65
+ throw new BodyError(400, "The message could not be read.");
66
+ }
67
+ for (const [name, value] of data.entries()) add(name, value);
68
+ return fields;
69
+ }
70
+ throw new BodyError(415, "Send the form as JSON or as form data.");
71
+ }
72
+ //#endregion
73
+ //#region src/forms/turnstile.ts
74
+ /**
75
+ * Server side of Cloudflare Turnstile: the widget in the page gives the visitor a token; this asks Cloudflare whether
76
+ * it is genuine. A token works once, so call it once per submission.
77
+ */
78
+ const TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
79
+ /** Turnstile could not be asked: Cloudflare was unreachable or answered something unreadable. */
80
+ var TurnstileUnavailableError = class extends Error {
81
+ constructor(message, options) {
82
+ super(message, options);
83
+ this.name = "TurnstileUnavailableError";
84
+ }
85
+ };
86
+ /** Asks Cloudflare whether `token` is a genuine, unused Turnstile token for your secret key. */
87
+ async function verifyTurnstile({ secret, token, remoteIp, fetch: send = fetch }) {
88
+ const body = new URLSearchParams({
89
+ secret,
90
+ response: token
91
+ });
92
+ if (remoteIp) body.set("remoteip", remoteIp);
93
+ let answer;
94
+ try {
95
+ answer = await (await send(TURNSTILE_VERIFY_URL, {
96
+ method: "POST",
97
+ body
98
+ })).json();
99
+ } catch (error) {
100
+ throw new TurnstileUnavailableError("Could not reach Cloudflare Turnstile.", { cause: error });
101
+ }
102
+ if (typeof answer !== "object" || answer === null) throw new TurnstileUnavailableError("Turnstile answered something unreadable.");
103
+ const record = answer;
104
+ if (record.success === true) return { success: true };
105
+ const codes = Array.isArray(record["error-codes"]) ? record["error-codes"].filter((code) => typeof code === "string") : [];
106
+ return {
107
+ success: false,
108
+ codes,
109
+ misconfigured: codes.some((code) => code === "missing-input-secret" || code === "invalid-input-secret")
110
+ };
111
+ }
112
+ //#endregion
113
+ //#region src/forms/define-form.ts
114
+ const FORM_ERROR = Symbol.for("bearminion.form-error");
115
+ /**
116
+ * Throw this from a handler to refuse the message with a text the visitor sees, instead of the generic "could not be
117
+ * delivered". `fieldErrors` mark fields. The status is 422 with `fieldErrors` and 400 without, unless you give one.
118
+ */
119
+ var FormError = class extends Error {
120
+ status;
121
+ fieldErrors;
122
+ constructor(message, options = {}) {
123
+ super(message);
124
+ this.name = "FormError";
125
+ this.fieldErrors = options.fieldErrors;
126
+ const wanted = options.status ?? (options.fieldErrors ? 422 : 400);
127
+ this.status = Number.isInteger(wanted) && wanted >= 400 && wanted <= 599 ? wanted : 400;
128
+ Object.defineProperty(this, FORM_ERROR, { value: true });
129
+ }
130
+ };
131
+ function isFormError(error) {
132
+ return typeof error === "object" && error !== null && error[FORM_ERROR] === true;
133
+ }
134
+ const UNDELIVERED = "The message could not be delivered. Try again later.";
135
+ const NOT_SET_UP = "This form is not set up correctly. Please try again later.";
136
+ const SPAM_CHECK_FAILED = "The spam check did not pass. Reload the page and try again.";
137
+ const SPAM_CHECK_UNAVAILABLE = "The spam check could not be completed. Try again in a moment.";
138
+ const jsonHeaders = {
139
+ "content-type": "application/json; charset=utf-8",
140
+ "cache-control": "no-store"
141
+ };
142
+ function reply(status, result, headers = {}) {
143
+ return new Response(JSON.stringify(result), {
144
+ status,
145
+ headers: {
146
+ ...jsonHeaders,
147
+ ...headers
148
+ }
149
+ });
150
+ }
151
+ const refuse = (status, error, headers) => reply(status, {
152
+ ok: false,
153
+ error
154
+ }, headers);
155
+ /** A browser posting the form itself (JavaScript off) asks for HTML. The script on the page asks for JSON. */
156
+ function isNavigation(request) {
157
+ if (request.method !== "POST") return false;
158
+ const accept = request.headers.get("accept") ?? "";
159
+ return accept.includes("text/html") && !accept.includes("application/json");
160
+ }
161
+ /** The page the visitor came from, as a path. Only on this host: anything else would be an open redirect. */
162
+ function cameFrom(request) {
163
+ const referer = request.headers.get("referer");
164
+ if (!referer) return null;
165
+ try {
166
+ const from = new URL(referer);
167
+ if (from.host !== new URL(request.url).host) return null;
168
+ return `${from.pathname}${from.search}`;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+ /** Who may post, and the CORS headers that go with it. `null` means refuse. */
174
+ function originHeaders(request, allowed) {
175
+ const origin = request.headers.get("origin");
176
+ if (origin === null) return {};
177
+ try {
178
+ if (new URL(origin).host === new URL(request.url).host) return {};
179
+ } catch {
180
+ return null;
181
+ }
182
+ const vary = { vary: "Origin" };
183
+ if (allowed.includes("*")) return {
184
+ ...vary,
185
+ "access-control-allow-origin": "*"
186
+ };
187
+ if (allowed.includes(origin)) return {
188
+ ...vary,
189
+ "access-control-allow-origin": origin
190
+ };
191
+ return null;
192
+ }
193
+ const CORS_METHODS = {
194
+ "access-control-allow-methods": "POST, OPTIONS",
195
+ "access-control-allow-headers": "Content-Type",
196
+ "access-control-max-age": "86400"
197
+ };
198
+ function remoteIp(headers) {
199
+ return headers.get("cf-connecting-ip") ?? headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers.get("x-real-ip") ?? void 0;
200
+ }
201
+ /**
202
+ * Puts your function behind a form. It runs on your server with your keys, so a service's token never reaches the
203
+ * browser. It gets the message the Contact form sent and returns what the visitor should see.
204
+ *
205
+ * ```ts
206
+ * // src/forms/contact.ts
207
+ * import { defineForm, FormError } from 'bearminion/forms'
208
+ *
209
+ * export default defineForm(async (submission, { env }) => {
210
+ * const response = await fetch('https://api.example.com/send', {
211
+ * method: 'POST',
212
+ * headers: { Authorization: `Bearer ${env.EXAMPLE_API_KEY}` },
213
+ * body: JSON.stringify({ from: submission.email, text: submission.message }),
214
+ * })
215
+ * if (!response.ok) throw new FormError('The message could not be sent.', { status: 502 })
216
+ * })
217
+ * ```
218
+ *
219
+ * What it does around your function, whatever the host: answers only `POST` (and the CORS preflight), accepts JSON,
220
+ * `multipart/form-data` and `application/x-www-form-urlencoded`, refuses a post over `maxBytes` and a post from another
221
+ * site, drops a message whose trap field is filled (without calling you), checks Turnstile when asked, and turns what
222
+ * you return or throw into the `{ ok, error, fieldErrors }` answer the page understands. It does not validate the
223
+ * fields: the Contact form already does in the browser.
224
+ */
225
+ function defineForm(handler, options = {}) {
226
+ if (typeof handler !== "function") throw new TypeError("defineForm needs a function: defineForm(async (submission, { env }) => { ... }).");
227
+ const maxBytes = options.maxBytes ?? 65536;
228
+ const allowed = options.origins ?? [];
229
+ const secretEnv = options.turnstile === true ? "TURNSTILE_SECRET_KEY" : options.turnstile ? options.turnstile.secretEnv ?? "TURNSTILE_SECRET_KEY" : void 0;
230
+ async function answer(request, env, run, seen) {
231
+ const cors = originHeaders(request, allowed);
232
+ if (cors === null) return refuse(403, "This site is not allowed to send to this form.");
233
+ if (request.method === "OPTIONS") return new Response(null, {
234
+ status: 204,
235
+ headers: {
236
+ ...CORS_METHODS,
237
+ ...cors
238
+ }
239
+ });
240
+ if (request.method !== "POST") return refuse(405, "Send the form with POST.", {
241
+ allow: "POST, OPTIONS",
242
+ ...cors
243
+ });
244
+ let fields;
245
+ try {
246
+ fields = await parseFields(request.headers.get("content-type"), await readBody(request, maxBytes));
247
+ } catch (error) {
248
+ if (error instanceof BodyError) return refuse(error.status, error.message, cors);
249
+ throw error;
250
+ }
251
+ seen.formId = fields.formId ?? "";
252
+ const trap = fields[HONEYPOT_FIELD];
253
+ delete fields[HONEYPOT_FIELD];
254
+ if (trap !== void 0 && trap.trim() !== "") return reply(200, { ok: true }, cors);
255
+ const token = fields[TURNSTILE_FIELD];
256
+ delete fields[TURNSTILE_FIELD];
257
+ const { formId = "", page = cameFrom(request)?.split("?")[0] ?? "", ...rest } = fields;
258
+ const submission = {
259
+ formId,
260
+ page,
261
+ ...rest
262
+ };
263
+ if (run.dryRun) {
264
+ run.dryRun(submission);
265
+ return reply(200, { ok: true }, cors);
266
+ }
267
+ if (secretEnv !== void 0) {
268
+ const secret = env[secretEnv];
269
+ if (!secret) {
270
+ console.error(`[bearminion] This form checks Turnstile, but the environment variable ${secretEnv} is not set.`);
271
+ return refuse(500, NOT_SET_UP, cors);
272
+ }
273
+ if (!token) return refuse(422, SPAM_CHECK_FAILED, cors);
274
+ try {
275
+ const ip = remoteIp(request.headers);
276
+ const outcome = await verifyTurnstile({
277
+ secret,
278
+ token,
279
+ ...ip ? { remoteIp: ip } : {}
280
+ });
281
+ if (!outcome.success) {
282
+ if (outcome.misconfigured) {
283
+ console.error(`[bearminion] Turnstile refused the secret key in ${secretEnv} (${outcome.codes.join(", ")}). Check it in the Cloudflare dashboard.`);
284
+ return refuse(500, NOT_SET_UP, cors);
285
+ }
286
+ return refuse(422, SPAM_CHECK_FAILED, cors);
287
+ }
288
+ } catch (error) {
289
+ if (error instanceof TurnstileUnavailableError) {
290
+ console.error(`[bearminion] ${error.message}`, error.cause ?? "");
291
+ return refuse(502, SPAM_CHECK_UNAVAILABLE, cors);
292
+ }
293
+ throw error;
294
+ }
295
+ }
296
+ const context = {
297
+ env,
298
+ request: new Request(request.url, {
299
+ method: request.method,
300
+ headers: request.headers
301
+ }),
302
+ dev: run.dev === true
303
+ };
304
+ let outcome;
305
+ try {
306
+ outcome = await handler(submission, context);
307
+ } catch (error) {
308
+ if (isFormError(error)) return reply(error.status, error.fieldErrors ? {
309
+ ok: false,
310
+ error: error.message,
311
+ fieldErrors: error.fieldErrors
312
+ } : {
313
+ ok: false,
314
+ error: error.message
315
+ }, cors);
316
+ console.error("[bearminion] The form handler failed:", error);
317
+ return refuse(502, UNDELIVERED, cors);
318
+ }
319
+ if (outcome === void 0) return reply(200, { ok: true }, cors);
320
+ if (typeof outcome === "object" && outcome !== null && outcome.ok === true) {
321
+ const message = typeof outcome.message === "string" && outcome.message.trim() !== "" ? outcome.message.trim() : void 0;
322
+ return reply(200, message ? {
323
+ ok: true,
324
+ message
325
+ } : { ok: true }, cors);
326
+ }
327
+ if (typeof outcome === "object" && outcome !== null && outcome.ok === false && typeof outcome.error === "string" && outcome.error !== "") {
328
+ const fieldErrors = outcome.fieldErrors && Object.keys(outcome.fieldErrors).length > 0 ? outcome.fieldErrors : void 0;
329
+ return reply(fieldErrors ? 422 : 400, fieldErrors ? {
330
+ ok: false,
331
+ error: outcome.error,
332
+ fieldErrors
333
+ } : {
334
+ ok: false,
335
+ error: outcome.error
336
+ }, cors);
337
+ }
338
+ console.error("[bearminion] The form handler returned something else than nothing, { ok: true } or { ok: false, error }:", outcome);
339
+ return refuse(500, NOT_SET_UP, cors);
340
+ }
341
+ return { async fetch(request, env = {}, run = {}) {
342
+ const seen = { formId: "" };
343
+ const response = await answer(request, env, run, seen);
344
+ if (!isNavigation(request)) return response;
345
+ const back = cameFrom(request);
346
+ if (back === null) return response;
347
+ const fragment = seen.formId ? `#${seen.formId}-${response.status === 200 ? "sent" : "failed"}` : "";
348
+ return new Response(null, {
349
+ status: 303,
350
+ headers: {
351
+ location: `${back}${fragment}`,
352
+ "cache-control": "no-store"
353
+ }
354
+ });
355
+ } };
356
+ }
357
+ //#endregion
358
+ export { FormError, HONEYPOT_FIELD, TURNSTILE_FIELD, TURNSTILE_VERIFY_URL, TurnstileUnavailableError, defineForm, verifyTurnstile };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
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-B5NoN74Q.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-BfI9cD8g.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-DBfoi9D1.js";
3
+ import "./options-BeJQnsZM.js";
4
+ import { a as TURNSTILE_FIELD, i as HONEYPOT_FIELD, n as FormResult, r as FormSubmission, t as FormFieldErrors } from "./form-contract-BURSJP3Y.js";
4
5
  //#region src/errors.d.ts
5
6
  /** One schema problem, addressed by a dot path such as `sections.0.props.heading`. */
6
7
  interface ContentIssue {
@@ -70,6 +71,29 @@ interface ThemePreview<TModel extends ContentModel = ContentModel> {
70
71
  */
71
72
  export declare function defineThemePreview<TModel extends ContentModel = ContentModel>(preview: ThemePreview<TModel>): ThemePreview<TModel>;
72
73
  //#endregion
74
+ //#region src/media-source.d.ts
75
+ /**
76
+ * What a Media section's video link points at. YouTube and Vimeo links become privacy-friendly embeds
77
+ * (youtube-nocookie.com, Vimeo with Do Not Track) that load only after the visitor presses play. A link to a video file
78
+ * plays in a `<video>` element.
79
+ */
80
+ type MediaSource = {
81
+ kind: 'youtube';
82
+ id: string;
83
+ embed: string;
84
+ thumbnail: string;
85
+ } | {
86
+ kind: 'vimeo';
87
+ id: string;
88
+ embed: string;
89
+ } | {
90
+ kind: 'file';
91
+ src: string;
92
+ };
93
+ /** A path in `public/` (`/videos/demo.webm`) or an `https://` link to a video file. */
94
+ export declare const VIDEO_FILE: RegExp;
95
+ export declare function parseMediaSource(value: string): MediaSource | null;
96
+ //#endregion
73
97
  //#region src/git.d.ts
74
98
  type ChangeStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked';
75
99
  interface ChangedFile {
@@ -120,6 +144,15 @@ interface UploadedImage {
120
144
  path: string;
121
145
  bytes?: number;
122
146
  }
147
+ /** `GET /videos` entries and the body of a successful `POST /videos`. */
148
+ interface UploadedVideo {
149
+ filename: string;
150
+ /** Project-relative path of the file. */
151
+ path: string;
152
+ /** What a Media section's `video` field holds, such as `/videos/demo-1a2b3c4d.mp4`. */
153
+ url: string;
154
+ bytes?: number;
155
+ }
123
156
  /** `GET /history/site` and `GET /history/pages/:slug` entries. */
124
157
  interface HistoryEntry {
125
158
  id: string;
@@ -272,4 +305,4 @@ interface ContrastCheck {
272
305
  /** Text pairs a visitor reads: text on its background, label on the accent fill, link on its background. */
273
306
  export declare function contrastChecks(colors: ThemeColors | undefined): ContrastCheck[];
274
307
  //#endregion
275
- export { API_PREFIX, type ApiIssue, type ApiProblem, BRAND_LOGO_HEIGHT, type BaseSection, type BooleanOption, type ButtonStyle, type ChangedFile, type CommitRequest, type CommitResult, type ConsentCopy, type ConsentReopen, type ConsentText, type ConsentTextKey, type ContentIssue, type ContentMigration, type ContentMigrator, type ContentModel, type ContentVersioning, type ContrastCheck, type CountRule, type CreatePageRequest, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, type DocumentKind, type EnumOption, type FieldChoices, type FieldIcons, type FontMark, type Footer, type FooterColumn, type FooterConfig, type GitInfo, type Header, type HeaderConfig, type HistoryEntry, type Image, type ImageFit, type ImagePosition, type JsonLdBlock, type JsonLdResult, type Link, MAX_NAV_DEPTH, type NumberOption, type Option, type OptionalContent, type Page, type PageListItem, type PropsOf, type RichText, SCHEMA_VERSION_KEY, SYSTEM_PAGES, type SaveRequest, type SaveResponse, type SectionConfig, type SectionDefinition, type SectionOf, type SectionRegistry, type Seo, type ShowCondition, type ShowWhen, type Site, type SiteAnalytics, type SiteConfig, type SiteConsent, type SiteDefinition, type SiteJsonLdIds, type SiteJsonLdSource, type SiteOf, type SitePreview, type SitePreviewHtml, type SiteSeo, type SiteWith, type StringOption, type Text, type TextMark, type TextRun, type Theme, type ThemeColors, type ThemeConfig, type ThemeDefinition, type ThemeFont, type ThemePreview, type Tone, type UploadedImage, type WeightMark, type WireKind, type WireRect, type Wireframe, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineWireframe, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, htmlIdSchema, imageSchema, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeModes, themeSchema, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
308
+ export { API_PREFIX, type ApiIssue, type ApiProblem, BRAND_LOGO_HEIGHT, type BaseSection, type BooleanOption, type ButtonStyle, type ChangedFile, type CommitRequest, type CommitResult, type ConsentCopy, type ConsentReopen, type ConsentText, type ConsentTextKey, type ContentIssue, type ContentMigration, type ContentMigrator, type ContentModel, type ContentVersioning, type ContrastCheck, type CountRule, type CreatePageRequest, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, type DocumentKind, type EnumOption, type FieldChoices, type FieldIcons, type FontMark, type Footer, type FooterColumn, type FooterConfig, type FormFieldErrors, type FormResult, type FormSubmission, type GitInfo, HONEYPOT_FIELD, type Header, type HeaderConfig, type HistoryEntry, type Image, type ImageFit, type ImagePosition, type JsonLdBlock, type JsonLdResult, type Link, MAX_NAV_DEPTH, type MediaSource, type NumberOption, type Option, type OptionalContent, type Page, type PageListItem, type PropsOf, type RichText, SCHEMA_VERSION_KEY, SYSTEM_PAGES, type SaveRequest, type SaveResponse, type SectionConfig, type SectionDefinition, type SectionOf, type SectionRegistry, type Seo, type ShowCondition, type ShowWhen, type Site, type SiteAnalytics, type SiteConfig, type SiteConsent, type SiteDefinition, type SiteJsonLdIds, type SiteJsonLdSource, type SiteOf, type SitePreview, type SitePreviewHtml, type SiteSeo, type SiteWith, type StringOption, TURNSTILE_FIELD, type Text, type TextMark, type TextRun, type Theme, type ThemeColors, type ThemeConfig, type ThemeDefinition, type ThemeFont, type ThemePreview, type Tone, type UploadedImage, type UploadedVideo, type WeightMark, type WireKind, type WireRect, type Wireframe, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineWireframe, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, htmlIdSchema, imageSchema, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeModes, themeSchema, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@ import { c as ContentReadError, i as enumFields, l as ContentValidationError, n
2
2
  import { n as defineTheme, t as defaultTheme } from "./theme-DFjHjgFO.js";
3
3
  import { A as textSchema, C as MAX_NAV_DEPTH, D as linkSchema, E as imageSchema, F as DEFAULT_IMAGE_POSITION, G as tones, H as motionOption, I as IMAGE_FITS, K as variantOption, L as IMAGE_POSITIONS, M as trackingIdSchema, N as withEmphasis, O as richTextSchema, P as DEFAULT_IMAGE_FIT, R as isImageFit, S as upsertJsonLd, T as htmlIdSchema, U as themeModes, V as buttonStyles, W as toneOption, _ as jsonLdSchema, a as seoSchema, b as parseJsonLdInput, c as anchorSchema, d as sectionIdSchema, f as walkLinkIds, g as isPlaceholderSiteUrl, h as hasJsonLdId, i as isSystemPage, j as toneSchema, k as textMarkSchema, l as createSectionSchema, m as generateSiteJsonLd, n as createPageSchema, p as formatJsonLd, s as withoutOrphanSections, t as SYSTEM_PAGES, v as jsonLdWarnings, w as addMarkIssues, x as siteJsonLdIds, y as mergeJsonLd, z as isImagePosition } from "./page-NOFVEqn1.js";
4
4
  import { applyTextMark, fontMarks, markClass, marksFromEmphasis, reconcileMarks, renderMarkedHtml, splitMarkedText, weightMarks } from "./marks.js";
5
- import { n as createMigrator, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-B56wxCiC.js";
6
- import { _ as consentCopy, a as contrastRatio, c as hasThemeColors, d as tokenToHex, f as CONSENT_COPY, g as CONSENT_REOPEN, h as CONSENT_LIMITS, i as contrastChecks, l as hexToToken, m as CONSENT_HREF_MESSAGE, n as HEX_COLOR, o as derivePalette, p as CONSENT_HREF, s as hasOverrides, u as themeCss, v as consentTextIssues } from "./theme-colors-CbCyVANH.js";
5
+ import { n as createMigrator, r as API_PREFIX, t as SCHEMA_VERSION_KEY } from "./migrate-b408EaLp.js";
6
+ import { n as TURNSTILE_FIELD, t as HONEYPOT_FIELD } from "./form-contract-CIDTNab-.js";
7
+ import { _ as consentCopy, a as contrastRatio, b as parseMediaSource, c as hasThemeColors, d as tokenToHex, f as CONSENT_COPY, g as CONSENT_REOPEN, h as CONSENT_LIMITS, i as contrastChecks, l as hexToToken, m as CONSENT_HREF_MESSAGE, n as HEX_COLOR, o as derivePalette, p as CONSENT_HREF, s as hasOverrides, u as themeCss, v as consentTextIssues, y as VIDEO_FILE } from "./theme-colors-CHROGZkI.js";
7
8
  import { z } from "zod";
8
9
  //#region src/wireframe.ts
9
10
  /**
@@ -105,6 +106,7 @@ function defineSection(config) {
105
106
  choices,
106
107
  icons,
107
108
  showWhen,
109
+ form: config.form,
108
110
  refine: config.refine
109
111
  });
110
112
  }
@@ -441,4 +443,4 @@ function defineSite(config) {
441
443
  };
442
444
  }
443
445
  //#endregion
444
- export { API_PREFIX, BRAND_LOGO_HEIGHT, CONSENT_COPY, CONSENT_HREF, CONSENT_LIMITS, CONSENT_REOPEN, ContentError, ContentReadError, ContentValidationError, DEFAULT_IMAGE_FIT, DEFAULT_IMAGE_POSITION, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, HEX_COLOR, IMAGE_FITS, IMAGE_POSITIONS, MAX_NAV_DEPTH, SCHEMA_VERSION_KEY, SYSTEM_PAGES, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, consentCopy, consentTextIssues, contrastChecks, contrastRatio, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineThemePreview, defineWireframe, derivePalette, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, hasOverrides, hasThemeColors, hexToToken, htmlIdSchema, imageSchema, isImageFit, isImagePosition, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeCss, themeModes, themeSchema, tokenToHex, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };
446
+ export { API_PREFIX, BRAND_LOGO_HEIGHT, CONSENT_COPY, CONSENT_HREF, CONSENT_LIMITS, CONSENT_REOPEN, ContentError, ContentReadError, ContentValidationError, DEFAULT_IMAGE_FIT, DEFAULT_IMAGE_POSITION, DEFAULT_MAX_FOOTER_COLUMNS, DEFAULT_MAX_HEADER_ACTIONS, HEX_COLOR, HONEYPOT_FIELD, IMAGE_FITS, IMAGE_POSITIONS, MAX_NAV_DEPTH, SCHEMA_VERSION_KEY, SYSTEM_PAGES, TURNSTILE_FIELD, VIDEO_FILE, anchorSchema, applyTextMark, brandLogoSchema, buttonStyles, consentCopy, consentTextIssues, contrastChecks, contrastRatio, createMigrator, createPageSchema, createSectionSchema, defaultTheme, defineSection, defineSite, defineTheme, defineThemePreview, defineWireframe, derivePalette, fontMarks, formatJsonLd, generateSiteJsonLd, hasJsonLdId, hasOverrides, hasThemeColors, hexToToken, htmlIdSchema, imageSchema, isImageFit, isImagePosition, isPlaceholderSiteUrl, isSystemPage, jsonLdSchema, jsonLdWarnings, linkSchema, markClass, marksFromEmphasis, mergeJsonLd, motionOption, parseJsonLdInput, parseMediaSource, reconcileMarks, renderMarkedHtml, richTextSchema, sectionIdSchema, seoSchema, siteAnalyticsSchema, siteConsentSchema, siteJsonLdIds, siteSeoSchema, splitMarkedText, textMarkSchema, textSchema, themeColorsSchema, themeCss, themeModes, themeSchema, tokenToHex, toneOption, toneSchema, tones, trackingIdSchema, upsertJsonLd, variantOption, weightMarks, wireKinds, wireframeIssues, withEmphasis, withoutOrphanSections };