@formhaus/core 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,13 +47,13 @@ Write the JSON by hand, or use the [`/formhaus:formhaus-create-form`](https://fo
47
47
 
48
48
  ## Navigation and submission
49
49
 
50
- Use `nextStepAsync()`, `prevStepAsync()` and `submitAsync(handler)` for cancellable async before/after hooks. Synchronous navigation remains available without lifecycle hooks. See [step navigation and lifecycle](https://formhaus.dev/guide/steps.html#lifecycle-hooks).
50
+ `await engine.next()`, `back()`, `skip()` and `submit(handler)` validate and run the async before/after hooks, which can cancel the action. See [step navigation and lifecycle](https://formhaus.dev/guide/steps.html#lifecycle-hooks).
51
51
 
52
52
  Step `routes` choose an ordered forward path from answers. Back, progress, validation and submission follow that path. See [branching and retained answers](https://formhaus.dev/guide/steps.html#route-between-branches).
53
53
 
54
54
  ## Server-side validation
55
55
 
56
- `validateSubmission()` checks a submitted payload against the definition without a browser. It drops hidden, skipped and unknown keys, checks value types and ignores custom validators. Strings over 10,000 characters or the field's `maxLength` fail before any rule runs. `pattern` rules still run on untrusted input, so bound the execution time of the call.
56
+ `validateSubmission()` checks a submitted payload against the definition without a browser. It drops hidden, skipped and unknown keys and checks value types. Custom validators run only when you pass them in `validators`. Strings over 10,000 characters or the field's `maxLength` fail before any rule runs. `pattern` rules still run on untrusted input, so bound the execution time of the call.
57
57
 
58
58
  ```ts
59
59
  import { validateSubmission } from '@formhaus/core/server';
@@ -61,12 +61,12 @@ import { validateSubmission } from '@formhaus/core/server';
61
61
  const { values, errors } = validateSubmission(definition, body.values, { skippedSteps: body.skippedSteps });
62
62
  ```
63
63
 
64
- `checkDefinition()` splits the `validateDefinition()` output into errors, which `FormEngine` rejects, and warnings.
64
+ `checkDefinition()` returns a list of issues with a `code`, a `severity` (`error` or `warning`), a JSON pointer `path` and a `message`. `FormEngine` throws a `FormDefinitionError` on errors.
65
65
 
66
66
  ```ts
67
- import { checkDefinition } from '@formhaus/core/server';
67
+ import { checkDefinition } from '@formhaus/core';
68
68
 
69
- const { errors, warnings } = checkDefinition(definition);
69
+ const errors = checkDefinition(definition).filter((issue) => issue.severity === 'error');
70
70
  ```
71
71
 
72
72
  `@formhaus/core/server.iife.js` exposes both functions on a `Formhaus` global for embedded JS runtimes.
@@ -88,7 +88,7 @@ Theme via CSS custom properties (`--fh-color-primary`, `--fh-radius`, `--fh-gap`
88
88
  - Field validation (required, min/max, pattern, matchField, custom validators)
89
89
  - Visibility conditions (`show` / `showAny`) with cascade-clearing of hidden values
90
90
  - Multi-step forms with conditional steps and per-step validation
91
- - Async step validation via `onStepValidate` + `nextStepAsync()`
91
+ - Async step validation via `onStepValidate` + `next()`
92
92
  - Definition validation (duplicate keys, invalid regex, circular show conditions)
93
93
 
94
94
  ## Granular subscriptions
@@ -0,0 +1,10 @@
1
+ import { f as FormDefinition } from './definition-Bufih_Bx.js';
2
+ import { D as DefinitionIssue } from './validate-field-glVVoN3E.js';
3
+
4
+ interface CheckDefinitionOptions {
5
+ validators?: Record<string, unknown>;
6
+ }
7
+ declare function checkDefinition(input: unknown, options?: CheckDefinitionOptions): DefinitionIssue[];
8
+ declare function parseDefinition(input: unknown, options?: CheckDefinitionOptions): FormDefinition;
9
+
10
+ export { type CheckDefinitionOptions as C, checkDefinition as c, parseDefinition as p };
@@ -0,0 +1,3 @@
1
+ var xt=["eq","neq","in","notIn","notEmpty","gt","gte","lt","lte"];function F(t){return t==null||t===""||Array.isArray(t)&&!t.length}function nt(t){let r=typeof t=="string"&&t.trim()!==""?Number(t):t;return typeof r=="number"&&Number.isFinite(r)?r:void 0}function v(t,r,e){let n=nt(t);return n!==void 0&&e(n,r)}function T(t,r){let e=r[t.field];return t.eq!==void 0?e===t.eq:t.neq!==void 0?e!==t.neq:t.in!==void 0?t.in.includes(e):t.notIn!==void 0?!t.notIn.includes(e):t.notEmpty!==void 0?!t.notEmpty||!F(e):t.gt!==void 0?v(e,t.gt,(n,o)=>n>o):t.gte!==void 0?v(e,t.gte,(n,o)=>n>=o):t.lt!==void 0?v(e,t.lt,(n,o)=>n<o):t.lte!==void 0?v(e,t.lte,(n,o)=>n<=o):false}var L=class extends Error{constructor(e,n){super(`The action completed, but ${e} failed: ${n instanceof Error?n.message:String(n)}`);this.phase=e;this.committed=true;this.name="FormLifecycleError",this.cause=n;}};async function I(t,r){try{await r();}catch(e){throw new L(t,e)}}var l={email:"Enter a valid email",number:"Enter a number",boolean:"Must be true or false",option:"Select one of the available options",options:"Must be a list of available options",string:"Must be text",date:"Enter a valid date",datetime:"Enter a valid date and time",file:"Must be a file reference",value:"Invalid value"};function p(t,r){switch(t){case "required":return "This field is required";case "minLength":return `Must be at least ${r?.min} ${r?.unit??"characters"}`;case "maxLength":return `Must be at most ${r?.max} ${r?.unit??"characters"}`;case "min":return `Must be at least ${r?.min}`;case "max":return `Must be at most ${r?.max}`;case "pattern":return "Invalid format";case "matchField":return "Fields must match";default:return "Invalid value"}}function c(t,r){let e=n=>T(n,r);return (t.show??[]).every(e)&&(!t.showAny?.length||t.showAny.some(e))}var j=new Set(["checkbox","switch"]),ot=new Set(["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","date","datetime","textarea"]),E=1e4,st=254,it=1e3,at=/^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/,ut=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,_="\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",lt=new RegExp(`^${_}$`),dt=new RegExp(`^${_}T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,3})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)?$`),ft=new Set(["text","phone","password","textarea","autocomplete"]),pt=new Map([["email",[at,l.email,st]],["date",[lt,l.date,E]],["datetime",[dt,l.datetime,E]]]);function At(t,r){if(t.type!=="number"||typeof r!="string"||!ut.test(r))return r;let e=Number(r);return Number.isFinite(e)?e:r}function q(t,r){return !t.options||t.options.some(e=>e.value===r)}function K(t,r){let e=Math.min(E,t.validation?.maxLength??E);return r.length<=e?null:t.validation?.maxLengthMessage??p("maxLength",{max:e})}function ct(t,r){return Array.isArray(r)?r.length>(t.options?.length??it)?l.option:r.every(n=>typeof n=="string"&&n.length<=E&&q(t,n))?null:l.option:l.options}function R(t,r,e){return typeof r=="string"?K(t,r):e}function mt(t,r,[e,n,o]){return typeof r!="string"?n:K(t,r)??(r.length<=o&&e.test(r)?null:n)}function ht(t,r){return typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)?null:R(t,r,l.value)}function yt(t,r){return r==null||r===""||t.type==="multiselect"&&Array.isArray(r)&&!r.length}function bt(t,r){if(yt(t,r))return null;if(j.has(t.type))return typeof r=="boolean"?null:l.boolean;if(t.type==="number")return typeof r=="number"&&Number.isFinite(r)?null:l.number;if(t.type==="multiselect")return ct(t,r);if(t.type==="file")return R(t,r,l.file);let e=pt.get(t.type);return e?mt(t,r,e):t.type==="select"||t.type==="radio"?R(t,r,l.option)??(q(t,r)?null:l.option):ft.has(t.type)?R(t,r,l.string):ht(t,r)}function B(t,r){return ot.has(t.type)?bt(t.optionsFrom?{...t,options:void 0}:t,r):null}function St(t,r){return F(t)||t===false&&j.has(r.type)}function Y(t,r,e,n){let o=e[`min${r}`],s=e[`max${r}`];if(o!==void 0&&t<o)return e[`min${r}Message`]??p(`min${r}`,{min:o,unit:n});if(s!==void 0&&t>s)return e[`max${r}Message`]??p(`max${r}`,{max:s,unit:n})}function Ft(t,r){if(r.pattern!==void 0)try{return new RegExp(r.pattern).test(String(t))?void 0:r.patternMessage??p("pattern")}catch{return}}function b(t,r,e,n){let o=t.validation??{},s=o.matchFieldMessage??p("matchField");if(St(r,t))return o.required?typeof o.required=="string"?o.required:p("required"):o.matchField!==void 0&&!F(e[o.matchField])?s:null;let i=B(t,r);if(i)return i;let a=typeof r=="string"||Array.isArray(r)?Y(r.length,"Length",o,Array.isArray(r)?"items":void 0):typeof r=="number"?Y(r,"",o):void 0,d=o.matchField!==void 0&&r!==e[o.matchField]?s:void 0;return (a??Ft(r,o)??d??(o.validator?n?.[o.validator]?.(r,e):void 0))||null}function k(t,r,e){return V(t.fields,r,e)}function V(t,r,e){let n={};for(let o of t){if(!c(o,r))continue;let s=b(o,r[o.key],r,e);s&&(n[o.key]=s);}return n}function Gt(t){return [...t.show??[],...t.showAny??[]].map(r=>r.field)}function Ht(t){return t.steps?.length?t.steps.flatMap(r=>r.fields):t.fields??[]}function C(t,r){let e={};for(let n of t)n.defaultValue!==void 0&&(e[n.key]=n.defaultValue);return Object.assign(e,r)}function h(t,r){let e=new Set([...Object.keys(t),...Object.keys(r)]);return new Set([...e].filter(n=>!Object.is(t[n],r[n])))}function G(t){return t.visibleSteps.map(r=>r.id).join(`
2
+ `)}function x(t,r){let e=G(t);return ()=>G(t)!==e||Object.keys(r).some(n=>r[n]!==void 0&&!Object.is(t.values[n],r[n]))}function H(t,r,e=false){let n=t.errors;t.state.errors={},t.state.topLevelErrors=[];for(let[s,i]of Object.entries(r))t.visibility.isFieldVisible(s,t.values)?t.errors[s]=i:t.topLevelErrors.push(i);let o=e&&X(t,r);t.notify({fieldKeys:h(n,t.errors),structureChanged:o});}function X(t,r){let e=Object.keys(r).find(o=>t.errors[o]!==void 0),n=e&&t.isMultiStep?t.visibility.findStepIndex(e,t.values,t.currentStepIndex):null;return n===null||n===t.currentStepIndex?false:(t.state.currentStepIndex=n,true)}function Jt(t,r){let e=[];for(let n of t.visibility.allFields)n.validation?.matchField!==r||t.errors[n.key]===void 0||b(n,t.values[n.key],y(t),t.validators)||(delete t.errors[n.key],e.push(n.key));return e}function z(t){let r=new Set(t.visibleSteps.flatMap(n=>n.fields.map(o=>o.key))),e=Object.keys(t.errors).filter(n=>!r.has(n));for(let n of e)delete t.errors[n];return e}function y(t){return M(t)}function Et(t,r){for(let e of [...t.skipped.values()].flat())delete r[e];return r}function $(t,r=false){let e=t.errors,n={};if(t.isMultiStep)for(let s of t.visibleSteps)t.skipped.has(s.id)||Object.assign(n,k(s,y(t),t.validators));else Object.assign(n,V(t.definition.fields??[],y(t),t.validators));t.state.errors=n;let o=r&&X(t,n);return t.notify({fieldKeys:h(e,n),structureChanged:o}),n}function Qt(t,r){let e=t.visibility.activeField(r,t.values);if(!e)return null;let n=t.errors[r],o=b(e,t.values[r],y(t),t.validators);o?t.errors[r]=o:delete t.errors[r];let s=Object.is(n,t.errors[r])?[]:[r];return t.notify({fieldKeys:s}),o}function M(t){return Et(t,{...t.visibility.conditionValues(t.values)})}function Ut(t,r){let e=t.values,n=t.errors,o=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.state.submitting=false,t.state.values=C(t.visibility.allFields,r),t.state.errors={},t.state.topLevelErrors=[],t.state.fieldLoading={},t.state.stepValidating=false,t.state.currentStepIndex=0,t.skipped.clear(),t.visibility.reconcileHidden(t.values,t.errors);let s=h(e,t.values),i=new Set([...s,...h(n,t.errors),...o]);t.notify({fieldKeys:i,structureChanged:true,valuesChanged:s.size>0});}function N(t,r){let e=t.steps??[],n=new Map(e.map((i,a)=>[i.id,a])),o=[],s={};for(let i=0;i<e.length;){let a=e[i];if(!c(a,s)){i++;continue}o.push(a),Object.assign(s,Z(a,r,s));let d=a.routes?.find(u=>c(u,s)&&(u.to===null||(n.get(u.to)??-1)>i&&c(e[n.get(u.to)],s)));if(d?.to===null)break;i=d?n.get(d.to):i+1;}return o}function er(t,r,e){let n=t[e]??t[t.length-1],o=r.findIndex(i=>i.id===n?.id);if(o!==-1)return o;let s=new Map(r.map((i,a)=>[i.id,a]));for(let i=Math.min(e-1,t.length-1);i>=0;i--){let a=s.get(t[i].id);if(a!==void 0)return a}return 0}function Z(t,r,e){let n={...e};for(let s of t.fields)n[s.key]=r[s.key];let o={};for(let s of t.fields)c(s,n)&&r[s.key]!==void 0&&(o[s.key]=r[s.key]);return o}var W=class{constructor(r){this.definition=r;this.source=null;this.activeStepList=[];this.activeValueMap={};}invalidate(){this.source=null;}steps(r){return this.refresh(r),this.activeStepList}values(r){return this.refresh(r),this.activeValueMap}refresh(r){if(this.source===r)return;this.source=r,this.activeStepList=N(this.definition,r);let e={},n=this.definition.steps?.length?this.activeStepList:[{fields:this.definition.fields??[]}];for(let o of n)Object.assign(e,Z(o,r,e));this.activeValueMap=e;}};function J(t){let r=t.currentStep?.fields??[],e={...t.values};for(let{key:n}of r)delete e[n];return Object.assign(e,C(r))}function P(t){return N(t.definition,J(t))[t.currentStepIndex+1]}function O(t){let r=t.currentStep,e=r.fields.map(({key:o})=>o);t.state.values=J(t);for(let o of e)delete t.errors[o];t.skipped.set(r.id,e),t.visibility.reconcileHidden(t.values,t.errors),t.visibility.markChanged(true,true);let n=z(t);return t.notify({fieldKeys:[...e,...n],structureChanged:true,valuesChanged:true}),e}function A(t){let r=t.currentStep;r&&t.skipped.delete(r.id);}function ar(t,r){return t.state.currentStepIndex=r,t.notify({structureChanged:true}),O(t)}async function Q(t,r,e=false){if(t.submitting||t.stepValidating)return false;e||A(t);let n={...t.lifecycle},o=false,s=t.validationEpoch,i=++t.operationEpoch,a=M(t),d=x(t,a),u=()=>s!==t.validationEpoch||i!==t.operationEpoch||d();t.state.submitting=true,t.notify();try{if(u()||Object.keys($(t,!0)).length>0||u())return !1;if(n.onBeforeSubmit){let w=await n.onBeforeSubmit(a);if(u()||w===!1)return !1}if(u())return !1;if(n.onBeforeSubmit){if(Object.keys($(t,!0)).length>0||u())return !1;a=M(t);}o=!0;let f=[...t.skipped.keys()];return await r(a,[...f]),i!==t.operationEpoch||await I("afterSubmit",()=>n.onAfterSubmit?.(a,f)),!0}catch(f){if(!o&&u())return false;throw f}finally{i===t.operationEpoch&&(t.state.submitting=false,t.notify());}}function U(t){let r=t.currentStep;if(!r)return true;let e=k(r,y(t),t.validators);if(Object.keys(e).length===0)return false;let n={...t.errors};return Object.assign(t.errors,e),t.notify({fieldKeys:h(n,t.errors)}),true}function tt(t,r){t.validationEpoch++,t.state.currentStepIndex=r,t.notify({structureChanged:true});}async function kr(t,r){if(!t.isMultiStep||t.stepValidating||t.submitting||!t.currentStep?.skip)return false;if(P(t))return kt(t,"next","skip");let e=t.currentStep;if(!r||!e)return false;let n=t.values,o={...t.errors},s=false,i=O(t),a=t.values,d=x(t,{...a});try{return await Q(t,async(u,f)=>{await r(u,f),s=!0;},!0)}finally{!s&&t.values===a&&!d()&&(t.state.values=n,t.state.errors={...o,...t.errors},t.skipped.delete(e.id),t.notify({fieldKeys:i,structureChanged:true,valuesChanged:true}));}}async function kt(t,r,e=r){let n=e==="skip";if(!t.isMultiStep||t.stepValidating||t.submitting||!n&&(r==="next"?t.isLastStep:t.isFirstStep))return false;let o=t.currentStep,s=r==="next"&&!n;if(s&&A(t),s&&U(t))return false;let i={...t.lifecycle},a=t.onStepValidate,d=false,f=t.currentStepIndex+(r==="next"?1:-1),w=n?P(t):t.visibleSteps[f];if(!w)return false;let g={fromStepId:o.id,toStepId:w.id,reason:e,values:{...y(t)}},rt=t.validationEpoch,D=++t.operationEpoch,et=x(t,g.values),S=()=>rt!==t.validationEpoch||D!==t.operationEpoch||t.currentStep?.id!==o.id||et();t.state.stepValidating=true,t.notify();try{if(S())return !1;if(s&&a){let m=await a(o.id,g.values);if(S())return !1;if(m&&Object.keys(m).length>0)return H(t,m),!1}if(i.onBeforeStepChange){let m=await i.onBeforeStepChange(g);if(S()||m===!1)return !1}return S()||s&&U(t)?!1:(d=!0,n&&O(t),tt(t,f),await I("afterStepChange",()=>i.onAfterStepChange?.(g)),!0)}catch(m){if(!d&&S())return false;throw m}finally{D===t.operationEpoch&&(t.state.stepValidating=false,t.notify());}}function xr(t,r){if(!t.isMultiStep)return;let e=t.visibility.findStepIndex(r,t.values,t.currentStepIndex);e===t.currentStepIndex?t.notify():e!==null&&tt(t,e);}export{xr as A,xt as a,T as b,Gt as c,Ht as d,C as e,L as f,p as g,c as h,At as i,bt as j,b as k,k as l,V as m,H as n,Jt as o,z as p,$ as q,Qt as r,M as s,Ut as t,er as u,W as v,ar as w,Q as x,kr as y,kt as z};//# sourceMappingURL=chunk-BXI5P7PF.js.map
3
+ //# sourceMappingURL=chunk-BXI5P7PF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/visibility/evaluate-condition.ts","../src/engine/lifecycle-error.ts","../src/validation/default-messages.ts","../src/visibility/is-visible.ts","../src/validation/type-checks.ts","../src/validation/validate-field.ts","../src/validation/validate-step.ts","../src/engine/engine-utils.ts","../src/engine/pending-inputs.ts","../src/engine/validation-state.ts","../src/engine/step-routes.ts","../src/engine/step-skip.ts","../src/engine/submission.ts","../src/engine/navigation.ts"],"names":["CONDITION_OPERATORS","isBlank","value","toNumber","number","compare","operand","test","evaluateCondition","condition","values","a","b","FormLifecycleError","phase","cause","afterCommit","callback","error","TYPE_MESSAGES","getDefaultMessage","rule","params","isVisible","field","matches","BOOLEAN_TYPES","CLIENT_TYPES","MAX_STRING_LENGTH","MAX_EMAIL_LENGTH","MAX_ITEMS","EMAIL","DECIMAL","DATE","DATE_ONLY","DATE_TIME","TEXT_TYPES","FORMATS","normalizeValue","parsed","isOption","option","lengthError","max","multiselectError","item","stringError","message","formatError","format","primitiveError","typeError","clientTypeError","isEmpty","boundError","size","rules","unit","min","patternError","validateFieldValue","allValues","validators","matchMessage","typeIssue","sizeError","matchError","validateStep","step","validateFields","fields","errors","conditionFields","source","getAllFields","definition","createValues","initialValues","getChangedKeys","previous","next","keys","key","activePath","engine","watchCheckedInputs","checked","path","applyValidationErrors","navigate","previousErrors","structureChanged","moveToFirstError","firstErrorKey","targetIndex","clearResolvedMatchErrors","cleared","getValidationValues","pruneOffPathErrors","pathFields","pruned","getSubmitValues","withoutSkipped","validateForm","validateOne","previousError","fieldKeys","resetEngine","previousValues","loadingFields","changedValues","changedFields","activeSteps","steps","indexes","index","result","available","stepValues","route","reconcileStepIndex","previousStep","preserved","nextIds","before","predecessor","candidates","ActivePath","groups","resetValues","skipTarget","skipCurrentStep","includeCurrentStep","skipStepAt","submitForm","submit","keepSkipped","lifecycle","dispatched","epoch","operation","inputsChanged","stale","allowed","skippedSteps","hasStepErrors","moveTo","skipStep","changeStep","committed","skippedValues","edited","submitted","skipped","direction","reason","skipping","validating","validate","toIndex","target","context","goToStepWithField","fieldKey"],"mappings":"AAEO,IAAMA,EAAAA,CAAsB,CAAC,IAAA,CAAM,KAAA,CAAO,KAAM,OAAA,CAAS,UAAA,CAAY,IAAA,CAAM,KAAA,CAAO,IAAA,CAAM,KAAK,EAE7F,SAASC,EAAQC,CAAAA,CAAyB,CAC/C,OAAOA,CAAAA,EAAS,IAAA,EAAQA,CAAAA,GAAU,EAAA,EAAO,KAAA,CAAM,QAAQA,CAAK,CAAA,EAAK,CAACA,CAAAA,CAAM,MAC1E,CAEA,SAASC,EAAAA,CAASD,CAAAA,CAAoC,CACpD,IAAME,CAAAA,CAAS,OAAOF,CAAAA,EAAU,QAAA,EAAYA,CAAAA,CAAM,IAAA,EAAK,GAAM,GAAK,MAAA,CAAOA,CAAK,CAAA,CAAIA,CAAAA,CAClF,OAAO,OAAOE,CAAAA,EAAW,QAAA,EAAY,MAAA,CAAO,SAASA,CAAM,CAAA,CAAIA,CAAAA,CAAS,MAC1E,CAEA,SAASC,CAAAA,CAAQH,CAAAA,CAAgBI,EAAiBC,CAAAA,CAA4D,CAC5G,IAAMH,CAAAA,CAASD,GAASD,CAAK,CAAA,CAC7B,OAAOE,CAAAA,GAAW,QAAaG,CAAAA,CAAKH,CAAAA,CAAQE,CAAO,CACrD,CAEO,SAASE,CAAAA,CACdC,CAAAA,CACAC,EACS,CACT,IAAMR,CAAAA,CAAQQ,CAAAA,CAAOD,EAAU,KAAK,CAAA,CACpC,OAAIA,CAAAA,CAAU,KAAO,MAAA,CAAkBP,CAAAA,GAAUO,CAAAA,CAAU,EAAA,CACvDA,CAAAA,CAAU,GAAA,GAAQ,MAAA,CAAkBP,CAAAA,GAAUO,EAAU,GAAA,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AO,CAAC,EAC1E,CAAA,CAAA,CACT,CAAA,MAAS/I,CAAAA,CAAO,CACd,GAAI,CAACmI,GAAaP,CAAAA,EAAM,CAAG,OAAO,MAAA,CAClC,MAAM5H,CACR,CAAA,OAAE,CACI0H,CAAAA,GAAcxD,CAAAA,CAAO,cAAA,GACvBA,CAAAA,CAAO,MAAM,cAAA,CAAiB,KAAA,CAC9BA,CAAAA,CAAO,MAAA,EAAO,EAElB,CACF,CAEO,SAAS8E,EAAAA,CAAkB9E,CAAAA,CAAyB+E,CAAAA,CAAwB,CACjF,GAAI,CAAC/E,CAAAA,CAAO,WAAA,CAAa,OACzB,IAAMU,CAAAA,CAAcV,CAAAA,CAAO,WAAW,aAAA,CACpC+E,CAAAA,CACA/E,CAAAA,CAAO,MAAA,CACPA,CAAAA,CAAO,gBACT,EACIU,CAAAA,GAAgBV,CAAAA,CAAO,gBAAA,CAAkBA,CAAAA,CAAO,MAAA,EAAO,CAClDU,IAAgB,IAAA,EAAMoD,EAAAA,CAAO9D,CAAAA,CAAQU,CAAW,EAC3D","file":"chunk-BXI5P7PF.js","sourcesContent":["import type { ShowCondition } from '../types';\n\nexport const CONDITION_OPERATORS = ['eq', 'neq', 'in', 'notIn', 'notEmpty', 'gt', 'gte', 'lt', 'lte'] as const;\n\nexport function isBlank(value: unknown): boolean {\n return value == null || value === '' || (Array.isArray(value) && !value.length);\n}\n\nfunction toNumber(value: unknown): number | undefined {\n const number = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;\n return typeof number === 'number' && Number.isFinite(number) ? number : undefined;\n}\n\nfunction compare(value: unknown, operand: number, test: (value: number, operand: number) => boolean): boolean {\n const number = toNumber(value);\n return number !== undefined && test(number, operand);\n}\n\nexport function evaluateCondition(\n condition: ShowCondition,\n values: Record<string, unknown>,\n): boolean {\n const value = values[condition.field];\n if (condition.eq !== undefined) return value === condition.eq;\n if (condition.neq !== undefined) return value !== condition.neq;\n if (condition.in !== undefined) return condition.in.includes(value as string | number);\n if (condition.notIn !== undefined) return !condition.notIn.includes(value as string | number);\n if (condition.notEmpty !== undefined) return !condition.notEmpty || !isBlank(value);\n if (condition.gt !== undefined) return compare(value, condition.gt, (a, b) => a > b);\n if (condition.gte !== undefined) return compare(value, condition.gte, (a, b) => a >= b);\n if (condition.lt !== undefined) return compare(value, condition.lt, (a, b) => a < b);\n if (condition.lte !== undefined) return compare(value, condition.lte, (a, b) => a <= b);\n return false;\n}\n","export class FormLifecycleError extends Error {\n readonly committed = true;\n readonly cause: unknown;\n\n constructor(readonly phase: 'afterStepChange' | 'afterSubmit', cause: unknown) {\n super(`The action completed, but ${phase} failed: ${cause instanceof Error ? cause.message : String(cause)}`);\n this.name = 'FormLifecycleError';\n this.cause = cause;\n }\n}\n\nexport async function afterCommit(phase: 'afterStepChange' | 'afterSubmit', callback: () => void | Promise<void>): Promise<void> {\n try { await callback(); }\n catch (error) { throw new FormLifecycleError(phase, error); }\n}\n","export const TYPE_MESSAGES = {\n email: 'Enter a valid email',\n number: 'Enter a number',\n boolean: 'Must be true or false',\n option: 'Select one of the available options',\n options: 'Must be a list of available options',\n string: 'Must be text',\n date: 'Enter a valid date',\n datetime: 'Enter a valid date and time',\n file: 'Must be a file reference',\n value: 'Invalid value',\n};\n\nexport type ValidationRule = 'required' | 'minLength' | 'maxLength' | 'min' | 'max' | 'pattern' | 'matchField';\n\nexport function getDefaultMessage(rule: ValidationRule, params?: Record<string, unknown>): string {\n switch (rule) {\n case 'required':\n return 'This field is required';\n case 'minLength':\n return `Must be at least ${params?.min} ${params?.unit ?? 'characters'}`;\n case 'maxLength':\n return `Must be at most ${params?.max} ${params?.unit ?? 'characters'}`;\n case 'min':\n return `Must be at least ${params?.min}`;\n case 'max':\n return `Must be at most ${params?.max}`;\n case 'pattern':\n return 'Invalid format';\n case 'matchField':\n return 'Fields must match';\n default:\n return 'Invalid value';\n }\n}\n","import type { FormField, ShowCondition } from '../types';\nimport { evaluateCondition } from './evaluate-condition';\n\nexport function isVisible(\n field: Pick<FormField, 'show' | 'showAny'>,\n values: Record<string, unknown>,\n): boolean {\n const matches = (condition: ShowCondition) => evaluateCondition(condition, values);\n return (field.show ?? []).every(matches) && (!field.showAny?.length || field.showAny.some(matches));\n}\n","import type { FormField } from '../types';\nimport { getDefaultMessage, TYPE_MESSAGES } from './default-messages';\n\nexport const BOOLEAN_TYPES = new Set(['checkbox', 'switch']);\nconst CLIENT_TYPES = new Set(['text', 'email', 'phone', 'number', 'password', 'select', 'autocomplete', 'multiselect', 'checkbox', 'radio', 'switch', 'date', 'datetime', 'textarea']);\n\nexport const MAX_STRING_LENGTH = 10000;\nconst MAX_EMAIL_LENGTH = 254;\nconst MAX_ITEMS = 1000;\nconst EMAIL = /^[^\\s@]+@[^\\s@.]+(?:\\.[^\\s@.]+)+$/;\nconst DECIMAL = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/;\nconst DATE = '\\\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\\\d|3[01])';\nconst DATE_ONLY = new RegExp(`^${DATE}$`);\nconst DATE_TIME = new RegExp(`^${DATE}T(?:[01]\\\\d|2[0-3]):[0-5]\\\\d(?::[0-5]\\\\d(?:\\\\.\\\\d{1,3})?)?(?:Z|[+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)?$`);\nconst TEXT_TYPES = new Set(['text', 'phone', 'password', 'textarea', 'autocomplete']);\nconst FORMATS = new Map<string, [RegExp, string, number]>([\n ['email', [EMAIL, TYPE_MESSAGES.email, MAX_EMAIL_LENGTH]],\n ['date', [DATE_ONLY, TYPE_MESSAGES.date, MAX_STRING_LENGTH]],\n ['datetime', [DATE_TIME, TYPE_MESSAGES.datetime, MAX_STRING_LENGTH]],\n]);\n\nexport function normalizeValue(field: FormField, value: unknown): unknown {\n if (field.type !== 'number' || typeof value !== 'string' || !DECIMAL.test(value)) return value;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : value;\n}\n\nfunction isOption(field: FormField, value: unknown): boolean {\n return !field.options || field.options.some((option) => option.value === value);\n}\n\nfunction lengthError(field: FormField, value: string): string | null {\n const max = Math.min(MAX_STRING_LENGTH, field.validation?.maxLength ?? MAX_STRING_LENGTH);\n if (value.length <= max) return null;\n return field.validation?.maxLengthMessage ?? getDefaultMessage('maxLength', { max });\n}\n\nfunction multiselectError(field: FormField, value: unknown): string | null {\n if (!Array.isArray(value)) return TYPE_MESSAGES.options;\n if (value.length > (field.options?.length ?? MAX_ITEMS)) return TYPE_MESSAGES.option;\n const valid = value.every((item) => typeof item === 'string' && item.length <= MAX_STRING_LENGTH && isOption(field, item));\n return valid ? null : TYPE_MESSAGES.option;\n}\n\nfunction stringError(field: FormField, value: unknown, message: string): string | null {\n return typeof value === 'string' ? lengthError(field, value) : message;\n}\n\nfunction formatError(field: FormField, value: unknown, [format, message, max]: [RegExp, string, number]): string | null {\n if (typeof value !== 'string') return message;\n return lengthError(field, value) ?? (value.length <= max && format.test(value) ? null : message);\n}\n\nfunction primitiveError(field: FormField, value: unknown): string | null {\n if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) return null;\n return stringError(field, value, TYPE_MESSAGES.value);\n}\n\nfunction isBlank(field: FormField, value: unknown): boolean {\n return value == null || value === '' || (field.type === 'multiselect' && Array.isArray(value) && !value.length);\n}\n\nexport function typeError(field: FormField, value: unknown): string | null {\n if (isBlank(field, value)) return null;\n if (BOOLEAN_TYPES.has(field.type)) return typeof value === 'boolean' ? null : TYPE_MESSAGES.boolean;\n if (field.type === 'number') return typeof value === 'number' && Number.isFinite(value) ? null : TYPE_MESSAGES.number;\n if (field.type === 'multiselect') return multiselectError(field, value);\n if (field.type === 'file') return stringError(field, value, TYPE_MESSAGES.file);\n const format = FORMATS.get(field.type);\n if (format) return formatError(field, value, format);\n if (field.type === 'select' || field.type === 'radio') return stringError(field, value, TYPE_MESSAGES.option) ?? (isOption(field, value) ? null : TYPE_MESSAGES.option);\n return TEXT_TYPES.has(field.type) ? stringError(field, value, TYPE_MESSAGES.string) : primitiveError(field, value);\n}\n\nexport function clientTypeError(field: FormField, value: unknown): string | null {\n if (!CLIENT_TYPES.has(field.type)) return null;\n return typeError(field.optionsFrom ? { ...field, options: undefined } : field, value);\n}\n","import type { FieldValidation, FormField } from '../types';\nimport { isBlank } from '../visibility';\nimport { getDefaultMessage } from './default-messages';\nimport { BOOLEAN_TYPES, clientTypeError } from './type-checks';\n\nexport type ValidatorFn = (\n value: unknown,\n allValues: Record<string, unknown>,\n) => string | null;\n\n\nfunction isEmpty(value: unknown, field: FormField): boolean {\n return isBlank(value) || (value === false && BOOLEAN_TYPES.has(field.type));\n}\n\nfunction boundError(\n size: number,\n rule: 'Length' | '',\n rules: FieldValidation,\n unit?: string,\n): string | undefined {\n const min = rules[`min${rule}`];\n const max = rules[`max${rule}`];\n if (min !== undefined && size < min) return rules[`min${rule}Message`] ?? getDefaultMessage(`min${rule}`, { min, unit });\n if (max !== undefined && size > max) return rules[`max${rule}Message`] ?? getDefaultMessage(`max${rule}`, { max, unit });\n return undefined;\n}\n\nfunction patternError(value: unknown, rules: FieldValidation): string | undefined {\n if (rules.pattern === undefined) return undefined;\n try {\n return new RegExp(rules.pattern).test(String(value)) ? undefined : rules.patternMessage ?? getDefaultMessage('pattern');\n } catch {\n return undefined;\n }\n}\n\nexport function validateFieldValue(\n field: FormField,\n value: unknown,\n allValues: Record<string, unknown>,\n validators?: Record<string, ValidatorFn>,\n): string | null {\n const rules = field.validation ?? {};\n const matchMessage = rules.matchFieldMessage ?? getDefaultMessage('matchField');\n if (isEmpty(value, field)) {\n if (rules.required) return typeof rules.required === 'string' ? rules.required : getDefaultMessage('required');\n return rules.matchField !== undefined && !isBlank(allValues[rules.matchField]) ? matchMessage : null;\n }\n const typeIssue = clientTypeError(field, value);\n if (typeIssue) return typeIssue;\n const sizeError = typeof value === 'string' || Array.isArray(value)\n ? boundError(value.length, 'Length', rules, Array.isArray(value) ? 'items' : undefined)\n : typeof value === 'number' ? boundError(value, '', rules) : undefined;\n const matchError = rules.matchField !== undefined && value !== allValues[rules.matchField] ? matchMessage : undefined;\n return (sizeError\n ?? patternError(value, rules)\n ?? matchError\n ?? (rules.validator ? validators?.[rules.validator]?.(value, allValues) : undefined)) || null;\n}\n","import type { FormField, FormStep } from '../types';\nimport { isVisible } from '../visibility';\nimport { type ValidatorFn, validateFieldValue } from './validate-field';\n\nexport function validateStep(\n step: FormStep,\n values: Record<string, unknown>,\n validators?: Record<string, ValidatorFn>,\n): Record<string, string> {\n return validateFields(step.fields, values, validators);\n}\n\nexport function validateFields(\n fields: FormField[],\n values: Record<string, unknown>,\n validators?: Record<string, ValidatorFn>,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n\n for (const field of fields) {\n if (!isVisible(field, values)) continue;\n\n const error = validateFieldValue(field, values[field.key], values, validators);\n if (error) {\n errors[field.key] = error;\n }\n }\n\n return errors;\n}\n","import type { FormDefinition, FormField } from '../types';\n\nexport function conditionFields(source: Pick<FormField, 'show' | 'showAny'>): string[] {\n return [...(source.show ?? []), ...(source.showAny ?? [])].map((condition) => condition.field);\n}\n\nexport function getAllFields(definition: FormDefinition): FormField[] {\n return definition.steps?.length ? definition.steps.flatMap((step) => step.fields) : definition.fields ?? [];\n}\n\nexport function createValues(\n fields: FormField[],\n initialValues?: Record<string, unknown>,\n): Record<string, unknown> {\n const values: Record<string, unknown> = {};\n for (const field of fields) {\n if (field.defaultValue !== undefined) values[field.key] = field.defaultValue;\n }\n return Object.assign(values, initialValues);\n}\n\nexport function getChangedKeys(\n previous: Record<string, unknown>,\n next: Record<string, unknown>,\n): Set<string> {\n const keys = new Set([...Object.keys(previous), ...Object.keys(next)]);\n return new Set([...keys].filter((key) => !Object.is(previous[key], next[key])));\n}\n","import type { EngineInternals } from './runtime-internals';\n\nfunction activePath(engine: EngineInternals): string {\n return engine.visibleSteps.map((step) => step.id).join('\\n');\n}\n\nexport function watchCheckedInputs(engine: EngineInternals, checked: Record<string, unknown>): () => boolean {\n const path = activePath(engine);\n return () => activePath(engine) !== path || Object.keys(checked).some(\n (key) => checked[key] !== undefined && !Object.is(engine.values[key], checked[key]),\n );\n}\n","import { validateFieldValue, validateFields, validateStep } from '../validation';\nimport { createValues, getChangedKeys } from './engine-utils';\nimport type { EngineInternals } from './runtime-internals';\n\nexport function applyValidationErrors(engine: EngineInternals, errors: Record<string, string>, navigate = false): void {\n const previousErrors = engine.errors;\n engine.state.errors = {};\n engine.state.topLevelErrors = [];\n for (const [key, message] of Object.entries(errors)) {\n if (engine.visibility.isFieldVisible(key, engine.values)) engine.errors[key] = message;\n else engine.topLevelErrors.push(message);\n }\n const structureChanged = navigate && moveToFirstError(engine, errors);\n engine.notify({ fieldKeys: getChangedKeys(previousErrors, engine.errors), structureChanged });\n}\n\nfunction moveToFirstError(engine: EngineInternals, errors: Record<string, string>): boolean {\n const firstErrorKey = Object.keys(errors).find((key) => engine.errors[key] !== undefined);\n const targetIndex = firstErrorKey && engine.isMultiStep\n ? engine.visibility.findStepIndex(firstErrorKey, engine.values, engine.currentStepIndex)\n : null;\n if (targetIndex === null || targetIndex === engine.currentStepIndex) return false;\n engine.state.currentStepIndex = targetIndex;\n return true;\n}\n\nexport function clearResolvedMatchErrors(engine: EngineInternals, key: string): string[] {\n const cleared: string[] = [];\n for (const field of engine.visibility.allFields) {\n if (field.validation?.matchField !== key || engine.errors[field.key] === undefined) continue;\n if (validateFieldValue(field, engine.values[field.key], getValidationValues(engine), engine.validators)) continue;\n delete engine.errors[field.key];\n cleared.push(field.key);\n }\n return cleared;\n}\n\nexport function pruneOffPathErrors(engine: EngineInternals): string[] {\n const pathFields = new Set(engine.visibleSteps.flatMap((step) => step.fields.map((field) => field.key)));\n const pruned = Object.keys(engine.errors).filter((key) => !pathFields.has(key));\n for (const key of pruned) delete engine.errors[key];\n return pruned;\n}\n\nexport function getValidationValues(engine: EngineInternals): Record<string, unknown> {\n return getSubmitValues(engine);\n}\n\nfunction withoutSkipped(engine: EngineInternals, values: Record<string, unknown>): Record<string, unknown> {\n for (const key of [...engine.skipped.values()].flat()) delete values[key];\n return values;\n}\n\nexport function validateForm(engine: EngineInternals, navigate = false): Record<string, string> {\n const previousErrors = engine.errors;\n const errors: Record<string, string> = {};\n if (engine.isMultiStep) {\n for (const step of engine.visibleSteps) {\n if (engine.skipped.has(step.id)) continue;\n Object.assign(errors, validateStep(step, getValidationValues(engine), engine.validators));\n }\n } else {\n Object.assign(\n errors,\n validateFields(engine.definition.fields ?? [], getValidationValues(engine), engine.validators),\n );\n }\n engine.state.errors = errors;\n const structureChanged = navigate && moveToFirstError(engine, errors);\n engine.notify({ fieldKeys: getChangedKeys(previousErrors, errors), structureChanged });\n return errors;\n}\n\nexport function validateOne(engine: EngineInternals, key: string): string | null {\n const field = engine.visibility.activeField(key, engine.values);\n if (!field) return null;\n const previousError = engine.errors[key];\n const error = validateFieldValue(field, engine.values[key], getValidationValues(engine), engine.validators);\n if (error) engine.errors[key] = error;\n else delete engine.errors[key];\n const fieldKeys = Object.is(previousError, engine.errors[key]) ? [] : [key];\n engine.notify({ fieldKeys });\n return error;\n}\n\nexport function getSubmitValues(engine: EngineInternals): Record<string, unknown> {\n return withoutSkipped(engine, { ...engine.visibility.conditionValues(engine.values) });\n}\n\nexport function resetEngine(engine: EngineInternals, values?: Record<string, unknown>): void {\n const previousValues = engine.values;\n const previousErrors = engine.errors;\n const loadingFields = Object.keys(engine.fieldLoading);\n engine.validationEpoch++;\n engine.operationEpoch++;\n engine.state.submitting = false;\n engine.state.values = createValues(engine.visibility.allFields, values);\n engine.state.errors = {};\n engine.state.topLevelErrors = [];\n engine.state.fieldLoading = {};\n engine.state.stepValidating = false;\n engine.state.currentStepIndex = 0;\n engine.skipped.clear();\n engine.visibility.reconcileHidden(engine.values, engine.errors);\n const changedValues = getChangedKeys(previousValues, engine.values);\n const changedFields = new Set([\n ...changedValues,\n ...getChangedKeys(previousErrors, engine.errors),\n ...loadingFields,\n ]);\n engine.notify({\n fieldKeys: changedFields,\n structureChanged: true,\n valuesChanged: changedValues.size > 0,\n });\n}\n","import type { FormDefinition, FormField, FormStep } from '../types';\nimport { isVisible } from '../visibility';\n\nexport function activeSteps(definition: FormDefinition, values: Record<string, unknown>): FormStep[] {\n const steps = definition.steps ?? [];\n const indexes = new Map(steps.map((step, index) => [step.id, index]));\n const result: FormStep[] = [];\n const available: Record<string, unknown> = {};\n for (let index = 0; index < steps.length;) {\n const step = steps[index];\n if (!isVisible(step, available)) { index++; continue; }\n result.push(step);\n Object.assign(available, stepValues(step, values, available));\n const route = step.routes?.find((route) => (\n isVisible(route, available) && (route.to === null || ((indexes.get(route.to) ?? -1) > index\n && isVisible(steps[indexes.get(route.to)!], available)))\n ));\n if (route?.to === null) break;\n index = route ? indexes.get(route.to)! : index + 1;\n }\n return result;\n}\n\nexport function reconcileStepIndex(previous: FormStep[], next: FormStep[], index: number): number {\n const previousStep = previous[index] ?? previous[previous.length - 1];\n const preserved = next.findIndex((step) => step.id === previousStep?.id);\n if (preserved !== -1) return preserved;\n const nextIds = new Map(next.map((step, index) => [step.id, index]));\n for (let before = Math.min(index - 1, previous.length - 1); before >= 0; before--) {\n const predecessor = nextIds.get(previous[before].id);\n if (predecessor !== undefined) return predecessor;\n }\n return 0;\n}\n\nfunction stepValues(step: { fields: FormField[] }, values: Record<string, unknown>, previous: Record<string, unknown>) {\n const candidates = { ...previous };\n for (const field of step.fields) candidates[field.key] = values[field.key];\n const result: Record<string, unknown> = {};\n for (const field of step.fields) {\n if (isVisible(field, candidates) && values[field.key] !== undefined) result[field.key] = values[field.key];\n }\n return result;\n}\n\nexport class ActivePath {\n private source: Record<string, unknown> | null = null;\n private activeStepList: FormStep[] = [];\n private activeValueMap: Record<string, unknown> = {};\n\n constructor(private definition: FormDefinition) {}\n\n invalidate(): void { this.source = null; }\n\n steps(values: Record<string, unknown>): FormStep[] {\n this.refresh(values);\n return this.activeStepList;\n }\n\n values(values: Record<string, unknown>): Record<string, unknown> {\n this.refresh(values);\n return this.activeValueMap;\n }\n\n private refresh(values: Record<string, unknown>): void {\n if (this.source === values) return;\n this.source = values;\n this.activeStepList = activeSteps(this.definition, values);\n const result: Record<string, unknown> = {};\n const groups = this.definition.steps?.length ? this.activeStepList : [{ fields: this.definition.fields ?? [] }];\n for (const step of groups) Object.assign(result, stepValues(step, values, result));\n this.activeValueMap = result;\n }\n}\n","import type { FormStep } from '../types';\nimport { createValues } from './engine-utils';\nimport type { EngineInternals } from './runtime-internals';\nimport { activeSteps } from './step-routes';\nimport { pruneOffPathErrors } from './validation-state';\n\nfunction resetValues(engine: EngineInternals): Record<string, unknown> {\n const fields = engine.currentStep?.fields ?? [];\n const values = { ...engine.values };\n for (const { key } of fields) delete values[key];\n return Object.assign(values, createValues(fields));\n}\n\nexport function skipTarget(engine: EngineInternals): FormStep | undefined {\n return activeSteps(engine.definition, resetValues(engine))[engine.currentStepIndex + 1];\n}\n\nexport function skipCurrentStep(engine: EngineInternals): string[] {\n const step = engine.currentStep!;\n const fieldKeys = step.fields.map(({ key }) => key);\n engine.state.values = resetValues(engine);\n for (const key of fieldKeys) delete engine.errors[key];\n engine.skipped.set(step.id, fieldKeys);\n engine.visibility.reconcileHidden(engine.values, engine.errors);\n engine.visibility.markChanged(true, true);\n const pruned = pruneOffPathErrors(engine);\n engine.notify({ fieldKeys: [...fieldKeys, ...pruned], structureChanged: true, valuesChanged: true });\n return fieldKeys;\n}\n\nexport function includeCurrentStep(engine: EngineInternals): void {\n const step = engine.currentStep;\n if (step) engine.skipped.delete(step.id);\n}\n\nexport function skipStepAt(engine: EngineInternals, index: number): string[] {\n engine.state.currentStepIndex = index;\n engine.notify({ structureChanged: true });\n return skipCurrentStep(engine);\n}\n","import { afterCommit } from './lifecycle-error';\nimport { watchCheckedInputs } from './pending-inputs';\nimport type { SubmitFn } from './engine-options';\nimport type { EngineInternals } from './runtime-internals';\nimport { getSubmitValues, validateForm } from './validation-state';\nimport { includeCurrentStep } from './step-skip';\n\nexport async function submitForm(engine: EngineInternals, submit: SubmitFn, keepSkipped = false): Promise<boolean> {\n if (engine.submitting || engine.stepValidating) return false;\n if (!keepSkipped) includeCurrentStep(engine);\n const lifecycle = { ...engine.lifecycle };\n let dispatched = false;\n const epoch = engine.validationEpoch;\n const operation = ++engine.operationEpoch;\n let values = getSubmitValues(engine);\n const inputsChanged = watchCheckedInputs(engine, values);\n const stale = () => epoch !== engine.validationEpoch || operation !== engine.operationEpoch || inputsChanged();\n engine.state.submitting = true;\n engine.notify();\n try {\n if (stale()) return false;\n if (Object.keys(validateForm(engine, true)).length > 0 || stale()) return false;\n if (lifecycle.onBeforeSubmit) {\n const allowed = await lifecycle.onBeforeSubmit(values);\n if (stale() || allowed === false) return false;\n }\n if (stale()) return false;\n if (lifecycle.onBeforeSubmit) {\n if (Object.keys(validateForm(engine, true)).length > 0 || stale()) return false;\n values = getSubmitValues(engine);\n }\n dispatched = true;\n const skippedSteps = [...engine.skipped.keys()];\n await submit(values, [...skippedSteps]);\n if (operation !== engine.operationEpoch) return true;\n await afterCommit('afterSubmit', () => lifecycle.onAfterSubmit?.(values, skippedSteps));\n return true;\n } catch (error) {\n if (!dispatched && stale()) return false;\n throw error;\n } finally {\n if (operation === engine.operationEpoch) {\n engine.state.submitting = false;\n engine.notify();\n }\n }\n}\n","import { getChangedKeys } from './engine-utils';\nimport { afterCommit } from './lifecycle-error';\nimport { watchCheckedInputs } from './pending-inputs';\nimport { validateStep } from '../validation';\nimport { applyValidationErrors, getValidationValues } from './validation-state';\nimport { includeCurrentStep, skipCurrentStep, skipTarget } from './step-skip';\nimport { submitForm } from './submission';\nimport type { StepChangeContext, SubmitFn } from './engine-options';\nimport type { EngineInternals } from './runtime-internals';\n\nfunction hasStepErrors(engine: EngineInternals): boolean {\n const step = engine.currentStep;\n if (!step) return true;\n const errors = validateStep(step, getValidationValues(engine), engine.validators);\n if (Object.keys(errors).length === 0) return false;\n const previousErrors = { ...engine.errors };\n Object.assign(engine.errors, errors);\n engine.notify({ fieldKeys: getChangedKeys(previousErrors, engine.errors) });\n return true;\n}\n\nfunction moveTo(engine: EngineInternals, index: number): void {\n engine.validationEpoch++;\n engine.state.currentStepIndex = index;\n engine.notify({ structureChanged: true });\n}\n\nexport async function skipStep(engine: EngineInternals, submit?: SubmitFn): Promise<boolean> {\n if (!engine.isMultiStep || engine.stepValidating || engine.submitting || !engine.currentStep?.skip) return false;\n if (skipTarget(engine)) return changeStep(engine, 'next', 'skip');\n const step = engine.currentStep;\n if (!submit || !step) return false;\n const values = engine.values;\n const errors = { ...engine.errors };\n let committed = false;\n const fieldKeys = skipCurrentStep(engine);\n const skippedValues = engine.values;\n const edited = watchCheckedInputs(engine, { ...skippedValues });\n try {\n return await submitForm(engine, async (submitted, skipped) => {\n await submit(submitted, skipped);\n committed = true;\n }, true);\n } finally {\n if (!committed && engine.values === skippedValues && !edited()) {\n engine.state.values = values;\n engine.state.errors = { ...errors, ...engine.errors };\n engine.skipped.delete(step.id);\n engine.notify({ fieldKeys, structureChanged: true, valuesChanged: true });\n }\n }\n}\n\nexport async function changeStep(engine: EngineInternals, direction: 'next' | 'back', reason: StepChangeContext['reason'] = direction): Promise<boolean> {\n const skipping = reason === 'skip';\n if (!engine.isMultiStep || engine.stepValidating || engine.submitting) return false;\n if (!skipping && (direction === 'next' ? engine.isLastStep : engine.isFirstStep)) return false;\n const step = engine.currentStep!;\n const validating = direction === 'next' && !skipping;\n if (validating) includeCurrentStep(engine);\n if (validating && hasStepErrors(engine)) return false;\n const lifecycle = { ...engine.lifecycle };\n const validate = engine.onStepValidate;\n let committed = false;\n const fromIndex = engine.currentStepIndex;\n const toIndex = fromIndex + (direction === 'next' ? 1 : -1);\n const target = skipping ? skipTarget(engine) : engine.visibleSteps[toIndex];\n if (!target) return false;\n const context: StepChangeContext = { fromStepId: step.id, toStepId: target.id, reason, values: { ...getValidationValues(engine) } };\n const epoch = engine.validationEpoch;\n const operation = ++engine.operationEpoch;\n const inputsChanged = watchCheckedInputs(engine, context.values);\n const stale = () => epoch !== engine.validationEpoch || operation !== engine.operationEpoch\n || engine.currentStep?.id !== step.id || inputsChanged();\n engine.state.stepValidating = true;\n engine.notify();\n try {\n if (stale()) return false;\n if (validating && validate) {\n const result = await validate!(step.id, context.values);\n if (stale()) return false;\n if (result && Object.keys(result).length > 0) {\n applyValidationErrors(engine, result);\n return false;\n }\n }\n if (lifecycle.onBeforeStepChange) {\n const allowed = await lifecycle.onBeforeStepChange(context);\n if (stale() || allowed === false) return false;\n }\n if (stale()) return false;\n if (validating && hasStepErrors(engine)) return false;\n committed = true;\n if (skipping) skipCurrentStep(engine);\n moveTo(engine, toIndex);\n await afterCommit('afterStepChange', () => lifecycle.onAfterStepChange?.(context));\n return true;\n } catch (error) {\n if (!committed && stale()) return false;\n throw error;\n } finally {\n if (operation === engine.operationEpoch) {\n engine.state.stepValidating = false;\n engine.notify();\n }\n }\n}\n\nexport function goToStepWithField(engine: EngineInternals, fieldKey: string): void {\n if (!engine.isMultiStep) return;\n const targetIndex = engine.visibility.findStepIndex(\n fieldKey,\n engine.values,\n engine.currentStepIndex,\n );\n if (targetIndex === engine.currentStepIndex) engine.notify();\n else if (targetIndex !== null) moveTo(engine, targetIndex);\n}\n"]}
@@ -0,0 +1,3 @@
1
+ var M="This form was updated. Please review your answers and submit again.",V="Please answer again.",c={message:"Something went wrong. Try again.",action:"retry"},T={message:"Could not send. Try again.",action:"retry"},l={message:"Could not send. Reload the page and try again.",action:"reload"},y={network:{message:"Could not reach the form server. Check your connection and try again.",action:"retry"},timeout:{message:"The form server did not respond. Try again.",action:"retry"},invalid:{message:"Some answers were not accepted.",action:null},rate_limited:{message:"Too many attempts. Wait a minute and try again.",action:"retry"},limit_reached:{message:"This form is not accepting responses right now.",action:null},not_found:{message:"This form no longer exists.",action:null},paused:{message:"This form is paused.",action:null},expired:{message:"This form has expired.",action:null},body_too_large:{message:"Your answers are too long. Shorten them and try again.",action:null},idempotency_key_reused:{message:"Your answers changed while sending. Try again.",action:"retry"},form_updated:{message:"This form was updated. Reload the page.",action:"reload"},client_outdated:{message:"This form needs a newer version of this page.",action:null},malformed_body:l,unsupported_media_type:l,invalid_idempotency_key:l,invalid_response:c,unavailable:c,internal:c},E={0:"network",400:"malformed_body",402:"limit_reached",404:"not_found",409:"paused",410:"expired",413:"body_too_large",422:"invalid",426:"client_outdated",429:"rate_limited"};function w(e,n=""){let t=y[n]??y[E[e]??""];return t||(e>=500?c:T)}var u=class extends Error{constructor(n,t,o,r,i){let s=w(n,t);super(s.message),this.name="CloudError",this.status=n,this.code=t,this.errors=o,this.version=r,this.action=s.action,this.cause=i;}get retryable(){return this.action==="retry"}};function h(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var x=new Map([["Form paused","paused"],["Form not found","not_found"],["Form expired","expired"],["internal error","internal"]]);function k(e,n="network"){return new u(0,n,void 0,void 0,e)}async function m(e){try{return await e.json()}catch(n){throw new u(e.status,"invalid_response",void 0,void 0,n)}}async function f(e){let n=await e.json().catch(()=>null);if(!h(n))return new u(e.status,"unknown");let t=h(n.errors)?n.errors:void 0,o=typeof n.version=="number"&&Number.isInteger(n.version)?n.version:void 0,r=typeof n.error=="string"?x.get(n.error)??n.error:"unknown";return new u(e.status,r,t,o)}var A=["Formhaus-Form-Version","Formhaus-Version"];function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function b(e){let n=Number(e);return e!==null&&e!==""&&Number.isInteger(n)&&n>0?n:void 0}function C(e){for(let n of A){let t=b(e.headers?.get(n));if(t!==void 0)return t}}function d(e){return typeof e=="string"&&e!==""?e:void 0}function F(e){if(!g(e))return {};let n=d(e.redirectUrl);return {...d(e.successMessage)&&{successMessage:d(e.successMessage)},...n&&/^https?:\/\//i.test(n)&&{redirectUrl:n},...typeof e.allowAnother=="boolean"&&{allowAnother:e.allowAnother}}}function S(e,n){if(!g(e))throw new u(n.status,"invalid_response");if(!("definition"in e))return {definition:e,version:C(n),settings:{}};if(!g(e.definition))throw new u(n.status,"invalid_response");return {definition:e.definition,version:b(e.version)??C(n),settings:F(e.settings),...d(e.renderToken)&&{renderToken:d(e.renderToken)}}}function _(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");return `${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}var D="https://api.formhaus.dev",p="core=0.11.0";function v({id:e,apiBase:n=D}){return `${n.replace(/\/+$/,"")}/f/${encodeURIComponent(e)}`}var I=15e3,O=3e4;async function R(e,n,t={},o){let r=new AbortController,i=()=>r.abort(),s=setTimeout(i,n);o?.aborted&&i(),o?.addEventListener("abort",i);try{return await fetch(e,{...t,signal:r.signal})}catch(a){throw o?.aborted?a:k(a,r.signal.aborted?"timeout":"network")}finally{clearTimeout(s),o?.removeEventListener("abort",i);}}async function U(e,n,t){let o=t===void 0?p:`${p}&v=${t}`,r=await R(`${v(e)}/form?${o}`,I,{},n);if(!r.ok)throw await f(r);return S(await m(r),r)}async function H(e,n){return (await U(e,n)).definition}function z(e){let n=null;return async(t,o=[])=>{let r=JSON.stringify({...e.extraBody?.(),values:t,skippedSteps:o,version:e.version,_fh_rt:e.renderToken});n?.body!==r&&(n={body:r,key:_()});let i=await R(`${v(e)}?${p}`,O,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":n.key},body:r});if(!i.ok)throw await f(i);let s=await m(i);return n=null,s}}var $=new Set(["password","file"]),P=10080*60*1e3;function X(e,n){let t=[...e.fields??[],...(e.steps??[]).flatMap(r=>r.fields)],o={};for(let r of t)!$.has(r.type)&&n[r.key]!==void 0&&(o[r.key]=n[r.key]);return o}var N=()=>globalThis.sessionStorage;function Z(e=P,n=N){let t=r=>`formhaus:draft:${r}`,o=(r,i)=>{try{let s=n();return s?r(s):i}catch{return i}};return {load:(r,i)=>o(s=>{let a=JSON.parse(s.getItem(t(r))??"null");return a&&a.version===i&&Date.now()-a.savedAt<e?a.values:null},null),save:(r,i,s)=>o(a=>a.setItem(t(r),JSON.stringify({version:i,savedAt:Date.now(),values:s})),void 0),clear:r=>o(i=>i.removeItem(t(r)),void 0)}}
2
+ export{M as a,V as b,w as c,u as d,k as e,F as f,U as g,H as h,z as i,X as j,Z as k};//# sourceMappingURL=chunk-EPXEKDCK.js.map
3
+ //# sourceMappingURL=chunk-EPXEKDCK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cloud/failures.ts","../src/cloud/error.ts","../src/cloud/envelope.ts","../src/cloud/uuid.ts","../src/cloud/client.ts","../src/cloud/draft.ts"],"names":["FORM_UPDATED_MESSAGE","ANSWER_AGAIN","SERVER","GENERIC","BROKEN","BY_CODE","CODE_BY_STATUS","failureFor","status","code","known","CloudError","errors","version","cause","failure","isRecord","value","LEGACY_CODES","networkError","readJson","response","error","toCloudError","body","VERSION_HEADERS","toVersion","headerVersion","name","text","parseSettings","redirect","parseForm","randomId","bytes","hex","byte","DEFAULT_API_BASE","CORE","endpoint","id","apiBase","LOAD_TIMEOUT","SUBMIT_TIMEOUT","send","url","timeout","init","signal","controller","abort","timer","fetchForm","options","after","query","fetchDefinition","createSubmitter","pending","values","skippedSteps","submission","SENSITIVE","WEEK","draftValues","definition","fields","step","kept","field","sessionStorageOf","sessionDraftStore","maxAge","storageOf","key","attempt","action","fallback","storage","draft"],"mappings":"AAOO,IAAMA,CAAAA,CAAuB,qEAAA,CACvBC,CAAAA,CAAe,sBAAA,CAEtBC,CAAAA,CAAuB,CAAE,OAAA,CAAS,kCAAA,CAAoC,MAAA,CAAQ,OAAQ,CAAA,CACtFC,CAAAA,CAAwB,CAAE,OAAA,CAAS,4BAAA,CAA8B,MAAA,CAAQ,OAAQ,CAAA,CACjFC,CAAAA,CAAuB,CAAE,OAAA,CAAS,iDAAkD,MAAA,CAAQ,QAAS,CAAA,CAErGC,CAAAA,CAAwC,CAC5C,OAAA,CAAS,CAAE,OAAA,CAAS,wEAAyE,MAAA,CA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AAA,CAAQnB,CAAAA,EAAOmC,EAASG,CAAAA,EAAYA,CAAAA,CAAQ,UAAA,CAAWJ,CAAAA,CAAIlC,CAAE,CAAC,CAAA,CAAG,MAAS,CAC5E,CACF","file":"chunk-EPXEKDCK.js","sourcesContent":["export type CloudAction = 'retry' | 'reload' | null;\n\nexport interface CloudFailure {\n message: string;\n action: CloudAction;\n}\n\nexport const FORM_UPDATED_MESSAGE = 'This form was updated. Please review your answers and submit again.';\nexport const ANSWER_AGAIN = 'Please answer again.';\n\nconst SERVER: CloudFailure = { message: 'Something went wrong. Try again.', action: 'retry' };\nconst GENERIC: CloudFailure = { message: 'Could not send. Try again.', action: 'retry' };\nconst BROKEN: CloudFailure = { message: 'Could not send. Reload the page and try again.', action: 'reload' };\n\nconst BY_CODE: Record<string, CloudFailure> = {\n network: { message: 'Could not reach the form server. Check your connection and try again.', action: 'retry' },\n timeout: { message: 'The form server did not respond. Try again.', action: 'retry' },\n invalid: { message: 'Some answers were not accepted.', action: null },\n rate_limited: { message: 'Too many attempts. Wait a minute and try again.', action: 'retry' },\n limit_reached: { message: 'This form is not accepting responses right now.', action: null },\n not_found: { message: 'This form no longer exists.', action: null },\n paused: { message: 'This form is paused.', action: null },\n expired: { message: 'This form has expired.', action: null },\n body_too_large: { message: 'Your answers are too long. Shorten them and try again.', action: null },\n idempotency_key_reused: { message: 'Your answers changed while sending. Try again.', action: 'retry' },\n form_updated: { message: 'This form was updated. Reload the page.', action: 'reload' },\n client_outdated: { message: 'This form needs a newer version of this page.', action: null },\n malformed_body: BROKEN,\n unsupported_media_type: BROKEN,\n invalid_idempotency_key: BROKEN,\n invalid_response: SERVER,\n unavailable: SERVER,\n internal: SERVER,\n};\n\nconst CODE_BY_STATUS: Record<number, string> = {\n 0: 'network',\n 400: 'malformed_body',\n 402: 'limit_reached',\n 404: 'not_found',\n 409: 'paused',\n 410: 'expired',\n 413: 'body_too_large',\n 422: 'invalid',\n 426: 'client_outdated',\n 429: 'rate_limited',\n};\n\nexport function failureFor(status: number, code = ''): CloudFailure {\n const known = BY_CODE[code] ?? BY_CODE[CODE_BY_STATUS[status] ?? ''];\n if (known) return known;\n return status >= 500 ? SERVER : GENERIC;\n}\n","import { failureFor, type CloudAction } from './failures';\n\nexport class CloudError extends Error {\n readonly status: number;\n readonly code: string;\n readonly errors?: Record<string, string>;\n readonly version?: number;\n readonly action: CloudAction;\n readonly cause?: unknown;\n\n constructor(status: number, code: string, errors?: Record<string, string>, version?: number, cause?: unknown) {\n const failure = failureFor(status, code);\n super(failure.message);\n this.name = 'CloudError';\n this.status = status;\n this.code = code;\n this.errors = errors;\n this.version = version;\n this.action = failure.action;\n this.cause = cause;\n }\n\n get retryable(): boolean {\n return this.action === 'retry';\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nconst LEGACY_CODES = new Map([\n ['Form paused', 'paused'],\n ['Form not found', 'not_found'],\n ['Form expired', 'expired'],\n ['internal error', 'internal'],\n]);\n\nexport function networkError(cause: unknown, code = 'network'): CloudError {\n return new CloudError(0, code, undefined, undefined, cause);\n}\n\nexport async function readJson(response: CloudResponse): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new CloudError(response.status, 'invalid_response', undefined, undefined, error);\n }\n}\n\nexport async function toCloudError(response: CloudResponse): Promise<CloudError> {\n const body: unknown = await response.json().catch(() => null);\n if (!isRecord(body)) return new CloudError(response.status, 'unknown');\n const errors = isRecord(body.errors) ? body.errors as Record<string, string> : undefined;\n const version = typeof body.version === 'number' && Number.isInteger(body.version) ? body.version : undefined;\n const code = typeof body.error === 'string' ? LEGACY_CODES.get(body.error) ?? body.error : 'unknown';\n return new CloudError(response.status, code, errors, version);\n}\n","import type { FormDefinition } from '../types';\nimport { CloudError } from './error';\n\nexport interface CloudSettings {\n successMessage?: string;\n redirectUrl?: string;\n allowAnother?: boolean;\n}\n\nexport interface PublishedForm {\n definition: FormDefinition;\n version?: number;\n settings?: CloudSettings;\n renderToken?: string;\n}\n\nconst VERSION_HEADERS = ['Formhaus-Form-Version', 'Formhaus-Version'];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction toVersion(value: unknown): number | undefined {\n const version = Number(value);\n return value !== null && value !== '' && Number.isInteger(version) && version > 0 ? version : undefined;\n}\n\nfunction headerVersion(response: CloudResponse): number | undefined {\n for (const name of VERSION_HEADERS) {\n const version = toVersion(response.headers?.get(name));\n if (version !== undefined) return version;\n }\n return undefined;\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\nexport function parseSettings(value: unknown): CloudSettings {\n if (!isRecord(value)) return {};\n const redirect = text(value.redirectUrl);\n return {\n ...(text(value.successMessage) && { successMessage: text(value.successMessage) }),\n ...(redirect && /^https?:\\/\\//i.test(redirect) && { redirectUrl: redirect }),\n ...(typeof value.allowAnother === 'boolean' && { allowAnother: value.allowAnother }),\n };\n}\n\nexport function parseForm(body: unknown, response: CloudResponse): PublishedForm {\n if (!isRecord(body)) throw new CloudError(response.status, 'invalid_response');\n if (!('definition' in body)) return { definition: body as unknown as FormDefinition, version: headerVersion(response), settings: {} };\n if (!isRecord(body.definition)) throw new CloudError(response.status, 'invalid_response');\n return {\n definition: body.definition as unknown as FormDefinition,\n version: toVersion(body.version) ?? headerVersion(response),\n settings: parseSettings(body.settings),\n ...(text(body.renderToken) && { renderToken: text(body.renderToken) }),\n };\n}\n","export function randomId(): string {\n if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6] & 15) | 64;\n bytes[8] = (bytes[8] & 63) | 128;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","import type { FormDefinition } from '../types';\nimport { networkError, readJson, toCloudError } from './error';\nimport { parseForm, type PublishedForm } from './envelope';\nimport { randomId } from './uuid';\n\nconst DEFAULT_API_BASE = 'https://api.formhaus.dev';\nconst CORE = `core=${__FORMHAUS_CORE_VERSION__}`;\n\nexport interface CloudSubmission {\n id: string;\n values: Record<string, unknown>;\n}\n\nexport interface CloudClientOptions {\n id: string;\n apiBase?: string;\n}\n\nfunction endpoint({ id, apiBase = DEFAULT_API_BASE }: CloudClientOptions): string {\n return `${apiBase.replace(/\\/+$/, '')}/f/${encodeURIComponent(id)}`;\n}\n\nconst LOAD_TIMEOUT = 15_000;\nconst SUBMIT_TIMEOUT = 30_000;\n\nasync function send(url: string, timeout: number, init: CloudRequestInit = {}, signal?: AbortSignal): Promise<CloudResponse> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n const timer = setTimeout(abort, timeout);\n if (signal?.aborted) abort();\n signal?.addEventListener('abort', abort);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (signal?.aborted) throw error;\n throw networkError(error, controller.signal.aborted ? 'timeout' : 'network');\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n }\n}\n\nexport async function fetchForm(options: CloudClientOptions, signal?: AbortSignal, after?: number): Promise<PublishedForm> {\n const query = after === undefined ? CORE : `${CORE}&v=${after}`;\n const response = await send(`${endpoint(options)}/form?${query}`, LOAD_TIMEOUT, {}, signal);\n if (!response.ok) throw await toCloudError(response);\n return parseForm(await readJson(response), response);\n}\n\nexport async function fetchDefinition(options: CloudClientOptions, signal?: AbortSignal): Promise<FormDefinition> {\n return (await fetchForm(options, signal)).definition;\n}\n\nexport interface CloudSubmitterOptions extends CloudClientOptions {\n version?: number;\n renderToken?: string;\n extraBody?: () => Record<string, unknown>;\n}\n\nexport function createSubmitter(options: CloudSubmitterOptions) {\n let pending: { body: string; key: string } | null = null;\n\n return async (values: Record<string, unknown>, skippedSteps: string[] = []): Promise<CloudSubmission> => {\n const body = JSON.stringify({ ...options.extraBody?.(), values, skippedSteps, version: options.version, _fh_rt: options.renderToken });\n if (pending?.body !== body) pending = { body, key: randomId() };\n const response = await send(`${endpoint(options)}?${CORE}`, SUBMIT_TIMEOUT, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': pending.key },\n body,\n });\n if (!response.ok) throw await toCloudError(response);\n const submission = await readJson(response) as CloudSubmission;\n pending = null;\n return submission;\n };\n}\n","import type { FormDefinition } from '../types';\n\nexport interface DraftStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport interface DraftStore {\n load(id: string, version: number | undefined): Record<string, unknown> | null;\n save(id: string, version: number | undefined, values: Record<string, unknown>): void;\n clear(id: string): void;\n}\n\nconst SENSITIVE = new Set(['password', 'file']);\nconst WEEK = 7 * 24 * 60 * 60 * 1000;\n\nexport function draftValues(definition: FormDefinition, values: Record<string, unknown>): Record<string, unknown> {\n const fields = [...(definition.fields ?? []), ...(definition.steps ?? []).flatMap((step) => step.fields)];\n const kept: Record<string, unknown> = {};\n for (const field of fields) {\n if (!SENSITIVE.has(field.type) && values[field.key] !== undefined) kept[field.key] = values[field.key];\n }\n return kept;\n}\n\nconst sessionStorageOf = () => (globalThis as { sessionStorage?: DraftStorage }).sessionStorage;\n\nexport function sessionDraftStore(maxAge = WEEK, storageOf: () => DraftStorage | undefined = sessionStorageOf): DraftStore {\n const key = (id: string) => `formhaus:draft:${id}`;\n const attempt = <T>(action: (storage: DraftStorage) => T, fallback: T): T => {\n try {\n const storage = storageOf();\n return storage ? action(storage) : fallback;\n } catch {\n return fallback;\n }\n };\n return {\n load: (id, version) => attempt((storage) => {\n const draft = JSON.parse(storage.getItem(key(id)) ?? 'null') as { version?: number; savedAt: number; values: Record<string, unknown> } | null;\n return draft && draft.version === version && Date.now() - draft.savedAt < maxAge ? draft.values : null;\n }, null),\n save: (id, version, values) => attempt((storage) => storage.setItem(key(id), JSON.stringify({ version, savedAt: Date.now(), values })), undefined),\n clear: (id) => attempt((storage) => storage.removeItem(key(id)), undefined),\n };\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import {e,o,u as u$1,p as p$1,n,z,y as y$1,x as x$1,q,r,s,A as A$1,t,a,d,v as v$1,l,h as h$1,c as c$1}from'./chunk-BXI5P7PF.js';var h=class extends Error{constructor(e){super(`Invalid form definition:
2
+ ${e.map(i=>i.message).join(`
3
+ `)}`),this.name="FormDefinitionError",this.issues=e;}};function ie(t){return (e,i,n,r)=>({code:e,severity:t,path:i,message:`${i||"/"}: ${n}.${r?` ${r}.`:""}`,...r&&{hint:`${r}.`}})}var u=ie("error"),c=ie("warning");function I(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function y(t){return t.severity==="error"}function m(t){if(t.length===1)return `Use ${JSON.stringify(t[0])}`;let e=t.slice(0,10).map(i=>JSON.stringify(i)).join(", ");return t.length>10?`Use one of: ${e}, ...`:`Use one of: ${e}`}function ve(t,e){let i=Array.from({length:e.length+1},(n,r)=>r);for(let n=1;n<=t.length;n++){let r=[n];for(let o=1;o<=e.length;o++)r[o]=Math.min(i[o]+1,r[o-1]+1,i[o-1]+(t[n-1]===e[o-1]?0:1));i=r;}return i[e.length]}function V(t,e){let i=t.toLowerCase();return e.find(n=>n!==t&&ve(i,n.toLowerCase())<=(n.length>4?2:1))}function b(t,e){let i=V(t,e);return i!==void 0?`Use ${JSON.stringify(i)}`:e.length?m(e):void 0}var D=a,Se=new Set(["in","notIn"]),Fe=new Set(["neq","notIn"]),we=new Set(["gt","gte","lt","lte"]),ke=new Set(["text","email","phone","password","textarea","date","datetime","select","radio","autocomplete"]),ne=new Set(["checkbox","switch"]);function $e(t){return t.type==="number"?"number":ne.has(t.type)?"boolean":ke.has(t.type)?"string":void 0}function Ie(t,e,i){if(!(t.type!=="multiselect"&&!ne.has(t.type)))return c("condition-value-mismatch",i,`"${t.key}" is a ${t.type} field, so "${e}" never matches it`,"Compare a number, text, radio or select field")}function De(t,e,i,n){if(e==="notEmpty")return;if(we.has(e))return Ie(t,e,n);if(t.type==="multiselect"){let d=Fe.has(e)?"always":"never";return c("condition-value-mismatch",n,`"${t.key}" holds a list of values, so "${e}" ${d} matches it`,"Use notEmpty, or a select or radio field")}let r=Se.has(e)&&Array.isArray(i)?i:[i],o=$e(t),s=o&&r.find(d=>typeof d!==o);if(o&&s!==void 0)return c("condition-value-mismatch",n,`${JSON.stringify(s)} is a ${typeof s}, but "${t.key}" holds a ${o}`,`Use a ${o} value`);let a=o==="string"&&!t.optionsFrom&&t.options?.length?t.options.map(d=>d.value):null,l=a&&r.find(d=>!a.includes(d));if(a&&l!==void 0)return c("condition-value-mismatch",n,`${JSON.stringify(l)} is not an option of "${t.key}"`,m(a))}function xe(t,e){let i=Object.keys(t).filter(s=>s!=="field"),n=i.filter(s=>!D.includes(s)),r=n.map(s=>u("unknown-operator",`${e}/${I(s)}`,`"${s}" is not a condition operator`,b(s,[...D]))),o=i.length-n.length;if(o!==1&&!(o===0&&n.length)){let s=o?`the condition has ${o} operators`:"the condition has no operator";r.push(u("condition-operator-count",e,s,`Use exactly one of: ${D.join(", ")}`));}return r}function Ce(t,{condition:e,path:i,owner:n,step:r,key:o}){let s=t.keys.get(e.field);if(!s){let d=t.keyList.filter(f=>f!==o);return u("unknown-field",`${i}/field`,`"${e.field}" is not a field key`,b(e.field,d))}if(r<0||n==="action")return;let a=n==="step"?"this or a later step":"a later step";if(s.step<r||n!=="step"&&s.step===r)return;let l=n==="step"?"earlier steps":"this or an earlier step";return u("forward-reference",`${i}/field`,`"${e.field}" belongs to ${a}`,`${n==="route"?"Route":n==="step"?"Step":"Field"} conditions can use fields of ${l}`)}function se(t){let e=[];for(let i of t.conditions){let{condition:n,path:r}=i;if(typeof n.field!="string"){e.push(u("missing-property",`${r}/field`,'the condition has no "field"',"Add the key of the field to test"));continue}let o=xe(n,r);e.push(...o);let s=Ce(t,i);s&&e.push(s);let a=t.keys.get(n.field),l=D.find(d=>d in n);if(!s&&!o.length&&a&&l){let d=De(a.field,l,n[l],`${r}/${l}`);d&&e.push(d);}}return e}function A(t,e,i,n,r,o){for(let s of ["show","showAny"])(e[s]??[]).forEach((a,l)=>t.push({condition:a,path:`${i}/${s}/${l}`,owner:n,step:r,key:o}));}function L(t,e,i,n){(e?e.disabled??[]:[]).forEach((r,o)=>t.push({condition:r,path:`${i}/disabled/${o}`,owner:"action",step:n}));}function oe(t,e){let i=t.steps??[],n=i.length?i.flatMap((s,a)=>s.fields.map((l,d)=>({field:l,path:`/steps/${a}/fields/${d}`,step:a}))):(t.fields??[]).map((s,a)=>({field:s,path:`/fields/${a}`,step:-1})),r=new Map;for(let s of n)r.has(s.field.key)||r.set(s.field.key,s);let o=[];for(let s of n)A(o,s.field,s.path,"field",s.step,s.field.key);return i.forEach((s,a)=>{A(o,s,`/steps/${a}`,"step",a),(s.routes??[]).forEach((l,d)=>A(o,l,`/steps/${a}/routes/${d}`,"route",a));for(let l of ["next","back","skip"])L(o,s[l],`/steps/${a}/${l}`,a);}),L(o,t.submit,"/submit",-1),L(o,t.cancel,"/cancel",-1),{definition:t,entries:n,keys:r,keyList:[...r.keys()],conditions:o,validators:e}}var N=["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","file","date","datetime","textarea"],Ee=new Set(["select","radio","multiselect"]),Re=new Set(["number","checkbox","switch"]);function Oe({field:t,path:e}){let i=N.includes(t.type)?void 0:V(t.type,N);return i===void 0?[]:[c("unknown-field-type",`${e}/type`,`"${t.type}" is not a built-in field type`,`Use "${i}", or register a component for "${t.type}"`)]}function Ve({field:t,path:e}){if(!Ee.has(t.type))return [];if(!Array.isArray(t.options))return t.optionsFrom?[]:[c("missing-options",`${e}/options`,`the ${t.type} field "${t.key}" has no options`,'Add "options" or "optionsFrom"')];let i=t.options.map(o=>o.value),n=t.type==="multiselect"&&Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue],r=t.defaultValue===void 0||!i.length||t.optionsFrom?void 0:n.find(o=>!i.includes(o));return r===void 0?[]:[c("default-not-in-options",`${e}/defaultValue`,`${JSON.stringify(r)} is not an option of "${t.key}"`,m(i))]}function re(t,e,i,n){let r=t[i],o=t[n];return r===void 0||o===void 0||r<=o?[]:[u("invalid-range",`${e}/validation/${i}`,`${i} (${r}) is greater than ${n} (${o})`,`Lower ${i} or raise ${n}`)]}function Ae({field:t,path:e},i){if(!N.includes(t.type))return [];let n=t.type==="number",r=n?[]:["min","max"].filter(s=>i[s]!==void 0),o=Re.has(t.type)?["minLength","maxLength"].filter(s=>i[s]!==void 0):[];return [...r.map(s=>c("rule-not-applicable",`${e}/validation/${s}`,`"${s}" applies to number fields only`,`Use ${s}Length to limit text length`)),...o.map(s=>c("rule-not-applicable",`${e}/validation/${s}`,`"${s}" does not apply to ${t.type} fields`,n?"Use min and max for numbers":`Remove ${s}`))]}function Le(t,e){if(t===void 0)return [];try{return new RegExp(t),[]}catch{return [u("invalid-pattern",`${e}/validation/pattern`,`${JSON.stringify(t)} is not a valid regular expression`,"Fix the pattern or escape special characters with a backslash")]}}function Ne(t,e){let i=e.field.validation;if(!i)return [];let{path:n}=e,r=[...re(i,n,"minLength","maxLength"),...re(i,n,"min","max"),...Ae(e,i),...Le(i.pattern,n)];i.matchField!==void 0&&!t.keys.has(i.matchField)&&r.push(u("unknown-field",`${n}/validation/matchField`,`"${i.matchField}" is not a field key`,b(i.matchField,t.keyList)));let o=t.validators;return i.validator!==void 0&&o&&!Object.prototype.hasOwnProperty.call(o,i.validator)&&r.push(c("unknown-validator",`${n}/validation/validator`,`the validator "${i.validator}" is not registered`,'Pass it in the "validators" option')),r}function Me(t,{field:e,path:i}){return (e.optionsDependsOn??[]).flatMap((n,r)=>t.keys.has(n)?[]:[c("unknown-field",`${i}/optionsDependsOn/${r}`,`"${n}" is not a field key`,b(n,t.keyList))])}function ae(t){return t.entries.flatMap(e=>[...Oe(e),...Ve(e),...Ne(t,e),...Me(t,e)])}function Pe({definition:t,entries:e,keys:i}){let n=new Map,r=(s,a)=>{let l=a.filter(d=>i.has(d));if(l.length)for(let d of s)n.set(d,[...n.get(d)??[],...l]);},o=s=>[...s.show??[],...s.showAny??[]].map(a=>a.field);for(let{field:s}of e)r([s.key],o(s));for(let s of t.steps??[])r(s.fields.map(a=>a.key),o(s));return n}function Te(t){let e=new Map,i=[];for(let n of t.keys()){if(e.has(n))continue;e.set(n,true);let r=[[n,0]];for(;r.length>0;){let o=r[r.length-1],s=t.get(o[0])?.[o[1]++];if(s===void 0)e.set(o[0],false),r.pop();else if(e.get(s)){let a=r.map(([l])=>l);i.push([...a.slice(a.indexOf(s)),s]);}else e.has(s)||(e.set(s,true),r.push([s,0]));}}return i}function je(t){return Te(Pe(t)).map(e=>u("condition-cycle",t.keys.get(e[0]).path,`show conditions form a cycle: ${e.join(" -> ")}`,"Remove one of the conditions in the cycle"))}function Ge({definition:t}){let e=t.steps??[],i=[];return e.forEach((n,r)=>{let o=new Set((n.routes??[]).map(s=>s.to).filter(s=>s!==null));for(let s of o){let a=e.findIndex(f=>f.id===s),l=e[a+1],d=e[a]?.routes?.some(f=>!f.show?.length&&!f.showAny?.length);!l||!o.has(l.id)||d||i.push(c("route-fallthrough",`/steps/${a}`,`branch "${s}" from "${n.id}" continues into the sibling branch "${l.id}"`,`Add an unconditional route on "${s}" to the step where the branches meet`));}n.skip&&(n.next===false||!e[1])&&i.push(c("skip-unreachable",`/steps/${r}/skip`,`step "${n.id}" has "skip" but no Continue button or later step`,'Remove "skip", or remove "next": false'));}),i}function le(t){return [...je(t),...Ge(t)]}var F=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Ue={string:[t=>typeof t=="string","a string"],number:[t=>typeof t=="number"&&Number.isFinite(t),"a number"],boolean:[t=>typeof t=="boolean","true or false"],scalar:[t=>["string","number","boolean"].includes(typeof t),"a string, number or boolean"],list:[t=>Array.isArray(t)&&t.every(e=>["string","number"].includes(typeof e)),"an array of strings or numbers"]};function de(t,e,i){return Object.entries(e).flatMap(([n,r])=>{let[o,s]=Ue[r];return t[n]===void 0||o(t[n])?[]:[u("invalid-type",`${i}/${I(n)}`,`"${n}" must be ${s}`)]})}function p(t,e,i,n,r=false){return t==null&&!r?[]:Array.isArray(t)?t.flatMap((o,s)=>F(o)?n(o,`${e}/${s}`):[u("invalid-type",`${e}/${s}`,`must be ${i}`)]):[u("invalid-type",e,"must be an array",r?"Use [] when there is nothing to list":void 0)]}function S(t,e,i){return typeof t[e]=="string"?[]:[u("missing-property",`${i}/${e}`,`"${e}" must be a string`)]}var M=(t,e)=>de(t,{field:"string",eq:"scalar",neq:"scalar",in:"list",notIn:"list",notEmpty:"boolean",gt:"number",gte:"number",lt:"number",lte:"number"},e);function T(t,e){return [...p(t.show,`${e}/show`,"a condition object",M),...p(t.showAny,`${e}/showAny`,"a condition object",M)]}function P(t,e){return F(t)?p(t.disabled,`${e}/disabled`,"a condition object",M):[]}var Ke=(t,e)=>S(t,"value",e),_e={minLength:"number",maxLength:"number",min:"number",max:"number",pattern:"string",matchField:"string",validator:"string"};function He(t,e){return t===void 0?[]:F(t)?de(t,_e,e):[u("invalid-type",e,"must be an object of validation rules")]}function Je(t,e){return t===void 0||Array.isArray(t)&&t.every(n=>typeof n=="string")?[]:[u("invalid-type",e,"must be an array of field keys")]}var ue=(t,e)=>[...S(t,"key",e),...S(t,"type",e),...T(t,e),...p(t.options,`${e}/options`,"an option object",Ke),...He(t.validation,`${e}/validation`),...Je(t.optionsDependsOn,`${e}/optionsDependsOn`)],qe=(t,e)=>[...t.to===null||typeof t.to=="string"?[]:[u("missing-property",`${e}/to`,'"to" must be a step id or null')],...T(t,e)],Be=(t,e)=>[...S(t,"id",e),...p(t.fields,`${e}/fields`,"a field object",ue,true),...T(t,e),...p(t.routes,`${e}/routes`,"a route object",qe),...["next","back","skip"].flatMap(i=>P(t[i],`${e}/${i}`))];function ce(t){return F(t)?[...p(t.fields,"/fields","a field object",ue),...p(t.steps,"/steps","a step object",Be),...P(t.submit,"/submit"),...P(t.cancel,"/cancel")]:[u("invalid-type","","the form definition must be an object")]}function fe(t){return [...S(t,"id",""),...typeof t.title=="string"?[]:[c("missing-property","/title",'"title" must be a string',"Add a title for host UI and editors")],...F(t.submit)?[]:[u("missing-property","/submit","the submit action is missing",'Add "submit": { "label": "Submit" }')]]}var x=t=>!!(t.show?.length||t.showAny?.length);function pe(t,e,i){let n=[];for(let r of t[i].routes??[]){let o=r.to===null?null:e.get(r.to);if(o===null&&!x(r))return n;if(!(o==null||o<=i)&&(n.push(o),!x(r)&&!x(t[o])))return n}return i+1<t.length?[...n,i+1]:n}function he(t){let e=new Map(t.map((i,n)=>[i.id,n]));return t.map((i,n)=>{let r=new Set,o=pe(t,e,n);for(;o.length;){let s=o.pop();r.has(s)||(r.add(s),o.push(...pe(t,e,s)),x(t[s])&&s+1<t.length&&o.push(s+1));}return r})}var Ye=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]);function ze({definition:t}){let e=[],i=t.steps??[],n=new Map;return i.forEach((r,o)=>{let s=n.get(r.id);s===void 0?n.set(r.id,o):e.push(u("duplicate-step-id",`/steps/${o}/id`,`step id "${r.id}" is already used by /steps/${s}`,"Give each step a unique id"));}),i.forEach((r,o)=>(r.routes??[]).forEach((s,a)=>{if(s.to===null)return;let l=n.get(s.to);if(l!==void 0&&l>o)return;let d=i.slice(o+1).map(k=>k.id),f=l===void 0?`"${s.to}" is not a step id`:`"${s.to}" is not a later step`,w=d.length?`${m(d)}, or null to end the form here`:"Use null to end the form here";e.push(u("route-target",`/steps/${o}/routes/${a}/to`,f,w));})),e}function We({definition:t,entries:e}){let i=[],n=he(t.steps??[]),r=(o,s)=>o.step!==s.step&&!n[o.step]?.has(s.step);return e.forEach((o,s)=>{let{field:a,path:l}=o,d=e.slice(0,s).find(f=>f.field.key===a.key&&!r(f,o));Ye.has(a.key)?i.push(u("reserved-key",`${l}/key`,`"${a.key}" is a built-in object property name`,"Rename the field key")):d&&i.push(u("duplicate-key",`${l}/key`,`key "${a.key}" is already used by ${d.path} on the same path`,"Rename one of the fields, or move them to route branches that never meet"));}),i}function me(t){let{definition:e}=t;return [...!!e.fields?.length&&!!e.steps?.length?[u("fields-and-steps","",'the definition has both "fields" and "steps"','Move the top-level fields into a step, or remove "steps"')]:[],...ze(t),...We(t)]}function Qe(t){return [...t.filter(y),...t.filter(e=>!y(e))]}function v(t,e={}){let i=ce(t);if(i.length)return i;let n=oe(t,e.validators);return Qe([...fe(t),...me(n),...se(n),...ae(n),...le(n)])}function Ze(t,e){let i=v(t,e).filter(y);if(i.length)throw new h(i);return t}function Xe(t){return v(t).map(e=>e.message)}var C=class{constructor(){this.version=0;this.listeners=new Set;this.fieldVersions=new Map;this.fieldListeners=new Map;this.structureVersion=0;this.structureListeners=new Set;}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getSnapshot(){return this.version}subscribeField(e,i){let n=this.fieldListeners.get(e)??new Set;return n.add(i),this.fieldListeners.set(e,n),()=>{n.delete(i),n.size===0&&this.fieldListeners.delete(e);}}getFieldSnapshot(e){return this.fieldVersions.get(e)??0}subscribeStructure(e){return this.structureListeners.add(e),()=>this.structureListeners.delete(e)}getStructureSnapshot(){return this.structureVersion}notify({fieldKeys:e=[],structureChanged:i=false}={}){for(let n of new Set(e))this.notifyField(n);i&&this.notifyStructure(),this.version++;for(let n of this.listeners)n();}notifyField(e){this.fieldVersions.set(e,(this.fieldVersions.get(e)??0)+1);for(let i of this.fieldListeners.get(e)??[])i();}notifyStructure(){this.structureVersion++;for(let e of this.structureListeners)e();}};function et(){try{return process.env.NODE_ENV==="production"}catch{return false}}function ge(t){et()||console.warn(`[formhaus] ${t.message}`);}function j(t,e){for(let i of c$1(t)){let n=e.get(i)??new Set;n.add(t),e.set(i,n);}}var E=class{constructor(e){this.definition=e;this.fieldsByKey=new Map;this.routeFields=new Set;this.fieldDependents=new Map;this.stepDependents=new Map;this.stepOfField=new Map;this.visibilityDirty=true;this.canGoNextDirty=true;this.cache={visibleSteps:[],currentStep:null,visibleFields:[],canGoNext:false};this.allFields=d(e);for(let i of this.allFields)this.fieldsByKey.set(i.key,[...this.fieldsByKey.get(i.key)??[],i]);this.path=new v$1(e);for(let i of e.steps??[])for(let n of i.fields)this.stepOfField.set(n,i);this.buildIndexes();}markChanged(e,i){(e||i)&&this.path.invalidate(),e?(this.visibilityDirty=true,this.canGoNextDirty=true):i&&(this.canGoNextDirty=true);}state(e,i){return this.recomputeVisibility(e,i),this.cache}getCanGoNext(e,i,n){if(this.recomputeVisibility(e,i),!this.canGoNextDirty)return this.cache.canGoNext;this.canGoNextDirty=false;let r=this.cache.currentStep,o=r?l(r,this.conditionValues(e),n):{};return this.cache.canGoNext=this.isMultiStep&&Object.keys(o).length===0,this.cache.canGoNext}findStepIndex(e,i,n){let o=this.state(i,n).visibleSteps.findIndex(s=>s.fields.some(a=>a.key===e));return o===-1?null:o}affectsStructure(e,i){return this.routeFields.has(e)||this.fieldDependents.has(e)||this.stepDependents.has(e)||i.size>0}cascadeHiddenFields(e,i){return this.reconcileHidden(e,i)}reconcileHidden(e,i){this.path.invalidate();let n=new Set([...this.fieldDependents.keys(),...this.stepDependents.keys()]);return this.drainQueue(n,e,i)}drainQueue(e,i,n){let r=[...e],o=new Set(r),s=new Set,a=l=>{delete i[l],delete n[l],this.path.invalidate(),s.add(l),!o.has(l)&&(o.add(l),r.push(l));};for(let l=0;l<r.length;l++){let d=r[l];o.delete(d),this.clearHiddenFields(this.fieldDependents.get(d),i,n,a),this.clearHiddenSteps(this.stepDependents.get(d),i,n,a);}return s}activeField(e,i){return this.fieldsByKey.get(e)?.find(n=>this.onPath(n,i)&&h$1(n,this.conditionValues(i)))}isFieldVisible(e,i){return this.activeField(e,i)!==void 0}conditionValues(e){return this.path.values(e)}onPath(e,i){let n=this.stepOfField.get(e);return !n||this.path.steps(i).includes(n)}get isMultiStep(){return (this.definition.steps??[]).length>0}buildIndexes(){for(let e of this.allFields)j(e,this.fieldDependents);for(let e of this.definition.steps??[]){j(e,this.stepDependents);for(let i of e.routes??[])for(let n of c$1(i))this.routeFields.add(n);}}recomputeVisibility(e,i){if(!this.visibilityDirty)return;if(this.visibilityDirty=false,!this.isMultiStep){this.cache.visibleSteps=[],this.cache.currentStep=null,this.cache.visibleFields=(this.definition.fields??[]).filter(o=>h$1(o,this.conditionValues(e)));return}this.cache.visibleSteps=this.path.steps(e);let n=this.cache.visibleSteps;this.cache.currentStep=n[i]??n[n.length-1]??null;let r=this.cache.currentStep;this.cache.visibleFields=r?r.fields.filter(o=>h$1(o,this.conditionValues(e))):[];}clearHiddenFields(e,i,n,r){for(let o of e??[])this.onPath(o,i)&&(h$1(o,this.conditionValues(i))||i[o.key]===void 0&&n[o.key]===void 0||r(o.key));}clearHiddenSteps(e,i,n,r){for(let o of e??[])if(!h$1(o,this.conditionValues(i)))for(let s of o.fields)i[s.key]===void 0&&n[s.key]===void 0||r(s.key);}};var ye=class{constructor(e$1,i,n){this.definition=e$1;this.skipped=new Map;this.validationEpoch=0;this.operationEpoch=0;this.subscriptions=new C;this.lifecycle=n??{},this.validators=n?.validators??{};let r=v(e$1,{validators:this.validators}),o=r.filter(y);if(o.length)throw new h(o);let s=this.lifecycle.onWarning??ge;for(let l of r)s(l);this.visibility=new E(e$1);let a=e(this.visibility.allFields,i);this.state={values:a,errors:{},topLevelErrors:[],currentStepIndex:0,fieldLoading:{},stepValidating:false,submitting:false},this.visibility.reconcileHidden(a,this.state.errors);}get onStepValidate(){return this.lifecycle.onStepValidate}get values(){return this.state.values}get errors(){return this.state.errors}get topLevelErrors(){return this.state.topLevelErrors}get currentStepIndex(){return this.state.currentStepIndex}get fieldLoading(){return this.state.fieldLoading}get stepValidating(){return this.state.stepValidating}get submitting(){return this.state.submitting}get isMultiStep(){return (this.definition.steps??[]).length>0}get visibleSteps(){return this.visibility.state(this.state.values,this.currentStepIndex).visibleSteps}get currentStep(){return this.visibility.state(this.state.values,this.currentStepIndex).currentStep}get visibleFields(){return this.visibility.state(this.state.values,this.currentStepIndex).visibleFields}get isFirstStep(){return this.currentStepIndex===0}get isLastStep(){return this.currentStepIndex>=this.visibleSteps.length-1}get canGoNext(){return this.visibility.getCanGoNext(this.state.values,this.currentStepIndex,this.validators)}get progress(){let e=this.visibleSteps.length;return {current:Math.min(this.currentStepIndex+1,e),total:e}}subscribe(e){return this.subscriptions.subscribe(e)}getSnapshot(){return this.subscriptions.getSnapshot()}subscribeField(e,i){return this.subscriptions.subscribeField(e,i)}getFieldSnapshot(e){return this.subscriptions.getFieldSnapshot(e)}subscribeStructure(e){return this.subscriptions.subscribeStructure(e)}getStructureSnapshot(){return this.subscriptions.getStructureSnapshot()}setValue(e,i){let{values:n,errors:r}=this.state,o$1=this.isMultiStep?this.visibleSteps:null,s=!Object.is(n[e],i),a=r[e]!==void 0;n[e]=i,delete r[e];for(let[R,be]of this.skipped)s&&be.includes(e)&&this.skipped.delete(R);let l=this.visibility.cascadeHiddenFields(n,r),d=o(this.internals,e),f=new Set([...l,...d]);(s||a)&&f.add(e);let w=s||l.size>0,k=w&&this.visibility.affectsStructure(e,l);if(o$1&&k){this.visibility.markChanged(true,true),this.state.currentStepIndex=u$1(o$1,this.visibleSteps,this.currentStepIndex);for(let R of p$1(this.internals))f.add(R);}this.notify({fieldKeys:f,structureChanged:k,valuesChanged:w});}setErrors(e){n(this.internals,e,true);}setFieldLoading(e,i){let n=this.state.fieldLoading[e]===true;i?this.state.fieldLoading[e]=true:delete this.state.fieldLoading[e],this.notify({fieldKeys:n===i?[]:[e]});}cancelPendingActions(){this.validationEpoch++,this.operationEpoch++,this.state.stepValidating=false,this.state.submitting=false,this.notify();}next(){return z(this.internals,"next")}back(){return z(this.internals,"back")}skip(e){return y$1(this.internals,e)}submit(e){return x$1(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}validate(){return q(this.internals)}validateField(e){return r(this.internals,e)}getSubmitValues(){return s(this.internals)}goToStepWithField(e){A$1(this.internals,e);}reset(e){t(this.internals,e);}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};
4
+ export{h as a,v as b,Ze as c,Xe as d,ye as e};//# sourceMappingURL=chunk-OMINRKEL.js.map
5
+ //# sourceMappingURL=chunk-OMINRKEL.js.map