@vulcantech/forms 0.1.1 → 0.2.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/README.md CHANGED
@@ -2,9 +2,89 @@
2
2
 
3
3
  Dynamic form renderer for VulcanTech apps. Renders a form from a JSON `FormDefinition` (authored in the CMS form builder) using Formik + Yup, with sensitive-field encryption and Tailwind styling.
4
4
 
5
- **Exports**: `DynamicForm`, `DynamicFormSection`, `FormDefinition` (type), `buildYupSchema`, `buildInitialValues`, plus transform / crypto / email-template helpers.
5
+ **Exports**: `DynamicForm`, `DynamicFormSection`, `DynamicFormField`, `buildYupSchema`, `buildInitialValues`, `parseFormDefinition`, `getSafeRedirectUrl`, `renderEmailTemplate`, `encryptSensitiveValue`, the `useFormDefinition` / `useUndoRedo` / `useDragReorder` builder hooks, and the `FormDefinition` / `FormDefinitionJSON` / `FormFieldDefinition` / `FormStyle` / `FormSubmissionType` types.
6
6
 
7
- **Field types**: `text`, `email`, `phone`, `textarea`, `select`, `checkbox`, `radio`, `number`, `date`, `datetime`, `url`, `address`, `hidden`.
7
+ **Field types**: `text`, `email`, `phone`, `url`, `address`, `textarea`, `select`, `checkbox`, `radio`, `number`, `date`, `datetime`, `hidden`, `sensitive`, `file`.
8
+
9
+ ## Form shape (`FormDefinition`)
10
+
11
+ A `FormDefinition` is the CMS-authored schema for one form. Consumer sites never build it by hand — they fetch it from the CMS `GET /api/forms` and hand it to `<DynamicForm>`.
12
+
13
+ ```ts
14
+ interface FormDefinition {
15
+ id: string;
16
+ projectId?: string; // SERVER-ONLY — stripped from every client response (see below)
17
+ name: string;
18
+ slug: string; // unique per project; the CMS 409s on a collision
19
+ description?: string;
20
+ version: number; // bumped on each CMS edit; emitted as data-form-version
21
+ status: string; // "draft" | "published" | "archived" — typed as string, NOT the union
22
+ submissionType?: FormSubmissionType; // absent = "contact"; decides the target collection
23
+ bookingConfig?: FormBookingConfig; // only read when submissionType === "booking"
24
+ sections: FormSection[]; // render order is `order`, NOT array order
25
+ submitConfig: FormSubmitConfig; // button text, success/error copy, redirect, spam settings
26
+ style?: FormStyle; // absent = DEFAULT_FORM_STYLE (structure only, no colors)
27
+ defaultTextColor?: string; // hex; per-section `textColor` overrides it
28
+ metadata?: { trackAdReferral?: boolean; customFields?: Record<string, unknown> };
29
+ integrations?: FormIntegrations; // SERVER-ONLY — stripped
30
+ notificationEmailTemplate?: NotificationEmailTemplate; // SERVER-ONLY — stripped
31
+ applicationStatusEmails?: ApplicationStatusEmailTemplates; // SERVER-ONLY — stripped
32
+ createdAt: string; // ISO 8601
33
+ updatedAt: string; // ISO 8601
34
+ createdBy: string; // CMS user uid
35
+ }
36
+ ```
37
+
38
+ Field notes:
39
+
40
+ - **Four fields are server-only and will always be `undefined` on a consumer site.** The CMS strips `projectId`, `integrations`, `notificationEmailTemplate`, and `applicationStatusEmails` from every public response (`stripSensitiveFields`). Do not branch on them client-side, and never read `definition.projectId` — resolve the project from `VULCANTECH_PROJECT_ID` in your server-side proxy instead.
41
+ - **`status` is typed `string`, not `FormStatus`.** Same for the `*JSON` mirror types. Compare against the literals (`status === "published"`) rather than assuming a narrowed union. The CMS `GET /api/forms` already filters to published forms unless you pass `includeDrafts=1`, so you rarely need to check it.
42
+ - **`sections[].order` and `fields[].layout.order` drive render order**, not array position — `DynamicForm` sorts by `order` before rendering. Field width comes from `layout.width` (`"full"` / `"half"` / `"third"`) on a 6-column grid.
43
+ - **`style` is colors-optional by design.** `DEFAULT_FORM_STYLE` supplies only the structural choices (`preset`, `borderRadius`, `spacing`, `buttonVariant`, `buttonPlacement`, `sectionDividers`, `inputVariant`). Every color is optional and resolves through CSS `var()` fallbacks, so an unstyled form inherits the host page rather than forcing its own palette.
44
+ - **`FormDefinitionJSON` vs `FormDefinition`.** The strict type keeps string-literal unions; JSON parsed off a `fetch` widens them to `string` and won't assign. Type the raw value as `FormDefinitionJSON`, then call `parseFormDefinition(json)` — an unchecked structural cast that trusts the CMS, not a validator.
45
+
46
+ ### Where a submission lands (`submissionType`)
47
+
48
+ `submissionType` is read **from the form definition on the server**, never from the request body. A submission whose `formId` doesn't resolve always routes to `contact`.
49
+
50
+ | `submissionType` | Firestore collection | Notes |
51
+ | --- | --- | --- |
52
+ | `contact` (default) | `projects/{id}/contact-forms` | Values stored flat at the doc top level. |
53
+ | `application` | `projects/{id}/applications` | Values nested under `data`; adds `referenceNumber`, `status: "received"`, `statusHistory`. The route echoes `referenceNumber` back in the response. |
54
+ | `newsletter` | `projects/{id}/newsletter_subscribers` | Restricted to `email` + `checkbox` fields (`NEWSLETTER_ALLOWED_FIELD_TYPES`); checkbox ids become `preferences` booleans. A repeat email updates the existing record instead of creating one. |
55
+ | `booking` | `projects/{id}/bookings` | Values nested under `data`, plus a denormalized `date`. |
56
+
57
+ For `booking`, the CMS resolves the booking date in three steps: `bookingConfig.dateFieldId` → the first `date`/`datetime` field in render order → a top-level `date` key. **Date-only convention:** a `date` field submits `"yyyy-MM-dd"`, which parses to UTC midnight, so a stored epoch that is an exact multiple of 86,400,000 is treated as date-only and formatted in UTC; a `datetime` field submits a full ISO string and is treated as a real instant.
58
+
59
+ ## Submitting (`DynamicForm`)
60
+
61
+ `<DynamicForm definition={…} apiRoute="/api/contact" />` POSTs a **flat JSON object** to `apiRoute` — the form's own field ids as top-level keys, plus anything in `extraData`, plus `formId: definition.id`. There is no `data` or `values` wrapper. Before sending it strips the honeypot, fields hidden by an unmet `showWhen`, and the synthetic `_sameAs_*` toggles.
62
+
63
+ Your `apiRoute` is expected to be a **server-side proxy in your own app** that adds the credentials and forwards to the CMS `POST /api/contact`. The renderer never sends `projectId`, `apiKey`, or `url` — the proxy adds those. Forward the browser's body through **whole**; hand-picking fields into a new object is what silently destroys leads once the CMS re-validates the definition's required fields.
64
+
65
+ Other `DynamicForm` props: `onSuccess(data?)` (receives the parsed response body — this is how you read `referenceNumber`), `onError(error)`, `extraData`, `className`, `onFormView` / `onFormSubmit` (analytics; they fall back to `window.__vtTrack` so a site running `@vulcantech/analytics` tracks conversions with no wiring), `transportKeyEndpoint`, and the `preview*` props used only by the CMS builder.
66
+
67
+ ### Two CMS rejections that will bite you
68
+
69
+ - **`url` binding → `400 {"error":"Invalid url"}`.** The CMS compares the submitted `url` against the project's stored `url` by exact string equality. Proxies therefore hardcode the production origin, which means **submissions from a localhost dev server are rejected**. Test against the CMS directly (or temporarily point the project's `url` at your dev origin) rather than assuming the form is broken.
70
+ - **A top-level `email` is required on every submission type.** After the credential, URL, rate-limit and honeypot gates, the CMS runs a Yup schema requiring a valid `email` and returns `400 {"error":"Validation failed","details":[…]}`. Because builder-generated field ids look like `field-1712…`, a form satisfies this only if its email field's id is literally `email`, or the proxy adds a canonical `email` key alongside the raw field ids. A second pass then re-enforces the definition's own `required` rules (skipping `showWhen`-hidden fields), reporting `"<Field label> is required"` in the same `details` array.
71
+
72
+ ### Failure mode
73
+
74
+ **`DynamicForm` never throws at the call site** — it catches everything internally, sets its own error banner, and calls `onError(error)`. There is no promise to await and no exception to catch around the component.
75
+
76
+ Three outcomes look like success but aren't a stored lead, and each is deliberate:
77
+
78
+ - **Spam (honeypot filled, or submitted faster than `minSubmitTime`, default 3s).** The renderer shows the success banner, calls `onSuccess()` **with no argument**, and makes **no network request at all**. Treat a missing argument in `onSuccess` as "no server response", not as an error.
79
+ - **Server-side honeypot.** If a filled honeypot does reach the CMS it writes the row with `status: "spam"` and still answers `200 {"success":true}` — indistinguishable from success by design.
80
+ - **Duplicate.** The CMS fingerprints each submission (all values except `apiKey`, `projectId`, `url`, `formId`, `formType`, `submittedAt`, `_hp_website`) and suppresses an identical resubmit within **10 minutes**, answering `200 {"success":true,"duplicate":true}` with the original `referenceNumber`. No second document, no second notification email. Dedupe fails open — a Firestore outage lets the write through rather than dropping a lead. Forms with sensitive fields are never fingerprinted (fresh ciphertext each submit).
81
+
82
+ Other CMS statuses reach `onError` with the server's `error` string as the message: `413` (payload over 256KB, any string over 20,000 chars, or over 100 top-level keys), `429` (60 submissions/min per IP, 200/hour per project), `401`/`403` (bad or out-of-scope API key), `400` for the two rejections above.
83
+
84
+ ### Field types needing extra wiring
85
+
86
+ - **`sensitive`** — encrypted in the browser (RSA-OAEP + AES-GCM) before submission. The renderer fetches the wrapping key from `transportKeyEndpoint`, defaulting to **`/api/forms/transport-key` on the same origin**. That route exists in the CMS, not in consumer apps, so a site with a sensitive field must either proxy it or pass an absolute CMS URL. Values arrive at the CMS as envelopes, get re-encrypted with KMS into an isolated `sensitive_data` collection, and the submission keeps only `{ sensitiveDataId, last4 }`. An envelope on a field the definition doesn't declare sensitive is rejected with `400 {"error":"Failed to process sensitive fields"}` — the usual cause is a wrong or missing `formId`.
87
+ - **`file`** — the value submitted is a URL string (or an array of them when `multiple`), never file bytes; the CMS stores it as an ordinary string. **`FileField`'s `onUpload` prop is not currently threaded through `DynamicForm`**, so file fields rendered by `DynamicForm` fall back to `URL.createObjectURL` and submit a `blob:` URL that is meaningless outside the submitting tab. Render `FileField` directly with an `onUpload` handler if you need real uploads.
8
88
 
