@vulcantech/forms 0.2.0 → 0.4.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/utils/visibility.ts","../src/schema/buildYupSchema.ts","../src/utils/initialValues.ts","../src/utils/transforms.ts","../src/utils/redirect.ts","../src/utils/textTransforms.ts","../src/utils/renderEmailTemplate.ts","../src/crypto/sensitive.ts","../src/renderer/FormStyleContext.tsx","../src/renderer/cssVars.ts","../src/renderer/fields/useInputStyles.ts","../src/renderer/fields/StyledInput.tsx","../src/renderer/fields/TextField.tsx","../src/renderer/fields/EmailField.tsx","../src/renderer/fields/PhoneField.tsx","../src/renderer/fields/UrlField.tsx","../src/renderer/fields/AddressField.tsx","../src/renderer/fields/TextAreaField.tsx","../src/renderer/fields/SelectField.tsx","../src/renderer/fields/CheckboxField.tsx","../src/renderer/fields/RadioField.tsx","../src/renderer/fields/NumberField.tsx","../src/renderer/fields/dateExclusions.ts","../src/renderer/fields/DateTimeField.tsx","../src/renderer/fields/DateField.tsx","../src/renderer/fields/HiddenField.tsx","../src/renderer/fields/SensitiveField.tsx","../src/renderer/fields/FileField.tsx","../src/renderer/DynamicFormField.tsx","../src/renderer/DynamicFormSection.tsx","../src/renderer/DynamicForm.tsx","../src/hooks/useFormDefinition.ts","../src/hooks/useUndoRedo.ts","../src/hooks/useDragReorder.ts"],"names":["twMerge","jsx","useField","useState","jsxs","BsCheck","_a","_b","useFormikContext","useEffect","Checkbox","useRef","_c","useCallback","e"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+GO,IAAM,8BAAA,GAAuD;AAAA,EAClE,OAAA,EAAS,EAAA;AAAA,EACT,WAAA,EAAa,CAAC,OAAA,EAAS,uBAAuB,CAAA;AAAA,EAC9C,SAAA,EAAW;AACb;AAiCO,IAAM,yBAAA,GAA6C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AAA;AAC/B,QAAA,SAAA,CAAU,IAAI,CAAA;AACd,QAAA,KAAA,EAAM;AAAA,MACR;AAAA,KACF,CAAA;AAAA,IACA,CAAC,KAAA,EAAO,KAAA,EAAO,WAAW,QAAA,EAAU,KAAA,EAAO,MAAM,gBAAgB;AAAA,GACnE;AAEA,EAAA,MAAM,UAAA,GAAaD,WAAAA;AAAA,IACjB,CAAC,EAAA,KAAe,KAAA,CAAM,UAAA,KAAe,EAAA;AAAA,IACrC,CAAC,MAAM,UAAU;AAAA,GACnB;AAEA,EAAA,MAAM,aAAA,GAAgBA,WAAAA;AAAA,IACpB,CAAC,EAAA,KAAoC;AACnC,MAAA,IAAI,KAAA,CAAM,UAAA,KAAe,EAAA,EAAI,OAAO,IAAA;AACpC,MAAA,IAAI,KAAA,CAAM,UAAA,KAAe,EAAA,EAAI,OAAO,IAAA;AACpC,MAAA,OAAO,KAAA,CAAM,gBAAA;AAAA,IACf,CAAA;AAAA,IACA,CAAC,KAAA,CAAM,UAAA,EAAY,KAAA,CAAM,UAAA,EAAY,MAAM,gBAAgB;AAAA,GAC7D;AAEA,EAAA,OAAO,iCACF,KAAA,CAAA,EADE;AAAA,IAEL,YAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF,CAAA;AACF","file":"index.mjs","sourcesContent":["export type FieldType =\n | \"text\"\n | \"email\"\n | \"phone\"\n | \"url\"\n | \"address\"\n | \"textarea\"\n | \"select\"\n | \"checkbox\"\n | \"radio\"\n | \"number\"\n | \"date\"\n | \"datetime\"\n | \"hidden\"\n | \"sensitive\"\n | \"file\";\n\nexport type TextTransform =\n | \"capitalize-sentences\"\n | \"capitalize-words\"\n | \"phone-number\"\n | \"ssn\";\n\nexport interface ValidationRule {\n type:\n | \"required\"\n | \"min\"\n | \"max\"\n | \"minLength\"\n | \"maxLength\"\n | \"pattern\"\n | \"email\"\n | \"phone\"\n | \"notEquals\";\n value?: string | number | boolean;\n message: string;\n}\n\nexport interface FieldOption {\n label: string;\n value: string;\n}\n\nexport type FieldWidth = \"full\" | \"half\" | \"third\";\n\nexport interface DatetimeConfig {\n showTimeSelect?: boolean;\n timeIntervals?: number;\n minTime?: string;\n maxTime?: string;\n excludeWeekends?: boolean;\n excludePastDates?: boolean;\n /** Block selecting today — for forms needing at least a day of lead time. */\n excludeToday?: boolean;\n /** Block selecting tomorrow. */\n excludeTomorrow?: boolean;\n /**\n * Block selecting the next business day relative to today (the first\n * non-weekend day after today — on a Friday or Saturday that's Monday).\n */\n excludeNextBusinessDay?: boolean;\n filterPastTimes?: boolean;\n dateFormat?: string;\n placeholderText?: string;\n}\n\n/**\n * Comparison applied by a {@link FieldVisibilityCondition}. `greater-than` /\n * `less-than` compare numerically (both sides parsed as numbers; the\n * condition is unmet when either side isn't numeric).\n */\nexport type VisibilityOperator =\n | \"equals\"\n | \"not-equals\"\n | \"greater-than\"\n | \"less-than\";\n\nexport interface FieldVisibilityCondition {\n fieldId: string;\n value: string | boolean;\n /** Defaults to \"equals\" (the only behavior before operators existed). */\n operator?: VisibilityOperator;\n}\n\n/**\n * Per-field configuration for the `sensitive` field type. Sensitive fields\n * are encrypted client-side before submission, re-encrypted by the server\n * with a KMS-managed key, and stored in an isolated `sensitive_data`\n * collection. The TTL controls automatic deletion; viewerRoles gates which\n * authenticated users can call the decrypt Cloud Function to reveal the\n * value.\n */\nexport interface SensitiveFieldConfig {\n /** Days until the encrypted record auto-deletes. Defaults to 30. */\n ttlDays: 30 | 60 | 90;\n /**\n * Roles allowed to invoke the decrypt Cloud Function. The Cloud Function\n * re-checks against the caller's user document; this list is also used to\n * gate the Reveal button in the CMS UI.\n */\n viewerRoles: string[];\n /**\n * Optional input mask pattern. Currently only `ssn` is implemented\n * (formats input as XXX-XX-XXXX, validates 9 digits). When omitted, the\n * field accepts free-form text. The form builder keeps this in lockstep\n * with the field-level `ssn` TextTransform — both drive the same\n * formatter, and the renderer honors either.\n */\n inputMask?: \"ssn\";\n}\n\nexport const DEFAULT_SENSITIVE_FIELD_CONFIG: SensitiveFieldConfig = {\n ttlDays: 30,\n viewerRoles: [\"admin\", \"sensitive_data_viewer\"],\n inputMask: \"ssn\",\n};\n\n/**\n * Configuration for the `file` field type. Files are uploaded to\n * Firebase Storage client-side; the form submission receives the\n * download URL(s) rather than raw file data — a string, or an array of\n * strings when `multiple`. The CMS stores whatever string arrives and does\n * nothing file-specific with it.\n *\n * KNOWN LIMITATION: `FileField`'s `onUpload` prop is not threaded through\n * `DynamicFormField`, so a file field rendered via `DynamicForm` falls back\n * to `URL.createObjectURL` and submits a `blob:` URL that is meaningless\n * outside the submitting tab. Render `FileField` directly with an `onUpload`\n * handler when real uploads are needed.\n */\nexport interface FileFieldConfig {\n /** Accepted MIME types. Default: \"image/*\" */\n accept?: string;\n /** Max file size in bytes. Default: 10MB (10485760). */\n maxSizeBytes?: number;\n /** Allow multiple files. Default: false. */\n multiple?: boolean;\n /** Max number of files when multiple=true. Default: 5. */\n maxFiles?: number;\n /**\n * Resize images before upload. Default: true.\n * When true, images are scaled to maxImageWidth and compressed.\n */\n resizeImages?: boolean;\n /** Max image width for resize. Default: 1600. */\n maxImageWidth?: number;\n}\n\nexport const DEFAULT_FILE_FIELD_CONFIG: FileFieldConfig = {\n accept: \"image/*\",\n maxSizeBytes: 10 * 1024 * 1024,\n multiple: false,\n maxFiles: 5,\n resizeImages: true,\n maxImageWidth: 1600,\n};\n\nexport interface FormFieldDefinition {\n id: string;\n type: FieldType;\n label: string;\n placeholder?: string;\n helpText?: string;\n description?: string;\n defaultValue?: string;\n transform?: TextTransform;\n validation: ValidationRule[];\n options?: FieldOption[];\n layout?: {\n width: FieldWidth;\n order: number;\n };\n characterCounter?: boolean;\n rows?: number;\n datetimeConfig?: DatetimeConfig;\n showWhen?: FieldVisibilityCondition;\n /** Required when `type === \"sensitive\"`. Ignored for other field types. */\n sensitiveConfig?: SensitiveFieldConfig;\n /** Configuration for `type === \"file\"`. */\n fileConfig?: FileFieldConfig;\n}\n\n/**\n * \"Same as another section\" mirroring. A later section can copy values from\n * an earlier one (e.g. billing address = home address) behind a checkbox.\n */\nexport interface SectionSameAsConfig {\n /** Section whose values are copied in. MUST have a lower `order`. */\n sourceSectionId: string;\n /** targetFieldId (in THIS section) -> sourceFieldId (in the source section). */\n fieldMap: Record<string, string>;\n /** Checkbox label, e.g. \"Billing same as home address\". */\n toggleLabel: string;\n /** Hide the target fields while mirrored, or show them locked (read-only). */\n behavior: \"hide\" | \"lock\";\n}\n\nexport interface FormSection {\n id: string;\n title?: string;\n description?: string;\n fields: FormFieldDefinition[];\n order: number;\n /**\n * Optional hex color (e.g. \"#ffffff\") applied as inline color to the\n * section's title and description. When unset, the section inherits its\n * color from the form-level `defaultTextColor` or, if that's also unset,\n * from the surrounding CSS cascade.\n */\n textColor?: string;\n /** When set, this section mirrors fields from an earlier section. */\n sameAs?: SectionSameAsConfig;\n}\n\nexport type FormSuccessBehavior = \"message\" | \"replace\" | \"reset\" | \"disable\";\n\nexport interface FormSpamProtectionConfig {\n /** Adds an invisible honeypot field that catches bots. Defaults to true. */\n honeypot?: boolean;\n /** Minimum seconds between mount and submit. Set to 0 to disable. Defaults to 3. */\n minSubmitTime?: number;\n}\n\nexport interface FormSubmitConfig {\n buttonText: string;\n submittingText?: string;\n successMessage: string;\n errorMessage: string;\n successBehavior?: FormSuccessBehavior;\n /**\n * When set, the browser navigates here after a successful submission\n * instead of staying on the page — typically a dedicated thank-you page\n * used for Google Ads conversion tracking. Must be an absolute http(s)\n * URL or a site-relative path (`/thank-you`); see `getSafeRedirectUrl`.\n * Takes precedence over `successBehavior` on real (non-spam) submits.\n */\n redirectUrl?: string;\n spamProtection?: FormSpamProtectionConfig;\n}\n\n/** Field name used for the honeypot. Bots tend to fill anything called \"website\". */\nexport const HONEYPOT_FIELD_NAME = \"_hp_website\";\n\n/** Reserved Formik key for a section's synthetic \"same as\" toggle. Stripped before submit. */\nexport const SAME_AS_TOGGLE_PREFIX = \"_sameAs_\";\nexport const sameAsToggleKey = (sectionId: string): string =>\n `${SAME_AS_TOGGLE_PREFIX}${sectionId}`;\n\n/** Default spam-protection settings (opt-out). */\nexport const DEFAULT_SPAM_PROTECTION: Required<FormSpamProtectionConfig> = {\n honeypot: true,\n minSubmitTime: 3,\n};\n\nexport type FormStylePreset =\n | \"default\"\n | \"minimal\"\n | \"bordered\"\n | \"shadow\"\n | \"card\"\n | \"dark\";\n\nexport type InputVariant = \"outlined\" | \"filled\" | \"underlined\" | \"stacked\";\n\n/**\n * Theme overrides for a form. Every color is OPTIONAL — when unset, the\n * renderer falls back to a baked-in default via CSS `var()` fallbacks. This\n * lets the form builder ship forms that adapt to any consumer site\n * (CastleRents' warm tan, EuroComp's dark, etc.) without the package forcing\n * its own surface color or text color when the user hasn't picked one.\n *\n * The non-color fields (`preset`, `borderRadius`, `spacing`, variants,\n * `sectionDividers`) remain required structural choices and DEFAULT_FORM_STYLE\n * supplies their defaults.\n */\nexport interface FormStyle {\n preset: FormStylePreset;\n borderRadius: \"none\" | \"sm\" | \"md\" | \"lg\" | \"full\";\n spacing: \"compact\" | \"normal\" | \"relaxed\";\n buttonVariant: \"filled\" | \"outline\" | \"ghost\";\n /**\n * Where the submit button renders. \"below\" (default) spans the full form\n * width under the fields; \"inline\" places it in a row beside the fields —\n * suited to single-field forms like a newsletter email + Join button.\n */\n buttonPlacement?: \"below\" | \"inline\";\n sectionDividers: boolean;\n inputVariant: InputVariant;\n\n // Surface\n /** Form container background. Default: transparent (inherits from the page). */\n formBackgroundColor?: string;\n\n // Inputs\n /** Input fill color (used by filled/stacked variants and the floating-label mask). Default: #ffffff. */\n inputBgColor?: string;\n /** Input border color (idle state). Default: #d1d5db. */\n inputBorderColor?: string;\n /** Input border color on focus. Default: #2563eb. */\n inputFocusColor?: string;\n /** Color of the text typed into inputs. Default: inherit from the page. */\n inputTextColor?: string;\n /** Placeholder text color. Default: #9ca3af. */\n placeholderColor?: string;\n\n // Labels / errors\n /** Field label text color. Default: inherit from the page. */\n labelColor?: string;\n /** Color used for error text + error border outline. Default: #ef4444. */\n errorColor?: string;\n\n // Submit button\n /** Submit button background (filled variant) / border + text (outline / ghost). Default: #2563eb. */\n buttonColor?: string;\n /** Submit button text color (filled variant only — outline/ghost use buttonColor). Default: #ffffff. */\n buttonTextColor?: string;\n}\n\n/**\n * Structural defaults only. Colors are intentionally absent — they resolve\n * via the renderer's CSS var fallbacks (see `cssVars.ts`) when the form\n * definition doesn't override them.\n */\nexport const DEFAULT_FORM_STYLE: FormStyle = {\n preset: \"default\",\n borderRadius: \"md\",\n spacing: \"normal\",\n buttonVariant: \"filled\",\n buttonPlacement: \"below\",\n sectionDividers: false,\n inputVariant: \"outlined\",\n};\n\nexport type FieldTransform =\n | \"full\"\n | \"extractFirstName\"\n | \"extractLastName\"\n | \"extractStreet\"\n | \"extractCity\"\n | \"extractState\"\n | \"extractZip\";\n\nexport interface IntegrationFieldMappingEntry {\n /** Form field ID to read the value from */\n field: string;\n /** Optional transform applied to the source value before mapping */\n transform?: FieldTransform;\n}\n\nexport interface FormIntegrationConfig {\n enabled: boolean;\n /** Map of integration destination key (e.g. \"customer.firstName\") → source mapping */\n fieldMapping: Record<string, IntegrationFieldMappingEntry>;\n}\n\nexport type FormIntegrations = Record<string, FormIntegrationConfig>;\n\nexport type FormStatus = \"draft\" | \"published\" | \"archived\";\n\n/**\n * Where the CMS routes a submission for this form.\n *\n * - `contact` (default): writes to the project's `contact-forms` subcollection\n * and surfaces in the Contacts dashboard.\n * - `application`: writes to the project's `applications` subcollection with\n * workflow state (`status`, `assignedTo`, notes, statusHistory) and\n * surfaces in the Applications dashboard.\n * - `newsletter`: writes to the project's `newsletter_subscribers` collection.\n * Newsletter forms are restricted to `email` (required) and `checkbox`\n * (optional, for preferences/consent) fields. Duplicate emails within a\n * project update the existing record's preferences rather than creating\n * a new entry.\n * - `booking`: writes to the project's `bookings` subcollection and surfaces\n * in the Bookings dashboard. The submitted values are stored like an\n * application (nested `data` map), plus a denormalized booking `date`\n * (epoch ms) parsed from the form's designated date field — see\n * {@link FormBookingConfig}.\n *\n * Only the routing changes — spam protection, sensitive field handling,\n * notification emails, and integrations behave identically.\n */\nexport type FormSubmissionType =\n | \"contact\"\n | \"application\"\n | \"newsletter\"\n | \"booking\";\n\n/**\n * Booking settings for a form with `submissionType: \"booking\"`. The renderer\n * is unaffected — booking forms submit exactly like any other form; the CMS\n * submission route uses this config to pull the booking date(s) out of the\n * submitted values.\n *\n * Date-only convention: a `date` field submits `\"yyyy-MM-dd\"`, which parses\n * to UTC midnight, so a stored epoch that is an exact multiple of a day is\n * treated as date-only and displayed in UTC. A `datetime` field submits a\n * full ISO string and is stored as a real instant. An unparseable value is\n * stored as an explicit `null` rather than a fabricated date.\n */\nexport interface FormBookingConfig {\n /**\n * Field id of the `date`/`datetime` field holding the booking date (the\n * start date, when `endDateFieldId` is also set). When omitted, the\n * submission route falls back to the form's first date/datetime field in\n * render order, and then to a top-level `date` key on the submission.\n */\n dateFieldId?: string;\n /**\n * Optional second `date`/`datetime` field id for begin/end bookings.\n * Bookings without an end date use `defaultDurationMinutes` instead.\n */\n endDateFieldId?: string;\n /**\n * Default duration (minutes) stamped onto each new booking. Individual\n * bookings can be overridden afterwards in the Bookings dashboard.\n */\n defaultDurationMinutes?: number;\n}\n\n/**\n * Field types allowed on a newsletter form. Enforced by the form builder UI\n * and (defensively) by the submission route. Keep in sync with\n * `FormSubmissionType === \"newsletter\"` handling.\n */\nexport const NEWSLETTER_ALLOWED_FIELD_TYPES: FieldType[] = [\"email\", \"checkbox\"];\n\n/**\n * Customizable notification email sent to project members when a submission\n * arrives. Both `subject` and `html` support `{{variable}}` interpolation —\n * see `renderEmailTemplate` for the rules. When omitted, the API falls back\n * to the built-in default template.\n */\nexport interface NotificationEmailTemplate {\n subject: string;\n html: string;\n}\n\nexport const DEFAULT_NOTIFICATION_EMAIL_SUBJECT =\n \"New Contact Form: {{name}}\";\n\n/**\n * Default HTML body for the notification email. Mirrors the look of\n * `buildContactNotificationEmail` in the CMS but uses `{{variable}}`\n * placeholders so users can edit it in the form builder.\n */\nexport const DEFAULT_NOTIFICATION_EMAIL_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"UTF-8\" /></head>\n<body style=\"font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;\">\n <div style=\"background: #4f46e5; color: white; padding: 20px; border-radius: 8px 8px 0 0;\">\n <h1 style=\"margin: 0; font-size: 20px;\">New {{formName}} Submission</h1>\n <p style=\"margin: 4px 0 0; opacity: 0.9; font-size: 14px;\">{{projectName}}</p>\n </div>\n <div style=\"border: 1px solid #e5e7eb; border-top: none; padding: 20px; border-radius: 0 0 8px 8px;\">\n <table style=\"width: 100%; border-collapse: collapse;\">\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; width: 120px; vertical-align: top;\">Name:</td>\n <td style=\"padding: 8px 0;\">{{name}}</td>\n </tr>\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; vertical-align: top;\">Email:</td>\n <td style=\"padding: 8px 0;\"><a href=\"mailto:{{email}}\">{{email}}</a></td>\n </tr>\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; vertical-align: top;\">Phone:</td>\n <td style=\"padding: 8px 0;\"><a href=\"tel:{{phone}}\">{{phone}}</a></td>\n </tr>\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; vertical-align: top;\">Message:</td>\n <td style=\"padding: 8px 0;\">{{message}}</td>\n </tr>\n </table>\n <hr style=\"border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;\" />\n <p style=\"font-size: 12px; color: #9ca3af; margin: 0;\">\n Sent via VulcanTech CMS &middot; <a href=\"https://cms.vulcantech.io\">Dashboard</a>\n </p>\n </div>\n</body>\n</html>`;\n\nexport const DEFAULT_NOTIFICATION_EMAIL_TEMPLATE: NotificationEmailTemplate = {\n subject: DEFAULT_NOTIFICATION_EMAIL_SUBJECT,\n html: DEFAULT_NOTIFICATION_EMAIL_HTML,\n};\n\n/**\n * The set of workflow states an application can be in. Mirrors\n * `ApplicationStatus` in apps/vulcantech-cms/src/types/APPLICATION.ts — duplicated\n * here so the forms package (which is consumed by both the CMS server and\n * client apps) can describe per-status email templates without importing\n * from the CMS app.\n */\nexport type ApplicationStatusKey =\n | \"received\"\n | \"reviewing\"\n | \"approved\"\n | \"denied\"\n | \"pending-documents\"\n | \"withdrawn\";\n\nexport const APPLICATION_STATUS_KEYS: ApplicationStatusKey[] = [\n \"received\",\n \"reviewing\",\n \"approved\",\n \"denied\",\n \"pending-documents\",\n \"withdrawn\",\n];\n\n/**\n * Per-status applicant-facing email template. Keyed by `ApplicationStatusKey`.\n * Missing entries fall back to {@link DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES}.\n *\n * These templates are RENDERED with the same `renderEmailTemplate` engine as\n * the admin notification template, but the available variables are\n * application-centric: `{{referenceNumber}}`, `{{applicantName}}`,\n * `{{status}}`, `{{requestedDocuments}}` (only when status is\n * `pending-documents`), plus any form-field values that match the\n * applicant's submission.\n */\nexport type ApplicationStatusEmailTemplates = Partial<\n Record<ApplicationStatusKey, NotificationEmailTemplate>\n>;\n\n/**\n * HTML body shared by every default status template — same chrome as the\n * admin notification email but with applicant-centric copy in the middle.\n * Placeholders: `{{status}}`, `{{statusLabel}}`, `{{statusMessage}}`,\n * `{{referenceNumber}}`, `{{applicantName}}`, `{{projectName}}`,\n * `{{formName}}`, and (only for pending-documents) `{{requestedDocuments}}`.\n */\nfunction buildDefaultStatusEmailHtml(bodyHtml: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"UTF-8\" /></head>\n<body style=\"font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;\">\n <div style=\"background: #4f46e5; color: white; padding: 20px; border-radius: 8px 8px 0 0;\">\n <h1 style=\"margin: 0; font-size: 20px;\">{{projectName}}</h1>\n <p style=\"margin: 4px 0 0; opacity: 0.9; font-size: 14px;\">Application update</p>\n </div>\n <div style=\"border: 1px solid #e5e7eb; border-top: none; padding: 20px; border-radius: 0 0 8px 8px;\">\n <p style=\"margin-top: 0;\">Hi {{applicantName}},</p>\n ${bodyHtml}\n <p style=\"font-size: 13px; color: #6b7280; margin: 20px 0 0;\">\n Reference number: <strong style=\"font-family: monospace;\">{{referenceNumber}}</strong>\n </p>\n <hr style=\"border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;\" />\n <p style=\"font-size: 12px; color: #9ca3af; margin: 0;\">\n This is an automated message from {{projectName}}.\n </p>\n </div>\n</body>\n</html>`;\n}\n\nexport const DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES: Record<\n ApplicationStatusKey,\n NotificationEmailTemplate\n> = {\n received: {\n subject: \"We've received your application — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Thanks for applying to {{projectName}}. We've received your submission and our team will be in touch as it moves through review.</p>`,\n ),\n },\n reviewing: {\n subject: \"Your application is under review — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Good news — your application has moved into active review. We'll reach out as soon as a decision is made or we need anything else from you.</p>`,\n ),\n },\n approved: {\n subject: \"Your application has been approved — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Congratulations — your application has been <strong style=\"color: #047857;\">approved</strong>. We'll follow up shortly with next steps.</p>`,\n ),\n },\n denied: {\n subject: \"Update on your application — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Thank you for taking the time to apply to {{projectName}}. After review, we won't be moving forward with your application at this time.</p>\n <p>We appreciate your interest and wish you the best.</p>`,\n ),\n },\n \"pending-documents\": {\n subject: \"Additional documents needed — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>To continue reviewing your application we need a few more documents from you:</p>\n <div style=\"white-space: pre-wrap; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin: 12px 0; font-size: 14px;\">{{requestedDocuments}}</div>\n <p>Reply to this email with the requested items and we'll resume review as soon as they arrive.</p>`,\n ),\n },\n withdrawn: {\n subject: \"Your application has been withdrawn — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Per request, your application to {{projectName}} has been withdrawn. If this wasn't expected, please reply and let us know.</p>`,\n ),\n },\n};\n\n/**\n * The CMS-authored schema for one form — the value `DynamicForm` renders and\n * the CMS submission route consults to route and validate a submission.\n *\n * Consumer sites fetch this from `GET /api/forms` rather than building it.\n * Four fields are stripped from every client-facing response by the CMS\n * (`stripSensitiveFields`) and are therefore always `undefined` outside the\n * CMS server: `projectId`, `integrations`, `notificationEmailTemplate`, and\n * `applicationStatusEmails`.\n */\nexport interface FormDefinition {\n id: string;\n /**\n * Server-only project owner. The CMS stores this in Firestore and uses it\n * internally (to scope writes, build cache tags, address integration\n * configs), but it is stripped from every client-facing response by\n * `stripSensitiveFields` before reaching consumer apps. Client code MUST\n * NOT depend on this field — resolve projectId from a server-side env var\n * (`VULCANTECH_PROJECT_ID`) in proxy/fetch routes instead.\n */\n projectId?: string;\n name: string;\n /** Unique within a project — the CMS rejects a colliding slug with a 409. */\n slug: string;\n description?: string;\n /** Bumped on every CMS edit. Emitted by the renderer as `data-form-version`. */\n version: number;\n /**\n * FormStatus values: \"draft\" | \"published\" | \"archived\".\n *\n * Deliberately typed `string`, not the {@link FormStatus} union, because\n * definitions cross a JSON boundary. Compare against the literals. The\n * public GET route already filters to published forms unless the caller\n * passes `includeDrafts=1`.\n */\n status: string;\n /**\n * Routes submissions to the matching dashboard collection.\n * Defaults to `\"contact\"` when omitted. See {@link FormSubmissionType}.\n *\n * Read server-side from this definition, never from the request body — a\n * submission whose `formId` does not resolve always routes to `contact`.\n */\n submissionType?: FormSubmissionType;\n /**\n * Booking settings. Only consulted when `submissionType === \"booking\"`.\n * See {@link FormBookingConfig}.\n */\n bookingConfig?: FormBookingConfig;\n /** Rendered in `order`, not array order — the renderer sorts before rendering. */\n sections: FormSection[];\n submitConfig: FormSubmitConfig;\n /** Absent = {@link DEFAULT_FORM_STYLE} (structure only; colors stay unset). */\n style?: FormStyle;\n /**\n * Optional hex color applied as the default text color for every section\n * header and description. Per-section `textColor` overrides this. When\n * unset, sections inherit from the surrounding CSS cascade (useful when\n * the form is embedded on a page with its own typography).\n */\n defaultTextColor?: string;\n metadata?: {\n trackAdReferral?: boolean;\n customFields?: Record<string, unknown>;\n };\n /** Server-only — stripped from client-facing responses like `projectId`. */\n integrations?: FormIntegrations;\n /**\n * Customizable email sent to project members when a submission arrives.\n * Falls back to `DEFAULT_NOTIFICATION_EMAIL_TEMPLATE` when undefined.\n *\n * Server-only — stripped from client-facing responses like `projectId`.\n */\n notificationEmailTemplate?: NotificationEmailTemplate;\n /**\n * Per-status applicant-facing email templates. Only consulted when\n * `submissionType === \"application\"`. Server-only — stripped from\n * client-facing responses like `projectId`. Missing entries fall back to\n * `DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES[status]`. Set to an empty\n * object to opt every status into the defaults explicitly.\n */\n applicationStatusEmails?: ApplicationStatusEmailTemplates;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n}\n\n/**\n * JSON-friendly mirror of {@link FormDefinition}.\n *\n * `FormDefinition` keeps narrow string-literal unions (e.g. `FieldType`,\n * `FormStylePreset`, `FormSuccessBehavior`) for editor autocomplete and\n * exhaustive-switch safety inside this package. But when a definition\n * crosses a JSON boundary — `JSON.parse`, an `await res.json()` on an ISR\n * fetch, a Firestore document, or a literal object pasted into source —\n * TypeScript widens the string values to `string`, which fails to match\n * the narrow unions and forces every consumer to cast.\n *\n * Use `FormDefinitionJSON` as the type of the raw JSON value, then call\n * {@link parseFormDefinition} (or assert it yourself) when you need the\n * strict shape:\n *\n * ```ts\n * const json = (await res.json()) as FormDefinitionJSON;\n * const definition = parseFormDefinition(json);\n * ```\n *\n * Structurally, `FormDefinition` is assignable to `FormDefinitionJSON`,\n * so values you've already validated flow back into JSON-typed slots\n * without a cast.\n */\nexport interface ValidationRuleJSON {\n // ValidationRuleType values: \"required\" | \"min\" | \"max\" | \"minLength\" | \"maxLength\" | \"pattern\" | \"email\" | \"phone\"\n type: string;\n value?: string | number | boolean;\n message: string;\n}\n\nexport interface SensitiveFieldConfigJSON {\n /** Days until the encrypted record auto-deletes. Defaults to 30. */\n ttlDays: number;\n viewerRoles: string[];\n /** Currently only `ssn` is implemented. */\n inputMask?: string;\n}\n\nexport interface FormFieldDefinitionJSON {\n id: string;\n // FieldType values: \"text\" | \"email\" | \"phone\" | \"url\" | \"address\" | \"textarea\" | \"select\" | \"checkbox\" | \"radio\" | \"number\" | \"date\" | \"datetime\" | \"hidden\" | \"sensitive\"\n type: string;\n label: string;\n placeholder?: string;\n helpText?: string;\n description?: string;\n defaultValue?: string;\n // TextTransform values: \"capitalize-sentences\" | \"capitalize-words\" | \"phone-number\" | \"ssn\"\n transform?: string;\n validation: ValidationRuleJSON[];\n options?: FieldOption[];\n layout?: {\n // FieldWidth values: \"full\" | \"half\" | \"third\"\n width: string;\n order: number;\n };\n characterCounter?: boolean;\n rows?: number;\n datetimeConfig?: DatetimeConfig;\n showWhen?: FieldVisibilityCondition;\n sensitiveConfig?: SensitiveFieldConfigJSON;\n}\n\nexport interface FormSectionJSON {\n id: string;\n title?: string;\n description?: string;\n fields: FormFieldDefinitionJSON[];\n order: number;\n textColor?: string;\n sameAs?: SectionSameAsConfig;\n}\n\nexport interface FormStyleJSON {\n // FormStylePreset values: \"default\" | \"minimal\" | \"bordered\" | \"shadow\" | \"card\" | \"dark\"\n preset: string;\n // \"none\" | \"sm\" | \"md\" | \"lg\" | \"full\"\n borderRadius: string;\n // \"compact\" | \"normal\" | \"relaxed\"\n spacing: string;\n // \"filled\" | \"outline\" | \"ghost\"\n buttonVariant: string;\n // \"below\" | \"inline\"\n buttonPlacement?: string;\n sectionDividers: boolean;\n // InputVariant values: \"outlined\" | \"filled\" | \"underlined\" | \"stacked\"\n inputVariant: string;\n formBackgroundColor?: string;\n inputBgColor?: string;\n inputBorderColor?: string;\n inputFocusColor?: string;\n inputTextColor?: string;\n placeholderColor?: string;\n labelColor?: string;\n errorColor?: string;\n buttonColor?: string;\n buttonTextColor?: string;\n}\n\nexport interface FormSubmitConfigJSON {\n buttonText: string;\n submittingText?: string;\n successMessage: string;\n errorMessage: string;\n // FormSuccessBehavior values: \"message\" | \"replace\" | \"reset\" | \"disable\"\n successBehavior?: string;\n redirectUrl?: string;\n spamProtection?: FormSpamProtectionConfig;\n}\n\nexport interface IntegrationFieldMappingEntryJSON {\n field: string;\n // FieldTransform values: \"full\" | \"extractFirstName\" | \"extractLastName\" | \"extractStreet\" | \"extractCity\" | \"extractState\" | \"extractZip\"\n transform?: string;\n}\n\nexport interface FormIntegrationConfigJSON {\n enabled: boolean;\n fieldMapping: Record<string, IntegrationFieldMappingEntryJSON>;\n}\n\nexport type FormIntegrationsJSON = Record<string, FormIntegrationConfigJSON>;\n\nexport interface FormDefinitionJSON {\n id: string;\n /** See {@link FormDefinition.projectId} — server-only, optional at the JSON boundary. */\n projectId?: string;\n name: string;\n slug: string;\n description?: string;\n version: number;\n // FormStatus values: \"draft\" | \"published\" | \"archived\"\n status: string;\n // FormSubmissionType values: \"contact\" | \"application\" | \"newsletter\" | \"booking\"\n submissionType?: string;\n /** See {@link FormDefinition.bookingConfig} — no narrowed unions, so the strict type is reused. */\n bookingConfig?: FormBookingConfig;\n sections: FormSectionJSON[];\n submitConfig: FormSubmitConfigJSON;\n style?: FormStyleJSON;\n defaultTextColor?: string;\n metadata?: {\n trackAdReferral?: boolean;\n customFields?: Record<string, unknown>;\n };\n integrations?: FormIntegrationsJSON;\n notificationEmailTemplate?: NotificationEmailTemplate;\n /** See {@link FormDefinition.applicationStatusEmails}. */\n applicationStatusEmails?: ApplicationStatusEmailTemplates;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n}\n\n/**\n * Narrow a `FormDefinitionJSON` to the strict {@link FormDefinition} type.\n *\n * This is a structural cast — it trusts that the JSON was produced by the\n * CMS (or another well-formed source) and does not validate individual\n * enum values. Use it at trust boundaries where you've already verified\n * the source. For untrusted JSON, validate explicitly (e.g. with Yup or\n * Zod) before treating the result as a `FormDefinition`.\n */\nexport function parseFormDefinition(json: FormDefinitionJSON): FormDefinition {\n return json as unknown as FormDefinition;\n}\n","import type { FieldVisibilityCondition } from \"../types\";\n\n/**\n * Evaluate a field's `showWhen` condition against the current form values.\n *\n * This is the single source of truth for conditional visibility — the\n * renderer (show/hide), the Yup schema (skip validation while hidden), the\n * submit payload (strip hidden values), and the CMS's server-side submission\n * validation must all agree, so they all call this.\n *\n * Operators:\n * - `equals` (default) / `not-equals`: strict comparison, matching the\n * original behavior.\n * - `greater-than` / `less-than`: numeric comparison. Both the watched value\n * and the condition value are parsed as numbers; if either side isn't\n * numeric (empty input, non-number text, booleans), the condition is unmet\n * and the dependent field stays hidden.\n *\n * @param condition - The field's `showWhen` config.\n * @param watchedValue - Current value of `condition.fieldId`.\n * @returns True when the dependent field should be visible.\n */\nexport function isVisibilityConditionMet(\n condition: FieldVisibilityCondition,\n watchedValue: unknown,\n): boolean {\n const operator = condition.operator ?? \"equals\";\n\n switch (operator) {\n case \"greater-than\":\n case \"less-than\": {\n if (typeof watchedValue === \"boolean\") return false;\n const actual =\n typeof watchedValue === \"number\"\n ? watchedValue\n : parseFloat(String(watchedValue ?? \"\"));\n const expected = parseFloat(String(condition.value));\n if (Number.isNaN(actual) || Number.isNaN(expected)) return false;\n return operator === \"greater-than\"\n ? actual > expected\n : actual < expected;\n }\n case \"not-equals\":\n return watchedValue !== condition.value;\n case \"equals\":\n default:\n return watchedValue === condition.value;\n }\n}\n","import * as Yup from \"yup\";\nimport type { FormDefinition, FormFieldDefinition, ValidationRule } from \"../types\";\nimport { sameAsToggleKey } from \"../types\";\nimport { isVisibilityConditionMet } from \"../utils/visibility\";\n\nfunction getBaseSchema(field: FormFieldDefinition): Yup.AnySchema {\n switch (field.type) {\n case \"number\":\n // An untouched <input type=\"number\"> submits \"\" — without this\n // transform Yup casts that to NaN and throws the typeError even for\n // OPTIONAL number fields, making the form unsubmittable.\n return Yup.number()\n .transform((value, original) =>\n original === \"\" || original === null ? undefined : value,\n )\n .typeError(`${field.label} must be a number`);\n case \"checkbox\":\n return Yup.boolean();\n case \"url\":\n return Yup.string().url(`${field.label} must be a valid URL`);\n case \"datetime\":\n return Yup.string();\n case \"select\":\n case \"radio\": {\n // Constrain choice fields to their defined options so a tampered\n // payload can't carry arbitrary values. \"\" is the untouched state and\n // must stay valid for optional fields; `required` still rejects it.\n const allowed = (field.options ?? []).map((o) => o.value);\n if (allowed.length === 0) return Yup.string();\n return Yup.string().oneOf(\n [...allowed, \"\"],\n `${field.label} has an invalid selection`,\n );\n }\n case \"sensitive\": {\n let schema = Yup.string();\n // The builder keeps the ssn input mask and the ssn transform in\n // lockstep, but honor either so older definitions still validate.\n if (\n field.sensitiveConfig?.inputMask === \"ssn\" ||\n field.transform === \"ssn\"\n ) {\n schema = schema.matches(\n /^\\d{3}-\\d{2}-\\d{4}$/,\n `${field.label} must be a valid Social Security number`\n );\n }\n return schema;\n }\n case \"file\":\n // File field value is a URL string (single) or array of URL strings (multiple)\n if (field.fileConfig?.multiple) {\n return Yup.array()\n .of(Yup.string().url())\n .default([]);\n }\n return Yup.string();\n default:\n return Yup.string();\n }\n}\n\nfunction applyValidationRule(\n schema: Yup.AnySchema,\n rule: ValidationRule,\n field: FormFieldDefinition\n): Yup.AnySchema {\n switch (rule.type) {\n case \"required\":\n // For checkboxes, `.required()` alone is useless — `false` is a\n // present value and passes it. A required checkbox (consent box)\n // additionally demands the value be `true`.\n if (field.type === \"checkbox\" && schema instanceof Yup.BooleanSchema) {\n return schema.required(rule.message).oneOf([true], rule.message);\n }\n return schema.required(rule.message);\n\n case \"email\":\n if (schema instanceof Yup.StringSchema) {\n return schema.email(rule.message);\n }\n return schema;\n\n case \"phone\":\n if (schema instanceof Yup.StringSchema) {\n return schema.matches(\n /^[\\d\\s\\-()+ .]+$/,\n rule.message\n );\n }\n return schema;\n\n case \"min\":\n if (schema instanceof Yup.NumberSchema && typeof rule.value === \"number\") {\n return schema.min(rule.value, rule.message);\n }\n return schema;\n\n case \"max\":\n if (schema instanceof Yup.NumberSchema && typeof rule.value === \"number\") {\n return schema.max(rule.value, rule.message);\n }\n return schema;\n\n case \"minLength\":\n if (schema instanceof Yup.StringSchema && typeof rule.value === \"number\") {\n return schema.min(rule.value, rule.message);\n }\n return schema;\n\n case \"maxLength\":\n if (schema instanceof Yup.StringSchema && typeof rule.value === \"number\") {\n return schema.max(rule.value, rule.message);\n }\n return schema;\n\n case \"pattern\":\n if (schema instanceof Yup.StringSchema && typeof rule.value === \"string\") {\n // A malformed regex typed in the builder must not crash the whole\n // form at render time — skip the rule instead.\n try {\n return schema.matches(new RegExp(rule.value), rule.message);\n } catch {\n console.warn(\n `[forms] Invalid pattern for field \"${field.id}\": ${rule.value}`,\n );\n return schema;\n }\n }\n return schema;\n\n case \"notEquals\":\n if (schema instanceof Yup.StringSchema && rule.value !== undefined) {\n return schema.notOneOf([String(rule.value)], rule.message);\n }\n if (schema instanceof Yup.NumberSchema && typeof rule.value === \"number\") {\n return schema.notOneOf([rule.value], rule.message);\n }\n return schema;\n\n default:\n return schema;\n }\n}\n\nexport function buildYupSchema(definition: FormDefinition): Yup.ObjectSchema<Record<string, unknown>> {\n const shape: Record<string, Yup.AnySchema> = {};\n\n for (const section of definition.sections) {\n // Fields mirrored-and-hidden by a \"same as\" toggle must not block submit\n // (they carry a copied value but are invisible). Exempt them while the\n // toggle is on, mirroring the showWhen pattern below.\n const hideToggleKey =\n section.sameAs?.behavior === \"hide\"\n ? sameAsToggleKey(section.id)\n : null;\n const hiddenTargetIds = hideToggleKey\n ? new Set(Object.keys(section.sameAs!.fieldMap))\n : null;\n\n for (const field of section.fields) {\n let schema = getBaseSchema(field);\n\n for (const rule of field.validation) {\n schema = applyValidationRule(schema, rule, field);\n }\n\n const baseSchema = getBaseSchema(field);\n\n if (field.showWhen) {\n const condition = field.showWhen;\n shape[field.id] = Yup.mixed().when(condition.fieldId, {\n is: (value: unknown) => isVisibilityConditionMet(condition, value),\n then: () => schema,\n otherwise: () => baseSchema.notRequired(),\n });\n } else if (hideToggleKey && hiddenTargetIds?.has(field.id)) {\n shape[field.id] = Yup.mixed().when(hideToggleKey, {\n is: true,\n then: () => baseSchema.notRequired(),\n otherwise: () => schema,\n });\n } else {\n shape[field.id] = schema;\n }\n }\n }\n\n return Yup.object().shape(shape);\n}\n","import type { FormDefinition } from \"../types\";\nimport { sameAsToggleKey } from \"../types\";\n\nexport function buildInitialValues(definition: FormDefinition): Record<string, string | boolean | string[]> {\n const values: Record<string, string | boolean | string[]> = {};\n\n for (const section of definition.sections) {\n // Synthetic \"same as\" toggle starts unchecked.\n if (section.sameAs) values[sameAsToggleKey(section.id)] = false;\n for (const field of section.fields) {\n if (field.type === \"checkbox\") {\n values[field.id] = field.defaultValue === \"true\";\n } else if (field.type === \"datetime\") {\n values[field.id] = field.defaultValue || \"\";\n } else if (field.type === \"sensitive\") {\n values[field.id] = \"\";\n } else if (field.type === \"file\") {\n // File fields store URL(s) after upload — start empty\n values[field.id] = field.fileConfig?.multiple ? [] : \"\";\n } else {\n values[field.id] = field.defaultValue || \"\";\n }\n }\n }\n\n return values;\n}\n","import type { FieldTransform } from \"../types\";\n\n/**\n * Apply a field transform to a string value before passing it to an\n * integration. Used by integration adapters to derive things like\n * \"first name\" from a single \"Full Name\" field, or to split an address\n * into its components.\n *\n * @param value - The raw form field value.\n * @param transform - The transform to apply. Falsy or \"full\" returns the\n * value unchanged.\n * @returns The transformed value, or an empty string if the transform\n * could not produce a result.\n */\nexport function applyTransform(\n value: string,\n transform?: FieldTransform\n): string {\n if (!value) return \"\";\n if (!transform || transform === \"full\") return value;\n\n switch (transform) {\n case \"extractFirstName\":\n return value.trim().split(/\\s+/)[0] || value;\n case \"extractLastName\": {\n const parts = value.trim().split(/\\s+/);\n return parts.length > 1 ? parts.slice(1).join(\" \") : \"\";\n }\n case \"extractStreet\":\n case \"extractCity\":\n case \"extractState\":\n case \"extractZip\":\n return extractAddressPart(value, transform);\n default:\n return value;\n }\n}\n\n/**\n * Naive US-address splitter. Expects roughly:\n * \"123 Main St, Phoenix, AZ 85001\"\n *\n * - street → everything before the first comma\n * - city → between the first and second commas\n * - state → first whitespace-separated token after the second comma\n * - zip → second whitespace-separated token after the second comma\n *\n * Returns an empty string if the input doesn't have enough parts to\n * satisfy the requested piece.\n */\nfunction extractAddressPart(\n value: string,\n transform: \"extractStreet\" | \"extractCity\" | \"extractState\" | \"extractZip\"\n): string {\n const parts = value.split(\",\").map((p) => p.trim());\n\n if (transform === \"extractStreet\") return parts[0] ?? \"\";\n if (transform === \"extractCity\") return parts[1] ?? \"\";\n\n const tail = (parts[2] ?? \"\").split(/\\s+/).filter(Boolean);\n if (transform === \"extractState\") return tail[0] ?? \"\";\n if (transform === \"extractZip\") return tail.slice(1).join(\" \") || \"\";\n\n return \"\";\n}\n","/**\n * Validate a configured post-submit redirect target.\n *\n * Accepts absolute http(s) URLs and site-relative paths (`/thank-you`).\n * Anything else — `javascript:`/`data:` schemes, protocol-relative\n * `//host` values, unparseable strings — returns `null` so the caller\n * falls back to the normal on-page success behavior. Shared by the\n * renderer (before navigating) and the CMS save endpoint (before\n * persisting) so both enforce the same rule.\n *\n * @param raw - The `submitConfig.redirectUrl` value as authored/stored.\n * @returns The trimmed URL when it is safe to navigate to, otherwise `null`.\n */\nexport function getSafeRedirectUrl(\n raw: string | null | undefined,\n): string | null {\n if (typeof raw !== \"string\") return null;\n const url = raw.trim();\n if (!url) return null;\n if (url.startsWith(\"/\") && !url.startsWith(\"//\")) return url;\n try {\n const parsed = new URL(url);\n if (parsed.protocol === \"http:\" || parsed.protocol === \"https:\") {\n return url;\n }\n } catch {\n // Not an absolute URL and not a site-relative path — reject below.\n }\n return null;\n}\n","import type { TextTransform } from \"../types\";\n\n/**\n * Formats raw digits as a US Social Security number (NNN-NN-NNNN).\n * Truncates anything past 9 digits.\n */\nexport function formatSsn(raw: string): string {\n const digits = raw.replace(/\\D/g, \"\").slice(0, 9);\n if (digits.length <= 3) return digits;\n if (digits.length <= 5) return `${digits.slice(0, 3)}-${digits.slice(3)}`;\n return `${digits.slice(0, 3)}-${digits.slice(3, 5)}-${digits.slice(5)}`;\n}\n\n/**\n * Formats raw digits as a US phone number: (555) 123 - 4567.\n * Strips a leading \"1\" country code from 11-digit pastes like\n * \"+1 (555) 123-4567\" and truncates anything past 10 digits so\n * oversized values don't dead-end the input.\n */\nexport function formatUsPhone(raw: string): string {\n const digits = raw.replace(/[^\\d]/g, \"\");\n const onlyNums = (\n digits.length === 11 && digits.startsWith(\"1\") ? digits.slice(1) : digits\n ).slice(0, 10);\n\n if (onlyNums.length > 6) {\n return `(${onlyNums.slice(0, 3)}) ${onlyNums.slice(3, 6)} - ${onlyNums.slice(6, 10)}`;\n }\n if (onlyNums.length > 3) {\n return `(${onlyNums.slice(0, 3)}) ${onlyNums.slice(3)}`;\n }\n if (onlyNums.length > 0) {\n return `(${onlyNums}`;\n }\n return \"\";\n}\n\n/**\n * Apply a `TextTransform` to a field value as the user types. Shared by the\n * free-text field renderers so every field type honors the transform picked\n * in the builder, and so the `ssn` transform and the sensitive `ssn` input\n * mask always produce identical output.\n *\n * @param value - The current input value.\n * @param transform - The transform configured on the field definition.\n * @returns The transformed value; unrecognized or absent transforms return\n * the value unchanged.\n */\nexport function applyTextTransform(\n value: string,\n transform?: TextTransform\n): string {\n switch (transform) {\n case \"capitalize-sentences\":\n return value.replace(/(^|\\. *)([a-z])/g, (letter) =>\n letter.toUpperCase()\n );\n case \"capitalize-words\":\n return value.replace(/^([a-z])|\\s+([a-z])/g, (letter) =>\n letter.toUpperCase()\n );\n case \"phone-number\":\n return formatUsPhone(value);\n case \"ssn\":\n return formatSsn(value);\n default:\n return value;\n }\n}\n","import type { FormDefinition, NotificationEmailTemplate } from \"../types\";\n\n/**\n * Variables available to a notification email template. Beyond the canonical\n * keys here, the renderer also accepts arbitrary form-field IDs / labels\n * looked up from the form definition (see `buildEmailTemplateVariables`).\n */\nexport interface EmailTemplateVariables {\n /** Project (site) display name. */\n projectName: string;\n /** Form display name (e.g. \"Contact Form\"). */\n formName: string;\n /** Submission timestamp as an ISO string. */\n submittedAt: string;\n /** Anything else the form sends — keyed by field id, label-slug, or canonical key. */\n [key: string]: string | number | boolean | undefined;\n}\n\n/** HTML-escape a value before substituting it into a template. */\nfunction escapeHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n return String(value)\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Replace `{{key}}` placeholders in `template` with values from `variables`.\n * Unknown keys are replaced with an empty string. Whitespace inside the\n * braces is tolerated (`{{ name }}` works the same as `{{name}}`). Values\n * are HTML-escaped by default; pass `{ escape: false }` to interpolate into\n * non-HTML targets like the email subject line.\n */\nexport function renderEmailTemplate(\n template: string,\n variables: EmailTemplateVariables,\n options: { escape?: boolean } = {},\n): string {\n const shouldEscape = options.escape !== false;\n return template.replace(/\\{\\{\\s*([\\w.-]+)\\s*\\}\\}/g, (_match, key: string) => {\n const value = variables[key];\n if (value === undefined || value === null || value === \"\") return \"\";\n return shouldEscape ? escapeHtml(value) : String(value);\n });\n}\n\n/**\n * Build the variable bag handed to `renderEmailTemplate` from a form\n * definition + raw submission payload. Each form field is exposed under its\n * `id` and (when distinct) under a slugified version of its `label`, so\n * authors can reference fields with either `{{customer_name_1234}}` or\n * `{{customer_name}}`.\n */\nexport function buildEmailTemplateVariables(args: {\n definition?: Pick<FormDefinition, \"name\" | \"sections\">;\n projectName: string;\n formName?: string;\n submission: Record<string, unknown>;\n submittedAt?: string;\n}): EmailTemplateVariables {\n const { definition, projectName, submission, submittedAt } = args;\n\n const vars: EmailTemplateVariables = {\n projectName,\n formName: args.formName ?? definition?.name ?? \"Contact Form\",\n submittedAt: submittedAt ?? new Date().toISOString(),\n };\n\n // Pass through every primitive value on the submission directly so canonical\n // keys (`name`, `email`, `phone`, `message`, `serviceType`, …) just work.\n for (const [key, value] of Object.entries(submission)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n vars[key] = value;\n }\n }\n\n // Also expose each defined field by a label-slug alias (e.g. \"Full Name\" →\n // \"full_name\") so authors don't need to remember opaque field IDs.\n if (definition?.sections) {\n for (const section of definition.sections) {\n for (const field of section.fields) {\n const value = submission[field.id];\n if (value === undefined || value === null) continue;\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n ) {\n continue;\n }\n const slug = labelToSlug(field.label);\n if (slug && vars[slug] === undefined) vars[slug] = value;\n }\n }\n }\n\n return vars;\n}\n\n/** Lowercase, alnum + underscore form of a field label — `\"Full Name\" → \"full_name\"`. */\nfunction labelToSlug(label: string): string {\n return label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n}\n\n/**\n * Variable descriptor used by the dashboard editor to render the \"Insert\n * variable\" picker. Order is informational; renderers don't depend on it.\n */\nexport interface EmailTemplateVariableDescriptor {\n key: string;\n description: string;\n example: string;\n}\n\nexport const CORE_EMAIL_TEMPLATE_VARIABLES: EmailTemplateVariableDescriptor[] =\n [\n {\n key: \"projectName\",\n description: \"Project (site) display name.\",\n example: \"Acme Co.\",\n },\n {\n key: \"formName\",\n description: \"Name of the form that was submitted.\",\n example: \"Contact Form\",\n },\n {\n key: \"submittedAt\",\n description: \"Submission timestamp (ISO 8601).\",\n example: new Date().toISOString(),\n },\n {\n key: \"name\",\n description: \"Submitter's name.\",\n example: \"Jane Doe\",\n },\n {\n key: \"email\",\n description: \"Submitter's email.\",\n example: \"jane@example.com\",\n },\n {\n key: \"phone\",\n description: \"Submitter's phone (if collected).\",\n example: \"555-123-4567\",\n },\n {\n key: \"message\",\n description: \"Free-text message body (if collected).\",\n example: \"I'd like to schedule a consultation.\",\n },\n {\n key: \"serviceType\",\n description: \"Selected service / category (if collected).\",\n example: \"Roof Repair\",\n },\n ];\n\n/**\n * Sample submission used to populate the editor's preview pane. Mirrors the\n * canonical keys most contact forms collect.\n */\nexport const SAMPLE_EMAIL_TEMPLATE_VARIABLES: EmailTemplateVariables = {\n projectName: \"Acme Co.\",\n formName: \"Contact Form\",\n submittedAt: new Date().toISOString(),\n name: \"Jane Doe\",\n email: \"jane@example.com\",\n phone: \"555-123-4567\",\n message: \"I'd like to schedule a consultation about your services.\",\n serviceType: \"Roof Repair\",\n};\n\n/** Convenience: render both subject + body of a template in one pass. */\nexport function renderNotificationEmail(\n template: NotificationEmailTemplate,\n variables: EmailTemplateVariables,\n): { subject: string; html: string } {\n // Subjects are plain text (no HTML escaping), but interpolated values are\n // user-submitted — flatten newlines so they can't smuggle extra headers\n // into a naive mailer.\n const subject = renderEmailTemplate(template.subject, variables, {\n escape: false,\n }).replace(/[\\r\\n]+/g, \" \");\n return {\n subject,\n html: renderEmailTemplate(template.html, variables),\n };\n}\n","/**\n * Client-side encryption utilities for sensitive form fields.\n *\n * Hybrid encryption scheme:\n * 1. The browser fetches a transport public key (RSA-OAEP, 2048-bit) from\n * the server. The matching private key never leaves the server.\n * 2. For each sensitive field we generate a fresh AES-GCM-256 data key,\n * encrypt the plaintext with it, then wrap the data key with the RSA\n * public key. Both ciphertexts plus the IV travel to the server.\n * 3. The server unwraps the data key with its private key, decrypts the\n * plaintext, then re-encrypts with Google Cloud KMS for storage.\n *\n * The plaintext SSN (or other sensitive value) therefore never appears on\n * the wire in cleartext beyond TLS — even an attacker with access to the\n * Next.js request body would see only ciphertext.\n */\n\n/** Wire-format for an encrypted sensitive field value. */\nexport interface EncryptedSensitiveValue {\n /** Schema marker. Always \"v1\". */\n v: \"v1\";\n /** Identifier of the transport key used (matches server kid). */\n kid: string;\n /** Base64 RSA-OAEP-wrapped AES key. */\n wrappedKey: string;\n /** Base64 AES-GCM IV (12 bytes). */\n iv: string;\n /** Base64 AES-GCM ciphertext + auth tag. */\n ciphertext: string;\n /** Plaintext last-4 digits for display. Safe to store unencrypted. */\n last4: string;\n}\n\n/** JWK payload returned by the transport-key endpoint. */\nexport interface TransportPublicKey {\n kid: string;\n jwk: JsonWebKey;\n}\n\nfunction bufferToBase64(buf: ArrayBuffer): string {\n const bytes = new Uint8Array(buf);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i += 1) {\n binary += String.fromCharCode(bytes[i]);\n }\n // `btoa` is globally available in browsers and in Node 16+. The forms\n // package targets that environment everywhere it runs, so we don't fall\n // back to a Node-specific `Buffer` API.\n return btoa(binary);\n}\n\nfunction base64ToBuffer(b64: string): ArrayBuffer {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes.buffer;\n}\n\n/**\n * Imports a server-supplied JWK as an RSA-OAEP public key for wrapping.\n */\nasync function importTransportPublicKey(jwk: JsonWebKey): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"jwk\",\n jwk,\n { name: \"RSA-OAEP\", hash: \"SHA-256\" },\n false,\n [\"wrapKey\", \"encrypt\"]\n );\n}\n\n/**\n * Encrypt a single plaintext value using the supplied transport public key.\n * Returns the wire-format payload that the server expects.\n *\n * @param plaintext The cleartext value to encrypt (e.g. a Social Security\n * number). Must be a non-empty string.\n * @param publicKey Transport key descriptor previously fetched from the\n * server's transport-key endpoint.\n */\nexport async function encryptSensitiveValue(\n plaintext: string,\n publicKey: TransportPublicKey\n): Promise<EncryptedSensitiveValue> {\n if (typeof crypto === \"undefined\" || !crypto.subtle) {\n throw new Error(\n \"Web Crypto API is unavailable — sensitive fields require a secure browser context\"\n );\n }\n if (typeof plaintext !== \"string\" || plaintext.length === 0) {\n throw new Error(\"encryptSensitiveValue: plaintext must be a non-empty string\");\n }\n\n const rsaKey = await importTransportPublicKey(publicKey.jwk);\n\n // Fresh data key per submission — never reused.\n const dataKey = await crypto.subtle.generateKey(\n { name: \"AES-GCM\", length: 256 },\n true,\n [\"encrypt\"]\n );\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const encoded = new TextEncoder().encode(plaintext);\n\n const ciphertext = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv },\n dataKey,\n encoded\n );\n\n // Wrap the data key with the RSA-OAEP public key so only the server can\n // unwrap it. The wrapped key is opaque to the browser after this point.\n const wrappedKey = await crypto.subtle.wrapKey(\"raw\", dataKey, rsaKey, {\n name: \"RSA-OAEP\",\n });\n\n return {\n v: \"v1\",\n kid: publicKey.kid,\n wrappedKey: bufferToBase64(wrappedKey),\n iv: bufferToBase64(iv.buffer),\n ciphertext: bufferToBase64(ciphertext),\n last4: deriveLast4(plaintext),\n };\n}\n\n/**\n * Strips formatting (dashes, spaces) and returns the last four digits.\n * Used for the plaintext display marker stored alongside the ciphertext.\n */\nexport function deriveLast4(plaintext: string): string {\n const digits = plaintext.replace(/\\D/g, \"\");\n return digits.slice(-4).padStart(4, \"•\");\n}\n\nexport { bufferToBase64, base64ToBuffer };\n","\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { FormStyle } from \"../types\";\nimport { DEFAULT_FORM_STYLE } from \"../types\";\n\nconst FormStyleContext = createContext<FormStyle>(DEFAULT_FORM_STYLE);\n\nexport const useFormStyle = () => useContext(FormStyleContext);\nexport const FormStyleProvider = FormStyleContext.Provider;\n\n/**\n * Editor-only overrides for the in-builder preview. When a value is set,\n * descendants should drop conflicting Tailwind utility classes and apply\n * these as inline styles so they win on specificity.\n *\n * These are never persisted to the FormDefinition and never reach consumers.\n */\nexport interface FormPreviewOverrides {\n backgroundColor?: string;\n textColor?: string;\n}\n\nconst FormPreviewOverridesContext = createContext<FormPreviewOverrides | null>(\n null,\n);\n\nexport const useFormPreviewOverrides = () =>\n useContext(FormPreviewOverridesContext);\nexport const FormPreviewOverridesProvider =\n FormPreviewOverridesContext.Provider;\n","import type { CSSProperties } from \"react\";\nimport type { FormStyle } from \"../types\";\n\n/**\n * Single source of truth for the CSS custom properties the renderer publishes\n * on the form root.\n *\n * The form builder writes per-form color overrides into `FormStyle`. Every\n * color is optional: when set, `buildFormCssVars()` emits it as an inline CSS\n * variable on the form root; when unset, the variable is omitted and the\n * `var(..., fallback)` references in `INPUT_VAR` / `BUTTON_VAR` etc. resolve\n * to the baked-in default below.\n *\n * Field components read from these var references — they never touch the\n * raw `FormStyle` colors — so a single picker change cascades to every\n * field automatically.\n */\n\nexport const FORM_CSS_VAR = {\n formBg: \"--form-bg\",\n inputBg: \"--form-input-bg\",\n inputBorder: \"--form-input-border\",\n inputFocusBorder: \"--form-input-focus-border\",\n inputText: \"--form-input-text\",\n placeholder: \"--form-placeholder\",\n labelText: \"--form-label-text\",\n error: \"--form-error\",\n buttonBg: \"--form-button-bg\",\n buttonText: \"--form-button-text\",\n} as const;\n\n/**\n * Baked-in defaults used when the FormStyle doesn't override a color. These\n * are the fallbacks inside the `var(--name, fallback)` references that the\n * renderer uses, so they apply automatically whenever the corresponding var\n * isn't set on the form root.\n */\nexport const FORM_DEFAULT_COLOR = {\n formBg: \"transparent\",\n inputBg: \"inherit\",\n inputBorder: \"#d1d5db\",\n inputFocusBorder: \"#2563eb\",\n inputText: \"inherit\",\n placeholder: \"#9ca3af\",\n labelText: \"inherit\",\n error: \"#ef4444\",\n buttonBg: \"#2563eb\",\n buttonText: \"#ffffff\",\n} as const;\n\n/** Reference like `var(--form-input-bg, #ffffff)` for inline-style use. */\nfunction ref(name: string, fallback: string): string {\n return `var(${name}, ${fallback})`;\n}\n\n/**\n * Pre-built `var(...)` references with fallbacks. Pass these straight into\n * inline `style` props; the form root's CSS variables override the fallback\n * automatically wherever the user has set a color.\n */\nexport const FORM_VAR = {\n formBg: ref(FORM_CSS_VAR.formBg, FORM_DEFAULT_COLOR.formBg),\n inputBg: ref(FORM_CSS_VAR.inputBg, FORM_DEFAULT_COLOR.inputBg),\n inputBorder: ref(FORM_CSS_VAR.inputBorder, FORM_DEFAULT_COLOR.inputBorder),\n inputFocusBorder: ref(\n FORM_CSS_VAR.inputFocusBorder,\n FORM_DEFAULT_COLOR.inputFocusBorder,\n ),\n inputText: ref(FORM_CSS_VAR.inputText, FORM_DEFAULT_COLOR.inputText),\n placeholder: ref(FORM_CSS_VAR.placeholder, FORM_DEFAULT_COLOR.placeholder),\n labelText: ref(FORM_CSS_VAR.labelText, FORM_DEFAULT_COLOR.labelText),\n error: ref(FORM_CSS_VAR.error, FORM_DEFAULT_COLOR.error),\n buttonBg: ref(FORM_CSS_VAR.buttonBg, FORM_DEFAULT_COLOR.buttonBg),\n buttonText: ref(FORM_CSS_VAR.buttonText, FORM_DEFAULT_COLOR.buttonText),\n} as const;\n\n/**\n * Build the inline `style` object the form root should receive: only emits\n * a CSS variable for colors the FormStyle actually overrides, leaving the\n * rest to fall back via `FORM_VAR.*`. Optional `previewBg` (editor-only)\n * takes precedence over the persisted form background and is also published\n * to the input-bg variable so floating-label masks track the live preview.\n */\nexport function buildFormCssVars(\n style: FormStyle,\n previewBg?: string,\n): CSSProperties {\n const out: Record<string, string> = {};\n\n const effectiveFormBg = previewBg ?? style.formBackgroundColor;\n if (effectiveFormBg) out[FORM_CSS_VAR.formBg] = effectiveFormBg;\n\n // When a preview bg is active, the input-bg var follows it so outlined\n // floating labels paint over the input border in the same color the\n // surrounding surface is using. Otherwise the persisted inputBgColor wins.\n const effectiveInputBg = previewBg ?? style.inputBgColor;\n if (effectiveInputBg) out[FORM_CSS_VAR.inputBg] = effectiveInputBg;\n\n if (style.inputBorderColor)\n out[FORM_CSS_VAR.inputBorder] = style.inputBorderColor;\n if (style.inputFocusColor)\n out[FORM_CSS_VAR.inputFocusBorder] = style.inputFocusColor;\n if (style.inputTextColor)\n out[FORM_CSS_VAR.inputText] = style.inputTextColor;\n if (style.placeholderColor)\n out[FORM_CSS_VAR.placeholder] = style.placeholderColor;\n if (style.labelColor) out[FORM_CSS_VAR.labelText] = style.labelColor;\n if (style.errorColor) out[FORM_CSS_VAR.error] = style.errorColor;\n if (style.buttonColor) out[FORM_CSS_VAR.buttonBg] = style.buttonColor;\n if (style.buttonTextColor)\n out[FORM_CSS_VAR.buttonText] = style.buttonTextColor;\n\n return out as CSSProperties;\n}\n","import { twMerge } from \"tailwind-merge\";\nimport type { FormStyle } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { FORM_VAR } from \"../cssVars\";\n\ninterface InputStyles {\n wrapperClass: string;\n inputClass: string;\n inputStyle: React.CSSProperties;\n inputFocusStyle: React.CSSProperties;\n labelClass: string;\n labelStyle: React.CSSProperties;\n errorStyle: React.CSSProperties;\n /** CSS `var(...)` reference for the focus / accent color. */\n accentColor: string;\n isStacked: boolean;\n}\n\n// Placeholder color is the one property that needs a pseudo-element selector,\n// which inline `style` can't reach. Tailwind's arbitrary-property syntax\n// emits the equivalent rule and reads the same CSS variable as everything\n// else, so the placeholder picker still cascades from the form root.\nconst placeholderClass =\n \"placeholder:[color:var(--form-placeholder,#9ca3af)]\";\n\n// Input text color flows through the var system too — using arbitrary-color\n// syntax lets us pick it up without giving every variant its own inline\n// color rule. The fallback `inherit` lets the consumer's typography win when\n// the picker is left on \"Inherited\".\nconst textClass = \"text-[color:var(--form-input-text,inherit)]\";\n\nfunction getVariantClasses(style: FormStyle): {\n inputClass: string;\n inputStyle: React.CSSProperties;\n labelClass: string;\n} {\n switch (style.inputVariant) {\n case \"stacked\":\n return {\n inputClass: twMerge(\n \"w-full rounded-lg border px-4 py-3 text-base transition focus:outline-none disabled:cursor-not-allowed\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderColor: FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n },\n labelClass: \"mb-1 block text-sm font-medium\",\n };\n\n case \"filled\":\n return {\n inputClass: twMerge(\n \"rounded-t-md px-3 py-1.5 text-base transition ease-in-out placeholder:opacity-0 focus:outline-none focus:placeholder:opacity-100 disabled:cursor-not-allowed\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderStyle: \"solid\",\n borderWidth: 0,\n borderBottomWidth: 2,\n borderBottomColor: FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n },\n labelClass:\n \"absolute left-2 top-2 z-10 flex min-h-[1ch] w-min -translate-y-[18px] cursor-text flex-col justify-around whitespace-nowrap rounded-md px-1 text-sm transition-transform group-focus-within:-translate-y-[18px] peer-placeholder-shown:translate-y-0 peer-focus:-translate-y-[18px]\",\n };\n\n case \"underlined\":\n return {\n inputClass: twMerge(\n \"rounded-none bg-transparent px-1 py-1.5 text-base transition ease-in-out placeholder:opacity-0 focus:outline-none focus:placeholder:opacity-100 disabled:cursor-not-allowed\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderStyle: \"solid\",\n borderWidth: 0,\n borderBottomWidth: 2,\n borderBottomColor: FORM_VAR.inputBorder,\n },\n labelClass:\n \"absolute left-1 top-2 z-10 flex min-h-[1ch] w-min -translate-y-[18px] cursor-text flex-col justify-around whitespace-nowrap px-0 text-sm transition-transform group-focus-within:-translate-y-[18px] peer-placeholder-shown:translate-y-0 peer-focus:-translate-y-[18px]\",\n };\n\n case \"outlined\":\n default:\n return {\n inputClass: twMerge(\n \"rounded px-3 py-1.5 text-base transition ease-in-out placeholder:opacity-0 focus:outline-none focus:placeholder:opacity-100 disabled:cursor-not-allowed bg-transparent\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderStyle: \"solid\",\n borderWidth: 1,\n borderColor: FORM_VAR.inputBorder,\n },\n // Label must paint a solid bg on top of the input border. `bg-inherit`\n // doesn't work — wrapper divs between the form root and the label\n // have transparent bgs, so `inherit` resolves to transparent. Read\n // from `--form-input-bg`, which DynamicForm publishes on the form\n // root from the resolved input background (or the editor preview\n // override). The fallback matches FORM_DEFAULT_COLOR.inputBg.\n labelClass:\n \"absolute left-2 top-2 z-10 flex min-h-[1ch] w-min -translate-y-[18px] cursor-text flex-col justify-around whitespace-nowrap rounded-md bg-[var(--form-input-bg,inherit)] px-1 text-sm transition-transform group-focus-within:-translate-y-[18px] peer-placeholder-shown:translate-y-0 peer-focus:-translate-y-[18px]\",\n };\n }\n}\n\nfunction getFocusStyle(style: FormStyle): React.CSSProperties {\n if (style.inputVariant === \"filled\" || style.inputVariant === \"underlined\") {\n return { borderBottomColor: FORM_VAR.inputFocusBorder };\n }\n if (style.inputVariant === \"stacked\") {\n // Stacked picks up a 2px focus ring tinted from the accent color. We\n // can't shade a CSS var inside a string template here so the ring uses\n // a fixed translucent slate — the focus border itself still tracks the\n // user-picked focus color.\n return {\n borderColor: FORM_VAR.inputFocusBorder,\n boxShadow: \"0 0 0 2px rgba(37, 99, 235, 0.2)\",\n };\n }\n return { borderColor: FORM_VAR.inputFocusBorder };\n}\n\nexport function useInputStyles(): InputStyles {\n const style = useFormStyle();\n const variant = getVariantClasses(style);\n const isStacked = style.inputVariant === \"stacked\";\n\n return {\n wrapperClass: isStacked\n ? \"flex w-full flex-col\"\n : \"group relative flex w-full flex-col pt-3\",\n inputClass: isStacked\n ? twMerge(\"block w-full\", variant.inputClass)\n : twMerge(\n \"peer m-0 mb-3 block min-h-8 w-full overflow-hidden\",\n variant.inputClass,\n ),\n inputStyle: variant.inputStyle,\n inputFocusStyle: getFocusStyle(style),\n labelClass: variant.labelClass,\n labelStyle: { color: FORM_VAR.labelText },\n errorStyle: { color: FORM_VAR.error },\n accentColor: FORM_VAR.inputFocusBorder,\n isStacked,\n };\n}\n\n/**\n * Inline-style outline applied to the input wrapper when validation has\n * flagged the field. Border / outline color tracks the `--form-error`\n * variable so a single picker change covers every variant at once.\n */\nexport function getErrorOutlineStyle(\n hasError: boolean,\n variant: string,\n): React.CSSProperties {\n if (!hasError) return {};\n\n if (variant === \"stacked\") {\n return {\n outline: `2px solid ${FORM_VAR.error}`,\n outlineOffset: \"-2px\",\n };\n }\n if (variant === \"outlined\") {\n return {\n outline: `1px solid ${FORM_VAR.error}`,\n outlineOffset: \"-1px\",\n borderColor: FORM_VAR.error,\n };\n }\n return {\n borderBottomColor: FORM_VAR.error,\n };\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface StyledInputProps {\n id: string;\n label: string;\n placeholder?: string;\n type?: string;\n value: string;\n error?: string;\n touched?: boolean;\n disabled?: boolean;\n onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n onBlur: (e: React.FocusEvent<HTMLInputElement>) => void;\n}\n\nexport const StyledInput = ({\n id,\n label,\n placeholder,\n type = \"text\",\n value,\n error,\n touched,\n disabled,\n onChange,\n onBlur,\n}: StyledInputProps) => {\n const [focused, setFocused] = useState(false);\n const style = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(error && touched);\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, style.inputVariant),\n };\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={id} className={styles.labelClass} style={styles.labelStyle}>\n {label}\n </label>\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={id}\n name={id}\n type={type}\n placeholder={placeholder}\n value={value}\n disabled={disabled}\n onChange={onChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n onBlur(e);\n }}\n />\n {hasError && (\n <span\n className={twMerge(\"mt-1 text-xs\", \"text-red-600 dark:text-red-400\")}\n style={styles.errorStyle}\n >\n {error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={id} className=\"relative inline-block\">\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={id}\n name={id}\n type={type}\n placeholder={placeholder || label}\n value={value}\n disabled={disabled}\n onChange={onChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {label}\n </span>\n </label>\n {hasError && (\n <span className=\"mt-[-8px] text-xs\" style={styles.errorStyle}>\n {error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const TextField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n e.target.value = applyTextTransform(e.target.value, fieldDef.transform);\n field.onChange(e);\n };\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder}\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={handleChange}\n onBlur={field.onBlur}\n />\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const EmailField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder}\n type=\"email\"\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={field.onChange}\n onBlur={field.onBlur}\n />\n );\n};\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { formatUsPhone } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const PhoneField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle.inputVariant),\n };\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n helpers.setValue(formatUsPhone(e.target.value));\n };\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <label\n htmlFor={fieldDef.id}\n className={styles.labelClass}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </label>\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n type=\"tel\"\n placeholder={fieldDef.placeholder}\n value={field.value ?? \"\"}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n {hasError && (\n <span\n className={twMerge(\"mt-1 text-xs\", \"text-red-600 dark:text-red-400\")}\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n type=\"tel\"\n placeholder={fieldDef.placeholder || fieldDef.label}\n value={field.value ?? \"\"}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n {hasError && (\n <span className=\"mt-[-8px] text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const UrlField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder || \"https://example.com\"}\n type=\"url\"\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={field.onChange}\n onBlur={field.onBlur}\n />\n );\n};\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const AddressField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n\n const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n e.target.value = applyTextTransform(e.target.value, fieldDef.transform);\n field.onChange(e);\n };\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle.inputVariant),\n };\n\n const placeholder =\n fieldDef.placeholder || \"123 Main St, City, State 12345\";\n\n return (\n <div className={`${styles.wrapperClass} pb-5 lg:pb-0`}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <textarea\n className={`${styles.inputClass} min-h-[4ch] resize-y`}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n autoComplete=\"street-address\"\n placeholder={placeholder}\n rows={fieldDef.rows ?? 2}\n value={field.value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n {hasError && (\n <span className=\"text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const TextAreaField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n\n const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n e.target.value = applyTextTransform(e.target.value, fieldDef.transform);\n field.onChange(e);\n };\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n const value = (field.value ?? \"\") as string;\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle.inputVariant),\n };\n\n if (styles.isStacked) {\n return (\n <div className={twMerge(styles.wrapperClass, \"relative\")}>\n <label\n htmlFor={fieldDef.id}\n className={styles.labelClass}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </label>\n <textarea\n className={twMerge(styles.inputClass, \"resize-y\")}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n placeholder={fieldDef.placeholder}\n rows={fieldDef.rows}\n value={value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n {fieldDef.characterCounter && (\n <span className=\"mt-1 text-right text-xs text-gray-500 dark:text-zinc-400\">\n {value.length}\n </span>\n )}\n {hasError && (\n <span\n className={twMerge(\"mt-1 text-xs\", \"text-red-600 dark:text-red-400\")}\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={twMerge(styles.wrapperClass, \"pb-5 lg:pb-0\")}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block\">\n <textarea\n className={twMerge(styles.inputClass, \"min-h-[5ch] resize-y\")}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n placeholder={fieldDef.placeholder || fieldDef.label}\n rows={fieldDef.rows}\n value={value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n {fieldDef.characterCounter && (\n <span className=\"absolute bottom-1.5 right-2 rounded-md text-sm\">\n {value.length}\n </span>\n )}\n {hasError && (\n <span className=\"text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useState, useEffect } from \"react\";\nimport { useField } from \"formik\";\nimport { Select } from \"radix-ui\";\nimport { BsChevronDown, BsCheck } from \"react-icons/bs\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\nimport { FORM_VAR } from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const SelectField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const [currentValue, setCurrentValue] = useState<string>(field.value || \"\");\n useEffect(() => {\n setCurrentValue(field.value || \"\");\n }, [field.value]);\n\n // Radix Select.Item throws on an empty-string value (it's reserved for\n // \"no selection\") — drop such options instead of crashing the form.\n const options = (fieldDef.options || []).filter((opt) => opt.value !== \"\");\n const displayName =\n options.find((opt) => opt.value === currentValue)?.label || \"\";\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle.inputVariant),\n };\n\n return (\n <div className={styles.wrapperClass}>\n <Select.Root\n disabled={disabled}\n onValueChange={(value) => {\n helpers.setValue(value);\n setCurrentValue(value);\n }}\n value={currentValue}\n >\n <label\n htmlFor={fieldDef.id}\n className=\"relative block bg-inherit\"\n >\n <Select.Trigger\n className={`${styles.inputClass} cursor-pointer text-left`}\n style={borderStyle}\n aria-label={fieldDef.label}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n setFocused(false);\n // Mark touched so a required-error can render after the user\n // tabs past without choosing.\n helpers.setTouched(true);\n }}\n >\n <Select.Value placeholder=\"Choose an option\">\n <span className=\"block truncate\">{displayName}</span>\n </Select.Value>\n <Select.Icon className=\"absolute right-3 top-1/2 -translate-y-1/2\">\n <BsChevronDown style={{ color: FORM_VAR.placeholder }} />\n </Select.Icon>\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </Select.Trigger>\n </label>\n <Select.Portal>\n <Select.Content\n className=\"z-20 rounded-md border p-3 shadow-lg\"\n style={{\n // Portal renders outside the form DOM tree, so CSS variables\n // from the form wrapper don't cascade. Use resolved style\n // values from the form context instead.\n backgroundColor: formStyle.inputBgColor || \"#ffffff\",\n borderColor: formStyle.inputBorderColor || \"#e5e7eb\",\n color: formStyle.inputTextColor || \"#1f2937\",\n }}\n >\n <Select.ScrollUpButton>\n <BsChevronDown className=\"rotate-180\" />\n </Select.ScrollUpButton>\n <Select.Viewport>\n <Select.Group>\n {options.map((opt) => (\n <Select.Item\n key={opt.value}\n className=\"relative m-1 flex cursor-pointer select-none justify-between rounded p-1 pr-8 hover:ring-1 focus:ring-1\"\n style={{\n \"--tw-ring-color\": formStyle.inputFocusColor || \"#2563eb\",\n } as React.CSSProperties}\n value={opt.value}\n >\n <Select.ItemText>{opt.label}</Select.ItemText>\n <Select.ItemIndicator>\n <BsCheck className=\"absolute bottom-0 right-3 top-0 my-auto\" />\n </Select.ItemIndicator>\n </Select.Item>\n ))}\n </Select.Group>\n </Select.Viewport>\n <Select.ScrollDownButton>\n <BsChevronDown />\n </Select.ScrollDownButton>\n </Select.Content>\n </Select.Portal>\n </Select.Root>\n {hasError && (\n <span className=\"text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport { Checkbox } from \"radix-ui\";\nimport { BsCheck } from \"react-icons/bs\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { FORM_VAR } from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n}\n\nexport const CheckboxField = ({ field: fieldDef }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const formStyle = useFormStyle();\n const isChecked = field.value === true;\n const isStacked = formStyle.inputVariant === \"stacked\";\n\n const checkboxStyle: React.CSSProperties = isChecked\n ? { borderColor: FORM_VAR.inputFocusBorder, backgroundColor: FORM_VAR.inputFocusBorder }\n : { borderColor: FORM_VAR.inputBorder, backgroundColor: FORM_VAR.inputBg };\n\n return (\n <div\n className={twMerge(\n isStacked ? \"flex items-start gap-3\" : \"flex items-center gap-3 pt-3\"\n )}\n >\n <Checkbox.Root\n id={fieldDef.id}\n checked={isChecked}\n onCheckedChange={(checked) => {\n helpers.setValue(checked === true);\n helpers.setTouched(true, false);\n }}\n className={twMerge(\n \"flex h-5 w-5 items-center justify-center rounded border\",\n isStacked && \"mt-0.5 shrink-0\"\n )}\n style={checkboxStyle}\n >\n <Checkbox.Indicator>\n <BsCheck className=\"text-white\" />\n </Checkbox.Indicator>\n </Checkbox.Root>\n <label\n htmlFor={fieldDef.id}\n className=\"cursor-pointer text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {fieldDef.label}\n </label>\n {meta.touched && meta.error && (\n <span className=\"text-sm\" style={{ color: FORM_VAR.error }}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport { RadioGroup } from \"radix-ui\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { FORM_VAR } from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const RadioField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n\n return (\n <div className=\"pt-3\">\n <span\n className=\"mb-2 block text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {fieldDef.label}\n </span>\n <RadioGroup.Root\n value={field.value}\n disabled={disabled}\n onValueChange={(value) => {\n helpers.setValue(value);\n helpers.setTouched(true, false);\n }}\n className=\"flex flex-col gap-2\"\n >\n {(fieldDef.options || []).map((opt) => {\n const isSelected = field.value === opt.value;\n return (\n <div key={opt.value} className=\"flex items-center gap-2\">\n <RadioGroup.Item\n value={opt.value}\n id={`${fieldDef.id}-${opt.value}`}\n className=\"flex h-5 w-5 items-center justify-center rounded-full border\"\n style={{\n borderColor: isSelected\n ? FORM_VAR.inputFocusBorder\n : FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n }}\n >\n <RadioGroup.Indicator\n className=\"h-2.5 w-2.5 rounded-full\"\n style={{ backgroundColor: FORM_VAR.inputFocusBorder }}\n />\n </RadioGroup.Item>\n <label\n htmlFor={`${fieldDef.id}-${opt.value}`}\n className=\"cursor-pointer text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {opt.label}\n </label>\n </div>\n );\n })}\n </RadioGroup.Root>\n {meta.touched && meta.error && (\n <span className=\"mt-1 block text-sm\" style={{ color: FORM_VAR.error }}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const NumberField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder}\n type=\"number\"\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={field.onChange}\n onBlur={field.onBlur}\n />\n );\n};\n","import { addDays, isSameDay, isWeekend } from \"date-fns\";\nimport type { DatetimeConfig } from \"../../types\";\n\n/**\n * The first non-weekend day strictly after `from` — on a Friday or Saturday\n * that's the following Monday.\n */\nexport function nextBusinessDay(from: Date): Date {\n let d = addDays(from, 1);\n while (isWeekend(d)) d = addDays(d, 1);\n return d;\n}\n\n/**\n * Build the `filterDate` predicate for react-datepicker from a field's\n * datetime config, combining every day-level exclusion (weekends, today,\n * tomorrow, next business day). Returns `undefined` when nothing is\n * excluded so the picker prop can be omitted entirely.\n *\n * \"Today\" is evaluated at click time (not render time) so a form left open\n * across midnight stays correct.\n *\n * These exclusions are picker-level UX, not schema validation — consistent\n * with how excludeWeekends/excludePastDates already behave.\n */\nexport function buildDateFilter(\n config: DatetimeConfig | undefined,\n): ((date: Date) => boolean) | undefined {\n const excludeWeekends = config?.excludeWeekends ?? false;\n const excludeToday = config?.excludeToday ?? false;\n const excludeTomorrow = config?.excludeTomorrow ?? false;\n const excludeNext = config?.excludeNextBusinessDay ?? false;\n\n if (!excludeWeekends && !excludeToday && !excludeTomorrow && !excludeNext) {\n return undefined;\n }\n\n return (date: Date) => {\n const now = new Date();\n if (excludeWeekends && isWeekend(date)) return false;\n if (excludeToday && isSameDay(date, now)) return false;\n if (excludeTomorrow && isSameDay(date, addDays(now, 1))) return false;\n if (excludeNext && isSameDay(date, nextBusinessDay(now))) return false;\n return true;\n };\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport DatePicker from \"react-datepicker\";\nimport { format, isValid, parse, set } from \"date-fns\";\nimport { twMerge } from \"tailwind-merge\";\nimport \"react-datepicker/dist/react-datepicker.css\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\nimport { buildDateFilter } from \"./dateExclusions\";\n\ninterface Props {\n field: FormFieldDefinition;\n /**\n * Date-only mode (used by the `date` field type): hides the time selector\n * and stores the value as \"yyyy-MM-dd\" instead of a full ISO timestamp,\n * matching what the native date input previously produced.\n */\n dateOnly?: boolean;\n disabled?: boolean;\n}\n\nfunction parseTimeString(value: string | undefined, fallbackHours: number, fallbackMinutes: number): Date {\n if (!value) {\n return set(new Date(), { hours: fallbackHours, minutes: fallbackMinutes, seconds: 0, milliseconds: 0 });\n }\n try {\n return parse(value, \"HH:mm\", new Date());\n } catch {\n return set(new Date(), { hours: fallbackHours, minutes: fallbackMinutes, seconds: 0, milliseconds: 0 });\n }\n}\n\n/**\n * Parse a stored field value into a Date. Plain dates (\"2026-06-10\") are\n * parsed at LOCAL midnight — `new Date(\"2026-06-10\")` would read it as UTC\n * and show the previous day in negative-offset timezones.\n */\nfunction parseStoredValue(value: string): Date | null {\n if (!value) return null;\n const d = /^\\d{4}-\\d{2}-\\d{2}$/.test(value)\n ? parse(value, \"yyyy-MM-dd\", new Date())\n : new Date(value);\n return isValid(d) ? d : null;\n}\n\nexport const DateTimeField = ({\n field: fieldDef,\n dateOnly = false,\n disabled,\n}: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const config = fieldDef.datetimeConfig ?? {};\n const showTimeSelect = dateOnly ? false : (config.showTimeSelect ?? true);\n const timeIntervals = config.timeIntervals ?? 30;\n const excludePastDates = config.excludePastDates ?? true;\n const filterPastTimes = config.filterPastTimes ?? true;\n const dateFormat = config.dateFormat ?? (showTimeSelect ? \"MMMM d, yyyy h:mm aa\" : \"MMMM d, yyyy\");\n const placeholderText =\n config.placeholderText ??\n fieldDef.placeholder ??\n (dateOnly ? \"Select date\" : \"Select date and time\");\n\n const minTime = showTimeSelect ? parseTimeString(config.minTime, 0, 0) : undefined;\n const maxTime = showTimeSelect ? parseTimeString(config.maxTime, 23, 59) : undefined;\n const minDate = excludePastDates ? new Date() : undefined;\n\n const selected = parseStoredValue(field.value);\n\n // Combined day-level exclusions: weekends / today / tomorrow / next\n // business day. Undefined when nothing is excluded.\n const filterDate = buildDateFilter(config);\n\n const filterTime = (time: Date) => {\n if (!filterPastTimes) return true;\n return time.getTime() >= Date.now();\n };\n\n const handleChange = (date: Date | null) => {\n if (!date) {\n helpers.setValue(\"\");\n return;\n }\n helpers.setValue(dateOnly ? format(date, \"yyyy-MM-dd\") : date.toISOString());\n };\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle.inputVariant),\n };\n\n const pickerProps = {\n id: fieldDef.id,\n name: fieldDef.id,\n wrapperClassName: \"block w-full\",\n disabled,\n selected,\n onChange: handleChange,\n onFocus: () => setFocused(true),\n onBlur: () => {\n setFocused(false);\n helpers.setTouched(true);\n },\n showTimeSelect,\n timeIntervals,\n minDate,\n minTime,\n maxTime,\n filterDate,\n filterTime: showTimeSelect && filterPastTimes ? filterTime : undefined,\n dateFormat,\n placeholderText,\n autoComplete: \"off\",\n };\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <label\n htmlFor={fieldDef.id}\n className={styles.labelClass}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </label>\n <DatePicker\n {...pickerProps}\n customInput={\n <input\n className={twMerge(styles.inputClass, \"cursor-pointer\")}\n style={borderStyle}\n />\n }\n />\n {hasError && (\n <span\n className={twMerge(\"mt-1 text-xs\", \"text-red-600 dark:text-red-400\")}\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <DatePicker\n {...pickerProps}\n className={styles.inputClass}\n customInput={\n <input\n className={styles.inputClass}\n style={borderStyle}\n />\n }\n />\n <span\n className={twMerge(\n styles.labelClass,\n // react-datepicker nests the real input inside wrapper divs, so\n // the `peer-placeholder-shown` rest rule from labelClass never\n // matches (the peer must be a direct sibling). Recreate the\n // resting position from tracked state instead.\n !focused && !field.value && \"translate-y-0\",\n )}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </span>\n </label>\n {hasError && (\n <span className=\"mt-[-8px] text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport type { FormFieldDefinition } from \"../../types\";\nimport { DateTimeField } from \"./DateTimeField\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\n/**\n * Date-only picker — the DateTimeField in `dateOnly` mode.\n *\n * Previously this was a native <input type=\"date\">, which silently ignored\n * every `datetimeConfig` option the builder offers for date fields\n * (exclude weekends / past dates / today / tomorrow / next business day).\n * The shared picker honors them all; the stored value stays \"yyyy-MM-dd\"\n * so existing submissions and integrations are unaffected.\n */\nexport const DateField = ({ field, disabled }: Props) => {\n return <DateTimeField field={field} dateOnly disabled={disabled} />;\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\n\ninterface Props {\n field: FormFieldDefinition;\n /** Accepted for renderer prop-compat; a hidden input has nothing to disable. */\n disabled?: boolean;\n}\n\nexport const HiddenField = ({ field: fieldDef }: Props) => {\n const [field] = useField(fieldDef.id);\n\n return <input type=\"hidden\" name={fieldDef.id} value={field.value} />;\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport { useState } from \"react\";\nimport { FiEye, FiEyeOff } from \"react-icons/fi\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\n/**\n * Renders a sensitive field as a password-style input. The plaintext value\n * lives in Formik state for the lifetime of the form; on submit, the\n * `DynamicForm` submission handler walks the form definition, encrypts each\n * sensitive field with the transport public key, and only ciphertext is\n * sent to the API. The plaintext never touches the network in cleartext.\n *\n * Visual treatment: an \"Encrypted before submission\" hint with a lock glyph\n * and an eye-icon reveal toggle. When hidden (default), the browser's native\n * password masking applies.\n */\nexport const SensitiveField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField<string>(fieldDef.id);\n const [reveal, setReveal] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const [focused, setFocused] = useState(false);\n const hasError = !!(meta.error && meta.touched);\n const isSsn =\n fieldDef.sensitiveConfig?.inputMask === \"ssn\" ||\n fieldDef.transform === \"ssn\";\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n // The ssn input mask wins over any other configured transform; both\n // routes go through the shared formatter.\n const next = applyTextTransform(\n e.target.value,\n isSsn ? \"ssn\" : fieldDef.transform\n );\n helpers.setValue(next);\n };\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle.inputVariant),\n paddingRight: \"2.75rem\",\n };\n\n const inputType = reveal ? \"text\" : \"password\";\n const inputProps = {\n id: fieldDef.id,\n name: fieldDef.id,\n type: inputType,\n disabled,\n autoComplete: \"off\",\n inputMode: isSsn ? (\"numeric\" as const) : undefined,\n placeholder: fieldDef.placeholder || (isSsn ? \"•••-••-••••\" : fieldDef.label),\n value: field.value,\n onChange: handleChange,\n onFocus: () => setFocused(true),\n onBlur: (e: React.FocusEvent<HTMLInputElement>) => {\n setFocused(false);\n field.onBlur(e);\n },\n \"aria-describedby\": `${fieldDef.id}-secure`,\n \"data-sensitive\": \"true\" as const,\n };\n\n // The button lives inside an inset-y-0 flex wrapper so it always centers\n // on the wrapper's height. In the floating-label layout the input carries\n // a 12px bottom margin (`mb-3`) inside the relative container, so the\n // wrapper takes a matching `mb-3` to center on the input itself.\n const renderToggle = (wrapperClass?: string) => (\n <span\n className={twMerge(\n \"absolute inset-y-0 right-2 flex items-center\",\n wrapperClass,\n )}\n >\n <button\n type=\"button\"\n onClick={() => setReveal((r) => !r)}\n className=\"flex h-7 w-7 items-center justify-center rounded text-gray-600 hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/60 dark:text-zinc-400 dark:hover:bg-zinc-700\"\n aria-pressed={reveal}\n aria-label={reveal ? \"Hide value\" : \"Show value\"}\n >\n {reveal ? (\n <FiEyeOff size={16} aria-hidden=\"true\" />\n ) : (\n <FiEye size={16} aria-hidden=\"true\" />\n )}\n </button>\n </span>\n );\n\n // Rendered beside (stacked) or above (floating) the input so the space\n // below stays reserved for validation errors.\n const renderSecureHint = (className?: string) => (\n <p\n id={`${fieldDef.id}-secure`}\n className={twMerge(\n \"flex items-center gap-1 text-xs text-gray-500 dark:text-zinc-400\",\n className,\n )}\n >\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 16 16\"\n className=\"h-3 w-3 flex-shrink-0\"\n fill=\"currentColor\"\n >\n <path d=\"M8 1a3 3 0 0 0-3 3v3H4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-1V4a3 3 0 0 0-3-3Zm-2 6V4a2 2 0 1 1 4 0v3H6Z\" />\n </svg>\n Encrypted before submission\n </p>\n );\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <div className=\"flex flex-wrap items-baseline justify-between gap-x-2\">\n <label htmlFor={fieldDef.id} className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </label>\n {renderSecureHint(\"mb-1\")}\n </div>\n <div className=\"relative\">\n <input className={styles.inputClass} style={borderStyle} {...inputProps} />\n {renderToggle()}\n </div>\n {hasError && (\n <span\n className={twMerge(\"mt-1 text-xs\", \"text-red-600 dark:text-red-400\")}\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n {renderSecureHint(\"absolute right-0 top-0 leading-none\")}\n <label htmlFor={fieldDef.id} className=\"relative inline-block w-full bg-inherit\">\n <input className={styles.inputClass} style={borderStyle} {...inputProps} />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n {renderToggle(\"mb-3\")}\n </label>\n {hasError && (\n <span className=\"mt-[-8px] text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField, useFormikContext } from \"formik\";\nimport { useCallback, useRef, useState } from \"react\";\nimport type { FormFieldDefinition, FileFieldConfig } from \"../../types\";\nimport { DEFAULT_FILE_FIELD_CONFIG } from \"../../types\";\n\ninterface Props {\n field: FormFieldDefinition;\n /** Project ID for storage path. Passed from the form renderer. */\n projectId?: string;\n /** Upload handler — provided by the consuming app. */\n onUpload?: (\n file: File,\n config: FileFieldConfig,\n ) => Promise<{ url: string; name: string; size: number }>;\n /** When true (mirrored/locked), the picker is read-only. */\n disabled?: boolean;\n}\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check a file against an `accept` attribute value (comma-separated MIME\n * types, `type/*` wildcards, or `.ext` extensions). The native picker\n * enforces this, but drag-and-drop bypasses it entirely.\n */\nfunction matchesAccept(file: File, accept?: string): boolean {\n if (!accept?.trim()) return true;\n const patterns = accept.split(\",\").map((p) => p.trim()).filter(Boolean);\n return patterns.some((pattern) => {\n if (pattern.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(pattern.toLowerCase());\n }\n if (pattern.endsWith(\"/*\")) {\n return file.type.startsWith(pattern.slice(0, -1));\n }\n return file.type === pattern;\n });\n}\n\ninterface UploadedFile {\n url: string;\n name: string;\n size: number;\n}\n\nexport const FileField = ({ field: fieldDef, onUpload, disabled }: Props) => {\n const [, meta, helpers] = useField(fieldDef.id);\n const { setFieldTouched } = useFormikContext();\n const inputRef = useRef<HTMLInputElement>(null);\n const [uploading, setUploading] = useState(false);\n const [uploadError, setUploadError] = useState<string | null>(null);\n const [files, setFiles] = useState<UploadedFile[]>([]);\n\n const config: FileFieldConfig = {\n ...DEFAULT_FILE_FIELD_CONFIG,\n ...fieldDef.fileConfig,\n };\n\n const maxSizeBytes = config.maxSizeBytes ?? 10 * 1024 * 1024;\n const multiple = config.multiple ?? false;\n const maxFiles = config.maxFiles ?? 5;\n\n const handleFiles = useCallback(\n async (fileList: FileList | null) => {\n if (!fileList || fileList.length === 0) return;\n setUploadError(null);\n\n const toUpload = Array.from(fileList);\n\n // Check max files\n if (multiple && files.length + toUpload.length > maxFiles) {\n setUploadError(`Maximum ${maxFiles} files allowed.`);\n return;\n }\n\n // Accumulate locally, then commit files + Formik value together at the\n // end — setValue inside a setState updater is impure (double-fires\n // under StrictMode).\n let current = files;\n\n for (const file of toUpload) {\n // The input's accept attribute only filters the OS picker —\n // drag-and-drop arrives unfiltered.\n if (!matchesAccept(file, config.accept)) {\n setUploadError(`\"${file.name}\" is not an accepted file type.`);\n continue;\n }\n // Validate size\n if (file.size > maxSizeBytes) {\n setUploadError(\n `\"${file.name}\" exceeds ${formatBytes(maxSizeBytes)} limit.`,\n );\n continue;\n }\n\n setUploading(true);\n\n try {\n let result: UploadedFile;\n\n if (onUpload) {\n result = await onUpload(file, config);\n } else {\n // Fallback: create a local object URL (for preview/testing only)\n result = {\n url: URL.createObjectURL(file),\n name: file.name,\n size: file.size,\n };\n }\n\n current = multiple ? [...current, result] : [result];\n } catch (err) {\n setUploadError(`Upload failed: ${(err as Error).message}`);\n } finally {\n setUploading(false);\n }\n }\n\n if (current !== files) {\n setFiles(current);\n // Single file gets a string URL, multiple gets an array.\n helpers.setValue(multiple ? current.map((f) => f.url) : current[0]?.url ?? \"\");\n }\n\n setFieldTouched(fieldDef.id, true);\n },\n [\n files,\n multiple,\n maxFiles,\n maxSizeBytes,\n config,\n onUpload,\n helpers,\n fieldDef.id,\n setFieldTouched,\n ],\n );\n\n const removeFile = useCallback(\n (index: number) => {\n const next = files.filter((_, i) => i !== index);\n setFiles(next);\n // Keep the value's TYPE stable: multiple-mode is always an array\n // (an empty \"\" string would fail the array schema with a typeError).\n helpers.setValue(multiple ? next.map((f) => f.url) : \"\");\n },\n [files, multiple, helpers],\n );\n\n const hasError = meta.touched && meta.error;\n const isRequired = fieldDef.validation?.some((v) => v.type === \"required\");\n\n return (\n <div>\n {/* Label */}\n <label\n htmlFor={fieldDef.id}\n className=\"mb-1 block text-sm font-medium\"\n style={{ color: \"var(--form-label-color, inherit)\" }}\n >\n {fieldDef.label}\n {isRequired && <span className=\"ml-0.5 text-red-500\">*</span>}\n </label>\n\n {fieldDef.helpText && (\n <p\n className=\"mb-2 text-xs\"\n style={{ color: \"var(--form-placeholder-color, #9ca3af)\" }}\n >\n {fieldDef.helpText}\n </p>\n )}\n\n {/* Drop zone */}\n <div\n className={`relative rounded-lg border-2 border-dashed p-6 text-center transition-colors ${\n hasError\n ? \"border-red-400\"\n : \"border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500\"\n }`}\n onDragOver={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n onDrop={(e) => {\n e.preventDefault();\n e.stopPropagation();\n handleFiles(e.dataTransfer.files);\n }}\n >\n <input\n ref={inputRef}\n id={fieldDef.id}\n type=\"file\"\n accept={config.accept}\n multiple={multiple}\n disabled={disabled}\n onChange={(e) => {\n handleFiles(e.target.files);\n e.target.value = \"\";\n }}\n className=\"hidden\"\n />\n\n {uploading ? (\n <div className=\"space-y-2\">\n {/* Indeterminate — the onUpload contract has no progress hook. */}\n <div className=\"mx-auto h-1.5 w-32 overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700\">\n <div className=\"h-full w-1/3 animate-pulse rounded-full bg-indigo-500\" />\n </div>\n <p className=\"text-sm text-gray-500\">Uploading…</p>\n </div>\n ) : (\n <button\n type=\"button\"\n onClick={() => inputRef.current?.click()}\n disabled={disabled}\n className=\"cursor-pointer text-sm text-gray-500 hover:text-gray-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:text-gray-200\"\n >\n <svg\n className=\"mx-auto mb-2 h-8 w-8 text-gray-400\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth={1.5}\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5\"\n />\n </svg>\n <span className=\"font-medium\">Click to upload</span> or drag\n and drop\n <br />\n <span className=\"text-xs text-gray-400\">\n Max {formatBytes(maxSizeBytes)}\n {multiple && ` · Up to ${maxFiles} files`}\n </span>\n </button>\n )}\n </div>\n\n {/* Uploaded files */}\n {files.length > 0 && (\n <div className=\"mt-3 space-y-2\">\n {files.map((f, i) => (\n <div\n key={`${f.name}-${i}`}\n className=\"flex items-center gap-3 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 dark:border-gray-700 dark:bg-gray-800\"\n >\n {f.url && f.name.match(/\\.(jpg|jpeg|png|webp|gif|svg)$/i) && (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n src={f.url}\n alt={f.name}\n className=\"h-10 w-10 rounded object-cover\"\n />\n )}\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-medium text-gray-900 dark:text-gray-100\">\n {f.name}\n </p>\n <p className=\"text-xs text-gray-500\">{formatBytes(f.size)}</p>\n </div>\n <button\n type=\"button\"\n onClick={() => removeFile(i)}\n className=\"cursor-pointer text-gray-400 hover:text-red-500\"\n aria-label={`Remove ${f.name}`}\n >\n <svg\n className=\"h-4 w-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth={2}\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M6 18L18 6M6 6l12 12\"\n />\n </svg>\n </button>\n </div>\n ))}\n </div>\n )}\n\n {/* Errors */}\n {uploadError && (\n <p className=\"mt-1 text-sm text-red-500\">{uploadError}</p>\n )}\n {hasError && (\n <p className=\"mt-1 text-sm text-red-500\">{meta.error}</p>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useFormikContext } from \"formik\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../types\";\nimport { isVisibilityConditionMet } from \"../utils/visibility\";\nimport { TextField } from \"./fields/TextField\";\nimport { EmailField } from \"./fields/EmailField\";\nimport { PhoneField } from \"./fields/PhoneField\";\nimport { UrlField } from \"./fields/UrlField\";\nimport { AddressField } from \"./fields/AddressField\";\nimport { TextAreaField } from \"./fields/TextAreaField\";\nimport { SelectField } from \"./fields/SelectField\";\nimport { CheckboxField } from \"./fields/CheckboxField\";\nimport { RadioField } from \"./fields/RadioField\";\nimport { NumberField } from \"./fields/NumberField\";\nimport { DateField } from \"./fields/DateField\";\nimport { DateTimeField } from \"./fields/DateTimeField\";\nimport { HiddenField } from \"./fields/HiddenField\";\nimport { SensitiveField } from \"./fields/SensitiveField\";\nimport { FileField } from \"./fields/FileField\";\n\nconst fieldComponents: Record<\n string,\n React.ComponentType<{ field: FormFieldDefinition; disabled?: boolean }>\n> = {\n text: TextField,\n email: EmailField,\n phone: PhoneField,\n url: UrlField,\n address: AddressField,\n textarea: TextAreaField,\n select: SelectField,\n checkbox: CheckboxField,\n radio: RadioField,\n number: NumberField,\n date: DateField,\n datetime: DateTimeField,\n hidden: HiddenField,\n sensitive: SensitiveField,\n file: FileField as React.ComponentType<{\n field: FormFieldDefinition;\n disabled?: boolean;\n }>,\n};\n\ninterface Props {\n field: FormFieldDefinition;\n /** True when this field is a \"same as\" target and the toggle is on. */\n mirrored?: boolean;\n /** How a mirrored target renders while the toggle is on. */\n mirrorBehavior?: \"hide\" | \"lock\";\n}\n\nexport const DynamicFormField = ({ field, mirrored, mirrorBehavior }: Props) => {\n const { values } = useFormikContext<Record<string, unknown>>();\n const Component = fieldComponents[field.type];\n\n if (!Component) {\n console.warn(`Unknown field type: ${field.type}`);\n return null;\n }\n\n // A field with no id can't bind to Formik (useField(\"\") throws and takes\n // the whole form down). Definitions from the builder can't contain one,\n // but hand-edited/imported JSON might — skip the field instead of crashing.\n if (!field.id) {\n console.warn(\"Skipping form field with empty id\");\n return null;\n }\n\n if (\n field.showWhen &&\n !isVisibilityConditionMet(field.showWhen, values[field.showWhen.fieldId])\n ) {\n return null;\n }\n\n // A mirrored target in \"hide\" mode disappears while the toggle is on; its\n // copied value still submits (it isn't showWhen-hidden, so it's not stripped).\n if (mirrored && mirrorBehavior === \"hide\") {\n return null;\n }\n // \"lock\" mode renders the field read-only (disabled threaded below).\n const locked = mirrored && mirrorBehavior === \"lock\";\n\n if (field.type === \"hidden\") {\n return <Component field={field} disabled={locked} />;\n }\n\n const widthClasses: Record<string, string> = {\n full: \"md:col-span-6\",\n half: \"md:col-span-3\",\n third: \"md:col-span-2\",\n };\n const widthClass = widthClasses[field.layout?.width || \"full\"] || \"md:col-span-6\";\n const description = field.description ?? field.helpText;\n\n return (\n <div className={widthClass}>\n <Component field={field} disabled={locked} />\n {description && (\n <p className={twMerge(\"mt-1 text-xs\", \"text-gray-500 dark:text-zinc-400\")}>\n {description}\n </p>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useFormikContext } from \"formik\";\nimport { Checkbox } from \"radix-ui\";\nimport { useEffect } from \"react\";\nimport { BsCheck } from \"react-icons/bs\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormSection } from \"../types\";\nimport { sameAsToggleKey } from \"../types\";\nimport { DynamicFormField } from \"./DynamicFormField\";\nimport { FORM_VAR } from \"./cssVars\";\nimport { useFormPreviewOverrides, useFormStyle } from \"./FormStyleContext\";\n\ninterface Props {\n section: FormSection;\n isLast?: boolean;\n /**\n * Form-level default header text color from `FormDefinition.defaultTextColor`.\n * Per-section `textColor` overrides this; the editor preview text color\n * (when set) overrides both.\n */\n formDefaultTextColor?: string;\n /**\n * Submit button rendered beside this section's fields grid (inline\n * `buttonPlacement`). The section title/description stay full-width above\n * the row — only the fields share the row with the button.\n */\n inlineSubmit?: React.ReactNode;\n}\n\nconst spacingGap: Record<string, string> = {\n compact: \"gap-2\",\n normal: \"gap-4\",\n relaxed: \"gap-6\",\n};\n\nexport const DynamicFormSection = ({\n section,\n isLast,\n formDefaultTextColor,\n inlineSubmit,\n}: Props) => {\n const style = useFormStyle();\n const previewOverrides = useFormPreviewOverrides();\n const previewTextColor = previewOverrides?.textColor;\n\n // \"Same as another section\" mirroring. The toggle is a synthetic Formik\n // value (reserved key, stripped before submit); when on, target fields are\n // filled from their mapped source fields and kept in sync.\n const { values, setFieldValue } = useFormikContext<Record<string, unknown>>();\n const sameAs = section.sameAs;\n const toggleKey = sameAs ? sameAsToggleKey(section.id) : \"\";\n const toggleOn = sameAs ? values[toggleKey] === true : false;\n const fieldMap = sameAs?.fieldMap ?? {};\n // Re-copy whenever a mapped source value changes while the toggle is on.\n const sourceSignature = JSON.stringify(\n Object.values(fieldMap).map((sourceId) => values[sourceId] ?? null),\n );\n\n useEffect(() => {\n if (!sameAs || !toggleOn) return;\n for (const [targetId, sourceId] of Object.entries(sameAs.fieldMap)) {\n setFieldValue(targetId, values[sourceId] ?? \"\");\n }\n // values is read at run time; sourceSignature captures source changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toggleOn, sourceSignature]);\n\n // Resolution order: editor preview override > section-level > form-level.\n // When all are unset the title/description inherit from the surrounding\n // CSS so consumers can theme via their own typography.\n const effectiveTextColor =\n previewTextColor ?? section.textColor ?? formDefaultTextColor;\n\n const sortedFields = [...section.fields].sort(\n (a, b) => (a.layout?.order ?? 0) - (b.layout?.order ?? 0)\n );\n\n const gap = spacingGap[style.spacing || \"normal\"];\n const divider = style.sectionDividers && !isLast;\n const isStacked = style.inputVariant === \"stacked\";\n\n const sectionWrapperClass = twMerge(\n isStacked ? \"space-y-4\" : \"mb-6\",\n divider && \"border-b border-gray-200 dark:border-zinc-700 pb-6\"\n );\n\n // When an effective text color is set, drop the default Tailwind text-color\n // utilities so the inline style isn't overridden by dark-mode variants.\n const titleClass = twMerge(\n \"text-lg font-semibold\",\n effectiveTextColor ? \"\" : \"text-gray-800 dark:text-zinc-100\",\n !isStacked && \"mb-1\"\n );\n\n const descriptionClass = twMerge(\n \"text-sm\",\n effectiveTextColor ? \"\" : \"text-gray-500 dark:text-zinc-400\",\n !isStacked && \"mb-4\"\n );\n\n const textStyle = effectiveTextColor\n ? { color: effectiveTextColor }\n : undefined;\n\n return (\n <fieldset className={sectionWrapperClass}>\n {section.title && (\n <legend className={titleClass} style={textStyle}>\n {section.title}\n </legend>\n )}\n {section.description && (\n <p className={descriptionClass} style={textStyle}>\n {section.description}\n </p>\n )}\n {sameAs && (\n <div className=\"mb-4 flex items-center gap-3\">\n <Checkbox.Root\n id={toggleKey}\n checked={toggleOn}\n onCheckedChange={(checked) => setFieldValue(toggleKey, checked === true)}\n className=\"flex h-5 w-5 items-center justify-center rounded border\"\n style={\n toggleOn\n ? { borderColor: FORM_VAR.inputFocusBorder, backgroundColor: FORM_VAR.inputFocusBorder }\n : { borderColor: FORM_VAR.inputBorder, backgroundColor: FORM_VAR.inputBg }\n }\n >\n <Checkbox.Indicator>\n <BsCheck className=\"text-white\" />\n </Checkbox.Indicator>\n </Checkbox.Root>\n <label\n htmlFor={toggleKey}\n className=\"cursor-pointer text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {sameAs.toggleLabel}\n </label>\n </div>\n )}\n {(() => {\n const fieldsGrid = (\n <div\n className={twMerge(\n \"grid grid-cols-1 md:grid-cols-6\",\n gap,\n inlineSubmit && \"min-w-0 flex-auto\"\n )}\n >\n {/* Index-composited key: the builder's live preview can render\n transiently duplicated field ids mid-edit (saving them is\n blocked); ids alone would collide as keys. */}\n {sortedFields.map((field, i) => (\n <DynamicFormField\n key={`${field.id}-${i}`}\n field={field}\n mirrored={toggleOn && field.id in fieldMap}\n mirrorBehavior={sameAs?.behavior}\n />\n ))}\n </div>\n );\n\n return inlineSubmit ? (\n <div className=\"flex items-start gap-3\">\n {fieldsGrid}\n {/* Non-stacked field wrappers reserve pt-3 of floating-label\n headroom above the input border (see useInputStyles), so the\n button needs the same offset to align with the input box. */}\n <div className={twMerge(\"flex-none\", !isStacked && \"pt-3\")}>\n {inlineSubmit}\n </div>\n </div>\n ) : (\n fieldsGrid\n );\n })()}\n </fieldset>\n );\n};\n","\"use client\";\n\nimport { Formik, Form, type FormikProps } from \"formik\";\nimport { useEffect, useMemo, useRef, useState, type CSSProperties } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormDefinition, FormStyle, FormSuccessBehavior } from \"../types\";\nimport {\n DEFAULT_FORM_STYLE,\n DEFAULT_SPAM_PROTECTION,\n HONEYPOT_FIELD_NAME,\n sameAsToggleKey,\n} from \"../types\";\nimport { buildYupSchema } from \"../schema/buildYupSchema\";\nimport { buildInitialValues } from \"../utils/initialValues\";\nimport { isVisibilityConditionMet } from \"../utils/visibility\";\nimport { getSafeRedirectUrl } from \"../utils/redirect\";\nimport {\n encryptSensitiveValue,\n type TransportPublicKey,\n} from \"../crypto/sensitive\";\nimport { DynamicFormSection } from \"./DynamicFormSection\";\nimport {\n FormPreviewOverridesProvider,\n FormStyleProvider,\n} from \"./FormStyleContext\";\nimport { FORM_VAR, buildFormCssVars } from \"./cssVars\";\n\ninterface DynamicFormProps {\n /**\n * The CMS-authored schema, normally fetched from `GET /api/forms`. Note\n * that `projectId`, `integrations`, `notificationEmailTemplate` and\n * `applicationStatusEmails` are stripped from client-facing responses, so\n * they are always undefined here — never read `definition.projectId`.\n */\n definition: FormDefinition;\n /**\n * Endpoint this form POSTs to — expected to be a server-side proxy in the\n * consuming app that adds credentials and forwards to the CMS\n * `POST /api/contact`.\n *\n * The body is a FLAT JSON object: the definition's field ids as top-level\n * keys, plus `extraData`, plus `formId`. There is no `data`/`values`\n * wrapper. The honeypot, fields hidden by an unmet `showWhen`, and the\n * synthetic `_sameAs_*` toggles are stripped before sending. The renderer\n * never sends `projectId` / `apiKey` / `url` — the proxy must add those,\n * and must forward the browser's body WHOLE (hand-picking fields into a\n * new object drops values the CMS then rejects as required).\n *\n * Two CMS rejections to expect: `url` must exactly equal the project's\n * stored URL (so localhost dev submissions get `400 \"Invalid url\"`), and\n * a top-level `email` key is required on every submission type.\n */\n apiRoute: string;\n /**\n * Called after a successful submission. The argument is the parsed JSON\n * response body, when one was returned — application submissions echo\n * `{ success: true, referenceNumber: \"APP-…\" }` here so the consumer\n * can display it on its confirmation page.\n *\n * Also fired on the spam path (honeypot filled or submitted faster than\n * `minSubmitTime`) with NO argument and no network request at all — treat\n * a missing argument as \"no server response\", not as an error.\n */\n onSuccess?: (data?: unknown) => void;\n /**\n * Called when the submission fails. `DynamicForm` catches everything\n * internally and never throws at the call site, so this callback is the\n * only error channel. The message is the CMS `error` string when one was\n * returned (e.g. \"Invalid url\", \"Validation failed\"), otherwise\n * `Submission failed (<status>)`.\n */\n onError?: (error: Error) => void;\n /** Extra top-level keys merged into the payload alongside the field values. */\n extraData?: Record<string, unknown>;\n className?: string;\n /**\n * Endpoint that returns the RSA-OAEP transport public key used to wrap the\n * per-submission AES key for sensitive fields. Defaults to\n * `/api/forms/transport-key` (resolved against the same origin).\n *\n * The endpoint must respond with `{ kid: string, jwk: JsonWebKey }`.\n *\n * That route lives in the CMS, not in consumer apps — a consumer site with\n * a sensitive field must either proxy it or pass an absolute CMS URL here.\n * Only fetched when the definition actually contains a sensitive field.\n */\n transportKeyEndpoint?: string;\n /**\n * When set, overrides the form's internal submit state for preview purposes.\n * Network submissions are skipped while a previewState is active.\n */\n /**\n * Analytics callbacks. When omitted, the form falls back to the\n * `window.__vtTrack` hooks the @vulcantech/analytics tracker\n * registers — so form view/submit conversions track automatically on\n * any site running the tracker, with no per-form wiring.\n */\n onFormView?: (formId: string, formName: string) => void;\n onFormSubmit?: (formId: string, formName: string, submissionType: string) => void;\n previewState?: \"idle\" | \"submitting\" | \"success\" | \"error\";\n /**\n * Increment to trigger touching every field (so validation errors render).\n * Each new value re-runs the touch action.\n */\n previewTouchAllSignal?: number;\n /**\n * Increment to clear all touched state (so validation errors hide again).\n * Each new value re-runs the untouch action.\n */\n previewUntouchAllSignal?: number;\n /**\n * Editor-only background color override applied via inline style. Takes\n * precedence over `style.formBackgroundColor` for the lifetime of the\n * preview. Never persisted.\n */\n previewBg?: string;\n /**\n * Editor-only foreground color override propagated to section titles and\n * descriptions so dark backgrounds remain readable in preview. Never\n * persisted.\n */\n previewTextColor?: string;\n}\n\n/**\n * Returns the IDs of every `sensitive` field in the definition. Used to\n * locate plaintext values in the Formik state before submission so they can\n * be encrypted in place.\n */\n/**\n * Conversion hooks registered on `window` by the analytics tracker\n * (@vulcantech/analytics and the per-app copies of it). Used as the\n * fallback when no onFormView/onFormSubmit props are passed — keeps the\n * forms package free of a hard analytics dependency while making\n * conversion tracking automatic wherever the tracker runs.\n */\nfunction globalTracker():\n | {\n trackFormView?: (formId: string, formName: string) => void;\n trackFormSubmit?: (\n formId: string,\n formName: string,\n submissionType?: string,\n ) => void;\n }\n | undefined {\n if (typeof window === \"undefined\") return undefined;\n return (\n window as unknown as {\n __vtTrack?: {\n trackFormView?: (formId: string, formName: string) => void;\n trackFormSubmit?: (\n formId: string,\n formName: string,\n submissionType?: string,\n ) => void;\n };\n }\n ).__vtTrack;\n}\n\nfunction getSensitiveFieldIds(definition: FormDefinition): string[] {\n const ids: string[] = [];\n for (const section of definition.sections) {\n for (const field of section.fields) {\n if (field.type === \"sensitive\") ids.push(field.id);\n }\n }\n return ids;\n}\n\n/**\n * IDs of fields hidden by an unmet `showWhen` condition (mirrors the\n * renderer's visibility check). Their stale values must be stripped from\n * the payload — the user filled them in, flipped the condition off, and\n * the invisible value should not be submitted.\n */\nfunction getHiddenFieldIds(\n definition: FormDefinition,\n values: Record<string, unknown>,\n): string[] {\n const ids: string[] = [];\n for (const section of definition.sections) {\n for (const field of section.fields) {\n if (\n field.showWhen &&\n !isVisibilityConditionMet(field.showWhen, values[field.showWhen.fieldId])\n ) {\n ids.push(field.id);\n }\n }\n }\n return ids;\n}\n\n/**\n * Reserved Formik keys for \"same as\" section toggles. These are UI-only\n * controls and must be stripped from the submission payload (the copied\n * target field values are real and stay).\n */\nfunction getSameAsToggleKeys(definition: FormDefinition): string[] {\n return definition.sections\n .filter((s) => s.sameAs)\n .map((s) => sameAsToggleKey(s.id));\n}\n\nasync function fetchTransportKey(endpoint: string): Promise<TransportPublicKey> {\n const res = await fetch(endpoint, { method: \"GET\" });\n if (!res.ok) {\n throw new Error(\n `Failed to fetch transport key: ${res.status} ${res.statusText}`\n );\n }\n const data = (await res.json()) as TransportPublicKey;\n if (!data?.kid || !data?.jwk) {\n throw new Error(\"Transport key endpoint returned an invalid payload\");\n }\n return data;\n}\n\n// Presets only contribute non-background styling now (border / shadow / text\n// color). Every background — both the form surface and the input fill / label\n// mask via `--form-input-bg` — flows through inline styles below, so the form\n// stays transparent unless the definition opts in via `formBackgroundColor`\n// (or `inputBgColor`) and consumer Tailwind classes (especially `dark:`\n// variants) can't override the chosen color.\nconst presetNonBgClasses: Record<string, string> = {\n default: \"\",\n minimal: \"\",\n bordered: \"border border-gray-200\",\n shadow: \"shadow-lg\",\n card: \"shadow-lg border border-gray-200\",\n dark: \"\",\n};\n\nconst radiusClasses: Record<string, string> = {\n none: \"rounded-none\",\n sm: \"rounded-sm\",\n md: \"rounded-md\",\n lg: \"rounded-lg\",\n full: \"rounded-2xl\",\n};\n\nconst spacingClasses: Record<string, string> = {\n compact: \"p-3\",\n normal: \"p-6\",\n relaxed: \"p-8\",\n};\n\nfunction getButtonClasses(style: FormStyle): string {\n const radius = radiusClasses[style.borderRadius] || \"rounded-md\";\n const weight = style.inputVariant === \"stacked\" ? \"font-semibold\" : \"font-medium\";\n\n switch (style.buttonVariant) {\n case \"outline\":\n return `${radius} border-2 bg-transparent ${weight} transition-colors`;\n case \"ghost\":\n return `${radius} bg-transparent ${weight} transition-colors`;\n case \"filled\":\n default:\n return `${radius} ${weight} transition-colors`;\n }\n}\n\nfunction getButtonStyle(style: FormStyle): React.CSSProperties {\n // Pull colors from the form-root CSS variables (set by buildFormCssVars)\n // so a single update in the picker cascades here without having to thread\n // the resolved color through props.\n switch (style.buttonVariant) {\n case \"outline\":\n return { borderColor: FORM_VAR.buttonBg, color: FORM_VAR.buttonBg };\n case \"ghost\":\n return { color: FORM_VAR.buttonBg };\n case \"filled\":\n default:\n return {\n backgroundColor: FORM_VAR.buttonBg,\n color: FORM_VAR.buttonText,\n };\n }\n}\n\n/**\n * Replace `{{key}}` tokens in the success message with matching top-level\n * fields from the submit response body (currently used to surface the\n * `referenceNumber` echoed back by application submissions). Unknown keys\n * collapse to an empty string so the message stays presentable even when\n * the consumer's API didn't return the expected field.\n */\nfunction interpolateSuccessMessage(\n template: string,\n response: Record<string, unknown> | null,\n): string {\n if (!template.includes(\"{{\") || !response) return template;\n return template.replace(/\\{\\{\\s*([\\w.-]+)\\s*\\}\\}/g, (_match, key: string) => {\n const value = response[key];\n if (value === undefined || value === null) return \"\";\n return String(value);\n });\n}\n\nconst Spinner = () => (\n <svg\n className=\"-ml-1 mr-2 h-4 w-4 animate-spin\"\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n aria-hidden=\"true\"\n >\n <circle\n className=\"opacity-25\"\n cx=\"12\"\n cy=\"12\"\n r=\"10\"\n stroke=\"currentColor\"\n strokeWidth=\"4\"\n />\n <path\n className=\"opacity-75\"\n fill=\"currentColor\"\n d=\"M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z\"\n />\n </svg>\n);\n\nconst SuccessBanner = ({ message }: { message: string }) => (\n <div\n role=\"status\"\n aria-live=\"polite\"\n className=\"flex items-start gap-3 rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800\"\n >\n <svg\n className=\"mt-0.5 h-4 w-4 flex-shrink-0\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 20 20\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n >\n <path\n fillRule=\"evenodd\"\n d=\"M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm3.707-9.293a1 1 0 0 0-1.414-1.414L9 10.586 7.707 9.293a1 1 0 0 0-1.414 1.414l2 2a1 1 0 0 0 1.414 0l4-4z\"\n clipRule=\"evenodd\"\n />\n </svg>\n <span className=\"flex-1\">{message}</span>\n </div>\n);\n\nconst ErrorBanner = ({\n message,\n onDismiss,\n}: {\n message: string;\n onDismiss: () => void;\n}) => (\n <div\n role=\"alert\"\n className=\"flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800\"\n >\n <svg\n className=\"mt-0.5 h-4 w-4 flex-shrink-0\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 20 20\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n >\n <path\n fillRule=\"evenodd\"\n d=\"M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0zm-7 4a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-1-9a1 1 0 0 0-1 1v4a1 1 0 1 0 2 0V6a1 1 0 0 0-1-1z\"\n clipRule=\"evenodd\"\n />\n </svg>\n <span className=\"flex-1\">{message}</span>\n <button\n type=\"button\"\n onClick={onDismiss}\n className=\"font-medium text-red-900 underline-offset-2 hover:underline\"\n >\n Try again\n </button>\n </div>\n);\n\n/**\n * Render a CMS-authored {@link FormDefinition} as a working form.\n *\n * Sections and fields render in `order` (not array order); validation comes\n * from `buildYupSchema(definition)`; sensitive fields are encrypted in the\n * browser before submission. Submission goes to {@link DynamicFormProps.apiRoute}\n * as a flat JSON payload — see that prop for the wire contract.\n *\n * Failure mode: this component never throws. Network and CMS errors are\n * caught, shown in the built-in error banner, and reported via `onError`.\n * Note that a suppressed duplicate (an identical resubmit within 10 minutes)\n * and a server-side spam catch both answer `200` and are indistinguishable\n * from a stored lead by design.\n */\nexport const DynamicForm = ({\n definition,\n apiRoute,\n onSuccess,\n onError,\n extraData,\n className,\n onFormView,\n onFormSubmit: onFormSubmitCallback,\n transportKeyEndpoint = \"/api/forms/transport-key\",\n previewState,\n previewTouchAllSignal,\n previewUntouchAllSignal,\n previewBg,\n previewTextColor,\n}: DynamicFormProps) => {\n const [submitStatus, setSubmitStatus] = useState<\"idle\" | \"success\" | \"error\">(\"idle\");\n // Brief post-success lock so a double-click can't fire a second submission.\n // Time-boxed (not \"until remount\") — otherwise forms with the \"reset\" or\n // \"message\" success behavior could never be submitted a second time.\n const [postSuccessCooldown, setPostSuccessCooldown] = useState(false);\n useEffect(() => {\n if (submitStatus !== \"success\") return;\n setPostSuccessCooldown(true);\n const t = setTimeout(() => setPostSuccessCooldown(false), 2000);\n return () => clearTimeout(t);\n }, [submitStatus]);\n // Captured from the API response so the success message can interpolate\n // `{{referenceNumber}}` for application submissions. Cleared whenever\n // the form transitions back to idle/error.\n const [responseData, setResponseData] = useState<Record<string, unknown> | null>(\n null,\n );\n const formikRef = useRef<FormikProps<Record<string, string | boolean | string[]>> | null>(null);\n\n // Fire form view analytics on mount\n useEffect(() => {\n (onFormView ?? globalTracker()?.trackFormView)?.(\n definition.id,\n definition.name,\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const effectiveSubmitStatus: \"idle\" | \"success\" | \"error\" =\n previewState === \"success\"\n ? \"success\"\n : previewState === \"error\"\n ? \"error\"\n : previewState === \"idle\"\n ? \"idle\"\n : submitStatus;\n const previewSubmitting = previewState === \"submitting\";\n\n const spamProtection = {\n ...DEFAULT_SPAM_PROTECTION,\n ...definition.submitConfig.spamProtection,\n };\n const honeypotEnabled = spamProtection.honeypot !== false;\n const minSubmitTime = Math.max(0, spamProtection.minSubmitTime ?? 0);\n\n const mountTimeRef = useRef<number>(Date.now());\n useEffect(() => {\n mountTimeRef.current = Date.now();\n }, [definition.id]);\n\n const validationSchema = useMemo(() => buildYupSchema(definition), [definition]);\n const initialValues = useMemo(() => {\n const base = buildInitialValues(definition);\n if (honeypotEnabled) {\n base[HONEYPOT_FIELD_NAME] = \"\";\n }\n return base;\n }, [definition, honeypotEnabled]);\n\n const sortedSections = useMemo(\n () => [...definition.sections].sort((a, b) => a.order - b.order),\n [definition.sections]\n );\n\n useEffect(() => {\n if (previewTouchAllSignal === undefined || !formikRef.current) return;\n const touched: Record<string, boolean> = {};\n for (const section of definition.sections) {\n for (const field of section.fields) {\n touched[field.id] = true;\n }\n }\n formikRef.current.setTouched(touched, true);\n }, [previewTouchAllSignal, definition.sections]);\n\n useEffect(() => {\n if (previewUntouchAllSignal === undefined || !formikRef.current) return;\n // Skip validation — untouched fields don't render errors anyway.\n formikRef.current.setTouched({}, false);\n }, [previewUntouchAllSignal]);\n\n const style: FormStyle = { ...DEFAULT_FORM_STYLE, ...definition.style };\n const isStacked = style.inputVariant === \"stacked\";\n const isCard = style.preset === \"card\";\n\n const submittingText = definition.submitConfig.submittingText ?? \"Submitting...\";\n const successBehavior: FormSuccessBehavior =\n definition.submitConfig.successBehavior ?? \"message\";\n\n const hasPreviewOverride = Boolean(previewBg || previewTextColor);\n const previewOverrides = hasPreviewOverride\n ? { backgroundColor: previewBg, textColor: previewTextColor }\n : null;\n // Build the CSS-variable map the form root publishes: every color override\n // from the persisted FormStyle (or, for `--form-bg`, the editor's preview\n // override) is emitted here. Variables that aren't set are simply omitted,\n // and the renderer's `var(--name, fallback)` references resolve to the\n // baked-in defaults in `FORM_DEFAULT_COLOR`. This is what lets a single\n // picker change cascade to every input, button and label without any\n // prop-threading.\n const cssVarStyle = buildFormCssVars(style, previewBg);\n // The form root's actual `background-color` follows the effective surface\n // color so the chrome paints even before any child reads the CSS var.\n // Without this the input-bg var would resolve correctly inside fields but\n // the form root itself would be transparent against the preview canvas.\n const effectiveFormBg = previewBg ?? style.formBackgroundColor;\n const formInlineStyle: CSSProperties = {\n ...cssVarStyle,\n ...(effectiveFormBg ? { backgroundColor: effectiveFormBg } : {}),\n ...(previewTextColor ? { color: previewTextColor } : {}),\n };\n\n const formClasses = twMerge(\n presetNonBgClasses[style.preset] || \"\",\n radiusClasses[style.borderRadius] || \"rounded-md\",\n isCard ? \"p-8\" : spacingClasses[style.spacing] || \"p-6\",\n isStacked ? \"space-y-8\" : \"\",\n className\n );\n\n const inlineButton = style.buttonPlacement === \"inline\";\n const buttonSizeClass = inlineButton\n ? isStacked\n ? \"flex-none px-6 py-3 text-base\"\n : \"flex-none px-6 py-2.5 text-sm\"\n : isStacked\n ? \"w-full px-6 py-3 text-base\"\n : \"mt-4 w-full px-6 py-2.5 text-sm\";\n\n const bannerWrapperClass = isStacked ? \"\" : \"mb-4\";\n\n // Render `{{referenceNumber}}` (and any other top-level string field from\n // the API response) in the success message. Mostly relevant to\n // application submissions, which echo back `referenceNumber`. Falls\n // through to the raw message when no placeholders are present, which\n // keeps the contact-form flow identical to before.\n const successMessage = interpolateSuccessMessage(\n definition.submitConfig.successMessage,\n responseData,\n );\n\n if (successBehavior === \"replace\" && effectiveSubmitStatus === \"success\") {\n return (\n <FormStyleProvider value={style}>\n <FormPreviewOverridesProvider value={previewOverrides}>\n <div\n className={formClasses}\n style={formInlineStyle}\n data-form-version={definition.version}\n >\n <SuccessBanner message={successMessage} />\n </div>\n </FormPreviewOverridesProvider>\n </FormStyleProvider>\n );\n }\n\n return (\n <FormStyleProvider value={style}>\n <FormPreviewOverridesProvider value={previewOverrides}>\n <Formik\n innerRef={formikRef}\n initialValues={initialValues}\n validationSchema={validationSchema}\n onSubmit={async (values, { setSubmitting, resetForm }) => {\n if (previewState) {\n setSubmitting(false);\n return;\n }\n\n const honeypotTriggered =\n honeypotEnabled &&\n typeof values[HONEYPOT_FIELD_NAME] === \"string\" &&\n (values[HONEYPOT_FIELD_NAME] as string).length > 0;\n const elapsedSeconds = (Date.now() - mountTimeRef.current) / 1000;\n const timerTriggered =\n minSubmitTime > 0 && elapsedSeconds < minSubmitTime;\n\n if (honeypotTriggered || timerTriggered) {\n const proc = (globalThis as { process?: { env?: { NODE_ENV?: string } } })\n .process;\n if (proc?.env?.NODE_ENV !== \"production\") {\n const reason = honeypotTriggered ? \"honeypot\" : \"timer\";\n console.debug(`[forms] Spam detected: ${reason}`);\n }\n // Spam paths never get a real response — clear any stale data\n // so the success banner doesn't show a stale reference number.\n setResponseData(null);\n setSubmitStatus(\"success\");\n if (successBehavior === \"reset\" || successBehavior === \"replace\") {\n resetForm();\n }\n onSuccess?.();\n setSubmitting(false);\n return;\n }\n\n setSubmitStatus(\"idle\");\n try {\n // Strip the honeypot from the payload — it's already empty when\n // a human submits, but be defensive in case the field is renamed.\n const { [HONEYPOT_FIELD_NAME]: _hp, ...cleanValues } = values as Record<\n string,\n string | boolean | string[]\n >;\n const payload: Record<string, unknown> = {\n ...cleanValues,\n ...extraData,\n formId: definition.id,\n };\n\n // Drop values for fields currently hidden by showWhen — they're\n // invisible to the user and shouldn't reach the server.\n for (const hiddenId of getHiddenFieldIds(definition, cleanValues)) {\n delete payload[hiddenId];\n }\n\n // Drop the synthetic \"same as\" toggles — UI-only controls. The\n // copied target field values remain (they're real submission data).\n for (const toggleKey of getSameAsToggleKeys(definition)) {\n delete payload[toggleKey];\n }\n\n // Encrypt sensitive fields with the server's transport public key\n // before they ever leave the browser. The plaintext is replaced\n // in `payload` with an EncryptedSensitiveValue envelope; the API\n // route unwraps it server-side and re-encrypts with KMS.\n const sensitiveIds = getSensitiveFieldIds(definition);\n if (sensitiveIds.length > 0) {\n const transportKey = await fetchTransportKey(transportKeyEndpoint);\n for (const fieldId of sensitiveIds) {\n const plaintext = cleanValues[fieldId];\n if (typeof plaintext !== \"string\" || plaintext.length === 0) {\n delete payload[fieldId];\n continue;\n }\n payload[fieldId] = await encryptSensitiveValue(\n plaintext,\n transportKey\n );\n }\n }\n\n const res = await fetch(apiRoute, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (!res.ok) {\n // Surface the server's error message when it sent one —\n // `res.statusText` is usually empty with fetch.\n const errBody = (await res.json().catch(() => null)) as\n | { error?: string }\n | null;\n throw new Error(\n errBody?.error || `Submission failed (${res.status})`,\n );\n }\n\n // Parse JSON best-effort — the success path doesn't depend on\n // it but applications include a `referenceNumber` we surface in\n // the success message.\n let body: Record<string, unknown> | null = null;\n try {\n body = (await res.json()) as Record<string, unknown>;\n } catch {\n body = null;\n }\n setResponseData(body);\n setSubmitStatus(\"success\");\n (onFormSubmitCallback ?? globalTracker()?.trackFormSubmit)?.(\n definition.id,\n definition.name,\n (extraData?.submissionType as string) ?? \"contact\",\n );\n if (successBehavior === \"reset\" || successBehavior === \"replace\") {\n resetForm();\n }\n onSuccess?.(body ?? undefined);\n // Redirect only on genuine success — the fake-success spam path\n // above deliberately stays on-page so detected bots never reach\n // the redirect target and fire its ad-conversion tags. Never\n // reached in the builder preview (previewState short-circuits\n // before the network call).\n const redirectUrl = getSafeRedirectUrl(\n definition.submitConfig.redirectUrl,\n );\n if (redirectUrl) {\n window.location.assign(redirectUrl);\n }\n } catch (err) {\n setResponseData(null);\n setSubmitStatus(\"error\");\n onError?.(err instanceof Error ? err : new Error(\"Submission failed\"));\n } finally {\n setSubmitting(false);\n }\n }}\n >\n {({ isSubmitting, getFieldProps }) => {\n const showSubmitting = isSubmitting || previewSubmitting;\n const isDisabled =\n successBehavior === \"disable\" && effectiveSubmitStatus === \"success\";\n // Prevent double-submit: disable the button while submitting and\n // for a short cooldown after success.\n const submitLocked =\n showSubmitting ||\n postSuccessCooldown ||\n previewState === \"success\";\n\n return (\n <Form\n className={formClasses}\n style={formInlineStyle}\n data-form-version={definition.version}\n >\n {honeypotEnabled && (\n <div\n aria-hidden=\"true\"\n style={{\n position: \"absolute\",\n left: \"-9999px\",\n top: \"auto\",\n width: 0,\n height: 0,\n overflow: \"hidden\",\n opacity: 0,\n zIndex: -1,\n }}\n >\n <label htmlFor={HONEYPOT_FIELD_NAME}>\n Website (leave blank)\n </label>\n <input\n type=\"text\"\n id={HONEYPOT_FIELD_NAME}\n {...getFieldProps(HONEYPOT_FIELD_NAME)}\n tabIndex={-1}\n autoComplete=\"off\"\n />\n </div>\n )}\n {effectiveSubmitStatus === \"success\" && (\n <div className={bannerWrapperClass}>\n <SuccessBanner message={successMessage} />\n </div>\n )}\n\n {effectiveSubmitStatus === \"error\" && (\n <div className={bannerWrapperClass}>\n <ErrorBanner\n message={definition.submitConfig.errorMessage}\n onDismiss={() => setSubmitStatus(\"idle\")}\n />\n </div>\n )}\n\n <fieldset\n disabled={isDisabled}\n aria-disabled={isDisabled}\n className={twMerge(\n \"min-w-0 border-0 p-0\",\n isStacked ? \"space-y-8\" : \"\",\n isDisabled ? \"pointer-events-none opacity-60\" : \"\"\n )}\n >\n {(() => {\n const submitButton = (\n <button\n type=\"submit\"\n disabled={submitLocked || isDisabled}\n className={twMerge(\n buttonSizeClass,\n \"inline-flex cursor-pointer items-center justify-center disabled:cursor-not-allowed disabled:opacity-60\",\n getButtonClasses(style)\n )}\n style={getButtonStyle(style)}\n aria-busy={showSubmitting}\n >\n {showSubmitting && <Spinner />}\n {showSubmitting ? submittingText : definition.submitConfig.buttonText}\n </button>\n );\n\n // Inline placement hands the button to the last section,\n // which renders it beside its fields grid — the section\n // title/description stay full-width above the row.\n return (\n <>\n {sortedSections.map((section, idx) => {\n const isLast = idx === sortedSections.length - 1;\n return (\n <DynamicFormSection\n key={section.id}\n section={section}\n isLast={isLast}\n formDefaultTextColor={definition.defaultTextColor}\n inlineSubmit={\n inlineButton && isLast ? submitButton : undefined\n }\n />\n );\n })}\n {!inlineButton && submitButton}\n </>\n );\n })()}\n </fieldset>\n </Form>\n );\n }}\n </Formik>\n </FormPreviewOverridesProvider>\n </FormStyleProvider>\n );\n};\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport type { FormDefinition } from \"../types\";\n\ninterface BaseFetchOptions {\n cmsUrl: string;\n projectId: string;\n apiKey: string;\n}\n\n/**\n * One of `formId` or `formSlug` must be provided to identify which form to load.\n */\nexport type FormIdentifier =\n | { formId: string; formSlug?: never }\n | { formId?: never; formSlug: string };\n\nexport type UseFormDefinitionOptions = BaseFetchOptions & FormIdentifier;\n\ninterface UseFormDefinitionResult {\n definition: FormDefinition | null;\n isLoading: boolean;\n error: Error | null;\n}\n\nfunction buildQueryString(opts: UseFormDefinitionOptions): string {\n const params = new URLSearchParams({\n projectId: opts.projectId,\n apiKey: opts.apiKey,\n });\n if (\"formId\" in opts && opts.formId) params.set(\"formId\", opts.formId);\n if (\"formSlug\" in opts && opts.formSlug) params.set(\"slug\", opts.formSlug);\n return params.toString();\n}\n\nexport function useFormDefinition(\n opts: UseFormDefinitionOptions,\n): UseFormDefinitionResult {\n const [definition, setDefinition] = useState<FormDefinition | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const { cmsUrl, projectId, apiKey } = opts;\n const formId = \"formId\" in opts ? opts.formId : undefined;\n const formSlug = \"formSlug\" in opts ? opts.formSlug : undefined;\n\n useEffect(() => {\n let cancelled = false;\n\n async function fetchDefinition() {\n setIsLoading(true);\n setError(null);\n\n try {\n const qs = buildQueryString(opts);\n const res = await fetch(`${cmsUrl}/api/forms?${qs}`);\n\n if (!res.ok) {\n throw new Error(`Failed to fetch form definition: ${res.statusText}`);\n }\n\n const data = await res.json();\n if (!cancelled) {\n setDefinition(data);\n }\n } catch (err) {\n if (!cancelled) {\n setError(err instanceof Error ? err : new Error(\"Failed to fetch form\"));\n }\n } finally {\n if (!cancelled) {\n setIsLoading(false);\n }\n }\n }\n\n fetchDefinition();\n\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [cmsUrl, projectId, apiKey, formId, formSlug]);\n\n return { definition, isLoading, error };\n}\n\n/**\n * Server-side fetch for use in Next.js Server Components / RSC / getStaticProps.\n * Returns `null` on any error or when the form does not exist.\n */\nexport async function getFormDefinition(\n opts: UseFormDefinitionOptions & { revalidate?: number },\n): Promise<FormDefinition | null> {\n try {\n const qs = buildQueryString(opts);\n // Cast — `next` is a Next.js extension to RequestInit not present in the\n // forms package's stock TS lib. Consuming Next apps see the augmented type.\n const res = await fetch(`${opts.cmsUrl}/api/forms?${qs}`, {\n next: { revalidate: opts.revalidate ?? 3600 },\n } as RequestInit);\n\n if (!res.ok) return null;\n return res.json();\n } catch {\n return null;\n }\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nconst DEFAULT_HISTORY_LIMIT = 50;\n\nexport type SetStateUpdater<T> = T | ((prev: T) => T);\n\nexport interface UseUndoRedoOptions {\n /** Maximum number of past entries to retain. Defaults to 50. */\n historyLimit?: number;\n}\n\nexport interface UseUndoRedoControls<T> {\n /** Replace the current state without recording history. Clears past+future. */\n reset: (value: T) => void;\n /** Number of past entries currently retained. */\n historySize: number;\n}\n\nexport type UseUndoRedoReturn<T> = [\n T,\n (value: SetStateUpdater<T>) => void,\n () => void,\n () => void,\n boolean,\n boolean,\n UseUndoRedoControls<T>,\n];\n\ninterface History<T> {\n past: T[];\n present: T;\n future: T[];\n}\n\nfunction applyUpdater<T>(updater: SetStateUpdater<T>, current: T): T {\n return typeof updater === \"function\"\n ? (updater as (prev: T) => T)(current)\n : updater;\n}\n\n/**\n * Generic undo/redo state hook.\n *\n * Returns a tuple shaped like `useState`, plus undo/redo callbacks and\n * canUndo/canRedo flags. The 7th element exposes controls (`reset`,\n * `historySize`) that are only needed in advanced cases — most callers can\n * destructure just the first six.\n *\n * History is bounded at `historyLimit` (default 50) — the oldest past entries\n * are dropped when the cap is reached.\n */\nexport function useUndoRedo<T>(\n initialState: T,\n options: UseUndoRedoOptions = {},\n): UseUndoRedoReturn<T> {\n const limit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;\n\n const [history, setHistory] = useState<History<T>>(() => ({\n past: [],\n present: initialState,\n future: [],\n }));\n\n const setState = useCallback(\n (updater: SetStateUpdater<T>) => {\n setHistory((h) => {\n const next = applyUpdater(updater, h.present);\n if (Object.is(next, h.present)) return h;\n const past = [...h.past, h.present];\n if (past.length > limit) past.splice(0, past.length - limit);\n return { past, present: next, future: [] };\n });\n },\n [limit],\n );\n\n const reset = useCallback((value: T) => {\n setHistory((h) =>\n Object.is(value, h.present)\n ? h\n : { past: [], present: value, future: [] },\n );\n }, []);\n\n const undo = useCallback(() => {\n setHistory((h) => {\n if (h.past.length === 0) return h;\n const previous = h.past[h.past.length - 1];\n const past = h.past.slice(0, -1);\n return { past, present: previous, future: [h.present, ...h.future] };\n });\n }, []);\n\n const redo = useCallback(() => {\n setHistory((h) => {\n if (h.future.length === 0) return h;\n const [next, ...rest] = h.future;\n return { past: [...h.past, h.present], present: next, future: rest };\n });\n }, []);\n\n return [\n history.present,\n setState,\n undo,\n redo,\n history.past.length > 0,\n history.future.length > 0,\n { reset, historySize: history.past.length },\n ];\n}\n\n/**\n * Wires Cmd/Ctrl+Z (undo) and Cmd/Ctrl+Shift+Z (redo) keyboard shortcuts.\n *\n * Skips the shortcut when the user is typing in an input/textarea or\n * contenteditable region, so the browser's native input-history undo works\n * inside text fields without clobbering form-level history.\n */\nexport function useUndoRedoShortcuts(opts: {\n undo: () => void;\n redo: () => void;\n enabled?: boolean;\n}) {\n const { undo, redo, enabled = true } = opts;\n\n useEffect(() => {\n if (!enabled || typeof window === \"undefined\") return;\n\n const handler = (e: KeyboardEvent) => {\n const target = e.target as HTMLElement | null;\n if (target) {\n const tag = target.tagName;\n const editable = (target as HTMLElement).isContentEditable;\n if (\n tag === \"INPUT\" ||\n tag === \"TEXTAREA\" ||\n tag === \"SELECT\" ||\n editable\n ) {\n return;\n }\n }\n\n const meta = e.metaKey || e.ctrlKey;\n if (!meta) return;\n const key = e.key.toLowerCase();\n if (key !== \"z\") return;\n\n e.preventDefault();\n if (e.shiftKey) {\n redo();\n } else {\n undo();\n }\n };\n\n window.addEventListener(\"keydown\", handler);\n return () => window.removeEventListener(\"keydown\", handler);\n }, [undo, redo, enabled]);\n}\n","\"use client\";\n\nimport { useCallback, useRef, useState, type DragEvent } from \"react\";\n\nexport type DropPosition = \"before\" | \"after\";\n\nexport interface DragReorderState {\n draggingId: string | null;\n dragOverId: string | null;\n dragOverPosition: DropPosition | null;\n}\n\nexport interface DragReorderItemHandlers {\n draggable: true;\n onDragStart: (e: DragEvent<HTMLElement>) => void;\n onDragEnd: (e: DragEvent<HTMLElement>) => void;\n onDragOver: (e: DragEvent<HTMLElement>) => void;\n onDragLeave: (e: DragEvent<HTMLElement>) => void;\n onDrop: (e: DragEvent<HTMLElement>) => void;\n}\n\nexport interface UseDragReorderOptions<T> {\n items: T[];\n getId: (item: T) => string;\n onReorder: (newOrder: T[]) => void;\n /**\n * MIME type for the drag payload. Different reorder zones (e.g. sections vs.\n * fields) should use different types so a section drag can't be dropped on a\n * field row by accident.\n */\n dragType?: string;\n}\n\nexport interface UseDragReorderResult extends DragReorderState {\n itemHandlers: (id: string) => DragReorderItemHandlers;\n /** True when this item is being dragged. Useful for opacity styling. */\n isDragging: (id: string) => boolean;\n /**\n * Returns the drop indicator position for `id` (\"before\" / \"after\" / null).\n * Render a 2px blue line at the matching edge.\n */\n dropIndicator: (id: string) => DropPosition | null;\n}\n\nconst DEFAULT_DRAG_TYPE = \"application/x-vt-reorder\";\n\n/**\n * HTML5 drag-and-drop reordering for a flat list of items.\n *\n * Each item should spread the handlers returned by `itemHandlers(id)` onto\n * its root element, and render a drop indicator using `dropIndicator(id)`.\n *\n * The hook computes drop position from the cursor position relative to the\n * hovered item — top half means \"drop before\", bottom half means \"drop after\".\n */\nexport function useDragReorder<T>({\n items,\n getId,\n onReorder,\n dragType = DEFAULT_DRAG_TYPE,\n}: UseDragReorderOptions<T>): UseDragReorderResult {\n const [state, setState] = useState<DragReorderState>({\n draggingId: null,\n dragOverId: null,\n dragOverPosition: null,\n });\n\n // Track the most recent dragOver target so we can clear on drop without\n // depending on the dragLeave/dragEnd ordering, which differs between browsers.\n const lastOverRef = useRef<string | null>(null);\n\n const reset = useCallback(() => {\n lastOverRef.current = null;\n setState({ draggingId: null, dragOverId: null, dragOverPosition: null });\n }, []);\n\n const itemHandlers = useCallback(\n (id: string): DragReorderItemHandlers => ({\n draggable: true,\n onDragStart: (e) => {\n e.stopPropagation();\n try {\n e.dataTransfer.setData(dragType, id);\n e.dataTransfer.setData(\"text/plain\", id);\n } catch {\n /* setData throws in some test envs — ignore */\n }\n e.dataTransfer.effectAllowed = \"move\";\n setState({\n draggingId: id,\n dragOverId: null,\n dragOverPosition: null,\n });\n },\n onDragEnd: () => {\n reset();\n },\n onDragOver: (e) => {\n // Only react to drags initiated for this reorder zone.\n const types = Array.from(e.dataTransfer.types);\n if (!types.includes(dragType)) return;\n e.preventDefault();\n e.stopPropagation();\n e.dataTransfer.dropEffect = \"move\";\n\n const rect = e.currentTarget.getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position: DropPosition =\n e.clientY < midpoint ? \"before\" : \"after\";\n\n if (\n lastOverRef.current !== id ||\n state.dragOverPosition !== position\n ) {\n lastOverRef.current = id;\n setState((s) => ({\n ...s,\n dragOverId: id,\n dragOverPosition: position,\n }));\n }\n },\n onDragLeave: (e) => {\n // dragleave fires when the cursor enters a child element too — only\n // clear if we're actually leaving the item element.\n const related = e.relatedTarget as Node | null;\n if (!related || !e.currentTarget.contains(related)) {\n if (lastOverRef.current === id) {\n lastOverRef.current = null;\n setState((s) => ({\n ...s,\n dragOverId: null,\n dragOverPosition: null,\n }));\n }\n }\n },\n onDrop: (e) => {\n const draggedId = e.dataTransfer.getData(dragType);\n e.preventDefault();\n e.stopPropagation();\n if (!draggedId || draggedId === id) {\n reset();\n return;\n }\n\n const fromIdx = items.findIndex((it) => getId(it) === draggedId);\n const toIdx = items.findIndex((it) => getId(it) === id);\n if (fromIdx < 0 || toIdx < 0) {\n reset();\n return;\n }\n\n const rect = e.currentTarget.getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position: DropPosition =\n e.clientY < midpoint ? \"before\" : \"after\";\n\n const next = [...items];\n const [moved] = next.splice(fromIdx, 1);\n // Recompute target index now that we removed `fromIdx`.\n let insertIdx = next.findIndex((it) => getId(it) === id);\n if (insertIdx < 0) insertIdx = next.length;\n if (position === \"after\") insertIdx += 1;\n next.splice(insertIdx, 0, moved);\n onReorder(next);\n reset();\n },\n }),\n [items, getId, onReorder, dragType, reset, state.dragOverPosition],\n );\n\n const isDragging = useCallback(\n (id: string) => state.draggingId === id,\n [state.draggingId],\n );\n\n const dropIndicator = useCallback(\n (id: string): DropPosition | null => {\n if (state.dragOverId !== id) return null;\n if (state.draggingId === id) return null;\n return state.dragOverPosition;\n },\n [state.dragOverId, state.draggingId, state.dragOverPosition],\n );\n\n return {\n ...state,\n itemHandlers,\n isDragging,\n dropIndicator,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/utils/visibility.ts","../src/schema/buildYupSchema.ts","../src/utils/initialValues.ts","../src/utils/transforms.ts","../src/utils/redirect.ts","../src/utils/conversion.ts","../src/utils/textTransforms.ts","../src/utils/renderEmailTemplate.ts","../src/utils/resizeImage.ts","../src/crypto/sensitive.ts","../src/tracking/adReferral.ts","../src/tracking/analyticsSession.ts","../src/utils/colorScheme.ts","../src/renderer/cssVars.ts","../src/renderer/FormStyleContext.tsx","../src/renderer/fields/useInputStyles.ts","../src/renderer/fields/StyledInput.tsx","../src/renderer/fields/TextField.tsx","../src/renderer/fields/EmailField.tsx","../src/renderer/fields/PhoneField.tsx","../src/renderer/fields/UrlField.tsx","../src/renderer/fields/AddressField.tsx","../src/renderer/fields/TextAreaField.tsx","../src/renderer/fields/SelectField.tsx","../src/renderer/fields/CheckboxField.tsx","../src/renderer/fields/RadioField.tsx","../src/renderer/fields/NumberField.tsx","../src/renderer/fields/dateExclusions.ts","../src/renderer/fields/DateTimeField.tsx","../src/renderer/fields/DateField.tsx","../src/renderer/fields/HiddenField.tsx","../src/renderer/fields/SensitiveField.tsx","../src/renderer/FileUploadContext.tsx","../src/renderer/fields/FileField.tsx","../src/renderer/DynamicFormField.tsx","../src/renderer/DynamicFormSection.tsx","../src/hooks/useSuccessFeedback.ts","../src/renderer/DynamicForm.tsx","../src/tracking/AdReferralTracker.tsx","../src/hooks/useFormDefinition.ts","../src/hooks/useUndoRedo.ts","../src/hooks/useDragReorder.ts"],"names":["jsx","useField","useState","jsxs","twMerge","BsCheck","set","parse","format","createContext","useContext","useEffect","_a","_b","useFormikContext","Checkbox","useRef","_d","_c","useCallback","e"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJO,IAAM,8BAAA,GAAuD;AAAA,EAClE,OAAA,EAAS,EAAA;AAAA,EACT,WAAA,EAAa,CAAC,OAAA,EAAS,uBAAuB,CAAA;AAAA,EAC9C,SAAA,EAAW;AACb;AAwCO,IAAM,yBAAA,GAA6C;AAAA,EACxD,MAAA,EAAQ,SAAA;AAAA,EACR,YAAA,EAAc,KAAK,IAAA,GAAO,IAAA;AAAA,EAC1B,QAAA,EAAU,KAAA;AAAA,EACV,QAAA,EAAU,CAAA;AAAA,EACV,YAAA,EAAc,IAAA;AAAA,EACd,aAAA,EAAe;AACjB;AA2JO,IAAM,mBAAA,GAAsB;AAG5B,IAAM,qBAAA,GAAwB;AAC9B,IAAM,kBAAkB,CAAC,SAAA,KAC9B,CAAA,EAAG,qBAAqB,GAAG,SAAS,CAAA;AAG/B,IAAM,uBA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A;AAAA,IACA,CAAC,KAAA,EAAO,KAAA,EAAO,WAAW,QAAA,EAAU,KAAA,EAAO,MAAM,gBAAgB;AAAA,GACnE;AAEA,EAAA,MAAM,UAAA,GAAaD,WAAAA;AAAA,IACjB,CAAC,EAAA,KAAe,KAAA,CAAM,UAAA,KAAe,EAAA;AAAA,IACrC,CAAC,MAAM,UAAU;AAAA,GACnB;AAEA,EAAA,MAAM,aAAA,GAAgBA,WAAAA;AAAA,IACpB,CAAC,EAAA,KAAoC;AACnC,MAAA,IAAI,KAAA,CAAM,UAAA,KAAe,EAAA,EAAI,OAAO,IAAA;AACpC,MAAA,IAAI,KAAA,CAAM,UAAA,KAAe,EAAA,EAAI,OAAO,IAAA;AACpC,MAAA,OAAO,KAAA,CAAM,gBAAA;AAAA,IACf,CAAA;AAAA,IACA,CAAC,KAAA,CAAM,UAAA,EAAY,KAAA,CAAM,UAAA,EAAY,MAAM,gBAAgB;AAAA,GAC7D;AAEA,EAAA,OAAO,iCACF,KAAA,CAAA,EADE;AAAA,IAEL,YAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF,CAAA;AACF","file":"index.mjs","sourcesContent":["export type FieldType =\n | \"text\"\n | \"email\"\n | \"phone\"\n | \"url\"\n | \"address\"\n | \"textarea\"\n | \"select\"\n | \"checkbox\"\n | \"radio\"\n | \"number\"\n | \"date\"\n | \"datetime\"\n | \"hidden\"\n | \"sensitive\"\n | \"file\";\n\nexport type TextTransform =\n | \"capitalize-sentences\"\n | \"capitalize-words\"\n | \"phone-number\"\n | \"ssn\";\n\nexport interface ValidationRule {\n type:\n | \"required\"\n | \"min\"\n | \"max\"\n | \"minLength\"\n | \"maxLength\"\n | \"pattern\"\n | \"email\"\n | \"phone\"\n | \"notEquals\";\n value?: string | number | boolean;\n message: string;\n}\n\nexport interface FieldOption {\n label: string;\n value: string;\n}\n\nexport type FieldWidth = \"full\" | \"half\" | \"third\";\n\n/** A blocked window inside one calendar day. Times are local \"HH:mm\". */\nexport interface ExcludedTimeRange {\n /** The day this range applies to, \"yyyy-MM-dd\". */\n date: string;\n /** Start of the closed window, inclusive. */\n from: string;\n /** End of the closed window, exclusive. */\n to: string;\n}\n\nexport interface DatetimeConfig {\n showTimeSelect?: boolean;\n timeIntervals?: number;\n minTime?: string;\n maxTime?: string;\n excludeWeekends?: boolean;\n excludePastDates?: boolean;\n /** Block selecting today — for forms needing at least a day of lead time. */\n excludeToday?: boolean;\n /** Block selecting tomorrow. */\n excludeTomorrow?: boolean;\n /**\n * Block selecting the next business day relative to today (the first\n * non-weekend day after today — on a Friday or Saturday that's Monday).\n */\n excludeNextBusinessDay?: boolean;\n /**\n * Specific calendar days to block, as `\"yyyy-MM-dd\"` strings — holidays,\n * shop closures, vacations. Unlike the rule-based exclusions above these\n * name individual dates, so they are the mechanism a CMS closure calendar\n * uses: `/api/forms` merges the project's booking closures into this list\n * on every booking form's date fields before serving the definition.\n *\n * Dates are compared as local calendar days, so a viewer in any timezone\n * sees the same day blocked.\n */\n excludeDates?: string[];\n /**\n * Parts of a day to block, for days that are only partly closed — closing\n * early, opening late, an afternoon off. Written by the same CMS closure\n * calendar as {@link DatetimeConfig.excludeDates}; a day listed there is\n * closed outright and needs no ranges here.\n *\n * A day may carry several ranges. `from` is inclusive and `to` is\n * exclusive, so 12:00–18:00 blocks the 12:00 slot and leaves an 18:00 one\n * bookable — the shape a \"closed from noon\" instruction actually means.\n * Ranges only affect fields that offer a time; a date-only field ignores\n * them, since half a day is still that day.\n */\n excludeTimeRanges?: ExcludedTimeRange[];\n filterPastTimes?: boolean;\n dateFormat?: string;\n placeholderText?: string;\n}\n\n/**\n * Comparison applied by a {@link FieldVisibilityCondition}. `greater-than` /\n * `less-than` compare numerically (both sides parsed as numbers; the\n * condition is unmet when either side isn't numeric).\n */\nexport type VisibilityOperator =\n | \"equals\"\n | \"not-equals\"\n | \"greater-than\"\n | \"less-than\";\n\nexport interface FieldVisibilityCondition {\n fieldId: string;\n value: string | boolean;\n /** Defaults to \"equals\" (the only behavior before operators existed). */\n operator?: VisibilityOperator;\n}\n\n/**\n * Per-field configuration for the `sensitive` field type. Sensitive fields\n * are encrypted client-side before submission, re-encrypted by the server\n * with a KMS-managed key, and stored in an isolated `sensitive_data`\n * collection. The TTL controls automatic deletion; viewerRoles gates which\n * authenticated users can call the decrypt Cloud Function to reveal the\n * value.\n */\nexport interface SensitiveFieldConfig {\n /** Days until the encrypted record auto-deletes. Defaults to 30. */\n ttlDays: 30 | 60 | 90;\n /**\n * Roles allowed to invoke the decrypt Cloud Function. The Cloud Function\n * re-checks against the caller's user document; this list is also used to\n * gate the Reveal button in the CMS UI.\n */\n viewerRoles: string[];\n /**\n * Optional input mask pattern. Currently only `ssn` is implemented\n * (formats input as XXX-XX-XXXX, validates 9 digits). When omitted, the\n * field accepts free-form text. The form builder keeps this in lockstep\n * with the field-level `ssn` TextTransform — both drive the same\n * formatter, and the renderer honors either.\n */\n inputMask?: \"ssn\";\n}\n\nexport const DEFAULT_SENSITIVE_FIELD_CONFIG: SensitiveFieldConfig = {\n ttlDays: 30,\n viewerRoles: [\"admin\", \"sensitive_data_viewer\"],\n inputMask: \"ssn\",\n};\n\n/**\n * Configuration for the `file` field type. Files are uploaded by the\n * consuming app before submit; the form submission receives the resulting\n * URL(s) rather than raw file data — a string, or an array of strings when\n * `multiple`. The CMS stores whatever string arrives and does nothing\n * file-specific with it.\n *\n * Uploads are NOT automatic: a form containing a `file` field must be given\n * an upload path via `DynamicForm`'s `onFileUpload` or `fileUploadRoute`\n * prop (see {@link FormFileUploadHandler}). Without one the picker renders\n * disabled with an explanatory message rather than silently submitting a\n * throwaway `blob:` URL.\n */\nexport interface FileFieldConfig {\n /** Accepted MIME types. Default: \"image/*\" */\n accept?: string;\n /** Max file size in bytes. Default: 10MB (10485760). */\n maxSizeBytes?: number;\n /** Allow multiple files. Default: false. */\n multiple?: boolean;\n /** Max number of files when multiple=true. Default: 5. */\n maxFiles?: number;\n /**\n * Downscale images in the browser before handing them to the upload\n * handler. Default: true.\n *\n * Applies only to JPEG, PNG and WebP, and only when the image is wider\n * than {@link FileFieldConfig.maxImageWidth}; the format is preserved and\n * anything that can't be re-encoded (GIF — a canvas round-trip would drop\n * the animation, HEIC/HEIF, SVG, a file this browser can't decode) is\n * uploaded untouched. `maxSizeBytes` is checked against the resized file,\n * so a large photo that fits once downscaled is accepted.\n */\n resizeImages?: boolean;\n /** Max image width in pixels when `resizeImages`. Default: 1600. */\n maxImageWidth?: number;\n}\n\nexport const DEFAULT_FILE_FIELD_CONFIG: FileFieldConfig = {\n accept: \"image/*\",\n maxSizeBytes: 10 * 1024 * 1024,\n multiple: false,\n maxFiles: 5,\n resizeImages: true,\n maxImageWidth: 1600,\n};\n\n/**\n * A file that has finished uploading. `url` is the value the form submits\n * for the field (or one entry of the array, when `multiple`), so it must be\n * durable and reachable outside the submitting browser tab — never a\n * `blob:` or `data:` URL.\n */\nexport interface UploadedFormFile {\n /** Stored, publicly reachable URL. */\n url: string;\n /** Display name, shown in the field's file list. */\n name: string;\n /** Size in bytes, shown in the field's file list. */\n size: number;\n}\n\n/**\n * Uploads one picked file and resolves with its stored location.\n *\n * Supplied by the consuming app — this package deliberately ships no\n * default implementation, because a public form submitter holds no CMS\n * credentials. The usual shape mirrors `DynamicForm`'s `apiRoute`: POST the\n * file to a server-side route in your own app, which holds the credentials\n * and writes to storage, then return the stored URL.\n *\n * Called once per file, sequentially. Throw to fail the file — the message\n * is shown inline under the picker and no value is recorded.\n */\nexport type FormFileUploadHandler = (\n file: File,\n config: FileFieldConfig,\n) => Promise<UploadedFormFile>;\n\nexport interface FormFieldDefinition {\n id: string;\n type: FieldType;\n label: string;\n placeholder?: string;\n helpText?: string;\n description?: string;\n defaultValue?: string;\n transform?: TextTransform;\n validation: ValidationRule[];\n options?: FieldOption[];\n layout?: {\n width: FieldWidth;\n order: number;\n };\n characterCounter?: boolean;\n rows?: number;\n datetimeConfig?: DatetimeConfig;\n showWhen?: FieldVisibilityCondition;\n /** Required when `type === \"sensitive\"`. Ignored for other field types. */\n sensitiveConfig?: SensitiveFieldConfig;\n /** Configuration for `type === \"file\"`. */\n fileConfig?: FileFieldConfig;\n}\n\n/**\n * \"Same as another section\" mirroring. A later section can copy values from\n * an earlier one (e.g. billing address = home address) behind a checkbox.\n */\nexport interface SectionSameAsConfig {\n /** Section whose values are copied in. MUST have a lower `order`. */\n sourceSectionId: string;\n /** targetFieldId (in THIS section) -> sourceFieldId (in the source section). */\n fieldMap: Record<string, string>;\n /** Checkbox label, e.g. \"Billing same as home address\". */\n toggleLabel: string;\n /** Hide the target fields while mirrored, or show them locked (read-only). */\n behavior: \"hide\" | \"lock\";\n}\n\nexport interface FormSection {\n id: string;\n title?: string;\n description?: string;\n fields: FormFieldDefinition[];\n order: number;\n /**\n * Optional hex color (e.g. \"#ffffff\") applied as inline color to the\n * section's title and description. When unset, the section inherits its\n * color from the form-level `defaultTextColor` or, if that's also unset,\n * from the surrounding CSS cascade.\n */\n textColor?: string;\n /**\n * Dark-mode counterpart of `textColor`. In dark mode the dark chain is\n * consulted first (this, then the form's `defaultTextColorDark`) and only\n * then the light chain — so one form-level dark color re-themes every\n * section header, even ones that pinned a light `textColor`.\n */\n textColorDark?: string;\n /** When set, this section mirrors fields from an earlier section. */\n sameAs?: SectionSameAsConfig;\n}\n\nexport type FormSuccessBehavior = \"message\" | \"replace\" | \"reset\" | \"disable\";\n\nexport interface FormSpamProtectionConfig {\n /** Adds an invisible honeypot field that catches bots. Defaults to true. */\n honeypot?: boolean;\n /** Minimum seconds between mount and submit. Set to 0 to disable. Defaults to 3. */\n minSubmitTime?: number;\n}\n\n/**\n * Google Ads conversion settings for a single form.\n *\n * The `form_submit_success` dataLayer event fires on every successful submit\n * regardless of this config; these settings only control the *direct*\n * `gtag('event', 'conversion', …)` call, which sites without a GTM container\n * need. Leave unset to inherit the project-wide `formConversionSendTo`\n * tracking tag that `@vulcantech/analytics`'s `CMSTags` publishes.\n */\nexport interface FormConversionConfig {\n /**\n * Google Ads conversion label in `AW-<id>/<label>` form, e.g.\n * `\"AW-18321257894/AbC-D3fGhIjKlmNoP\"`. Copy it from Google Ads → Goals →\n * the conversion action → Tag setup → \"Install the tag yourself\".\n */\n sendTo?: string;\n}\n\nexport interface FormSubmitConfig {\n buttonText: string;\n submittingText?: string;\n /**\n * Terminal label the submit button shows after a successful submission,\n * for as long as no field has been edited since. Defaults to `\"Sent\"` —\n * `buttonText` returning makes a submitted form look unsubmitted, which is\n * what drove customers to click Submit twice.\n */\n submittedText?: string;\n successMessage: string;\n errorMessage: string;\n successBehavior?: FormSuccessBehavior;\n /**\n * When set, the browser navigates here after a successful submission\n * instead of staying on the page — typically a dedicated thank-you page\n * used for Google Ads conversion tracking. Must be an absolute http(s)\n * URL or a site-relative path (`/thank-you`); see `getSafeRedirectUrl`.\n * Takes precedence over `successBehavior` on real (non-spam) submits.\n */\n redirectUrl?: string;\n spamProtection?: FormSpamProtectionConfig;\n /**\n * Per-form Google Ads conversion override. Optional — see\n * {@link FormConversionConfig}.\n */\n conversion?: FormConversionConfig;\n}\n\n/** Field name used for the honeypot. Bots tend to fill anything called \"website\". */\nexport const HONEYPOT_FIELD_NAME = \"_hp_website\";\n\n/** Reserved Formik key for a section's synthetic \"same as\" toggle. Stripped before submit. */\nexport const SAME_AS_TOGGLE_PREFIX = \"_sameAs_\";\nexport const sameAsToggleKey = (sectionId: string): string =>\n `${SAME_AS_TOGGLE_PREFIX}${sectionId}`;\n\n/** Default spam-protection settings (opt-out). */\nexport const DEFAULT_SPAM_PROTECTION: Required<FormSpamProtectionConfig> = {\n honeypot: true,\n minSubmitTime: 3,\n};\n\nexport type FormStylePreset =\n | \"default\"\n | \"minimal\"\n | \"bordered\"\n | \"shadow\"\n | \"card\"\n | \"dark\";\n\nexport type InputVariant = \"outlined\" | \"filled\" | \"underlined\" | \"stacked\";\n\n/**\n * The two palettes a form can carry. \"light\" is the base set of colors every\n * form has always had; \"dark\" is the optional override set in `FormStyle.dark`.\n */\nexport type FormColorScheme = \"light\" | \"dark\";\n\n/**\n * Theme overrides for a form. Every color is OPTIONAL — when unset, the\n * renderer falls back to a baked-in default via CSS `var()` fallbacks. This\n * lets the form builder ship forms that adapt to any consumer site\n * (CastleRents' warm tan, EuroComp's dark, etc.) without the package forcing\n * its own surface color or text color when the user hasn't picked one.\n *\n * The non-color fields (`preset`, `borderRadius`, `spacing`, variants,\n * `sectionDividers`) remain required structural choices and DEFAULT_FORM_STYLE\n * supplies their defaults.\n */\nexport interface FormStyle {\n preset: FormStylePreset;\n borderRadius: \"none\" | \"sm\" | \"md\" | \"lg\" | \"full\";\n /**\n * Arbitrary CSS length overriding the `borderRadius` step, e.g. `\"3px\"`.\n *\n * The five named steps are Tailwind classes, which a consumer site cannot\n * override from its own stylesheet — that is what forced sites onto\n * `.eg-form-dark input { border-radius: 3px }`-style patches. When this is\n * set the renderer drops the `rounded-*` class and drives corners through\n * the `--form-radius` custom property instead, reaching the form root, the\n * inputs AND the submit button. (The named steps never reached inputs at\n * all — input geometry is baked per `inputVariant`.)\n *\n * Unset — the default — leaves the class-based behaviour exactly as it was.\n */\n borderRadiusValue?: string;\n spacing: \"none\" | \"compact\" | \"normal\" | \"relaxed\";\n /**\n * Arbitrary CSS length for the gap BETWEEN fields, e.g. `\"1.5rem\"`.\n *\n * `spacing` drives two different things — the form root's padding and the\n * field grid's gap — which is fine for the three graded steps but breaks down\n * at `\"none\"`: a form wanting zero padding almost never wants its fields\n * glued together. This overrides the gap independently, leaving `spacing` to\n * mean padding.\n *\n * Unset — the default — keeps the gap `spacing` implies.\n */\n fieldGapValue?: string;\n buttonVariant: \"filled\" | \"outline\" | \"ghost\";\n /**\n * Where the submit button renders. \"below\" (default) spans the full form\n * width under the fields; \"inline\" places it in a row beside the fields —\n * suited to single-field forms like a newsletter email + Join button.\n */\n buttonPlacement?: \"below\" | \"inline\";\n sectionDividers: boolean;\n inputVariant: InputVariant;\n\n // Surface\n /** Form container background. Default: transparent (inherits from the page). */\n formBackgroundColor?: string;\n\n // Inputs\n /** Input fill color (used by filled/stacked variants and the floating-label mask). Default: #ffffff. */\n inputBgColor?: string;\n /** Input border color (idle state). Default: #d1d5db. */\n inputBorderColor?: string;\n /** Input border color on focus. Default: #2563eb. */\n inputFocusColor?: string;\n /**\n * Arbitrary CSS length overriding the bottom-border thickness on focus and\n * on validation error, e.g. `\"3px\"`. Only affects the `filled` and\n * `underlined` variants — a full-border ring (`outlined`/`stacked`) already\n * reads as focused/errored from color alone, so a bare color change on\n * `filled`/`underlined` can be too subtle; thickening the underline is the\n * variant-appropriate substitute for those two.\n *\n * Unset — the default — keeps the idle 2px bottom border on focus/error.\n */\n inputFocusBorderWidth?: string;\n /** Color of the text typed into inputs. Default: inherit from the page. */\n inputTextColor?: string;\n /** Placeholder text color. Default: #9ca3af. */\n placeholderColor?: string;\n\n // Labels / errors\n /** Field label text color. Default: inherit from the page. */\n labelColor?: string;\n /** Color used for error text + error border outline. Default: #ef4444. */\n errorColor?: string;\n\n // Submit button\n /** Submit button background (filled variant) / border + text (outline / ghost). Default: #2563eb. */\n buttonColor?: string;\n /** Submit button text color (filled variant only — outline/ghost use buttonColor). Default: #ffffff. */\n buttonTextColor?: string;\n\n /**\n * Dark-mode overrides for the color slots above. They apply only while\n * the host page is in dark mode — an ancestor matching `.dark`, the class\n * next-themes puts on `<html>` in every VulcanTech site that has a theme\n * toggle (`DynamicForm`'s `darkModeSelector` prop changes the selector).\n * A light-only site never has that class and never sees these.\n *\n * Each slot falls back to its LIGHT value, so an unset dark slot means\n * \"same as light\", never \"package default\". Absent — the default — the\n * renderer emits exactly what it did before this existed.\n */\n dark?: FormStyleColors;\n}\n\n/**\n * The keys of `FormStyle` that carry a color, in the order the renderer\n * publishes them. Shared by the scheme resolver and the builder's color rows,\n * so a new color slot is added in exactly one place.\n */\nexport const FORM_STYLE_COLOR_KEYS = [\n \"formBackgroundColor\",\n \"inputBgColor\",\n \"inputBorderColor\",\n \"inputFocusColor\",\n \"inputTextColor\",\n \"placeholderColor\",\n \"labelColor\",\n \"errorColor\",\n \"buttonColor\",\n \"buttonTextColor\",\n] as const;\n\nexport type FormStyleColorKey = (typeof FORM_STYLE_COLOR_KEYS)[number];\n\n/** Just the color slots of a `FormStyle`, every one optional. */\nexport type FormStyleColors = Pick<FormStyle, FormStyleColorKey>;\n\n/**\n * Structural defaults only. Colors are intentionally absent — they resolve\n * via the renderer's CSS var fallbacks (see `cssVars.ts`) when the form\n * definition doesn't override them.\n */\nexport const DEFAULT_FORM_STYLE: FormStyle = {\n preset: \"default\",\n borderRadius: \"md\",\n spacing: \"normal\",\n buttonVariant: \"filled\",\n buttonPlacement: \"below\",\n sectionDividers: false,\n inputVariant: \"outlined\",\n};\n\nexport type FieldTransform =\n | \"full\"\n | \"extractFirstName\"\n | \"extractLastName\"\n | \"extractStreet\"\n | \"extractCity\"\n | \"extractState\"\n | \"extractZip\";\n\nexport interface IntegrationFieldMappingEntry {\n /** Form field ID to read the value from */\n field: string;\n /** Optional transform applied to the source value before mapping */\n transform?: FieldTransform;\n}\n\nexport interface FormIntegrationConfig {\n enabled: boolean;\n /** Map of integration destination key (e.g. \"customer.firstName\") → source mapping */\n fieldMapping: Record<string, IntegrationFieldMappingEntry>;\n}\n\nexport type FormIntegrations = Record<string, FormIntegrationConfig>;\n\nexport type FormStatus = \"draft\" | \"published\" | \"archived\";\n\n/**\n * Where the CMS routes a submission for this form.\n *\n * - `contact` (default): writes to the project's `contact-forms` subcollection\n * and surfaces in the Contacts dashboard.\n * - `application`: writes to the project's `applications` subcollection with\n * workflow state (`status`, `assignedTo`, notes, statusHistory) and\n * surfaces in the Applications dashboard.\n * - `newsletter`: writes to the project's `newsletter_subscribers` collection.\n * Newsletter forms are restricted to `email` (required) and `checkbox`\n * (optional, for preferences/consent) fields. Duplicate emails within a\n * project update the existing record's preferences rather than creating\n * a new entry.\n * - `booking`: writes to the project's `bookings` subcollection and surfaces\n * in the Bookings dashboard. The submitted values are stored like an\n * application (nested `data` map), plus a denormalized booking `date`\n * (epoch ms) parsed from the form's designated date field — see\n * {@link FormBookingConfig}.\n *\n * Only the routing changes — spam protection, sensitive field handling,\n * notification emails, and integrations behave identically.\n */\nexport type FormSubmissionType =\n | \"contact\"\n | \"application\"\n | \"newsletter\"\n | \"booking\"\n /**\n * A checklist run compiled from an SOP. Never submitted through the public\n * `/api/contact` path — runs are filled in by signed-in members inside the\n * CMS and go to the SOP runs API, so the contact route treats an unknown\n * type as `\"contact\"` exactly as before.\n */\n | \"sop\"\n /**\n * A public form compiled from a public-forms document. Filled in by\n * anyone holding the share link and submitted to the CMS public-forms\n * responses API, never to `/api/contact`.\n */\n | \"public-form\";\n\n/**\n * Booking settings for a form with `submissionType: \"booking\"`. The renderer\n * is unaffected — booking forms submit exactly like any other form; the CMS\n * submission route uses this config to pull the booking date(s) out of the\n * submitted values.\n *\n * Date-only convention: a `date` field submits `\"yyyy-MM-dd\"`, which parses\n * to UTC midnight, so a stored epoch that is an exact multiple of a day is\n * treated as date-only and displayed in UTC. A `datetime` field submits a\n * full ISO string and is stored as a real instant. An unparseable value is\n * stored as an explicit `null` rather than a fabricated date.\n */\nexport interface FormBookingConfig {\n /**\n * Field id of the `date`/`datetime` field holding the booking date (the\n * start date, when `endDateFieldId` is also set). When omitted, the\n * submission route falls back to the form's first date/datetime field in\n * render order, and then to a top-level `date` key on the submission.\n */\n dateFieldId?: string;\n /**\n * Optional second `date`/`datetime` field id for begin/end bookings.\n * Bookings without an end date use `defaultDurationMinutes` instead.\n */\n endDateFieldId?: string;\n /**\n * Default duration (minutes) stamped onto each new booking. Individual\n * bookings can be overridden afterwards in the Bookings dashboard.\n */\n defaultDurationMinutes?: number;\n}\n\n/**\n * Field types allowed on a newsletter form. Enforced by the form builder UI\n * and (defensively) by the submission route. Keep in sync with\n * `FormSubmissionType === \"newsletter\"` handling.\n */\nexport const NEWSLETTER_ALLOWED_FIELD_TYPES: FieldType[] = [\"email\", \"checkbox\"];\n\n/**\n * Customizable notification email sent to project members when a submission\n * arrives. Both `subject` and `html` support `{{variable}}` interpolation —\n * see `renderEmailTemplate` for the rules. When omitted, the API falls back\n * to the built-in default template.\n */\nexport interface NotificationEmailTemplate {\n subject: string;\n html: string;\n}\n\nexport const DEFAULT_NOTIFICATION_EMAIL_SUBJECT =\n \"New Contact Form: {{name}}\";\n\n/**\n * Default HTML body for the notification email. Mirrors the look of\n * `buildContactNotificationEmail` in the CMS but uses `{{variable}}`\n * placeholders so users can edit it in the form builder.\n */\nexport const DEFAULT_NOTIFICATION_EMAIL_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"UTF-8\" /></head>\n<body style=\"font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;\">\n <div style=\"background: #4f46e5; color: white; padding: 20px; border-radius: 8px 8px 0 0;\">\n <h1 style=\"margin: 0; font-size: 20px;\">New {{formName}} Submission</h1>\n <p style=\"margin: 4px 0 0; opacity: 0.9; font-size: 14px;\">{{projectName}}</p>\n </div>\n <div style=\"border: 1px solid #e5e7eb; border-top: none; padding: 20px; border-radius: 0 0 8px 8px;\">\n <table style=\"width: 100%; border-collapse: collapse;\">\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; width: 120px; vertical-align: top;\">Name:</td>\n <td style=\"padding: 8px 0;\">{{name}}</td>\n </tr>\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; vertical-align: top;\">Email:</td>\n <td style=\"padding: 8px 0;\"><a href=\"mailto:{{email}}\">{{email}}</a></td>\n </tr>\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; vertical-align: top;\">Phone:</td>\n <td style=\"padding: 8px 0;\"><a href=\"tel:{{phone}}\">{{phone}}</a></td>\n </tr>\n <tr>\n <td style=\"padding: 8px 0; font-weight: 600; vertical-align: top;\">Message:</td>\n <td style=\"padding: 8px 0;\">{{message}}</td>\n </tr>\n </table>\n <hr style=\"border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;\" />\n <p style=\"font-size: 12px; color: #9ca3af; margin: 0;\">\n Sent via VulcanTech CMS &middot; <a href=\"https://cms.vulcantech.io\">Dashboard</a>\n </p>\n </div>\n</body>\n</html>`;\n\nexport const DEFAULT_NOTIFICATION_EMAIL_TEMPLATE: NotificationEmailTemplate = {\n subject: DEFAULT_NOTIFICATION_EMAIL_SUBJECT,\n html: DEFAULT_NOTIFICATION_EMAIL_HTML,\n};\n\n/**\n * The set of workflow states an application can be in. Mirrors\n * `ApplicationStatus` in apps/vulcantech-cms/src/types/APPLICATION.ts — duplicated\n * here so the forms package (which is consumed by both the CMS server and\n * client apps) can describe per-status email templates without importing\n * from the CMS app.\n */\nexport type ApplicationStatusKey =\n | \"received\"\n | \"reviewing\"\n | \"approved\"\n | \"denied\"\n | \"pending-documents\"\n | \"withdrawn\";\n\nexport const APPLICATION_STATUS_KEYS: ApplicationStatusKey[] = [\n \"received\",\n \"reviewing\",\n \"approved\",\n \"denied\",\n \"pending-documents\",\n \"withdrawn\",\n];\n\n/**\n * Per-status applicant-facing email template. Keyed by `ApplicationStatusKey`.\n * Missing entries fall back to {@link DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES}.\n *\n * These templates are RENDERED with the same `renderEmailTemplate` engine as\n * the admin notification template, but the available variables are\n * application-centric: `{{referenceNumber}}`, `{{applicantName}}`,\n * `{{status}}`, `{{requestedDocuments}}` (only when status is\n * `pending-documents`), plus any form-field values that match the\n * applicant's submission.\n */\nexport type ApplicationStatusEmailTemplates = Partial<\n Record<ApplicationStatusKey, NotificationEmailTemplate>\n>;\n\n/**\n * HTML body shared by every default status template — same chrome as the\n * admin notification email but with applicant-centric copy in the middle.\n * Placeholders: `{{status}}`, `{{statusLabel}}`, `{{statusMessage}}`,\n * `{{referenceNumber}}`, `{{applicantName}}`, `{{projectName}}`,\n * `{{formName}}`, and (only for pending-documents) `{{requestedDocuments}}`.\n */\nfunction buildDefaultStatusEmailHtml(bodyHtml: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"UTF-8\" /></head>\n<body style=\"font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;\">\n <div style=\"background: #4f46e5; color: white; padding: 20px; border-radius: 8px 8px 0 0;\">\n <h1 style=\"margin: 0; font-size: 20px;\">{{projectName}}</h1>\n <p style=\"margin: 4px 0 0; opacity: 0.9; font-size: 14px;\">Application update</p>\n </div>\n <div style=\"border: 1px solid #e5e7eb; border-top: none; padding: 20px; border-radius: 0 0 8px 8px;\">\n <p style=\"margin-top: 0;\">Hi {{applicantName}},</p>\n ${bodyHtml}\n <p style=\"font-size: 13px; color: #6b7280; margin: 20px 0 0;\">\n Reference number: <strong style=\"font-family: monospace;\">{{referenceNumber}}</strong>\n </p>\n <hr style=\"border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;\" />\n <p style=\"font-size: 12px; color: #9ca3af; margin: 0;\">\n This is an automated message from {{projectName}}.\n </p>\n </div>\n</body>\n</html>`;\n}\n\nexport const DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES: Record<\n ApplicationStatusKey,\n NotificationEmailTemplate\n> = {\n received: {\n subject: \"We've received your application — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Thanks for applying to {{projectName}}. We've received your submission and our team will be in touch as it moves through review.</p>`,\n ),\n },\n reviewing: {\n subject: \"Your application is under review — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Good news — your application has moved into active review. We'll reach out as soon as a decision is made or we need anything else from you.</p>`,\n ),\n },\n approved: {\n subject: \"Your application has been approved — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Congratulations — your application has been <strong style=\"color: #047857;\">approved</strong>. We'll follow up shortly with next steps.</p>`,\n ),\n },\n denied: {\n subject: \"Update on your application — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Thank you for taking the time to apply to {{projectName}}. After review, we won't be moving forward with your application at this time.</p>\n <p>We appreciate your interest and wish you the best.</p>`,\n ),\n },\n \"pending-documents\": {\n subject: \"Additional documents needed — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>To continue reviewing your application we need a few more documents from you:</p>\n <div style=\"white-space: pre-wrap; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px; margin: 12px 0; font-size: 14px;\">{{requestedDocuments}}</div>\n <p>Reply to this email with the requested items and we'll resume review as soon as they arrive.</p>`,\n ),\n },\n withdrawn: {\n subject: \"Your application has been withdrawn — {{referenceNumber}}\",\n html: buildDefaultStatusEmailHtml(\n `<p>Per request, your application to {{projectName}} has been withdrawn. If this wasn't expected, please reply and let us know.</p>`,\n ),\n },\n};\n\n/**\n * The CMS-authored schema for one form — the value `DynamicForm` renders and\n * the CMS submission route consults to route and validate a submission.\n *\n * Consumer sites fetch this from `GET /api/forms` rather than building it.\n * Four fields are stripped from every client-facing response by the CMS\n * (`stripSensitiveFields`) and are therefore always `undefined` outside the\n * CMS server: `projectId`, `integrations`, `notificationEmailTemplate`, and\n * `applicationStatusEmails`.\n */\nexport interface FormDefinition {\n id: string;\n /**\n * Server-only project owner. The CMS stores this in Firestore and uses it\n * internally (to scope writes, build cache tags, address integration\n * configs), but it is stripped from every client-facing response by\n * `stripSensitiveFields` before reaching consumer apps. Client code MUST\n * NOT depend on this field — resolve projectId from a server-side env var\n * (`VULCANTECH_PROJECT_ID`) in proxy/fetch routes instead.\n */\n projectId?: string;\n name: string;\n /** Unique within a project — the CMS rejects a colliding slug with a 409. */\n slug: string;\n description?: string;\n /** Bumped on every CMS edit. Emitted by the renderer as `data-form-version`. */\n version: number;\n /**\n * FormStatus values: \"draft\" | \"published\" | \"archived\".\n *\n * Deliberately typed `string`, not the {@link FormStatus} union, because\n * definitions cross a JSON boundary. Compare against the literals. The\n * public GET route already filters to published forms unless the caller\n * passes `includeDrafts=1`.\n */\n status: string;\n /**\n * Routes submissions to the matching dashboard collection.\n * Defaults to `\"contact\"` when omitted. See {@link FormSubmissionType}.\n *\n * Read server-side from this definition, never from the request body — a\n * submission whose `formId` does not resolve always routes to `contact`.\n */\n submissionType?: FormSubmissionType;\n /**\n * Booking settings. Only consulted when `submissionType === \"booking\"`.\n * See {@link FormBookingConfig}.\n */\n bookingConfig?: FormBookingConfig;\n /** Rendered in `order`, not array order — the renderer sorts before rendering. */\n sections: FormSection[];\n submitConfig: FormSubmitConfig;\n /** Absent = {@link DEFAULT_FORM_STYLE} (structure only; colors stay unset). */\n style?: FormStyle;\n /**\n * Optional hex color applied as the default text color for every section\n * header and description. Per-section `textColor` overrides this. When\n * unset, sections inherit from the surrounding CSS cascade (useful when\n * the form is embedded on a page with its own typography).\n */\n defaultTextColor?: string;\n /**\n * Dark-mode counterpart of `defaultTextColor`, applied under the same\n * conditions as `FormStyle.dark`. Per-section `textColorDark` overrides it.\n */\n defaultTextColorDark?: string;\n metadata?: {\n trackAdReferral?: boolean;\n customFields?: Record<string, unknown>;\n };\n /** Server-only — stripped from client-facing responses like `projectId`. */\n integrations?: FormIntegrations;\n /**\n * Customizable email sent to project members when a submission arrives.\n * Falls back to `DEFAULT_NOTIFICATION_EMAIL_TEMPLATE` when undefined.\n *\n * Server-only — stripped from client-facing responses like `projectId`.\n */\n notificationEmailTemplate?: NotificationEmailTemplate;\n /**\n * Per-status applicant-facing email templates. Only consulted when\n * `submissionType === \"application\"`. Server-only — stripped from\n * client-facing responses like `projectId`. Missing entries fall back to\n * `DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES[status]`. Set to an empty\n * object to opt every status into the defaults explicitly.\n */\n applicationStatusEmails?: ApplicationStatusEmailTemplates;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n}\n\n/**\n * JSON-friendly mirror of {@link FormDefinition}.\n *\n * `FormDefinition` keeps narrow string-literal unions (e.g. `FieldType`,\n * `FormStylePreset`, `FormSuccessBehavior`) for editor autocomplete and\n * exhaustive-switch safety inside this package. But when a definition\n * crosses a JSON boundary — `JSON.parse`, an `await res.json()` on an ISR\n * fetch, a Firestore document, or a literal object pasted into source —\n * TypeScript widens the string values to `string`, which fails to match\n * the narrow unions and forces every consumer to cast.\n *\n * Use `FormDefinitionJSON` as the type of the raw JSON value, then call\n * {@link parseFormDefinition} (or assert it yourself) when you need the\n * strict shape:\n *\n * ```ts\n * const json = (await res.json()) as FormDefinitionJSON;\n * const definition = parseFormDefinition(json);\n * ```\n *\n * Structurally, `FormDefinition` is assignable to `FormDefinitionJSON`,\n * so values you've already validated flow back into JSON-typed slots\n * without a cast.\n */\nexport interface ValidationRuleJSON {\n // ValidationRuleType values: \"required\" | \"min\" | \"max\" | \"minLength\" | \"maxLength\" | \"pattern\" | \"email\" | \"phone\" | \"notEquals\"\n type: string;\n value?: string | number | boolean;\n message: string;\n}\n\nexport interface SensitiveFieldConfigJSON {\n /** Days until the encrypted record auto-deletes. Defaults to 30. */\n ttlDays: number;\n viewerRoles: string[];\n /** Currently only `ssn` is implemented. */\n inputMask?: string;\n}\n\nexport interface FormFieldDefinitionJSON {\n id: string;\n // FieldType values: \"text\" | \"email\" | \"phone\" | \"url\" | \"address\" | \"textarea\" | \"select\" | \"checkbox\" | \"radio\" | \"number\" | \"date\" | \"datetime\" | \"hidden\" | \"sensitive\" | \"file\"\n type: string;\n label: string;\n placeholder?: string;\n helpText?: string;\n description?: string;\n defaultValue?: string;\n // TextTransform values: \"capitalize-sentences\" | \"capitalize-words\" | \"phone-number\" | \"ssn\"\n transform?: string;\n validation: ValidationRuleJSON[];\n options?: FieldOption[];\n layout?: {\n // FieldWidth values: \"full\" | \"half\" | \"third\"\n width: string;\n order: number;\n };\n characterCounter?: boolean;\n rows?: number;\n datetimeConfig?: DatetimeConfig;\n showWhen?: FieldVisibilityCondition;\n sensitiveConfig?: SensitiveFieldConfigJSON;\n /** No narrowed unions, so the strict type is reused. */\n fileConfig?: FileFieldConfig;\n}\n\nexport interface FormSectionJSON {\n id: string;\n title?: string;\n description?: string;\n fields: FormFieldDefinitionJSON[];\n order: number;\n textColor?: string;\n textColorDark?: string;\n sameAs?: SectionSameAsConfig;\n}\n\nexport interface FormStyleJSON {\n // FormStylePreset values: \"default\" | \"minimal\" | \"bordered\" | \"shadow\" | \"card\" | \"dark\"\n preset: string;\n // \"none\" | \"sm\" | \"md\" | \"lg\" | \"full\"\n borderRadius: string;\n // \"compact\" | \"normal\" | \"relaxed\"\n spacing: string;\n // \"filled\" | \"outline\" | \"ghost\"\n buttonVariant: string;\n // \"below\" | \"inline\"\n buttonPlacement?: string;\n sectionDividers: boolean;\n // InputVariant values: \"outlined\" | \"filled\" | \"underlined\" | \"stacked\"\n inputVariant: string;\n formBackgroundColor?: string;\n inputBgColor?: string;\n inputBorderColor?: string;\n inputFocusColor?: string;\n inputFocusBorderWidth?: string;\n inputTextColor?: string;\n placeholderColor?: string;\n labelColor?: string;\n errorColor?: string;\n buttonColor?: string;\n buttonTextColor?: string;\n /** Dark-mode overrides; same optional color keys as the light set. */\n dark?: FormStyleColorsJSON;\n}\n\n/** JSON mirror of {@link FormStyleColors}. */\nexport interface FormStyleColorsJSON {\n formBackgroundColor?: string;\n inputBgColor?: string;\n inputBorderColor?: string;\n inputFocusColor?: string;\n inputTextColor?: string;\n placeholderColor?: string;\n labelColor?: string;\n errorColor?: string;\n buttonColor?: string;\n buttonTextColor?: string;\n}\n\nexport interface FormSubmitConfigJSON {\n buttonText: string;\n submittingText?: string;\n submittedText?: string;\n successMessage: string;\n errorMessage: string;\n // FormSuccessBehavior values: \"message\" | \"replace\" | \"reset\" | \"disable\"\n successBehavior?: string;\n redirectUrl?: string;\n spamProtection?: FormSpamProtectionConfig;\n /** See {@link FormSubmitConfig.conversion} — no narrowed unions, so the strict type is reused. */\n conversion?: FormConversionConfig;\n}\n\nexport interface IntegrationFieldMappingEntryJSON {\n field: string;\n // FieldTransform values: \"full\" | \"extractFirstName\" | \"extractLastName\" | \"extractStreet\" | \"extractCity\" | \"extractState\" | \"extractZip\"\n transform?: string;\n}\n\nexport interface FormIntegrationConfigJSON {\n enabled: boolean;\n fieldMapping: Record<string, IntegrationFieldMappingEntryJSON>;\n}\n\nexport type FormIntegrationsJSON = Record<string, FormIntegrationConfigJSON>;\n\nexport interface FormDefinitionJSON {\n id: string;\n /** See {@link FormDefinition.projectId} — server-only, optional at the JSON boundary. */\n projectId?: string;\n name: string;\n slug: string;\n description?: string;\n version: number;\n // FormStatus values: \"draft\" | \"published\" | \"archived\"\n status: string;\n // FormSubmissionType values: \"contact\" | \"application\" | \"newsletter\" | \"booking\"\n submissionType?: string;\n /** See {@link FormDefinition.bookingConfig} — no narrowed unions, so the strict type is reused. */\n bookingConfig?: FormBookingConfig;\n sections: FormSectionJSON[];\n submitConfig: FormSubmitConfigJSON;\n style?: FormStyleJSON;\n defaultTextColor?: string;\n defaultTextColorDark?: string;\n metadata?: {\n trackAdReferral?: boolean;\n customFields?: Record<string, unknown>;\n };\n integrations?: FormIntegrationsJSON;\n notificationEmailTemplate?: NotificationEmailTemplate;\n /** See {@link FormDefinition.applicationStatusEmails}. */\n applicationStatusEmails?: ApplicationStatusEmailTemplates;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n}\n\n/**\n * Narrow a `FormDefinitionJSON` to the strict {@link FormDefinition} type.\n *\n * This is a structural cast — it trusts that the JSON was produced by the\n * CMS (or another well-formed source) and does not validate individual\n * enum values. Use it at trust boundaries where you've already verified\n * the source. For untrusted JSON, validate explicitly (e.g. with Yup or\n * Zod) before treating the result as a `FormDefinition`.\n */\nexport function parseFormDefinition(json: FormDefinitionJSON): FormDefinition {\n return json as unknown as FormDefinition;\n}\n","import type { FieldVisibilityCondition } from \"../types\";\n\n/**\n * Evaluate a field's `showWhen` condition against the current form values.\n *\n * This is the single source of truth for conditional visibility — the\n * renderer (show/hide), the Yup schema (skip validation while hidden), the\n * submit payload (strip hidden values), and the CMS's server-side submission\n * validation must all agree, so they all call this.\n *\n * Operators:\n * - `equals` (default) / `not-equals`: strict comparison, matching the\n * original behavior.\n * - `greater-than` / `less-than`: numeric comparison. Both the watched value\n * and the condition value are parsed as numbers; if either side isn't\n * numeric (empty input, non-number text, booleans), the condition is unmet\n * and the dependent field stays hidden.\n *\n * @param condition - The field's `showWhen` config.\n * @param watchedValue - Current value of `condition.fieldId`.\n * @returns True when the dependent field should be visible.\n */\nexport function isVisibilityConditionMet(\n condition: FieldVisibilityCondition,\n watchedValue: unknown,\n): boolean {\n const operator = condition.operator ?? \"equals\";\n\n switch (operator) {\n case \"greater-than\":\n case \"less-than\": {\n if (typeof watchedValue === \"boolean\") return false;\n const actual =\n typeof watchedValue === \"number\"\n ? watchedValue\n : parseFloat(String(watchedValue ?? \"\"));\n const expected = parseFloat(String(condition.value));\n if (Number.isNaN(actual) || Number.isNaN(expected)) return false;\n return operator === \"greater-than\"\n ? actual > expected\n : actual < expected;\n }\n case \"not-equals\":\n return watchedValue !== condition.value;\n case \"equals\":\n default:\n return watchedValue === condition.value;\n }\n}\n","import * as Yup from \"yup\";\nimport type { FormDefinition, FormFieldDefinition, ValidationRule } from \"../types\";\nimport { sameAsToggleKey } from \"../types\";\nimport { isVisibilityConditionMet } from \"../utils/visibility\";\n\nfunction getBaseSchema(field: FormFieldDefinition): Yup.AnySchema {\n switch (field.type) {\n case \"number\":\n // An untouched <input type=\"number\"> submits \"\" — without this\n // transform Yup casts that to NaN and throws the typeError even for\n // OPTIONAL number fields, making the form unsubmittable.\n return Yup.number()\n .transform((value, original) =>\n original === \"\" || original === null ? undefined : value,\n )\n .typeError(`${field.label} must be a number`);\n case \"checkbox\":\n return Yup.boolean();\n case \"url\":\n return Yup.string().url(`${field.label} must be a valid URL`);\n case \"datetime\":\n return Yup.string();\n case \"select\":\n case \"radio\": {\n // Constrain choice fields to their defined options so a tampered\n // payload can't carry arbitrary values. \"\" is the untouched state and\n // must stay valid for optional fields; `required` still rejects it.\n const allowed = (field.options ?? []).map((o) => o.value);\n if (allowed.length === 0) return Yup.string();\n return Yup.string().oneOf(\n [...allowed, \"\"],\n `${field.label} has an invalid selection`,\n );\n }\n case \"sensitive\": {\n let schema = Yup.string();\n // The builder keeps the ssn input mask and the ssn transform in\n // lockstep, but honor either so older definitions still validate.\n if (\n field.sensitiveConfig?.inputMask === \"ssn\" ||\n field.transform === \"ssn\"\n ) {\n schema = schema.matches(\n /^\\d{3}-\\d{2}-\\d{4}$/,\n `${field.label} must be a valid Social Security number`\n );\n }\n return schema;\n }\n case \"file\":\n // File field value is a URL string (single) or array of URL strings (multiple)\n if (field.fileConfig?.multiple) {\n return Yup.array()\n .of(Yup.string().url())\n .default([]);\n }\n return Yup.string();\n default:\n return Yup.string();\n }\n}\n\nfunction applyValidationRule(\n schema: Yup.AnySchema,\n rule: ValidationRule,\n field: FormFieldDefinition\n): Yup.AnySchema {\n switch (rule.type) {\n case \"required\":\n // For checkboxes, `.required()` alone is useless — `false` is a\n // present value and passes it. A required checkbox (consent box)\n // additionally demands the value be `true`.\n if (field.type === \"checkbox\" && schema instanceof Yup.BooleanSchema) {\n return schema.required(rule.message).oneOf([true], rule.message);\n }\n return schema.required(rule.message);\n\n case \"email\":\n if (schema instanceof Yup.StringSchema) {\n return schema.email(rule.message);\n }\n return schema;\n\n case \"phone\":\n if (schema instanceof Yup.StringSchema) {\n return schema.matches(\n /^[\\d\\s\\-()+ .]+$/,\n rule.message\n );\n }\n return schema;\n\n case \"min\":\n if (schema instanceof Yup.NumberSchema && typeof rule.value === \"number\") {\n return schema.min(rule.value, rule.message);\n }\n return schema;\n\n case \"max\":\n if (schema instanceof Yup.NumberSchema && typeof rule.value === \"number\") {\n return schema.max(rule.value, rule.message);\n }\n return schema;\n\n case \"minLength\":\n if (schema instanceof Yup.StringSchema && typeof rule.value === \"number\") {\n return schema.min(rule.value, rule.message);\n }\n return schema;\n\n case \"maxLength\":\n if (schema instanceof Yup.StringSchema && typeof rule.value === \"number\") {\n return schema.max(rule.value, rule.message);\n }\n return schema;\n\n case \"pattern\":\n if (schema instanceof Yup.StringSchema && typeof rule.value === \"string\") {\n // A malformed regex typed in the builder must not crash the whole\n // form at render time — skip the rule instead.\n try {\n return schema.matches(new RegExp(rule.value), rule.message);\n } catch {\n console.warn(\n `[forms] Invalid pattern for field \"${field.id}\": ${rule.value}`,\n );\n return schema;\n }\n }\n return schema;\n\n case \"notEquals\":\n if (schema instanceof Yup.StringSchema && rule.value !== undefined) {\n return schema.notOneOf([String(rule.value)], rule.message);\n }\n if (schema instanceof Yup.NumberSchema && typeof rule.value === \"number\") {\n return schema.notOneOf([rule.value], rule.message);\n }\n return schema;\n\n default:\n return schema;\n }\n}\n\nexport function buildYupSchema(definition: FormDefinition): Yup.ObjectSchema<Record<string, unknown>> {\n const shape: Record<string, Yup.AnySchema> = {};\n\n for (const section of definition.sections) {\n // Fields mirrored-and-hidden by a \"same as\" toggle must not block submit\n // (they carry a copied value but are invisible). Exempt them while the\n // toggle is on, mirroring the showWhen pattern below.\n const hideToggleKey =\n section.sameAs?.behavior === \"hide\"\n ? sameAsToggleKey(section.id)\n : null;\n const hiddenTargetIds = hideToggleKey\n ? new Set(Object.keys(section.sameAs!.fieldMap))\n : null;\n\n for (const field of section.fields) {\n let schema = getBaseSchema(field);\n\n for (const rule of field.validation) {\n schema = applyValidationRule(schema, rule, field);\n }\n\n const baseSchema = getBaseSchema(field);\n\n if (field.showWhen) {\n const condition = field.showWhen;\n shape[field.id] = Yup.mixed().when(condition.fieldId, {\n is: (value: unknown) => isVisibilityConditionMet(condition, value),\n then: () => schema,\n otherwise: () => baseSchema.notRequired(),\n });\n } else if (hideToggleKey && hiddenTargetIds?.has(field.id)) {\n shape[field.id] = Yup.mixed().when(hideToggleKey, {\n is: true,\n then: () => baseSchema.notRequired(),\n otherwise: () => schema,\n });\n } else {\n shape[field.id] = schema;\n }\n }\n }\n\n return Yup.object().shape(shape);\n}\n","import type { FormDefinition } from \"../types\";\nimport { sameAsToggleKey } from \"../types\";\n\nexport function buildInitialValues(definition: FormDefinition): Record<string, string | boolean | string[]> {\n const values: Record<string, string | boolean | string[]> = {};\n\n for (const section of definition.sections) {\n // Synthetic \"same as\" toggle starts unchecked.\n if (section.sameAs) values[sameAsToggleKey(section.id)] = false;\n for (const field of section.fields) {\n if (field.type === \"checkbox\") {\n values[field.id] = field.defaultValue === \"true\";\n } else if (field.type === \"datetime\") {\n values[field.id] = field.defaultValue || \"\";\n } else if (field.type === \"sensitive\") {\n values[field.id] = \"\";\n } else if (field.type === \"file\") {\n // File fields store URL(s) after upload — start empty\n values[field.id] = field.fileConfig?.multiple ? [] : \"\";\n } else {\n values[field.id] = field.defaultValue || \"\";\n }\n }\n }\n\n return values;\n}\n","import type { FieldTransform } from \"../types\";\n\n/**\n * Apply a field transform to a string value before passing it to an\n * integration. Used by integration adapters to derive things like\n * \"first name\" from a single \"Full Name\" field, or to split an address\n * into its components.\n *\n * @param value - The raw form field value.\n * @param transform - The transform to apply. Falsy or \"full\" returns the\n * value unchanged.\n * @returns The transformed value, or an empty string if the transform\n * could not produce a result.\n */\nexport function applyTransform(\n value: string,\n transform?: FieldTransform\n): string {\n if (!value) return \"\";\n if (!transform || transform === \"full\") return value;\n\n switch (transform) {\n case \"extractFirstName\":\n return value.trim().split(/\\s+/)[0] || value;\n case \"extractLastName\": {\n const parts = value.trim().split(/\\s+/);\n return parts.length > 1 ? parts.slice(1).join(\" \") : \"\";\n }\n case \"extractStreet\":\n case \"extractCity\":\n case \"extractState\":\n case \"extractZip\":\n return extractAddressPart(value, transform);\n default:\n return value;\n }\n}\n\n/**\n * Naive US-address splitter. Expects roughly:\n * \"123 Main St, Phoenix, AZ 85001\"\n *\n * - street → everything before the first comma\n * - city → between the first and second commas\n * - state → first whitespace-separated token after the second comma\n * - zip → second whitespace-separated token after the second comma\n *\n * Returns an empty string if the input doesn't have enough parts to\n * satisfy the requested piece.\n */\nfunction extractAddressPart(\n value: string,\n transform: \"extractStreet\" | \"extractCity\" | \"extractState\" | \"extractZip\"\n): string {\n const parts = value.split(\",\").map((p) => p.trim());\n\n if (transform === \"extractStreet\") return parts[0] ?? \"\";\n if (transform === \"extractCity\") return parts[1] ?? \"\";\n\n const tail = (parts[2] ?? \"\").split(/\\s+/).filter(Boolean);\n if (transform === \"extractState\") return tail[0] ?? \"\";\n if (transform === \"extractZip\") return tail.slice(1).join(\" \") || \"\";\n\n return \"\";\n}\n","/**\n * Validate a configured post-submit redirect target.\n *\n * Accepts absolute http(s) URLs and site-relative paths (`/thank-you`).\n * Anything else — `javascript:`/`data:` schemes, protocol-relative\n * `//host` values, unparseable strings — returns `null` so the caller\n * falls back to the normal on-page success behavior. Shared by the\n * renderer (before navigating) and the CMS save endpoint (before\n * persisting) so both enforce the same rule.\n *\n * @param raw - The `submitConfig.redirectUrl` value as authored/stored.\n * @returns The trimmed URL when it is safe to navigate to, otherwise `null`.\n */\nexport function getSafeRedirectUrl(\n raw: string | null | undefined,\n): string | null {\n if (typeof raw !== \"string\") return null;\n const url = raw.trim();\n if (!url) return null;\n if (url.startsWith(\"/\") && !url.startsWith(\"//\")) return url;\n try {\n const parsed = new URL(url);\n if (parsed.protocol === \"http:\" || parsed.protocol === \"https:\") {\n return url;\n }\n } catch {\n // Not an absolute URL and not a site-relative path — reject below.\n }\n return null;\n}\n","/**\n * Google conversion signalling for successful form submissions.\n *\n * Two independent signals, both fired once per genuine success by\n * `DynamicForm` (see `trackFormConversion`):\n *\n * 1. A `dataLayer` push of `form_submit_success`. Works with BOTH plain\n * gtag.js (which creates `window.dataLayer` — `@vulcantech/analytics`'s\n * `CMSTags` bootstraps it) and Google Tag Manager, where it can drive a\n * Custom Event trigger. Always fired; costs nothing when nobody listens.\n * 2. An optional direct `gtag('event', 'conversion', { send_to })` for sites\n * with a Google Ads conversion action but no GTM container. Fired only\n * when a `send_to` label is configured — never hardcoded in a consumer app.\n * Carries a `transaction_id` so Google dedupes a double-fired submission,\n * and — only on sites that opted into enhanced conversions — is preceded\n * by `gtag('set', 'user_data', …)` with the lead's email and phone.\n * 3. A GA4 `generate_lead` event whenever `gtag` is on the page.\n *\n * Everything here is defensive by design: these are analytics side effects on\n * the lead-capture happy path, so a missing global, a hostile `dataLayer`\n * stub, or a throwing `gtag` must never turn a stored lead into an error\n * banner. Every function swallows its own failures and reports success as a\n * boolean instead.\n *\n * PII: the `dataLayer` push and `generate_lead` carry only the form's own\n * identity (id, name, type), never submitted values. The single exception is\n * enhanced conversions: when the site publishes\n * {@link ENHANCED_CONVERSIONS_GLOBAL} (`CMSTags`' `enhancedConversions` tag),\n * the submitted email and phone go to `gtag('set', 'user_data')`, which\n * hashes them before they leave the browser. Sites that enable it must say so\n * in their privacy policy.\n */\n\n/** `dataLayer` event name pushed after every successful form submission. */\nexport const FORM_SUBMIT_SUCCESS_EVENT = \"form_submit_success\";\n\n/**\n * `window` key a site-wide Google Ads `send_to` label can be published on.\n *\n * `@vulcantech/analytics`'s `CMSTags` writes the project's\n * `formConversionSendTo` tracking tag here, which lets every form on the site\n * fire the Ads conversion with no per-form and no per-app configuration. A\n * form's own `submitConfig.conversion.sendTo` overrides it.\n */\nexport const FORM_CONVERSION_SEND_TO_GLOBAL = \"__vtFormConversionSendTo\";\n\n/**\n * `window` key `CMSTags` sets to `true` when the project opted into Google\n * Ads enhanced conversions. Mirrored in `@vulcantech/analytics` (the two\n * packages are independent, so it is a constant, not an import).\n */\nexport const ENHANCED_CONVERSIONS_GLOBAL = \"__vtEnhancedConversions\";\n\n/** Identity of the submitted form. Deliberately free of submitted values. */\nexport interface FormConversionContext {\n /** The CMS form definition id. */\n formId: string;\n /** Human-readable form name, as authored in the CMS. */\n formName: string;\n /** Submission type — \"contact\", \"application\", \"newsletter\", \"booking\". */\n formType: string;\n}\n\n/** Minimal shape of the Google globals this module touches. */\ntype GoogleWindow = Window & {\n dataLayer?: unknown[];\n gtag?: (...args: unknown[]) => void;\n [FORM_CONVERSION_SEND_TO_GLOBAL]?: unknown;\n [ENHANCED_CONVERSIONS_GLOBAL]?: unknown;\n};\n\n/** Lead contact details for enhanced conversions, as submitted. */\nexport interface ConversionUserData {\n email?: unknown;\n phone?: unknown;\n}\n\n/** Per-submission extras for the Ads conversion. */\nexport interface ConversionExtras {\n /** Unique id for this submission — Google dedupes conversions on it. */\n transactionId?: string;\n /** Submitted email/phone; only sent when enhanced conversions is on. */\n userData?: ConversionUserData;\n}\n\n/**\n * Normalize a North American phone number to E.164 (`+1XXXXXXXXXX`), the\n * format Google requires for `user_data.phone_number`.\n *\n * @param raw The phone number as the visitor typed it.\n * @returns The E.164 string, or `undefined` when it is not a 10-digit NANP\n * number (with or without the leading 1) — an unparseable number is left\n * out rather than sent malformed.\n */\nexport function toE164(raw: unknown): string | undefined {\n if (typeof raw !== \"string\" && typeof raw !== \"number\") return undefined;\n const digits = String(raw).replace(/\\D/g, \"\");\n if (digits.length === 10) return `+1${digits}`;\n if (digits.length === 11 && digits[0] === \"1\") return `+${digits}`;\n return undefined;\n}\n\n/**\n * Build the `user_data` object for enhanced conversions, omitting any field\n * the visitor did not supply (Google wants absent fields left out, not empty).\n *\n * @returns The object, or `undefined` when neither email nor phone is usable.\n */\nexport function buildUserData(\n input: ConversionUserData | undefined,\n): { email?: string; phone_number?: string } | undefined {\n if (!input) return undefined;\n const email =\n typeof input.email === \"string\" ? input.email.trim().toLowerCase() : \"\";\n const phone = toE164(input.phone);\n if (!email && !phone) return undefined;\n return {\n ...(email ? { email } : {}),\n ...(phone ? { phone_number: phone } : {}),\n };\n}\n\n/**\n * A unique id for one submission, used as the Ads `transaction_id`.\n * `crypto.randomUUID` needs a secure context, so a timestamp+random id is the\n * fallback on plain-http dev hosts.\n */\nexport function newTransactionId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // fall through\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** The browser `window`, or `undefined` on the server. Never throws. */\nfunction googleWindow(): GoogleWindow | undefined {\n if (typeof window === \"undefined\") return undefined;\n return window as GoogleWindow;\n}\n\n/**\n * Push the `form_submit_success` event onto `window.dataLayer`.\n *\n * Creates `dataLayer` when it does not exist yet, so the event is not lost\n * when a form succeeds before gtag.js/GTM has finished loading — both replay\n * the pre-existing array on init.\n *\n * @param context Form identity to attach to the event. No submitted values.\n * @returns `true` when the event was pushed, `false` on the server or when\n * `dataLayer` is present but unusable (e.g. not an array-like with `push`).\n */\nexport function pushFormSubmitSuccess(context: FormConversionContext): boolean {\n const win = googleWindow();\n if (!win) return false;\n try {\n if (!Array.isArray(win.dataLayer)) {\n // Only create it — never clobber an existing non-array `dataLayer`,\n // which would break whatever put it there.\n if (win.dataLayer !== undefined) return false;\n win.dataLayer = [];\n }\n win.dataLayer.push({\n event: FORM_SUBMIT_SUCCESS_EVENT,\n formId: context.formId,\n formName: context.formName,\n formType: context.formType,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Fire a Google Ads conversion via the page's `gtag`.\n *\n * When the site opted into enhanced conversions and `extras.userData` holds a\n * usable email or phone, `gtag('set', 'user_data', …)` runs first — Google\n * requires it before the conversion event.\n *\n * @param sendTo The Ads conversion label, e.g.\n * `\"AW-18321257894/AbC-D3fGhIjKlmNoP\"`. Anything empty or non-string is a\n * no-op — an unconfigured site simply does not fire a conversion.\n * @param extras Optional `transactionId` and `userData` for this submission.\n * @returns `true` when the conversion was sent, `false` otherwise.\n */\nexport function fireAdsConversion(\n sendTo: unknown,\n extras: ConversionExtras = {},\n): boolean {\n if (typeof sendTo !== \"string\" || sendTo.trim() === \"\") return false;\n const win = googleWindow();\n if (!win || typeof win.gtag !== \"function\") return false;\n try {\n if (win[ENHANCED_CONVERSIONS_GLOBAL] === true) {\n const userData = buildUserData(extras.userData);\n if (userData) win.gtag(\"set\", \"user_data\", userData);\n }\n win.gtag(\"event\", \"conversion\", {\n send_to: sendTo.trim(),\n ...(extras.transactionId ? { transaction_id: extras.transactionId } : {}),\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Send GA4's recommended `generate_lead` event for a successful submission.\n * Form identity only — no submitted values.\n *\n * @returns `true` when `gtag` was called, `false` otherwise.\n */\nexport function fireGenerateLead(context: FormConversionContext): boolean {\n const win = googleWindow();\n if (!win || typeof win.gtag !== \"function\") return false;\n try {\n win.gtag(\"event\", \"generate_lead\", {\n form_id: context.formId,\n form_type: context.formType,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the Ads `send_to` label for a form: the form's own config first,\n * then the site-wide value published by `CMSTags` on\n * {@link FORM_CONVERSION_SEND_TO_GLOBAL}.\n *\n * @param formSendTo `submitConfig.conversion.sendTo` for this form, if any.\n * @returns The trimmed label, or `undefined` when neither source supplies one.\n */\nexport function resolveConversionSendTo(formSendTo?: string): string | undefined {\n if (typeof formSendTo === \"string\" && formSendTo.trim() !== \"\") {\n return formSendTo.trim();\n }\n const global = googleWindow()?.[FORM_CONVERSION_SEND_TO_GLOBAL];\n if (typeof global === \"string\" && global.trim() !== \"\") return global.trim();\n return undefined;\n}\n\n/**\n * The single call `DynamicForm` makes on a genuine submission success: push\n * the `dataLayer` event, then fire the Ads conversion when a label resolves.\n *\n * Called exactly once per successful submit — after the `/api/contact`\n * response is accepted and before any success UI or redirect. Deliberately\n * NOT called on the spam short-circuit (honeypot/timer), which fakes a\n * success without ever reaching the server: counting caught bots as\n * conversions is precisely the pollution the short-circuit exists to prevent,\n * and it matches the existing rule that the spam path never reaches\n * `redirectUrl` (typically a conversion thank-you page).\n *\n * @param context Form identity for the `dataLayer` payload.\n * @param formSendTo Per-form Ads label override from\n * `submitConfig.conversion.sendTo`.\n * @param extras `transactionId` and enhanced-conversion `userData`.\n * @returns Which signals actually fired — useful in tests; callers in the\n * renderer ignore it.\n */\nexport function trackFormConversion(\n context: FormConversionContext,\n formSendTo?: string,\n extras: ConversionExtras = {},\n): { pushed: boolean; conversionFired: boolean; leadFired: boolean } {\n const pushed = pushFormSubmitSuccess(context);\n const conversionFired = fireAdsConversion(\n resolveConversionSendTo(formSendTo),\n extras,\n );\n const leadFired = fireGenerateLead(context);\n return { pushed, conversionFired, leadFired };\n}\n","import type { TextTransform } from \"../types\";\n\n/**\n * Formats raw digits as a US Social Security number (NNN-NN-NNNN).\n * Truncates anything past 9 digits.\n */\nexport function formatSsn(raw: string): string {\n const digits = raw.replace(/\\D/g, \"\").slice(0, 9);\n if (digits.length <= 3) return digits;\n if (digits.length <= 5) return `${digits.slice(0, 3)}-${digits.slice(3)}`;\n return `${digits.slice(0, 3)}-${digits.slice(3, 5)}-${digits.slice(5)}`;\n}\n\n/**\n * Formats raw digits as a US phone number: (555) 123 - 4567.\n * Strips a leading \"1\" country code from 11-digit pastes like\n * \"+1 (555) 123-4567\" and truncates anything past 10 digits so\n * oversized values don't dead-end the input.\n */\nexport function formatUsPhone(raw: string): string {\n const digits = raw.replace(/[^\\d]/g, \"\");\n const onlyNums = (\n digits.length === 11 && digits.startsWith(\"1\") ? digits.slice(1) : digits\n ).slice(0, 10);\n\n if (onlyNums.length > 6) {\n return `(${onlyNums.slice(0, 3)}) ${onlyNums.slice(3, 6)} - ${onlyNums.slice(6, 10)}`;\n }\n if (onlyNums.length > 3) {\n return `(${onlyNums.slice(0, 3)}) ${onlyNums.slice(3)}`;\n }\n if (onlyNums.length > 0) {\n return `(${onlyNums}`;\n }\n return \"\";\n}\n\n/**\n * Apply a `TextTransform` to a field value as the user types. Shared by the\n * free-text field renderers so every field type honors the transform picked\n * in the builder, and so the `ssn` transform and the sensitive `ssn` input\n * mask always produce identical output.\n *\n * @param value - The current input value.\n * @param transform - The transform configured on the field definition.\n * @returns The transformed value; unrecognized or absent transforms return\n * the value unchanged.\n */\nexport function applyTextTransform(\n value: string,\n transform?: TextTransform\n): string {\n switch (transform) {\n case \"capitalize-sentences\":\n return value.replace(/(^|\\. *)([a-z])/g, (letter) =>\n letter.toUpperCase()\n );\n case \"capitalize-words\":\n return value.replace(/^([a-z])|\\s+([a-z])/g, (letter) =>\n letter.toUpperCase()\n );\n case \"phone-number\":\n return formatUsPhone(value);\n case \"ssn\":\n return formatSsn(value);\n default:\n return value;\n }\n}\n","import type { FormDefinition, NotificationEmailTemplate } from \"../types\";\n\n/**\n * Variables available to a notification email template. Beyond the canonical\n * keys here, the renderer also accepts arbitrary form-field IDs / labels\n * looked up from the form definition (see `buildEmailTemplateVariables`).\n */\nexport interface EmailTemplateVariables {\n /** Project (site) display name. */\n projectName: string;\n /** Form display name (e.g. \"Contact Form\"). */\n formName: string;\n /** Submission timestamp as an ISO string. */\n submittedAt: string;\n /** Anything else the form sends — keyed by field id, label-slug, or canonical key. */\n [key: string]: string | number | boolean | undefined;\n}\n\n/** HTML-escape a value before substituting it into a template. */\nfunction escapeHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n return String(value)\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/**\n * Replace `{{key}}` placeholders in `template` with values from `variables`.\n * Unknown keys are replaced with an empty string. Whitespace inside the\n * braces is tolerated (`{{ name }}` works the same as `{{name}}`). Values\n * are HTML-escaped by default; pass `{ escape: false }` to interpolate into\n * non-HTML targets like the email subject line.\n */\nexport function renderEmailTemplate(\n template: string,\n variables: EmailTemplateVariables,\n options: { escape?: boolean } = {},\n): string {\n const shouldEscape = options.escape !== false;\n return template.replace(/\\{\\{\\s*([\\w.-]+)\\s*\\}\\}/g, (_match, key: string) => {\n const value = variables[key];\n if (value === undefined || value === null || value === \"\") return \"\";\n return shouldEscape ? escapeHtml(value) : String(value);\n });\n}\n\n/**\n * Build the variable bag handed to `renderEmailTemplate` from a form\n * definition + raw submission payload. Each form field is exposed under its\n * `id` and (when distinct) under a slugified version of its `label`, so\n * authors can reference fields with either `{{customer_name_1234}}` or\n * `{{customer_name}}`.\n */\nexport function buildEmailTemplateVariables(args: {\n definition?: Pick<FormDefinition, \"name\" | \"sections\">;\n projectName: string;\n formName?: string;\n submission: Record<string, unknown>;\n submittedAt?: string;\n}): EmailTemplateVariables {\n const { definition, projectName, submission, submittedAt } = args;\n\n const vars: EmailTemplateVariables = {\n projectName,\n formName: args.formName ?? definition?.name ?? \"Contact Form\",\n submittedAt: submittedAt ?? new Date().toISOString(),\n };\n\n // Pass through every primitive value on the submission directly so canonical\n // keys (`name`, `email`, `phone`, `message`, `serviceType`, …) just work.\n for (const [key, value] of Object.entries(submission)) {\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n vars[key] = value;\n }\n }\n\n // Also expose each defined field by a label-slug alias (e.g. \"Full Name\" →\n // \"full_name\") so authors don't need to remember opaque field IDs.\n if (definition?.sections) {\n for (const section of definition.sections) {\n for (const field of section.fields) {\n const value = submission[field.id];\n if (value === undefined || value === null) continue;\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n ) {\n continue;\n }\n const slug = labelToSlug(field.label);\n if (slug && vars[slug] === undefined) vars[slug] = value;\n }\n }\n }\n\n return vars;\n}\n\n/** Lowercase, alnum + underscore form of a field label — `\"Full Name\" → \"full_name\"`. */\nfunction labelToSlug(label: string): string {\n return label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n}\n\n/**\n * Variable descriptor used by the dashboard editor to render the \"Insert\n * variable\" picker. Order is informational; renderers don't depend on it.\n */\nexport interface EmailTemplateVariableDescriptor {\n key: string;\n description: string;\n example: string;\n}\n\nexport const CORE_EMAIL_TEMPLATE_VARIABLES: EmailTemplateVariableDescriptor[] =\n [\n {\n key: \"projectName\",\n description: \"Project (site) display name.\",\n example: \"Acme Co.\",\n },\n {\n key: \"formName\",\n description: \"Name of the form that was submitted.\",\n example: \"Contact Form\",\n },\n {\n key: \"submittedAt\",\n description: \"Submission timestamp (ISO 8601).\",\n example: new Date().toISOString(),\n },\n {\n key: \"name\",\n description: \"Submitter's name.\",\n example: \"Jane Doe\",\n },\n {\n key: \"email\",\n description: \"Submitter's email.\",\n example: \"jane@example.com\",\n },\n {\n key: \"phone\",\n description: \"Submitter's phone (if collected).\",\n example: \"555-123-4567\",\n },\n {\n key: \"message\",\n description: \"Free-text message body (if collected).\",\n example: \"I'd like to schedule a consultation.\",\n },\n {\n key: \"serviceType\",\n description: \"Selected service / category (if collected).\",\n example: \"Roof Repair\",\n },\n ];\n\n/**\n * Sample submission used to populate the editor's preview pane. Mirrors the\n * canonical keys most contact forms collect.\n */\nexport const SAMPLE_EMAIL_TEMPLATE_VARIABLES: EmailTemplateVariables = {\n projectName: \"Acme Co.\",\n formName: \"Contact Form\",\n submittedAt: new Date().toISOString(),\n name: \"Jane Doe\",\n email: \"jane@example.com\",\n phone: \"555-123-4567\",\n message: \"I'd like to schedule a consultation about your services.\",\n serviceType: \"Roof Repair\",\n};\n\n/** Convenience: render both subject + body of a template in one pass. */\nexport function renderNotificationEmail(\n template: NotificationEmailTemplate,\n variables: EmailTemplateVariables,\n): { subject: string; html: string } {\n // Subjects are plain text (no HTML escaping), but interpolated values are\n // user-submitted — flatten newlines so they can't smuggle extra headers\n // into a naive mailer.\n const subject = renderEmailTemplate(template.subject, variables, {\n escape: false,\n }).replace(/[\\r\\n]+/g, \" \");\n return {\n subject,\n html: renderEmailTemplate(template.html, variables),\n };\n}\n","/**\n * Client-side image downscaling for `file` fields.\n *\n * A phone camera hands the picker a 4000px, several-megabyte photo for what\n * is almost always displayed as a thumbnail on a lead. Downscaling in the\n * browser — before the bytes leave it — is the only place that saves the\n * submitter's upload time as well as our storage.\n *\n * The rule this module follows everywhere: **never lose a file to an\n * optimisation.** Every failure path (an undecodable file, a browser without\n * the APIs, an encoder that returns nothing, a re-encode that came out\n * bigger) returns the original `File` unchanged, so the worst case is the\n * behaviour we had before resizing existed.\n */\n\n/**\n * Formats that are safe to decode and re-encode.\n *\n * Deliberately short. GIF is excluded because a canvas round-trip keeps only\n * the first frame, silently turning an animation into a still. HEIC/HEIF are\n * excluded because only Safari can decode them, so the result would differ by\n * browser — and the `image/heic` file that reaches the CMS unresized is still\n * a valid stored attachment. SVG is excluded because it has no pixel width to\n * scale (and the CMS rejects it outright).\n */\nconst RESIZABLE_TYPES = new Set([\"image/jpeg\", \"image/png\", \"image/webp\"]);\n\n/**\n * Quality passed to the encoder for lossy formats. 0.85 is the usual\n * \"no visible difference at 100%\" point for photographic content and is what\n * the CMS media pipeline settled on.\n */\nconst ENCODE_QUALITY = 0.85;\n\n/**\n * Files above this are handed on untouched rather than decoded. Decoding\n * happens before the field's `maxSizeBytes` check (so that a large photo can\n * be *rescued* by resizing rather than rejected), which means this is the\n * only thing standing between the picker and a browser tab told to decode an\n * arbitrarily large file.\n */\nconst MAX_DECODE_BYTES = 50 * 1024 * 1024;\n\n/** True when this environment can actually do a canvas round-trip. */\nfunction canResize(): boolean {\n return (\n typeof createImageBitmap === \"function\" &&\n typeof document !== \"undefined\" &&\n typeof document.createElement === \"function\"\n );\n}\n\n/** Promise wrapper over the callback-style `canvas.toBlob`. */\nfunction canvasToBlob(\n canvas: HTMLCanvasElement,\n type: string,\n quality: number,\n): Promise<Blob | null> {\n return new Promise((resolve) => canvas.toBlob(resolve, type, quality));\n}\n\n/**\n * Scale an image file down so it is at most `maxWidth` pixels wide,\n * re-encoding it in its original format.\n *\n * Only images narrower-or-equal to the limit, unsupported formats, and files\n * this environment cannot decode are left alone — everything else comes back\n * as a new `File` carrying the same name, type and `lastModified`, so the\n * upload handler and the CMS's magic-byte check see an ordinary picked file.\n *\n * EXIF orientation is baked into the pixels (`imageOrientation: \"from-image\"`),\n * which is what a browser would have rendered anyway; the resized copy carries\n * no EXIF of its own, so a rotated photo stays upright without the metadata\n * that made it so.\n *\n * @param file - The picked file.\n * @param maxWidth - Maximum width in pixels. Non-positive or non-finite\n * values disable resizing.\n * @returns The downscaled file, or the original when resizing was skipped or\n * failed. Never rejects.\n */\nexport async function resizeImageFile(\n file: File,\n maxWidth: number,\n): Promise<File> {\n if (!Number.isFinite(maxWidth) || maxWidth <= 0) return file;\n if (!RESIZABLE_TYPES.has(file.type)) return file;\n if (file.size > MAX_DECODE_BYTES) return file;\n if (!canResize()) return file;\n\n let bitmap: ImageBitmap | undefined;\n try {\n bitmap = await createImageBitmap(file, { imageOrientation: \"from-image\" });\n if (bitmap.width <= maxWidth) return file;\n\n const width = Math.round(maxWidth);\n const height = Math.max(1, Math.round((bitmap.height * width) / bitmap.width));\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return file;\n ctx.drawImage(bitmap, 0, 0, width, height);\n\n const blob = await canvasToBlob(canvas, file.type, ENCODE_QUALITY);\n // A re-encode that grew (already-optimised source, or a PNG of a photo)\n // is a loss on both counts — bytes and fidelity. Keep the original.\n if (!blob || blob.size >= file.size) return file;\n\n return new File([blob], file.name, {\n type: file.type,\n lastModified: file.lastModified,\n });\n } catch {\n // Undecodable, out of memory, a tainted canvas — the original still\n // uploads fine, and a failed optimisation is not a failed submission.\n return file;\n } finally {\n bitmap?.close();\n }\n}\n","/**\n * Client-side encryption utilities for sensitive form fields.\n *\n * Hybrid encryption scheme:\n * 1. The browser fetches a transport public key (RSA-OAEP, 2048-bit) from\n * the server. The matching private key never leaves the server.\n * 2. For each sensitive field we generate a fresh AES-GCM-256 data key,\n * encrypt the plaintext with it, then wrap the data key with the RSA\n * public key. Both ciphertexts plus the IV travel to the server.\n * 3. The server unwraps the data key with its private key, decrypts the\n * plaintext, then re-encrypts with Google Cloud KMS for storage.\n *\n * The plaintext SSN (or other sensitive value) therefore never appears on\n * the wire in cleartext beyond TLS — even an attacker with access to the\n * Next.js request body would see only ciphertext.\n */\n\n/** Wire-format for an encrypted sensitive field value. */\nexport interface EncryptedSensitiveValue {\n /** Schema marker. Always \"v1\". */\n v: \"v1\";\n /** Identifier of the transport key used (matches server kid). */\n kid: string;\n /** Base64 RSA-OAEP-wrapped AES key. */\n wrappedKey: string;\n /** Base64 AES-GCM IV (12 bytes). */\n iv: string;\n /** Base64 AES-GCM ciphertext + auth tag. */\n ciphertext: string;\n /** Plaintext last-4 digits for display. Safe to store unencrypted. */\n last4: string;\n}\n\n/** JWK payload returned by the transport-key endpoint. */\nexport interface TransportPublicKey {\n kid: string;\n jwk: JsonWebKey;\n}\n\nfunction bufferToBase64(buf: ArrayBuffer): string {\n const bytes = new Uint8Array(buf);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i += 1) {\n binary += String.fromCharCode(bytes[i]);\n }\n // `btoa` is globally available in browsers and in Node 16+. The forms\n // package targets that environment everywhere it runs, so we don't fall\n // back to a Node-specific `Buffer` API.\n return btoa(binary);\n}\n\nfunction base64ToBuffer(b64: string): ArrayBuffer {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes.buffer;\n}\n\n/**\n * Imports a server-supplied JWK as an RSA-OAEP public key for wrapping.\n */\nasync function importTransportPublicKey(jwk: JsonWebKey): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"jwk\",\n jwk,\n { name: \"RSA-OAEP\", hash: \"SHA-256\" },\n false,\n [\"wrapKey\", \"encrypt\"]\n );\n}\n\n/**\n * Encrypt a single plaintext value using the supplied transport public key.\n * Returns the wire-format payload that the server expects.\n *\n * @param plaintext The cleartext value to encrypt (e.g. a Social Security\n * number). Must be a non-empty string.\n * @param publicKey Transport key descriptor previously fetched from the\n * server's transport-key endpoint.\n */\nexport async function encryptSensitiveValue(\n plaintext: string,\n publicKey: TransportPublicKey\n): Promise<EncryptedSensitiveValue> {\n if (typeof crypto === \"undefined\" || !crypto.subtle) {\n throw new Error(\n \"Web Crypto API is unavailable — sensitive fields require a secure browser context\"\n );\n }\n if (typeof plaintext !== \"string\" || plaintext.length === 0) {\n throw new Error(\"encryptSensitiveValue: plaintext must be a non-empty string\");\n }\n\n const rsaKey = await importTransportPublicKey(publicKey.jwk);\n\n // Fresh data key per submission — never reused.\n const dataKey = await crypto.subtle.generateKey(\n { name: \"AES-GCM\", length: 256 },\n true,\n [\"encrypt\"]\n );\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const encoded = new TextEncoder().encode(plaintext);\n\n const ciphertext = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv },\n dataKey,\n encoded\n );\n\n // Wrap the data key with the RSA-OAEP public key so only the server can\n // unwrap it. The wrapped key is opaque to the browser after this point.\n const wrappedKey = await crypto.subtle.wrapKey(\"raw\", dataKey, rsaKey, {\n name: \"RSA-OAEP\",\n });\n\n return {\n v: \"v1\",\n kid: publicKey.kid,\n wrappedKey: bufferToBase64(wrappedKey),\n iv: bufferToBase64(iv.buffer),\n ciphertext: bufferToBase64(ciphertext),\n last4: deriveLast4(plaintext),\n };\n}\n\n/**\n * Strips formatting (dashes, spaces) and returns the last four digits.\n * Used for the plaintext display marker stored alongside the ciphertext.\n */\nexport function deriveLast4(plaintext: string): string {\n const digits = plaintext.replace(/\\D/g, \"\");\n return digits.slice(-4).padStart(4, \"•\");\n}\n\nexport { bufferToBase64, base64ToBuffer };\n","/**\n * Ad-referral attribution — capture the campaign that brought a visitor to\n * the site, so a lead they submit later can be traced back to it.\n *\n * The flow has two halves that are deliberately separable:\n *\n * 1. {@link AdReferralTracker} (mounted once, in a site's root layout)\n * writes a 30-day cookie when the entry URL carries ad signal.\n * 2. `DynamicForm` reads that cookie at submit time and attaches it to the\n * payload as `adReferral`.\n *\n * Half 2 is inert without half 1: a site that never mounts the tracker has\n * no cookie, so its submissions are byte-identical to what they were before.\n * That is what makes the renderer-side read safe to ship to every consumer\n * at once — attribution turns on per site, by adding the tracker, not by\n * redeploying.\n *\n * The CMS normalizes the `adReferral` blob into a single groupable\n * `leadSource` bucket at ingestion (`lib/contacts/leadSource.ts`), which is\n * what the Contacts table and the lead-source breakdown chart read.\n *\n * Pure module — no React, no imports. Every function is a no-op on the\n * server, so it can be called from anywhere without a `typeof window` guard\n * at the call site.\n */\n\n/** Cookie the tracker writes and the renderer reads. */\nexport const AD_REFERRAL_COOKIE = \"vt_ad_ref\";\n\n/** How long an ad click stays credited for a later conversion. */\nexport const AD_REFERRAL_TTL_DAYS = 30;\n\n/**\n * Campaign context for a visit, as stored in the cookie and sent with a\n * submission.\n *\n * `source` / `medium` are the two the CMS actually classifies on; everything\n * else rides along for reporting.\n */\nexport interface AdReferral {\n /** `utm_source`, or \"google\" when inferred from a Google click id. */\n source: string;\n /** `utm_medium`, or \"cpc\" when inferred from a Google click id. */\n medium: string;\n /** `utm_campaign`, or \"(not set)\" when auto-tagging supplied no campaign. */\n campaign: string;\n /** `utm_term` — the keyword, when the campaign tags one. */\n term?: string;\n /** `utm_content` — the ad variant, when the campaign tags one. */\n content?: string;\n /**\n * The raw Google click id (`gclid`, `gbraid` or `wbraid`) when the visit\n * was auto-tagged. Kept so a lead can be reconciled against Google Ads\n * reporting, which joins on this and not on UTMs.\n */\n clickId?: string;\n /**\n * Which param {@link AdReferral.clickId} came from. Google's offline\n * conversion upload takes `gclid`, `gbraid` and `wbraid` in separate\n * columns, and the value alone can't reliably tell them apart, so a lead\n * without this can't be uploaded back to Google Ads. Absent on cookies\n * written before it existed.\n */\n clickIdType?: ClickIdType;\n /**\n * Path the visitor landed on (pathname only — the query string is already\n * captured as UTMs/click id, and dropping it keeps anything else a URL\n * might carry off the lead). Absent on cookies written before it existed.\n */\n landingPage?: string;\n /** When the visitor arrived, ISO 8601. */\n landedAt: string;\n}\n\n/** Longest `landingPage` stored, so a hostile path can't bloat the cookie. */\nconst LANDING_PAGE_MAX = 200;\n\n/** Normalize a pathname for storage, or `undefined` when unusable. */\nfunction cleanLandingPage(pathname: string | undefined): string | undefined {\n if (typeof pathname !== \"string\" || !pathname.startsWith(\"/\")) return undefined;\n return pathname.slice(0, LANDING_PAGE_MAX);\n}\n\n/**\n * Click-id params Google Ads auto-tagging appends.\n *\n * Auto-tagging is ON by default in Google Ads and does NOT add UTMs, so a\n * great many real ad clicks arrive carrying nothing but one of these. Reading\n * them is the difference between attributing most paid traffic and\n * attributing only the campaigns someone remembered to hand-tag.\n *\n * `gbraid` / `wbraid` are the iOS privacy-preserving variants of `gclid`.\n */\nconst CLICK_ID_PARAMS = [\"gclid\", \"gbraid\", \"wbraid\"] as const;\n\n/** One of the Google click-id params, as recorded in `clickIdType`. */\nexport type ClickIdType = (typeof CLICK_ID_PARAMS)[number];\n\n/** Narrow an untrusted value (e.g. from a cookie) to a {@link ClickIdType}. */\nfunction isClickIdType(value: unknown): value is ClickIdType {\n return (CLICK_ID_PARAMS as readonly unknown[]).includes(value);\n}\n\n/**\n * Params Google Ads adds to every ad click alongside the click id. They\n * matter on their own because Safari's tracking protection (Private\n * Browsing, links opened from Mail/Messages) strips `gclid` but leaves\n * these — so an ad click can arrive with `gad_source=1` and no click id.\n */\nconst GOOGLE_AD_PARAMS = [\"gad_source\", \"gad_campaignid\"] as const;\n\n/** UTM params read into an {@link AdReferral}, in `AdReferral` key order. */\nconst UTM_PARAMS = [\n [\"utm_source\", \"source\"],\n [\"utm_medium\", \"medium\"],\n [\"utm_campaign\", \"campaign\"],\n [\"utm_term\", \"term\"],\n [\"utm_content\", \"content\"],\n] as const;\n\n/**\n * Defaults applied on a page that only ever receives ad traffic.\n *\n * Used for a dedicated paid-search landing page that is `noindex` and\n * unlinked from the rest of the site: everyone there came from an ad, so a\n * visit with no tagging at all is still an ad visit. Supplying this on a\n * normal page would label organic visitors as paid, which is why it is\n * opt-in per page rather than a built-in default.\n */\nexport interface AdReferralFallback {\n source: string;\n medium: string;\n campaign: string;\n}\n\n/**\n * Build an {@link AdReferral} from a URL's query string.\n *\n * Returns `null` when the URL carries no ad signal and no `fallback` is\n * given — the gate that keeps organic, direct and internal traffic out of\n * the paid bucket. \"Ad signal\" means any `utm_*` param or any Google click\n * id; a click id alone is read as `google` / `cpc`, matching how the CMS's\n * own realtime analytics classifies `gclid`.\n *\n * @param search The URL query string (`window.location.search`).\n * @param fallback Applied only when the URL carries no signal at all.\n * @param now Injectable clock, for tests.\n * @param pathname The landing path (`window.location.pathname`), stored as\n * `landingPage`. Optional so older callers keep working.\n * @returns The referral to store, or `null` to leave any existing cookie alone.\n */\nexport function captureAdReferral(\n search: string,\n fallback?: AdReferralFallback,\n now: Date = new Date(),\n pathname?: string,\n): AdReferral | null {\n const landingPage = cleanLandingPage(pathname);\n const params = new URLSearchParams(search);\n\n const utm: Partial<Record<(typeof UTM_PARAMS)[number][1], string>> = {};\n for (const [param, key] of UTM_PARAMS) {\n const value = params.get(param);\n if (value) utm[key] = value;\n }\n\n let clickId: string | undefined;\n let clickIdType: ClickIdType | undefined;\n for (const param of CLICK_ID_PARAMS) {\n const value = params.get(param);\n if (value) {\n clickId = value;\n clickIdType = param;\n break;\n }\n }\n\n const adCampaignId = params.get(\"gad_campaignid\") || undefined;\n const googleAdClick =\n clickId !== undefined || GOOGLE_AD_PARAMS.some((p) => params.get(p));\n\n const hasSignal = Object.keys(utm).length > 0 || googleAdClick;\n if (!hasSignal) {\n if (!fallback) return null;\n // Named fields rather than a spread: a fallback built at runtime could\n // otherwise smuggle arbitrary keys into the cookie and onto a lead.\n return {\n source: fallback.source,\n medium: fallback.medium,\n campaign: fallback.campaign,\n ...(landingPage ? { landingPage } : {}),\n landedAt: now.toISOString(),\n };\n }\n\n return {\n // An auto-tagged click with no UTMs is a Google paid click. Inferring\n // this is what makes `classifySource` bucket it as \"paid\" rather than\n // leaving the lead unattributed.\n //\n // Tagging that sets only `utm_campaign` (or only term/content) leaves\n // BOTH of these empty, and that is deliberate: the CMS's\n // `deriveLeadSource` only classifies when one of them is non-empty and\n // otherwise returns undefined, so such a lead reads as \"unknown\". Do not\n // \"fix\" this by defaulting to \"direct\" — an honest unknown beats a\n // fabricated bucket, and the campaign still rides along for inspection.\n source: utm.source ?? (googleAdClick ? \"google\" : \"\"),\n medium: utm.medium ?? (googleAdClick ? \"cpc\" : \"\"),\n campaign: utm.campaign ?? adCampaignId ?? (googleAdClick ? \"(not set)\" : \"\"),\n ...(utm.term ? { term: utm.term } : {}),\n ...(utm.content ? { content: utm.content } : {}),\n ...(clickId ? { clickId, clickIdType } : {}),\n ...(landingPage ? { landingPage } : {}),\n landedAt: now.toISOString(),\n };\n}\n\n/**\n * Read the stored referral for this browser.\n *\n * @param cookieName Override for a site still on a legacy cookie name.\n * @returns The stored referral, or `null` when absent, unreadable or malformed.\n */\nexport function readAdReferral(\n cookieName: string = AD_REFERRAL_COOKIE,\n): AdReferral | null {\n if (typeof document === \"undefined\") return null;\n\n for (const cookie of document.cookie.split(\";\")) {\n const separator = cookie.indexOf(\"=\");\n if (separator === -1) continue;\n if (cookie.slice(0, separator).trim() !== cookieName) continue;\n\n try {\n const parsed: unknown = JSON.parse(\n decodeURIComponent(cookie.slice(separator + 1)),\n );\n // A hand-edited or truncated cookie must not become a malformed\n // `adReferral` on a real lead.\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return null;\n }\n const { source, medium, campaign, landedAt, clickIdType, ...rest } =\n parsed as Partial<AdReferral>;\n if (typeof source !== \"string\" || typeof medium !== \"string\") return null;\n // Normalise rather than reject: a cookie that still carries source and\n // medium is a usable credit, and throwing it away loses a real lead's\n // attribution. Filling the two required-but-missing fields keeps the\n // returned object honest to its type, which a bare cast did not.\n // `clickIdType` feeds an upload to Google, so anything but one of the\n // three known params is dropped rather than passed along.\n return {\n ...rest,\n source,\n medium,\n campaign: typeof campaign === \"string\" ? campaign : \"\",\n ...(isClickIdType(clickIdType) ? { clickIdType } : {}),\n landedAt: typeof landedAt === \"string\" ? landedAt : \"\",\n };\n } catch {\n return null;\n }\n }\n\n return null;\n}\n\n/**\n * Whether two referrals record the same touch: every field equal except\n * `landedAt`, which is just when it was stamped.\n *\n * The client tracker uses this to leave alone a cookie the server already\n * wrote for this landing (`adReferralServer.ts`). Rewriting identical content\n * from JavaScript would turn an uncapped HTTP cookie into a script-written one,\n * and Safari caps those to 7 days, or 24 hours after a gclid landing.\n *\n * @returns `true` when the two differ in nothing but `landedAt`.\n */\nexport function isSameAdReferralTouch(a: AdReferral, b: AdReferral): boolean {\n // Both directions, so a field present on only one side counts as a change.\n return [...Object.keys(a), ...Object.keys(b)].every(\n (key) =>\n key === \"landedAt\" ||\n a[key as keyof AdReferral] === b[key as keyof AdReferral],\n );\n}\n\n/**\n * Store a referral, replacing any previous one.\n *\n * Overwriting is last-touch attribution on purpose: when a visitor arrives\n * on a fresh ad click, that click is what earned the conversion, not one\n * from three weeks ago. Visits with no ad signal never reach here (see\n * {@link captureAdReferral}), so ordinary browsing can't erase a credit.\n *\n * @param referral What to store.\n * @param cookieName Override for a site still on a legacy cookie name.\n * @param ttlDays How long the credit survives.\n */\nexport function writeAdReferral(\n referral: AdReferral,\n cookieName: string = AD_REFERRAL_COOKIE,\n ttlDays: number = AD_REFERRAL_TTL_DAYS,\n): void {\n if (typeof document === \"undefined\") return;\n\n const expires = new Date();\n expires.setDate(expires.getDate() + ttlDays);\n\n const value = encodeURIComponent(JSON.stringify(referral));\n document.cookie =\n `${cookieName}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;\n}\n","/**\n * The `@vulcantech/analytics` visit (session) id, read so a form submission\n * can carry it. The CMS looks the visit up to label where the lead came from\n * (Google Ads, Google, ChatGPT, a referring site…) even when no ad cookie\n * exists — see `lib/contacts/visitSource.ts` in the CMS.\n *\n * The two packages are independent, so the storage key is mirrored here\n * rather than imported; it must match `SESSION_KEY` in\n * `packages/analytics/src/tracker.ts`.\n */\nexport const ANALYTICS_SESSION_KEY = \"__vt_sid\";\n\n/**\n * @returns The current tab's analytics session id, or `undefined` on the\n * server, when the site has no analytics tracker, or when storage is blocked.\n */\nexport function readAnalyticsSessionId(): string | undefined {\n if (typeof window === \"undefined\") return undefined;\n try {\n const sid = window.sessionStorage.getItem(ANALYTICS_SESSION_KEY);\n return sid && /^[a-z0-9]{6,64}$/i.test(sid) ? sid : undefined;\n } catch {\n return undefined;\n }\n}\n","import type {\n FormColorScheme,\n FormDefinition,\n FormSection,\n FormStyle,\n FormStyleColors,\n} from \"../types\";\nimport { FORM_STYLE_COLOR_KEYS } from \"../types\";\n\n/** True when at least one dark color slot is set on the style. */\nexport function hasDarkColors(style: FormStyle | undefined): boolean {\n const dark = style?.dark;\n if (!dark) return false;\n return FORM_STYLE_COLOR_KEYS.some((key) => Boolean(dark[key]));\n}\n\n/**\n * True when the definition carries any dark-mode color at all — a style\n * slot, the form-level header text, or one section's header text. This is\n * what decides whether the renderer emits its dark-mode hooks; a record\n * with none renders byte-identical markup to one authored before dark mode\n * existed.\n */\nexport function definitionHasDarkColors(\n definition: Pick<FormDefinition, \"style\" | \"defaultTextColorDark\" | \"sections\">,\n): boolean {\n if (hasDarkColors(definition.style)) return true;\n if (definition.defaultTextColorDark) return true;\n return definition.sections.some((section) => Boolean(section.textColorDark));\n}\n\n/**\n * The color slots a form shows in `scheme`. For \"dark\", each slot takes its\n * dark value when set and its light value otherwise — an unset dark slot\n * means \"same as light\", never \"package default\". Slots unset in both\n * schemes are omitted so the renderer's `var()` fallbacks still apply.\n */\nexport function resolveSchemeColors(\n style: FormStyle,\n scheme: FormColorScheme,\n): FormStyleColors {\n const dark = scheme === \"dark\" ? style.dark : undefined;\n const out: FormStyleColors = {};\n for (const key of FORM_STYLE_COLOR_KEYS) {\n const value = dark?.[key] || style[key];\n if (value) out[key] = value;\n }\n return out;\n}\n\n/**\n * A `FormStyle` whose color slots are already resolved for `scheme`, with\n * no `dark` key left on it. This is what the builder preview renders when\n * it is pinned to one scheme.\n */\nexport function resolveSchemeStyle(\n style: FormStyle,\n scheme: FormColorScheme,\n): FormStyle {\n const structural: FormStyle = { ...style };\n delete structural.dark;\n for (const key of FORM_STYLE_COLOR_KEYS) delete structural[key];\n return { ...structural, ...resolveSchemeColors(style, scheme) };\n}\n\n/**\n * Section header text color for `scheme`. Dark mode consults the dark chain\n * first (the section, then the form default) and only then the light chain,\n * so a single form-level dark color re-themes every header — including\n * sections that pinned a light `textColor` before dark mode existed. Light\n * mode is the chain it always was: the section, then the form default.\n */\nexport function resolveSectionTextColor(\n section: Pick<FormSection, \"textColor\" | \"textColorDark\">,\n formDefaults: { light?: string; dark?: string },\n scheme: FormColorScheme,\n): string | undefined {\n const light = section.textColor || formDefaults.light || undefined;\n if (scheme === \"light\") return light;\n return section.textColorDark || formDefaults.dark || light;\n}\n","import type { CSSProperties } from \"react\";\nimport type { FormColorScheme, FormStyle, FormStyleColorKey } from \"../types\";\nimport { FORM_STYLE_COLOR_KEYS } from \"../types\";\nimport { resolveSchemeColors } from \"../utils/colorScheme\";\n\n/**\n * Single source of truth for the CSS custom properties the renderer publishes\n * on the form root.\n *\n * The form builder writes per-form color overrides into `FormStyle`. Every\n * color is optional: when set, `buildFormCssVars()` emits it as an inline CSS\n * variable on the form root; when unset, the variable is omitted and the\n * `var(..., fallback)` references in `INPUT_VAR` / `BUTTON_VAR` etc. resolve\n * to the baked-in default below.\n *\n * Field components read from these var references — they never touch the\n * raw `FormStyle` colors — so a single picker change cascades to every\n * field automatically.\n */\n\nexport const FORM_CSS_VAR = {\n formBg: \"--form-bg\",\n inputBg: \"--form-input-bg\",\n inputBorder: \"--form-input-border\",\n inputFocusBorder: \"--form-input-focus-border\",\n inputText: \"--form-input-text\",\n placeholder: \"--form-placeholder\",\n labelText: \"--form-label-text\",\n error: \"--form-error\",\n buttonBg: \"--form-button-bg\",\n buttonText: \"--form-button-text\",\n} as const;\n\n/**\n * Structural custom properties. Unlike the colors these are NOT always\n * available: `--form-radius` is published only when the form opts into a\n * custom corner via `FormStyle.borderRadiusValue`, because the default path\n * still uses Tailwind `rounded-*` classes and must keep emitting byte-identical\n * markup for every form authored before this existed.\n */\nexport const FORM_STRUCT_VAR = {\n radius: \"--form-radius\",\n gap: \"--form-gap\",\n focusBorderWidth: \"--form-focus-border-width\",\n} as const;\n\n/** Fallback used inside `var(--form-radius, ...)` if the var goes missing. */\nexport const FORM_DEFAULT_RADIUS = \"0.375rem\";\n\n/**\n * `var(--form-radius, 0.375rem)` — the reference the form root, inputs and\n * submit button all share, so one control moves every corner at once.\n */\nexport const FORM_RADIUS_VAR = `var(${FORM_STRUCT_VAR.radius}, ${FORM_DEFAULT_RADIUS})`;\n\n/** `var(--form-gap, 1rem)` — the gap between fields when overridden. */\nexport const FORM_GAP_VAR = `var(${FORM_STRUCT_VAR.gap}, 1rem)`;\n\n/** Fallback matching the `filled`/`underlined` variants' baked-in 2px bottom border. */\nexport const FORM_DEFAULT_FOCUS_BORDER_WIDTH = \"2px\";\n\n/**\n * `var(--form-focus-border-width, 2px)` — bottom-border thickness applied to\n * `filled`/`underlined` inputs on focus and on validation error.\n */\nexport const FORM_FOCUS_BORDER_WIDTH_VAR = `var(${FORM_STRUCT_VAR.focusBorderWidth}, ${FORM_DEFAULT_FOCUS_BORDER_WIDTH})`;\n\n/**\n * The custom field gap a form has opted into, or `null` when the gap should\n * keep following `style.spacing`.\n */\nexport function resolveCustomGap(style: FormStyle): string | null {\n const raw = style.fieldGapValue?.trim();\n return raw ? raw : null;\n}\n\n/**\n * The custom corner length a form has opted into, or `null` when it is still\n * on the named `borderRadius` steps. Every radius decision in the renderer\n * branches on this one helper so the opt-in stays in a single place.\n */\nexport function resolveCustomRadius(style: FormStyle): string | null {\n const raw = style.borderRadiusValue?.trim();\n return raw ? raw : null;\n}\n\n/**\n * The custom focus/error bottom-border width a form has opted into, or\n * `null` when it should keep the variant's baked-in 2px width.\n */\nexport function resolveCustomFocusBorderWidth(style: FormStyle): string | null {\n const raw = style.inputFocusBorderWidth?.trim();\n return raw ? raw : null;\n}\n\n/**\n * Baked-in defaults used when the FormStyle doesn't override a color. These\n * are the fallbacks inside the `var(--name, fallback)` references that the\n * renderer uses, so they apply automatically whenever the corresponding var\n * isn't set on the form root.\n */\nexport const FORM_DEFAULT_COLOR = {\n formBg: \"transparent\",\n inputBg: \"inherit\",\n inputBorder: \"#d1d5db\",\n inputFocusBorder: \"#2563eb\",\n inputText: \"inherit\",\n placeholder: \"#9ca3af\",\n labelText: \"inherit\",\n error: \"#ef4444\",\n buttonBg: \"#2563eb\",\n buttonText: \"#ffffff\",\n} as const;\n\n/** Reference like `var(--form-input-bg, #ffffff)` for inline-style use. */\nfunction ref(name: string, fallback: string): string {\n return `var(${name}, ${fallback})`;\n}\n\n/**\n * Pre-built `var(...)` references with fallbacks. Pass these straight into\n * inline `style` props; the form root's CSS variables override the fallback\n * automatically wherever the user has set a color.\n */\nexport const FORM_VAR = {\n formBg: ref(FORM_CSS_VAR.formBg, FORM_DEFAULT_COLOR.formBg),\n inputBg: ref(FORM_CSS_VAR.inputBg, FORM_DEFAULT_COLOR.inputBg),\n inputBorder: ref(FORM_CSS_VAR.inputBorder, FORM_DEFAULT_COLOR.inputBorder),\n inputFocusBorder: ref(\n FORM_CSS_VAR.inputFocusBorder,\n FORM_DEFAULT_COLOR.inputFocusBorder,\n ),\n inputText: ref(FORM_CSS_VAR.inputText, FORM_DEFAULT_COLOR.inputText),\n placeholder: ref(FORM_CSS_VAR.placeholder, FORM_DEFAULT_COLOR.placeholder),\n labelText: ref(FORM_CSS_VAR.labelText, FORM_DEFAULT_COLOR.labelText),\n error: ref(FORM_CSS_VAR.error, FORM_DEFAULT_COLOR.error),\n buttonBg: ref(FORM_CSS_VAR.buttonBg, FORM_DEFAULT_COLOR.buttonBg),\n buttonText: ref(FORM_CSS_VAR.buttonText, FORM_DEFAULT_COLOR.buttonText),\n} as const;\n\n/** `FormStyle` color key → the custom property it publishes. */\nconst COLOR_VAR_BY_KEY: Record<FormStyleColorKey, string> = {\n formBackgroundColor: FORM_CSS_VAR.formBg,\n inputBgColor: FORM_CSS_VAR.inputBg,\n inputBorderColor: FORM_CSS_VAR.inputBorder,\n inputFocusColor: FORM_CSS_VAR.inputFocusBorder,\n inputTextColor: FORM_CSS_VAR.inputText,\n placeholderColor: FORM_CSS_VAR.placeholder,\n labelColor: FORM_CSS_VAR.labelText,\n errorColor: FORM_CSS_VAR.error,\n buttonColor: FORM_CSS_VAR.buttonBg,\n buttonTextColor: FORM_CSS_VAR.buttonText,\n};\n\n/**\n * Attribute the renderer puts on a form root that carries a dark palette —\n * and on the select popover, which is portaled out of the root's subtree.\n * The dark-mode stylesheet keys off it, so a form without dark colors is\n * never touched by that stylesheet, even on a page that has the class.\n */\nexport const FORM_DARK_SCOPE_ATTR = \"data-vt-form-dark\";\n\n/** Attribute on a section title/description that publishes `--form-text-dark`. */\nexport const FORM_DARK_TEXT_ATTR = \"data-vt-text-dark\";\n\n/** Dark-mode header text color, published on the header element itself. */\nexport const FORM_DARK_TEXT_VAR = \"--form-text-dark\";\n\n/**\n * Ancestor selector under which a form's dark palette applies. `.dark` is\n * the class next-themes puts on `<html>` in every VulcanTech site with a\n * theme toggle. It is deliberately NOT `prefers-color-scheme`, which would\n * flip a form on a light-only site whenever the visitor's OS is dark — the\n * exact bug BL-553 removed from this package.\n */\nexport const FORM_DEFAULT_DARK_SELECTOR = \".dark\";\n\n/**\n * `var(--form-bg, inherit)` — what the root's own `background-color` reads\n * once a form carries a dark palette. The `inherit` fallback matches the\n * `bg-inherit` class the root always has, so a form with no background in\n * either scheme keeps flowing the consumer's container color down to the\n * inputs and floating labels.\n */\nexport const FORM_ROOT_BG_VAR = `var(${FORM_CSS_VAR.formBg}, inherit)`;\n\n/** The dark-mode counterpart of a color custom property: `--form-bg` → `--form-bg-dark`. */\nexport function darkVarName(name: string): string {\n return `${name}-dark`;\n}\n\n/**\n * Inline custom properties for the given color slots: light values under\n * their usual names, or the resolved dark values under the `-dark` names.\n * Unset slots are omitted so the renderer's `var()` fallbacks still apply.\n */\nexport function buildColorVars(\n style: FormStyle,\n scheme: FormColorScheme,\n keys: readonly FormStyleColorKey[] = FORM_STYLE_COLOR_KEYS,\n): Record<string, string> {\n const colors = resolveSchemeColors(style, scheme);\n const out: Record<string, string> = {};\n for (const key of keys) {\n const value = colors[key];\n if (!value) continue;\n const name = COLOR_VAR_BY_KEY[key];\n out[scheme === \"dark\" ? darkVarName(name) : name] = value;\n }\n return out;\n}\n\n/**\n * Build the inline `style` object the form root should receive: a CSS\n * variable for each color the FormStyle overrides, leaving the rest to fall\n * back via `FORM_VAR.*`, plus the structural custom properties the form has\n * opted into. `previewBg` (editor-only) is the canvas the builder shows the\n * form on; it fills `--form-bg` only when the record sets no background of\n * its own, so what the builder shows is what the record will render.\n */\nexport function buildFormCssVars(\n style: FormStyle,\n previewBg?: string,\n): CSSProperties {\n const light = buildColorVars(style, \"light\");\n const out: Record<string, string> = {};\n\n const formBg = light[FORM_CSS_VAR.formBg] ?? previewBg;\n if (formBg) out[FORM_CSS_VAR.formBg] = formBg;\n for (const [name, value] of Object.entries(light)) {\n if (name !== FORM_CSS_VAR.formBg) out[name] = value;\n }\n\n const customRadius = resolveCustomRadius(style);\n if (customRadius) out[FORM_STRUCT_VAR.radius] = customRadius;\n\n const customGap = resolveCustomGap(style);\n if (customGap) out[FORM_STRUCT_VAR.gap] = customGap;\n\n const customFocusBorderWidth = resolveCustomFocusBorderWidth(style);\n if (customFocusBorderWidth)\n out[FORM_STRUCT_VAR.focusBorderWidth] = customFocusBorderWidth;\n\n return out as CSSProperties;\n}\n\n/**\n * The `-dark` custom properties a form root (or the select popover)\n * publishes when the record carries a dark palette. Every slot with a value\n * in EITHER scheme gets one — the light value stands in where no dark value\n * is set — so the dark stylesheet's `var(--x-dark)` swap never drops a color\n * the light palette had.\n */\nexport function buildFormDarkCssVars(\n style: FormStyle,\n keys?: readonly FormStyleColorKey[],\n): CSSProperties {\n return buildColorVars(style, \"dark\", keys) as CSSProperties;\n}\n\n/**\n * The stylesheet that turns a dark palette on. It is one constant rule set,\n * independent of any record: under `darkSelector`, every color custom\n * property on a scoped element is replaced by its `-dark` counterpart, and a\n * scoped header takes `--form-text-dark`.\n *\n * `!important` is the point, not a shortcut. The light palette is inline on\n * the form root — that is what lets a record's colors beat any consumer\n * stylesheet — and an important author declaration is the one cascade level\n * that outranks an inline style without touching the markup light mode\n * renders. A slot with no `-dark` value computes to invalid and falls to the\n * same `var()` fallback light mode uses.\n */\nexport function buildDarkSchemeCss(\n darkSelector: string = FORM_DEFAULT_DARK_SELECTOR,\n): string {\n const swaps = Object.values(FORM_CSS_VAR)\n .map((name) => `${name}:var(${darkVarName(name)})!important`)\n .join(\";\");\n const scope = `${darkSelector} [${FORM_DARK_SCOPE_ATTR}]`;\n return (\n `${scope}{${swaps}}` +\n `${scope} [${FORM_DARK_TEXT_ATTR}]{color:var(${FORM_DARK_TEXT_VAR})!important}`\n );\n}\n\n/**\n * Chrome colors expressed relative to `currentColor` instead of fixed grays.\n *\n * The renderer ships as source that each consumer app compiles with its own\n * Tailwind config, so the package can't opt into a `dark:` class strategy —\n * a `dark:` variant here fires on the visitor's OS preference alone and has\n * no way to know whether the surrounding page even has a dark mode. A\n * light-only site (castlerents) was getting near-white section headings on\n * its cream ground whenever the visitor's OS was dark. Mixing `currentColor`\n * toward transparent tracks whatever text color the form inherits, in either\n * theme, with no media query and nothing for the consumer to configure.\n *\n * Text that has its own picker (`--form-label-text`, `--form-error`, …) keeps\n * using that var; these are only for the chrome that has no control of its\n * own — help text, counters, dividers, the file drop zone.\n */\nexport const FORM_MUTED_TEXT_CLASS = \"text-current/65\";\n\n/** Tertiary text — size hints, icons. Present, but never competing. */\nexport const FORM_FAINT_TEXT_CLASS = \"text-current/45\";\n\n/** Hairlines: section dividers, the drop zone, file chips. */\nexport const FORM_SUBTLE_BORDER_CLASS = \"border-current/20\";\n\n/** Barely-there fills: progress track, file chip. */\nexport const FORM_SUBTLE_FILL_CLASS = \"bg-current/10\";\n\n/**\n * Icon-button hover fill. Spelled out rather than built from\n * `FORM_SUBTLE_FILL_CLASS`, because Tailwind scans source for literal class\n * strings — an interpolated `hover:${...}` is a class that never gets\n * generated.\n */\nexport const FORM_SUBTLE_HOVER_FILL_CLASS = \"hover:bg-current/10\";\n","\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { FormColorScheme, FormStyle } from \"../types\";\nimport { DEFAULT_FORM_STYLE } from \"../types\";\n\nconst FormStyleContext = createContext<FormStyle>(DEFAULT_FORM_STYLE);\n\nexport const useFormStyle = () => useContext(FormStyleContext);\nexport const FormStyleProvider = FormStyleContext.Provider;\n\n/**\n * How the renderer is resolving color schemes for this form.\n *\n * - `forced` — editor-only. The builder pins its preview to one scheme; the\n * renderer then emits that palette inline and none of the dark-mode\n * hooks, so what the author sees never depends on the CMS's own theme.\n * - `darkEnabled` — the automatic path is on: the record carries a dark\n * palette, and the form root has published its `-dark` variables plus the\n * scope attribute the dark stylesheet keys off. Descendants rendered\n * outside the root's subtree (the select popover is portaled) read this\n * to know they must publish their own.\n */\nexport interface FormColorSchemeState {\n forced?: FormColorScheme;\n darkEnabled: boolean;\n}\n\nconst FormColorSchemeContext = createContext<FormColorSchemeState>({\n darkEnabled: false,\n});\n\nexport const useFormColorScheme = () => useContext(FormColorSchemeContext);\nexport const FormColorSchemeProvider = FormColorSchemeContext.Provider;\n","import { twMerge } from \"tailwind-merge\";\nimport type { FormStyle } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport {\n FORM_FOCUS_BORDER_WIDTH_VAR,\n FORM_RADIUS_VAR,\n FORM_VAR,\n resolveCustomFocusBorderWidth,\n resolveCustomRadius,\n} from \"../cssVars\";\n\ninterface InputStyles {\n wrapperClass: string;\n inputClass: string;\n inputStyle: React.CSSProperties;\n inputFocusStyle: React.CSSProperties;\n labelClass: string;\n labelStyle: React.CSSProperties;\n errorStyle: React.CSSProperties;\n /** CSS `var(...)` reference for the focus / accent color. */\n accentColor: string;\n isStacked: boolean;\n}\n\n// Placeholder color is the one property that needs a pseudo-element selector,\n// which inline `style` can't reach. Tailwind's arbitrary-property syntax\n// emits the equivalent rule and reads the same CSS variable as everything\n// else, so the placeholder picker still cascades from the form root.\nconst placeholderClass =\n \"placeholder:[color:var(--form-placeholder,#9ca3af)]\";\n\n// Input text color flows through the var system too — using arbitrary-color\n// syntax lets us pick it up without giving every variant its own inline\n// color rule. The fallback `inherit` lets the consumer's typography win when\n// the picker is left on \"Inherited\".\nconst textClass = \"text-[color:var(--form-input-text,inherit)]\";\n\nfunction getVariantClasses(style: FormStyle): {\n inputClass: string;\n inputStyle: React.CSSProperties;\n labelClass: string;\n} {\n switch (style.inputVariant) {\n case \"stacked\":\n return {\n inputClass: twMerge(\n \"w-full rounded-lg border px-4 py-3 text-base transition focus:outline-none disabled:cursor-not-allowed\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderColor: FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n },\n labelClass: \"mb-1 block text-sm font-medium\",\n };\n\n case \"filled\":\n return {\n inputClass: twMerge(\n \"rounded-t-md px-3 py-1.5 text-base transition ease-in-out placeholder:opacity-0 focus:outline-none focus:placeholder:opacity-100 disabled:cursor-not-allowed\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderStyle: \"solid\",\n borderWidth: 0,\n borderBottomWidth: 2,\n borderBottomColor: FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n },\n labelClass:\n \"absolute left-2 top-2 z-10 flex min-h-[1ch] w-min -translate-y-[18px] cursor-text flex-col justify-around whitespace-nowrap rounded-md px-1 text-sm transition-transform group-focus-within:-translate-y-[18px] peer-placeholder-shown:translate-y-0 peer-focus:-translate-y-[18px]\",\n };\n\n case \"underlined\":\n return {\n inputClass: twMerge(\n \"rounded-none bg-inherit px-1 py-1.5 text-base transition ease-in-out placeholder:opacity-0 focus:outline-none focus:placeholder:opacity-100 disabled:cursor-not-allowed\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderStyle: \"solid\",\n borderWidth: 0,\n borderBottomWidth: 2,\n borderBottomColor: FORM_VAR.inputBorder,\n },\n labelClass:\n \"absolute left-1 top-2 z-10 flex min-h-[1ch] w-min -translate-y-[18px] cursor-text flex-col justify-around whitespace-nowrap px-0 text-sm transition-transform group-focus-within:-translate-y-[18px] peer-placeholder-shown:translate-y-0 peer-focus:-translate-y-[18px]\",\n };\n\n case \"outlined\":\n default:\n return {\n inputClass: twMerge(\n \"rounded px-3 py-1.5 text-base transition ease-in-out placeholder:opacity-0 focus:outline-none focus:placeholder:opacity-100 disabled:cursor-not-allowed bg-inherit\",\n textClass,\n placeholderClass,\n ),\n inputStyle: {\n borderStyle: \"solid\",\n borderWidth: 1,\n borderColor: FORM_VAR.inputBorder,\n },\n // Label must paint a solid bg on top of the input border. It reads\n // `--form-input-bg`, which DynamicForm publishes on the form root\n // from the resolved input background (or the editor preview\n // override). The fallback is `inherit`, and it now resolves to a\n // real color: every element from the form root down to this span\n // carries `bg-inherit`, so an unstyled form picks up whatever\n // background the consumer's container paints. See the chain note in\n // DynamicForm.\n labelClass:\n \"absolute left-2 top-2 z-10 flex min-h-[1ch] w-min -translate-y-[18px] cursor-text flex-col justify-around whitespace-nowrap rounded-md bg-[var(--form-input-bg,inherit)] px-1 text-sm transition-transform group-focus-within:-translate-y-[18px] peer-placeholder-shown:translate-y-0 peer-focus:-translate-y-[18px]\",\n };\n }\n}\n\nfunction getFocusStyle(style: FormStyle): React.CSSProperties {\n if (style.inputVariant === \"filled\" || style.inputVariant === \"underlined\") {\n return {\n borderBottomColor: FORM_VAR.inputFocusBorder,\n ...(resolveCustomFocusBorderWidth(style)\n ? { borderBottomWidth: FORM_FOCUS_BORDER_WIDTH_VAR }\n : {}),\n };\n }\n if (style.inputVariant === \"stacked\") {\n // Stacked picks up a 2px focus ring tinted from the accent color. We\n // can't shade a CSS var inside a string template here so the ring uses\n // a fixed translucent slate — the focus border itself still tracks the\n // user-picked focus color.\n return {\n borderColor: FORM_VAR.inputFocusBorder,\n boxShadow: \"0 0 0 2px rgba(37, 99, 235, 0.2)\",\n };\n }\n return { borderColor: FORM_VAR.inputFocusBorder };\n}\n\nexport function useInputStyles(): InputStyles {\n const style = useFormStyle();\n const variant = getVariantClasses(style);\n const isStacked = style.inputVariant === \"stacked\";\n\n // Each variant bakes its own corner (`stacked` is rounded-lg, `underlined`\n // is square), and `style.borderRadius` never reached inputs at all. A form\n // that opts into a custom radius gets that class neutralised and the corner\n // driven from `--form-radius` instead, so one control moves the form root,\n // the inputs and the button together.\n const customRadius = resolveCustomRadius(style);\n const radiusStyle = customRadius ? { borderRadius: FORM_RADIUS_VAR } : {};\n const radiusClass = customRadius ? \"rounded-none\" : \"\";\n\n return {\n // `bg-inherit` keeps the form root's background flowing down to the\n // inputs and floating labels, which resolve theirs with `inherit`.\n wrapperClass: isStacked\n ? \"flex w-full flex-col bg-inherit\"\n : \"group relative flex w-full flex-col pt-3 bg-inherit\",\n inputClass: isStacked\n ? twMerge(\"block w-full\", variant.inputClass, radiusClass)\n : twMerge(\n \"peer m-0 mb-3 block min-h-8 w-full overflow-hidden\",\n variant.inputClass,\n radiusClass,\n ),\n inputStyle: { ...variant.inputStyle, ...radiusStyle },\n inputFocusStyle: getFocusStyle(style),\n labelClass: variant.labelClass,\n labelStyle: { color: FORM_VAR.labelText },\n errorStyle: { color: FORM_VAR.error },\n accentColor: FORM_VAR.inputFocusBorder,\n isStacked,\n };\n}\n\n/**\n * Inline-style outline applied to the input wrapper when validation has\n * flagged the field. Border / outline color tracks the `--form-error`\n * variable so a single picker change covers every variant at once.\n */\nexport function getErrorOutlineStyle(\n hasError: boolean,\n style: FormStyle,\n): React.CSSProperties {\n if (!hasError) return {};\n\n const variant = style.inputVariant;\n\n if (variant === \"stacked\") {\n return {\n outline: `2px solid ${FORM_VAR.error}`,\n outlineOffset: \"-2px\",\n };\n }\n if (variant === \"outlined\") {\n return {\n outline: `1px solid ${FORM_VAR.error}`,\n outlineOffset: \"-1px\",\n borderColor: FORM_VAR.error,\n };\n }\n // filled / underlined: same variant-appropriate substitute as the focus\n // state — no ring, just the bottom border recoloring (and, if the form\n // opted in, thickening) so a still-thin border doesn't read as unstyled.\n return {\n borderBottomColor: FORM_VAR.error,\n ...(resolveCustomFocusBorderWidth(style)\n ? { borderBottomWidth: FORM_FOCUS_BORDER_WIDTH_VAR }\n : {}),\n };\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface StyledInputProps {\n id: string;\n label: string;\n placeholder?: string;\n type?: string;\n value: string;\n error?: string;\n touched?: boolean;\n disabled?: boolean;\n onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;\n onBlur: (e: React.FocusEvent<HTMLInputElement>) => void;\n}\n\nexport const StyledInput = ({\n id,\n label,\n placeholder,\n type = \"text\",\n value,\n error,\n touched,\n disabled,\n onChange,\n onBlur,\n}: StyledInputProps) => {\n const [focused, setFocused] = useState(false);\n const style = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(error && touched);\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, style),\n };\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={id} className={styles.labelClass} style={styles.labelStyle}>\n {label}\n </label>\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={id}\n name={id}\n type={type}\n placeholder={placeholder}\n value={value}\n disabled={disabled}\n onChange={onChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n onBlur(e);\n }}\n />\n {hasError && (\n <span\n className=\"mt-1 text-xs\"\n style={styles.errorStyle}\n >\n {error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={id} className=\"relative inline-block bg-inherit\">\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={id}\n name={id}\n type={type}\n placeholder={placeholder || label}\n value={value}\n disabled={disabled}\n onChange={onChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {label}\n </span>\n </label>\n {hasError && (\n <span className=\"relative mt-[-8px] text-xs\" style={styles.errorStyle}>\n {error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const TextField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n e.target.value = applyTextTransform(e.target.value, fieldDef.transform);\n field.onChange(e);\n };\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder}\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={handleChange}\n onBlur={field.onBlur}\n />\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const EmailField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder}\n type=\"email\"\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={field.onChange}\n onBlur={field.onBlur}\n />\n );\n};\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { formatUsPhone } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const PhoneField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle),\n };\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n helpers.setValue(formatUsPhone(e.target.value));\n };\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <label\n htmlFor={fieldDef.id}\n className={styles.labelClass}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </label>\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n type=\"tel\"\n placeholder={fieldDef.placeholder}\n value={field.value ?? \"\"}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n {hasError && (\n <span\n className=\"mt-1 text-xs\"\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <input\n className={styles.inputClass}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n type=\"tel\"\n placeholder={fieldDef.placeholder || fieldDef.label}\n value={field.value ?? \"\"}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n {hasError && (\n <span className=\"relative mt-[-8px] text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const UrlField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder || \"https://example.com\"}\n type=\"url\"\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={field.onChange}\n onBlur={field.onBlur}\n />\n );\n};\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const AddressField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n\n const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n e.target.value = applyTextTransform(e.target.value, fieldDef.transform);\n field.onChange(e);\n };\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle),\n };\n\n const placeholder =\n fieldDef.placeholder || \"123 Main St, City, State 12345\";\n\n return (\n <div className={`${styles.wrapperClass} pb-5 lg:pb-0`}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <textarea\n className={`${styles.inputClass} min-h-[4ch] resize-y`}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n autoComplete=\"street-address\"\n placeholder={placeholder}\n rows={fieldDef.rows ?? 2}\n value={field.value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n {hasError && (\n <span className=\"text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport {\n FORM_MUTED_TEXT_CLASS,\n} from \"../cssVars\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const TextAreaField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n\n const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n e.target.value = applyTextTransform(e.target.value, fieldDef.transform);\n field.onChange(e);\n };\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n const value = (field.value ?? \"\") as string;\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle),\n };\n\n if (styles.isStacked) {\n return (\n <div className={twMerge(styles.wrapperClass, \"relative\")}>\n <label\n htmlFor={fieldDef.id}\n className={styles.labelClass}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </label>\n <textarea\n className={twMerge(styles.inputClass, \"resize-y\")}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n placeholder={fieldDef.placeholder}\n rows={fieldDef.rows}\n value={value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n {fieldDef.characterCounter && (\n <span\n className={twMerge(\n \"mt-1 text-right text-xs\",\n FORM_MUTED_TEXT_CLASS,\n )}\n >\n {value.length}\n </span>\n )}\n {hasError && (\n <span\n className=\"mt-1 text-xs\"\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={twMerge(styles.wrapperClass, \"pb-5 lg:pb-0\")}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <textarea\n className={twMerge(styles.inputClass, \"min-h-[5ch] resize-y\")}\n style={borderStyle}\n id={fieldDef.id}\n name={fieldDef.id}\n placeholder={fieldDef.placeholder || fieldDef.label}\n rows={fieldDef.rows}\n value={value}\n disabled={disabled}\n onChange={handleChange}\n onFocus={() => setFocused(true)}\n onBlur={(e) => {\n setFocused(false);\n field.onBlur(e);\n }}\n />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n {fieldDef.characterCounter && (\n <span className=\"absolute bottom-1.5 right-2 rounded-md text-sm\">\n {value.length}\n </span>\n )}\n {hasError && (\n <span className=\"text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useState, useEffect } from \"react\";\nimport { useField } from \"formik\";\nimport { Select } from \"radix-ui\";\nimport { BsChevronDown, BsCheck } from \"react-icons/bs\";\nimport type { FormFieldDefinition, FormStyleColorKey } from \"../../types\";\nimport { useFormColorScheme, useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\nimport {\n FORM_CSS_VAR,\n FORM_DARK_SCOPE_ATTR,\n FORM_VAR,\n buildColorVars,\n} from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\n/** The color slots the portaled popover has to carry for itself. */\nconst POPOVER_COLOR_KEYS: readonly FormStyleColorKey[] = [\n \"inputBgColor\",\n \"inputBorderColor\",\n \"inputTextColor\",\n \"inputFocusColor\",\n];\n\nexport const SelectField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n const formStyle = useFormStyle();\n const { darkEnabled } = useFormColorScheme();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n // Radix portals the popover to <body>, outside the form root, so the\n // root's custom properties don't cascade here. Re-publish the slots the\n // popover needs on the content element itself and read them the way every\n // in-tree field does. A form with a dark palette also publishes their\n // `-dark` counterparts plus the scope attribute, so the form's dark\n // stylesheet swaps them here exactly as it does on the root.\n const popoverVars = {\n ...buildColorVars(formStyle, \"light\", POPOVER_COLOR_KEYS),\n ...(darkEnabled\n ? buildColorVars(formStyle, \"dark\", POPOVER_COLOR_KEYS)\n : {}),\n } as React.CSSProperties;\n const popoverScopeAttr = darkEnabled ? { [FORM_DARK_SCOPE_ATTR]: \"\" } : {};\n\n const [currentValue, setCurrentValue] = useState<string>(field.value || \"\");\n useEffect(() => {\n setCurrentValue(field.value || \"\");\n }, [field.value]);\n\n // Radix Select.Item throws on an empty-string value (it's reserved for\n // \"no selection\") — drop such options instead of crashing the form.\n const options = (fieldDef.options || []).filter((opt) => opt.value !== \"\");\n const displayName =\n options.find((opt) => opt.value === currentValue)?.label || \"\";\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle),\n };\n\n return (\n <div className={styles.wrapperClass}>\n <Select.Root\n disabled={disabled}\n onValueChange={(value) => {\n helpers.setValue(value);\n setCurrentValue(value);\n }}\n value={currentValue}\n >\n <label\n htmlFor={fieldDef.id}\n className=\"relative block bg-inherit\"\n >\n <Select.Trigger\n className={`${styles.inputClass} relative cursor-pointer text-left`}\n style={borderStyle}\n aria-label={fieldDef.label}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n setFocused(false);\n // Mark touched so a required-error can render after the user\n // tabs past without choosing.\n helpers.setTouched(true);\n }}\n >\n <Select.Value placeholder=\"Choose an option\">\n <span className=\"block truncate\">{displayName}</span>\n </Select.Value>\n <Select.Icon className=\"absolute right-3 top-1/2 -translate-y-1/2\">\n <BsChevronDown style={{ color: FORM_VAR.placeholder }} />\n </Select.Icon>\n </Select.Trigger>\n {/* Sibling of Select.Trigger, not a child — Trigger carries the\n shared inputClass's overflow-hidden, which would clip the\n floating label the moment it translates above the border.\n Every other field type avoids this for free because their\n label is already a sibling of a childless <input>. */}\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n </label>\n <Select.Portal>\n <Select.Content\n className=\"z-20 rounded-md border p-3 shadow-lg\"\n style={{\n ...popoverVars,\n backgroundColor: `var(${FORM_CSS_VAR.inputBg}, #ffffff)`,\n borderColor: `var(${FORM_CSS_VAR.inputBorder}, #e5e7eb)`,\n color: `var(${FORM_CSS_VAR.inputText}, #1f2937)`,\n }}\n {...popoverScopeAttr}\n >\n <Select.ScrollUpButton>\n <BsChevronDown className=\"rotate-180\" />\n </Select.ScrollUpButton>\n <Select.Viewport>\n <Select.Group>\n {options.map((opt) => (\n <Select.Item\n key={opt.value}\n className=\"relative m-1 flex cursor-pointer select-none justify-between rounded p-1 pr-8 hover:ring-1 focus:ring-1\"\n style={{\n \"--tw-ring-color\": `var(${FORM_CSS_VAR.inputFocusBorder}, #2563eb)`,\n } as React.CSSProperties}\n value={opt.value}\n >\n <Select.ItemText>{opt.label}</Select.ItemText>\n <Select.ItemIndicator>\n <BsCheck className=\"absolute bottom-0 right-3 top-0 my-auto\" />\n </Select.ItemIndicator>\n </Select.Item>\n ))}\n </Select.Group>\n </Select.Viewport>\n <Select.ScrollDownButton>\n <BsChevronDown />\n </Select.ScrollDownButton>\n </Select.Content>\n </Select.Portal>\n </Select.Root>\n {hasError && (\n <span className=\"text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport { Checkbox } from \"radix-ui\";\nimport { BsCheck } from \"react-icons/bs\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { FORM_RADIUS_VAR, FORM_VAR, resolveCustomRadius } from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n}\n\nexport const CheckboxField = ({ field: fieldDef }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const formStyle = useFormStyle();\n const isChecked = field.value === true;\n const isStacked = formStyle.inputVariant === \"stacked\";\n\n // The box is square, so it takes the form's corner like every other\n // control. Radio indicators deliberately don't — a circle is a circle.\n const radiusStyle = resolveCustomRadius(formStyle)\n ? { borderRadius: FORM_RADIUS_VAR }\n : {};\n\n const checkboxStyle: React.CSSProperties = isChecked\n ? {\n ...radiusStyle,\n borderColor: FORM_VAR.inputFocusBorder,\n backgroundColor: FORM_VAR.inputFocusBorder,\n }\n : {\n ...radiusStyle,\n borderColor: FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n };\n\n return (\n <div\n className={twMerge(\n \"bg-inherit\",\n isStacked ? \"flex items-start gap-3\" : \"flex items-center gap-3 pt-3\"\n )}\n >\n <Checkbox.Root\n id={fieldDef.id}\n checked={isChecked}\n onCheckedChange={(checked) => {\n helpers.setValue(checked === true);\n helpers.setTouched(true, false);\n }}\n // `shrink-0`: a long label must wrap, never squash the box — flex\n // otherwise shares the row's width with the label and the checkbox\n // renders narrower the longer its text gets.\n className={twMerge(\n \"flex h-5 w-5 shrink-0 items-center justify-center rounded border\",\n isStacked && \"mt-0.5\"\n )}\n style={checkboxStyle}\n >\n <Checkbox.Indicator>\n <BsCheck className=\"text-white\" />\n </Checkbox.Indicator>\n </Checkbox.Root>\n <label\n htmlFor={fieldDef.id}\n className=\"min-w-0 cursor-pointer text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {fieldDef.label}\n </label>\n {meta.touched && meta.error && (\n <span className=\"text-sm\" style={{ color: FORM_VAR.error }}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport { RadioGroup } from \"radix-ui\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { FORM_VAR } from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const RadioField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n\n return (\n <div className=\"bg-inherit pt-3\">\n <span\n className=\"mb-2 block text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {fieldDef.label}\n </span>\n <RadioGroup.Root\n value={field.value}\n disabled={disabled}\n onValueChange={(value) => {\n helpers.setValue(value);\n helpers.setTouched(true, false);\n }}\n className=\"flex flex-col gap-2 bg-inherit\"\n >\n {(fieldDef.options || []).map((opt) => {\n const isSelected = field.value === opt.value;\n return (\n <div key={opt.value} className=\"flex items-center gap-2 bg-inherit\">\n <RadioGroup.Item\n value={opt.value}\n id={`${fieldDef.id}-${opt.value}`}\n className=\"flex h-5 w-5 items-center justify-center rounded-full border\"\n style={{\n borderColor: isSelected\n ? FORM_VAR.inputFocusBorder\n : FORM_VAR.inputBorder,\n backgroundColor: FORM_VAR.inputBg,\n }}\n >\n <RadioGroup.Indicator\n className=\"h-2.5 w-2.5 rounded-full\"\n style={{ backgroundColor: FORM_VAR.inputFocusBorder }}\n />\n </RadioGroup.Item>\n <label\n htmlFor={`${fieldDef.id}-${opt.value}`}\n className=\"cursor-pointer text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {opt.label}\n </label>\n </div>\n );\n })}\n </RadioGroup.Root>\n {meta.touched && meta.error && (\n <span className=\"mt-1 block text-sm\" style={{ color: FORM_VAR.error }}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { StyledInput } from \"./StyledInput\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\nexport const NumberField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta] = useField(fieldDef.id);\n\n return (\n <StyledInput\n id={fieldDef.id}\n label={fieldDef.label}\n placeholder={fieldDef.placeholder}\n type=\"number\"\n value={field.value}\n error={meta.error}\n touched={meta.touched}\n disabled={disabled}\n onChange={field.onChange}\n onBlur={field.onBlur}\n />\n );\n};\n","import { addDays, format, isSameDay, isWeekend, parse, set } from \"date-fns\";\nimport type { DatetimeConfig, ExcludedTimeRange } from \"../../types\";\n\n/**\n * The first non-weekend day strictly after `from` — on a Friday or Saturday\n * that's the following Monday.\n */\nexport function nextBusinessDay(from: Date): Date {\n let d = addDays(from, 1);\n while (isWeekend(d)) d = addDays(d, 1);\n return d;\n}\n\n/** Parse \"HH:mm\" onto `onDay`, or return null when it isn't a valid time. */\nfunction timeOnDay(value: string, onDay: Date): Date | null {\n const parsed = parse(value, \"HH:mm\", onDay);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n}\n\n/** Minutes since midnight for a Date, for comparing against \"HH:mm\". */\nfunction minutesOfDay(d: Date): number {\n return d.getHours() * 60 + d.getMinutes();\n}\n\n/** Minutes since midnight for an \"HH:mm\" string, or null if unparseable. */\nfunction minutesOfString(value: string): number | null {\n const m = /^(\\d{2}):(\\d{2})$/.exec(value);\n if (!m) return null;\n const mins = Number(m[1]) * 60 + Number(m[2]);\n return Number.isFinite(mins) ? mins : null;\n}\n\n/**\n * The booking window's bounds on `day`, as Dates. Defaults to the whole day\n * when the field configures no window.\n */\nfunction windowOnDay(\n config: DatetimeConfig | undefined,\n day: Date,\n): { min: Date; max: Date } | null {\n const base = set(day, { seconds: 0, milliseconds: 0 });\n const min = config?.minTime\n ? timeOnDay(config.minTime, base)\n : set(base, { hours: 0, minutes: 0 });\n const max = config?.maxTime\n ? timeOnDay(config.maxTime, base)\n : set(base, { hours: 23, minutes: 59 });\n if (!min || !max || max < min) return null;\n return { min, max };\n}\n\n/**\n * The last time slot a visitor could still pick on `day`, given the field's\n * booking window and interval.\n *\n * react-datepicker generates slots from `minTime` in `timeIntervals` steps\n * and stops at `maxTime`, so the final slot is not always `maxTime` itself:\n * a 9:15–17:00 window on a 30-minute interval ends at 16:45, not 17:00.\n *\n * @param config - The field's datetime config.\n * @param day - The day to place the window on.\n * @returns The last selectable instant that day, or null if unknowable.\n */\nexport function lastSlotOnDay(\n config: DatetimeConfig | undefined,\n day: Date,\n): Date | null {\n const bounds = windowOnDay(config, day);\n if (!bounds) return null;\n const intervalMs = Math.max(1, config?.timeIntervals ?? 30) * 60_000;\n const steps = Math.floor(\n (bounds.max.getTime() - bounds.min.getTime()) / intervalMs,\n );\n return new Date(bounds.min.getTime() + steps * intervalMs);\n}\n\n/** The excluded ranges that apply to `day`, if any. */\nfunction rangesOnDay(\n config: DatetimeConfig | undefined,\n day: Date,\n): ExcludedTimeRange[] {\n const ranges = config?.excludeTimeRanges;\n if (!ranges || ranges.length === 0) return [];\n const key = format(day, \"yyyy-MM-dd\");\n return ranges.filter((r) => r && r.date === key);\n}\n\n/**\n * Whether `slot` falls inside a closed window on its own day.\n *\n * `from` is inclusive and `to` exclusive, so a 12:00–18:00 closure blocks\n * the noon slot and leaves an 18:00 one bookable — what \"closed from noon\"\n * is normally taken to mean.\n *\n * @param config - The field's datetime config.\n * @param slot - The candidate slot, carrying its own date.\n * @returns True when the slot is inside a closed window.\n */\nexport function isTimeExcluded(\n config: DatetimeConfig | undefined,\n slot: Date,\n): boolean {\n const ranges = rangesOnDay(config, slot);\n if (ranges.length === 0) return false;\n const at = minutesOfDay(slot);\n return ranges.some((r) => {\n const from = minutesOfString(r.from);\n const to = minutesOfString(r.to);\n if (from === null || to === null || to <= from) return false;\n return at >= from && at < to;\n });\n}\n\n/** Options the renderer resolves before the config alone can be trusted. */\nexport interface DateFilterOptions {\n /**\n * Whether the field actually offers a time. A `date` field renders the\n * shared picker in date-only mode, where time-of-day exclusions must not\n * apply — the visitor is choosing a day, not a slot.\n */\n showTimeSelect?: boolean;\n /** Whether past time slots are filtered out (the picker's default). */\n filterPastTimes?: boolean;\n}\n\n/**\n * Whether any slot on `day` can still be chosen.\n *\n * This is the general form of two rules that would otherwise be written\n * separately: a day whose slots have all gone by, and a day whose slots are\n * all inside a closed window. Either way the visitor must not be able to\n * select the day and be met with a time column where nothing is available.\n *\n * @param config - The field's datetime config.\n * @param day - The day to test.\n * @param options - Renderer-resolved flags; see {@link DateFilterOptions}.\n * @param now - The current instant, injected so callers can evaluate it at\n * click time rather than render time.\n * @returns True when at least one slot survives.\n */\nexport function hasSelectableSlot(\n config: DatetimeConfig | undefined,\n day: Date,\n options: DateFilterOptions = {},\n now: Date = new Date(),\n): boolean {\n const bounds = windowOnDay(config, day);\n if (!bounds) return true; // Misconfigured window — don't hide the day.\n const filterPast = options.filterPastTimes ?? config?.filterPastTimes ?? true;\n const intervalMs = Math.max(1, config?.timeIntervals ?? 30) * 60_000;\n const last = lastSlotOnDay(config, day);\n if (!last) return true;\n\n for (let t = bounds.min.getTime(); t <= last.getTime(); t += intervalMs) {\n const slot = new Date(t);\n if (filterPast && slot.getTime() < now.getTime()) continue;\n if (isTimeExcluded(config, slot)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Whether a whole day is closed by the day-level rules: weekends, today,\n * tomorrow, next business day, or a named closed date.\n *\n * Deliberately excludes the \"has any slot left\" test, which belongs to\n * {@link buildDateFilter} alone — asking it here, from inside a per-slot\n * predicate, would be both circular in spirit and quadratic in cost.\n *\n * @param config - The field's datetime config.\n * @param date - The day to test.\n * @param now - The current instant, for the relative rules.\n * @returns True when the day is closed outright.\n */\nexport function isDayExcluded(\n config: DatetimeConfig | undefined,\n date: Date,\n now: Date = new Date(),\n): boolean {\n if ((config?.excludeWeekends ?? false) && isWeekend(date)) return true;\n if ((config?.excludeToday ?? false) && isSameDay(date, now)) return true;\n if ((config?.excludeTomorrow ?? false) && isSameDay(date, addDays(now, 1))) {\n return true;\n }\n if (\n (config?.excludeNextBusinessDay ?? false) &&\n isSameDay(date, nextBusinessDay(now))\n ) {\n return true;\n }\n const named = config?.excludeDates;\n if (named && named.length > 0) {\n const key = format(date, \"yyyy-MM-dd\");\n if (named.some((d) => d === key)) return true;\n }\n return false;\n}\n\n/**\n * Build the `filterTime` predicate for react-datepicker: drops slots that\n * have already passed, slots inside a closed window, and every slot on a\n * day that is closed outright.\n *\n * That last one is not redundant with `filterDate`. react-datepicker builds\n * a selection from its *pre-selected* date plus the clicked time, and that\n * pre-selection is today whether or not `filterDate` allows today — so\n * clicking a time without first picking a date would otherwise commit a\n * closed day, straight past the date filter. Guarding the times is what\n * makes the closure real rather than decorative.\n *\n * @param config - The field's datetime config.\n * @param options - Renderer-resolved flags; see {@link DateFilterOptions}.\n * @returns A `filterTime` predicate, or undefined when nothing is filtered.\n */\nexport function buildTimeFilter(\n config: DatetimeConfig | undefined,\n options: DateFilterOptions = {},\n): ((time: Date) => boolean) | undefined {\n if (!(options.showTimeSelect ?? config?.showTimeSelect ?? true)) return undefined;\n const filterPast = options.filterPastTimes ?? config?.filterPastTimes ?? true;\n const hasRanges = (config?.excludeTimeRanges?.length ?? 0) > 0;\n const hasDayRules =\n (config?.excludeWeekends ?? false) ||\n (config?.excludeToday ?? false) ||\n (config?.excludeTomorrow ?? false) ||\n (config?.excludeNextBusinessDay ?? false) ||\n (config?.excludeDates?.length ?? 0) > 0;\n if (!filterPast && !hasRanges && !hasDayRules) return undefined;\n\n return (time: Date) => {\n const now = new Date();\n if (filterPast && time.getTime() < now.getTime()) return false;\n if (hasDayRules && isDayExcluded(config, time, now)) return false;\n if (hasRanges && isTimeExcluded(config, time)) return false;\n return true;\n };\n}\n\n/**\n * The first day at or after `from` that the picker will actually accept.\n *\n * Used to open the calendar somewhere usable. Without it the panel opens on\n * today even when today is closed, presenting a month whose time column is\n * entirely disabled and leaving the visitor to work out that they must page\n * forward.\n *\n * @param config - The field's datetime config.\n * @param options - Renderer-resolved flags; see {@link DateFilterOptions}.\n * @param from - Where to start looking. Defaults to today.\n * @param limit - How many days to scan before giving up.\n * @returns The first selectable day, or null if none within `limit`.\n */\nexport function firstSelectableDay(\n config: DatetimeConfig | undefined,\n options: DateFilterOptions = {},\n from: Date = new Date(),\n limit = 370,\n): Date | null {\n const filter = buildDateFilter(config, options);\n let day = new Date(from.getFullYear(), from.getMonth(), from.getDate());\n for (let i = 0; i < limit; i += 1) {\n if (!filter || filter(day)) return day;\n day = addDays(day, 1);\n }\n return null;\n}\n\n/**\n * Build the `filterDate` predicate for react-datepicker from a field's\n * datetime config, combining every day-level exclusion: weekends, today,\n * tomorrow, next business day, named calendar dates, and — on a field that\n * offers times — any day left with no selectable slot, whether because they\n * have all passed or because they are all inside a closed window. Returns\n * `undefined` when nothing is excluded so the picker prop can be omitted\n * entirely.\n *\n * \"Now\" is evaluated at click time rather than render time, so a form left\n * open across the last slot (or across midnight) stays correct without a\n * re-render. Named dates in `excludeDates` are matched on the viewer's local\n * calendar day, so a \"yyyy-MM-dd\" closure blocks that date in every timezone\n * rather than sliding by one.\n *\n * These exclusions are picker-level UX, not schema validation — consistent\n * with how excludeWeekends/excludePastDates already behave.\n *\n * @param config - The field's datetime config.\n * @param options - Renderer-resolved flags; see {@link DateFilterOptions}.\n * @returns A `filterDate` predicate, or undefined when nothing is excluded.\n */\nexport function buildDateFilter(\n config: DatetimeConfig | undefined,\n options: DateFilterOptions = {},\n): ((date: Date) => boolean) | undefined {\n const excludeWeekends = config?.excludeWeekends ?? false;\n const excludeToday = config?.excludeToday ?? false;\n const excludeTomorrow = config?.excludeTomorrow ?? false;\n const excludeNext = config?.excludeNextBusinessDay ?? false;\n // A Set keeps the predicate O(1) per day — the picker calls it for every\n // cell of every month the visitor pages through.\n const excludedDays = new Set(\n (config?.excludeDates ?? []).filter(\n (d): d is string => typeof d === \"string\" && d.length === 10,\n ),\n );\n\n const timeSelect = options.showTimeSelect ?? config?.showTimeSelect ?? true;\n const filterPast = options.filterPastTimes ?? config?.filterPastTimes ?? true;\n const hasRanges = (config?.excludeTimeRanges?.length ?? 0) > 0;\n // Only worth walking a day's slots when something could empty it.\n const checkSlots = timeSelect && (filterPast || hasRanges);\n\n if (\n !excludeWeekends &&\n !excludeToday &&\n !excludeTomorrow &&\n !excludeNext &&\n !checkSlots &&\n excludedDays.size === 0\n ) {\n return undefined;\n }\n\n return (date: Date) => {\n const now = new Date();\n if (excludeWeekends && isWeekend(date)) return false;\n if (excludeToday && isSameDay(date, now)) return false;\n if (excludeTomorrow && isSameDay(date, addDays(now, 1))) return false;\n if (excludeNext && isSameDay(date, nextBusinessDay(now))) return false;\n if (excludedDays.size > 0 && excludedDays.has(format(date, \"yyyy-MM-dd\"))) {\n return false;\n }\n // Walking the slots is the expensive branch, so only take it for days\n // that could actually be emptied: today (past slots) or a day carrying\n // closed windows.\n if (checkSlots) {\n const needsCheck =\n (filterPast && isSameDay(date, now)) ||\n (hasRanges && rangesOnDay(config, date).length > 0);\n if (needsCheck && !hasSelectableSlot(config, date, options, now)) {\n return false;\n }\n }\n return true;\n };\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport { useField } from \"formik\";\nimport DatePicker from \"react-datepicker\";\nimport { format, isValid, parse, set } from \"date-fns\";\nimport { twMerge } from \"tailwind-merge\";\nimport \"react-datepicker/dist/react-datepicker.css\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\nimport {\n buildDateFilter,\n buildTimeFilter,\n firstSelectableDay,\n} from \"./dateExclusions\";\n\ninterface Props {\n field: FormFieldDefinition;\n /**\n * Date-only mode (used by the `date` field type): hides the time selector\n * and stores the value as \"yyyy-MM-dd\" instead of a full ISO timestamp,\n * matching what the native date input previously produced.\n */\n dateOnly?: boolean;\n disabled?: boolean;\n}\n\nfunction parseTimeString(value: string | undefined, fallbackHours: number, fallbackMinutes: number): Date {\n if (!value) {\n return set(new Date(), { hours: fallbackHours, minutes: fallbackMinutes, seconds: 0, milliseconds: 0 });\n }\n try {\n return parse(value, \"HH:mm\", new Date());\n } catch {\n return set(new Date(), { hours: fallbackHours, minutes: fallbackMinutes, seconds: 0, milliseconds: 0 });\n }\n}\n\n/**\n * Parse a stored field value into a Date. Plain dates (\"2026-06-10\") are\n * parsed at LOCAL midnight — `new Date(\"2026-06-10\")` would read it as UTC\n * and show the previous day in negative-offset timezones.\n */\nfunction parseStoredValue(value: string): Date | null {\n if (!value) return null;\n const d = /^\\d{4}-\\d{2}-\\d{2}$/.test(value)\n ? parse(value, \"yyyy-MM-dd\", new Date())\n : new Date(value);\n return isValid(d) ? d : null;\n}\n\nexport const DateTimeField = ({\n field: fieldDef,\n dateOnly = false,\n disabled,\n}: Props) => {\n const [field, meta, helpers] = useField(fieldDef.id);\n const [focused, setFocused] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const hasError = !!(meta.error && meta.touched);\n\n const config = fieldDef.datetimeConfig ?? {};\n const showTimeSelect = dateOnly ? false : (config.showTimeSelect ?? true);\n const timeIntervals = config.timeIntervals ?? 30;\n const excludePastDates = config.excludePastDates ?? true;\n const filterPastTimes = config.filterPastTimes ?? true;\n const dateFormat = config.dateFormat ?? (showTimeSelect ? \"MMMM d, yyyy h:mm aa\" : \"MMMM d, yyyy\");\n const placeholderText =\n config.placeholderText ??\n fieldDef.placeholder ??\n (dateOnly ? \"Select date\" : \"Select date and time\");\n\n const minTime = showTimeSelect ? parseTimeString(config.minTime, 0, 0) : undefined;\n const maxTime = showTimeSelect ? parseTimeString(config.maxTime, 23, 59) : undefined;\n const minDate = excludePastDates ? new Date() : undefined;\n\n const selected = parseStoredValue(field.value);\n\n // Combined day-level exclusions: weekends / today / tomorrow / next\n // business day / named closures, plus today once its last bookable slot\n // has passed. Undefined when nothing is excluded.\n const filterDate = buildDateFilter(config, {\n showTimeSelect,\n filterPastTimes,\n });\n\n // Drops slots that have passed and slots inside a closed window (an\n // afternoon off, an early close). Undefined when neither applies.\n const filterTime = buildTimeFilter(config, {\n showTimeSelect,\n filterPastTimes,\n });\n\n // Open on the first day the picker will actually accept. react-datepicker\n // otherwise opens on today even when today is closed, which shows a month\n // whose entire time column is disabled and leaves the visitor to work out\n // that they need to page forward.\n const openToDate =\n selected || !filterDate\n ? undefined\n : (firstSelectableDay(config, { showTimeSelect, filterPastTimes }) ??\n undefined);\n\n const handleChange = (date: Date | null) => {\n if (!date) {\n helpers.setValue(\"\");\n return;\n }\n helpers.setValue(dateOnly ? format(date, \"yyyy-MM-dd\") : date.toISOString());\n };\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle),\n };\n\n const pickerProps = {\n id: fieldDef.id,\n name: fieldDef.id,\n wrapperClassName: \"block w-full\",\n // react-datepicker's stylesheet pins the popper at z-index 1, below the\n // z-10 floating labels in useInputStyles — neighboring fields' labels\n // would paint over the open calendar.\n popperClassName: \"!z-50\",\n disabled,\n selected,\n onChange: handleChange,\n onFocus: () => setFocused(true),\n onBlur: () => {\n setFocused(false);\n helpers.setTouched(true);\n },\n showTimeSelect,\n timeIntervals,\n minDate,\n ...(openToDate ? { openToDate } : {}),\n minTime,\n maxTime,\n filterDate,\n filterTime,\n dateFormat,\n placeholderText,\n autoComplete: \"off\",\n };\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <label\n htmlFor={fieldDef.id}\n className={styles.labelClass}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </label>\n <DatePicker\n {...pickerProps}\n customInput={\n <input\n className={twMerge(styles.inputClass, \"cursor-pointer\")}\n style={borderStyle}\n />\n }\n />\n {hasError && (\n <span\n className=\"mt-1 text-xs\"\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n <label htmlFor={fieldDef.id} className=\"relative inline-block bg-inherit\">\n <DatePicker\n {...pickerProps}\n className={styles.inputClass}\n customInput={\n <input\n className={styles.inputClass}\n style={borderStyle}\n />\n }\n />\n <span\n className={twMerge(\n styles.labelClass,\n // react-datepicker nests the real input inside wrapper divs, so\n // the `peer-placeholder-shown` rest rule from labelClass never\n // matches (the peer must be a direct sibling). Recreate the\n // resting position from tracked state instead.\n !focused && !field.value && \"translate-y-0\",\n )}\n style={styles.labelStyle}\n >\n {fieldDef.label}\n </span>\n </label>\n {hasError && (\n <span className=\"relative mt-[-8px] text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport type { FormFieldDefinition } from \"../../types\";\nimport { DateTimeField } from \"./DateTimeField\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\n/**\n * Date-only picker — the DateTimeField in `dateOnly` mode.\n *\n * Previously this was a native <input type=\"date\">, which silently ignored\n * every `datetimeConfig` option the builder offers for date fields\n * (exclude weekends / past dates / today / tomorrow / next business day).\n * The shared picker honors them all; the stored value stays \"yyyy-MM-dd\"\n * so existing submissions and integrations are unaffected.\n */\nexport const DateField = ({ field, disabled }: Props) => {\n return <DateTimeField field={field} dateOnly disabled={disabled} />;\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport type { FormFieldDefinition } from \"../../types\";\n\ninterface Props {\n field: FormFieldDefinition;\n /** Accepted for renderer prop-compat; a hidden input has nothing to disable. */\n disabled?: boolean;\n}\n\nexport const HiddenField = ({ field: fieldDef }: Props) => {\n const [field] = useField(fieldDef.id);\n\n return <input type=\"hidden\" name={fieldDef.id} value={field.value} />;\n};\n","\"use client\";\n\nimport { useField } from \"formik\";\nimport { useState } from \"react\";\nimport { FiEye, FiEyeOff } from \"react-icons/fi\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../../types\";\nimport { applyTextTransform } from \"../../utils/textTransforms\";\nimport { useFormStyle } from \"../FormStyleContext\";\nimport {\n FORM_MUTED_TEXT_CLASS,\n FORM_SUBTLE_HOVER_FILL_CLASS,\n} from \"../cssVars\";\nimport { useInputStyles, getErrorOutlineStyle } from \"./useInputStyles\";\n\ninterface Props {\n field: FormFieldDefinition;\n disabled?: boolean;\n}\n\n/**\n * Renders a sensitive field as a password-style input. The plaintext value\n * lives in Formik state for the lifetime of the form; on submit, the\n * `DynamicForm` submission handler walks the form definition, encrypts each\n * sensitive field with the transport public key, and only ciphertext is\n * sent to the API. The plaintext never touches the network in cleartext.\n *\n * Visual treatment: an \"Encrypted before submission\" hint with a lock glyph\n * and an eye-icon reveal toggle. When hidden (default), the browser's native\n * password masking applies.\n */\nexport const SensitiveField = ({ field: fieldDef, disabled }: Props) => {\n const [field, meta, helpers] = useField<string>(fieldDef.id);\n const [reveal, setReveal] = useState(false);\n const formStyle = useFormStyle();\n const styles = useInputStyles();\n const [focused, setFocused] = useState(false);\n const hasError = !!(meta.error && meta.touched);\n const isSsn =\n fieldDef.sensitiveConfig?.inputMask === \"ssn\" ||\n fieldDef.transform === \"ssn\";\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n // The ssn input mask wins over any other configured transform; both\n // routes go through the shared formatter.\n const next = applyTextTransform(\n e.target.value,\n isSsn ? \"ssn\" : fieldDef.transform\n );\n helpers.setValue(next);\n };\n\n const borderStyle: React.CSSProperties = {\n ...styles.inputStyle,\n ...(focused ? styles.inputFocusStyle : {}),\n ...getErrorOutlineStyle(hasError, formStyle),\n paddingRight: \"2.75rem\",\n };\n\n const inputType = reveal ? \"text\" : \"password\";\n // Deliberately no `name`: a browser only serializes named controls, so if\n // the form is ever submitted natively (before hydration, or with JS\n // broken) the plaintext can't ride along. Formik state is keyed by\n // `fieldDef.id` through `useField`, which needs no DOM name.\n const inputProps = {\n id: fieldDef.id,\n type: inputType,\n disabled,\n autoComplete: \"off\",\n inputMode: isSsn ? (\"numeric\" as const) : undefined,\n placeholder: fieldDef.placeholder || (isSsn ? \"•••-••-••••\" : fieldDef.label),\n value: field.value,\n onChange: handleChange,\n onFocus: () => setFocused(true),\n onBlur: () => {\n setFocused(false);\n // Not `field.onBlur(e)`: Formik resolves that from the input's `name`,\n // which this input intentionally lacks.\n helpers.setTouched(true);\n },\n \"aria-describedby\": `${fieldDef.id}-secure`,\n \"data-sensitive\": \"true\" as const,\n };\n\n // The button lives inside an inset-y-0 flex wrapper so it always centers\n // on the wrapper's height. In the floating-label layout the input carries\n // a 12px bottom margin (`mb-3`) inside the relative container, so the\n // wrapper takes a matching `mb-3` to center on the input itself.\n const renderToggle = (wrapperClass?: string) => (\n <span\n className={twMerge(\n \"absolute inset-y-0 right-2 flex items-center\",\n wrapperClass,\n )}\n >\n <button\n type=\"button\"\n onClick={() => setReveal((r) => !r)}\n className={twMerge(\n \"flex h-7 w-7 items-center justify-center rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/60\",\n FORM_MUTED_TEXT_CLASS,\n FORM_SUBTLE_HOVER_FILL_CLASS,\n )}\n aria-pressed={reveal}\n aria-label={reveal ? \"Hide value\" : \"Show value\"}\n >\n {reveal ? (\n <FiEyeOff size={16} aria-hidden=\"true\" />\n ) : (\n <FiEye size={16} aria-hidden=\"true\" />\n )}\n </button>\n </span>\n );\n\n // Rendered beside (stacked) or above (floating) the input so the space\n // below stays reserved for validation errors.\n const renderSecureHint = (className?: string) => (\n <p\n id={`${fieldDef.id}-secure`}\n className={twMerge(\n \"flex items-center gap-1 text-xs\",\n FORM_MUTED_TEXT_CLASS,\n className,\n )}\n >\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 16 16\"\n className=\"h-3 w-3 flex-shrink-0\"\n fill=\"currentColor\"\n >\n <path d=\"M8 1a3 3 0 0 0-3 3v3H4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-1V4a3 3 0 0 0-3-3Zm-2 6V4a2 2 0 1 1 4 0v3H6Z\" />\n </svg>\n Encrypted before submission\n </p>\n );\n\n if (styles.isStacked) {\n return (\n <div className={styles.wrapperClass}>\n <div className=\"flex flex-wrap items-baseline justify-between gap-x-2\">\n <label htmlFor={fieldDef.id} className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </label>\n {renderSecureHint(\"mb-1\")}\n </div>\n <div className=\"relative bg-inherit\">\n <input className={styles.inputClass} style={borderStyle} {...inputProps} />\n {renderToggle()}\n </div>\n {hasError && (\n <span\n className=\"mt-1 text-xs\"\n style={styles.errorStyle}\n >\n {meta.error}\n </span>\n )}\n </div>\n );\n }\n\n return (\n <div className={styles.wrapperClass}>\n {renderSecureHint(\"absolute right-0 top-0 leading-none\")}\n <label htmlFor={fieldDef.id} className=\"relative inline-block w-full bg-inherit\">\n <input className={styles.inputClass} style={borderStyle} {...inputProps} />\n <span className={styles.labelClass} style={styles.labelStyle}>\n {fieldDef.label}\n </span>\n {renderToggle(\"mb-3\")}\n </label>\n {hasError && (\n <span className=\"relative mt-[-8px] text-xs\" style={styles.errorStyle}>\n {meta.error}\n </span>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { FormFileUploadHandler } from \"../types\";\n\n/**\n * The upload path `DynamicForm` publishes to the `file` fields beneath it.\n *\n * Threaded by context rather than by prop because `FileField` sits two\n * levels down (section → field) and no intermediate component has any other\n * reason to know about uploads.\n */\nexport interface FormFileUploadContextValue {\n /**\n * Uploads a picked file and returns its stored URL. Undefined means the\n * consuming app wired no upload path — file fields then render disabled\n * instead of submitting an unusable value.\n */\n upload?: FormFileUploadHandler;\n /**\n * Builder-preview escape hatch: allows `FileField` to stand in a local\n * `URL.createObjectURL` value when no `upload` is set. Only ever true in\n * the CMS form builder, where submissions are short-circuited and the\n * throwaway URL can't reach a lead.\n */\n allowObjectUrlFallback?: boolean;\n}\n\nconst FormFileUploadContext = createContext<FormFileUploadContextValue>({});\n\nexport const useFormFileUpload = () => useContext(FormFileUploadContext);\nexport const FormFileUploadProvider = FormFileUploadContext.Provider;\n","\"use client\";\n\nimport { useField, useFormikContext } from \"formik\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type {\n FormFieldDefinition,\n FileFieldConfig,\n FormFileUploadHandler,\n UploadedFormFile,\n} from \"../../types\";\nimport { DEFAULT_FILE_FIELD_CONFIG } from \"../../types\";\nimport { resizeImageFile } from \"../../utils/resizeImage\";\nimport { useFormFileUpload } from \"../FileUploadContext\";\nimport {\n FORM_FAINT_TEXT_CLASS,\n FORM_MUTED_TEXT_CLASS,\n FORM_SUBTLE_BORDER_CLASS,\n FORM_SUBTLE_FILL_CLASS,\n FORM_VAR,\n} from \"../cssVars\";\n\ninterface Props {\n field: FormFieldDefinition;\n /** Project ID for storage path. Passed from the form renderer. */\n projectId?: string;\n /**\n * Upload handler. Normally supplied through `DynamicForm`'s\n * `onFileUpload` / `fileUploadRoute` prop (delivered by context); pass it\n * here when rendering `FileField` outside a `DynamicForm`. This prop wins\n * over the context value.\n */\n onUpload?: FormFileUploadHandler;\n /** When true (mirrored/locked), the picker is read-only. */\n disabled?: boolean;\n}\n\n/**\n * Shown in place of the picker when no upload path is wired. The field\n * refuses files outright rather than accepting them and submitting a\n * `blob:` URL that dies with the tab — a silently lost attachment on a real\n * lead is worse than a visibly unavailable one.\n */\nconst NO_UPLOADER_MESSAGE =\n \"File uploads aren't configured for this form.\";\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check a file against an `accept` attribute value (comma-separated MIME\n * types, `type/*` wildcards, or `.ext` extensions). The native picker\n * enforces this, but drag-and-drop bypasses it entirely.\n */\nfunction matchesAccept(file: File, accept?: string): boolean {\n if (!accept?.trim()) return true;\n const patterns = accept.split(\",\").map((p) => p.trim()).filter(Boolean);\n return patterns.some((pattern) => {\n if (pattern.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(pattern.toLowerCase());\n }\n if (pattern.endsWith(\"/*\")) {\n return file.type.startsWith(pattern.slice(0, -1));\n }\n return file.type === pattern;\n });\n}\n\nexport const FileField = ({ field: fieldDef, onUpload, disabled }: Props) => {\n const [, meta, helpers] = useField(fieldDef.id);\n const { setFieldTouched } = useFormikContext();\n const { upload: contextUpload, allowObjectUrlFallback } = useFormFileUpload();\n const inputRef = useRef<HTMLInputElement>(null);\n const [uploading, setUploading] = useState(false);\n const [uploadError, setUploadError] = useState<string | null>(null);\n const [files, setFiles] = useState<UploadedFormFile[]>([]);\n\n const uploader = onUpload ?? contextUpload;\n // No uploader and no preview stand-in — the picker can't produce a usable\n // value, so it stays shut.\n const uploadsUnavailable = !uploader && !allowObjectUrlFallback;\n\n useEffect(() => {\n if (!uploadsUnavailable) return;\n console.warn(\n `[forms] Field \"${fieldDef.id}\" is a file field but no upload path is ` +\n \"configured. Pass onFileUpload or fileUploadRoute to <DynamicForm> \" +\n \"(or onUpload to <FileField>) to enable it.\",\n );\n }, [uploadsUnavailable, fieldDef.id]);\n\n const config: FileFieldConfig = {\n ...DEFAULT_FILE_FIELD_CONFIG,\n ...fieldDef.fileConfig,\n };\n\n const maxSizeBytes = config.maxSizeBytes ?? 10 * 1024 * 1024;\n const multiple = config.multiple ?? false;\n const maxFiles = config.maxFiles ?? 5;\n const resizeImages = config.resizeImages ?? true;\n const maxImageWidth = config.maxImageWidth ?? 1600;\n\n const handleFiles = useCallback(\n async (fileList: FileList | null) => {\n if (!fileList || fileList.length === 0) return;\n if (uploadsUnavailable) {\n setUploadError(NO_UPLOADER_MESSAGE);\n return;\n }\n setUploadError(null);\n\n const toUpload = Array.from(fileList);\n\n // Check max files\n if (multiple && files.length + toUpload.length > maxFiles) {\n setUploadError(`Maximum ${maxFiles} files allowed.`);\n return;\n }\n\n // Accumulate locally, then commit files + Formik value together at the\n // end — setValue inside a setState updater is impure (double-fires\n // under StrictMode).\n let current = files;\n\n for (const file of toUpload) {\n // The input's accept attribute only filters the OS picker —\n // drag-and-drop arrives unfiltered.\n if (!matchesAccept(file, config.accept)) {\n setUploadError(`\"${file.name}\" is not an accepted file type.`);\n continue;\n }\n\n setUploading(true);\n\n try {\n // Downscale first, then check the limit against what will actually\n // be uploaded: `maxSizeBytes` is advertised on the picker as the\n // upload cap, and a 4000px photo that fits once resized shouldn't\n // be rejected for its original weight. Non-images, unsupported\n // formats, and any failure come back untouched.\n const prepared = resizeImages\n ? await resizeImageFile(file, maxImageWidth)\n : file;\n\n // Validate size\n if (prepared.size > maxSizeBytes) {\n setUploadError(\n `\"${file.name}\" exceeds ${formatBytes(maxSizeBytes)} limit.`,\n );\n continue;\n }\n\n // The object-URL branch is preview-only and unreachable without\n // `allowObjectUrlFallback` (guarded by `uploadsUnavailable` above),\n // so a real submission can never carry a `blob:` value.\n const result: UploadedFormFile = uploader\n ? await uploader(prepared, config)\n : {\n url: URL.createObjectURL(prepared),\n name: prepared.name,\n size: prepared.size,\n };\n\n current = multiple ? [...current, result] : [result];\n } catch (err) {\n setUploadError(`Upload failed: ${(err as Error).message}`);\n } finally {\n setUploading(false);\n }\n }\n\n if (current !== files) {\n setFiles(current);\n // Single file gets a string URL, multiple gets an array.\n helpers.setValue(multiple ? current.map((f) => f.url) : current[0]?.url ?? \"\");\n }\n\n setFieldTouched(fieldDef.id, true);\n },\n [\n files,\n multiple,\n maxFiles,\n maxSizeBytes,\n resizeImages,\n maxImageWidth,\n config,\n uploader,\n uploadsUnavailable,\n helpers,\n fieldDef.id,\n setFieldTouched,\n ],\n );\n\n const removeFile = useCallback(\n (index: number) => {\n const next = files.filter((_, i) => i !== index);\n setFiles(next);\n // Keep the value's TYPE stable: multiple-mode is always an array\n // (an empty \"\" string would fail the array schema with a typeError).\n helpers.setValue(multiple ? next.map((f) => f.url) : \"\");\n },\n [files, multiple, helpers],\n );\n\n const hasError = meta.touched && meta.error;\n const isRequired = fieldDef.validation?.some((v) => v.type === \"required\");\n const pickerDisabled = disabled || uploadsUnavailable;\n\n return (\n <div>\n {/* Label */}\n <label\n htmlFor={fieldDef.id}\n className=\"mb-1 block text-sm font-medium\"\n style={{ color: \"var(--form-label-color, inherit)\" }}\n >\n {fieldDef.label}\n {isRequired && <span className=\"ml-0.5 text-red-500\">*</span>}\n </label>\n\n {fieldDef.helpText && (\n <p\n className=\"mb-2 text-xs\"\n style={{ color: FORM_VAR.placeholder }}\n >\n {fieldDef.helpText}\n </p>\n )}\n\n {/* Drop zone */}\n <div\n className={`relative rounded-lg border-2 border-dashed p-6 text-center transition-colors ${\n hasError\n ? \"border-red-400\"\n : pickerDisabled\n ? \"border-current/10\"\n : \"border-current/25 hover:border-current/40\"\n }`}\n onDragOver={(e) => {\n if (pickerDisabled) return;\n e.preventDefault();\n e.stopPropagation();\n }}\n onDrop={(e) => {\n if (pickerDisabled) return;\n e.preventDefault();\n e.stopPropagation();\n handleFiles(e.dataTransfer.files);\n }}\n >\n <input\n ref={inputRef}\n id={fieldDef.id}\n type=\"file\"\n accept={config.accept}\n multiple={multiple}\n disabled={pickerDisabled}\n onChange={(e) => {\n handleFiles(e.target.files);\n e.target.value = \"\";\n }}\n className=\"hidden\"\n />\n\n {uploading ? (\n <div className=\"space-y-2\">\n {/* Indeterminate — the onUpload contract has no progress hook. */}\n <div\n className={`mx-auto h-1.5 w-32 overflow-hidden rounded-full ${FORM_SUBTLE_FILL_CLASS}`}\n >\n <div className=\"h-full w-1/3 animate-pulse rounded-full bg-indigo-500\" />\n </div>\n <p className={`text-sm ${FORM_MUTED_TEXT_CLASS}`}>Uploading…</p>\n </div>\n ) : uploadsUnavailable ? (\n <p className={`text-sm ${FORM_MUTED_TEXT_CLASS}`}>{NO_UPLOADER_MESSAGE}</p>\n ) : (\n <button\n type=\"button\"\n onClick={() => inputRef.current?.click()}\n disabled={disabled}\n className={`cursor-pointer text-sm ${FORM_MUTED_TEXT_CLASS} hover:text-current disabled:cursor-not-allowed disabled:opacity-50`}\n >\n <svg\n className={`mx-auto mb-2 h-8 w-8 ${FORM_FAINT_TEXT_CLASS}`}\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth={1.5}\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5\"\n />\n </svg>\n <span className=\"font-medium\">Click to upload</span> or drag\n and drop\n <br />\n <span className={`text-xs ${FORM_FAINT_TEXT_CLASS}`}>\n Max {formatBytes(maxSizeBytes)}\n {multiple && ` · Up to ${maxFiles} files`}\n </span>\n </button>\n )}\n </div>\n\n {/* Uploaded files */}\n {files.length > 0 && (\n <div className=\"mt-3 space-y-2\">\n {files.map((f, i) => (\n <div\n key={`${f.name}-${i}`}\n className={`flex items-center gap-3 rounded-md border ${FORM_SUBTLE_BORDER_CLASS} ${FORM_SUBTLE_FILL_CLASS} px-3 py-2`}\n >\n {f.url && f.name.match(/\\.(jpg|jpeg|png|webp|gif|svg)$/i) && (\n // eslint-disable-next-line @next/next/no-img-element\n <img\n src={f.url}\n alt={f.name}\n className=\"h-10 w-10 rounded object-cover\"\n />\n )}\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-medium\">\n {f.name}\n </p>\n <p className={`text-xs ${FORM_MUTED_TEXT_CLASS}`}>\n {formatBytes(f.size)}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={() => removeFile(i)}\n className={`cursor-pointer ${FORM_FAINT_TEXT_CLASS} hover:text-red-500`}\n aria-label={`Remove ${f.name}`}\n >\n <svg\n className=\"h-4 w-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth={2}\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M6 18L18 6M6 6l12 12\"\n />\n </svg>\n </button>\n </div>\n ))}\n </div>\n )}\n\n {/* Errors */}\n {uploadError && (\n <p className=\"mt-1 text-sm text-red-500\">{uploadError}</p>\n )}\n {hasError && (\n <p className=\"mt-1 text-sm text-red-500\">{meta.error}</p>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useFormikContext } from \"formik\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormFieldDefinition } from \"../types\";\nimport { isVisibilityConditionMet } from \"../utils/visibility\";\nimport { FORM_MUTED_TEXT_CLASS } from \"./cssVars\";\nimport { TextField } from \"./fields/TextField\";\nimport { EmailField } from \"./fields/EmailField\";\nimport { PhoneField } from \"./fields/PhoneField\";\nimport { UrlField } from \"./fields/UrlField\";\nimport { AddressField } from \"./fields/AddressField\";\nimport { TextAreaField } from \"./fields/TextAreaField\";\nimport { SelectField } from \"./fields/SelectField\";\nimport { CheckboxField } from \"./fields/CheckboxField\";\nimport { RadioField } from \"./fields/RadioField\";\nimport { NumberField } from \"./fields/NumberField\";\nimport { DateField } from \"./fields/DateField\";\nimport { DateTimeField } from \"./fields/DateTimeField\";\nimport { HiddenField } from \"./fields/HiddenField\";\nimport { SensitiveField } from \"./fields/SensitiveField\";\nimport { FileField } from \"./fields/FileField\";\n\nconst fieldComponents: Record<\n string,\n React.ComponentType<{ field: FormFieldDefinition; disabled?: boolean }>\n> = {\n text: TextField,\n email: EmailField,\n phone: PhoneField,\n url: UrlField,\n address: AddressField,\n textarea: TextAreaField,\n select: SelectField,\n checkbox: CheckboxField,\n radio: RadioField,\n number: NumberField,\n date: DateField,\n datetime: DateTimeField,\n hidden: HiddenField,\n sensitive: SensitiveField,\n // Its `onUpload`/`projectId` props are optional and normally arrive by\n // context (see FileUploadContext), so it fits the shared signature.\n file: FileField,\n};\n\ninterface Props {\n field: FormFieldDefinition;\n /** True when this field is a \"same as\" target and the toggle is on. */\n mirrored?: boolean;\n /** How a mirrored target renders while the toggle is on. */\n mirrorBehavior?: \"hide\" | \"lock\";\n}\n\nexport const DynamicFormField = ({ field, mirrored, mirrorBehavior }: Props) => {\n const { values } = useFormikContext<Record<string, unknown>>();\n const Component = fieldComponents[field.type];\n\n if (!Component) {\n console.warn(`Unknown field type: ${field.type}`);\n return null;\n }\n\n // A field with no id can't bind to Formik (useField(\"\") throws and takes\n // the whole form down). Definitions from the builder can't contain one,\n // but hand-edited/imported JSON might — skip the field instead of crashing.\n if (!field.id) {\n console.warn(\"Skipping form field with empty id\");\n return null;\n }\n\n if (\n field.showWhen &&\n !isVisibilityConditionMet(field.showWhen, values[field.showWhen.fieldId])\n ) {\n return null;\n }\n\n // A mirrored target in \"hide\" mode disappears while the toggle is on; its\n // copied value still submits (it isn't showWhen-hidden, so it's not stripped).\n if (mirrored && mirrorBehavior === \"hide\") {\n return null;\n }\n // \"lock\" mode renders the field read-only (disabled threaded below).\n const locked = mirrored && mirrorBehavior === \"lock\";\n\n if (field.type === \"hidden\") {\n return <Component field={field} disabled={locked} />;\n }\n\n const widthClasses: Record<string, string> = {\n full: \"md:col-span-6\",\n half: \"md:col-span-3\",\n third: \"md:col-span-2\",\n };\n const widthClass = widthClasses[field.layout?.width || \"full\"] || \"md:col-span-6\";\n const description = field.description ?? field.helpText;\n\n return (\n <div className={twMerge(widthClass, \"bg-inherit\")}>\n <Component field={field} disabled={locked} />\n {description && (\n <p className={twMerge(\"mt-1 text-xs\", FORM_MUTED_TEXT_CLASS)}>\n {description}\n </p>\n )}\n </div>\n );\n};\n","\"use client\";\n\nimport { useFormikContext } from \"formik\";\nimport { Checkbox } from \"radix-ui\";\nimport { useEffect } from \"react\";\nimport { BsCheck } from \"react-icons/bs\";\nimport { twMerge } from \"tailwind-merge\";\nimport type { FormSection } from \"../types\";\nimport { sameAsToggleKey } from \"../types\";\nimport { DynamicFormField } from \"./DynamicFormField\";\nimport {\n FORM_DARK_TEXT_ATTR,\n FORM_DARK_TEXT_VAR,\n FORM_GAP_VAR,\n FORM_MUTED_TEXT_CLASS,\n FORM_SUBTLE_BORDER_CLASS,\n FORM_VAR,\n resolveCustomGap,\n} from \"./cssVars\";\nimport { useFormColorScheme, useFormStyle } from \"./FormStyleContext\";\nimport { resolveSectionTextColor } from \"../utils/colorScheme\";\n\ninterface Props {\n section: FormSection;\n isLast?: boolean;\n /**\n * Form-level default header text color from `FormDefinition.defaultTextColor`.\n * Per-section `textColor` overrides this.\n */\n formDefaultTextColor?: string;\n /**\n * Dark-mode counterpart from `FormDefinition.defaultTextColorDark`.\n * Per-section `textColorDark` overrides this; see `resolveSectionTextColor`\n * for how the two chains combine.\n */\n formDefaultTextColorDark?: string;\n /**\n * Submit button rendered beside this section's fields grid (inline\n * `buttonPlacement`). The section title/description stay full-width above\n * the row — only the fields share the row with the button.\n */\n inlineSubmit?: React.ReactNode;\n}\n\n// `spacing` also drives the form root's padding (see DynamicForm). \"none\"\n// means no PADDING — a form that sits in a page owning its own layout — and\n// deliberately keeps the normal gap here: fields butted together is never what\n// anyone is asking for. Use `fieldGapValue` to set the gap independently.\nconst spacingGap: Record<string, string> = {\n none: \"gap-4\",\n compact: \"gap-2\",\n normal: \"gap-4\",\n relaxed: \"gap-6\",\n};\n\nexport const DynamicFormSection = ({\n section,\n isLast,\n formDefaultTextColor,\n formDefaultTextColorDark,\n inlineSubmit,\n}: Props) => {\n const style = useFormStyle();\n const { forced, darkEnabled } = useFormColorScheme();\n\n // \"Same as another section\" mirroring. The toggle is a synthetic Formik\n // value (reserved key, stripped before submit); when on, target fields are\n // filled from their mapped source fields and kept in sync.\n const { values, setFieldValue } = useFormikContext<Record<string, unknown>>();\n const sameAs = section.sameAs;\n const toggleKey = sameAs ? sameAsToggleKey(section.id) : \"\";\n const toggleOn = sameAs ? values[toggleKey] === true : false;\n const fieldMap = sameAs?.fieldMap ?? {};\n // Re-copy whenever a mapped source value changes while the toggle is on.\n const sourceSignature = JSON.stringify(\n Object.values(fieldMap).map((sourceId) => values[sourceId] ?? null),\n );\n\n useEffect(() => {\n if (!sameAs || !toggleOn) return;\n for (const [targetId, sourceId] of Object.entries(sameAs.fieldMap)) {\n setFieldValue(targetId, values[sourceId] ?? \"\");\n }\n // values is read at run time; sourceSignature captures source changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toggleOn, sourceSignature]);\n\n // Section beats form default; when both are unset the title/description\n // inherit from the surrounding CSS so consumers can theme via their own\n // typography (in the builder that is the canvas text color, set on the\n // form root). Pinned to a scheme, that scheme's color is what renders.\n // Otherwise the light color renders inline and, when the record carries a\n // dark header color, the dark one is published on the element for the\n // form's dark stylesheet to swap in.\n const formDefaults = {\n light: formDefaultTextColor,\n dark: formDefaultTextColorDark,\n };\n const effectiveTextColor = resolveSectionTextColor(\n section,\n formDefaults,\n forced ?? \"light\",\n );\n const darkTextColor =\n darkEnabled && (section.textColorDark || formDefaultTextColorDark)\n ? resolveSectionTextColor(section, formDefaults, \"dark\")\n : undefined;\n\n const sortedFields = [...section.fields].sort(\n (a, b) => (a.layout?.order ?? 0) - (b.layout?.order ?? 0)\n );\n\n const customGap = resolveCustomGap(style);\n // An explicit gap wins over the spacing step: neutralise the class so the\n // inline `gap` below is what applies.\n const gap = customGap ? \"gap-0\" : spacingGap[style.spacing || \"normal\"];\n const gapStyle: React.CSSProperties = customGap\n ? { gap: FORM_GAP_VAR }\n : {};\n const divider = style.sectionDividers && !isLast;\n const isStacked = style.inputVariant === \"stacked\";\n\n const sectionWrapperClass = twMerge(\n \"bg-inherit\",\n isStacked ? \"space-y-4\" : \"mb-6\",\n divider && `border-b ${FORM_SUBTLE_BORDER_CLASS} pb-6`\n );\n\n // With no effective text color the title simply inherits the consumer's\n // typography — the form has no opinion about what color a heading is on a\n // page it doesn't own. The description is the same color held back to a\n // murmur, which reads as secondary on a light or a dark ground alike.\n const titleClass = twMerge(\"text-lg font-semibold\", !isStacked && \"mb-1\");\n\n const descriptionClass = twMerge(\n \"text-sm\",\n effectiveTextColor ? \"\" : FORM_MUTED_TEXT_CLASS,\n !isStacked && \"mb-4\"\n );\n\n const textStyle =\n effectiveTextColor || darkTextColor\n ? ({\n ...(effectiveTextColor ? { color: effectiveTextColor } : {}),\n ...(darkTextColor ? { [FORM_DARK_TEXT_VAR]: darkTextColor } : {}),\n } as React.CSSProperties)\n : undefined;\n const darkTextAttr = darkTextColor ? { [FORM_DARK_TEXT_ATTR]: \"\" } : {};\n\n return (\n <fieldset className={sectionWrapperClass}>\n {section.title && (\n <legend className={titleClass} style={textStyle} {...darkTextAttr}>\n {section.title}\n </legend>\n )}\n {section.description && (\n <p className={descriptionClass} style={textStyle} {...darkTextAttr}>\n {section.description}\n </p>\n )}\n {sameAs && (\n <div className=\"mb-4 flex items-center gap-3 bg-inherit\">\n <Checkbox.Root\n id={toggleKey}\n checked={toggleOn}\n onCheckedChange={(checked) => setFieldValue(toggleKey, checked === true)}\n className=\"flex h-5 w-5 items-center justify-center rounded border\"\n style={\n toggleOn\n ? { borderColor: FORM_VAR.inputFocusBorder, backgroundColor: FORM_VAR.inputFocusBorder }\n : { borderColor: FORM_VAR.inputBorder, backgroundColor: FORM_VAR.inputBg }\n }\n >\n <Checkbox.Indicator>\n <BsCheck className=\"text-white\" />\n </Checkbox.Indicator>\n </Checkbox.Root>\n <label\n htmlFor={toggleKey}\n className=\"cursor-pointer text-sm\"\n style={{ color: FORM_VAR.labelText }}\n >\n {sameAs.toggleLabel}\n </label>\n </div>\n )}\n {(() => {\n const fieldsGrid = (\n <div\n className={twMerge(\n \"grid grid-cols-1 bg-inherit md:grid-cols-6\",\n gap,\n inlineSubmit && \"min-w-0 flex-auto\"\n )}\n style={gapStyle}\n >\n {/* Index-composited key: the builder's live preview can render\n transiently duplicated field ids mid-edit (saving them is\n blocked); ids alone would collide as keys. */}\n {sortedFields.map((field, i) => (\n <DynamicFormField\n key={`${field.id}-${i}`}\n field={field}\n mirrored={toggleOn && field.id in fieldMap}\n mirrorBehavior={sameAs?.behavior}\n />\n ))}\n </div>\n );\n\n return inlineSubmit ? (\n <div className=\"flex items-start gap-3 bg-inherit\">\n {fieldsGrid}\n {/* Non-stacked field wrappers reserve pt-3 of floating-label\n headroom above the input border (see useInputStyles), so the\n button needs the same offset to align with the input box. */}\n <div className={twMerge(\"flex-none bg-inherit\", !isStacked && \"pt-3\")}>\n {inlineSubmit}\n </div>\n </div>\n ) : (\n fieldsGrid\n );\n })()}\n </fieldset>\n );\n};\n","\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\n\n/**\n * How long the submit button stays hard-locked after a success, regardless of\n * whether the customer has edited anything. Deliberately short — the durable\n * lock is the value snapshot below, not this timer.\n */\nconst COOLDOWN_MS = 2000;\n\nexport interface SuccessFeedback {\n /** Attach to the success banner wrapper so it can be scrolled into view. */\n bannerRef: React.RefObject<HTMLDivElement | null>;\n /** True for {@link COOLDOWN_MS} after a success — blocks double-clicks. */\n cooldown: boolean;\n /**\n * Serialized form values as of the last successful submit, or `null` when\n * the form has never succeeded (or has since errored). Compare the live\n * values against this to tell \"already sent\" from \"edited since sending\".\n */\n submittedSnapshot: string | null;\n /** Record the values that were just submitted. */\n markSubmitted: (values: unknown) => void;\n /** Forget the last success — call when the form returns to idle or errors. */\n clearSubmitted: () => void;\n}\n\n/**\n * Post-success feedback state for `DynamicForm`.\n *\n * Exists because customers could not tell a submission had worked and clicked\n * Submit again (~13% of live leads arrived as byte-identical duplicate pairs).\n * It supplies the three signals that make success unmistakable: a short\n * anti-double-click cooldown, a snapshot of the submitted values so the button\n * can stay locked until something is actually edited, and a ref used to scroll\n * the success banner into view (it is above the button, so on mobile it is\n * usually off-screen at the moment it appears).\n *\n * @param isSuccess Whether the form is currently showing a real success.\n * @returns Refs, flags and setters described in {@link SuccessFeedback}.\n */\nexport function useSuccessFeedback(isSuccess: boolean): SuccessFeedback {\n const bannerRef = useRef<HTMLDivElement | null>(null);\n const [cooldown, setCooldown] = useState(false);\n const [submittedSnapshot, setSubmittedSnapshot] = useState<string | null>(null);\n\n useEffect(() => {\n if (!isSuccess) return;\n setCooldown(true);\n const timer = setTimeout(() => setCooldown(false), COOLDOWN_MS);\n\n // The banner renders above the fields; the customer is normally looking at\n // the submit button below them, so without this the only success signal is\n // off-screen.\n const node = bannerRef.current;\n if (node && typeof node.scrollIntoView === \"function\") {\n const reduceMotion =\n typeof window !== \"undefined\" &&\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n node.scrollIntoView({\n behavior: reduceMotion ? \"auto\" : \"smooth\",\n block: \"center\",\n });\n }\n\n return () => clearTimeout(timer);\n }, [isSuccess]);\n\n return {\n bannerRef,\n cooldown,\n submittedSnapshot,\n markSubmitted: (values: unknown) =>\n setSubmittedSnapshot(JSON.stringify(values)),\n clearSubmitted: () => setSubmittedSnapshot(null),\n };\n}\n","\"use client\";\n\nimport { Formik, Form, useFormikContext, type FormikProps } from \"formik\";\nimport { useEffect, useMemo, useRef, useState, type CSSProperties } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport type {\n FormColorScheme,\n FormDefinition,\n FormFileUploadHandler,\n FormStyle,\n FormSuccessBehavior,\n} from \"../types\";\nimport {\n DEFAULT_FORM_STYLE,\n DEFAULT_SPAM_PROTECTION,\n HONEYPOT_FIELD_NAME,\n sameAsToggleKey,\n} from \"../types\";\nimport { buildYupSchema } from \"../schema/buildYupSchema\";\nimport { buildInitialValues } from \"../utils/initialValues\";\nimport { isVisibilityConditionMet } from \"../utils/visibility\";\nimport { getSafeRedirectUrl } from \"../utils/redirect\";\nimport { newTransactionId, trackFormConversion } from \"../utils/conversion\";\nimport { readAdReferral } from \"../tracking/adReferral\";\nimport { readAnalyticsSessionId } from \"../tracking/analyticsSession\";\nimport {\n encryptSensitiveValue,\n type TransportPublicKey,\n} from \"../crypto/sensitive\";\nimport { DynamicFormSection } from \"./DynamicFormSection\";\nimport {\n FormColorSchemeProvider,\n FormStyleProvider,\n type FormColorSchemeState,\n} from \"./FormStyleContext\";\nimport { FormFileUploadProvider } from \"./FileUploadContext\";\nimport {\n FORM_DARK_SCOPE_ATTR,\n FORM_DEFAULT_DARK_SELECTOR,\n FORM_RADIUS_VAR,\n FORM_ROOT_BG_VAR,\n FORM_VAR,\n buildDarkSchemeCss,\n buildFormCssVars,\n buildFormDarkCssVars,\n resolveCustomRadius,\n} from \"./cssVars\";\nimport {\n definitionHasDarkColors,\n resolveSchemeStyle,\n} from \"../utils/colorScheme\";\nimport { useSuccessFeedback } from \"../hooks/useSuccessFeedback\";\n\ninterface DynamicFormProps {\n /**\n * The CMS-authored schema, normally fetched from `GET /api/forms`. Note\n * that `projectId`, `integrations`, `notificationEmailTemplate` and\n * `applicationStatusEmails` are stripped from client-facing responses, so\n * they are always undefined here — never read `definition.projectId`.\n */\n definition: FormDefinition;\n /**\n * Endpoint this form POSTs to — expected to be a server-side proxy in the\n * consuming app that adds credentials and forwards to the CMS\n * `POST /api/contact`.\n *\n * The body is a FLAT JSON object: the definition's field ids as top-level\n * keys, plus `extraData`, plus `formId`, plus `adReferral` when this site\n * mounts an `AdReferralTracker` and the visitor arrived on a tagged ad\n * click. There is no `data`/`values` wrapper. The honeypot, fields hidden\n * by an unmet `showWhen`, and the synthetic `_sameAs_*` toggles are\n * stripped before sending. The renderer never sends\n * `projectId` / `apiKey` / `url` — the proxy must add those,\n * and must forward the browser's body WHOLE (hand-picking fields into a\n * new object drops values the CMS then rejects as required).\n *\n * Two CMS rejections to expect: `url` must exactly equal the project's\n * stored URL (so localhost dev submissions get `400 \"Invalid url\"`), and\n * a top-level `email` key is required on every submission type.\n */\n apiRoute: string;\n /**\n * Bring-your-own transport. When set, the form hands the finished payload\n * (the same flat object it would have POSTed to {@link DynamicFormProps.apiRoute})\n * to this function instead of calling `fetch` itself, and treats whatever it\n * resolves with as the server response. Reject (throw) to land on the error\n * path with the thrown message.\n *\n * Exists for surfaces where a plain POST cannot work — dashboard pages whose\n * API needs a Bearer token the renderer never holds, or a preview that wants\n * the values without a network round-trip. `apiRoute` is ignored while this\n * is set.\n */\n submit?: (payload: Record<string, unknown>) => Promise<unknown>;\n /**\n * Values to start from, merged over the definition's own defaults — the\n * way a saved draft is resumed. Keys that are not fields of the definition\n * are ignored. Read once, on mount: changing it later does not reset the\n * form (remount with a `key` for that).\n */\n initialValues?: Partial<FormValues>;\n /**\n * Fired with the full value set after every edit (not on mount). The hook\n * for autosaving a long form; debounce on the consuming side.\n */\n onValuesChange?: (values: FormValues) => void;\n /**\n * Called after a successful submission. The argument is the parsed JSON\n * response body, when one was returned — application submissions echo\n * `{ success: true, referenceNumber: \"APP-…\" }` here so the consumer\n * can display it on its confirmation page.\n *\n * Also fired on the spam path (honeypot filled or submitted faster than\n * `minSubmitTime`) with NO argument and no network request at all — treat\n * a missing argument as \"no server response\", not as an error.\n */\n onSuccess?: (data?: unknown) => void;\n /**\n * Called when the submission fails. `DynamicForm` catches everything\n * internally and never throws at the call site, so this callback is the\n * only error channel. The message is the CMS `error` string when one was\n * returned (e.g. \"Invalid url\", \"Validation failed\"), otherwise\n * `Submission failed (<status>)`.\n */\n onError?: (error: Error) => void;\n /** Extra top-level keys merged into the payload alongside the field values. */\n extraData?: Record<string, unknown>;\n /**\n * Upload path for `file` fields. Called once per picked file; resolve with\n * the stored URL, which becomes the field's submitted value.\n *\n * There is no default — a public form submitter holds no CMS credentials,\n * so the upload has to go through a route in the consuming app, exactly\n * like {@link DynamicFormProps.apiRoute}. Use {@link DynamicFormProps.fileUploadRoute}\n * for the standard multipart wiring, or this prop for full control.\n *\n * A definition containing a `file` field with neither prop set renders the\n * picker disabled with an explanatory message — it will NOT fall back to a\n * throwaway `blob:` URL, which used to look like a successful upload and\n * arrive as an unopenable attachment on the lead.\n */\n onFileUpload?: FormFileUploadHandler;\n /**\n * Convenience alternative to {@link DynamicFormProps.onFileUpload}: an\n * endpoint in the consuming app that accepts one file and returns its\n * stored location.\n *\n * Request: `POST <fileUploadRoute>` with `multipart/form-data` carrying\n * `file` (the File) and `formId` (the definition id).\n * Response: `200` with JSON `{ url: string, name?: string, size?: number }`.\n * `url` must be durable — a `blob:`/`data:` URL is rejected. On failure,\n * answer non-2xx with `{ error }` and the message is shown under the field.\n *\n * Ignored when `onFileUpload` is set.\n */\n fileUploadRoute?: string;\n className?: string;\n /**\n * Endpoint that returns the RSA-OAEP transport public key used to wrap the\n * per-submission AES key for sensitive fields. Defaults to\n * `/api/forms/transport-key` (resolved against the same origin).\n *\n * The endpoint must respond with `{ kid: string, jwk: JsonWebKey }`.\n *\n * That route lives in the CMS, not in consumer apps — a consumer site with\n * a sensitive field must either proxy it or pass an absolute CMS URL here.\n * Only fetched when the definition actually contains a sensitive field.\n */\n transportKeyEndpoint?: string;\n /**\n * When set, overrides the form's internal submit state for preview purposes.\n * Network submissions are skipped while a previewState is active.\n */\n /**\n * Analytics callbacks. When omitted, the form falls back to the\n * `window.__vtTrack` hooks the @vulcantech/analytics tracker\n * registers — so form view/submit conversions track automatically on\n * any site running the tracker, with no per-form wiring.\n */\n onFormView?: (formId: string, formName: string) => void;\n onFormSubmit?: (formId: string, formName: string, submissionType: string) => void;\n previewState?: \"idle\" | \"submitting\" | \"success\" | \"error\";\n /**\n * Increment to trigger touching every field (so validation errors render).\n * Each new value re-runs the touch action.\n */\n previewTouchAllSignal?: number;\n /**\n * Increment to clear all touched state (so validation errors hide again).\n * Each new value re-runs the untouch action.\n */\n previewUntouchAllSignal?: number;\n /**\n * Editor-only: the canvas color the builder shows the form on. Fills the\n * form background only when the record sets none of its own, so the\n * preview shows what the record will render. Never persisted.\n */\n previewBg?: string;\n /**\n * Editor-only: the canvas text color, set on the form root so headers\n * with no record color inherit something readable against `previewBg`.\n * A record color always wins over it. Never persisted.\n */\n previewTextColor?: string;\n /**\n * Editor-only: render the record's colors for one scheme regardless of\n * the host page. The builder passes the scheme its Light/Dark toggle is\n * on; the renderer then emits that palette inline and none of the\n * dark-mode hooks, so the preview never depends on the CMS's own theme.\n * Consumer sites leave this unset and get the automatic behaviour.\n */\n previewColorScheme?: FormColorScheme;\n /**\n * Ancestor selector under which the record's dark palette (`style.dark`,\n * `defaultTextColorDark`, section `textColorDark`) applies. Defaults to\n * `.dark`, the class next-themes puts on `<html>` in every VulcanTech\n * site with a theme toggle. Only read when the definition carries dark\n * colors; a record without them emits nothing dark-related at all.\n *\n * Must match an ancestor of `<body>`'s children — `<html>` or `<body>`\n * itself — because the select popover is portaled to `<body>` and has to\n * fall under the same selector as the form root.\n */\n darkModeSelector?: string;\n}\n\n/** The value set Formik holds for a rendered definition. */\nexport type FormValues = Record<string, string | boolean | string[]>;\n\n/**\n * Reports Formik's values to {@link DynamicFormProps.onValuesChange}. Lives\n * inside the Formik tree so it can read the context; skips the mount render\n * because nothing has been edited yet.\n */\nfunction ValuesObserver({ onChange }: { onChange: (values: FormValues) => void }) {\n const { values } = useFormikContext<FormValues>();\n const mounted = useRef(false);\n useEffect(() => {\n if (!mounted.current) {\n mounted.current = true;\n return;\n }\n onChange(values);\n }, [values, onChange]);\n return null;\n}\n\n/**\n * Returns the IDs of every `sensitive` field in the definition. Used to\n * locate plaintext values in the Formik state before submission so they can\n * be encrypted in place.\n */\n/**\n * Conversion hooks registered on `window` by the analytics tracker\n * (@vulcantech/analytics and the per-app copies of it). Used as the\n * fallback when no onFormView/onFormSubmit props are passed — keeps the\n * forms package free of a hard analytics dependency while making\n * conversion tracking automatic wherever the tracker runs.\n */\nfunction globalTracker():\n | {\n trackFormView?: (formId: string, formName: string) => void;\n trackFormSubmit?: (\n formId: string,\n formName: string,\n submissionType?: string,\n ) => void;\n }\n | undefined {\n if (typeof window === \"undefined\") return undefined;\n return (\n window as unknown as {\n __vtTrack?: {\n trackFormView?: (formId: string, formName: string) => void;\n trackFormSubmit?: (\n formId: string,\n formName: string,\n submissionType?: string,\n ) => void;\n };\n }\n ).__vtTrack;\n}\n\n/**\n * Build the default `file` field upload handler from a route in the\n * consuming app — see {@link DynamicFormProps.fileUploadRoute} for the wire\n * contract.\n */\nfunction createRouteFileUploader(\n route: string,\n formId: string,\n): FormFileUploadHandler {\n return async (file) => {\n const body = new FormData();\n body.append(\"file\", file);\n body.append(\"formId\", formId);\n\n const res = await fetch(route, { method: \"POST\", body });\n if (!res.ok) {\n const errBody = (await res.json().catch(() => null)) as\n | { error?: string }\n | null;\n throw new Error(errBody?.error || `Upload failed (${res.status})`);\n }\n\n const data = (await res.json().catch(() => null)) as\n | { url?: unknown; name?: unknown; size?: unknown }\n | null;\n if (!data || typeof data.url !== \"string\" || data.url.length === 0) {\n throw new Error(\"Upload route did not return a url\");\n }\n if (isUnresolvedUploadUrl(data.url)) {\n throw new Error(\"Upload route returned a temporary, non-durable url\");\n }\n return {\n url: data.url,\n name: typeof data.name === \"string\" ? data.name : file.name,\n size: typeof data.size === \"number\" ? data.size : file.size,\n };\n };\n}\n\n/**\n * A URL that only resolves inside the tab that created it. Such a value must\n * never be submitted — the lead would carry a link nobody else can open.\n */\nfunction isUnresolvedUploadUrl(value: unknown): boolean {\n return (\n typeof value === \"string\" &&\n (value.startsWith(\"blob:\") || value.startsWith(\"data:\"))\n );\n}\n\n/**\n * Field ids in the payload still holding a tab-local URL. Non-empty means an\n * upload never completed, and the submission is aborted rather than storing\n * a dead link.\n */\nfunction findUnresolvedUploads(payload: Record<string, unknown>): string[] {\n const ids: string[] = [];\n for (const [key, value] of Object.entries(payload)) {\n if (Array.isArray(value)) {\n if (value.some(isUnresolvedUploadUrl)) ids.push(key);\n } else if (isUnresolvedUploadUrl(value)) {\n ids.push(key);\n }\n }\n return ids;\n}\n\n/**\n * The first submitted email and phone values, located by field type, for\n * Google Ads enhanced conversions. Whether they are actually sent is decided\n * in `fireAdsConversion` (site opt-in); this only reads them.\n */\nfunction getConversionUserData(\n definition: FormDefinition,\n values: Record<string, unknown>,\n): { email?: unknown; phone?: unknown } {\n const out: { email?: unknown; phone?: unknown } = {};\n for (const section of definition.sections) {\n for (const field of section.fields) {\n if (field.type === \"email\" && out.email === undefined && values[field.id]) {\n out.email = values[field.id];\n }\n if (field.type === \"phone\" && out.phone === undefined && values[field.id]) {\n out.phone = values[field.id];\n }\n }\n }\n return out;\n}\n\nfunction getSensitiveFieldIds(definition: FormDefinition): string[] {\n const ids: string[] = [];\n for (const section of definition.sections) {\n for (const field of section.fields) {\n if (field.type === \"sensitive\") ids.push(field.id);\n }\n }\n return ids;\n}\n\n/**\n * IDs of fields hidden by an unmet `showWhen` condition (mirrors the\n * renderer's visibility check). Their stale values must be stripped from\n * the payload — the user filled them in, flipped the condition off, and\n * the invisible value should not be submitted.\n */\nfunction getHiddenFieldIds(\n definition: FormDefinition,\n values: Record<string, unknown>,\n): string[] {\n const ids: string[] = [];\n for (const section of definition.sections) {\n for (const field of section.fields) {\n if (\n field.showWhen &&\n !isVisibilityConditionMet(field.showWhen, values[field.showWhen.fieldId])\n ) {\n ids.push(field.id);\n }\n }\n }\n return ids;\n}\n\n/**\n * Reserved Formik keys for \"same as\" section toggles. These are UI-only\n * controls and must be stripped from the submission payload (the copied\n * target field values are real and stay).\n */\nfunction getSameAsToggleKeys(definition: FormDefinition): string[] {\n return definition.sections\n .filter((s) => s.sameAs)\n .map((s) => sameAsToggleKey(s.id));\n}\n\nasync function fetchTransportKey(endpoint: string): Promise<TransportPublicKey> {\n const res = await fetch(endpoint, { method: \"GET\" });\n if (!res.ok) {\n throw new Error(\n `Failed to fetch transport key: ${res.status} ${res.statusText}`\n );\n }\n const data = (await res.json()) as TransportPublicKey;\n if (!data?.kid || !data?.jwk) {\n throw new Error(\"Transport key endpoint returned an invalid payload\");\n }\n return data;\n}\n\n// Presets only contribute non-background styling now (border / shadow / text\n// color). Every background — both the form surface and the input fill / label\n// mask via `--form-input-bg` — flows through inline styles below, so the form\n// stays transparent unless the definition opts in via `formBackgroundColor`\n// (or `inputBgColor`) and consumer Tailwind classes (especially `dark:`\n// variants) can't override the chosen color.\nconst presetNonBgClasses: Record<string, string> = {\n default: \"\",\n minimal: \"\",\n bordered: \"border border-current/15\",\n shadow: \"shadow-lg\",\n card: \"shadow-lg border border-current/15\",\n dark: \"\",\n};\n\nconst radiusClasses: Record<string, string> = {\n none: \"rounded-none\",\n sm: \"rounded-sm\",\n md: \"rounded-md\",\n lg: \"rounded-lg\",\n full: \"rounded-2xl\",\n};\n\nconst spacingClasses: Record<string, string> = {\n // \"none\" exists for forms dropped into a page that owns its own layout —\n // without it a consumer had to neutralise the padding with a `p-0` class\n // override from the outside.\n none: \"p-0\",\n compact: \"p-3\",\n normal: \"p-6\",\n relaxed: \"p-8\",\n};\n\n/**\n * Corner class for a control, or `rounded-none` when the form has opted into\n * a custom radius — in that case the caller pairs this with an inline\n * `borderRadius: FORM_RADIUS_VAR`, which wins over the class.\n */\nfunction getRadiusClass(style: FormStyle, fallback = \"rounded-md\"): string {\n if (resolveCustomRadius(style)) return \"rounded-none\";\n return radiusClasses[style.borderRadius] || fallback;\n}\n\n/** Inline corner override, empty unless the form opted into a custom radius. */\nfunction getRadiusStyle(style: FormStyle): React.CSSProperties {\n return resolveCustomRadius(style) ? { borderRadius: FORM_RADIUS_VAR } : {};\n}\n\nfunction getButtonClasses(style: FormStyle): string {\n const radius = getRadiusClass(style);\n const weight = style.inputVariant === \"stacked\" ? \"font-semibold\" : \"font-medium\";\n\n switch (style.buttonVariant) {\n case \"outline\":\n return `${radius} border-2 bg-transparent ${weight} transition-colors`;\n case \"ghost\":\n return `${radius} bg-transparent ${weight} transition-colors`;\n case \"filled\":\n default:\n return `${radius} ${weight} transition-colors`;\n }\n}\n\nfunction getButtonStyle(style: FormStyle): React.CSSProperties {\n // Pull colors from the form-root CSS variables (set by buildFormCssVars)\n // so a single update in the picker cascades here without having to thread\n // the resolved color through props.\n const radius = getRadiusStyle(style);\n switch (style.buttonVariant) {\n case \"outline\":\n return { ...radius, borderColor: FORM_VAR.buttonBg, color: FORM_VAR.buttonBg };\n case \"ghost\":\n return { ...radius, color: FORM_VAR.buttonBg };\n case \"filled\":\n default:\n return {\n ...radius,\n backgroundColor: FORM_VAR.buttonBg,\n color: FORM_VAR.buttonText,\n };\n }\n}\n\n/**\n * Replace `{{key}}` tokens in the success message with matching top-level\n * fields from the submit response body (currently used to surface the\n * `referenceNumber` echoed back by application submissions). Unknown keys\n * collapse to an empty string so the message stays presentable even when\n * the consumer's API didn't return the expected field.\n */\nfunction interpolateSuccessMessage(\n template: string,\n response: Record<string, unknown> | null,\n): string {\n if (!template.includes(\"{{\") || !response) return template;\n return template.replace(/\\{\\{\\s*([\\w.-]+)\\s*\\}\\}/g, (_match, key: string) => {\n const value = response[key];\n if (value === undefined || value === null) return \"\";\n return String(value);\n });\n}\n\nconst Spinner = () => (\n <svg\n className=\"-ml-1 mr-2 h-4 w-4 animate-spin\"\n xmlns=\"http://www.w3.org/2000/svg\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n aria-hidden=\"true\"\n >\n <circle\n className=\"opacity-25\"\n cx=\"12\"\n cy=\"12\"\n r=\"10\"\n stroke=\"currentColor\"\n strokeWidth=\"4\"\n />\n <path\n className=\"opacity-75\"\n fill=\"currentColor\"\n d=\"M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z\"\n />\n </svg>\n);\n\nconst SuccessBanner = ({ message }: { message: string }) => (\n <div\n role=\"status\"\n aria-live=\"polite\"\n className=\"flex items-start gap-3 rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800\"\n >\n <svg\n className=\"mt-0.5 h-4 w-4 flex-shrink-0\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 20 20\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n >\n <path\n fillRule=\"evenodd\"\n d=\"M10 18a8 8 0 1 0 0-16 8 8 0 0 0 0 16zm3.707-9.293a1 1 0 0 0-1.414-1.414L9 10.586 7.707 9.293a1 1 0 0 0-1.414 1.414l2 2a1 1 0 0 0 1.414 0l4-4z\"\n clipRule=\"evenodd\"\n />\n </svg>\n <span className=\"flex-1\">{message}</span>\n </div>\n);\n\nconst ErrorBanner = ({\n message,\n onDismiss,\n}: {\n message: string;\n onDismiss: () => void;\n}) => (\n <div\n role=\"alert\"\n className=\"flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800\"\n >\n <svg\n className=\"mt-0.5 h-4 w-4 flex-shrink-0\"\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 20 20\"\n fill=\"currentColor\"\n aria-hidden=\"true\"\n >\n <path\n fillRule=\"evenodd\"\n d=\"M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0zm-7 4a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-1-9a1 1 0 0 0-1 1v4a1 1 0 1 0 2 0V6a1 1 0 0 0-1-1z\"\n clipRule=\"evenodd\"\n />\n </svg>\n <span className=\"flex-1\">{message}</span>\n <button\n type=\"button\"\n onClick={onDismiss}\n className=\"font-medium text-red-900 underline-offset-2 hover:underline\"\n >\n Try again\n </button>\n </div>\n);\n\n/**\n * Render a CMS-authored {@link FormDefinition} as a working form.\n *\n * Sections and fields render in `order` (not array order); validation comes\n * from `buildYupSchema(definition)`; sensitive fields are encrypted in the\n * browser before submission. Submission goes to {@link DynamicFormProps.apiRoute}\n * as a flat JSON payload — see that prop for the wire contract.\n *\n * Failure mode: this component never throws. Network and CMS errors are\n * caught, shown in the built-in error banner, and reported via `onError`.\n * Note that a suppressed duplicate (an identical resubmit within 10 minutes)\n * and a server-side spam catch both answer `200` and are indistinguishable\n * from a stored lead by design.\n */\nexport const DynamicForm = ({\n definition,\n apiRoute,\n submit,\n initialValues: initialValueOverrides,\n onValuesChange,\n onSuccess,\n onError,\n extraData,\n onFileUpload,\n fileUploadRoute,\n className,\n onFormView,\n onFormSubmit: onFormSubmitCallback,\n transportKeyEndpoint = \"/api/forms/transport-key\",\n previewState,\n previewTouchAllSignal,\n previewUntouchAllSignal,\n previewBg,\n previewTextColor,\n previewColorScheme,\n darkModeSelector = FORM_DEFAULT_DARK_SELECTOR,\n}: DynamicFormProps) => {\n const [submitStatus, setSubmitStatus] = useState<\"idle\" | \"success\" | \"error\">(\"idle\");\n // Post-success feedback: the anti-double-click cooldown, the snapshot of the\n // submitted values that keeps the button locked until something is actually\n // edited, and the ref used to scroll the success banner into view. See\n // {@link useSuccessFeedback} — the whole point is that an unchanged form is\n // a duplicate by definition, so it stays unsubmittable, while a `reset` or\n // `message` form becomes submittable again the moment a value changes.\n const {\n bannerRef,\n cooldown: postSuccessCooldown,\n submittedSnapshot,\n markSubmitted,\n clearSubmitted,\n } = useSuccessFeedback(submitStatus === \"success\");\n // Captured from the API response so the success message can interpolate\n // `{{referenceNumber}}` for application submissions. Cleared whenever\n // the form transitions back to idle/error.\n const [responseData, setResponseData] = useState<Record<string, unknown> | null>(\n null,\n );\n const formikRef = useRef<FormikProps<Record<string, string | boolean | string[]>> | null>(null);\n\n // Fire form view analytics on mount\n useEffect(() => {\n (onFormView ?? globalTracker()?.trackFormView)?.(\n definition.id,\n definition.name,\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const effectiveSubmitStatus: \"idle\" | \"success\" | \"error\" =\n previewState === \"success\"\n ? \"success\"\n : previewState === \"error\"\n ? \"error\"\n : previewState === \"idle\"\n ? \"idle\"\n : submitStatus;\n const previewSubmitting = previewState === \"submitting\";\n\n const spamProtection = {\n ...DEFAULT_SPAM_PROTECTION,\n ...definition.submitConfig.spamProtection,\n };\n const honeypotEnabled = spamProtection.honeypot !== false;\n const minSubmitTime = Math.max(0, spamProtection.minSubmitTime ?? 0);\n\n const mountTimeRef = useRef<number>(Date.now());\n useEffect(() => {\n mountTimeRef.current = Date.now();\n }, [definition.id]);\n\n const validationSchema = useMemo(() => buildYupSchema(definition), [definition]);\n // Formik only re-validates on change/blur, so a definition swap that\n // relaxes a rule would leave its stale error on screen until the next\n // keystroke. Re-run validation whenever the schema itself changes.\n useEffect(() => {\n void formikRef.current?.validateForm();\n }, [validationSchema]);\n const initialValues = useMemo(() => {\n const base = buildInitialValues(definition);\n // Overrides only for keys the definition actually has — a stale draft\n // must not smuggle values for fields that no longer exist.\n for (const [key, value] of Object.entries(initialValueOverrides ?? {})) {\n if (key in base && value !== undefined) base[key] = value;\n }\n if (honeypotEnabled) {\n base[HONEYPOT_FIELD_NAME] = \"\";\n }\n return base;\n // Overrides are read once: see the prop's doc.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [definition, honeypotEnabled]);\n\n const sortedSections = useMemo(\n () => [...definition.sections].sort((a, b) => a.order - b.order),\n [definition.sections]\n );\n\n // Upload path published to any `file` field below. `onFileUpload` wins;\n // `fileUploadRoute` gets the standard multipart wiring; neither leaves\n // `upload` undefined, which makes file fields render disabled — except in\n // the builder preview, where a local object URL stands in and no\n // submission ever leaves the browser.\n const fileUploadValue = useMemo(\n () => ({\n upload:\n onFileUpload ??\n (fileUploadRoute\n ? createRouteFileUploader(fileUploadRoute, definition.id)\n : undefined),\n allowObjectUrlFallback: Boolean(previewState),\n }),\n [onFileUpload, fileUploadRoute, definition.id, previewState],\n );\n\n useEffect(() => {\n if (previewTouchAllSignal === undefined || !formikRef.current) return;\n const touched: Record<string, boolean> = {};\n for (const section of definition.sections) {\n for (const field of section.fields) {\n touched[field.id] = true;\n }\n }\n formikRef.current.setTouched(touched, true);\n }, [previewTouchAllSignal, definition.sections]);\n\n useEffect(() => {\n if (previewUntouchAllSignal === undefined || !formikRef.current) return;\n // Skip validation — untouched fields don't render errors anyway.\n formikRef.current.setTouched({}, false);\n }, [previewUntouchAllSignal]);\n\n // Two ways a form's colors get resolved. Pinned to a scheme (the builder\n // preview), the palette for that scheme is emitted inline and nothing\n // dark-related is rendered. Otherwise — every consumer site — the light\n // palette is inline exactly as it always was, and a record that carries\n // dark colors additionally publishes its `-dark` variables, the scope\n // attribute and the stylesheet that swaps them in under `darkModeSelector`.\n const rawStyle: FormStyle = { ...DEFAULT_FORM_STYLE, ...definition.style };\n const style: FormStyle = previewColorScheme\n ? resolveSchemeStyle(rawStyle, previewColorScheme)\n : rawStyle;\n const darkEnabled = !previewColorScheme && definitionHasDarkColors(definition);\n const colorSchemeState: FormColorSchemeState = {\n forced: previewColorScheme,\n darkEnabled,\n };\n const isStacked = style.inputVariant === \"stacked\";\n const isCard = style.preset === \"card\";\n\n const submittingText = definition.submitConfig.submittingText ?? \"Submitting...\";\n // Terminal label shown while the values still match the last successful\n // submit — \"Submit\" coming back looks like nothing happened.\n const submittedText = definition.submitConfig.submittedText ?? \"Sent\";\n const successBehavior: FormSuccessBehavior =\n definition.submitConfig.successBehavior ?? \"message\";\n\n // Build the CSS-variable map the form root publishes: every color override\n // from the persisted FormStyle (or, for `--form-bg` alone, the editor's\n // preview canvas when the record sets no background) is emitted here.\n // Variables that aren't set are simply omitted, and the renderer's\n // `var(--name, fallback)` references resolve to the baked-in defaults in\n // `FORM_DEFAULT_COLOR`. This is what lets a single picker change cascade\n // to every input, button and label without any prop-threading.\n const cssVarStyle: CSSProperties = {\n ...buildFormCssVars(style, previewBg),\n ...(darkEnabled ? buildFormDarkCssVars(style) : {}),\n };\n // The form root's actual `background-color` follows the effective surface\n // color so the chrome paints even before any child reads the CSS var.\n // Without this the input-bg var would resolve correctly inside fields but\n // the form root itself would be transparent against the preview canvas.\n // A form with a dark palette reads the variable instead of a literal, so\n // the dark stylesheet's swap of `--form-bg` reaches the root as well.\n // Truthiness, not `??`: a cleared picker leaves an empty string behind,\n // and `buildFormCssVars` already treats that as unset.\n const effectiveFormBg = style.formBackgroundColor || previewBg;\n const rootBgStyle: CSSProperties = darkEnabled\n ? { backgroundColor: FORM_ROOT_BG_VAR }\n : effectiveFormBg\n ? { backgroundColor: effectiveFormBg }\n : {};\n const formInlineStyle: CSSProperties = {\n ...cssVarStyle,\n ...getRadiusStyle(style),\n ...rootBgStyle,\n ...(previewTextColor ? { color: previewTextColor } : {}),\n };\n // Hooks only a dark-palette form renders: the scope attribute the dark\n // stylesheet keys off, and that stylesheet itself.\n const darkScopeAttr = darkEnabled ? { [FORM_DARK_SCOPE_ATTR]: \"\" } : {};\n const darkStyleSheet = darkEnabled ? (\n <style\n data-vt-forms-dark=\"\"\n dangerouslySetInnerHTML={{ __html: buildDarkSchemeCss(darkModeSelector) }}\n />\n ) : null;\n\n // `bg-inherit` is the base of the background-inheritance chain: every\n // element from here down to the inputs and floating labels carries it, so\n // a form with no `formBackgroundColor` of its own picks up whatever\n // background the consumer's container paints instead of resolving\n // `inherit` to transparent. An explicit form background still wins — it\n // lands in `formInlineStyle`, and inline styles beat the class.\n const formClasses = twMerge(\n \"bg-inherit\",\n presetNonBgClasses[style.preset] || \"\",\n getRadiusClass(style),\n isCard ? \"p-8\" : spacingClasses[style.spacing] || \"p-6\",\n isStacked ? \"space-y-8\" : \"\",\n className\n );\n\n const inlineButton = style.buttonPlacement === \"inline\";\n const buttonSizeClass = inlineButton\n ? isStacked\n ? \"flex-none px-6 py-3 text-base\"\n : \"flex-none px-6 py-2.5 text-sm\"\n : isStacked\n ? \"w-full px-6 py-3 text-base\"\n : \"mt-4 w-full px-6 py-2.5 text-sm\";\n\n const bannerWrapperClass = isStacked ? \"\" : \"mb-4\";\n\n // Render `{{referenceNumber}}` (and any other top-level string field from\n // the API response) in the success message. Mostly relevant to\n // application submissions, which echo back `referenceNumber`. Falls\n // through to the raw message when no placeholders are present, which\n // keeps the contact-form flow identical to before.\n const successMessage = interpolateSuccessMessage(\n definition.submitConfig.successMessage,\n responseData,\n );\n\n if (successBehavior === \"replace\" && effectiveSubmitStatus === \"success\") {\n return (\n <FormStyleProvider value={style}>\n <FormColorSchemeProvider value={colorSchemeState}>\n <div\n ref={bannerRef}\n className={formClasses}\n style={formInlineStyle}\n data-form-version={definition.version}\n {...darkScopeAttr}\n >\n {darkStyleSheet}\n <SuccessBanner message={successMessage} />\n </div>\n </FormColorSchemeProvider>\n </FormStyleProvider>\n );\n }\n\n return (\n <FormStyleProvider value={style}>\n <FormColorSchemeProvider value={colorSchemeState}>\n <FormFileUploadProvider value={fileUploadValue}>\n <Formik\n innerRef={formikRef}\n initialValues={initialValues}\n validationSchema={validationSchema}\n onSubmit={async (values, { setSubmitting, resetForm }) => {\n if (previewState) {\n setSubmitting(false);\n return;\n }\n\n const honeypotTriggered =\n honeypotEnabled &&\n typeof values[HONEYPOT_FIELD_NAME] === \"string\" &&\n (values[HONEYPOT_FIELD_NAME] as string).length > 0;\n const elapsedSeconds = (Date.now() - mountTimeRef.current) / 1000;\n const timerTriggered =\n minSubmitTime > 0 && elapsedSeconds < minSubmitTime;\n\n if (honeypotTriggered || timerTriggered) {\n const proc = (globalThis as { process?: { env?: { NODE_ENV?: string } } })\n .process;\n if (proc?.env?.NODE_ENV !== \"production\") {\n const reason = honeypotTriggered ? \"honeypot\" : \"timer\";\n console.debug(`[forms] Spam detected: ${reason}`);\n }\n // Spam paths never get a real response — clear any stale data\n // so the success banner doesn't show a stale reference number.\n // They also fire NO conversion signals: no `form_submit_success`\n // dataLayer push and no Ads conversion. The bot sees a success it\n // can't distinguish from the real thing, but nothing reaches\n // Google — same reasoning as the `redirectUrl` skip below.\n setResponseData(null);\n markSubmitted(values);\n setSubmitStatus(\"success\");\n if (successBehavior === \"reset\" || successBehavior === \"replace\") {\n resetForm();\n }\n onSuccess?.();\n setSubmitting(false);\n return;\n }\n\n setSubmitStatus(\"idle\");\n try {\n // Strip the honeypot from the payload — it's already empty when\n // a human submits, but be defensive in case the field is renamed.\n const { [HONEYPOT_FIELD_NAME]: _hp, ...cleanValues } = values as Record<\n string,\n string | boolean | string[]\n >;\n // Campaign attribution, when this site mounts an\n // `AdReferralTracker` and the visitor arrived on a tagged ad\n // click. Absent otherwise — a site with no tracker has no\n // cookie, so its payload is unchanged. `extraData` is spread\n // after, so a caller passing its own `adReferral` still wins.\n const adReferral = readAdReferral();\n // Lets the CMS label the lead's source from this visit's landing\n // page (Google, ChatGPT, a referrer…) when there's no ad cookie.\n const analyticsSessionId = readAnalyticsSessionId();\n const payload: Record<string, unknown> = {\n ...cleanValues,\n ...(adReferral ? { adReferral } : {}),\n ...(analyticsSessionId ? { analyticsSessionId } : {}),\n ...extraData,\n formId: definition.id,\n };\n\n // Drop values for fields currently hidden by showWhen — they're\n // invisible to the user and shouldn't reach the server.\n for (const hiddenId of getHiddenFieldIds(definition, cleanValues)) {\n delete payload[hiddenId];\n }\n\n // Drop the synthetic \"same as\" toggles — UI-only controls. The\n // copied target field values remain (they're real submission data).\n for (const toggleKey of getSameAsToggleKeys(definition)) {\n delete payload[toggleKey];\n }\n\n // A file field whose upload never completed still holds its\n // tab-local URL. Fail loudly instead of storing a lead with an\n // attachment link nobody can open.\n const unresolved = findUnresolvedUploads(payload);\n if (unresolved.length > 0) {\n throw new Error(\n `File upload did not complete for: ${unresolved.join(\", \")}. ` +\n \"Remove the file and add it again.\",\n );\n }\n\n // Encrypt sensitive fields with the server's transport public key\n // before they ever leave the browser. The plaintext is replaced\n // in `payload` with an EncryptedSensitiveValue envelope; the API\n // route unwraps it server-side and re-encrypts with KMS.\n const sensitiveIds = getSensitiveFieldIds(definition);\n if (sensitiveIds.length > 0) {\n const transportKey = await fetchTransportKey(transportKeyEndpoint);\n for (const fieldId of sensitiveIds) {\n const plaintext = cleanValues[fieldId];\n if (typeof plaintext !== \"string\" || plaintext.length === 0) {\n delete payload[fieldId];\n continue;\n }\n payload[fieldId] = await encryptSensitiveValue(\n plaintext,\n transportKey\n );\n }\n }\n\n let body: Record<string, unknown> | null = null;\n if (submit) {\n // Caller-owned transport: whatever it resolves with stands in\n // for the parsed response body.\n const result = await submit(payload);\n body =\n result && typeof result === \"object\"\n ? (result as Record<string, unknown>)\n : null;\n } else {\n const res = await fetch(apiRoute, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (!res.ok) {\n // Surface the server's error message when it sent one —\n // `res.statusText` is usually empty with fetch.\n const errBody = (await res.json().catch(() => null)) as\n | { error?: string }\n | null;\n throw new Error(\n errBody?.error || `Submission failed (${res.status})`,\n );\n }\n\n // Parse JSON best-effort — the success path doesn't depend on\n // it but applications include a `referenceNumber` we surface in\n // the success message.\n try {\n body = (await res.json()) as Record<string, unknown>;\n } catch {\n body = null;\n }\n }\n setResponseData(body);\n const submissionType =\n (extraData?.submissionType as string) ?? \"contact\";\n // Google conversion signals, fired once per genuine success and\n // before any success UI so a `redirectUrl` can't navigate away\n // first: a `form_submit_success` dataLayer push (gtag.js and GTM\n // both see it) plus, when a `send_to` label is configured, a\n // direct Ads conversion, plus GA4 `generate_lead`. The server's\n // submission id (when it returns one) is the transaction_id, so\n // Google dedupes a double fire. Deliberately absent from the spam\n // short-circuit above — see `trackFormConversion`. Never throws.\n const serverId = body?.submissionId;\n trackFormConversion(\n {\n formId: definition.id,\n formName: definition.name,\n formType: submissionType,\n },\n definition.submitConfig.conversion?.sendTo,\n {\n transactionId:\n typeof serverId === \"string\" && serverId\n ? serverId\n : newTransactionId(),\n userData: getConversionUserData(definition, values),\n },\n );\n markSubmitted(values);\n setSubmitStatus(\"success\");\n (onFormSubmitCallback ?? globalTracker()?.trackFormSubmit)?.(\n definition.id,\n definition.name,\n submissionType,\n );\n if (successBehavior === \"reset\" || successBehavior === \"replace\") {\n resetForm();\n }\n onSuccess?.(body ?? undefined);\n // Redirect only on genuine success — the fake-success spam path\n // above deliberately stays on-page so detected bots never reach\n // the redirect target and fire its ad-conversion tags. Never\n // reached in the builder preview (previewState short-circuits\n // before the network call).\n const redirectUrl = getSafeRedirectUrl(\n definition.submitConfig.redirectUrl,\n );\n if (redirectUrl) {\n window.location.assign(redirectUrl);\n }\n } catch (err) {\n setResponseData(null);\n clearSubmitted();\n setSubmitStatus(\"error\");\n onError?.(err instanceof Error ? err : new Error(\"Submission failed\"));\n } finally {\n setSubmitting(false);\n }\n }}\n >\n {({ isSubmitting, getFieldProps, values }) => {\n const showSubmitting = isSubmitting || previewSubmitting;\n const isDisabled =\n successBehavior === \"disable\" && effectiveSubmitStatus === \"success\";\n // Nothing has been edited since the submission that succeeded, so\n // pressing the button again could only produce a byte-identical\n // duplicate. Editing any field changes the serialization and lifts\n // the lock, which keeps `reset`/`message` forms submittable later.\n const unchangedSinceSuccess =\n effectiveSubmitStatus === \"success\" &&\n submittedSnapshot !== null &&\n JSON.stringify(values) === submittedSnapshot;\n // Prevent double-submit: disable the button while submitting, for a\n // short cooldown after success, and for as long as the values are\n // unchanged since that success.\n const submitLocked =\n showSubmitting ||\n postSuccessCooldown ||\n unchangedSinceSuccess ||\n previewState === \"success\";\n\n return (\n <Form\n // Formik renders `action=\"#\"` and no method, so a submit that\n // beats hydration (slow network, script error, blocked JS)\n // falls through to a native GET that writes every field into\n // the URL: browser history, analytics page_location, access\n // logs. POST keeps a native fallback out of the URL; sensitive\n // inputs also carry no `name`, so they are never in it at all.\n method=\"post\"\n className={formClasses}\n style={formInlineStyle}\n data-form-version={definition.version}\n {...darkScopeAttr}\n >\n {darkStyleSheet}\n {onValuesChange && <ValuesObserver onChange={onValuesChange} />}\n {honeypotEnabled && (\n <div\n aria-hidden=\"true\"\n style={{\n position: \"absolute\",\n left: \"-9999px\",\n top: \"auto\",\n width: 0,\n height: 0,\n overflow: \"hidden\",\n opacity: 0,\n zIndex: -1,\n }}\n >\n <label htmlFor={HONEYPOT_FIELD_NAME}>\n Website (leave blank)\n </label>\n <input\n type=\"text\"\n id={HONEYPOT_FIELD_NAME}\n {...getFieldProps(HONEYPOT_FIELD_NAME)}\n tabIndex={-1}\n autoComplete=\"off\"\n />\n </div>\n )}\n {effectiveSubmitStatus === \"success\" && (\n <div ref={bannerRef} className={bannerWrapperClass}>\n <SuccessBanner message={successMessage} />\n </div>\n )}\n\n {effectiveSubmitStatus === \"error\" && (\n <div className={bannerWrapperClass}>\n <ErrorBanner\n message={definition.submitConfig.errorMessage}\n onDismiss={() => setSubmitStatus(\"idle\")}\n />\n </div>\n )}\n\n <fieldset\n disabled={isDisabled}\n aria-disabled={isDisabled}\n className={twMerge(\n \"min-w-0 border-0 bg-inherit p-0\",\n isStacked ? \"space-y-8\" : \"\",\n isDisabled ? \"pointer-events-none opacity-60\" : \"\"\n )}\n >\n {(() => {\n const submitButton = (\n <button\n type=\"submit\"\n disabled={submitLocked || isDisabled}\n className={twMerge(\n buttonSizeClass,\n \"inline-flex cursor-pointer items-center justify-center disabled:cursor-not-allowed disabled:opacity-60\",\n getButtonClasses(style)\n )}\n style={getButtonStyle(style)}\n aria-busy={showSubmitting}\n >\n {showSubmitting && <Spinner />}\n {showSubmitting\n ? submittingText\n : unchangedSinceSuccess\n ? submittedText\n : definition.submitConfig.buttonText}\n </button>\n );\n\n // Inline placement hands the button to the last section,\n // which renders it beside its fields grid — the section\n // title/description stay full-width above the row.\n return (\n <>\n {sortedSections.map((section, idx) => {\n const isLast = idx === sortedSections.length - 1;\n return (\n <DynamicFormSection\n key={section.id}\n section={section}\n isLast={isLast}\n formDefaultTextColor={definition.defaultTextColor}\n formDefaultTextColorDark={\n definition.defaultTextColorDark\n }\n inlineSubmit={\n inlineButton && isLast ? submitButton : undefined\n }\n />\n );\n })}\n {!inlineButton && submitButton}\n </>\n );\n })()}\n </fieldset>\n </Form>\n );\n }}\n </Formik>\n </FormFileUploadProvider>\n </FormColorSchemeProvider>\n </FormStyleProvider>\n );\n};\n","\"use client\";\n\nimport { useEffect } from \"react\";\nimport {\n AD_REFERRAL_COOKIE,\n AD_REFERRAL_TTL_DAYS,\n captureAdReferral,\n isSameAdReferralTouch,\n readAdReferral,\n writeAdReferral,\n type AdReferralFallback,\n} from \"./adReferral\";\n\ninterface AdReferralTrackerProps {\n /**\n * Applied only on a page that receives nothing but ad traffic — a\n * `noindex`, unlinked paid-search landing page — so an untagged ad click\n * there is still credited. Omit it everywhere else: on a normal page it\n * would label every organic visitor as paid.\n */\n fallback?: AdReferralFallback;\n /** Override for a site still on a legacy cookie name. */\n cookieName?: string;\n /** How long an ad click stays credited for a later conversion. */\n ttlDays?: number;\n}\n\n/**\n * Records the campaign that brought this visitor to the site, in a cookie\n * `DynamicForm` attaches to any form they later submit.\n *\n * Mount once, in the root layout, so a click is captured wherever it lands —\n * ads point at homepages, service pages and city pages, not only at\n * purpose-built landing pages, and a form on any of them can be the\n * conversion.\n *\n * Writing is gated on the entry URL actually carrying ad signal (`utm_*` or\n * a Google click id), so mounting it site-wide does not make every visitor\n * look like paid traffic. A visit with no signal leaves any existing cookie\n * untouched.\n *\n * Renders nothing — it exists purely to keep the `window`-dependent effect\n * in a leaf client component, so the layout around it can stay a server\n * component.\n */\nexport function AdReferralTracker({\n fallback,\n cookieName = AD_REFERRAL_COOKIE,\n ttlDays = AD_REFERRAL_TTL_DAYS,\n}: AdReferralTrackerProps = {}) {\n useEffect(() => {\n // Empty deps on purpose: this reads the URL the visitor ARRIVED on. A\n // root-layout client component mounts once and survives client-side\n // navigation, so the entry query string is exactly what's wanted — and\n // re-running per route would let an internal link with no UTMs look like\n // a fresh untagged visit.\n const referral = captureAdReferral(\n window.location.search,\n fallback,\n new Date(),\n window.location.pathname,\n );\n if (!referral) return;\n // The site's proxy may already have set this cookie from the same URL\n // (`setAdReferralCookie`). Rewriting it from JS would only bump `landedAt`\n // by the hydration delay, and would make Safari cap a 30-day HTTP cookie\n // to 7 days, or 24h after a gclid landing. A genuinely new touch differs\n // in some field, so last-touch still wins.\n const existing = readAdReferral(cookieName);\n if (existing && isSameAdReferralTouch(existing, referral)) return;\n writeAdReferral(referral, cookieName, ttlDays);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return null;\n}\n","\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport type { FormDefinition } from \"../types\";\n\ninterface BaseFetchOptions {\n cmsUrl: string;\n projectId: string;\n apiKey: string;\n}\n\n/**\n * One of `formId` or `formSlug` must be provided to identify which form to load.\n */\nexport type FormIdentifier =\n | { formId: string; formSlug?: never }\n | { formId?: never; formSlug: string };\n\nexport type UseFormDefinitionOptions = BaseFetchOptions & FormIdentifier;\n\ninterface UseFormDefinitionResult {\n definition: FormDefinition | null;\n isLoading: boolean;\n error: Error | null;\n}\n\nfunction buildQueryString(opts: UseFormDefinitionOptions): string {\n const params = new URLSearchParams({\n projectId: opts.projectId,\n apiKey: opts.apiKey,\n });\n if (\"formId\" in opts && opts.formId) params.set(\"formId\", opts.formId);\n if (\"formSlug\" in opts && opts.formSlug) params.set(\"slug\", opts.formSlug);\n return params.toString();\n}\n\nexport function useFormDefinition(\n opts: UseFormDefinitionOptions,\n): UseFormDefinitionResult {\n const [definition, setDefinition] = useState<FormDefinition | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const { cmsUrl, projectId, apiKey } = opts;\n const formId = \"formId\" in opts ? opts.formId : undefined;\n const formSlug = \"formSlug\" in opts ? opts.formSlug : undefined;\n\n useEffect(() => {\n let cancelled = false;\n\n async function fetchDefinition() {\n setIsLoading(true);\n setError(null);\n\n try {\n const qs = buildQueryString(opts);\n const res = await fetch(`${cmsUrl}/api/forms?${qs}`);\n\n if (!res.ok) {\n throw new Error(`Failed to fetch form definition: ${res.statusText}`);\n }\n\n const data = await res.json();\n if (!cancelled) {\n setDefinition(data);\n }\n } catch (err) {\n if (!cancelled) {\n setError(err instanceof Error ? err : new Error(\"Failed to fetch form\"));\n }\n } finally {\n if (!cancelled) {\n setIsLoading(false);\n }\n }\n }\n\n fetchDefinition();\n\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [cmsUrl, projectId, apiKey, formId, formSlug]);\n\n return { definition, isLoading, error };\n}\n\n/**\n * Server-side fetch for use in Next.js Server Components / RSC / getStaticProps.\n * Returns `null` on any error or when the form does not exist.\n */\nexport async function getFormDefinition(\n opts: UseFormDefinitionOptions & { revalidate?: number },\n): Promise<FormDefinition | null> {\n try {\n const qs = buildQueryString(opts);\n // Cast — `next` is a Next.js extension to RequestInit not present in the\n // forms package's stock TS lib. Consuming Next apps see the augmented type.\n const res = await fetch(`${opts.cmsUrl}/api/forms?${qs}`, {\n next: { revalidate: opts.revalidate ?? 3600 },\n } as RequestInit);\n\n if (!res.ok) return null;\n return res.json();\n } catch {\n return null;\n }\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\n\nconst DEFAULT_HISTORY_LIMIT = 50;\n\nexport type SetStateUpdater<T> = T | ((prev: T) => T);\n\nexport interface UseUndoRedoOptions {\n /** Maximum number of past entries to retain. Defaults to 50. */\n historyLimit?: number;\n}\n\nexport interface UseUndoRedoControls<T> {\n /** Replace the current state without recording history. Clears past+future. */\n reset: (value: T) => void;\n /** Number of past entries currently retained. */\n historySize: number;\n}\n\nexport type UseUndoRedoReturn<T> = [\n T,\n (value: SetStateUpdater<T>) => void,\n () => void,\n () => void,\n boolean,\n boolean,\n UseUndoRedoControls<T>,\n];\n\ninterface History<T> {\n past: T[];\n present: T;\n future: T[];\n}\n\nfunction applyUpdater<T>(updater: SetStateUpdater<T>, current: T): T {\n return typeof updater === \"function\"\n ? (updater as (prev: T) => T)(current)\n : updater;\n}\n\n/**\n * Generic undo/redo state hook.\n *\n * Returns a tuple shaped like `useState`, plus undo/redo callbacks and\n * canUndo/canRedo flags. The 7th element exposes controls (`reset`,\n * `historySize`) that are only needed in advanced cases — most callers can\n * destructure just the first six.\n *\n * History is bounded at `historyLimit` (default 50) — the oldest past entries\n * are dropped when the cap is reached.\n */\nexport function useUndoRedo<T>(\n initialState: T,\n options: UseUndoRedoOptions = {},\n): UseUndoRedoReturn<T> {\n const limit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;\n\n const [history, setHistory] = useState<History<T>>(() => ({\n past: [],\n present: initialState,\n future: [],\n }));\n\n const setState = useCallback(\n (updater: SetStateUpdater<T>) => {\n setHistory((h) => {\n const next = applyUpdater(updater, h.present);\n if (Object.is(next, h.present)) return h;\n const past = [...h.past, h.present];\n if (past.length > limit) past.splice(0, past.length - limit);\n return { past, present: next, future: [] };\n });\n },\n [limit],\n );\n\n const reset = useCallback((value: T) => {\n setHistory((h) =>\n Object.is(value, h.present)\n ? h\n : { past: [], present: value, future: [] },\n );\n }, []);\n\n const undo = useCallback(() => {\n setHistory((h) => {\n if (h.past.length === 0) return h;\n const previous = h.past[h.past.length - 1];\n const past = h.past.slice(0, -1);\n return { past, present: previous, future: [h.present, ...h.future] };\n });\n }, []);\n\n const redo = useCallback(() => {\n setHistory((h) => {\n if (h.future.length === 0) return h;\n const [next, ...rest] = h.future;\n return { past: [...h.past, h.present], present: next, future: rest };\n });\n }, []);\n\n return [\n history.present,\n setState,\n undo,\n redo,\n history.past.length > 0,\n history.future.length > 0,\n { reset, historySize: history.past.length },\n ];\n}\n\n/**\n * Wires Cmd/Ctrl+Z (undo) and Cmd/Ctrl+Shift+Z (redo) keyboard shortcuts.\n *\n * Skips the shortcut when the user is typing in an input/textarea or\n * contenteditable region, so the browser's native input-history undo works\n * inside text fields without clobbering form-level history.\n */\nexport function useUndoRedoShortcuts(opts: {\n undo: () => void;\n redo: () => void;\n enabled?: boolean;\n}) {\n const { undo, redo, enabled = true } = opts;\n\n useEffect(() => {\n if (!enabled || typeof window === \"undefined\") return;\n\n const handler = (e: KeyboardEvent) => {\n const target = e.target as HTMLElement | null;\n if (target) {\n const tag = target.tagName;\n const editable = (target as HTMLElement).isContentEditable;\n if (\n tag === \"INPUT\" ||\n tag === \"TEXTAREA\" ||\n tag === \"SELECT\" ||\n editable\n ) {\n return;\n }\n }\n\n const meta = e.metaKey || e.ctrlKey;\n if (!meta) return;\n const key = e.key.toLowerCase();\n if (key !== \"z\") return;\n\n e.preventDefault();\n if (e.shiftKey) {\n redo();\n } else {\n undo();\n }\n };\n\n window.addEventListener(\"keydown\", handler);\n return () => window.removeEventListener(\"keydown\", handler);\n }, [undo, redo, enabled]);\n}\n","\"use client\";\n\nimport { useCallback, useRef, useState, type DragEvent } from \"react\";\n\nexport type DropPosition = \"before\" | \"after\";\n\nexport interface DragReorderState {\n draggingId: string | null;\n dragOverId: string | null;\n dragOverPosition: DropPosition | null;\n}\n\nexport interface DragReorderItemHandlers {\n draggable: true;\n onDragStart: (e: DragEvent<HTMLElement>) => void;\n onDragEnd: (e: DragEvent<HTMLElement>) => void;\n onDragOver: (e: DragEvent<HTMLElement>) => void;\n onDragLeave: (e: DragEvent<HTMLElement>) => void;\n onDrop: (e: DragEvent<HTMLElement>) => void;\n}\n\nexport interface UseDragReorderOptions<T> {\n items: T[];\n getId: (item: T) => string;\n onReorder: (newOrder: T[]) => void;\n /**\n * MIME type for the drag payload. Different reorder zones (e.g. sections vs.\n * fields) should use different types so a section drag can't be dropped on a\n * field row by accident.\n */\n dragType?: string;\n}\n\nexport interface UseDragReorderResult extends DragReorderState {\n itemHandlers: (id: string) => DragReorderItemHandlers;\n /** True when this item is being dragged. Useful for opacity styling. */\n isDragging: (id: string) => boolean;\n /**\n * Returns the drop indicator position for `id` (\"before\" / \"after\" / null).\n * Render a 2px blue line at the matching edge.\n */\n dropIndicator: (id: string) => DropPosition | null;\n}\n\nconst DEFAULT_DRAG_TYPE = \"application/x-vt-reorder\";\n\n/**\n * HTML5 drag-and-drop reordering for a flat list of items.\n *\n * Each item should spread the handlers returned by `itemHandlers(id)` onto\n * its root element, and render a drop indicator using `dropIndicator(id)`.\n *\n * The hook computes drop position from the cursor position relative to the\n * hovered item — top half means \"drop before\", bottom half means \"drop after\".\n */\nexport function useDragReorder<T>({\n items,\n getId,\n onReorder,\n dragType = DEFAULT_DRAG_TYPE,\n}: UseDragReorderOptions<T>): UseDragReorderResult {\n const [state, setState] = useState<DragReorderState>({\n draggingId: null,\n dragOverId: null,\n dragOverPosition: null,\n });\n\n // Track the most recent dragOver target so we can clear on drop without\n // depending on the dragLeave/dragEnd ordering, which differs between browsers.\n const lastOverRef = useRef<string | null>(null);\n\n const reset = useCallback(() => {\n lastOverRef.current = null;\n setState({ draggingId: null, dragOverId: null, dragOverPosition: null });\n }, []);\n\n const itemHandlers = useCallback(\n (id: string): DragReorderItemHandlers => ({\n draggable: true,\n onDragStart: (e) => {\n e.stopPropagation();\n try {\n e.dataTransfer.setData(dragType, id);\n e.dataTransfer.setData(\"text/plain\", id);\n } catch {\n /* setData throws in some test envs — ignore */\n }\n e.dataTransfer.effectAllowed = \"move\";\n setState({\n draggingId: id,\n dragOverId: null,\n dragOverPosition: null,\n });\n },\n onDragEnd: () => {\n reset();\n },\n onDragOver: (e) => {\n // Only react to drags initiated for this reorder zone.\n const types = Array.from(e.dataTransfer.types);\n if (!types.includes(dragType)) return;\n e.preventDefault();\n e.stopPropagation();\n e.dataTransfer.dropEffect = \"move\";\n\n const rect = e.currentTarget.getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position: DropPosition =\n e.clientY < midpoint ? \"before\" : \"after\";\n\n if (\n lastOverRef.current !== id ||\n state.dragOverPosition !== position\n ) {\n lastOverRef.current = id;\n setState((s) => ({\n ...s,\n dragOverId: id,\n dragOverPosition: position,\n }));\n }\n },\n onDragLeave: (e) => {\n // dragleave fires when the cursor enters a child element too — only\n // clear if we're actually leaving the item element.\n const related = e.relatedTarget as Node | null;\n if (!related || !e.currentTarget.contains(related)) {\n if (lastOverRef.current === id) {\n lastOverRef.current = null;\n setState((s) => ({\n ...s,\n dragOverId: null,\n dragOverPosition: null,\n }));\n }\n }\n },\n onDrop: (e) => {\n const draggedId = e.dataTransfer.getData(dragType);\n e.preventDefault();\n e.stopPropagation();\n if (!draggedId || draggedId === id) {\n reset();\n return;\n }\n\n const fromIdx = items.findIndex((it) => getId(it) === draggedId);\n const toIdx = items.findIndex((it) => getId(it) === id);\n if (fromIdx < 0 || toIdx < 0) {\n reset();\n return;\n }\n\n const rect = e.currentTarget.getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position: DropPosition =\n e.clientY < midpoint ? \"before\" : \"after\";\n\n const next = [...items];\n const [moved] = next.splice(fromIdx, 1);\n // Recompute target index now that we removed `fromIdx`.\n let insertIdx = next.findIndex((it) => getId(it) === id);\n if (insertIdx < 0) insertIdx = next.length;\n if (position === \"after\") insertIdx += 1;\n next.splice(insertIdx, 0, moved);\n onReorder(next);\n reset();\n },\n }),\n [items, getId, onReorder, dragType, reset, state.dragOverPosition],\n );\n\n const isDragging = useCallback(\n (id: string) => state.draggingId === id,\n [state.draggingId],\n );\n\n const dropIndicator = useCallback(\n (id: string): DropPosition | null => {\n if (state.dragOverId !== id) return null;\n if (state.draggingId === id) return null;\n return state.dragOverPosition;\n },\n [state.dragOverId, state.draggingId, state.dragOverPosition],\n );\n\n return {\n ...state,\n itemHandlers,\n isDragging,\n dropIndicator,\n };\n}\n"]}