@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/dist/server.d.ts CHANGED
@@ -1,18 +1,16 @@
1
- import { b as FormDefinition } from './definition-H3WUR596.js';
2
-
3
- interface DefinitionCheck {
4
- errors: string[];
5
- warnings: string[];
6
- }
7
- declare function checkDefinition(definition: FormDefinition): DefinitionCheck;
1
+ export { C as CheckDefinitionOptions, c as checkDefinition, p as parseDefinition } from './check-definition-BTMV3Ziq.js';
2
+ import { V as ValidatorFn } from './validate-field-glVVoN3E.js';
3
+ export { D as DefinitionIssue, a as DefinitionIssueCode, F as FormDefinitionError } from './validate-field-glVVoN3E.js';
4
+ import { f as FormDefinition } from './definition-Bufih_Bx.js';
8
5
 
9
6
  interface SubmissionOptions {
10
7
  skippedSteps?: string[];
8
+ validators?: Record<string, ValidatorFn>;
11
9
  }
12
10
  interface SubmissionResult {
13
11
  values: Record<string, unknown>;
14
12
  errors: Record<string, string>;
15
13
  }
16
- declare function validateSubmission(definition: FormDefinition, input: unknown, options?: SubmissionOptions): SubmissionResult;
14
+ declare function validateSubmission(definition: FormDefinition, values: unknown, options?: SubmissionOptions): SubmissionResult;
17
15
 