9
89
  ## Integration
10
90
 
@@ -26,6 +106,8 @@ npm install @vulcantech/forms
26
106
 
27
107
  **4. Server fetcher** `src/lib/cms/forms.ts` — ISR-cached wrapper over the CMS `/api/forms`. Exposes `getFormById(id)` / `getFormBySlug(slug)`; tags each fetch `form:{projectId}:{formId}` + `forms:{projectId}`; returns `null` on failure so the page still renders.
28
108
 
109
+ `GET /api/forms` takes its credentials as **query params, not headers**: `projectId` and `apiKey` (required, scope `forms:read`), then `formId` **or** `slug` to fetch one form (`formId` wins if both are sent), and optional `includeDrafts=1` to bypass the published-only filter. With neither `formId` nor `slug` it returns `{ forms: [{ id, name, slug, status, updatedAt }] }`. A single form comes back as the definition object itself with `id` set from the Firestore doc id. It answers `404 {"error":"Form not found"}` for a missing, deleted, or unpublished form, and sends `Cache-Control: private, no-store` deliberately — caching is the consumer's job via Next fetch tags plus `/api/revalidate`.
110
+
29
111
  **5. Per-form loader** `src/lib/cms/load<Name>Form.ts` — pin the form's Firestore id and wrap the fetcher with a fallback:
