bearminion 1.6.0 → 1.8.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/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-BFuPEq6Q.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-DdCyRbPs.js";
3
+ import "./options-4HWVEj9O.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 {
@@ -304,4 +305,4 @@ interface ContrastCheck {
304
305
  /** Text pairs a visitor reads: text on its background, label on the accent fill, link on its background. */
305
306
  export declare function contrastChecks(colors: ThemeColors | undefined): ContrastCheck[];
306
307
  //#endregion
307
- 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 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, 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 };
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
@@ -3,6 +3,7 @@ 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
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";
6
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
@@ -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, 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 };
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 };
@@ -1,4 +1,4 @@
1
- import { A as SectionRegistry, J as SiteDefinition, M as ThemeDefinition, Yt as ContentMigrator, k as ContentModel } from "./page-BFuPEq6Q.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 {
@@ -117,6 +117,22 @@ interface BearminionOptions extends ContentModel {
117
117
  * Default `/src/lib/render-preview.ts`. Preview never writes to disk.
118
118
  */
119
119
  previewModule?: string;
120
+ /**
121
+ * The folder that holds the section directories and the files `bearminion sync` generates from them, relative to the
122
+ * project root. When set, `astro build`, `astro check` and `astro sync` stop if those files are stale, and
123
+ * `astro dev` warns. Default: not checked.
124
+ */
125
+ sectionsDir?: string;
126
+ /**
127
+ * The dev route for the forms in your site. A file `src/forms/contact.ts` that default-exports `defineForm(...)`
128
+ * answers at `/api/contact` during `astro dev`, as a dry run unless `BEARMINION_FORMS_LIVE=on`. `dir` is the folder
129
+ * (default `src/forms`) and `prefix` the path (default `/api`). `false` turns the route off, for a site whose
130
+ * Astro adapter serves the endpoint itself.
131
+ */
132
+ forms?: false | {
133
+ dir?: string;
134
+ prefix?: string;
135
+ };
120
136
  /**
121
137
  * Show Commit changes in the editor, which commits the changed content and uploads to the local git repository.
122
138
  * Off by default. It never pushes, and it does nothing outside a git work tree.
@@ -143,6 +159,8 @@ interface EditorContext {
143
159
  migrator: ContentMigrator;
144
160
  /** Commit changes is enabled. */
145
161
  git: boolean;
162
+ /** The folder with the site's form handlers, or `null` when the `forms` option turns them off. */
163
+ formsDir?: string | null;
146
164
  }
147
165
  //#endregion
148
166
  export { StoreKeyError as a, createFileStore as c, FileStoreOptions as i, EditorContext as n, StoreOperation as o, ContentStore as r, UploadStore as s, BearminionOptions as t };
@@ -172,6 +172,7 @@ declare function defineWireframe(wireframe: Wireframe): Wireframe;
172
172
  * - `wireframe` is the thumbnail in the Add section picker.
173
173
  * - `choices` lists every string enum in `props` (derived from the schema); the sidebar offers them as choices.
174
174
  * - `icons` draws those choices as icons in the sidebar's picker.
175
+ * - `form` names the handler in `src/forms` that receives what the section's form sends. The sidebar says whether it exists.
175
176
  * - `showWhen` hides props in the sidebar while the section's options make them unused.
176
177
  */