18
- export { type DefinitionCheck, type SubmissionOptions, type SubmissionResult, checkDefinition, validateSubmission };
16
+ export { type SubmissionOptions, type SubmissionResult, validateSubmission };
@@ -1,5 +1,6 @@
1
1
  var Formhaus=(function(exports){'use strict';typeof console==="undefined"&&(globalThis.console={log:function(){},warn:function(){},error:function(){}});
2
- var Ot=Object.defineProperty,Lt=Object.defineProperties;var $t=Object.getOwnPropertyDescriptors;var ot=Object.getOwnPropertySymbols;var jt=Object.prototype.hasOwnProperty,Nt=Object.prototype.propertyIsEnumerable;var lt=(t,e,r)=>e in t?Ot(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r,p=(t,e)=>{for(var r in e||(e={}))jt.call(e,r)&&lt(t,r,e[r]);if(ot)for(var r of ot(e))Nt.call(e,r)&&lt(t,r,e[r]);return t},J=(t,e)=>Lt(t,$t(e));function K(t){return t==null||t===""||Array.isArray(t)&&!t.length}function U(t,e){let r=e[t.field];return t.eq!==void 0?r===t.eq:t.neq!==void 0?r!==t.neq:t.in!==void 0?t.in.includes(r):t.notIn!==void 0?!t.notIn.includes(r):t.notEmpty===true?!K(r):true}function h(t,e){var i,n;let r=s=>U(s,e);return ((i=t.show)!=null?i:[]).every(r)&&(!((n=t.showAny)!=null&&n.length)||t.showAny.some(r))}var x=h;function at(t){var e,r;return !!((e=t.fields)!=null&&e.length)&&!!((r=t.steps)!=null&&r.length)}function F(t){var e;return !!((e=t.steps)!=null&&e.some(r=>{var i;return (i=r.routes)==null?void 0:i.length}))}function S(t){var e,r;return [...(e=t.show)!=null?e:[],...(r=t.showAny)!=null?r:[]].map(i=>i.field)}function w(t){var e,r;return (e=t.steps)!=null&&e.length?t.steps.flatMap(i=>i.fields):(r=t.fields)!=null?r:[]}function I(t,e){let r={};for(let i of t)i.defaultValue!==void 0&&(r[i.key]=i.defaultValue);return Object.assign(r,e)}function E(t,e){let r=new Set([...Object.keys(t),...Object.keys(e)]);return new Set([...r].filter(i=>!Object.is(t[i],e[i])))}function V(t){var s;let e=(s=t.steps)!=null?s:[],r=at(t)?['FormEngine rejects a definition with both "fields" and "steps".']:[],i=new Map,n=new Map;e.forEach((o,l)=>{i.has(o.id)&&r.push(`Duplicate step id "${o.id}".`),i.set(o.id,l);for(let a of o.fields)n.set(a.key,l);});for(let{key:o}of w(t))(o in Object.prototype||o==="prototype")&&r.push(`Reserved field key "${o}".`);return F(t)&&e.forEach((o,l)=>{var a,u;for(let d of (a=o.routes)!=null?a:[]){let c=d.to===null?null:i.get(d.to);(c===void 0||c!==null&&c<=l)&&r.push(`Invalid route from "${o.id}" to "${d.to}": targets must be later steps or null.`);for(let f of S(d))((u=n.get(f))!=null?u:1/0)<=l||r.push(`Invalid route on "${o.id}": condition field "${f}" must belong to this or an earlier step.`);}}),r}function ut(t){var i,n,s,o;let e=(i=t.steps)!=null?i:[],r=[];for(let l of e){let a=new Set(((n=l.routes)!=null?n:[]).map(u=>u.to).filter(u=>u!==null));for(let u of a){let d=e.findIndex(y=>y.id===u),c=e[d+1],f=(o=(s=e[d])==null?void 0:s.routes)==null?void 0:o.some(y=>{var v,b;return !((v=y.show)!=null&&v.length)&&!((b=y.showAny)!=null&&b.length)});c&&a.has(c.id)&&!f&&r.push(`Route branch "${u}" from "${l.id}" continues into sibling branch "${c.id}". Add an unconditional route where it should continue.`);}}return r}function tt(t,e){var o,l;let r=(o=t.steps)!=null?o:[];if(!F(t))return r.filter(a=>x(a,e));let i=new Map(r.map((a,u)=>[a.id,u])),n=[],s={};for(let a=0;a<r.length;){let u=r[a];if(!x(u,s)){a++;continue}n.push(u),Object.assign(s,ct(u,e,s));let d=(l=u.routes)==null?void 0:l.find(c=>{var f;return h(c,s)&&(c.to===null||((f=i.get(c.to))!=null?f:-1)>a&&x(r[i.get(c.to)],s))});if((d==null?void 0:d.to)===null)break;a=d?i.get(d.to):a+1;}return n}function dt(t,e,r){var o;let i=(o=t[r])!=null?o:t[t.length-1],n=e.findIndex(l=>l.id===(i==null?void 0:i.id));if(n!==-1)return n;let s=new Map(e.map((l,a)=>[l.id,a]));for(let l=Math.min(r-1,t.length-1);l>=0;l--){let a=s.get(t[l].id);if(a!==void 0)return a}return 0}function ct(t,e,r){let i=p({},r);for(let s of t.fields)i[s.key]=e[s.key];let n={};for(let s of t.fields)h(s,i)&&e[s.key]!==void 0&&(n[s.key]=e[s.key]);return n}var P=class{constructor(e){this.definition=e;this.source=null;this.activeStepList=[];this.activeValueMap={};this.enabled=F(e);}invalidate(){this.source=null;}steps(e){return this.refresh(e),this.activeStepList}values(e){return this.refresh(e),this.activeValueMap}refresh(e){if(this.source===e)return;this.source=e,this.activeStepList=tt(this.definition,e);let r={};for(let i of this.activeStepList)Object.assign(r,ct(i,e,r));this.activeValueMap=r;}};function pt(t){var l,a;let e=[],r=new Map,i=w(t),n=new Set;for(let{key:u}of i)n.has(u)&&e.push(`Duplicate field key "${u}" \u2014 fields will share state and overwrite each other`),n.add(u);let s=(u,d,c,f)=>{var v;let y=S(c);for(let b of y)n.has(b)||e.push(`${u} "${d}" has show condition referencing non-existent field "${b}"`);if(y.length)for(let b of f)r.set(b,[...(v=r.get(b))!=null?v:[],...y]);};for(let u of i){s("Field",u.key,u,[u.key]);let d=(l=u.validation)==null?void 0:l.pattern;if(d!==void 0)try{new RegExp(d);}catch(c){e.push(`Field "${u.key}" has invalid regex pattern: "${d}"`);}}let o=new Set;for(let u of (a=t.steps)!=null?a:[]){s("Step",u.id,u,u.fields.map(d=>d.key));for(let d of S(u))F(t)&&n.has(d)&&!o.has(d)&&e.push(`Step "${u.id}" condition field "${d}" must belong to an earlier step.`);for(let{key:d}of u.fields)o.add(d);u.skip&&(u.next===false||!t.steps[1])&&e.push(`Step "${u.id}" has "skip" but no Next button or later step.`);}return {graph:r,warnings:e}}function Tt(t){var i;let e=new Map,r=[];for(let n of t.keys()){if(e.has(n))continue;e.set(n,true);let s=[[n,0]];for(;s.length>0;){let o=s[s.length-1],l=(i=t.get(o[0]))==null?void 0:i[o[1]++];if(l===void 0)e.set(o[0],false),s.pop();else if(e.get(l)){let a=s.map(([u])=>u);r.push([...a.slice(a.indexOf(l)),l]);}else e.has(l)||(e.set(l,true),s.push([l,0]));}}return r}function O(t){let{graph:e,warnings:r}=pt(t);for(let i of Tt(e))r.push(`Circular show condition detected: ${i.join(" -> ")}`);return [...V(t),...r,...ut(t)]}function Kt(t){let e=V(t),r=new Set(e);return {errors:e,warnings:O(t).filter(i=>!r.has(i))}}var et=class extends Error{constructor(r,i){super(`The action completed, but ${r} failed: ${i instanceof Error?i.message:String(i)}`);this.phase=r;this.committed=true;this.name="FormLifecycleError",this.cause=i;}};async function B(t,e){try{await e();}catch(r){throw new et(t,r)}}function ft(t){return t.visibleSteps.map(e=>e.id).join(`
3
- `)}function L(t,e){let r=ft(t);return ()=>ft(t)!==r||Object.keys(e).some(i=>e[i]!==void 0&&!Object.is(t.values[i],e[i]))}var m={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 k(t,e){var r,i;switch(t){case "required":return "This field is required";case "minLength":return `Must be at least ${e==null?void 0:e.min} ${(r=e==null?void 0:e.unit)!=null?r:"characters"}`;case "maxLength":return `Must be at most ${e==null?void 0:e.max} ${(i=e==null?void 0:e.unit)!=null?i:"characters"}`;case "min":return `Must be at least ${e==null?void 0:e.min}`;case "max":return `Must be at most ${e==null?void 0:e.max}`;case "pattern":return "Invalid format";case "matchField":return "Fields must match";default:return "Invalid value"}}var rt=new Set(["checkbox","switch"]);function Pt(t,e){return K(t)||t===false&&rt.has(e.type)}function ht(t,e,r,i){var o,l;let n=r[`min${e}`],s=r[`max${e}`];if(n!==void 0&&t<n)return (o=r[`min${e}Message`])!=null?o:k(`min${e}`,{min:n,unit:i});if(s!==void 0&&t>s)return (l=r[`max${e}Message`])!=null?l:k(`max${e}`,{max:s,unit:i})}function Bt(t,e){var r;if(e.pattern!==void 0)try{return new RegExp(e.pattern).test(String(t))?void 0:(r=e.patternMessage)!=null?r:k("pattern")}catch(i){return}}function M(t,e,r,i){var l,a,u,d;let n=t.validation;if(!n)return null;if(Pt(e,t))return n.required?typeof n.required=="string"?n.required:k("required"):null;let s=typeof e=="string"||Array.isArray(e)?ht(e.length,"Length",n,Array.isArray(e)?"items":void 0):typeof e=="number"?ht(e,"",n):void 0,o=n.matchField!==void 0&&e!==r[n.matchField]?(l=n.matchFieldMessage)!=null?l:k("matchField"):void 0;return ((d=(a=s!=null?s:Bt(e,n))!=null?a:o)!=null?d:n.validator?(u=i==null?void 0:i[n.validator])==null?void 0:u.call(i,e,r):void 0)||null}function R(t,e,r){return G(t.fields,e,r)}function G(t,e,r){let i={};for(let n of t){if(!h(n,e))continue;let s=M(n,e[n.key],e,r);s&&(i[n.key]=s);}return i}function q(t,e,r=false){let i=t.errors;t.errors={},t.topLevelErrors=[];for(let[l,a]of Object.entries(e))t.visibility.isFieldVisible(l,t.values)?t.errors[l]=a:t.topLevelErrors.push(a);let n=Object.keys(e).find(l=>t.errors[l]!==void 0),s=r&&n&&t.isMultiStep?t.visibility.findStepIndex(n,t.values,t.currentStepIndex):null,o=s!==null&&s!==t.currentStepIndex;s!==null&&(t.currentStepIndex=s),t.notify({fieldKeys:E(i,t.errors),structureChanged:o});}function mt(t,e){var i;let r=[];for(let n of t.visibility.allFields)((i=n.validation)==null?void 0:i.matchField)!==e||t.errors[n.key]===void 0||M(n,t.values[n.key],D(t),t.validators)||(delete t.errors[n.key],r.push(n.key));return r}function gt(t){let e=new Set(t.visibleSteps.flatMap(i=>i.fields.map(n=>n.key))),r=Object.keys(t.errors).filter(i=>!e.has(i));for(let i of r)delete t.errors[i];return r}function D(t){return F(t.definition)?C(t):yt(t,p({},t.values))}function yt(t,e){for(let r of [...t.skipped.values()].flat())delete e[r];return e}function $(t){var i;let e=t.errors,r={};if(t.isMultiStep)for(let n of t.visibleSteps)t.skipped.has(n.id)||Object.assign(r,R(n,D(t),t.validators));else Object.assign(r,G((i=t.definition.fields)!=null?i:[],t.values,t.validators));return t.errors=r,t.notify({fieldKeys:E(e,r)}),r}function bt(t,e){let r=t.visibility.fieldByKey.get(e);if(!r||!t.visibility.isFieldVisible(e,t.values))return null;let i=t.errors[e],n=M(r,t.values[e],D(t),t.validators);n?t.errors[e]=n:delete t.errors[e];let s=Object.is(i,t.errors[e])?[]:[e];return t.notify({fieldKeys:s}),n}function C(t){let e={},r=t.visibility.getVisibleFieldKeys(t.values,t.currentStepIndex);for(let i of r)t.values[i]!==void 0&&(e[i]=t.values[i]);return yt(t,e)}function St(t,e){let r=t.values,i=t.errors,n=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.submitting=false,t.values=I(t.visibility.allFields,e),t.errors={},t.topLevelErrors=[],t.fieldLoading={},t.stepValidating=false,t.currentStepIndex=0,t.skipped.clear(),t.visibility.reconcileHidden(t.values,t.errors);let s=E(r,t.values),o=new Set([...s,...E(i,t.errors),...n]);t.notify({fieldKeys:o,structureChanged:true,valuesChanged:s.size>0});}function vt(t){var i,n;let e=(n=(i=t.currentStep)==null?void 0:i.fields)!=null?n:[],r=p({},t.values);for(let{key:s}of e)delete r[s];return Object.assign(r,I(e))}function H(t){return tt(t.definition,vt(t))[t.currentStepIndex+1]}function j(t){let e=t.currentStep,r=e.fields.map(({key:i})=>i);t.values=vt(t);for(let i of r)delete t.errors[i];return t.skipped.set(e.id,r),t.visibility.reconcileHidden(t.values,t.errors),t.notify({fieldKeys:r,structureChanged:true,valuesChanged:true}),r}function N(t){let e=t.currentStep;e&&t.skipped.delete(e.id);}function Ft(t,e){return t.currentStepIndex=e,t.notify({structureChanged:true}),j(t)}async function _(t,e,r=false){if(t.submitting||t.stepValidating)return false;r||N(t);let i=p({},t.lifecycle),n=false,s=t.validationEpoch,o=++t.operationEpoch,l=C(t),a=L(t,l),u=()=>s!==t.validationEpoch||o!==t.operationEpoch||a();t.submitting=true,t.notify();try{if(u()||Object.keys($(t)).length>0||u())return !1;if(i.onBeforeSubmit){let d=await i.onBeforeSubmit(l);if(u()||d===!1)return !1}if(u())return !1;if(i.onBeforeSubmit){if(Object.keys($(t)).length>0||u())return !1;l=C(t);}return n=!0,await e(l,[...t.skipped.keys()]),o!==t.operationEpoch||await B("afterSubmit",()=>{var d;return (d=i.onAfterSubmit)==null?void 0:d.call(i,l)}),!0}catch(d){if(!n&&u())return false;throw d}finally{o===t.operationEpoch&&(t.submitting=false,t.notify());}}function it(t){let e=t.currentStep;if(!e)return true;let r=R(e,D(t),t.validators);if(Object.keys(r).length===0)return false;let i=p({},t.errors);return Object.assign(t.errors,r),t.notify({fieldKeys:E(i,t.errors)}),true}function z(t,e){t.validationEpoch++,t.currentStepIndex=e,t.notify({structureChanged:true});}function wt(t){return t.isLastStep?false:(z(t,t.currentStepIndex+1),true)}function kt(t){return t.isMultiStep?(N(t),!it(t)&&wt(t)):false}function xt(t){return !t.isMultiStep||!H(t)?false:(j(t),wt(t))}async function Et(t,e){if(!t.isMultiStep||t.stepValidating||t.submitting)return false;if(H(t))return Y(t,"next","skip");let r=t.currentStep;if(!e||!r)return false;let i=t.values,n=p({},t.errors),s=false,o=j(t),l=t.values,a=L(t,p({},l));try{return await _(t,async(u,d)=>{await e(u,d),s=!0;},!0)}finally{!s&&t.values===l&&!a()&&(t.values=i,t.errors=p(p({},n),t.errors),t.skipped.delete(r.id),t.notify({fieldKeys:o,structureChanged:true,valuesChanged:true}));}}async function Y(t,e,r=e){let i=r==="skip";if(!t.isMultiStep||t.stepValidating||t.submitting||!i&&(e==="next"?t.isLastStep:t.isFirstStep))return false;let n=t.currentStep,s=e==="next"&&!i;if(s&&N(t),s&&it(t))return false;let o=p({},t.lifecycle),l=t.onStepValidate,a=false,d=t.currentStepIndex+(e==="next"?1:-1),c=i?H(t):t.visibleSteps[d];if(!c)return false;let f={fromStepId:n.id,toStepId:c.id,direction:e,reason:r,values:p({},D(t))},y=t.validationEpoch,v=++t.operationEpoch,b=L(t,f.values),A=()=>{var g;return y!==t.validationEpoch||v!==t.operationEpoch||((g=t.currentStep)==null?void 0:g.id)!==n.id||b()};t.stepValidating=true,t.notify();try{if(A())return !1;if(s&&l){let g=await l(n.id,f.values);if(A())return !1;if(g&&Object.keys(g).length>0)return q(t,g),!1}if(o.onBeforeStepChange){let g=await o.onBeforeStepChange(f);if(A()||g===!1)return !1}return A()||s&&it(t)?!1:(a=!0,i&&j(t),z(t,d),await B("afterStepChange",()=>{var g;return (g=o.onAfterStepChange)==null?void 0:g.call(o,f)}),!0)}catch(g){if(!a&&A())return false;throw g}finally{v===t.operationEpoch&&(t.stepValidating=false,t.notify());}}function Rt(t){t.isMultiStep&&!t.isFirstStep&&z(t,t.currentStepIndex-1);}function It(t,e){if(!t.isMultiStep)return;let r=t.visibility.findStepIndex(e,t.values,t.currentStepIndex);r===t.currentStepIndex?t.notify():r!==null&&z(t,r);}var W=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,r){var n;let i=(n=this.fieldListeners.get(e))!=null?n:new Set;return i.add(r),this.fieldListeners.set(e,i),()=>{i.delete(r),i.size===0&&this.fieldListeners.delete(e);}}getFieldSnapshot(e){var r;return (r=this.fieldVersions.get(e))!=null?r:0}subscribeStructure(e){return this.structureListeners.add(e),()=>this.structureListeners.delete(e)}getStructureSnapshot(){return this.structureVersion}notify({fieldKeys:e=[],structureChanged:r=false}={}){for(let i of new Set(e))this.notifyField(i);r&&this.notifyStructure(),this.version++;for(let i of this.listeners)i();}notifyField(e){var r,i;this.fieldVersions.set(e,((r=this.fieldVersions.get(e))!=null?r:0)+1);for(let n of (i=this.fieldListeners.get(e))!=null?i:[])n();}notifyStructure(){this.structureVersion++;for(let e of this.structureListeners)e();}};function nt(t,e){var r;for(let i of S(t)){let n=(r=e.get(i))!=null?r:new Set;n.add(t),e.set(i,n);}}var X=class{constructor(e){this.definition=e;this.routeFields=new Set;this.fieldDependents=new Map;this.stepDependents=new Map;this.stepByFieldKey=new Map;this.visibilityDirty=true;this.canGoNextDirty=true;this.cache={visibleSteps:[],currentStep:null,visibleFields:[],canGoNext:false};var r;this.allFields=w(e),this.fieldByKey=new Map(this.allFields.map(i=>[i.key,i])),this.path=new P(e);for(let i of (r=e.steps)!=null?r:[])for(let n of i.fields)this.stepByFieldKey.set(n.key,i);this.buildIndexes();}markChanged(e,r){(e||r)&&this.path.invalidate(),e?(this.visibilityDirty=true,this.canGoNextDirty=true):r&&(this.canGoNextDirty=true);}state(e,r){return this.recomputeVisibility(e,r),this.cache}getCanGoNext(e,r,i){if(this.recomputeVisibility(e,r),!this.canGoNextDirty)return this.cache.canGoNext;this.canGoNextDirty=false;let n=this.cache.currentStep,s=n?R(n,this.conditionValues(e),i):{};return this.cache.canGoNext=this.isMultiStep&&Object.keys(s).length===0,this.cache.canGoNext}findStepIndex(e,r,i){let s=this.state(r,i).visibleSteps.findIndex(o=>o.fields.some(l=>l.key===e));return s===-1?null:s}affectsStructure(e,r){return this.routeFields.has(e)||this.fieldDependents.has(e)||this.stepDependents.has(e)||r.size>0}cascadeHiddenFields(e,r,i){return this.path.invalidate(),this.hasRoutes?this.reconcileHidden(r,i):this.drainQueue(new Set([e]),r,i)}reconcileHidden(e,r){this.path.invalidate();let i=new Set([...this.fieldDependents.keys(),...this.stepDependents.keys()]);return this.drainQueue(i,e,r)}drainQueue(e,r,i){let n=[...e],s=new Set(n),o=new Set,l=a=>{delete r[a],delete i[a],this.path.invalidate(),o.add(a),!s.has(a)&&(s.add(a),n.push(a));};for(let a=0;a<n.length;a++){let u=n[a];s.delete(u),this.clearHiddenFields(this.fieldDependents.get(u),r,l),this.clearHiddenSteps(this.stepDependents.get(u),r,l);}return o}isFieldVisible(e,r){let i=this.fieldByKey.get(e);if(!i||!h(i,this.conditionValues(r)))return false;let n=this.stepByFieldKey.get(e);return !n||this.path.steps(r).includes(n)}getVisibleFieldKeys(e,r){var s;if(this.hasRoutes)return new Set(Object.keys(this.path.values(e)));let i=new Set,n=this.isMultiStep?this.state(e,r).visibleSteps.flatMap(o=>o.fields):(s=this.definition.fields)!=null?s:[];for(let o of n)h(o,this.conditionValues(e))&&i.add(o.key);return i}conditionValues(e){return this.hasRoutes?this.path.values(e):e}get hasRoutes(){return this.path.enabled}get isMultiStep(){var e;return ((e=this.definition.steps)!=null?e:[]).length>0}buildIndexes(){var e,r;for(let i of this.allFields)nt(i,this.fieldDependents);for(let i of (e=this.definition.steps)!=null?e:[]){nt(i,this.stepDependents);for(let n of (r=i.routes)!=null?r:[])for(let s of S(n))this.routeFields.add(s);}}recomputeVisibility(e,r){var s,o,l;if(!this.visibilityDirty)return;if(this.visibilityDirty=false,!this.isMultiStep){this.cache.visibleSteps=[],this.cache.currentStep=null,this.cache.visibleFields=((s=this.definition.fields)!=null?s:[]).filter(a=>h(a,this.conditionValues(e)));return}this.cache.visibleSteps=this.path.steps(e);let i=this.cache.visibleSteps;this.cache.currentStep=(l=(o=i[r])!=null?o:i[i.length-1])!=null?l:null;let n=this.cache.currentStep;this.cache.visibleFields=n?n.fields.filter(a=>h(a,this.conditionValues(e))):[];}clearHiddenFields(e,r,i){for(let n of e!=null?e:[]){let s=this.stepByFieldKey.get(n.key);this.hasRoutes&&s&&!this.path.steps(r).includes(s)||h(n,this.conditionValues(r))||r[n.key]===void 0||i(n.key);}}clearHiddenSteps(e,r,i){for(let n of e!=null?e:[])if(!x(n,this.conditionValues(r)))for(let s of n.fields)r[s.key]!==void 0&&i(s.key);}};var Q=class{constructor(e,r,i){this.definition=e;this.errors={};this.topLevelErrors=[];this.currentStepIndex=0;this.fieldLoading={};this.stepValidating=false;this.submitting=false;this.skipped=new Map;this.validationEpoch=0;this.operationEpoch=0;this.subscriptions=new W;var o;let n=V(e);if(n.length)throw new Error(n.join(`
4
- `));this.lifecycle=i!=null?i:{},this.validators=(o=i==null?void 0:i.validators)!=null?o:{},this.visibility=new X(e);let s=O(e);for(let{key:l,validation:a}of this.visibility.allFields){let u=a==null?void 0:a.validator;u&&!this.validators[u]&&s.push(`Field "${l}" references unknown validator "${u}".`);}for(let l of s)console.warn(`[FormEngine] ${l}`);this.values=I(this.visibility.allFields,r),this.visibility.reconcileHidden(this.values,this.errors);}get onStepValidate(){return this.lifecycle.onStepValidate}get isMultiStep(){var e;return ((e=this.definition.steps)!=null?e:[]).length>0}get visibleSteps(){return this.visibility.state(this.values,this.currentStepIndex).visibleSteps}get currentStep(){return this.visibility.state(this.values,this.currentStepIndex).currentStep}get visibleFields(){return this.visibility.state(this.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.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,r){return this.subscriptions.subscribeField(e,r)}getFieldSnapshot(e){return this.subscriptions.getFieldSnapshot(e)}subscribeStructure(e){return this.subscriptions.subscribeStructure(e)}getStructureSnapshot(){return this.subscriptions.getStructureSnapshot()}setValue(e,r){let i=this.isMultiStep?this.visibleSteps:null,n=!Object.is(this.values[e],r),s=this.errors[e]!==void 0;this.values[e]=r,delete this.errors[e];for(let[c,f]of this.skipped)n&&f.includes(e)&&this.skipped.delete(c);let o=this.visibility.cascadeHiddenFields(e,this.values,this.errors),l=mt(this.internals,e),a=new Set([...o,...l]);(n||s)&&a.add(e);let u=n||o.size>0,d=u&&this.visibility.affectsStructure(e,o);if(i&&d){this.visibility.markChanged(true,true),this.currentStepIndex=dt(i,this.visibleSteps,this.currentStepIndex);for(let c of gt(this.internals))a.add(c);}this.notify({fieldKeys:a,structureChanged:d,valuesChanged:u});}setErrors(e){q(this.internals,e,true);}setFieldLoading(e,r){let i=this.fieldLoading[e]===true;r?this.fieldLoading[e]=true:delete this.fieldLoading[e],this.notify({fieldKeys:i===r?[]:[e]});}cancelPendingActions(){this.validationEpoch++,this.operationEpoch++,this.stepValidating=false,this.submitting=false,this.notify();}nextStep(){return kt(this.internals)}nextStepAsync(e="next"){return Y(this.internals,"next",e)}prevStepAsync(){return Y(this.internals,"back")}skipStep(){return xt(this.internals)}skipStepAsync(e){return Et(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}submitAsync(e){return _(this.internals,e)}prevStep(){Rt(this.internals);}validate(){return $(this.internals)}validateField(e){return bt(this.internals,e)}getSubmitValues(){return C(this.internals)}goToStepWithField(e){It(this.internals,e);}reset(e){St(this.internals,e);}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};var T=1e4,Gt=254,qt=1e3,Ht=/^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/,_t=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,Vt="\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",zt=new RegExp(`^${Vt}$`),Yt=new RegExp(`^${Vt}T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,3})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)?$`),Wt=new Set(["text","phone","password","textarea","autocomplete"]),Xt=new Map([["email",[Ht,m.email,Gt]],["date",[zt,m.date,T]],["datetime",[Yt,m.datetime,T]]]);function Mt(t,e){if(t.type!=="number"||typeof e!="string"||!_t.test(e))return e;let r=Number(e);return Number.isFinite(r)?r:e}function Dt(t,e){return !t.options||t.options.some(r=>r.value===e)}function Ct(t,e){var i,n,s,o;let r=Math.min(T,(n=(i=t.validation)==null?void 0:i.maxLength)!=null?n:T);return e.length<=r?null:(o=(s=t.validation)==null?void 0:s.maxLengthMessage)!=null?o:k("maxLength",{max:r})}function Qt(t,e){var i,n;return Array.isArray(e)?e.length>((n=(i=t.options)==null?void 0:i.length)!=null?n:qt)?m.option:e.every(s=>typeof s=="string"&&s.length<=T&&Dt(t,s))?null:m.option:m.options}function Z(t,e,r){return typeof e=="string"?Ct(t,e):r}function Zt(t,e,[r,i,n]){var s;return typeof e!="string"?i:(s=Ct(t,e))!=null?s:e.length<=n&&r.test(e)?null:i}function Jt(t,e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)?null:Z(t,e,m.value)}function Ut(t,e){return e==null||e===""||t.type==="multiselect"&&Array.isArray(e)&&!e.length}function At(t,e){var i;if(Ut(t,e))return null;if(rt.has(t.type))return typeof e=="boolean"?null:m.boolean;if(t.type==="number")return typeof e=="number"&&Number.isFinite(e)?null:m.number;if(t.type==="multiselect")return Qt(t,e);if(t.type==="file")return Z(t,e,m.file);let r=Xt.get(t.type);return r?Zt(t,e,r):t.type==="select"||t.type==="radio"?(i=Z(t,e,m.option))!=null?i:Dt(t,e)?null:m.option:Wt.has(t.type)?Z(t,e,m.string):Jt(t,e)}var te=()=>null,st=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function ee(t,e){let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},i={};for(let n of t)st(r,n.key)&&(i[n.key]=Mt(n,r[n.key]));return i}function re(t,e){let r=new Map;for(let i of t){let n=st(e,i.key)?At(i,e[i.key]):null;n&&r.set(i.key,n);}return r}function ie(t,e){var n;let r=s=>s.map(o=>e.has(o.key)?J(p({},o),{validation:void 0}):o),i=(n=t.steps)==null?void 0:n.map(s=>J(p({},s),{fields:r(s.fields)}));return p(p(p({},t),t.fields&&{fields:r(t.fields)}),i&&{steps:i})}function ne(t){let e={};for(let{validation:r}of t)r!=null&&r.validator&&(e[r.validator]=te);return e}function se(t,e){if(!Array.isArray(e))return;let r=new Set(e);for(let i=0;i<t.visibleSteps.length;i++){let n=t.visibleSteps[i];n.skip&&r.has(n.id)&&Ft(t,i);}}function oe(t,e,r={}){let i=w(t),n=ee(i,e),s=re(i,n),o=new Q(ie(t,s),n,{validators:ne(i)});se(o,r.skippedSteps);let l=o.validate(),a=o.getSubmitValues();for(let[u,d]of s)st(a,u)&&(l[u]=d);return {values:a,errors:l}}exports.checkDefinition=Kt;exports.validateSubmission=oe;return exports;})({});//# sourceMappingURL=server.iife.js.map
2
+ var ae=Object.defineProperty,ue=Object.defineProperties;var le=Object.getOwnPropertyDescriptors;var xt=Object.getOwnPropertySymbols;var de=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var Et=(t,e,n)=>e in t?ae(t,e,{enumerable:true,configurable:true,writable:true,value:n}):t[e]=n,f=(t,e)=>{for(var n in e||(e={}))de.call(e,n)&&Et(t,n,e[n]);if(xt)for(var n of xt(e))ce.call(e,n)&&Et(t,n,e[n]);return t},M=(t,e)=>ue(t,le(e));var It=["eq","neq","in","notIn","notEmpty","gt","gte","lt","lte"];function L(t){return t==null||t===""||Array.isArray(t)&&!t.length}function fe(t){let e=typeof t=="string"&&t.trim()!==""?Number(t):t;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function q(t,e,n){let i=fe(t);return i!==void 0&&n(i,e)}function dt(t,e){let n=e[t.field];return t.eq!==void 0?n===t.eq:t.neq!==void 0?n!==t.neq:t.in!==void 0?t.in.includes(n):t.notIn!==void 0?!t.notIn.includes(n):t.notEmpty!==void 0?!t.notEmpty||!L(n):t.gt!==void 0?q(n,t.gt,(i,r)=>i>r):t.gte!==void 0?q(n,t.gte,(i,r)=>i>=r):t.lt!==void 0?q(n,t.lt,(i,r)=>i<r):t.lte!==void 0?q(n,t.lte,(i,r)=>i<=r):false}var k=class extends Error{constructor(e){super(`Invalid form definition:
3
+ ${e.map(n=>n.message).join(`
4
+ `)}`),this.name="FormDefinitionError",this.issues=e;}};function $t(t){return (e,n,i,r)=>f({code:e,severity:t,path:n,message:`${n||"/"}: ${i}.${r?` ${r}.`:""}`},r&&{hint:`${r}.`})}var p=$t("error"),h=$t("warning");function B(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function D(t){return t.severity==="error"}function E(t){if(t.length===1)return `Use ${JSON.stringify(t[0])}`;let e=t.slice(0,10).map(n=>JSON.stringify(n)).join(", ");return t.length>10?`Use one of: ${e}, ...`:`Use one of: ${e}`}function pe(t,e){let n=Array.from({length:e.length+1},(i,r)=>r);for(let i=1;i<=t.length;i++){let r=[i];for(let s=1;s<=e.length;s++)r[s]=Math.min(n[s]+1,r[s-1]+1,n[s-1]+(t[i-1]===e[s-1]?0:1));n=r;}return n[e.length]}function ct(t,e){let n=t.toLowerCase();return e.find(i=>i!==t&&pe(n,i.toLowerCase())<=(i.length>4?2:1))}function R(t,e){let n=ct(t,e);return n!==void 0?`Use ${JSON.stringify(n)}`:e.length?E(e):void 0}var U=It,me=new Set(["in","notIn"]),he=new Set(["neq","notIn"]),ye=new Set(["gt","gte","lt","lte"]),ge=new Set(["text","email","phone","password","textarea","date","datetime","select","radio","autocomplete"]),Ct=new Set(["checkbox","switch"]);function be(t){return t.type==="number"?"number":Ct.has(t.type)?"boolean":ge.has(t.type)?"string":void 0}function Se(t,e,n){if(!(t.type!=="multiselect"&&!Ct.has(t.type)))return h("condition-value-mismatch",n,`"${t.key}" is a ${t.type} field, so "${e}" never matches it`,"Compare a number, text, radio or select field")}function Fe(t,e,n,i){var l;if(e==="notEmpty")return;if(ye.has(e))return Se(t,e,i);if(t.type==="multiselect"){let d=he.has(e)?"always":"never";return h("condition-value-mismatch",i,`"${t.key}" holds a list of values, so "${e}" ${d} matches it`,"Use notEmpty, or a select or radio field")}let r=me.has(e)&&Array.isArray(n)?n:[n],s=be(t),o=s&&r.find(d=>typeof d!==s);if(s&&o!==void 0)return h("condition-value-mismatch",i,`${JSON.stringify(o)} is a ${typeof o}, but "${t.key}" holds a ${s}`,`Use a ${s} value`);let u=s==="string"&&!t.optionsFrom&&((l=t.options)!=null&&l.length)?t.options.map(d=>d.value):null,a=u&&r.find(d=>!u.includes(d));if(u&&a!==void 0)return h("condition-value-mismatch",i,`${JSON.stringify(a)} is not an option of "${t.key}"`,E(u))}function ve(t,e){let n=Object.keys(t).filter(o=>o!=="field"),i=n.filter(o=>!U.includes(o)),r=i.map(o=>p("unknown-operator",`${e}/${B(o)}`,`"${o}" is not a condition operator`,R(o,[...U]))),s=n.length-i.length;if(s!==1&&!(s===0&&i.length)){let o=s?`the condition has ${s} operators`:"the condition has no operator";r.push(p("condition-operator-count",e,o,`Use exactly one of: ${U.join(", ")}`));}return r}function ke(t,{condition:e,path:n,owner:i,step:r,key:s}){let o=t.keys.get(e.field);if(!o){let l=t.keyList.filter(d=>d!==s);return p("unknown-field",`${n}/field`,`"${e.field}" is not a field key`,R(e.field,l))}if(r<0||i==="action")return;let u=i==="step"?"this or a later step":"a later step";if(o.step<r||i!=="step"&&o.step===r)return;let a=i==="step"?"earlier steps":"this or an earlier step";return p("forward-reference",`${n}/field`,`"${e.field}" belongs to ${u}`,`${i==="route"?"Route":i==="step"?"Step":"Field"} conditions can use fields of ${a}`)}function Dt(t){let e=[];for(let n of t.conditions){let{condition:i,path:r}=n;if(typeof i.field!="string"){e.push(p("missing-property",`${r}/field`,'the condition has no "field"',"Add the key of the field to test"));continue}let s=ve(i,r);e.push(...s);let o=ke(t,n);o&&e.push(o);let u=t.keys.get(i.field),a=U.find(l=>l in i);if(!o&&!s.length&&u&&a){let l=Fe(u.field,a,i[a],`${r}/${a}`);l&&e.push(l);}}return e}function ft(t,e,n,i,r,s){var o;for(let u of ["show","showAny"])((o=e[u])!=null?o:[]).forEach((a,l)=>t.push({condition:a,path:`${n}/${u}/${l}`,owner:i,step:r,key:s}));}function pt(t,e,n,i){var r;(e?(r=e.disabled)!=null?r:[]:[]).forEach((s,o)=>t.push({condition:s,path:`${n}/disabled/${o}`,owner:"action",step:i}));}function Rt(t,e){var o,u;let n=(o=t.steps)!=null?o:[],i=n.length?n.flatMap((a,l)=>a.fields.map((d,c)=>({field:d,path:`/steps/${l}/fields/${c}`,step:l}))):((u=t.fields)!=null?u:[]).map((a,l)=>({field:a,path:`/fields/${l}`,step:-1})),r=new Map;for(let a of i)r.has(a.field.key)||r.set(a.field.key,a);let s=[];for(let a of i)ft(s,a.field,a.path,"field",a.step,a.field.key);return n.forEach((a,l)=>{var d;ft(s,a,`/steps/${l}`,"step",l),((d=a.routes)!=null?d:[]).forEach((c,m)=>ft(s,c,`/steps/${l}/routes/${m}`,"route",l));for(let c of ["next","back","skip"])pt(s,a[c],`/steps/${l}/${c}`,l);}),pt(s,t.submit,"/submit",-1),pt(s,t.cancel,"/cancel",-1),{definition:t,entries:i,keys:r,keyList:[...r.keys()],conditions:s,validators:e}}var mt=["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","file","date","datetime","textarea"],we=new Set(["select","radio","multiselect"]),xe=new Set(["number","checkbox","switch"]);function Ee({field:t,path:e}){let n=mt.includes(t.type)?void 0:ct(t.type,mt);return n===void 0?[]:[h("unknown-field-type",`${e}/type`,`"${t.type}" is not a built-in field type`,`Use "${n}", or register a component for "${t.type}"`)]}function Ie({field:t,path:e}){if(!we.has(t.type))return [];if(!Array.isArray(t.options))return t.optionsFrom?[]:[h("missing-options",`${e}/options`,`the ${t.type} field "${t.key}" has no options`,'Add "options" or "optionsFrom"')];let n=t.options.map(s=>s.value),i=t.type==="multiselect"&&Array.isArray(t.defaultValue)?t.defaultValue:[t.defaultValue],r=t.defaultValue===void 0||!n.length||t.optionsFrom?void 0:i.find(s=>!n.includes(s));return r===void 0?[]:[h("default-not-in-options",`${e}/defaultValue`,`${JSON.stringify(r)} is not an option of "${t.key}"`,E(n))]}function Vt(t,e,n,i){let r=t[n],s=t[i];return r===void 0||s===void 0||r<=s?[]:[p("invalid-range",`${e}/validation/${n}`,`${n} (${r}) is greater than ${i} (${s})`,`Lower ${n} or raise ${i}`)]}function $e({field:t,path:e},n){if(!mt.includes(t.type))return [];let i=t.type==="number",r=i?[]:["min","max"].filter(o=>n[o]!==void 0),s=xe.has(t.type)?["minLength","maxLength"].filter(o=>n[o]!==void 0):[];return [...r.map(o=>h("rule-not-applicable",`${e}/validation/${o}`,`"${o}" applies to number fields only`,`Use ${o}Length to limit text length`)),...s.map(o=>h("rule-not-applicable",`${e}/validation/${o}`,`"${o}" does not apply to ${t.type} fields`,i?"Use min and max for numbers":`Remove ${o}`))]}function Ce(t,e){if(t===void 0)return [];try{return new RegExp(t),[]}catch(n){return [p("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 De(t,e){let n=e.field.validation;if(!n)return [];let{path:i}=e,r=[...Vt(n,i,"minLength","maxLength"),...Vt(n,i,"min","max"),...$e(e,n),...Ce(n.pattern,i)];n.matchField!==void 0&&!t.keys.has(n.matchField)&&r.push(p("unknown-field",`${i}/validation/matchField`,`"${n.matchField}" is not a field key`,R(n.matchField,t.keyList)));let s=t.validators;return n.validator!==void 0&&s&&!Object.prototype.hasOwnProperty.call(s,n.validator)&&r.push(h("unknown-validator",`${i}/validation/validator`,`the validator "${n.validator}" is not registered`,'Pass it in the "validators" option')),r}function Re(t,{field:e,path:n}){var i;return ((i=e.optionsDependsOn)!=null?i:[]).flatMap((r,s)=>t.keys.has(r)?[]:[h("unknown-field",`${n}/optionsDependsOn/${s}`,`"${r}" is not a field key`,R(r,t.keyList))])}function Ot(t){return t.entries.flatMap(e=>[...Ee(e),...Ie(e),...De(t,e),...Re(t,e)])}function Ve({definition:t,entries:e,keys:n}){var o;let i=new Map,r=(u,a)=>{var d;let l=a.filter(c=>n.has(c));if(l.length)for(let c of u)i.set(c,[...(d=i.get(c))!=null?d:[],...l]);},s=u=>{var a,l;return [...(a=u.show)!=null?a:[],...(l=u.showAny)!=null?l:[]].map(d=>d.field)};for(let{field:u}of e)r([u.key],s(u));for(let u of (o=t.steps)!=null?o:[])r(u.fields.map(a=>a.key),s(u));return i}function Oe(t){var i;let e=new Map,n=[];for(let r of t.keys()){if(e.has(r))continue;e.set(r,true);let s=[[r,0]];for(;s.length>0;){let o=s[s.length-1],u=(i=t.get(o[0]))==null?void 0:i[o[1]++];if(u===void 0)e.set(o[0],false),s.pop();else if(e.get(u)){let a=s.map(([l])=>l);n.push([...a.slice(a.indexOf(u)),u]);}else e.has(u)||(e.set(u,true),s.push([u,0]));}}return n}function Ae(t){return Oe(Ve(t)).map(e=>p("condition-cycle",t.keys.get(e[0]).path,`show conditions form a cycle: ${e.join(" -> ")}`,"Remove one of the conditions in the cycle"))}function Me({definition:t}){var i;let e=(i=t.steps)!=null?i:[],n=[];return e.forEach((r,s)=>{var u,a,l;let o=new Set(((u=r.routes)!=null?u:[]).map(d=>d.to).filter(d=>d!==null));for(let d of o){let c=e.findIndex(F=>F.id===d),m=e[c+1],S=(l=(a=e[c])==null?void 0:a.routes)==null?void 0:l.some(F=>{var G,v;return !((G=F.show)!=null&&G.length)&&!((v=F.showAny)!=null&&v.length)});!m||!o.has(m.id)||S||n.push(h("route-fallthrough",`/steps/${c}`,`branch "${d}" from "${r.id}" continues into the sibling branch "${m.id}"`,`Add an unconditional route on "${d}" to the step where the branches meet`));}r.skip&&(r.next===false||!e[1])&&n.push(h("skip-unreachable",`/steps/${s}/skip`,`step "${r.id}" has "skip" but no Continue button or later step`,'Remove "skip", or remove "next": false'));}),n}function At(t){return [...Ae(t),...Me(t)]}var T=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Le={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 Mt(t,e,n){return Object.entries(e).flatMap(([i,r])=>{let[s,o]=Le[r];return t[i]===void 0||s(t[i])?[]:[p("invalid-type",`${n}/${B(i)}`,`"${i}" must be ${o}`)]})}function w(t,e,n,i,r=false){return t==null&&!r?[]:Array.isArray(t)?t.flatMap((s,o)=>T(s)?i(s,`${e}/${o}`):[p("invalid-type",`${e}/${o}`,`must be ${n}`)]):[p("invalid-type",e,"must be an array",r?"Use [] when there is nothing to list":void 0)]}function N(t,e,n){return typeof t[e]=="string"?[]:[p("missing-property",`${n}/${e}`,`"${e}" must be a string`)]}var ht=(t,e)=>Mt(t,{field:"string",eq:"scalar",neq:"scalar",in:"list",notIn:"list",notEmpty:"boolean",gt:"number",gte:"number",lt:"number",lte:"number"},e);function gt(t,e){return [...w(t.show,`${e}/show`,"a condition object",ht),...w(t.showAny,`${e}/showAny`,"a condition object",ht)]}function yt(t,e){return T(t)?w(t.disabled,`${e}/disabled`,"a condition object",ht):[]}var Ne=(t,e)=>N(t,"value",e),Te={minLength:"number",maxLength:"number",min:"number",max:"number",pattern:"string",matchField:"string",validator:"string"};function je(t,e){return t===void 0?[]:T(t)?Mt(t,Te,e):[p("invalid-type",e,"must be an object of validation rules")]}function Pe(t,e){return t===void 0||Array.isArray(t)&&t.every(i=>typeof i=="string")?[]:[p("invalid-type",e,"must be an array of field keys")]}var Lt=(t,e)=>[...N(t,"key",e),...N(t,"type",e),...gt(t,e),...w(t.options,`${e}/options`,"an option object",Ne),...je(t.validation,`${e}/validation`),...Pe(t.optionsDependsOn,`${e}/optionsDependsOn`)],_e=(t,e)=>[...t.to===null||typeof t.to=="string"?[]:[p("missing-property",`${e}/to`,'"to" must be a step id or null')],...gt(t,e)],Ke=(t,e)=>[...N(t,"id",e),...w(t.fields,`${e}/fields`,"a field object",Lt,true),...gt(t,e),...w(t.routes,`${e}/routes`,"a route object",_e),...["next","back","skip"].flatMap(n=>yt(t[n],`${e}/${n}`))];function Nt(t){return T(t)?[...w(t.fields,"/fields","a field object",Lt),...w(t.steps,"/steps","a step object",Ke),...yt(t.submit,"/submit"),...yt(t.cancel,"/cancel")]:[p("invalid-type","","the form definition must be an object")]}function Tt(t){return [...N(t,"id",""),...typeof t.title=="string"?[]:[h("missing-property","/title",'"title" must be a string',"Add a title for host UI and editors")],...T(t.submit)?[]:[p("missing-property","/submit","the submit action is missing",'Add "submit": { "label": "Submit" }')]]}var H=t=>{var e,n;return !!((e=t.show)!=null&&e.length||(n=t.showAny)!=null&&n.length)};function jt(t,e,n){var r;let i=[];for(let s of (r=t[n].routes)!=null?r:[]){let o=s.to===null?null:e.get(s.to);if(o===null&&!H(s))return i;if(!(o==null||o<=n)&&(i.push(o),!H(s)&&!H(t[o])))return i}return n+1<t.length?[...i,n+1]:i}function Pt(t){let e=new Map(t.map((n,i)=>[n.id,i]));return t.map((n,i)=>{let r=new Set,s=jt(t,e,i);for(;s.length;){let o=s.pop();r.has(o)||(r.add(o),s.push(...jt(t,e,o)),H(t[o])&&o+1<t.length&&s.push(o+1));}return r})}var Ge=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]);function qe({definition:t}){var r;let e=[],n=(r=t.steps)!=null?r:[],i=new Map;return n.forEach((s,o)=>{let u=i.get(s.id);u===void 0?i.set(s.id,o):e.push(p("duplicate-step-id",`/steps/${o}/id`,`step id "${s.id}" is already used by /steps/${u}`,"Give each step a unique id"));}),n.forEach((s,o)=>{var u;return ((u=s.routes)!=null?u:[]).forEach((a,l)=>{if(a.to===null)return;let d=i.get(a.to);if(d!==void 0&&d>o)return;let c=n.slice(o+1).map(F=>F.id),m=d===void 0?`"${a.to}" is not a step id`:`"${a.to}" is not a later step`,S=c.length?`${E(c)}, or null to end the form here`:"Use null to end the form here";e.push(p("route-target",`/steps/${o}/routes/${l}/to`,m,S));})}),e}function Be({definition:t,entries:e}){var s;let n=[],i=Pt((s=t.steps)!=null?s:[]),r=(o,u)=>{var a;return o.step!==u.step&&!((a=i[o.step])!=null&&a.has(u.step))};return e.forEach((o,u)=>{let{field:a,path:l}=o,d=e.slice(0,u).find(c=>c.field.key===a.key&&!r(c,o));Ge.has(a.key)?n.push(p("reserved-key",`${l}/key`,`"${a.key}" is a built-in object property name`,"Rename the field key")):d&&n.push(p("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"));}),n}function _t(t){var i,r;let{definition:e}=t;return [...!!((i=e.fields)!=null&&i.length)&&!!((r=e.steps)!=null&&r.length)?[p("fields-and-steps","",'the definition has both "fields" and "steps"','Move the top-level fields into a step, or remove "steps"')]:[],...qe(t),...Be(t)]}function Ue(t){return [...t.filter(D),...t.filter(e=>!D(e))]}function j(t,e={}){let n=Nt(t);if(n.length)return n;let i=Rt(t,e.validators);return Ue([...Tt(t),..._t(i),...Dt(i),...Ot(i),...At(i)])}function Y(t,e){let n=j(t,e).filter(D);if(n.length)throw new k(n);return t}function J(t){var e,n;return [...(e=t.show)!=null?e:[],...(n=t.showAny)!=null?n:[]].map(i=>i.field)}function z(t){var e,n;return (e=t.steps)!=null&&e.length?t.steps.flatMap(i=>i.fields):(n=t.fields)!=null?n:[]}function V(t,e){let n={};for(let i of t)i.defaultValue!==void 0&&(n[i.key]=i.defaultValue);return Object.assign(n,e)}function I(t,e){let n=new Set([...Object.keys(t),...Object.keys(e)]);return new Set([...n].filter(i=>!Object.is(t[i],e[i])))}var bt=class extends Error{constructor(n,i){super(`The action completed, but ${n} failed: ${i instanceof Error?i.message:String(i)}`);this.phase=n;this.committed=true;this.name="FormLifecycleError",this.cause=i;}};async function W(t,e){try{await e();}catch(n){throw new bt(t,n)}}function Kt(t){return t.visibleSteps.map(e=>e.id).join(`
5
+ `)}function P(t,e){let n=Kt(t);return ()=>Kt(t)!==n||Object.keys(e).some(i=>e[i]!==void 0&&!Object.is(t.values[i],e[i]))}var y={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 x(t,e){var n,i;switch(t){case "required":return "This field is required";case "minLength":return `Must be at least ${e==null?void 0:e.min} ${(n=e==null?void 0:e.unit)!=null?n:"characters"}`;case "maxLength":return `Must be at most ${e==null?void 0:e.max} ${(i=e==null?void 0:e.unit)!=null?i:"characters"}`;case "min":return `Must be at least ${e==null?void 0:e.min}`;case "max":return `Must be at most ${e==null?void 0:e.max}`;case "pattern":return "Invalid format";case "matchField":return "Fields must match";default:return "Invalid value"}}function g(t,e){var i,r;let n=s=>dt(s,e);return ((i=t.show)!=null?i:[]).every(n)&&(!((r=t.showAny)!=null&&r.length)||t.showAny.some(n))}var St=new Set(["checkbox","switch"]),He=new Set(["text","email","phone","number","password","select","autocomplete","multiselect","checkbox","radio","switch","date","datetime","textarea"]),_=1e4,Ye=254,Je=1e3,ze=/^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/,We=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,Gt="\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",Xe=new RegExp(`^${Gt}$`),Qe=new RegExp(`^${Gt}T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,3})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)?$`),Ze=new Set(["text","phone","password","textarea","autocomplete"]),tn=new Map([["email",[ze,y.email,Ye]],["date",[Xe,y.date,_]],["datetime",[Qe,y.datetime,_]]]);function qt(t,e){if(t.type!=="number"||typeof e!="string"||!We.test(e))return e;let n=Number(e);return Number.isFinite(n)?n:e}function Bt(t,e){return !t.options||t.options.some(n=>n.value===e)}function Ut(t,e){var i,r,s,o;let n=Math.min(_,(r=(i=t.validation)==null?void 0:i.maxLength)!=null?r:_);return e.length<=n?null:(o=(s=t.validation)==null?void 0:s.maxLengthMessage)!=null?o:x("maxLength",{max:n})}function en(t,e){var i,r;return Array.isArray(e)?e.length>((r=(i=t.options)==null?void 0:i.length)!=null?r:Je)?y.option:e.every(s=>typeof s=="string"&&s.length<=_&&Bt(t,s))?null:y.option:y.options}function X(t,e,n){return typeof e=="string"?Ut(t,e):n}function nn(t,e,[n,i,r]){var s;return typeof e!="string"?i:(s=Ut(t,e))!=null?s:e.length<=r&&n.test(e)?null:i}function rn(t,e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)?null:X(t,e,y.value)}function sn(t,e){return e==null||e===""||t.type==="multiselect"&&Array.isArray(e)&&!e.length}function Ft(t,e){var i;if(sn(t,e))return null;if(St.has(t.type))return typeof e=="boolean"?null:y.boolean;if(t.type==="number")return typeof e=="number"&&Number.isFinite(e)?null:y.number;if(t.type==="multiselect")return en(t,e);if(t.type==="file")return X(t,e,y.file);let n=tn.get(t.type);return n?nn(t,e,n):t.type==="select"||t.type==="radio"?(i=X(t,e,y.option))!=null?i:Bt(t,e)?null:y.option:Ze.has(t.type)?X(t,e,y.string):rn(t,e)}function Ht(t,e){return He.has(t.type)?Ft(t.optionsFrom?M(f({},t),{options:void 0}):t,e):null}function on(t,e){return L(t)||t===false&&St.has(e.type)}function Yt(t,e,n,i){var o,u;let r=n[`min${e}`],s=n[`max${e}`];if(r!==void 0&&t<r)return (o=n[`min${e}Message`])!=null?o:x(`min${e}`,{min:r,unit:i});if(s!==void 0&&t>s)return (u=n[`max${e}Message`])!=null?u:x(`max${e}`,{max:s,unit:i})}function an(t,e){var n;if(e.pattern!==void 0)try{return new RegExp(e.pattern).test(String(t))?void 0:(n=e.patternMessage)!=null?n:x("pattern")}catch(i){return}}function O(t,e,n,i){var l,d,c,m,S;let r=(l=t.validation)!=null?l:{},s=(d=r.matchFieldMessage)!=null?d:x("matchField");if(on(e,t))return r.required?typeof r.required=="string"?r.required:x("required"):r.matchField!==void 0&&!L(n[r.matchField])?s:null;let o=Ht(t,e);if(o)return o;let u=typeof e=="string"||Array.isArray(e)?Yt(e.length,"Length",r,Array.isArray(e)?"items":void 0):typeof e=="number"?Yt(e,"",r):void 0,a=r.matchField!==void 0&&e!==n[r.matchField]?s:void 0;return ((S=(c=u!=null?u:an(e,r))!=null?c:a)!=null?S:r.validator?(m=i==null?void 0:i[r.validator])==null?void 0:m.call(i,e,n):void 0)||null}function $(t,e,n){return Q(t.fields,e,n)}function Q(t,e,n){let i={};for(let r of t){if(!g(r,e))continue;let s=O(r,e[r.key],e,n);s&&(i[r.key]=s);}return i}function Z(t,e,n=false){let i=t.errors;t.state.errors={},t.state.topLevelErrors=[];for(let[s,o]of Object.entries(e))t.visibility.isFieldVisible(s,t.values)?t.errors[s]=o:t.topLevelErrors.push(o);let r=n&&Jt(t,e);t.notify({fieldKeys:I(i,t.errors),structureChanged:r});}function Jt(t,e){let n=Object.keys(e).find(r=>t.errors[r]!==void 0),i=n&&t.isMultiStep?t.visibility.findStepIndex(n,t.values,t.currentStepIndex):null;return i===null||i===t.currentStepIndex?false:(t.state.currentStepIndex=i,true)}function zt(t,e){var i;let n=[];for(let r of t.visibility.allFields)((i=r.validation)==null?void 0:i.matchField)!==e||t.errors[r.key]===void 0||O(r,t.values[r.key],C(t),t.validators)||(delete t.errors[r.key],n.push(r.key));return n}function tt(t){let e=new Set(t.visibleSteps.flatMap(i=>i.fields.map(r=>r.key))),n=Object.keys(t.errors).filter(i=>!e.has(i));for(let i of n)delete t.errors[i];return n}function C(t){return A(t)}function un(t,e){for(let n of [...t.skipped.values()].flat())delete e[n];return e}function K(t,e=false){var s;let n=t.errors,i={};if(t.isMultiStep)for(let o of t.visibleSteps)t.skipped.has(o.id)||Object.assign(i,$(o,C(t),t.validators));else Object.assign(i,Q((s=t.definition.fields)!=null?s:[],C(t),t.validators));t.state.errors=i;let r=e&&Jt(t,i);return t.notify({fieldKeys:I(n,i),structureChanged:r}),i}function Wt(t,e){let n=t.visibility.activeField(e,t.values);if(!n)return null;let i=t.errors[e],r=O(n,t.values[e],C(t),t.validators);r?t.errors[e]=r:delete t.errors[e];let s=Object.is(i,t.errors[e])?[]:[e];return t.notify({fieldKeys:s}),r}function A(t){return un(t,f({},t.visibility.conditionValues(t.values)))}function Xt(t,e){let n=t.values,i=t.errors,r=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.state.submitting=false,t.state.values=V(t.visibility.allFields,e),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=I(n,t.values),o=new Set([...s,...I(i,t.errors),...r]);t.notify({fieldKeys:o,structureChanged:true,valuesChanged:s.size>0});}function vt(t,e){var o,u;let n=(o=t.steps)!=null?o:[],i=new Map(n.map((a,l)=>[a.id,l])),r=[],s={};for(let a=0;a<n.length;){let l=n[a];if(!g(l,s)){a++;continue}r.push(l),Object.assign(s,Zt(l,e,s));let d=(u=l.routes)==null?void 0:u.find(c=>{var m;return g(c,s)&&(c.to===null||((m=i.get(c.to))!=null?m:-1)>a&&g(n[i.get(c.to)],s))});if((d==null?void 0:d.to)===null)break;a=d?i.get(d.to):a+1;}return r}function Qt(t,e,n){var o;let i=(o=t[n])!=null?o:t[t.length-1],r=e.findIndex(u=>u.id===(i==null?void 0:i.id));if(r!==-1)return r;let s=new Map(e.map((u,a)=>[u.id,a]));for(let u=Math.min(n-1,t.length-1);u>=0;u--){let a=s.get(t[u].id);if(a!==void 0)return a}return 0}function Zt(t,e,n){let i=f({},n);for(let s of t.fields)i[s.key]=e[s.key];let r={};for(let s of t.fields)g(s,i)&&e[s.key]!==void 0&&(r[s.key]=e[s.key]);return r}var et=class{constructor(e){this.definition=e;this.source=null;this.activeStepList=[];this.activeValueMap={};}invalidate(){this.source=null;}steps(e){return this.refresh(e),this.activeStepList}values(e){return this.refresh(e),this.activeValueMap}refresh(e){var r,s;if(this.source===e)return;this.source=e,this.activeStepList=vt(this.definition,e);let n={},i=(r=this.definition.steps)!=null&&r.length?this.activeStepList:[{fields:(s=this.definition.fields)!=null?s:[]}];for(let o of i)Object.assign(n,Zt(o,e,n));this.activeValueMap=n;}};function te(t){var i,r;let e=(r=(i=t.currentStep)==null?void 0:i.fields)!=null?r:[],n=f({},t.values);for(let{key:s}of e)delete n[s];return Object.assign(n,V(e))}function kt(t){return vt(t.definition,te(t))[t.currentStepIndex+1]}function nt(t){let e=t.currentStep,n=e.fields.map(({key:r})=>r);t.state.values=te(t);for(let r of n)delete t.errors[r];t.skipped.set(e.id,n),t.visibility.reconcileHidden(t.values,t.errors),t.visibility.markChanged(true,true);let i=tt(t);return t.notify({fieldKeys:[...n,...i],structureChanged:true,valuesChanged:true}),n}function it(t){let e=t.currentStep;e&&t.skipped.delete(e.id);}function ee(t,e){return t.state.currentStepIndex=e,t.notify({structureChanged:true}),nt(t)}async function rt(t,e,n=false){if(t.submitting||t.stepValidating)return false;n||it(t);let i=f({},t.lifecycle),r=false,s=t.validationEpoch,o=++t.operationEpoch,u=A(t),a=P(t,u),l=()=>s!==t.validationEpoch||o!==t.operationEpoch||a();t.state.submitting=true,t.notify();try{if(l()||Object.keys(K(t,!0)).length>0||l())return !1;if(i.onBeforeSubmit){let c=await i.onBeforeSubmit(u);if(l()||c===!1)return !1}if(l())return !1;if(i.onBeforeSubmit){if(Object.keys(K(t,!0)).length>0||l())return !1;u=A(t);}r=!0;let d=[...t.skipped.keys()];return await e(u,[...d]),o!==t.operationEpoch||await W("afterSubmit",()=>{var c;return (c=i.onAfterSubmit)==null?void 0:c.call(i,u,d)}),!0}catch(d){if(!r&&l())return false;throw d}finally{o===t.operationEpoch&&(t.state.submitting=false,t.notify());}}function ne(t){let e=t.currentStep;if(!e)return true;let n=$(e,C(t),t.validators);if(Object.keys(n).length===0)return false;let i=f({},t.errors);return Object.assign(t.errors,n),t.notify({fieldKeys:I(i,t.errors)}),true}function ie(t,e){t.validationEpoch++,t.state.currentStepIndex=e,t.notify({structureChanged:true});}async function re(t,e){var l;if(!t.isMultiStep||t.stepValidating||t.submitting||!((l=t.currentStep)!=null&&l.skip))return false;if(kt(t))return st(t,"next","skip");let n=t.currentStep;if(!e||!n)return false;let i=t.values,r=f({},t.errors),s=false,o=nt(t),u=t.values,a=P(t,f({},u));try{return await rt(t,async(d,c)=>{await e(d,c),s=!0;},!0)}finally{!s&&t.values===u&&!a()&&(t.state.values=i,t.state.errors=f(f({},r),t.errors),t.skipped.delete(n.id),t.notify({fieldKeys:o,structureChanged:true,valuesChanged:true}));}}async function st(t,e,n=e){let i=n==="skip";if(!t.isMultiStep||t.stepValidating||t.submitting||!i&&(e==="next"?t.isLastStep:t.isFirstStep))return false;let r=t.currentStep,s=e==="next"&&!i;if(s&&it(t),s&&ne(t))return false;let o=f({},t.lifecycle),u=t.onStepValidate,a=false,d=t.currentStepIndex+(e==="next"?1:-1),c=i?kt(t):t.visibleSteps[d];if(!c)return false;let m={fromStepId:r.id,toStepId:c.id,reason:n,values:f({},C(t))},S=t.validationEpoch,F=++t.operationEpoch,G=P(t,m.values),v=()=>{var b;return S!==t.validationEpoch||F!==t.operationEpoch||((b=t.currentStep)==null?void 0:b.id)!==r.id||G()};t.state.stepValidating=true,t.notify();try{if(v())return !1;if(s&&u){let b=await u(r.id,m.values);if(v())return !1;if(b&&Object.keys(b).length>0)return Z(t,b),!1}if(o.onBeforeStepChange){let b=await o.onBeforeStepChange(m);if(v()||b===!1)return !1}return v()||s&&ne(t)?!1:(a=!0,i&&nt(t),ie(t,d),await W("afterStepChange",()=>{var b;return (b=o.onAfterStepChange)==null?void 0:b.call(o,m)}),!0)}catch(b){if(!a&&v())return false;throw b}finally{F===t.operationEpoch&&(t.state.stepValidating=false,t.notify());}}function se(t,e){if(!t.isMultiStep)return;let n=t.visibility.findStepIndex(e,t.values,t.currentStepIndex);n===t.currentStepIndex?t.notify():n!==null&&ie(t,n);}var ot=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,n){var r;let i=(r=this.fieldListeners.get(e))!=null?r:new Set;return i.add(n),this.fieldListeners.set(e,i),()=>{i.delete(n),i.size===0&&this.fieldListeners.delete(e);}}getFieldSnapshot(e){var n;return (n=this.fieldVersions.get(e))!=null?n:0}subscribeStructure(e){return this.structureListeners.add(e),()=>this.structureListeners.delete(e)}getStructureSnapshot(){return this.structureVersion}notify({fieldKeys:e=[],structureChanged:n=false}={}){for(let i of new Set(e))this.notifyField(i);n&&this.notifyStructure(),this.version++;for(let i of this.listeners)i();}notifyField(e){var n,i;this.fieldVersions.set(e,((n=this.fieldVersions.get(e))!=null?n:0)+1);for(let r of (i=this.fieldListeners.get(e))!=null?i:[])r();}notifyStructure(){this.structureVersion++;for(let e of this.structureListeners)e();}};function ln(){try{return process.env.NODE_ENV==="production"}catch(t){return false}}function oe(t){ln()||console.warn(`[formhaus] ${t.message}`);}function wt(t,e){var n;for(let i of J(t)){let r=(n=e.get(i))!=null?n:new Set;r.add(t),e.set(i,r);}}var at=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};var n,i;this.allFields=z(e);for(let r of this.allFields)this.fieldsByKey.set(r.key,[...(n=this.fieldsByKey.get(r.key))!=null?n:[],r]);this.path=new et(e);for(let r of (i=e.steps)!=null?i:[])for(let s of r.fields)this.stepOfField.set(s,r);this.buildIndexes();}markChanged(e,n){(e||n)&&this.path.invalidate(),e?(this.visibilityDirty=true,this.canGoNextDirty=true):n&&(this.canGoNextDirty=true);}state(e,n){return this.recomputeVisibility(e,n),this.cache}getCanGoNext(e,n,i){if(this.recomputeVisibility(e,n),!this.canGoNextDirty)return this.cache.canGoNext;this.canGoNextDirty=false;let r=this.cache.currentStep,s=r?$(r,this.conditionValues(e),i):{};return this.cache.canGoNext=this.isMultiStep&&Object.keys(s).length===0,this.cache.canGoNext}findStepIndex(e,n,i){let s=this.state(n,i).visibleSteps.findIndex(o=>o.fields.some(u=>u.key===e));return s===-1?null:s}affectsStructure(e,n){return this.routeFields.has(e)||this.fieldDependents.has(e)||this.stepDependents.has(e)||n.size>0}cascadeHiddenFields(e,n){return this.reconcileHidden(e,n)}reconcileHidden(e,n){this.path.invalidate();let i=new Set([...this.fieldDependents.keys(),...this.stepDependents.keys()]);return this.drainQueue(i,e,n)}drainQueue(e,n,i){let r=[...e],s=new Set(r),o=new Set,u=a=>{delete n[a],delete i[a],this.path.invalidate(),o.add(a),!s.has(a)&&(s.add(a),r.push(a));};for(let a=0;a<r.length;a++){let l=r[a];s.delete(l),this.clearHiddenFields(this.fieldDependents.get(l),n,i,u),this.clearHiddenSteps(this.stepDependents.get(l),n,i,u);}return o}activeField(e,n){var i;return (i=this.fieldsByKey.get(e))==null?void 0:i.find(r=>this.onPath(r,n)&&g(r,this.conditionValues(n)))}isFieldVisible(e,n){return this.activeField(e,n)!==void 0}conditionValues(e){return this.path.values(e)}onPath(e,n){let i=this.stepOfField.get(e);return !i||this.path.steps(n).includes(i)}get isMultiStep(){var e;return ((e=this.definition.steps)!=null?e:[]).length>0}buildIndexes(){var e,n;for(let i of this.allFields)wt(i,this.fieldDependents);for(let i of (e=this.definition.steps)!=null?e:[]){wt(i,this.stepDependents);for(let r of (n=i.routes)!=null?n:[])for(let s of J(r))this.routeFields.add(s);}}recomputeVisibility(e,n){var s,o,u;if(!this.visibilityDirty)return;if(this.visibilityDirty=false,!this.isMultiStep){this.cache.visibleSteps=[],this.cache.currentStep=null,this.cache.visibleFields=((s=this.definition.fields)!=null?s:[]).filter(a=>g(a,this.conditionValues(e)));return}this.cache.visibleSteps=this.path.steps(e);let i=this.cache.visibleSteps;this.cache.currentStep=(u=(o=i[n])!=null?o:i[i.length-1])!=null?u:null;let r=this.cache.currentStep;this.cache.visibleFields=r?r.fields.filter(a=>g(a,this.conditionValues(e))):[];}clearHiddenFields(e,n,i,r){for(let s of e!=null?e:[])this.onPath(s,n)&&(g(s,this.conditionValues(n))||n[s.key]===void 0&&i[s.key]===void 0||r(s.key));}clearHiddenSteps(e,n,i,r){for(let s of e!=null?e:[])if(!g(s,this.conditionValues(n)))for(let o of s.fields)n[o.key]===void 0&&i[o.key]===void 0||r(o.key);}};var ut=class{constructor(e,n,i){this.definition=e;this.skipped=new Map;this.validationEpoch=0;this.operationEpoch=0;this.subscriptions=new ot;var a,l;this.lifecycle=i!=null?i:{},this.validators=(a=i==null?void 0:i.validators)!=null?a:{};let r=j(e,{validators:this.validators}),s=r.filter(D);if(s.length)throw new k(s);let o=(l=this.lifecycle.onWarning)!=null?l:oe;for(let d of r)o(d);this.visibility=new at(e);let u=V(this.visibility.allFields,n);this.state={values:u,errors:{},topLevelErrors:[],currentStepIndex:0,fieldLoading:{},stepValidating:false,submitting:false},this.visibility.reconcileHidden(u,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(){var e;return ((e=this.definition.steps)!=null?e:[]).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,n){return this.subscriptions.subscribeField(e,n)}getFieldSnapshot(e){return this.subscriptions.getFieldSnapshot(e)}subscribeStructure(e){return this.subscriptions.subscribeStructure(e)}getStructureSnapshot(){return this.subscriptions.getStructureSnapshot()}setValue(e,n){let{values:i,errors:r}=this.state,s=this.isMultiStep?this.visibleSteps:null,o=!Object.is(i[e],n),u=r[e]!==void 0;i[e]=n,delete r[e];for(let[S,F]of this.skipped)o&&F.includes(e)&&this.skipped.delete(S);let a=this.visibility.cascadeHiddenFields(i,r),l=zt(this.internals,e),d=new Set([...a,...l]);(o||u)&&d.add(e);let c=o||a.size>0,m=c&&this.visibility.affectsStructure(e,a);if(s&&m){this.visibility.markChanged(true,true),this.state.currentStepIndex=Qt(s,this.visibleSteps,this.currentStepIndex);for(let S of tt(this.internals))d.add(S);}this.notify({fieldKeys:d,structureChanged:m,valuesChanged:c});}setErrors(e){Z(this.internals,e,true);}setFieldLoading(e,n){let i=this.state.fieldLoading[e]===true;n?this.state.fieldLoading[e]=true:delete this.state.fieldLoading[e],this.notify({fieldKeys:i===n?[]:[e]});}cancelPendingActions(){this.validationEpoch++,this.operationEpoch++,this.state.stepValidating=false,this.state.submitting=false,this.notify();}next(){return st(this.internals,"next")}back(){return st(this.internals,"back")}skip(e){return re(this.internals,e)}submit(e){return rt(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}validate(){return K(this.internals)}validateField(e){return Wt(this.internals,e)}getSubmitValues(){return A(this.internals)}goToStepWithField(e){se(this.internals,e);}reset(e){Xt(this.internals,e);}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};var dn='Pass the values object as the second argument, not the request body with "values" and "skippedSteps".',cn=()=>null,lt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function fn(t,e){let n=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},i={};for(let r of t)lt(n,r.key)&&(i[r.key]=qt(r,n[r.key]));return i}function pn(t,e){let n=new Map;for(let i of t){let r=lt(e,i.key)?Ft(i,e[i.key]):null;r&&n.set(i.key,r);}return n}function mn(t,e){var r;let n=s=>s.map(o=>e.has(o.key)?M(f({},o),{validation:void 0}):o),i=(r=t.steps)==null?void 0:r.map(s=>M(f({},s),{fields:n(s.fields)}));return f(f(f({},t),t.fields&&{fields:n(t.fields)}),i&&{steps:i})}function hn(t,e={}){let n={};for(let{validation:i}of t)i!=null&&i.validator&&(n[i.validator]=cn);return f(f({},n),e)}function yn(t,e){return e===null||typeof e!="object"||!lt(e,"values")?false:!t.some(n=>n.key==="values"||n.key==="skippedSteps")}function gn(t,e){if(!Array.isArray(e))return;let n=new Set(e);for(let i=0;i<t.visibleSteps.length;i++){let r=t.visibleSteps[i];r.skip&&n.has(r.id)&&ee(t,i);}}function bn(t,e,n={}){Y(t);let i=z(t),r=fn(i,e),s=pn(i,r),o={validators:hn(i,n.validators),onWarning:()=>{}},u=new ut(mn(t,s),r,o);gn(u,n.skippedSteps);let a=u.validate(),l=u.getSubmitValues();for(let[d,c]of s)lt(l,d)&&(a[d]=c);return yn(i,e)&&(a.values=dn),{values:l,errors:a}}exports.FormDefinitionError=k;exports.checkDefinition=j;exports.parseDefinition=Y;exports.validateSubmission=bn;return exports;})({});//# sourceMappingURL=server.iife.js.map
5
6
  //# sourceMappingURL=server.iife.js.map