30
112
  ```ts
31
113
  import { getFormById } from "./forms";
@@ -58,7 +140,8 @@ export function ContactForm({ definition }: { definition?: FormDefinition }) {
58
140
  - **Form definition ID(s)** — Firestore doc id from the CMS admin (one per form), pinned in `load<Name>Form.ts` (e.g. `CONTACT_FORM_ID`, `SERVICE_REQUEST_FORM_ID`).
59
141
 
60
142
  ### Notes
61
- - `FormDefinition` is the CMS-authored schema (sections, fields, submit config, style).
143
+ - `FormDefinition` is the CMS-authored schema (sections, fields, submit config, style) — see [Form shape](#form-shape-formdefinition) above.
62
144
  - `style.buttonPlacement: "inline"` renders the submit button beside the fields instead of full-width below them — suited to single-field forms (newsletter email + Join). Editable in the CMS form builder under Style → Submit Button → Button Placement.
63
145
  - Newsletter forms (`submissionType: "newsletter"`) should submit to an app route that proxies to the CMS `/api/contact` — the CMS routes them into `newsletter_subscribers`.
146
+ - `submitConfig.redirectUrl` takes precedence over `successBehavior` on genuine submissions (typically a thank-you page for ad conversion tracking). It fires only on a real success — the spam path deliberately stays on-page so a detected bot never triggers the conversion tag. Values are passed through `getSafeRedirectUrl`, which accepts absolute http(s) URLs and site-relative paths only.
64
147
  - The package also ships `buildYupSchema` / `buildInitialValues` for custom render paths, but consumer sites use the server-fetcher pattern above for ISR caching.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as Yup from 'yup';
2
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import * as react from 'react';
3
3
  import { CSSProperties, DragEvent } from 'react';
4
4
 
5
5
  type FieldType = "text" | "email" | "phone" | "url" | "address" | "textarea" | "select" | "checkbox" | "radio" | "number" | "date" | "datetime" | "hidden" | "sensitive" | "file";
@@ -76,7 +76,15 @@ declare const DEFAULT_SENSITIVE_FIELD_CONFIG: SensitiveFieldConfig;
76
76
  /**
77
77
  * Configuration for the `file` field type. Files are uploaded to
78
78
  * Firebase Storage client-side; the form submission receives the
79
- * download URL(s) rather than raw file data.
79
+ * download URL(s) rather than raw file data — a string, or an array of
80
+ * strings when `multiple`. The CMS stores whatever string arrives and does
81
+ * nothing file-specific with it.
82
+ *
83
+ * KNOWN LIMITATION: `FileField`'s `onUpload` prop is not threaded through
84
+ * `DynamicFormField`, so a file field rendered via `DynamicForm` falls back
85
+ * to `URL.createObjectURL` and submits a `blob:` URL that is meaningless
86
+ * outside the submitting tab. Render `FileField` directly with an `onUpload`
87
+ * handler when real uploads are needed.
80
88
  */
81
89
  interface FileFieldConfig {
82
90
  /** Accepted MIME types. Default: "image/*" */
@@ -260,11 +268,47 @@ type FormStatus = "draft" | "published" | "archived";
260
268
  * (optional, for preferences/consent) fields. Duplicate emails within a
261
269
  * project update the existing record's preferences rather than creating
262
270
  * a new entry.
271
+ * - `booking`: writes to the project's `bookings` subcollection and surfaces
272
+ * in the Bookings dashboard. The submitted values are stored like an
273
+ * application (nested `data` map), plus a denormalized booking `date`
274
+ * (epoch ms) parsed from the form's designated date field — see
275
+ * {@link FormBookingConfig}.
263
276
  *
264
277
  * Only the routing changes — spam protection, sensitive field handling,
265
278
  * notification emails, and integrations behave identically.
266
279
  */
267
- type FormSubmissionType = "contact" | "application" | "newsletter";
280
+ type FormSubmissionType = "contact" | "application" | "newsletter" | "booking";
281
+ /**
282
+ * Booking settings for a form with `submissionType: "booking"`. The renderer
283
+ * is unaffected — booking forms submit exactly like any other form; the CMS
284
+ * submission route uses this config to pull the booking date(s) out of the
285
+ * submitted values.
286
+ *
287
+ * Date-only convention: a `date` field submits `"yyyy-MM-dd"`, which parses
288
+ * to UTC midnight, so a stored epoch that is an exact multiple of a day is
289
+ * treated as date-only and displayed in UTC. A `datetime` field submits a
290
+ * full ISO string and is stored as a real instant. An unparseable value is
291
+ * stored as an explicit `null` rather than a fabricated date.
292
+ */
293
+ interface FormBookingConfig {
294
+ /**
295
+ * Field id of the `date`/`datetime` field holding the booking date (the
296
+ * start date, when `endDateFieldId` is also set). When omitted, the
297
+ * submission route falls back to the form's first date/datetime field in
298
+ * render order, and then to a top-level `date` key on the submission.
299
+ */
300
+ dateFieldId?: string;
301
+ /**
302
+ * Optional second `date`/`datetime` field id for begin/end bookings.
303
+ * Bookings without an end date use `defaultDurationMinutes` instead.
304
+ */
305
+ endDateFieldId?: string;
306
+ /**
307
+ * Default duration (minutes) stamped onto each new booking. Individual
308
+ * bookings can be overridden afterwards in the Bookings dashboard.
309
+ */
310
+ defaultDurationMinutes?: number;
311
+ }
268
312
  /**
269
313
  * Field types allowed on a newsletter form. Enforced by the form builder UI
270
314
  * and (defensively) by the submission route. Keep in sync with
@@ -311,6 +355,16 @@ declare const APPLICATION_STATUS_KEYS: ApplicationStatusKey[];
311
355
  */
312
356
  type ApplicationStatusEmailTemplates = Partial<Record<ApplicationStatusKey, NotificationEmailTemplate>>;
313
357
  declare const DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES: Record<ApplicationStatusKey, NotificationEmailTemplate>;
358
+ /**
359
+ * The CMS-authored schema for one form — the value `DynamicForm` renders and
360
+ * the CMS submission route consults to route and validate a submission.
361
+ *
362
+ * Consumer sites fetch this from `GET /api/forms` rather than building it.
363
+ * Four fields are stripped from every client-facing response by the CMS
364
+ * (`stripSensitiveFields`) and are therefore always `undefined` outside the
365
+ * CMS server: `projectId`, `integrations`, `notificationEmailTemplate`, and
366
+ * `applicationStatusEmails`.
367
+ */
314
368
  interface FormDefinition {
315
369
  id: string;
316
370
  /**
@@ -323,17 +377,37 @@ interface FormDefinition {
323
377
  */
324
378
  projectId?: string;
325
379
  name: string;
380
+ /** Unique within a project — the CMS rejects a colliding slug with a 409. */
326
381
  slug: string;
327
382
  description?: string;
383
+ /** Bumped on every CMS edit. Emitted by the renderer as `data-form-version`. */
328
384
  version: number;
385
+ /**
386
+ * FormStatus values: "draft" | "published" | "archived".
387
+ *
388
+ * Deliberately typed `string`, not the {@link FormStatus} union, because
389
+ * definitions cross a JSON boundary. Compare against the literals. The
390
+ * public GET route already filters to published forms unless the caller
391
+ * passes `includeDrafts=1`.
392
+ */
329
393
  status: string;
330
394
  /**
331
395
  * Routes submissions to the matching dashboard collection.
332
396
  * Defaults to `"contact"` when omitted. See {@link FormSubmissionType}.
397
+ *
398
+ * Read server-side from this definition, never from the request body — a
399
+ * submission whose `formId` does not resolve always routes to `contact`.
333
400
  */
334
401
  submissionType?: FormSubmissionType;
402
+ /**
403
+ * Booking settings. Only consulted when `submissionType === "booking"`.
404
+ * See {@link FormBookingConfig}.
405
+ */
406
+ bookingConfig?: FormBookingConfig;
407
+ /** Rendered in `order`, not array order — the renderer sorts before rendering. */
335
408
  sections: FormSection[];
336
409
  submitConfig: FormSubmitConfig;
410
+ /** Absent = {@link DEFAULT_FORM_STYLE} (structure only; colors stay unset). */
337
411
  style?: FormStyle;
338
412
  /**
339
413
  * Optional hex color applied as the default text color for every section
@@ -346,15 +420,19 @@ interface FormDefinition {
346
420
  trackAdReferral?: boolean;
347
421
  customFields?: Record<string, unknown>;
348
422
  };
423
+ /** Server-only — stripped from client-facing responses like `projectId`. */
349
424
  integrations?: FormIntegrations;
350
425
  /**
351
426
  * Customizable email sent to project members when a submission arrives.
352
427
  * Falls back to `DEFAULT_NOTIFICATION_EMAIL_TEMPLATE` when undefined.
428
+ *
429
+ * Server-only — stripped from client-facing responses like `projectId`.
353
430
  */
354
431
  notificationEmailTemplate?: NotificationEmailTemplate;
355
432
  /**
356
433
  * Per-status applicant-facing email templates. Only consulted when
357
- * `submissionType === "application"`. Missing entries fall back to
434
+ * `submissionType === "application"`. Server-only — stripped from
435
+ * client-facing responses like `projectId`. Missing entries fall back to
358
436
  * `DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES[status]`. Set to an empty
359
437
  * object to opt every status into the defaults explicitly.
360
438
  */
@@ -476,6 +554,8 @@ interface FormDefinitionJSON {
476
554
  version: number;
477
555
  status: string;
478
556
  submissionType?: string;
557
+ /** See {@link FormDefinition.bookingConfig} — no narrowed unions, so the strict type is reused. */
558
+ bookingConfig?: FormBookingConfig;
479
559
  sections: FormSectionJSON[];
480
560
  submitConfig: FormSubmitConfigJSON;
481
561
  style?: FormStyleJSON;
@@ -698,16 +778,51 @@ declare function encryptSensitiveValue(plaintext: string, publicKey: TransportPu
698
778
  declare function deriveLast4(plaintext: string): string;
699
779
 
700
780
  interface DynamicFormProps {
781
+ /**
782
+ * The CMS-authored schema, normally fetched from `GET /api/forms`. Note
783
+ * that `projectId`, `integrations`, `notificationEmailTemplate` and
784
+ * `applicationStatusEmails` are stripped from client-facing responses, so
785
+ * they are always undefined here — never read `definition.projectId`.
786
+ */
701
787
  definition: FormDefinition;
788
+ /**
789
+ * Endpoint this form POSTs to — expected to be a server-side proxy in the
790
+ * consuming app that adds credentials and forwards to the CMS
791
+ * `POST /api/contact`.
792
+ *
793
+ * The body is a FLAT JSON object: the definition's field ids as top-level
794
+ * keys, plus `extraData`, plus `formId`. There is no `data`/`values`
795
+ * wrapper. The honeypot, fields hidden by an unmet `showWhen`, and the
796
+ * synthetic `_sameAs_*` toggles are stripped before sending. The renderer
797
+ * never sends `projectId` / `apiKey` / `url` — the proxy must add those,
798
+ * and must forward the browser's body WHOLE (hand-picking fields into a
799
+ * new object drops values the CMS then rejects as required).
800
+ *
801
+ * Two CMS rejections to expect: `url` must exactly equal the project's
802
+ * stored URL (so localhost dev submissions get `400 "Invalid url"`), and
803
+ * a top-level `email` key is required on every submission type.
804
+ */
702
805
  apiRoute: string;
703
806
  /**
704
807
  * Called after a successful submission. The argument is the parsed JSON
705
808
  * response body, when one was returned — application submissions echo
706
809
  * `{ success: true, referenceNumber: "APP-…" }` here so the consumer
707
810
  * can display it on its confirmation page.
811
+ *
812
+ * Also fired on the spam path (honeypot filled or submitted faster than
813
+ * `minSubmitTime`) with NO argument and no network request at all — treat
814
+ * a missing argument as "no server response", not as an error.
708
815
  */
709
816
  onSuccess?: (data?: unknown) => void;
817
+ /**
818
+ * Called when the submission fails. `DynamicForm` catches everything
819
+ * internally and never throws at the call site, so this callback is the
820
+ * only error channel. The message is the CMS `error` string when one was
821
+ * returned (e.g. "Invalid url", "Validation failed"), otherwise
822
+ * `Submission failed (<status>)`.
823
+ */
710
824
  onError?: (error: Error) => void;
825
+ /** Extra top-level keys merged into the payload alongside the field values. */
711
826
  extraData?: Record<string, unknown>;
712
827
  className?: string;
713
828
  /**
@@ -716,6 +831,10 @@ interface DynamicFormProps {
716
831
  * `/api/forms/transport-key` (resolved against the same origin).
717
832
  *
718
833
  * The endpoint must respond with `{ kid: string, jwk: JsonWebKey }`.
834
+ *
835
+ * That route lives in the CMS, not in consumer apps — a consumer site with
836
+ * a sensitive field must either proxy it or pass an absolute CMS URL here.
837
+ * Only fetched when the definition actually contains a sensitive field.
719
838
  */
720
839
  transportKeyEndpoint?: string;
721
840
  /**
@@ -754,7 +873,21 @@ interface DynamicFormProps {
754
873
  */
755
874
  previewTextColor?: string;
756
875
  }
757
- declare const DynamicForm: ({ definition, apiRoute, onSuccess, onError, extraData, className, onFormView, onFormSubmit: onFormSubmitCallback, transportKeyEndpoint, previewState, previewTouchAllSignal, previewUntouchAllSignal, previewBg, previewTextColor, }: DynamicFormProps) => react_jsx_runtime.JSX.Element;
876
+ /**
877
+ * Render a CMS-authored {@link FormDefinition} as a working form.
878
+ *
879
+ * Sections and fields render in `order` (not array order); validation comes
880
+ * from `buildYupSchema(definition)`; sensitive fields are encrypted in the
881
+ * browser before submission. Submission goes to {@link DynamicFormProps.apiRoute}
882
+ * as a flat JSON payload — see that prop for the wire contract.
883
+ *
884
+ * Failure mode: this component never throws. Network and CMS errors are
885
+ * caught, shown in the built-in error banner, and reported via `onError`.
886
+ * Note that a suppressed duplicate (an identical resubmit within 10 minutes)
887
+ * and a server-side spam catch both answer `200` and are indistinguishable
888
+ * from a stored lead by design.
889
+ */
890
+ declare const DynamicForm: ({ definition, apiRoute, onSuccess, onError, extraData, className, onFormView, onFormSubmit: onFormSubmitCallback, transportKeyEndpoint, previewState, previewTouchAllSignal, previewUntouchAllSignal, previewBg, previewTextColor, }: DynamicFormProps) => react.JSX.Element;
758
891
 
759
892
  /**
760
893
  * Single source of truth for the CSS custom properties the renderer publishes
@@ -842,7 +975,7 @@ interface Props$1 {
842
975
  */
843
976
  inlineSubmit?: React.ReactNode;
844
977
  }
845
- declare const DynamicFormSection: ({ section, isLast, formDefaultTextColor, inlineSubmit, }: Props$1) => react_jsx_runtime.JSX.Element;
978
+ declare const DynamicFormSection: ({ section, isLast, formDefaultTextColor, inlineSubmit, }: Props$1) => react.JSX.Element;
846
979
 
847
980
  interface Props {
848
981
  field: FormFieldDefinition;
@@ -851,7 +984,7 @@ interface Props {
851
984
  /** How a mirrored target renders while the toggle is on. */
852
985
  mirrorBehavior?: "hide" | "lock";
853
986
  }
854
- declare const DynamicFormField: ({ field, mirrored, mirrorBehavior }: Props) => react_jsx_runtime.JSX.Element | null;
987
+ declare const DynamicFormField: ({ field, mirrored, mirrorBehavior }: Props) => react.JSX.Element | null;
855
988
 
856
989
  interface BaseFetchOptions {
857
990
  cmsUrl: string;
@@ -974,4 +1107,4 @@ interface UseDragReorderResult extends DragReorderState {
974
1107
  */
975
1108
  declare function useDragReorder<T>({ items, getId, onReorder, dragType, }: UseDragReorderOptions<T>): UseDragReorderResult;
976
1109
 
977
- export { APPLICATION_STATUS_KEYS, type ApplicationStatusEmailTemplates, type ApplicationStatusKey, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, type DatetimeConfig, type DragReorderItemHandlers, type DragReorderState, type DropPosition, DynamicForm, DynamicFormField, DynamicFormSection, type EmailTemplateVariableDescriptor, type EmailTemplateVariables, type EncryptedSensitiveValue, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, type FieldOption, type FieldTransform, type FieldType, type FieldVisibilityCondition, type FieldWidth, type FileFieldConfig, type FormDefinition, type FormDefinitionJSON, type FormFieldDefinition, type FormFieldDefinitionJSON, type FormIdentifier, type FormIntegrationConfig, type FormIntegrationConfigJSON, type FormIntegrations, type FormIntegrationsJSON, type FormSection, type FormSectionJSON, type FormSpamProtectionConfig, type FormStatus, type FormStyle, type FormStyleJSON, type FormStylePreset, type FormSubmissionType, type FormSubmitConfig, type FormSubmitConfigJSON, type FormSuccessBehavior, HONEYPOT_FIELD_NAME, type InputVariant, type IntegrationFieldMappingEntry, type IntegrationFieldMappingEntryJSON, NEWSLETTER_ALLOWED_FIELD_TYPES, type NotificationEmailTemplate, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, type SectionSameAsConfig, type SensitiveFieldConfig, type SensitiveFieldConfigJSON, type SetStateUpdater, type TextTransform, type TransportPublicKey, type UseDragReorderOptions, type UseDragReorderResult, type UseFormDefinitionOptions, type UseUndoRedoControls, type UseUndoRedoOptions, type UseUndoRedoReturn, type ValidationRule, type ValidationRuleJSON, type VisibilityOperator, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, sameAsToggleKey, useDragReorder, useFormDefinition, useUndoRedo, useUndoRedoShortcuts };
1110
+ export { APPLICATION_STATUS_KEYS, type ApplicationStatusEmailTemplates, type ApplicationStatusKey, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, type DatetimeConfig, type DragReorderItemHandlers, type DragReorderState, type DropPosition, DynamicForm, DynamicFormField, DynamicFormSection, type EmailTemplateVariableDescriptor, type EmailTemplateVariables, type EncryptedSensitiveValue, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, type FieldOption, type FieldTransform, type FieldType, type FieldVisibilityCondition, type FieldWidth, type FileFieldConfig, type FormBookingConfig, type FormDefinition, type FormDefinitionJSON, type FormFieldDefinition, type FormFieldDefinitionJSON, type FormIdentifier, type FormIntegrationConfig, type FormIntegrationConfigJSON, type FormIntegrations, type FormIntegrationsJSON, type FormSection, type FormSectionJSON, type FormSpamProtectionConfig, type FormStatus, type FormStyle, type FormStyleJSON, type FormStylePreset, type FormSubmissionType, type FormSubmitConfig, type FormSubmitConfigJSON, type FormSuccessBehavior, HONEYPOT_FIELD_NAME, type InputVariant, type IntegrationFieldMappingEntry, type IntegrationFieldMappingEntryJSON, NEWSLETTER_ALLOWED_FIELD_TYPES, type NotificationEmailTemplate, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, type SectionSameAsConfig, type SensitiveFieldConfig, type SensitiveFieldConfigJSON, type SetStateUpdater, type TextTransform, type TransportPublicKey, type UseDragReorderOptions, type UseDragReorderResult, type UseFormDefinitionOptions, type UseUndoRedoControls, type UseUndoRedoOptions, type UseUndoRedoReturn, type ValidationRule, type ValidationRuleJSON, type VisibilityOperator, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, sameAsToggleKey, useDragReorder, useFormDefinition, useUndoRedo, useUndoRedoShortcuts };