177
178
  interface SectionDefinition<TType extends string = string, TSchema extends z.ZodType = z.ZodType, TVariant extends string = string> {
@@ -190,6 +191,7 @@ interface SectionDefinition<TType extends string = string, TSchema extends z.Zod
190
191
  readonly choices: FieldChoices;
191
192
  readonly icons: FieldIcons;
192
193
  readonly showWhen: ShowWhen;
194
+ readonly form?: string;
193
195
  /** Cross-field rules the schema cannot express, such as a variant that needs an exact item count. */
194
196
  refine?(section: {
195
197
  variant: TVariant;
@@ -220,6 +222,8 @@ interface SectionConfig<TType extends string, TSchema extends z.ZodType, TVarian
220
222
  * means any of its values; `variant`, `tone` and `motion` count as options. A hidden prop keeps its value in the file.
221
223
  */
222
224
  showWhen?: ShowWhen;
225
+ /** The form handler this section posts to: the file `src/forms/<form>.ts`, answering at `/api/<form>`. */
226
+ form?: string;
223
227
  refine?(section: {
224
228
  variant: TVariants[number];
225
229
  props: z.infer<TSchema>;
@@ -0,0 +1,97 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/sections-manifest.ts
4
+ /** The two files `bearminion sync` writes next to the section directories. */
5
+ const DEFINITIONS_FILE = "definitions.gen.ts";
6
+ const COMPONENTS_FILE = "components.gen.ts";
7
+ /** A section directory that does not follow the convention. The message says what to fix. */
8
+ var SectionsError = class extends Error {};
9
+ const DIRECTORY_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
10
+ const toCamelCase = (dir) => dir.replace(/-([a-z0-9])/g, (_, char) => char.toUpperCase());
11
+ const toPascalCase = (dir) => {
12
+ const camel = toCamelCase(dir);
13
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
14
+ };
15
+ /**
16
+ * Lists the section directories: every folder under `sectionsDir` that holds a `definition.ts`. Folders that start
17
+ * with `_` or `.` and folders without a definition are not sections. Sorted by name, so the result never depends on
18
+ * the file system.
19
+ */
20
+ function scanSections(sectionsDir) {
21
+ if (!fs.existsSync(sectionsDir)) throw new SectionsError(`No sections folder at ${sectionsDir}.`);
22
+ const entries = [];
23
+ for (const child of fs.readdirSync(sectionsDir, { withFileTypes: true })) {
24
+ if (!child.isDirectory() || child.name.startsWith("_") || child.name.startsWith(".")) continue;
25
+ if (!fs.existsSync(path.join(sectionsDir, child.name, "definition.ts"))) continue;
26
+ if (!DIRECTORY_NAME.test(child.name)) throw new SectionsError(`"${child.name}" is not a usable section name. Use lowercase words joined by hyphens, such as "logo-strip": the directory name becomes the section type.`);
27
+ const component = toPascalCase(child.name);
28
+ if (!fs.existsSync(path.join(sectionsDir, child.name, `${component}.astro`))) throw new SectionsError(`${child.name}/ has a definition.ts but no ${component}.astro. The component is named after the directory.`);
29
+ entries.push({
30
+ dir: child.name,
31
+ key: toCamelCase(child.name),
32
+ component
33
+ });
34
+ }
35
+ if (entries.length === 0) throw new SectionsError(`No sections found in ${sectionsDir}. A section is a directory with a definition.ts.`);
36
+ return entries.sort((a, b) => a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0);
37
+ }
38
+ const HEADER = "// Generated by `bearminion sync`. Do not edit: add or remove a directory under sections/ and run it again.";
39
+ /** The contents of `definitions.gen.ts`: schemas only, no `.astro` imports, so `astro.config.ts` and the editor can load it. */
40
+ function renderDefinitions(entries) {
41
+ const imports = entries.map((entry) => `import { ${entry.key} } from './${entry.dir}/definition'`);
42
+ const keys = entries.map((entry) => ` ${entry.key},`);
43
+ return [
44
+ HEADER,
45
+ "import type { SectionRegistry } from 'bearminion'",
46
+ ...imports,
47
+ "",
48
+ "export const sectionDefinitions = {",
49
+ ...keys,
50
+ "} satisfies SectionRegistry",
51
+ ""
52
+ ].join("\n");
53
+ }
54
+ /** The contents of `components.gen.ts`: the section type to the component that renders it. */
55
+ function renderComponents(entries) {
56
+ const imports = entries.map((entry) => `import ${entry.component} from './${entry.dir}/${entry.component}.astro'`);
57
+ const map = entries.map((entry) => ` ${entry.key}: ${entry.component},`);
58
+ return [
59
+ HEADER,
60
+ "import type { SectionType } from './definitions'",
61
+ ...imports,
62
+ "",
63
+ "/** Maps a content section `type` to the component that renders it. */",
64
+ "export const sectionComponents = {",
65
+ ...map,
66
+ "} satisfies Record<SectionType, unknown>",
67
+ ""
68
+ ].join("\n");
69
+ }
70
+ /**
71
+ * Makes `definitions.gen.ts` and `components.gen.ts` match the section directories. With `check` it only reports
72
+ * which files are stale and writes nothing.
73
+ */
74
+ function syncSections(sectionsDir, options = {}) {
75
+ const entries = scanSections(sectionsDir);
76
+ const wanted = {
77
+ [DEFINITIONS_FILE]: renderDefinitions(entries),
78
+ [COMPONENTS_FILE]: renderComponents(entries)
79
+ };
80
+ const changed = [];
81
+ for (const [file, content] of Object.entries(wanted)) {
82
+ const target = path.join(sectionsDir, file);
83
+ if ((fs.existsSync(target) ? fs.readFileSync(target, "utf8") : void 0) === content) continue;
84
+ changed.push(file);
85
+ if (!options.check) fs.writeFileSync(target, content);
86
+ }
87
+ return {
88
+ changed,
89
+ entries
90
+ };
91
+ }
92
+ /** The sentence for a build that stops on stale files, or for the dev server's warning. */
93
+ function staleSectionsMessage(changed) {
94
+ return `${changed.join(" and ")} no longer match the directories under sections/. Run \`npx bearminion sync\`.`;
95
+ }
96
+ //#endregion
97
+ export { staleSectionsMessage as n, syncSections as r, SectionsError as t };
package/dist/ui/mount.js CHANGED
@@ -14309,7 +14309,7 @@ function attachShortcuts(editor) {
14309
14309
  if (ui.open.peek() && !isTyping(event.target)) ui.open.value = false;
14310
14310
  };
14311
14311
  const onKey = (event) => {
14312
- const key = event.key.toLowerCase();
14312
+ const key = (event.key ?? "").toLowerCase();
14313
14313
  const mod = event.metaKey || event.ctrlKey;
14314
14314
  if (mod && key === "s") {
14315
14315
  event.preventDefault();
@@ -14711,6 +14711,8 @@ function uploadVideo(file) {
14711
14711
  });
14712
14712
  }
14713
14713
  const getGit = () => request("/git");
14714
+ /** Whether the form handlers the sections post to exist in `src/forms`. */
14715
+ const getForms = () => request("/forms");
14714
14716
  const commit = (body) => request("/git/commit", sendJson("POST", body));
14715
14717
  /** Saved versions of the site (`scope` site) or of one page. */
14716
14718
  function historyPath(scope, slug) {
@@ -22646,6 +22648,56 @@ function PagesForm({ pages, labels, current, homeSlug, onCreated, onNavigate })
22646
22648
  });
22647
22649
  }
22648
22650
  //#endregion
22651
+ //#region src/ui/forms/form-handler.tsx
22652
+ const FORMS_DOCS = "https://docs.bearminion.com/forms";
22653
+ /**
22654
+ * What the sidebar says about the code behind a section's form. BearMinion can see that the file exists, not that it
22655
+ * works: its keys, its service and its host are outside the project, so the note says to test it by hand.
22656
+ */
22657
+ function describeHandler(name, file) {
22658
+ if (file === null) return {
22659
+ tone: "warn",
22660
+ text: `Nothing receives this form yet: there is no src/forms/${name}.ts. A visitor who sends it gets an error. Create the file to connect it.`
22661
+ };
22662
+ return {
22663
+ tone: "hint",
22664
+ text: `This form posts to /api/${name}, handled by your own code in ${file}. BearMinion cannot check that it works: send a test message and see that it arrives.`
22665
+ };
22666
+ }
22667
+ /** Under a section's fields, for a section that posts to a handler of the site. */
22668
+ function FormHandlerNote({ name }) {
22669
+ const [file, setFile] = useState(void 0);
22670
+ useEffect(() => {
22671
+ let current = true;
22672
+ getForms().then((answer) => {
22673
+ if (!current) return;
22674
+ setFile(answer.ok && answer.value.enabled ? answer.value.handlers[name]?.file ?? null : void 0);
22675
+ }, () => {
22676
+ if (current) setFile(void 0);
22677
+ });
22678
+ return () => {
22679
+ current = false;
22680
+ };
22681
+ }, [name]);
22682
+ if (file === void 0) return null;
22683
+ const note = describeHandler(name, file);
22684
+ return /* @__PURE__ */ jsxs("span", {
22685
+ class: note.tone === "warn" ? "bm-error" : "bm-hint",
22686
+ role: note.tone === "warn" ? "alert" : "status",
22687
+ "data-form-handler": name,
22688
+ children: [
22689
+ note.text,
22690
+ " ",
22691
+ /* @__PURE__ */ jsx("a", {
22692
+ href: FORMS_DOCS,
22693
+ target: "_blank",
22694
+ rel: "noopener",
22695
+ children: "How to set up a form"
22696
+ })
22697
+ ]
22698
+ });
22699
+ }
22700
+ //#endregion
22649
22701
  //#region src/ui/forms/section-form.tsx
22650
22702
  const LAYOUT_OPTIONS = [
22651
22703
  "variant",
@@ -22892,6 +22944,7 @@ function SectionForm({ section, index, sections, catalog, siteMotion, taken, ima
22892
22944
  })
22893
22945
  })
22894
22946
  }),
22947
+ catalog.sectionForms?.[section.type] && /* @__PURE__ */ jsx(FormHandlerNote, { name: catalog.sectionForms[section.type] }),
22895
22948
  /* @__PURE__ */ jsxs("div", {
22896
22949
  class: "bm-actions-split",
22897
22950
  children: [/* @__PURE__ */ jsx("button", {