@vulcantech/forms 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2852 @@
1
+ import * as Yup from 'yup';
2
+ import { useFormikContext, Formik, Form, useField } from 'formik';
3
+ import { createContext, useContext, useEffect, useState, useRef, useMemo, useCallback } from 'react';
4
+ import { twMerge } from 'tailwind-merge';
5
+ import { Checkbox, RadioGroup, Select } from 'radix-ui';
6
+ import { BsCheck, BsChevronDown } from 'react-icons/bs';
7
+ import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
8
+ import DatePicker from 'react-datepicker';
9
+ import { set, parse, isValid, isWeekend, isSameDay, addDays, format } from 'date-fns';
10
+ import 'react-datepicker/dist/react-datepicker.css';
11
+ import { FiEyeOff, FiEye } from 'react-icons/fi';
12
+
13
+ var __defProp = Object.defineProperty;
14
+ var __defProps = Object.defineProperties;
15
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
16
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
17
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
18
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
19
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
20
+ var __spreadValues = (a, b) => {
21
+ for (var prop in b || (b = {}))
22
+ if (__hasOwnProp.call(b, prop))
23
+ __defNormalProp(a, prop, b[prop]);
24
+ if (__getOwnPropSymbols)
25
+ for (var prop of __getOwnPropSymbols(b)) {
26
+ if (__propIsEnum.call(b, prop))
27
+ __defNormalProp(a, prop, b[prop]);
28
+ }
29
+ return a;
30
+ };
31
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
32
+ var __restKey = (key) => typeof key === "symbol" ? key : key + "";
33
+ var __objRest = (source, exclude) => {
34
+ var target = {};
35
+ for (var prop in source)
36
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
37
+ target[prop] = source[prop];
38
+ if (source != null && __getOwnPropSymbols)
39
+ for (var prop of __getOwnPropSymbols(source)) {
40
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
41
+ target[prop] = source[prop];
42
+ }
43
+ return target;
44
+ };
45
+ var __async = (__this, __arguments, generator) => {
46
+ return new Promise((resolve, reject) => {
47
+ var fulfilled = (value) => {
48
+ try {
49
+ step(generator.next(value));
50
+ } catch (e) {
51
+ reject(e);
52
+ }
53
+ };
54
+ var rejected = (value) => {
55
+ try {
56
+ step(generator.throw(value));
57
+ } catch (e) {
58
+ reject(e);
59
+ }
60
+ };
61
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
62
+ step((generator = generator.apply(__this, __arguments)).next());
63
+ });
64
+ };
65
+
66
+ // src/types.ts
67
+ var DEFAULT_SENSITIVE_FIELD_CONFIG = {
68
+ ttlDays: 30,
69
+ viewerRoles: ["admin", "sensitive_data_viewer"],
70
+ inputMask: "ssn"
71
+ };
72
+ var DEFAULT_FILE_FIELD_CONFIG = {
73
+ accept: "image/*",
74
+ maxSizeBytes: 10 * 1024 * 1024,
75
+ multiple: false,
76
+ maxFiles: 5,
77
+ resizeImages: true,
78
+ maxImageWidth: 1600
79
+ };
80
+ var HONEYPOT_FIELD_NAME = "_hp_website";
81
+ var SAME_AS_TOGGLE_PREFIX = "_sameAs_";
82
+ var sameAsToggleKey = (sectionId) => `${SAME_AS_TOGGLE_PREFIX}${sectionId}`;
83
+ var DEFAULT_SPAM_PROTECTION = {
84
+ honeypot: true,
85
+ minSubmitTime: 3
86
+ };
87
+ var DEFAULT_FORM_STYLE = {
88
+ preset: "default",
89
+ borderRadius: "md",
90
+ spacing: "normal",
91
+ buttonVariant: "filled",
92
+ buttonPlacement: "below",
93
+ sectionDividers: false,
94
+ inputVariant: "outlined"
95
+ };
96
+ var NEWSLETTER_ALLOWED_FIELD_TYPES = ["email", "checkbox"];
97
+ var DEFAULT_NOTIFICATION_EMAIL_SUBJECT = "New Contact Form: {{name}}";
98
+ var DEFAULT_NOTIFICATION_EMAIL_HTML = `<!DOCTYPE html>
99
+ <html lang="en">
100
+ <head><meta charset="UTF-8" /></head>
101
+ <body style="font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;">
102
+ <div style="background: #4f46e5; color: white; padding: 20px; border-radius: 8px 8px 0 0;">
103
+ <h1 style="margin: 0; font-size: 20px;">New {{formName}} Submission</h1>
104
+ <p style="margin: 4px 0 0; opacity: 0.9; font-size: 14px;">{{projectName}}</p>
105
+ </div>
106
+ <div style="border: 1px solid #e5e7eb; border-top: none; padding: 20px; border-radius: 0 0 8px 8px;">
107
+ <table style="width: 100%; border-collapse: collapse;">
108
+ <tr>
109
+ <td style="padding: 8px 0; font-weight: 600; width: 120px; vertical-align: top;">Name:</td>
110
+ <td style="padding: 8px 0;">{{name}}</td>
111
+ </tr>
112
+ <tr>
113
+ <td style="padding: 8px 0; font-weight: 600; vertical-align: top;">Email:</td>
114
+ <td style="padding: 8px 0;"><a href="mailto:{{email}}">{{email}}</a></td>
115
+ </tr>
116
+ <tr>
117
+ <td style="padding: 8px 0; font-weight: 600; vertical-align: top;">Phone:</td>
118
+ <td style="padding: 8px 0;"><a href="tel:{{phone}}">{{phone}}</a></td>
119
+ </tr>
120
+ <tr>
121
+ <td style="padding: 8px 0; font-weight: 600; vertical-align: top;">Message:</td>
122
+ <td style="padding: 8px 0;">{{message}}</td>
123
+ </tr>
124
+ </table>
125
+ <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
126
+ <p style="font-size: 12px; color: #9ca3af; margin: 0;">
127
+ Sent via VulcanTech CMS &middot; <a href="https://cms.vulcantech.io">Dashboard</a>
128
+ </p>
129
+ </div>
130
+ </body>
131
+ </html>`;
132
+ var DEFAULT_NOTIFICATION_EMAIL_TEMPLATE = {
133
+ subject: DEFAULT_NOTIFICATION_EMAIL_SUBJECT,
134
+ html: DEFAULT_NOTIFICATION_EMAIL_HTML
135
+ };
136
+ var APPLICATION_STATUS_KEYS = [
137
+ "received",
138
+ "reviewing",
139
+ "approved",
140
+ "denied",
141
+ "pending-documents",
142
+ "withdrawn"
143
+ ];
144
+ function buildDefaultStatusEmailHtml(bodyHtml) {
145
+ return `<!DOCTYPE html>
146
+ <html lang="en">
147
+ <head><meta charset="UTF-8" /></head>
148
+ <body style="font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;">
149
+ <div style="background: #4f46e5; color: white; padding: 20px; border-radius: 8px 8px 0 0;">
150
+ <h1 style="margin: 0; font-size: 20px;">{{projectName}}</h1>
151
+ <p style="margin: 4px 0 0; opacity: 0.9; font-size: 14px;">Application update</p>
152
+ </div>
153
+ <div style="border: 1px solid #e5e7eb; border-top: none; padding: 20px; border-radius: 0 0 8px 8px;">
154
+ <p style="margin-top: 0;">Hi {{applicantName}},</p>
155
+ ${bodyHtml}
156
+ <p style="font-size: 13px; color: #6b7280; margin: 20px 0 0;">
157
+ Reference number: <strong style="font-family: monospace;">{{referenceNumber}}</strong>
158
+ </p>
159
+ <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
160
+ <p style="font-size: 12px; color: #9ca3af; margin: 0;">
161
+ This is an automated message from {{projectName}}.
162
+ </p>
163
+ </div>
164
+ </body>
165
+ </html>`;
166
+ }
167
+ var DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES = {
168
+ received: {
169
+ subject: "We've received your application \u2014 {{referenceNumber}}",
170
+ html: buildDefaultStatusEmailHtml(
171
+ `<p>Thanks for applying to {{projectName}}. We've received your submission and our team will be in touch as it moves through review.</p>`
172
+ )
173
+ },
174
+ reviewing: {
175
+ subject: "Your application is under review \u2014 {{referenceNumber}}",
176
+ html: buildDefaultStatusEmailHtml(
177
+ `<p>Good news \u2014 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>`
178
+ )
179
+ },
180
+ approved: {
181
+ subject: "Your application has been approved \u2014 {{referenceNumber}}",
182
+ html: buildDefaultStatusEmailHtml(
183
+ `<p>Congratulations \u2014 your application has been <strong style="color: #047857;">approved</strong>. We'll follow up shortly with next steps.</p>`
184
+ )
185
+ },
186
+ denied: {
187
+ subject: "Update on your application \u2014 {{referenceNumber}}",
188
+ html: buildDefaultStatusEmailHtml(
189
+ `<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>
190
+ <p>We appreciate your interest and wish you the best.</p>`
191
+ )
192
+ },
193
+ "pending-documents": {
194
+ subject: "Additional documents needed \u2014 {{referenceNumber}}",
195
+ html: buildDefaultStatusEmailHtml(
196
+ `<p>To continue reviewing your application we need a few more documents from you:</p>
197
+ <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>
198
+ <p>Reply to this email with the requested items and we'll resume review as soon as they arrive.</p>`
199
+ )
200
+ },
201
+ withdrawn: {
202
+ subject: "Your application has been withdrawn \u2014 {{referenceNumber}}",
203
+ html: buildDefaultStatusEmailHtml(
204
+ `<p>Per request, your application to {{projectName}} has been withdrawn. If this wasn't expected, please reply and let us know.</p>`
205
+ )
206
+ }
207
+ };
208
+ function parseFormDefinition(json) {
209
+ return json;
210
+ }
211
+
212
+ // src/utils/visibility.ts
213
+ function isVisibilityConditionMet(condition, watchedValue) {
214
+ var _a;
215
+ const operator = (_a = condition.operator) != null ? _a : "equals";
216
+ switch (operator) {
217
+ case "greater-than":
218
+ case "less-than": {
219
+ if (typeof watchedValue === "boolean") return false;
220
+ const actual = typeof watchedValue === "number" ? watchedValue : parseFloat(String(watchedValue != null ? watchedValue : ""));
221
+ const expected = parseFloat(String(condition.value));
222
+ if (Number.isNaN(actual) || Number.isNaN(expected)) return false;
223
+ return operator === "greater-than" ? actual > expected : actual < expected;
224
+ }
225
+ case "not-equals":
226
+ return watchedValue !== condition.value;
227
+ case "equals":
228
+ default:
229
+ return watchedValue === condition.value;
230
+ }
231
+ }
232
+
233
+ // src/schema/buildYupSchema.ts
234
+ function getBaseSchema(field) {
235
+ var _a, _b, _c;
236
+ switch (field.type) {
237
+ case "number":
238
+ return Yup.number().transform(
239
+ (value, original) => original === "" || original === null ? void 0 : value
240
+ ).typeError(`${field.label} must be a number`);
241
+ case "checkbox":
242
+ return Yup.boolean();
243
+ case "url":
244
+ return Yup.string().url(`${field.label} must be a valid URL`);
245
+ case "datetime":
246
+ return Yup.string();
247
+ case "select":
248
+ case "radio": {
249
+ const allowed = ((_a = field.options) != null ? _a : []).map((o) => o.value);
250
+ if (allowed.length === 0) return Yup.string();
251
+ return Yup.string().oneOf(
252
+ [...allowed, ""],
253
+ `${field.label} has an invalid selection`
254
+ );
255
+ }
256
+ case "sensitive": {
257
+ let schema = Yup.string();
258
+ if (((_b = field.sensitiveConfig) == null ? void 0 : _b.inputMask) === "ssn" || field.transform === "ssn") {
259
+ schema = schema.matches(
260
+ /^\d{3}-\d{2}-\d{4}$/,
261
+ `${field.label} must be a valid Social Security number`
262
+ );
263
+ }
264
+ return schema;
265
+ }
266
+ case "file":
267
+ if ((_c = field.fileConfig) == null ? void 0 : _c.multiple) {
268
+ return Yup.array().of(Yup.string().url()).default([]);
269
+ }
270
+ return Yup.string();
271
+ default:
272
+ return Yup.string();
273
+ }
274
+ }
275
+ function applyValidationRule(schema, rule, field) {
276
+ switch (rule.type) {
277
+ case "required":
278
+ if (field.type === "checkbox" && schema instanceof Yup.BooleanSchema) {
279
+ return schema.required(rule.message).oneOf([true], rule.message);
280
+ }
281
+ return schema.required(rule.message);
282
+ case "email":
283
+ if (schema instanceof Yup.StringSchema) {
284
+ return schema.email(rule.message);
285
+ }
286
+ return schema;
287
+ case "phone":
288
+ if (schema instanceof Yup.StringSchema) {
289
+ return schema.matches(
290
+ /^[\d\s\-()+ .]+$/,
291
+ rule.message
292
+ );
293
+ }
294
+ return schema;
295
+ case "min":
296
+ if (schema instanceof Yup.NumberSchema && typeof rule.value === "number") {
297
+ return schema.min(rule.value, rule.message);
298
+ }
299
+ return schema;
300
+ case "max":
301
+ if (schema instanceof Yup.NumberSchema && typeof rule.value === "number") {
302
+ return schema.max(rule.value, rule.message);
303
+ }
304
+ return schema;
305
+ case "minLength":
306
+ if (schema instanceof Yup.StringSchema && typeof rule.value === "number") {
307
+ return schema.min(rule.value, rule.message);
308
+ }
309
+ return schema;
310
+ case "maxLength":
311
+ if (schema instanceof Yup.StringSchema && typeof rule.value === "number") {
312
+ return schema.max(rule.value, rule.message);
313
+ }
314
+ return schema;
315
+ case "pattern":
316
+ if (schema instanceof Yup.StringSchema && typeof rule.value === "string") {
317
+ try {
318
+ return schema.matches(new RegExp(rule.value), rule.message);
319
+ } catch (e) {
320
+ console.warn(
321
+ `[forms] Invalid pattern for field "${field.id}": ${rule.value}`
322
+ );
323
+ return schema;
324
+ }
325
+ }
326
+ return schema;
327
+ case "notEquals":
328
+ if (schema instanceof Yup.StringSchema && rule.value !== void 0) {
329
+ return schema.notOneOf([String(rule.value)], rule.message);
330
+ }
331
+ if (schema instanceof Yup.NumberSchema && typeof rule.value === "number") {
332
+ return schema.notOneOf([rule.value], rule.message);
333
+ }
334
+ return schema;
335
+ default:
336
+ return schema;
337
+ }
338
+ }
339
+ function buildYupSchema(definition) {
340
+ var _a;
341
+ const shape = {};
342
+ for (const section of definition.sections) {
343
+ const hideToggleKey = ((_a = section.sameAs) == null ? void 0 : _a.behavior) === "hide" ? sameAsToggleKey(section.id) : null;
344
+ const hiddenTargetIds = hideToggleKey ? new Set(Object.keys(section.sameAs.fieldMap)) : null;
345
+ for (const field of section.fields) {
346
+ let schema = getBaseSchema(field);
347
+ for (const rule of field.validation) {
348
+ schema = applyValidationRule(schema, rule, field);
349
+ }
350
+ const baseSchema = getBaseSchema(field);
351
+ if (field.showWhen) {
352
+ const condition = field.showWhen;
353
+ shape[field.id] = Yup.mixed().when(condition.fieldId, {
354
+ is: (value) => isVisibilityConditionMet(condition, value),
355
+ then: () => schema,
356
+ otherwise: () => baseSchema.notRequired()
357
+ });
358
+ } else if (hideToggleKey && (hiddenTargetIds == null ? void 0 : hiddenTargetIds.has(field.id))) {
359
+ shape[field.id] = Yup.mixed().when(hideToggleKey, {
360
+ is: true,
361
+ then: () => baseSchema.notRequired(),
362
+ otherwise: () => schema
363
+ });
364
+ } else {
365
+ shape[field.id] = schema;
366
+ }
367
+ }
368
+ }
369
+ return Yup.object().shape(shape);
370
+ }
371
+
372
+ // src/utils/initialValues.ts
373
+ function buildInitialValues(definition) {
374
+ var _a;
375
+ const values = {};
376
+ for (const section of definition.sections) {
377
+ if (section.sameAs) values[sameAsToggleKey(section.id)] = false;
378
+ for (const field of section.fields) {
379
+ if (field.type === "checkbox") {
380
+ values[field.id] = field.defaultValue === "true";
381
+ } else if (field.type === "datetime") {
382
+ values[field.id] = field.defaultValue || "";
383
+ } else if (field.type === "sensitive") {
384
+ values[field.id] = "";
385
+ } else if (field.type === "file") {
386
+ values[field.id] = ((_a = field.fileConfig) == null ? void 0 : _a.multiple) ? [] : "";
387
+ } else {
388
+ values[field.id] = field.defaultValue || "";
389
+ }
390
+ }
391
+ }
392
+ return values;
393
+ }
394
+
395
+ // src/utils/transforms.ts
396
+ function applyTransform(value, transform) {
397
+ if (!value) return "";
398
+ if (!transform || transform === "full") return value;
399
+ switch (transform) {
400
+ case "extractFirstName":
401
+ return value.trim().split(/\s+/)[0] || value;
402
+ case "extractLastName": {
403
+ const parts = value.trim().split(/\s+/);
404
+ return parts.length > 1 ? parts.slice(1).join(" ") : "";
405
+ }
406
+ case "extractStreet":
407
+ case "extractCity":
408
+ case "extractState":
409
+ case "extractZip":
410
+ return extractAddressPart(value, transform);
411
+ default:
412
+ return value;
413
+ }
414
+ }
415
+ function extractAddressPart(value, transform) {
416
+ var _a, _b, _c, _d;
417
+ const parts = value.split(",").map((p) => p.trim());
418
+ if (transform === "extractStreet") return (_a = parts[0]) != null ? _a : "";
419
+ if (transform === "extractCity") return (_b = parts[1]) != null ? _b : "";
420
+ const tail = ((_c = parts[2]) != null ? _c : "").split(/\s+/).filter(Boolean);
421
+ if (transform === "extractState") return (_d = tail[0]) != null ? _d : "";
422
+ if (transform === "extractZip") return tail.slice(1).join(" ") || "";
423
+ return "";
424
+ }
425
+
426
+ // src/utils/redirect.ts
427
+ function getSafeRedirectUrl(raw) {
428
+ if (typeof raw !== "string") return null;
429
+ const url = raw.trim();
430
+ if (!url) return null;
431
+ if (url.startsWith("/") && !url.startsWith("//")) return url;
432
+ try {
433
+ const parsed = new URL(url);
434
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
435
+ return url;
436
+ }
437
+ } catch (e) {
438
+ }
439
+ return null;
440
+ }
441
+
442
+ // src/utils/textTransforms.ts
443
+ function formatSsn(raw) {
444
+ const digits = raw.replace(/\D/g, "").slice(0, 9);
445
+ if (digits.length <= 3) return digits;
446
+ if (digits.length <= 5) return `${digits.slice(0, 3)}-${digits.slice(3)}`;
447
+ return `${digits.slice(0, 3)}-${digits.slice(3, 5)}-${digits.slice(5)}`;
448
+ }
449
+ function formatUsPhone(raw) {
450
+ const digits = raw.replace(/[^\d]/g, "");
451
+ const onlyNums = (digits.length === 11 && digits.startsWith("1") ? digits.slice(1) : digits).slice(0, 10);
452
+ if (onlyNums.length > 6) {
453
+ return `(${onlyNums.slice(0, 3)}) ${onlyNums.slice(3, 6)} - ${onlyNums.slice(6, 10)}`;
454
+ }
455
+ if (onlyNums.length > 3) {
456
+ return `(${onlyNums.slice(0, 3)}) ${onlyNums.slice(3)}`;
457
+ }
458
+ if (onlyNums.length > 0) {
459
+ return `(${onlyNums}`;
460
+ }
461
+ return "";
462
+ }
463
+ function applyTextTransform(value, transform) {
464
+ switch (transform) {
465
+ case "capitalize-sentences":
466
+ return value.replace(
467
+ /(^|\. *)([a-z])/g,
468
+ (letter) => letter.toUpperCase()
469
+ );
470
+ case "capitalize-words":
471
+ return value.replace(
472
+ /^([a-z])|\s+([a-z])/g,
473
+ (letter) => letter.toUpperCase()
474
+ );
475
+ case "phone-number":
476
+ return formatUsPhone(value);
477
+ case "ssn":
478
+ return formatSsn(value);
479
+ default:
480
+ return value;
481
+ }
482
+ }
483
+
484
+ // src/utils/renderEmailTemplate.ts
485
+ function escapeHtml(value) {
486
+ if (value === null || value === void 0) return "";
487
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
488
+ }
489
+ function renderEmailTemplate(template, variables, options = {}) {
490
+ const shouldEscape = options.escape !== false;
491
+ return template.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (_match, key) => {
492
+ const value = variables[key];
493
+ if (value === void 0 || value === null || value === "") return "";
494
+ return shouldEscape ? escapeHtml(value) : String(value);
495
+ });
496
+ }
497
+ function buildEmailTemplateVariables(args) {
498
+ var _a, _b;
499
+ const { definition, projectName, submission, submittedAt } = args;
500
+ const vars = {
501
+ projectName,
502
+ formName: (_b = (_a = args.formName) != null ? _a : definition == null ? void 0 : definition.name) != null ? _b : "Contact Form",
503
+ submittedAt: submittedAt != null ? submittedAt : (/* @__PURE__ */ new Date()).toISOString()
504
+ };
505
+ for (const [key, value] of Object.entries(submission)) {
506
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
507
+ vars[key] = value;
508
+ }
509
+ }
510
+ if (definition == null ? void 0 : definition.sections) {
511
+ for (const section of definition.sections) {
512
+ for (const field of section.fields) {
513
+ const value = submission[field.id];
514
+ if (value === void 0 || value === null) continue;
515
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
516
+ continue;
517
+ }
518
+ const slug = labelToSlug(field.label);
519
+ if (slug && vars[slug] === void 0) vars[slug] = value;
520
+ }
521
+ }
522
+ }
523
+ return vars;
524
+ }
525
+ function labelToSlug(label) {
526
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
527
+ }
528
+ var CORE_EMAIL_TEMPLATE_VARIABLES = [
529
+ {
530
+ key: "projectName",
531
+ description: "Project (site) display name.",
532
+ example: "Acme Co."
533
+ },
534
+ {
535
+ key: "formName",
536
+ description: "Name of the form that was submitted.",
537
+ example: "Contact Form"
538
+ },
539
+ {
540
+ key: "submittedAt",
541
+ description: "Submission timestamp (ISO 8601).",
542
+ example: (/* @__PURE__ */ new Date()).toISOString()
543
+ },
544
+ {
545
+ key: "name",
546
+ description: "Submitter's name.",
547
+ example: "Jane Doe"
548
+ },
549
+ {
550
+ key: "email",
551
+ description: "Submitter's email.",
552
+ example: "jane@example.com"
553
+ },
554
+ {
555
+ key: "phone",
556
+ description: "Submitter's phone (if collected).",
557
+ example: "555-123-4567"
558
+ },
559
+ {
560
+ key: "message",
561
+ description: "Free-text message body (if collected).",
562
+ example: "I'd like to schedule a consultation."
563
+ },
564
+ {
565
+ key: "serviceType",
566
+ description: "Selected service / category (if collected).",
567
+ example: "Roof Repair"
568
+ }
569
+ ];
570
+ var SAMPLE_EMAIL_TEMPLATE_VARIABLES = {
571
+ projectName: "Acme Co.",
572
+ formName: "Contact Form",
573
+ submittedAt: (/* @__PURE__ */ new Date()).toISOString(),
574
+ name: "Jane Doe",
575
+ email: "jane@example.com",
576
+ phone: "555-123-4567",
577
+ message: "I'd like to schedule a consultation about your services.",
578
+ serviceType: "Roof Repair"
579
+ };
580
+ function renderNotificationEmail(template, variables) {
581
+ const subject = renderEmailTemplate(template.subject, variables, {
582
+ escape: false
583
+ }).replace(/[\r\n]+/g, " ");
584
+ return {
585
+ subject,
586
+ html: renderEmailTemplate(template.html, variables)
587
+ };
588
+ }
589
+
590
+ // src/crypto/sensitive.ts
591
+ function bufferToBase64(buf) {
592
+ const bytes = new Uint8Array(buf);
593
+ let binary = "";
594
+ for (let i = 0; i < bytes.byteLength; i += 1) {
595
+ binary += String.fromCharCode(bytes[i]);
596
+ }
597
+ return btoa(binary);
598
+ }
599
+ function base64ToBuffer(b64) {
600
+ const binary = atob(b64);
601
+ const bytes = new Uint8Array(binary.length);
602
+ for (let i = 0; i < binary.length; i += 1) {
603
+ bytes[i] = binary.charCodeAt(i);
604
+ }
605
+ return bytes.buffer;
606
+ }
607
+ function importTransportPublicKey(jwk) {
608
+ return __async(this, null, function* () {
609
+ return crypto.subtle.importKey(
610
+ "jwk",
611
+ jwk,
612
+ { name: "RSA-OAEP", hash: "SHA-256" },
613
+ false,
614
+ ["wrapKey", "encrypt"]
615
+ );
616
+ });
617
+ }
618
+ function encryptSensitiveValue(plaintext, publicKey) {
619
+ return __async(this, null, function* () {
620
+ if (typeof crypto === "undefined" || !crypto.subtle) {
621
+ throw new Error(
622
+ "Web Crypto API is unavailable \u2014 sensitive fields require a secure browser context"
623
+ );
624
+ }
625
+ if (typeof plaintext !== "string" || plaintext.length === 0) {
626
+ throw new Error("encryptSensitiveValue: plaintext must be a non-empty string");
627
+ }
628
+ const rsaKey = yield importTransportPublicKey(publicKey.jwk);
629
+ const dataKey = yield crypto.subtle.generateKey(
630
+ { name: "AES-GCM", length: 256 },
631
+ true,
632
+ ["encrypt"]
633
+ );
634
+ const iv = crypto.getRandomValues(new Uint8Array(12));
635
+ const encoded = new TextEncoder().encode(plaintext);
636
+ const ciphertext = yield crypto.subtle.encrypt(
637
+ { name: "AES-GCM", iv },
638
+ dataKey,
639
+ encoded
640
+ );
641
+ const wrappedKey = yield crypto.subtle.wrapKey("raw", dataKey, rsaKey, {
642
+ name: "RSA-OAEP"
643
+ });
644
+ return {
645
+ v: "v1",
646
+ kid: publicKey.kid,
647
+ wrappedKey: bufferToBase64(wrappedKey),
648
+ iv: bufferToBase64(iv.buffer),
649
+ ciphertext: bufferToBase64(ciphertext),
650
+ last4: deriveLast4(plaintext)
651
+ };
652
+ });
653
+ }
654
+ function deriveLast4(plaintext) {
655
+ const digits = plaintext.replace(/\D/g, "");
656
+ return digits.slice(-4).padStart(4, "\u2022");
657
+ }
658
+ var FormStyleContext = createContext(DEFAULT_FORM_STYLE);
659
+ var useFormStyle = () => useContext(FormStyleContext);
660
+ var FormStyleProvider = FormStyleContext.Provider;
661
+ var FormPreviewOverridesContext = createContext(
662
+ null
663
+ );
664
+ var useFormPreviewOverrides = () => useContext(FormPreviewOverridesContext);
665
+ var FormPreviewOverridesProvider = FormPreviewOverridesContext.Provider;
666
+
667
+ // src/renderer/cssVars.ts
668
+ var FORM_CSS_VAR = {
669
+ formBg: "--form-bg",
670
+ inputBg: "--form-input-bg",
671
+ inputBorder: "--form-input-border",
672
+ inputFocusBorder: "--form-input-focus-border",
673
+ inputText: "--form-input-text",
674
+ placeholder: "--form-placeholder",
675
+ labelText: "--form-label-text",
676
+ error: "--form-error",
677
+ buttonBg: "--form-button-bg",
678
+ buttonText: "--form-button-text"
679
+ };
680
+ var FORM_DEFAULT_COLOR = {
681
+ formBg: "transparent",
682
+ inputBg: "inherit",
683
+ inputBorder: "#d1d5db",
684
+ inputFocusBorder: "#2563eb",
685
+ inputText: "inherit",
686
+ placeholder: "#9ca3af",
687
+ labelText: "inherit",
688
+ error: "#ef4444",
689
+ buttonBg: "#2563eb",
690
+ buttonText: "#ffffff"
691
+ };
692
+ function ref(name, fallback) {
693
+ return `var(${name}, ${fallback})`;
694
+ }
695
+ var FORM_VAR = {
696
+ formBg: ref(FORM_CSS_VAR.formBg, FORM_DEFAULT_COLOR.formBg),
697
+ inputBg: ref(FORM_CSS_VAR.inputBg, FORM_DEFAULT_COLOR.inputBg),
698
+ inputBorder: ref(FORM_CSS_VAR.inputBorder, FORM_DEFAULT_COLOR.inputBorder),
699
+ inputFocusBorder: ref(
700
+ FORM_CSS_VAR.inputFocusBorder,
701
+ FORM_DEFAULT_COLOR.inputFocusBorder
702
+ ),
703
+ inputText: ref(FORM_CSS_VAR.inputText, FORM_DEFAULT_COLOR.inputText),
704
+ placeholder: ref(FORM_CSS_VAR.placeholder, FORM_DEFAULT_COLOR.placeholder),
705
+ labelText: ref(FORM_CSS_VAR.labelText, FORM_DEFAULT_COLOR.labelText),
706
+ error: ref(FORM_CSS_VAR.error, FORM_DEFAULT_COLOR.error),
707
+ buttonBg: ref(FORM_CSS_VAR.buttonBg, FORM_DEFAULT_COLOR.buttonBg),
708
+ buttonText: ref(FORM_CSS_VAR.buttonText, FORM_DEFAULT_COLOR.buttonText)
709
+ };
710
+ function buildFormCssVars(style, previewBg) {
711
+ const out = {};
712
+ const effectiveFormBg = previewBg != null ? previewBg : style.formBackgroundColor;
713
+ if (effectiveFormBg) out[FORM_CSS_VAR.formBg] = effectiveFormBg;
714
+ const effectiveInputBg = previewBg != null ? previewBg : style.inputBgColor;
715
+ if (effectiveInputBg) out[FORM_CSS_VAR.inputBg] = effectiveInputBg;
716
+ if (style.inputBorderColor)
717
+ out[FORM_CSS_VAR.inputBorder] = style.inputBorderColor;
718
+ if (style.inputFocusColor)
719
+ out[FORM_CSS_VAR.inputFocusBorder] = style.inputFocusColor;
720
+ if (style.inputTextColor)
721
+ out[FORM_CSS_VAR.inputText] = style.inputTextColor;
722
+ if (style.placeholderColor)
723
+ out[FORM_CSS_VAR.placeholder] = style.placeholderColor;
724
+ if (style.labelColor) out[FORM_CSS_VAR.labelText] = style.labelColor;
725
+ if (style.errorColor) out[FORM_CSS_VAR.error] = style.errorColor;
726
+ if (style.buttonColor) out[FORM_CSS_VAR.buttonBg] = style.buttonColor;
727
+ if (style.buttonTextColor)
728
+ out[FORM_CSS_VAR.buttonText] = style.buttonTextColor;
729
+ return out;
730
+ }
731
+
732
+ // src/renderer/fields/useInputStyles.ts
733
+ var placeholderClass = "placeholder:[color:var(--form-placeholder,#9ca3af)]";
734
+ var textClass = "text-[color:var(--form-input-text,inherit)]";
735
+ function getVariantClasses(style) {
736
+ switch (style.inputVariant) {
737
+ case "stacked":
738
+ return {
739
+ inputClass: twMerge(
740
+ "w-full rounded-lg border px-4 py-3 text-base transition focus:outline-none disabled:cursor-not-allowed",
741
+ textClass,
742
+ placeholderClass
743
+ ),
744
+ inputStyle: {
745
+ borderColor: FORM_VAR.inputBorder,
746
+ backgroundColor: FORM_VAR.inputBg
747
+ },
748
+ labelClass: "mb-1 block text-sm font-medium"
749
+ };
750
+ case "filled":
751
+ return {
752
+ inputClass: twMerge(
753
+ "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",
754
+ textClass,
755
+ placeholderClass
756
+ ),
757
+ inputStyle: {
758
+ borderStyle: "solid",
759
+ borderWidth: 0,
760
+ borderBottomWidth: 2,
761
+ borderBottomColor: FORM_VAR.inputBorder,
762
+ backgroundColor: FORM_VAR.inputBg
763
+ },
764
+ labelClass: "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]"
765
+ };
766
+ case "underlined":
767
+ return {
768
+ inputClass: twMerge(
769
+ "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",
770
+ textClass,
771
+ placeholderClass
772
+ ),
773
+ inputStyle: {
774
+ borderStyle: "solid",
775
+ borderWidth: 0,
776
+ borderBottomWidth: 2,
777
+ borderBottomColor: FORM_VAR.inputBorder
778
+ },
779
+ labelClass: "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]"
780
+ };
781
+ case "outlined":
782
+ default:
783
+ return {
784
+ inputClass: twMerge(
785
+ "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",
786
+ textClass,
787
+ placeholderClass
788
+ ),
789
+ inputStyle: {
790
+ borderStyle: "solid",
791
+ borderWidth: 1,
792
+ borderColor: FORM_VAR.inputBorder
793
+ },
794
+ // Label must paint a solid bg on top of the input border. `bg-inherit`
795
+ // doesn't work — wrapper divs between the form root and the label
796
+ // have transparent bgs, so `inherit` resolves to transparent. Read
797
+ // from `--form-input-bg`, which DynamicForm publishes on the form
798
+ // root from the resolved input background (or the editor preview
799
+ // override). The fallback matches FORM_DEFAULT_COLOR.inputBg.
800
+ labelClass: "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]"
801
+ };
802
+ }
803
+ }
804
+ function getFocusStyle(style) {
805
+ if (style.inputVariant === "filled" || style.inputVariant === "underlined") {
806
+ return { borderBottomColor: FORM_VAR.inputFocusBorder };
807
+ }
808
+ if (style.inputVariant === "stacked") {
809
+ return {
810
+ borderColor: FORM_VAR.inputFocusBorder,
811
+ boxShadow: "0 0 0 2px rgba(37, 99, 235, 0.2)"
812
+ };
813
+ }
814
+ return { borderColor: FORM_VAR.inputFocusBorder };
815
+ }
816
+ function useInputStyles() {
817
+ const style = useFormStyle();
818
+ const variant = getVariantClasses(style);
819
+ const isStacked = style.inputVariant === "stacked";
820
+ return {
821
+ wrapperClass: isStacked ? "flex w-full flex-col" : "group relative flex w-full flex-col pt-3",
822
+ inputClass: isStacked ? twMerge("block w-full", variant.inputClass) : twMerge(
823
+ "peer m-0 mb-3 block min-h-8 w-full overflow-hidden",
824
+ variant.inputClass
825
+ ),
826
+ inputStyle: variant.inputStyle,
827
+ inputFocusStyle: getFocusStyle(style),
828
+ labelClass: variant.labelClass,
829
+ labelStyle: { color: FORM_VAR.labelText },
830
+ errorStyle: { color: FORM_VAR.error },
831
+ accentColor: FORM_VAR.inputFocusBorder,
832
+ isStacked
833
+ };
834
+ }
835
+ function getErrorOutlineStyle(hasError, variant) {
836
+ if (!hasError) return {};
837
+ if (variant === "stacked") {
838
+ return {
839
+ outline: `2px solid ${FORM_VAR.error}`,
840
+ outlineOffset: "-2px"
841
+ };
842
+ }
843
+ if (variant === "outlined") {
844
+ return {
845
+ outline: `1px solid ${FORM_VAR.error}`,
846
+ outlineOffset: "-1px",
847
+ borderColor: FORM_VAR.error
848
+ };
849
+ }
850
+ return {
851
+ borderBottomColor: FORM_VAR.error
852
+ };
853
+ }
854
+ var StyledInput = ({
855
+ id,
856
+ label,
857
+ placeholder,
858
+ type = "text",
859
+ value,
860
+ error,
861
+ touched,
862
+ disabled,
863
+ onChange,
864
+ onBlur
865
+ }) => {
866
+ const [focused, setFocused] = useState(false);
867
+ const style = useFormStyle();
868
+ const styles = useInputStyles();
869
+ const hasError = !!(error && touched);
870
+ const borderStyle = __spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, style.inputVariant));
871
+ if (styles.isStacked) {
872
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
873
+ /* @__PURE__ */ jsx("label", { htmlFor: id, className: styles.labelClass, style: styles.labelStyle, children: label }),
874
+ /* @__PURE__ */ jsx(
875
+ "input",
876
+ {
877
+ className: styles.inputClass,
878
+ style: borderStyle,
879
+ id,
880
+ name: id,
881
+ type,
882
+ placeholder,
883
+ value,
884
+ disabled,
885
+ onChange,
886
+ onFocus: () => setFocused(true),
887
+ onBlur: (e) => {
888
+ setFocused(false);
889
+ onBlur(e);
890
+ }
891
+ }
892
+ ),
893
+ hasError && /* @__PURE__ */ jsx(
894
+ "span",
895
+ {
896
+ className: twMerge("mt-1 text-xs", "text-red-600 dark:text-red-400"),
897
+ style: styles.errorStyle,
898
+ children: error
899
+ }
900
+ )
901
+ ] });
902
+ }
903
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
904
+ /* @__PURE__ */ jsxs("label", { htmlFor: id, className: "relative inline-block", children: [
905
+ /* @__PURE__ */ jsx(
906
+ "input",
907
+ {
908
+ className: styles.inputClass,
909
+ style: borderStyle,
910
+ id,
911
+ name: id,
912
+ type,
913
+ placeholder: placeholder || label,
914
+ value,
915
+ disabled,
916
+ onChange,
917
+ onFocus: () => setFocused(true),
918
+ onBlur: (e) => {
919
+ setFocused(false);
920
+ onBlur(e);
921
+ }
922
+ }
923
+ ),
924
+ /* @__PURE__ */ jsx("span", { className: styles.labelClass, style: styles.labelStyle, children: label })
925
+ ] }),
926
+ hasError && /* @__PURE__ */ jsx("span", { className: "mt-[-8px] text-xs", style: styles.errorStyle, children: error })
927
+ ] });
928
+ };
929
+ var TextField = ({ field: fieldDef, disabled }) => {
930
+ const [field, meta] = useField(fieldDef.id);
931
+ const handleChange = (e) => {
932
+ e.target.value = applyTextTransform(e.target.value, fieldDef.transform);
933
+ field.onChange(e);
934
+ };
935
+ return /* @__PURE__ */ jsx(
936
+ StyledInput,
937
+ {
938
+ id: fieldDef.id,
939
+ label: fieldDef.label,
940
+ placeholder: fieldDef.placeholder,
941
+ value: field.value,
942
+ error: meta.error,
943
+ touched: meta.touched,
944
+ disabled,
945
+ onChange: handleChange,
946
+ onBlur: field.onBlur
947
+ }
948
+ );
949
+ };
950
+ var EmailField = ({ field: fieldDef, disabled }) => {
951
+ const [field, meta] = useField(fieldDef.id);
952
+ return /* @__PURE__ */ jsx(
953
+ StyledInput,
954
+ {
955
+ id: fieldDef.id,
956
+ label: fieldDef.label,
957
+ placeholder: fieldDef.placeholder,
958
+ type: "email",
959
+ value: field.value,
960
+ error: meta.error,
961
+ touched: meta.touched,
962
+ disabled,
963
+ onChange: field.onChange,
964
+ onBlur: field.onBlur
965
+ }
966
+ );
967
+ };
968
+ var PhoneField = ({ field: fieldDef, disabled }) => {
969
+ var _a, _b;
970
+ const [field, meta, helpers] = useField(fieldDef.id);
971
+ const [focused, setFocused] = useState(false);
972
+ const formStyle = useFormStyle();
973
+ const styles = useInputStyles();
974
+ const hasError = !!(meta.error && meta.touched);
975
+ const borderStyle = __spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, formStyle.inputVariant));
976
+ const handleChange = (e) => {
977
+ helpers.setValue(formatUsPhone(e.target.value));
978
+ };
979
+ if (styles.isStacked) {
980
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
981
+ /* @__PURE__ */ jsx(
982
+ "label",
983
+ {
984
+ htmlFor: fieldDef.id,
985
+ className: styles.labelClass,
986
+ style: styles.labelStyle,
987
+ children: fieldDef.label
988
+ }
989
+ ),
990
+ /* @__PURE__ */ jsx(
991
+ "input",
992
+ {
993
+ className: styles.inputClass,
994
+ style: borderStyle,
995
+ id: fieldDef.id,
996
+ name: fieldDef.id,
997
+ type: "tel",
998
+ placeholder: fieldDef.placeholder,
999
+ value: (_a = field.value) != null ? _a : "",
1000
+ disabled,
1001
+ onChange: handleChange,
1002
+ onFocus: () => setFocused(true),
1003
+ onBlur: (e) => {
1004
+ setFocused(false);
1005
+ field.onBlur(e);
1006
+ }
1007
+ }
1008
+ ),
1009
+ hasError && /* @__PURE__ */ jsx(
1010
+ "span",
1011
+ {
1012
+ className: twMerge("mt-1 text-xs", "text-red-600 dark:text-red-400"),
1013
+ style: styles.errorStyle,
1014
+ children: meta.error
1015
+ }
1016
+ )
1017
+ ] });
1018
+ }
1019
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
1020
+ /* @__PURE__ */ jsxs("label", { htmlFor: fieldDef.id, className: "relative inline-block bg-inherit", children: [
1021
+ /* @__PURE__ */ jsx(
1022
+ "input",
1023
+ {
1024
+ className: styles.inputClass,
1025
+ style: borderStyle,
1026
+ id: fieldDef.id,
1027
+ name: fieldDef.id,
1028
+ type: "tel",
1029
+ placeholder: fieldDef.placeholder || fieldDef.label,
1030
+ value: (_b = field.value) != null ? _b : "",
1031
+ onChange: handleChange,
1032
+ onFocus: () => setFocused(true),
1033
+ onBlur: (e) => {
1034
+ setFocused(false);
1035
+ field.onBlur(e);
1036
+ }
1037
+ }
1038
+ ),
1039
+ /* @__PURE__ */ jsx("span", { className: styles.labelClass, style: styles.labelStyle, children: fieldDef.label })
1040
+ ] }),
1041
+ hasError && /* @__PURE__ */ jsx("span", { className: "mt-[-8px] text-xs", style: styles.errorStyle, children: meta.error })
1042
+ ] });
1043
+ };
1044
+ var UrlField = ({ field: fieldDef, disabled }) => {
1045
+ const [field, meta] = useField(fieldDef.id);
1046
+ return /* @__PURE__ */ jsx(
1047
+ StyledInput,
1048
+ {
1049
+ id: fieldDef.id,
1050
+ label: fieldDef.label,
1051
+ placeholder: fieldDef.placeholder || "https://example.com",
1052
+ type: "url",
1053
+ value: field.value,
1054
+ error: meta.error,
1055
+ touched: meta.touched,
1056
+ disabled,
1057
+ onChange: field.onChange,
1058
+ onBlur: field.onBlur
1059
+ }
1060
+ );
1061
+ };
1062
+ var AddressField = ({ field: fieldDef, disabled }) => {
1063
+ var _a;
1064
+ const [field, meta] = useField(fieldDef.id);
1065
+ const [focused, setFocused] = useState(false);
1066
+ const handleChange = (e) => {
1067
+ e.target.value = applyTextTransform(e.target.value, fieldDef.transform);
1068
+ field.onChange(e);
1069
+ };
1070
+ const formStyle = useFormStyle();
1071
+ const styles = useInputStyles();
1072
+ const hasError = !!(meta.error && meta.touched);
1073
+ const borderStyle = __spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, formStyle.inputVariant));
1074
+ const placeholder = fieldDef.placeholder || "123 Main St, City, State 12345";
1075
+ return /* @__PURE__ */ jsxs("div", { className: `${styles.wrapperClass} pb-5 lg:pb-0`, children: [
1076
+ /* @__PURE__ */ jsxs("label", { htmlFor: fieldDef.id, className: "relative inline-block bg-inherit", children: [
1077
+ /* @__PURE__ */ jsx(
1078
+ "textarea",
1079
+ {
1080
+ className: `${styles.inputClass} min-h-[4ch] resize-y`,
1081
+ style: borderStyle,
1082
+ id: fieldDef.id,
1083
+ name: fieldDef.id,
1084
+ autoComplete: "street-address",
1085
+ placeholder,
1086
+ rows: (_a = fieldDef.rows) != null ? _a : 2,
1087
+ value: field.value,
1088
+ disabled,
1089
+ onChange: handleChange,
1090
+ onFocus: () => setFocused(true),
1091
+ onBlur: (e) => {
1092
+ setFocused(false);
1093
+ field.onBlur(e);
1094
+ }
1095
+ }
1096
+ ),
1097
+ /* @__PURE__ */ jsx("span", { className: styles.labelClass, style: styles.labelStyle, children: fieldDef.label })
1098
+ ] }),
1099
+ hasError && /* @__PURE__ */ jsx("span", { className: "text-xs", style: styles.errorStyle, children: meta.error })
1100
+ ] });
1101
+ };
1102
+ var TextAreaField = ({ field: fieldDef, disabled }) => {
1103
+ var _a;
1104
+ const [field, meta] = useField(fieldDef.id);
1105
+ const [focused, setFocused] = useState(false);
1106
+ const handleChange = (e) => {
1107
+ e.target.value = applyTextTransform(e.target.value, fieldDef.transform);
1108
+ field.onChange(e);
1109
+ };
1110
+ const formStyle = useFormStyle();
1111
+ const styles = useInputStyles();
1112
+ const hasError = !!(meta.error && meta.touched);
1113
+ const value = (_a = field.value) != null ? _a : "";
1114
+ const borderStyle = __spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, formStyle.inputVariant));
1115
+ if (styles.isStacked) {
1116
+ return /* @__PURE__ */ jsxs("div", { className: twMerge(styles.wrapperClass, "relative"), children: [
1117
+ /* @__PURE__ */ jsx(
1118
+ "label",
1119
+ {
1120
+ htmlFor: fieldDef.id,
1121
+ className: styles.labelClass,
1122
+ style: styles.labelStyle,
1123
+ children: fieldDef.label
1124
+ }
1125
+ ),
1126
+ /* @__PURE__ */ jsx(
1127
+ "textarea",
1128
+ {
1129
+ className: twMerge(styles.inputClass, "resize-y"),
1130
+ style: borderStyle,
1131
+ id: fieldDef.id,
1132
+ name: fieldDef.id,
1133
+ placeholder: fieldDef.placeholder,
1134
+ rows: fieldDef.rows,
1135
+ value,
1136
+ disabled,
1137
+ onChange: handleChange,
1138
+ onFocus: () => setFocused(true),
1139
+ onBlur: (e) => {
1140
+ setFocused(false);
1141
+ field.onBlur(e);
1142
+ }
1143
+ }
1144
+ ),
1145
+ fieldDef.characterCounter && /* @__PURE__ */ jsx("span", { className: "mt-1 text-right text-xs text-gray-500 dark:text-zinc-400", children: value.length }),
1146
+ hasError && /* @__PURE__ */ jsx(
1147
+ "span",
1148
+ {
1149
+ className: twMerge("mt-1 text-xs", "text-red-600 dark:text-red-400"),
1150
+ style: styles.errorStyle,
1151
+ children: meta.error
1152
+ }
1153
+ )
1154
+ ] });
1155
+ }
1156
+ return /* @__PURE__ */ jsxs("div", { className: twMerge(styles.wrapperClass, "pb-5 lg:pb-0"), children: [
1157
+ /* @__PURE__ */ jsxs("label", { htmlFor: fieldDef.id, className: "relative inline-block", children: [
1158
+ /* @__PURE__ */ jsx(
1159
+ "textarea",
1160
+ {
1161
+ className: twMerge(styles.inputClass, "min-h-[5ch] resize-y"),
1162
+ style: borderStyle,
1163
+ id: fieldDef.id,
1164
+ name: fieldDef.id,
1165
+ placeholder: fieldDef.placeholder || fieldDef.label,
1166
+ rows: fieldDef.rows,
1167
+ value,
1168
+ disabled,
1169
+ onChange: handleChange,
1170
+ onFocus: () => setFocused(true),
1171
+ onBlur: (e) => {
1172
+ setFocused(false);
1173
+ field.onBlur(e);
1174
+ }
1175
+ }
1176
+ ),
1177
+ /* @__PURE__ */ jsx("span", { className: styles.labelClass, style: styles.labelStyle, children: fieldDef.label })
1178
+ ] }),
1179
+ fieldDef.characterCounter && /* @__PURE__ */ jsx("span", { className: "absolute bottom-1.5 right-2 rounded-md text-sm", children: value.length }),
1180
+ hasError && /* @__PURE__ */ jsx("span", { className: "text-xs", style: styles.errorStyle, children: meta.error })
1181
+ ] });
1182
+ };
1183
+ var SelectField = ({ field: fieldDef, disabled }) => {
1184
+ var _a;
1185
+ const [field, meta, helpers] = useField(fieldDef.id);
1186
+ const [focused, setFocused] = useState(false);
1187
+ const formStyle = useFormStyle();
1188
+ const styles = useInputStyles();
1189
+ const hasError = !!(meta.error && meta.touched);
1190
+ const [currentValue, setCurrentValue] = useState(field.value || "");
1191
+ useEffect(() => {
1192
+ setCurrentValue(field.value || "");
1193
+ }, [field.value]);
1194
+ const options = (fieldDef.options || []).filter((opt) => opt.value !== "");
1195
+ const displayName = ((_a = options.find((opt) => opt.value === currentValue)) == null ? void 0 : _a.label) || "";
1196
+ const borderStyle = __spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, formStyle.inputVariant));
1197
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
1198
+ /* @__PURE__ */ jsxs(
1199
+ Select.Root,
1200
+ {
1201
+ disabled,
1202
+ onValueChange: (value) => {
1203
+ helpers.setValue(value);
1204
+ setCurrentValue(value);
1205
+ },
1206
+ value: currentValue,
1207
+ children: [
1208
+ /* @__PURE__ */ jsx(
1209
+ "label",
1210
+ {
1211
+ htmlFor: fieldDef.id,
1212
+ className: "relative block bg-inherit",
1213
+ children: /* @__PURE__ */ jsxs(
1214
+ Select.Trigger,
1215
+ {
1216
+ className: `${styles.inputClass} cursor-pointer text-left`,
1217
+ style: borderStyle,
1218
+ "aria-label": fieldDef.label,
1219
+ onFocus: () => setFocused(true),
1220
+ onBlur: () => {
1221
+ setFocused(false);
1222
+ helpers.setTouched(true);
1223
+ },
1224
+ children: [
1225
+ /* @__PURE__ */ jsx(Select.Value, { placeholder: "Choose an option", children: /* @__PURE__ */ jsx("span", { className: "block truncate", children: displayName }) }),
1226
+ /* @__PURE__ */ jsx(Select.Icon, { className: "absolute right-3 top-1/2 -translate-y-1/2", children: /* @__PURE__ */ jsx(BsChevronDown, { style: { color: FORM_VAR.placeholder } }) }),
1227
+ /* @__PURE__ */ jsx("span", { className: styles.labelClass, style: styles.labelStyle, children: fieldDef.label })
1228
+ ]
1229
+ }
1230
+ )
1231
+ }
1232
+ ),
1233
+ /* @__PURE__ */ jsx(Select.Portal, { children: /* @__PURE__ */ jsxs(
1234
+ Select.Content,
1235
+ {
1236
+ className: "z-20 rounded-md border p-3 shadow-lg",
1237
+ style: {
1238
+ // Portal renders outside the form DOM tree, so CSS variables
1239
+ // from the form wrapper don't cascade. Use resolved style
1240
+ // values from the form context instead.
1241
+ backgroundColor: formStyle.inputBgColor || "#ffffff",
1242
+ borderColor: formStyle.inputBorderColor || "#e5e7eb",
1243
+ color: formStyle.inputTextColor || "#1f2937"
1244
+ },
1245
+ children: [
1246
+ /* @__PURE__ */ jsx(Select.ScrollUpButton, { children: /* @__PURE__ */ jsx(BsChevronDown, { className: "rotate-180" }) }),
1247
+ /* @__PURE__ */ jsx(Select.Viewport, { children: /* @__PURE__ */ jsx(Select.Group, { children: options.map((opt) => /* @__PURE__ */ jsxs(
1248
+ Select.Item,
1249
+ {
1250
+ className: "relative m-1 flex cursor-pointer select-none justify-between rounded p-1 pr-8 hover:ring-1 focus:ring-1",
1251
+ style: {
1252
+ "--tw-ring-color": formStyle.inputFocusColor || "#2563eb"
1253
+ },
1254
+ value: opt.value,
1255
+ children: [
1256
+ /* @__PURE__ */ jsx(Select.ItemText, { children: opt.label }),
1257
+ /* @__PURE__ */ jsx(Select.ItemIndicator, { children: /* @__PURE__ */ jsx(BsCheck, { className: "absolute bottom-0 right-3 top-0 my-auto" }) })
1258
+ ]
1259
+ },
1260
+ opt.value
1261
+ )) }) }),
1262
+ /* @__PURE__ */ jsx(Select.ScrollDownButton, { children: /* @__PURE__ */ jsx(BsChevronDown, {}) })
1263
+ ]
1264
+ }
1265
+ ) })
1266
+ ]
1267
+ }
1268
+ ),
1269
+ hasError && /* @__PURE__ */ jsx("span", { className: "text-xs", style: styles.errorStyle, children: meta.error })
1270
+ ] });
1271
+ };
1272
+ var CheckboxField = ({ field: fieldDef }) => {
1273
+ const [field, meta, helpers] = useField(fieldDef.id);
1274
+ const formStyle = useFormStyle();
1275
+ const isChecked = field.value === true;
1276
+ const isStacked = formStyle.inputVariant === "stacked";
1277
+ const checkboxStyle = isChecked ? { borderColor: FORM_VAR.inputFocusBorder, backgroundColor: FORM_VAR.inputFocusBorder } : { borderColor: FORM_VAR.inputBorder, backgroundColor: FORM_VAR.inputBg };
1278
+ return /* @__PURE__ */ jsxs(
1279
+ "div",
1280
+ {
1281
+ className: twMerge(
1282
+ isStacked ? "flex items-start gap-3" : "flex items-center gap-3 pt-3"
1283
+ ),
1284
+ children: [
1285
+ /* @__PURE__ */ jsx(
1286
+ Checkbox.Root,
1287
+ {
1288
+ id: fieldDef.id,
1289
+ checked: isChecked,
1290
+ onCheckedChange: (checked) => {
1291
+ helpers.setValue(checked === true);
1292
+ helpers.setTouched(true, false);
1293
+ },
1294
+ className: twMerge(
1295
+ "flex h-5 w-5 items-center justify-center rounded border",
1296
+ isStacked && "mt-0.5 shrink-0"
1297
+ ),
1298
+ style: checkboxStyle,
1299
+ children: /* @__PURE__ */ jsx(Checkbox.Indicator, { children: /* @__PURE__ */ jsx(BsCheck, { className: "text-white" }) })
1300
+ }
1301
+ ),
1302
+ /* @__PURE__ */ jsx(
1303
+ "label",
1304
+ {
1305
+ htmlFor: fieldDef.id,
1306
+ className: "cursor-pointer text-sm",
1307
+ style: { color: FORM_VAR.labelText },
1308
+ children: fieldDef.label
1309
+ }
1310
+ ),
1311
+ meta.touched && meta.error && /* @__PURE__ */ jsx("span", { className: "text-sm", style: { color: FORM_VAR.error }, children: meta.error })
1312
+ ]
1313
+ }
1314
+ );
1315
+ };
1316
+ var RadioField = ({ field: fieldDef, disabled }) => {
1317
+ const [field, meta, helpers] = useField(fieldDef.id);
1318
+ return /* @__PURE__ */ jsxs("div", { className: "pt-3", children: [
1319
+ /* @__PURE__ */ jsx(
1320
+ "span",
1321
+ {
1322
+ className: "mb-2 block text-sm",
1323
+ style: { color: FORM_VAR.labelText },
1324
+ children: fieldDef.label
1325
+ }
1326
+ ),
1327
+ /* @__PURE__ */ jsx(
1328
+ RadioGroup.Root,
1329
+ {
1330
+ value: field.value,
1331
+ disabled,
1332
+ onValueChange: (value) => {
1333
+ helpers.setValue(value);
1334
+ helpers.setTouched(true, false);
1335
+ },
1336
+ className: "flex flex-col gap-2",
1337
+ children: (fieldDef.options || []).map((opt) => {
1338
+ const isSelected = field.value === opt.value;
1339
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1340
+ /* @__PURE__ */ jsx(
1341
+ RadioGroup.Item,
1342
+ {
1343
+ value: opt.value,
1344
+ id: `${fieldDef.id}-${opt.value}`,
1345
+ className: "flex h-5 w-5 items-center justify-center rounded-full border",
1346
+ style: {
1347
+ borderColor: isSelected ? FORM_VAR.inputFocusBorder : FORM_VAR.inputBorder,
1348
+ backgroundColor: FORM_VAR.inputBg
1349
+ },
1350
+ children: /* @__PURE__ */ jsx(
1351
+ RadioGroup.Indicator,
1352
+ {
1353
+ className: "h-2.5 w-2.5 rounded-full",
1354
+ style: { backgroundColor: FORM_VAR.inputFocusBorder }
1355
+ }
1356
+ )
1357
+ }
1358
+ ),
1359
+ /* @__PURE__ */ jsx(
1360
+ "label",
1361
+ {
1362
+ htmlFor: `${fieldDef.id}-${opt.value}`,
1363
+ className: "cursor-pointer text-sm",
1364
+ style: { color: FORM_VAR.labelText },
1365
+ children: opt.label
1366
+ }
1367
+ )
1368
+ ] }, opt.value);
1369
+ })
1370
+ }
1371
+ ),
1372
+ meta.touched && meta.error && /* @__PURE__ */ jsx("span", { className: "mt-1 block text-sm", style: { color: FORM_VAR.error }, children: meta.error })
1373
+ ] });
1374
+ };
1375
+ var NumberField = ({ field: fieldDef, disabled }) => {
1376
+ const [field, meta] = useField(fieldDef.id);
1377
+ return /* @__PURE__ */ jsx(
1378
+ StyledInput,
1379
+ {
1380
+ id: fieldDef.id,
1381
+ label: fieldDef.label,
1382
+ placeholder: fieldDef.placeholder,
1383
+ type: "number",
1384
+ value: field.value,
1385
+ error: meta.error,
1386
+ touched: meta.touched,
1387
+ disabled,
1388
+ onChange: field.onChange,
1389
+ onBlur: field.onBlur
1390
+ }
1391
+ );
1392
+ };
1393
+ function nextBusinessDay(from) {
1394
+ let d = addDays(from, 1);
1395
+ while (isWeekend(d)) d = addDays(d, 1);
1396
+ return d;
1397
+ }
1398
+ function buildDateFilter(config) {
1399
+ var _a, _b, _c, _d;
1400
+ const excludeWeekends = (_a = config == null ? void 0 : config.excludeWeekends) != null ? _a : false;
1401
+ const excludeToday = (_b = config == null ? void 0 : config.excludeToday) != null ? _b : false;
1402
+ const excludeTomorrow = (_c = config == null ? void 0 : config.excludeTomorrow) != null ? _c : false;
1403
+ const excludeNext = (_d = config == null ? void 0 : config.excludeNextBusinessDay) != null ? _d : false;
1404
+ if (!excludeWeekends && !excludeToday && !excludeTomorrow && !excludeNext) {
1405
+ return void 0;
1406
+ }
1407
+ return (date) => {
1408
+ const now = /* @__PURE__ */ new Date();
1409
+ if (excludeWeekends && isWeekend(date)) return false;
1410
+ if (excludeToday && isSameDay(date, now)) return false;
1411
+ if (excludeTomorrow && isSameDay(date, addDays(now, 1))) return false;
1412
+ if (excludeNext && isSameDay(date, nextBusinessDay(now))) return false;
1413
+ return true;
1414
+ };
1415
+ }
1416
+ function parseTimeString(value, fallbackHours, fallbackMinutes) {
1417
+ if (!value) {
1418
+ return set(/* @__PURE__ */ new Date(), { hours: fallbackHours, minutes: fallbackMinutes, seconds: 0, milliseconds: 0 });
1419
+ }
1420
+ try {
1421
+ return parse(value, "HH:mm", /* @__PURE__ */ new Date());
1422
+ } catch (e) {
1423
+ return set(/* @__PURE__ */ new Date(), { hours: fallbackHours, minutes: fallbackMinutes, seconds: 0, milliseconds: 0 });
1424
+ }
1425
+ }
1426
+ function parseStoredValue(value) {
1427
+ if (!value) return null;
1428
+ const d = /^\d{4}-\d{2}-\d{2}$/.test(value) ? parse(value, "yyyy-MM-dd", /* @__PURE__ */ new Date()) : new Date(value);
1429
+ return isValid(d) ? d : null;
1430
+ }
1431
+ var DateTimeField = ({
1432
+ field: fieldDef,
1433
+ dateOnly = false,
1434
+ disabled
1435
+ }) => {
1436
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1437
+ const [field, meta, helpers] = useField(fieldDef.id);
1438
+ const [focused, setFocused] = useState(false);
1439
+ const formStyle = useFormStyle();
1440
+ const styles = useInputStyles();
1441
+ const hasError = !!(meta.error && meta.touched);
1442
+ const config = (_a = fieldDef.datetimeConfig) != null ? _a : {};
1443
+ const showTimeSelect = dateOnly ? false : (_b = config.showTimeSelect) != null ? _b : true;
1444
+ const timeIntervals = (_c = config.timeIntervals) != null ? _c : 30;
1445
+ const excludePastDates = (_d = config.excludePastDates) != null ? _d : true;
1446
+ const filterPastTimes = (_e = config.filterPastTimes) != null ? _e : true;
1447
+ const dateFormat = (_f = config.dateFormat) != null ? _f : showTimeSelect ? "MMMM d, yyyy h:mm aa" : "MMMM d, yyyy";
1448
+ const placeholderText = (_h = (_g = config.placeholderText) != null ? _g : fieldDef.placeholder) != null ? _h : dateOnly ? "Select date" : "Select date and time";
1449
+ const minTime = showTimeSelect ? parseTimeString(config.minTime, 0, 0) : void 0;
1450
+ const maxTime = showTimeSelect ? parseTimeString(config.maxTime, 23, 59) : void 0;
1451
+ const minDate = excludePastDates ? /* @__PURE__ */ new Date() : void 0;
1452
+ const selected = parseStoredValue(field.value);
1453
+ const filterDate = buildDateFilter(config);
1454
+ const filterTime = (time) => {
1455
+ if (!filterPastTimes) return true;
1456
+ return time.getTime() >= Date.now();
1457
+ };
1458
+ const handleChange = (date) => {
1459
+ if (!date) {
1460
+ helpers.setValue("");
1461
+ return;
1462
+ }
1463
+ helpers.setValue(dateOnly ? format(date, "yyyy-MM-dd") : date.toISOString());
1464
+ };
1465
+ const borderStyle = __spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, formStyle.inputVariant));
1466
+ const pickerProps = {
1467
+ id: fieldDef.id,
1468
+ name: fieldDef.id,
1469
+ wrapperClassName: "block w-full",
1470
+ disabled,
1471
+ selected,
1472
+ onChange: handleChange,
1473
+ onFocus: () => setFocused(true),
1474
+ onBlur: () => {
1475
+ setFocused(false);
1476
+ helpers.setTouched(true);
1477
+ },
1478
+ showTimeSelect,
1479
+ timeIntervals,
1480
+ minDate,
1481
+ minTime,
1482
+ maxTime,
1483
+ filterDate,
1484
+ filterTime: showTimeSelect && filterPastTimes ? filterTime : void 0,
1485
+ dateFormat,
1486
+ placeholderText,
1487
+ autoComplete: "off"
1488
+ };
1489
+ if (styles.isStacked) {
1490
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
1491
+ /* @__PURE__ */ jsx(
1492
+ "label",
1493
+ {
1494
+ htmlFor: fieldDef.id,
1495
+ className: styles.labelClass,
1496
+ style: styles.labelStyle,
1497
+ children: fieldDef.label
1498
+ }
1499
+ ),
1500
+ /* @__PURE__ */ jsx(
1501
+ DatePicker,
1502
+ __spreadProps(__spreadValues({}, pickerProps), {
1503
+ customInput: /* @__PURE__ */ jsx(
1504
+ "input",
1505
+ {
1506
+ className: twMerge(styles.inputClass, "cursor-pointer"),
1507
+ style: borderStyle
1508
+ }
1509
+ )
1510
+ })
1511
+ ),
1512
+ hasError && /* @__PURE__ */ jsx(
1513
+ "span",
1514
+ {
1515
+ className: twMerge("mt-1 text-xs", "text-red-600 dark:text-red-400"),
1516
+ style: styles.errorStyle,
1517
+ children: meta.error
1518
+ }
1519
+ )
1520
+ ] });
1521
+ }
1522
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
1523
+ /* @__PURE__ */ jsxs("label", { htmlFor: fieldDef.id, className: "relative inline-block bg-inherit", children: [
1524
+ /* @__PURE__ */ jsx(
1525
+ DatePicker,
1526
+ __spreadProps(__spreadValues({}, pickerProps), {
1527
+ className: styles.inputClass,
1528
+ customInput: /* @__PURE__ */ jsx(
1529
+ "input",
1530
+ {
1531
+ className: styles.inputClass,
1532
+ style: borderStyle
1533
+ }
1534
+ )
1535
+ })
1536
+ ),
1537
+ /* @__PURE__ */ jsx(
1538
+ "span",
1539
+ {
1540
+ className: twMerge(
1541
+ styles.labelClass,
1542
+ // react-datepicker nests the real input inside wrapper divs, so
1543
+ // the `peer-placeholder-shown` rest rule from labelClass never
1544
+ // matches (the peer must be a direct sibling). Recreate the
1545
+ // resting position from tracked state instead.
1546
+ !focused && !field.value && "translate-y-0"
1547
+ ),
1548
+ style: styles.labelStyle,
1549
+ children: fieldDef.label
1550
+ }
1551
+ )
1552
+ ] }),
1553
+ hasError && /* @__PURE__ */ jsx("span", { className: "mt-[-8px] text-xs", style: styles.errorStyle, children: meta.error })
1554
+ ] });
1555
+ };
1556
+ var DateField = ({ field, disabled }) => {
1557
+ return /* @__PURE__ */ jsx(DateTimeField, { field, dateOnly: true, disabled });
1558
+ };
1559
+ var HiddenField = ({ field: fieldDef }) => {
1560
+ const [field] = useField(fieldDef.id);
1561
+ return /* @__PURE__ */ jsx("input", { type: "hidden", name: fieldDef.id, value: field.value });
1562
+ };
1563
+ var SensitiveField = ({ field: fieldDef, disabled }) => {
1564
+ var _a;
1565
+ const [field, meta, helpers] = useField(fieldDef.id);
1566
+ const [reveal, setReveal] = useState(false);
1567
+ const formStyle = useFormStyle();
1568
+ const styles = useInputStyles();
1569
+ const [focused, setFocused] = useState(false);
1570
+ const hasError = !!(meta.error && meta.touched);
1571
+ const isSsn = ((_a = fieldDef.sensitiveConfig) == null ? void 0 : _a.inputMask) === "ssn" || fieldDef.transform === "ssn";
1572
+ const handleChange = (e) => {
1573
+ const next = applyTextTransform(
1574
+ e.target.value,
1575
+ isSsn ? "ssn" : fieldDef.transform
1576
+ );
1577
+ helpers.setValue(next);
1578
+ };
1579
+ const borderStyle = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, styles.inputStyle), focused ? styles.inputFocusStyle : {}), getErrorOutlineStyle(hasError, formStyle.inputVariant)), {
1580
+ paddingRight: "2.75rem"
1581
+ });
1582
+ const inputType = reveal ? "text" : "password";
1583
+ const inputProps = {
1584
+ id: fieldDef.id,
1585
+ name: fieldDef.id,
1586
+ type: inputType,
1587
+ disabled,
1588
+ autoComplete: "off",
1589
+ inputMode: isSsn ? "numeric" : void 0,
1590
+ placeholder: fieldDef.placeholder || (isSsn ? "\u2022\u2022\u2022-\u2022\u2022-\u2022\u2022\u2022\u2022" : fieldDef.label),
1591
+ value: field.value,
1592
+ onChange: handleChange,
1593
+ onFocus: () => setFocused(true),
1594
+ onBlur: (e) => {
1595
+ setFocused(false);
1596
+ field.onBlur(e);
1597
+ },
1598
+ "aria-describedby": `${fieldDef.id}-secure`,
1599
+ "data-sensitive": "true"
1600
+ };
1601
+ const renderToggle = (wrapperClass) => /* @__PURE__ */ jsx(
1602
+ "span",
1603
+ {
1604
+ className: twMerge(
1605
+ "absolute inset-y-0 right-2 flex items-center",
1606
+ wrapperClass
1607
+ ),
1608
+ children: /* @__PURE__ */ jsx(
1609
+ "button",
1610
+ {
1611
+ type: "button",
1612
+ onClick: () => setReveal((r) => !r),
1613
+ 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",
1614
+ "aria-pressed": reveal,
1615
+ "aria-label": reveal ? "Hide value" : "Show value",
1616
+ children: reveal ? /* @__PURE__ */ jsx(FiEyeOff, { size: 16, "aria-hidden": "true" }) : /* @__PURE__ */ jsx(FiEye, { size: 16, "aria-hidden": "true" })
1617
+ }
1618
+ )
1619
+ }
1620
+ );
1621
+ const renderSecureHint = (className) => /* @__PURE__ */ jsxs(
1622
+ "p",
1623
+ {
1624
+ id: `${fieldDef.id}-secure`,
1625
+ className: twMerge(
1626
+ "flex items-center gap-1 text-xs text-gray-500 dark:text-zinc-400",
1627
+ className
1628
+ ),
1629
+ children: [
1630
+ /* @__PURE__ */ jsx(
1631
+ "svg",
1632
+ {
1633
+ "aria-hidden": "true",
1634
+ viewBox: "0 0 16 16",
1635
+ className: "h-3 w-3 flex-shrink-0",
1636
+ fill: "currentColor",
1637
+ children: /* @__PURE__ */ jsx("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" })
1638
+ }
1639
+ ),
1640
+ "Encrypted before submission"
1641
+ ]
1642
+ }
1643
+ );
1644
+ if (styles.isStacked) {
1645
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
1646
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-baseline justify-between gap-x-2", children: [
1647
+ /* @__PURE__ */ jsx("label", { htmlFor: fieldDef.id, className: styles.labelClass, style: styles.labelStyle, children: fieldDef.label }),
1648
+ renderSecureHint("mb-1")
1649
+ ] }),
1650
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
1651
+ /* @__PURE__ */ jsx("input", __spreadValues({ className: styles.inputClass, style: borderStyle }, inputProps)),
1652
+ renderToggle()
1653
+ ] }),
1654
+ hasError && /* @__PURE__ */ jsx(
1655
+ "span",
1656
+ {
1657
+ className: twMerge("mt-1 text-xs", "text-red-600 dark:text-red-400"),
1658
+ style: styles.errorStyle,
1659
+ children: meta.error
1660
+ }
1661
+ )
1662
+ ] });
1663
+ }
1664
+ return /* @__PURE__ */ jsxs("div", { className: styles.wrapperClass, children: [
1665
+ renderSecureHint("absolute right-0 top-0 leading-none"),
1666
+ /* @__PURE__ */ jsxs("label", { htmlFor: fieldDef.id, className: "relative inline-block w-full bg-inherit", children: [
1667
+ /* @__PURE__ */ jsx("input", __spreadValues({ className: styles.inputClass, style: borderStyle }, inputProps)),
1668
+ /* @__PURE__ */ jsx("span", { className: styles.labelClass, style: styles.labelStyle, children: fieldDef.label }),
1669
+ renderToggle("mb-3")
1670
+ ] }),
1671
+ hasError && /* @__PURE__ */ jsx("span", { className: "mt-[-8px] text-xs", style: styles.errorStyle, children: meta.error })
1672
+ ] });
1673
+ };
1674
+ function formatBytes(bytes) {
1675
+ if (bytes < 1024) return `${bytes} B`;
1676
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1677
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1678
+ }
1679
+ function matchesAccept(file, accept) {
1680
+ if (!(accept == null ? void 0 : accept.trim())) return true;
1681
+ const patterns = accept.split(",").map((p) => p.trim()).filter(Boolean);
1682
+ return patterns.some((pattern) => {
1683
+ if (pattern.startsWith(".")) {
1684
+ return file.name.toLowerCase().endsWith(pattern.toLowerCase());
1685
+ }
1686
+ if (pattern.endsWith("/*")) {
1687
+ return file.type.startsWith(pattern.slice(0, -1));
1688
+ }
1689
+ return file.type === pattern;
1690
+ });
1691
+ }
1692
+ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1693
+ var _a, _b, _c, _d;
1694
+ const [, meta, helpers] = useField(fieldDef.id);
1695
+ const { setFieldTouched } = useFormikContext();
1696
+ const inputRef = useRef(null);
1697
+ const [uploading, setUploading] = useState(false);
1698
+ const [uploadError, setUploadError] = useState(null);
1699
+ const [files, setFiles] = useState([]);
1700
+ const config = __spreadValues(__spreadValues({}, DEFAULT_FILE_FIELD_CONFIG), fieldDef.fileConfig);
1701
+ const maxSizeBytes = (_a = config.maxSizeBytes) != null ? _a : 10 * 1024 * 1024;
1702
+ const multiple = (_b = config.multiple) != null ? _b : false;
1703
+ const maxFiles = (_c = config.maxFiles) != null ? _c : 5;
1704
+ const handleFiles = useCallback(
1705
+ (fileList) => __async(null, null, function* () {
1706
+ var _a2, _b2;
1707
+ if (!fileList || fileList.length === 0) return;
1708
+ setUploadError(null);
1709
+ const toUpload = Array.from(fileList);
1710
+ if (multiple && files.length + toUpload.length > maxFiles) {
1711
+ setUploadError(`Maximum ${maxFiles} files allowed.`);
1712
+ return;
1713
+ }
1714
+ let current = files;
1715
+ for (const file of toUpload) {
1716
+ if (!matchesAccept(file, config.accept)) {
1717
+ setUploadError(`"${file.name}" is not an accepted file type.`);
1718
+ continue;
1719
+ }
1720
+ if (file.size > maxSizeBytes) {
1721
+ setUploadError(
1722
+ `"${file.name}" exceeds ${formatBytes(maxSizeBytes)} limit.`
1723
+ );
1724
+ continue;
1725
+ }
1726
+ setUploading(true);
1727
+ try {
1728
+ let result;
1729
+ if (onUpload) {
1730
+ result = yield onUpload(file, config);
1731
+ } else {
1732
+ result = {
1733
+ url: URL.createObjectURL(file),
1734
+ name: file.name,
1735
+ size: file.size
1736
+ };
1737
+ }
1738
+ current = multiple ? [...current, result] : [result];
1739
+ } catch (err) {
1740
+ setUploadError(`Upload failed: ${err.message}`);
1741
+ } finally {
1742
+ setUploading(false);
1743
+ }
1744
+ }
1745
+ if (current !== files) {
1746
+ setFiles(current);
1747
+ helpers.setValue(multiple ? current.map((f) => f.url) : (_b2 = (_a2 = current[0]) == null ? void 0 : _a2.url) != null ? _b2 : "");
1748
+ }
1749
+ setFieldTouched(fieldDef.id, true);
1750
+ }),
1751
+ [
1752
+ files,
1753
+ multiple,
1754
+ maxFiles,
1755
+ maxSizeBytes,
1756
+ config,
1757
+ onUpload,
1758
+ helpers,
1759
+ fieldDef.id,
1760
+ setFieldTouched
1761
+ ]
1762
+ );
1763
+ const removeFile = useCallback(
1764
+ (index) => {
1765
+ const next = files.filter((_, i) => i !== index);
1766
+ setFiles(next);
1767
+ helpers.setValue(multiple ? next.map((f) => f.url) : "");
1768
+ },
1769
+ [files, multiple, helpers]
1770
+ );
1771
+ const hasError = meta.touched && meta.error;
1772
+ const isRequired = (_d = fieldDef.validation) == null ? void 0 : _d.some((v) => v.type === "required");
1773
+ return /* @__PURE__ */ jsxs("div", { children: [
1774
+ /* @__PURE__ */ jsxs(
1775
+ "label",
1776
+ {
1777
+ htmlFor: fieldDef.id,
1778
+ className: "mb-1 block text-sm font-medium",
1779
+ style: { color: "var(--form-label-color, inherit)" },
1780
+ children: [
1781
+ fieldDef.label,
1782
+ isRequired && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-red-500", children: "*" })
1783
+ ]
1784
+ }
1785
+ ),
1786
+ fieldDef.helpText && /* @__PURE__ */ jsx(
1787
+ "p",
1788
+ {
1789
+ className: "mb-2 text-xs",
1790
+ style: { color: "var(--form-placeholder-color, #9ca3af)" },
1791
+ children: fieldDef.helpText
1792
+ }
1793
+ ),
1794
+ /* @__PURE__ */ jsxs(
1795
+ "div",
1796
+ {
1797
+ className: `relative rounded-lg border-2 border-dashed p-6 text-center transition-colors ${hasError ? "border-red-400" : "border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500"}`,
1798
+ onDragOver: (e) => {
1799
+ e.preventDefault();
1800
+ e.stopPropagation();
1801
+ },
1802
+ onDrop: (e) => {
1803
+ e.preventDefault();
1804
+ e.stopPropagation();
1805
+ handleFiles(e.dataTransfer.files);
1806
+ },
1807
+ children: [
1808
+ /* @__PURE__ */ jsx(
1809
+ "input",
1810
+ {
1811
+ ref: inputRef,
1812
+ id: fieldDef.id,
1813
+ type: "file",
1814
+ accept: config.accept,
1815
+ multiple,
1816
+ disabled,
1817
+ onChange: (e) => {
1818
+ handleFiles(e.target.files);
1819
+ e.target.value = "";
1820
+ },
1821
+ className: "hidden"
1822
+ }
1823
+ ),
1824
+ uploading ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
1825
+ /* @__PURE__ */ jsx("div", { className: "mx-auto h-1.5 w-32 overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700", children: /* @__PURE__ */ jsx("div", { className: "h-full w-1/3 animate-pulse rounded-full bg-indigo-500" }) }),
1826
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500", children: "Uploading\u2026" })
1827
+ ] }) : /* @__PURE__ */ jsxs(
1828
+ "button",
1829
+ {
1830
+ type: "button",
1831
+ onClick: () => {
1832
+ var _a2;
1833
+ return (_a2 = inputRef.current) == null ? void 0 : _a2.click();
1834
+ },
1835
+ disabled,
1836
+ 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",
1837
+ children: [
1838
+ /* @__PURE__ */ jsx(
1839
+ "svg",
1840
+ {
1841
+ className: "mx-auto mb-2 h-8 w-8 text-gray-400",
1842
+ fill: "none",
1843
+ viewBox: "0 0 24 24",
1844
+ strokeWidth: 1.5,
1845
+ stroke: "currentColor",
1846
+ children: /* @__PURE__ */ jsx(
1847
+ "path",
1848
+ {
1849
+ strokeLinecap: "round",
1850
+ strokeLinejoin: "round",
1851
+ 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"
1852
+ }
1853
+ )
1854
+ }
1855
+ ),
1856
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: "Click to upload" }),
1857
+ " or drag and drop",
1858
+ /* @__PURE__ */ jsx("br", {}),
1859
+ /* @__PURE__ */ jsxs("span", { className: "text-xs text-gray-400", children: [
1860
+ "Max ",
1861
+ formatBytes(maxSizeBytes),
1862
+ multiple && ` \xB7 Up to ${maxFiles} files`
1863
+ ] })
1864
+ ]
1865
+ }
1866
+ )
1867
+ ]
1868
+ }
1869
+ ),
1870
+ files.length > 0 && /* @__PURE__ */ jsx("div", { className: "mt-3 space-y-2", children: files.map((f, i) => /* @__PURE__ */ jsxs(
1871
+ "div",
1872
+ {
1873
+ 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",
1874
+ children: [
1875
+ f.url && f.name.match(/\.(jpg|jpeg|png|webp|gif|svg)$/i) && // eslint-disable-next-line @next/next/no-img-element
1876
+ /* @__PURE__ */ jsx(
1877
+ "img",
1878
+ {
1879
+ src: f.url,
1880
+ alt: f.name,
1881
+ className: "h-10 w-10 rounded object-cover"
1882
+ }
1883
+ ),
1884
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
1885
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium text-gray-900 dark:text-gray-100", children: f.name }),
1886
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500", children: formatBytes(f.size) })
1887
+ ] }),
1888
+ /* @__PURE__ */ jsx(
1889
+ "button",
1890
+ {
1891
+ type: "button",
1892
+ onClick: () => removeFile(i),
1893
+ className: "cursor-pointer text-gray-400 hover:text-red-500",
1894
+ "aria-label": `Remove ${f.name}`,
1895
+ children: /* @__PURE__ */ jsx(
1896
+ "svg",
1897
+ {
1898
+ className: "h-4 w-4",
1899
+ fill: "none",
1900
+ viewBox: "0 0 24 24",
1901
+ strokeWidth: 2,
1902
+ stroke: "currentColor",
1903
+ children: /* @__PURE__ */ jsx(
1904
+ "path",
1905
+ {
1906
+ strokeLinecap: "round",
1907
+ strokeLinejoin: "round",
1908
+ d: "M6 18L18 6M6 6l12 12"
1909
+ }
1910
+ )
1911
+ }
1912
+ )
1913
+ }
1914
+ )
1915
+ ]
1916
+ },
1917
+ `${f.name}-${i}`
1918
+ )) }),
1919
+ uploadError && /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-red-500", children: uploadError }),
1920
+ hasError && /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-red-500", children: meta.error })
1921
+ ] });
1922
+ };
1923
+ var fieldComponents = {
1924
+ text: TextField,
1925
+ email: EmailField,
1926
+ phone: PhoneField,
1927
+ url: UrlField,
1928
+ address: AddressField,
1929
+ textarea: TextAreaField,
1930
+ select: SelectField,
1931
+ checkbox: CheckboxField,
1932
+ radio: RadioField,
1933
+ number: NumberField,
1934
+ date: DateField,
1935
+ datetime: DateTimeField,
1936
+ hidden: HiddenField,
1937
+ sensitive: SensitiveField,
1938
+ file: FileField
1939
+ };
1940
+ var DynamicFormField = ({ field, mirrored, mirrorBehavior }) => {
1941
+ var _a, _b;
1942
+ const { values } = useFormikContext();
1943
+ const Component = fieldComponents[field.type];
1944
+ if (!Component) {
1945
+ console.warn(`Unknown field type: ${field.type}`);
1946
+ return null;
1947
+ }
1948
+ if (!field.id) {
1949
+ console.warn("Skipping form field with empty id");
1950
+ return null;
1951
+ }
1952
+ if (field.showWhen && !isVisibilityConditionMet(field.showWhen, values[field.showWhen.fieldId])) {
1953
+ return null;
1954
+ }
1955
+ if (mirrored && mirrorBehavior === "hide") {
1956
+ return null;
1957
+ }
1958
+ const locked = mirrored && mirrorBehavior === "lock";
1959
+ if (field.type === "hidden") {
1960
+ return /* @__PURE__ */ jsx(Component, { field, disabled: locked });
1961
+ }
1962
+ const widthClasses = {
1963
+ full: "md:col-span-6",
1964
+ half: "md:col-span-3",
1965
+ third: "md:col-span-2"
1966
+ };
1967
+ const widthClass = widthClasses[((_a = field.layout) == null ? void 0 : _a.width) || "full"] || "md:col-span-6";
1968
+ const description = (_b = field.description) != null ? _b : field.helpText;
1969
+ return /* @__PURE__ */ jsxs("div", { className: widthClass, children: [
1970
+ /* @__PURE__ */ jsx(Component, { field, disabled: locked }),
1971
+ description && /* @__PURE__ */ jsx("p", { className: twMerge("mt-1 text-xs", "text-gray-500 dark:text-zinc-400"), children: description })
1972
+ ] });
1973
+ };
1974
+ var spacingGap = {
1975
+ compact: "gap-2",
1976
+ normal: "gap-4",
1977
+ relaxed: "gap-6"
1978
+ };
1979
+ var DynamicFormSection = ({
1980
+ section,
1981
+ isLast,
1982
+ formDefaultTextColor,
1983
+ inlineSubmit
1984
+ }) => {
1985
+ var _a, _b;
1986
+ const style = useFormStyle();
1987
+ const previewOverrides = useFormPreviewOverrides();
1988
+ const previewTextColor = previewOverrides == null ? void 0 : previewOverrides.textColor;
1989
+ const { values, setFieldValue } = useFormikContext();
1990
+ const sameAs = section.sameAs;
1991
+ const toggleKey = sameAs ? sameAsToggleKey(section.id) : "";
1992
+ const toggleOn = sameAs ? values[toggleKey] === true : false;
1993
+ const fieldMap = (_a = sameAs == null ? void 0 : sameAs.fieldMap) != null ? _a : {};
1994
+ const sourceSignature = JSON.stringify(
1995
+ Object.values(fieldMap).map((sourceId) => {
1996
+ var _a2;
1997
+ return (_a2 = values[sourceId]) != null ? _a2 : null;
1998
+ })
1999
+ );
2000
+ useEffect(() => {
2001
+ var _a2;
2002
+ if (!sameAs || !toggleOn) return;
2003
+ for (const [targetId, sourceId] of Object.entries(sameAs.fieldMap)) {
2004
+ setFieldValue(targetId, (_a2 = values[sourceId]) != null ? _a2 : "");
2005
+ }
2006
+ }, [toggleOn, sourceSignature]);
2007
+ const effectiveTextColor = (_b = previewTextColor != null ? previewTextColor : section.textColor) != null ? _b : formDefaultTextColor;
2008
+ const sortedFields = [...section.fields].sort(
2009
+ (a, b) => {
2010
+ var _a2, _b2, _c, _d;
2011
+ return ((_b2 = (_a2 = a.layout) == null ? void 0 : _a2.order) != null ? _b2 : 0) - ((_d = (_c = b.layout) == null ? void 0 : _c.order) != null ? _d : 0);
2012
+ }
2013
+ );
2014
+ const gap = spacingGap[style.spacing || "normal"];
2015
+ const divider = style.sectionDividers && !isLast;
2016
+ const isStacked = style.inputVariant === "stacked";
2017
+ const sectionWrapperClass = twMerge(
2018
+ isStacked ? "space-y-4" : "mb-6",
2019
+ divider && "border-b border-gray-200 dark:border-zinc-700 pb-6"
2020
+ );
2021
+ const titleClass = twMerge(
2022
+ "text-lg font-semibold",
2023
+ effectiveTextColor ? "" : "text-gray-800 dark:text-zinc-100",
2024
+ !isStacked && "mb-1"
2025
+ );
2026
+ const descriptionClass = twMerge(
2027
+ "text-sm",
2028
+ effectiveTextColor ? "" : "text-gray-500 dark:text-zinc-400",
2029
+ !isStacked && "mb-4"
2030
+ );
2031
+ const textStyle = effectiveTextColor ? { color: effectiveTextColor } : void 0;
2032
+ return /* @__PURE__ */ jsxs("fieldset", { className: sectionWrapperClass, children: [
2033
+ section.title && /* @__PURE__ */ jsx("legend", { className: titleClass, style: textStyle, children: section.title }),
2034
+ section.description && /* @__PURE__ */ jsx("p", { className: descriptionClass, style: textStyle, children: section.description }),
2035
+ sameAs && /* @__PURE__ */ jsxs("div", { className: "mb-4 flex items-center gap-3", children: [
2036
+ /* @__PURE__ */ jsx(
2037
+ Checkbox.Root,
2038
+ {
2039
+ id: toggleKey,
2040
+ checked: toggleOn,
2041
+ onCheckedChange: (checked) => setFieldValue(toggleKey, checked === true),
2042
+ className: "flex h-5 w-5 items-center justify-center rounded border",
2043
+ style: toggleOn ? { borderColor: FORM_VAR.inputFocusBorder, backgroundColor: FORM_VAR.inputFocusBorder } : { borderColor: FORM_VAR.inputBorder, backgroundColor: FORM_VAR.inputBg },
2044
+ children: /* @__PURE__ */ jsx(Checkbox.Indicator, { children: /* @__PURE__ */ jsx(BsCheck, { className: "text-white" }) })
2045
+ }
2046
+ ),
2047
+ /* @__PURE__ */ jsx(
2048
+ "label",
2049
+ {
2050
+ htmlFor: toggleKey,
2051
+ className: "cursor-pointer text-sm",
2052
+ style: { color: FORM_VAR.labelText },
2053
+ children: sameAs.toggleLabel
2054
+ }
2055
+ )
2056
+ ] }),
2057
+ (() => {
2058
+ const fieldsGrid = /* @__PURE__ */ jsx(
2059
+ "div",
2060
+ {
2061
+ className: twMerge(
2062
+ "grid grid-cols-1 md:grid-cols-6",
2063
+ gap,
2064
+ inlineSubmit && "min-w-0 flex-auto"
2065
+ ),
2066
+ children: sortedFields.map((field, i) => /* @__PURE__ */ jsx(
2067
+ DynamicFormField,
2068
+ {
2069
+ field,
2070
+ mirrored: toggleOn && field.id in fieldMap,
2071
+ mirrorBehavior: sameAs == null ? void 0 : sameAs.behavior
2072
+ },
2073
+ `${field.id}-${i}`
2074
+ ))
2075
+ }
2076
+ );
2077
+ return inlineSubmit ? /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
2078
+ fieldsGrid,
2079
+ /* @__PURE__ */ jsx("div", { className: twMerge("flex-none", !isStacked && "pt-3"), children: inlineSubmit })
2080
+ ] }) : fieldsGrid;
2081
+ })()
2082
+ ] });
2083
+ };
2084
+ function globalTracker() {
2085
+ if (typeof window === "undefined") return void 0;
2086
+ return window.__vtTrack;
2087
+ }
2088
+ function getSensitiveFieldIds(definition) {
2089
+ const ids = [];
2090
+ for (const section of definition.sections) {
2091
+ for (const field of section.fields) {
2092
+ if (field.type === "sensitive") ids.push(field.id);
2093
+ }
2094
+ }
2095
+ return ids;
2096
+ }
2097
+ function getHiddenFieldIds(definition, values) {
2098
+ const ids = [];
2099
+ for (const section of definition.sections) {
2100
+ for (const field of section.fields) {
2101
+ if (field.showWhen && !isVisibilityConditionMet(field.showWhen, values[field.showWhen.fieldId])) {
2102
+ ids.push(field.id);
2103
+ }
2104
+ }
2105
+ }
2106
+ return ids;
2107
+ }
2108
+ function getSameAsToggleKeys(definition) {
2109
+ return definition.sections.filter((s) => s.sameAs).map((s) => sameAsToggleKey(s.id));
2110
+ }
2111
+ function fetchTransportKey(endpoint) {
2112
+ return __async(this, null, function* () {
2113
+ const res = yield fetch(endpoint, { method: "GET" });
2114
+ if (!res.ok) {
2115
+ throw new Error(
2116
+ `Failed to fetch transport key: ${res.status} ${res.statusText}`
2117
+ );
2118
+ }
2119
+ const data = yield res.json();
2120
+ if (!(data == null ? void 0 : data.kid) || !(data == null ? void 0 : data.jwk)) {
2121
+ throw new Error("Transport key endpoint returned an invalid payload");
2122
+ }
2123
+ return data;
2124
+ });
2125
+ }
2126
+ var presetNonBgClasses = {
2127
+ default: "",
2128
+ minimal: "",
2129
+ bordered: "border border-gray-200",
2130
+ shadow: "shadow-lg",
2131
+ card: "shadow-lg border border-gray-200",
2132
+ dark: ""
2133
+ };
2134
+ var radiusClasses = {
2135
+ none: "rounded-none",
2136
+ sm: "rounded-sm",
2137
+ md: "rounded-md",
2138
+ lg: "rounded-lg",
2139
+ full: "rounded-2xl"
2140
+ };
2141
+ var spacingClasses = {
2142
+ compact: "p-3",
2143
+ normal: "p-6",
2144
+ relaxed: "p-8"
2145
+ };
2146
+ function getButtonClasses(style) {
2147
+ const radius = radiusClasses[style.borderRadius] || "rounded-md";
2148
+ const weight = style.inputVariant === "stacked" ? "font-semibold" : "font-medium";
2149
+ switch (style.buttonVariant) {
2150
+ case "outline":
2151
+ return `${radius} border-2 bg-transparent ${weight} transition-colors`;
2152
+ case "ghost":
2153
+ return `${radius} bg-transparent ${weight} transition-colors`;
2154
+ case "filled":
2155
+ default:
2156
+ return `${radius} ${weight} transition-colors`;
2157
+ }
2158
+ }
2159
+ function getButtonStyle(style) {
2160
+ switch (style.buttonVariant) {
2161
+ case "outline":
2162
+ return { borderColor: FORM_VAR.buttonBg, color: FORM_VAR.buttonBg };
2163
+ case "ghost":
2164
+ return { color: FORM_VAR.buttonBg };
2165
+ case "filled":
2166
+ default:
2167
+ return {
2168
+ backgroundColor: FORM_VAR.buttonBg,
2169
+ color: FORM_VAR.buttonText
2170
+ };
2171
+ }
2172
+ }
2173
+ function interpolateSuccessMessage(template, response) {
2174
+ if (!template.includes("{{") || !response) return template;
2175
+ return template.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (_match, key) => {
2176
+ const value = response[key];
2177
+ if (value === void 0 || value === null) return "";
2178
+ return String(value);
2179
+ });
2180
+ }
2181
+ var Spinner = () => /* @__PURE__ */ jsxs(
2182
+ "svg",
2183
+ {
2184
+ className: "-ml-1 mr-2 h-4 w-4 animate-spin",
2185
+ xmlns: "http://www.w3.org/2000/svg",
2186
+ fill: "none",
2187
+ viewBox: "0 0 24 24",
2188
+ "aria-hidden": "true",
2189
+ children: [
2190
+ /* @__PURE__ */ jsx(
2191
+ "circle",
2192
+ {
2193
+ className: "opacity-25",
2194
+ cx: "12",
2195
+ cy: "12",
2196
+ r: "10",
2197
+ stroke: "currentColor",
2198
+ strokeWidth: "4"
2199
+ }
2200
+ ),
2201
+ /* @__PURE__ */ jsx(
2202
+ "path",
2203
+ {
2204
+ className: "opacity-75",
2205
+ fill: "currentColor",
2206
+ d: "M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z"
2207
+ }
2208
+ )
2209
+ ]
2210
+ }
2211
+ );
2212
+ var SuccessBanner = ({ message }) => /* @__PURE__ */ jsxs(
2213
+ "div",
2214
+ {
2215
+ role: "status",
2216
+ "aria-live": "polite",
2217
+ className: "flex items-start gap-3 rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800",
2218
+ children: [
2219
+ /* @__PURE__ */ jsx(
2220
+ "svg",
2221
+ {
2222
+ className: "mt-0.5 h-4 w-4 flex-shrink-0",
2223
+ xmlns: "http://www.w3.org/2000/svg",
2224
+ viewBox: "0 0 20 20",
2225
+ fill: "currentColor",
2226
+ "aria-hidden": "true",
2227
+ children: /* @__PURE__ */ jsx(
2228
+ "path",
2229
+ {
2230
+ fillRule: "evenodd",
2231
+ 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",
2232
+ clipRule: "evenodd"
2233
+ }
2234
+ )
2235
+ }
2236
+ ),
2237
+ /* @__PURE__ */ jsx("span", { className: "flex-1", children: message })
2238
+ ]
2239
+ }
2240
+ );
2241
+ var ErrorBanner = ({
2242
+ message,
2243
+ onDismiss
2244
+ }) => /* @__PURE__ */ jsxs(
2245
+ "div",
2246
+ {
2247
+ role: "alert",
2248
+ className: "flex items-start gap-3 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800",
2249
+ children: [
2250
+ /* @__PURE__ */ jsx(
2251
+ "svg",
2252
+ {
2253
+ className: "mt-0.5 h-4 w-4 flex-shrink-0",
2254
+ xmlns: "http://www.w3.org/2000/svg",
2255
+ viewBox: "0 0 20 20",
2256
+ fill: "currentColor",
2257
+ "aria-hidden": "true",
2258
+ children: /* @__PURE__ */ jsx(
2259
+ "path",
2260
+ {
2261
+ fillRule: "evenodd",
2262
+ 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",
2263
+ clipRule: "evenodd"
2264
+ }
2265
+ )
2266
+ }
2267
+ ),
2268
+ /* @__PURE__ */ jsx("span", { className: "flex-1", children: message }),
2269
+ /* @__PURE__ */ jsx(
2270
+ "button",
2271
+ {
2272
+ type: "button",
2273
+ onClick: onDismiss,
2274
+ className: "font-medium text-red-900 underline-offset-2 hover:underline",
2275
+ children: "Try again"
2276
+ }
2277
+ )
2278
+ ]
2279
+ }
2280
+ );
2281
+ var DynamicForm = ({
2282
+ definition,
2283
+ apiRoute,
2284
+ onSuccess,
2285
+ onError,
2286
+ extraData,
2287
+ className,
2288
+ onFormView,
2289
+ onFormSubmit: onFormSubmitCallback,
2290
+ transportKeyEndpoint = "/api/forms/transport-key",
2291
+ previewState,
2292
+ previewTouchAllSignal,
2293
+ previewUntouchAllSignal,
2294
+ previewBg,
2295
+ previewTextColor
2296
+ }) => {
2297
+ var _a, _b, _c;
2298
+ const [submitStatus, setSubmitStatus] = useState("idle");
2299
+ const [postSuccessCooldown, setPostSuccessCooldown] = useState(false);
2300
+ useEffect(() => {
2301
+ if (submitStatus !== "success") return;
2302
+ setPostSuccessCooldown(true);
2303
+ const t = setTimeout(() => setPostSuccessCooldown(false), 2e3);
2304
+ return () => clearTimeout(t);
2305
+ }, [submitStatus]);
2306
+ const [responseData, setResponseData] = useState(
2307
+ null
2308
+ );
2309
+ const formikRef = useRef(null);
2310
+ useEffect(() => {
2311
+ var _a2, _b2;
2312
+ (_b2 = onFormView != null ? onFormView : (_a2 = globalTracker()) == null ? void 0 : _a2.trackFormView) == null ? void 0 : _b2(
2313
+ definition.id,
2314
+ definition.name
2315
+ );
2316
+ }, []);
2317
+ const effectiveSubmitStatus = previewState === "success" ? "success" : previewState === "error" ? "error" : previewState === "idle" ? "idle" : submitStatus;
2318
+ const previewSubmitting = previewState === "submitting";
2319
+ const spamProtection = __spreadValues(__spreadValues({}, DEFAULT_SPAM_PROTECTION), definition.submitConfig.spamProtection);
2320
+ const honeypotEnabled = spamProtection.honeypot !== false;
2321
+ const minSubmitTime = Math.max(0, (_a = spamProtection.minSubmitTime) != null ? _a : 0);
2322
+ const mountTimeRef = useRef(Date.now());
2323
+ useEffect(() => {
2324
+ mountTimeRef.current = Date.now();
2325
+ }, [definition.id]);
2326
+ const validationSchema = useMemo(() => buildYupSchema(definition), [definition]);
2327
+ const initialValues = useMemo(() => {
2328
+ const base = buildInitialValues(definition);
2329
+ if (honeypotEnabled) {
2330
+ base[HONEYPOT_FIELD_NAME] = "";
2331
+ }
2332
+ return base;
2333
+ }, [definition, honeypotEnabled]);
2334
+ const sortedSections = useMemo(
2335
+ () => [...definition.sections].sort((a, b) => a.order - b.order),
2336
+ [definition.sections]
2337
+ );
2338
+ useEffect(() => {
2339
+ if (previewTouchAllSignal === void 0 || !formikRef.current) return;
2340
+ const touched = {};
2341
+ for (const section of definition.sections) {
2342
+ for (const field of section.fields) {
2343
+ touched[field.id] = true;
2344
+ }
2345
+ }
2346
+ formikRef.current.setTouched(touched, true);
2347
+ }, [previewTouchAllSignal, definition.sections]);
2348
+ useEffect(() => {
2349
+ if (previewUntouchAllSignal === void 0 || !formikRef.current) return;
2350
+ formikRef.current.setTouched({}, false);
2351
+ }, [previewUntouchAllSignal]);
2352
+ const style = __spreadValues(__spreadValues({}, DEFAULT_FORM_STYLE), definition.style);
2353
+ const isStacked = style.inputVariant === "stacked";
2354
+ const isCard = style.preset === "card";
2355
+ const submittingText = (_b = definition.submitConfig.submittingText) != null ? _b : "Submitting...";
2356
+ const successBehavior = (_c = definition.submitConfig.successBehavior) != null ? _c : "message";
2357
+ const hasPreviewOverride = Boolean(previewBg || previewTextColor);
2358
+ const previewOverrides = hasPreviewOverride ? { backgroundColor: previewBg, textColor: previewTextColor } : null;
2359
+ const cssVarStyle = buildFormCssVars(style, previewBg);
2360
+ const effectiveFormBg = previewBg != null ? previewBg : style.formBackgroundColor;
2361
+ const formInlineStyle = __spreadValues(__spreadValues(__spreadValues({}, cssVarStyle), effectiveFormBg ? { backgroundColor: effectiveFormBg } : {}), previewTextColor ? { color: previewTextColor } : {});
2362
+ const formClasses = twMerge(
2363
+ presetNonBgClasses[style.preset] || "",
2364
+ radiusClasses[style.borderRadius] || "rounded-md",
2365
+ isCard ? "p-8" : spacingClasses[style.spacing] || "p-6",
2366
+ isStacked ? "space-y-8" : "",
2367
+ className
2368
+ );
2369
+ const inlineButton = style.buttonPlacement === "inline";
2370
+ const buttonSizeClass = inlineButton ? isStacked ? "flex-none px-6 py-3 text-base" : "flex-none px-6 py-2.5 text-sm" : isStacked ? "w-full px-6 py-3 text-base" : "mt-4 w-full px-6 py-2.5 text-sm";
2371
+ const bannerWrapperClass = isStacked ? "" : "mb-4";
2372
+ const successMessage = interpolateSuccessMessage(
2373
+ definition.submitConfig.successMessage,
2374
+ responseData
2375
+ );
2376
+ if (successBehavior === "replace" && effectiveSubmitStatus === "success") {
2377
+ return /* @__PURE__ */ jsx(FormStyleProvider, { value: style, children: /* @__PURE__ */ jsx(FormPreviewOverridesProvider, { value: previewOverrides, children: /* @__PURE__ */ jsx(
2378
+ "div",
2379
+ {
2380
+ className: formClasses,
2381
+ style: formInlineStyle,
2382
+ "data-form-version": definition.version,
2383
+ children: /* @__PURE__ */ jsx(SuccessBanner, { message: successMessage })
2384
+ }
2385
+ ) }) });
2386
+ }
2387
+ return /* @__PURE__ */ jsx(FormStyleProvider, { value: style, children: /* @__PURE__ */ jsx(FormPreviewOverridesProvider, { value: previewOverrides, children: /* @__PURE__ */ jsx(
2388
+ Formik,
2389
+ {
2390
+ innerRef: formikRef,
2391
+ initialValues,
2392
+ validationSchema,
2393
+ onSubmit: (_0, _1) => __async(null, [_0, _1], function* (values, { setSubmitting, resetForm }) {
2394
+ var _a2, _b2, _d, _e, _f;
2395
+ if (previewState) {
2396
+ setSubmitting(false);
2397
+ return;
2398
+ }
2399
+ const honeypotTriggered = honeypotEnabled && typeof values[HONEYPOT_FIELD_NAME] === "string" && values[HONEYPOT_FIELD_NAME].length > 0;
2400
+ const elapsedSeconds = (Date.now() - mountTimeRef.current) / 1e3;
2401
+ const timerTriggered = minSubmitTime > 0 && elapsedSeconds < minSubmitTime;
2402
+ if (honeypotTriggered || timerTriggered) {
2403
+ const proc = globalThis.process;
2404
+ if (((_a2 = proc == null ? void 0 : proc.env) == null ? void 0 : _a2.NODE_ENV) !== "production") {
2405
+ const reason = honeypotTriggered ? "honeypot" : "timer";
2406
+ console.debug(`[forms] Spam detected: ${reason}`);
2407
+ }
2408
+ setResponseData(null);
2409
+ setSubmitStatus("success");
2410
+ if (successBehavior === "reset" || successBehavior === "replace") {
2411
+ resetForm();
2412
+ }
2413
+ onSuccess == null ? void 0 : onSuccess();
2414
+ setSubmitting(false);
2415
+ return;
2416
+ }
2417
+ setSubmitStatus("idle");
2418
+ try {
2419
+ const _c2 = values, { [_b2 = HONEYPOT_FIELD_NAME]: _hp } = _c2, cleanValues = __objRest(_c2, [__restKey(_b2)]);
2420
+ const payload = __spreadProps(__spreadValues(__spreadValues({}, cleanValues), extraData), {
2421
+ formId: definition.id
2422
+ });
2423
+ for (const hiddenId of getHiddenFieldIds(definition, cleanValues)) {
2424
+ delete payload[hiddenId];
2425
+ }
2426
+ for (const toggleKey of getSameAsToggleKeys(definition)) {
2427
+ delete payload[toggleKey];
2428
+ }
2429
+ const sensitiveIds = getSensitiveFieldIds(definition);
2430
+ if (sensitiveIds.length > 0) {
2431
+ const transportKey = yield fetchTransportKey(transportKeyEndpoint);
2432
+ for (const fieldId of sensitiveIds) {
2433
+ const plaintext = cleanValues[fieldId];
2434
+ if (typeof plaintext !== "string" || plaintext.length === 0) {
2435
+ delete payload[fieldId];
2436
+ continue;
2437
+ }
2438
+ payload[fieldId] = yield encryptSensitiveValue(
2439
+ plaintext,
2440
+ transportKey
2441
+ );
2442
+ }
2443
+ }
2444
+ const res = yield fetch(apiRoute, {
2445
+ method: "POST",
2446
+ headers: { "Content-Type": "application/json" },
2447
+ body: JSON.stringify(payload)
2448
+ });
2449
+ if (!res.ok) {
2450
+ const errBody = yield res.json().catch(() => null);
2451
+ throw new Error(
2452
+ (errBody == null ? void 0 : errBody.error) || `Submission failed (${res.status})`
2453
+ );
2454
+ }
2455
+ let body = null;
2456
+ try {
2457
+ body = yield res.json();
2458
+ } catch (e) {
2459
+ body = null;
2460
+ }
2461
+ setResponseData(body);
2462
+ setSubmitStatus("success");
2463
+ (_f = onFormSubmitCallback != null ? onFormSubmitCallback : (_d = globalTracker()) == null ? void 0 : _d.trackFormSubmit) == null ? void 0 : _f(
2464
+ definition.id,
2465
+ definition.name,
2466
+ (_e = extraData == null ? void 0 : extraData.submissionType) != null ? _e : "contact"
2467
+ );
2468
+ if (successBehavior === "reset" || successBehavior === "replace") {
2469
+ resetForm();
2470
+ }
2471
+ onSuccess == null ? void 0 : onSuccess(body != null ? body : void 0);
2472
+ const redirectUrl = getSafeRedirectUrl(
2473
+ definition.submitConfig.redirectUrl
2474
+ );
2475
+ if (redirectUrl) {
2476
+ window.location.assign(redirectUrl);
2477
+ }
2478
+ } catch (err) {
2479
+ setResponseData(null);
2480
+ setSubmitStatus("error");
2481
+ onError == null ? void 0 : onError(err instanceof Error ? err : new Error("Submission failed"));
2482
+ } finally {
2483
+ setSubmitting(false);
2484
+ }
2485
+ }),
2486
+ children: ({ isSubmitting, getFieldProps }) => {
2487
+ const showSubmitting = isSubmitting || previewSubmitting;
2488
+ const isDisabled = successBehavior === "disable" && effectiveSubmitStatus === "success";
2489
+ const submitLocked = showSubmitting || postSuccessCooldown || previewState === "success";
2490
+ return /* @__PURE__ */ jsxs(
2491
+ Form,
2492
+ {
2493
+ className: formClasses,
2494
+ style: formInlineStyle,
2495
+ "data-form-version": definition.version,
2496
+ children: [
2497
+ honeypotEnabled && /* @__PURE__ */ jsxs(
2498
+ "div",
2499
+ {
2500
+ "aria-hidden": "true",
2501
+ style: {
2502
+ position: "absolute",
2503
+ left: "-9999px",
2504
+ top: "auto",
2505
+ width: 0,
2506
+ height: 0,
2507
+ overflow: "hidden",
2508
+ opacity: 0,
2509
+ zIndex: -1
2510
+ },
2511
+ children: [
2512
+ /* @__PURE__ */ jsx("label", { htmlFor: HONEYPOT_FIELD_NAME, children: "Website (leave blank)" }),
2513
+ /* @__PURE__ */ jsx(
2514
+ "input",
2515
+ __spreadProps(__spreadValues({
2516
+ type: "text",
2517
+ id: HONEYPOT_FIELD_NAME
2518
+ }, getFieldProps(HONEYPOT_FIELD_NAME)), {
2519
+ tabIndex: -1,
2520
+ autoComplete: "off"
2521
+ })
2522
+ )
2523
+ ]
2524
+ }
2525
+ ),
2526
+ effectiveSubmitStatus === "success" && /* @__PURE__ */ jsx("div", { className: bannerWrapperClass, children: /* @__PURE__ */ jsx(SuccessBanner, { message: successMessage }) }),
2527
+ effectiveSubmitStatus === "error" && /* @__PURE__ */ jsx("div", { className: bannerWrapperClass, children: /* @__PURE__ */ jsx(
2528
+ ErrorBanner,
2529
+ {
2530
+ message: definition.submitConfig.errorMessage,
2531
+ onDismiss: () => setSubmitStatus("idle")
2532
+ }
2533
+ ) }),
2534
+ /* @__PURE__ */ jsx(
2535
+ "fieldset",
2536
+ {
2537
+ disabled: isDisabled,
2538
+ "aria-disabled": isDisabled,
2539
+ className: twMerge(
2540
+ "min-w-0 border-0 p-0",
2541
+ isStacked ? "space-y-8" : "",
2542
+ isDisabled ? "pointer-events-none opacity-60" : ""
2543
+ ),
2544
+ children: (() => {
2545
+ const submitButton = /* @__PURE__ */ jsxs(
2546
+ "button",
2547
+ {
2548
+ type: "submit",
2549
+ disabled: submitLocked || isDisabled,
2550
+ className: twMerge(
2551
+ buttonSizeClass,
2552
+ "inline-flex cursor-pointer items-center justify-center disabled:cursor-not-allowed disabled:opacity-60",
2553
+ getButtonClasses(style)
2554
+ ),
2555
+ style: getButtonStyle(style),
2556
+ "aria-busy": showSubmitting,
2557
+ children: [
2558
+ showSubmitting && /* @__PURE__ */ jsx(Spinner, {}),
2559
+ showSubmitting ? submittingText : definition.submitConfig.buttonText
2560
+ ]
2561
+ }
2562
+ );
2563
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2564
+ sortedSections.map((section, idx) => {
2565
+ const isLast = idx === sortedSections.length - 1;
2566
+ return /* @__PURE__ */ jsx(
2567
+ DynamicFormSection,
2568
+ {
2569
+ section,
2570
+ isLast,
2571
+ formDefaultTextColor: definition.defaultTextColor,
2572
+ inlineSubmit: inlineButton && isLast ? submitButton : void 0
2573
+ },
2574
+ section.id
2575
+ );
2576
+ }),
2577
+ !inlineButton && submitButton
2578
+ ] });
2579
+ })()
2580
+ }
2581
+ )
2582
+ ]
2583
+ }
2584
+ );
2585
+ }
2586
+ }
2587
+ ) }) });
2588
+ };
2589
+ function buildQueryString(opts) {
2590
+ const params = new URLSearchParams({
2591
+ projectId: opts.projectId,
2592
+ apiKey: opts.apiKey
2593
+ });
2594
+ if ("formId" in opts && opts.formId) params.set("formId", opts.formId);
2595
+ if ("formSlug" in opts && opts.formSlug) params.set("slug", opts.formSlug);
2596
+ return params.toString();
2597
+ }
2598
+ function useFormDefinition(opts) {
2599
+ const [definition, setDefinition] = useState(null);
2600
+ const [isLoading, setIsLoading] = useState(true);
2601
+ const [error, setError] = useState(null);
2602
+ const { cmsUrl, projectId, apiKey } = opts;
2603
+ const formId = "formId" in opts ? opts.formId : void 0;
2604
+ const formSlug = "formSlug" in opts ? opts.formSlug : void 0;
2605
+ useEffect(() => {
2606
+ let cancelled = false;
2607
+ function fetchDefinition() {
2608
+ return __async(this, null, function* () {
2609
+ setIsLoading(true);
2610
+ setError(null);
2611
+ try {
2612
+ const qs = buildQueryString(opts);
2613
+ const res = yield fetch(`${cmsUrl}/api/forms?${qs}`);
2614
+ if (!res.ok) {
2615
+ throw new Error(`Failed to fetch form definition: ${res.statusText}`);
2616
+ }
2617
+ const data = yield res.json();
2618
+ if (!cancelled) {
2619
+ setDefinition(data);
2620
+ }
2621
+ } catch (err) {
2622
+ if (!cancelled) {
2623
+ setError(err instanceof Error ? err : new Error("Failed to fetch form"));
2624
+ }
2625
+ } finally {
2626
+ if (!cancelled) {
2627
+ setIsLoading(false);
2628
+ }
2629
+ }
2630
+ });
2631
+ }
2632
+ fetchDefinition();
2633
+ return () => {
2634
+ cancelled = true;
2635
+ };
2636
+ }, [cmsUrl, projectId, apiKey, formId, formSlug]);
2637
+ return { definition, isLoading, error };
2638
+ }
2639
+ function getFormDefinition(opts) {
2640
+ return __async(this, null, function* () {
2641
+ var _a;
2642
+ try {
2643
+ const qs = buildQueryString(opts);
2644
+ const res = yield fetch(`${opts.cmsUrl}/api/forms?${qs}`, {
2645
+ next: { revalidate: (_a = opts.revalidate) != null ? _a : 3600 }
2646
+ });
2647
+ if (!res.ok) return null;
2648
+ return res.json();
2649
+ } catch (e) {
2650
+ return null;
2651
+ }
2652
+ });
2653
+ }
2654
+ var DEFAULT_HISTORY_LIMIT = 50;
2655
+ function applyUpdater(updater, current) {
2656
+ return typeof updater === "function" ? updater(current) : updater;
2657
+ }
2658
+ function useUndoRedo(initialState, options = {}) {
2659
+ var _a;
2660
+ const limit = (_a = options.historyLimit) != null ? _a : DEFAULT_HISTORY_LIMIT;
2661
+ const [history, setHistory] = useState(() => ({
2662
+ past: [],
2663
+ present: initialState,
2664
+ future: []
2665
+ }));
2666
+ const setState = useCallback(
2667
+ (updater) => {
2668
+ setHistory((h) => {
2669
+ const next = applyUpdater(updater, h.present);
2670
+ if (Object.is(next, h.present)) return h;
2671
+ const past = [...h.past, h.present];
2672
+ if (past.length > limit) past.splice(0, past.length - limit);
2673
+ return { past, present: next, future: [] };
2674
+ });
2675
+ },
2676
+ [limit]
2677
+ );
2678
+ const reset = useCallback((value) => {
2679
+ setHistory(
2680
+ (h) => Object.is(value, h.present) ? h : { past: [], present: value, future: [] }
2681
+ );
2682
+ }, []);
2683
+ const undo = useCallback(() => {
2684
+ setHistory((h) => {
2685
+ if (h.past.length === 0) return h;
2686
+ const previous = h.past[h.past.length - 1];
2687
+ const past = h.past.slice(0, -1);
2688
+ return { past, present: previous, future: [h.present, ...h.future] };
2689
+ });
2690
+ }, []);
2691
+ const redo = useCallback(() => {
2692
+ setHistory((h) => {
2693
+ if (h.future.length === 0) return h;
2694
+ const [next, ...rest] = h.future;
2695
+ return { past: [...h.past, h.present], present: next, future: rest };
2696
+ });
2697
+ }, []);
2698
+ return [
2699
+ history.present,
2700
+ setState,
2701
+ undo,
2702
+ redo,
2703
+ history.past.length > 0,
2704
+ history.future.length > 0,
2705
+ { reset, historySize: history.past.length }
2706
+ ];
2707
+ }
2708
+ function useUndoRedoShortcuts(opts) {
2709
+ const { undo, redo, enabled = true } = opts;
2710
+ useEffect(() => {
2711
+ if (!enabled || typeof window === "undefined") return;
2712
+ const handler = (e) => {
2713
+ const target = e.target;
2714
+ if (target) {
2715
+ const tag = target.tagName;
2716
+ const editable = target.isContentEditable;
2717
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || editable) {
2718
+ return;
2719
+ }
2720
+ }
2721
+ const meta = e.metaKey || e.ctrlKey;
2722
+ if (!meta) return;
2723
+ const key = e.key.toLowerCase();
2724
+ if (key !== "z") return;
2725
+ e.preventDefault();
2726
+ if (e.shiftKey) {
2727
+ redo();
2728
+ } else {
2729
+ undo();
2730
+ }
2731
+ };
2732
+ window.addEventListener("keydown", handler);
2733
+ return () => window.removeEventListener("keydown", handler);
2734
+ }, [undo, redo, enabled]);
2735
+ }
2736
+ var DEFAULT_DRAG_TYPE = "application/x-vt-reorder";
2737
+ function useDragReorder({
2738
+ items,
2739
+ getId,
2740
+ onReorder,
2741
+ dragType = DEFAULT_DRAG_TYPE
2742
+ }) {
2743
+ const [state, setState] = useState({
2744
+ draggingId: null,
2745
+ dragOverId: null,
2746
+ dragOverPosition: null
2747
+ });
2748
+ const lastOverRef = useRef(null);
2749
+ const reset = useCallback(() => {
2750
+ lastOverRef.current = null;
2751
+ setState({ draggingId: null, dragOverId: null, dragOverPosition: null });
2752
+ }, []);
2753
+ const itemHandlers = useCallback(
2754
+ (id) => ({
2755
+ draggable: true,
2756
+ onDragStart: (e) => {
2757
+ e.stopPropagation();
2758
+ try {
2759
+ e.dataTransfer.setData(dragType, id);
2760
+ e.dataTransfer.setData("text/plain", id);
2761
+ } catch (e2) {
2762
+ }
2763
+ e.dataTransfer.effectAllowed = "move";
2764
+ setState({
2765
+ draggingId: id,
2766
+ dragOverId: null,
2767
+ dragOverPosition: null
2768
+ });
2769
+ },
2770
+ onDragEnd: () => {
2771
+ reset();
2772
+ },
2773
+ onDragOver: (e) => {
2774
+ const types = Array.from(e.dataTransfer.types);
2775
+ if (!types.includes(dragType)) return;
2776
+ e.preventDefault();
2777
+ e.stopPropagation();
2778
+ e.dataTransfer.dropEffect = "move";
2779
+ const rect = e.currentTarget.getBoundingClientRect();
2780
+ const midpoint = rect.top + rect.height / 2;
2781
+ const position = e.clientY < midpoint ? "before" : "after";
2782
+ if (lastOverRef.current !== id || state.dragOverPosition !== position) {
2783
+ lastOverRef.current = id;
2784
+ setState((s) => __spreadProps(__spreadValues({}, s), {
2785
+ dragOverId: id,
2786
+ dragOverPosition: position
2787
+ }));
2788
+ }
2789
+ },
2790
+ onDragLeave: (e) => {
2791
+ const related = e.relatedTarget;
2792
+ if (!related || !e.currentTarget.contains(related)) {
2793
+ if (lastOverRef.current === id) {
2794
+ lastOverRef.current = null;
2795
+ setState((s) => __spreadProps(__spreadValues({}, s), {
2796
+ dragOverId: null,
2797
+ dragOverPosition: null
2798
+ }));
2799
+ }
2800
+ }
2801
+ },
2802
+ onDrop: (e) => {
2803
+ const draggedId = e.dataTransfer.getData(dragType);
2804
+ e.preventDefault();
2805
+ e.stopPropagation();
2806
+ if (!draggedId || draggedId === id) {
2807
+ reset();
2808
+ return;
2809
+ }
2810
+ const fromIdx = items.findIndex((it) => getId(it) === draggedId);
2811
+ const toIdx = items.findIndex((it) => getId(it) === id);
2812
+ if (fromIdx < 0 || toIdx < 0) {
2813
+ reset();
2814
+ return;
2815
+ }
2816
+ const rect = e.currentTarget.getBoundingClientRect();
2817
+ const midpoint = rect.top + rect.height / 2;
2818
+ const position = e.clientY < midpoint ? "before" : "after";
2819
+ const next = [...items];
2820
+ const [moved] = next.splice(fromIdx, 1);
2821
+ let insertIdx = next.findIndex((it) => getId(it) === id);
2822
+ if (insertIdx < 0) insertIdx = next.length;
2823
+ if (position === "after") insertIdx += 1;
2824
+ next.splice(insertIdx, 0, moved);
2825
+ onReorder(next);
2826
+ reset();
2827
+ }
2828
+ }),
2829
+ [items, getId, onReorder, dragType, reset, state.dragOverPosition]
2830
+ );
2831
+ const isDragging = useCallback(
2832
+ (id) => state.draggingId === id,
2833
+ [state.draggingId]
2834
+ );
2835
+ const dropIndicator = useCallback(
2836
+ (id) => {
2837
+ if (state.dragOverId !== id) return null;
2838
+ if (state.draggingId === id) return null;
2839
+ return state.dragOverPosition;
2840
+ },
2841
+ [state.dragOverId, state.draggingId, state.dragOverPosition]
2842
+ );
2843
+ return __spreadProps(__spreadValues({}, state), {
2844
+ itemHandlers,
2845
+ isDragging,
2846
+ dropIndicator
2847
+ });
2848
+ }
2849
+
2850
+ export { APPLICATION_STATUS_KEYS, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, DynamicForm, DynamicFormField, DynamicFormSection, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, HONEYPOT_FIELD_NAME, NEWSLETTER_ALLOWED_FIELD_TYPES, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, sameAsToggleKey, useDragReorder, useFormDefinition, useUndoRedo, useUndoRedoShortcuts };
2851
+ //# sourceMappingURL=index.mjs.map
2852
+ //# sourceMappingURL=index.mjs.map