@formhaus/core 0.10.1 → 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.js CHANGED
@@ -1,4 +1,2 @@
1
- function T(t){return t==null||t===""||Array.isArray(t)&&!t.length}function J(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?!T(r):true}function c(t,e){let r=i=>J(i,e);return (t.show??[]).every(r)&&(!t.showAny?.length||t.showAny.some(r))}var v=c;function lt(t){return !!t.fields?.length&&!!t.steps?.length}function g(t){return !!t.steps?.some(e=>e.routes?.length)}function m(t){return [...t.show??[],...t.showAny??[]].map(e=>e.field)}function y(t){return t.steps?.length?t.steps.flatMap(e=>e.fields):t.fields??[]}function k(t,e){let r={};for(let i of t)i.defaultValue!==void 0&&(r[i.key]=i.defaultValue);return Object.assign(r,e)}function F(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 x(t){let e=t.steps??[],r=lt(t)?['FormEngine rejects a definition with both "fields" and "steps".']:[],i=new Map,n=new Map;e.forEach((s,a)=>{i.has(s.id)&&r.push(`Duplicate step id "${s.id}".`),i.set(s.id,a);for(let o of s.fields)n.set(o.key,a);});for(let{key:s}of y(t))(s in Object.prototype||s==="prototype")&&r.push(`Reserved field key "${s}".`);return g(t)&&e.forEach((s,a)=>{for(let o of s.routes??[]){let l=o.to===null?null:i.get(o.to);(l===void 0||l!==null&&l<=a)&&r.push(`Invalid route from "${s.id}" to "${o.to}": targets must be later steps or null.`);for(let u of m(o))(n.get(u)??1/0)<=a||r.push(`Invalid route on "${s.id}": condition field "${u}" must belong to this or an earlier step.`);}}),r}function ut(t){let e=t.steps??[],r=[];for(let i of e){let n=new Set((i.routes??[]).map(s=>s.to).filter(s=>s!==null));for(let s of n){let a=e.findIndex(u=>u.id===s),o=e[a+1],l=e[a]?.routes?.some(u=>!u.show?.length&&!u.showAny?.length);o&&n.has(o.id)&&!l&&r.push(`Route branch "${s}" from "${i.id}" continues into sibling branch "${o.id}". Add an unconditional route where it should continue.`);}}return r}function U(t,e){let r=t.steps??[];if(!g(t))return r.filter(a=>v(a,e));let i=new Map(r.map((a,o)=>[a.id,o])),n=[],s={};for(let a=0;a<r.length;){let o=r[a];if(!v(o,s)){a++;continue}n.push(o),Object.assign(s,ct(o,e,s));let l=o.routes?.find(u=>c(u,s)&&(u.to===null||(i.get(u.to)??-1)>a&&v(r[i.get(u.to)],s)));if(l?.to===null)break;a=l?i.get(l.to):a+1;}return n}function dt(t,e,r){let i=t[r]??t[t.length-1],n=e.findIndex(a=>a.id===i?.id);if(n!==-1)return n;let s=new Map(e.map((a,o)=>[a.id,o]));for(let a=Math.min(r-1,t.length-1);a>=0;a--){let o=s.get(t[a].id);if(o!==void 0)return o}return 0}function ct(t,e,r){let i={...r};for(let s of t.fields)i[s.key]=e[s.key];let n={};for(let s of t.fields)c(s,i)&&e[s.key]!==void 0&&(n[s.key]=e[s.key]);return n}var N=class{constructor(e){this.definition=e;this.source=null;this.activeStepList=[];this.activeValueMap={};this.enabled=g(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=U(this.definition,e);let r={};for(let i of this.activeStepList)Object.assign(r,ct(i,e,r));this.activeValueMap=r;}};function pt(t){let e=[],r=new Map,i=y(t),n=new Set;for(let{key:o}of i)n.has(o)&&e.push(`Duplicate field key "${o}" \u2014 fields will share state and overwrite each other`),n.add(o);let s=(o,l,u,d)=>{let h=m(u);for(let f of h)typeof f!="string"?e.push(`${o} "${l}" has a show condition without a "field" name`):n.has(f)||e.push(`${o} "${l}" has show condition referencing non-existent field "${f}"`);if(h.length)for(let f of d)r.set(f,[...r.get(f)??[],...h]);};for(let o of i){s("Field",o.key,o,[o.key]);let l=o.validation?.pattern;if(l!==void 0)try{new RegExp(l);}catch{e.push(`Field "${o.key}" has invalid regex pattern: "${l}"`);}}let a=new Set;for(let o of t.steps??[]){s("Step",o.id,o,o.fields.map(l=>l.key));for(let l of m(o))g(t)&&n.has(l)&&!a.has(l)&&e.push(`Step "${o.id}" condition field "${l}" must belong to an earlier step.`);for(let{key:l}of o.fields)a.add(l);o.skip&&(o.next===false||!t.steps[1])&&e.push(`Step "${o.id}" has "skip" but no Next button or later step.`);}return {graph:r,warnings:e}}var K=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function E(t,e,r,i=false){return t==null&&!i?[]:Array.isArray(t)?t.flatMap((n,s)=>r(n,`${e}[${s}]`)):[`${e} must be an array.`]}function P(t,e){return (r,i)=>K(r)?e(r,i):[`${i} must be ${t}.`]}var ft=P("a condition object",()=>[]);function tt(t,e){return [...E(t.show,`${e}.show`,ft),...E(t.showAny,`${e}.showAny`,ft)]}var ht=P("a field object",tt),Nt=P("a route object",tt),Kt=P("a step object",(t,e)=>[...E(t.fields,`${e}.fields`,ht,true),...tt(t,e),...E(t.routes,`${e}.routes`,Nt)]);function R(t){return K(t)?[...E(t.fields,"fields",ht),...E(t.steps,"steps",Kt)]:["Form definition must be an object."]}function Pt(t){let e=new Map,r=[];for(let i of t.keys()){if(e.has(i))continue;e.set(i,true);let n=[[i,0]];for(;n.length>0;){let s=n[n.length-1],a=t.get(s[0])?.[s[1]++];if(a===void 0)e.set(s[0],false),n.pop();else if(e.get(a)){let o=n.map(([l])=>l);r.push([...o.slice(o.indexOf(a)),a]);}else e.has(a)||(e.set(a,true),n.push([a,0]));}}return r}function D(t){let e=R(t);if(e.length)return e;let r=t,{graph:i,warnings:n}=pt(r);K(r.submit)||n.unshift('Form definition is missing the "submit" action.');for(let s of Pt(i))n.push(`Circular show condition detected: ${s.join(" -> ")}`);return [...x(r),...n,...ut(r)]}function Bt(t){let e=R(t);if(e.length)return {errors:e,warnings:[]};let r=t,i=x(r),n=new Set(i);return {errors:i,warnings:D(r).filter(s=>!n.has(s))}}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 mt(t){return t.visibleSteps.map(e=>e.id).join(`
2
- `)}function C(t,e){let r=mt(t);return ()=>mt(t)!==r||Object.keys(e).some(i=>e[i]!==void 0&&!Object.is(t.values[i],e[i]))}var p={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 b(t,e){switch(t){case "required":return "This field is required";case "minLength":return `Must be at least ${e?.min} ${e?.unit??"characters"}`;case "maxLength":return `Must be at most ${e?.max} ${e?.unit??"characters"}`;case "min":return `Must be at least ${e?.min}`;case "max":return `Must be at most ${e?.max}`;case "pattern":return "Invalid format";case "matchField":return "Fields must match";default:return "Invalid value"}}var rt=new Set(["checkbox","switch"]);function Gt(t,e){return T(t)||t===false&&rt.has(e.type)}function gt(t,e,r,i){let n=r[`min${e}`],s=r[`max${e}`];if(n!==void 0&&t<n)return r[`min${e}Message`]??b(`min${e}`,{min:n,unit:i});if(s!==void 0&&t>s)return r[`max${e}Message`]??b(`max${e}`,{max:s,unit:i})}function qt(t,e){if(e.pattern!==void 0)try{return new RegExp(e.pattern).test(String(t))?void 0:e.patternMessage??b("pattern")}catch{return}}function I(t,e,r,i){let n=t.validation;if(!n)return null;if(Gt(e,t))return n.required?typeof n.required=="string"?n.required:b("required"):null;let s=typeof e=="string"||Array.isArray(e)?gt(e.length,"Length",n,Array.isArray(e)?"items":void 0):typeof e=="number"?gt(e,"",n):void 0,a=n.matchField!==void 0&&e!==r[n.matchField]?n.matchFieldMessage??b("matchField"):void 0;return (s??qt(e,n)??a??(n.validator?i?.[n.validator]?.(e,r):void 0))||null}function w(t,e,r){return G(t.fields,e,r)}function G(t,e,r){let i={};for(let n of t){if(!c(n,e))continue;let s=I(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[s,a]of Object.entries(e))t.visibility.isFieldVisible(s,t.values)?t.errors[s]=a:t.topLevelErrors.push(a);let n=r&&yt(t,e);t.notify({fieldKeys:F(i,t.errors),structureChanged:n});}function yt(t,e){let r=Object.keys(e).find(n=>t.errors[n]!==void 0),i=r&&t.isMultiStep?t.visibility.findStepIndex(r,t.values,t.currentStepIndex):null;return i===null||i===t.currentStepIndex?false:(t.currentStepIndex=i,true)}function bt(t,e){let r=[];for(let i of t.visibility.allFields)i.validation?.matchField!==e||t.errors[i.key]===void 0||I(i,t.values[i.key],V(t),t.validators)||(delete t.errors[i.key],r.push(i.key));return r}function St(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 V(t){return g(t.definition)?M(t):vt(t,{...t.values})}function vt(t,e){for(let r of [...t.skipped.values()].flat())delete e[r];return e}function O(t,e=false){let r=t.errors,i={};if(t.isMultiStep)for(let s of t.visibleSteps)t.skipped.has(s.id)||Object.assign(i,w(s,V(t),t.validators));else Object.assign(i,G(t.definition.fields??[],t.values,t.validators));t.errors=i;let n=e&&yt(t,i);return t.notify({fieldKeys:F(r,i),structureChanged:n}),i}function Ft(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=I(r,t.values[e],V(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 M(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 vt(t,e)}function wt(t,e){let r=t.values,i=t.errors,n=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.submitting=false,t.values=k(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=F(r,t.values),a=new Set([...s,...F(i,t.errors),...n]);t.notify({fieldKeys:a,structureChanged:true,valuesChanged:s.size>0});}function kt(t){let e=t.currentStep?.fields??[],r={...t.values};for(let{key:i}of e)delete r[i];return Object.assign(r,k(e))}function H(t){return U(t.definition,kt(t))[t.currentStepIndex+1]}function $(t){let e=t.currentStep,r=e.fields.map(({key:i})=>i);t.values=kt(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 L(t){let e=t.currentStep;e&&t.skipped.delete(e.id);}function xt(t,e){return t.currentStepIndex=e,t.notify({structureChanged:true}),$(t)}async function _(t,e,r=false){if(t.submitting||t.stepValidating)return false;r||L(t);let i={...t.lifecycle},n=false,s=t.validationEpoch,a=++t.operationEpoch,o=M(t),l=C(t,o),u=()=>s!==t.validationEpoch||a!==t.operationEpoch||l();t.submitting=true,t.notify();try{if(u()||Object.keys(O(t,!0)).length>0||u())return !1;if(i.onBeforeSubmit){let d=await i.onBeforeSubmit(o);if(u()||d===!1)return !1}if(u())return !1;if(i.onBeforeSubmit){if(Object.keys(O(t,!0)).length>0||u())return !1;o=M(t);}return n=!0,await e(o,[...t.skipped.keys()]),a!==t.operationEpoch||await B("afterSubmit",()=>i.onAfterSubmit?.(o)),!0}catch(d){if(!n&&u())return false;throw d}finally{a===t.operationEpoch&&(t.submitting=false,t.notify());}}function it(t){let e=t.currentStep;if(!e)return true;let r=w(e,V(t),t.validators);if(Object.keys(r).length===0)return false;let i={...t.errors};return Object.assign(t.errors,r),t.notify({fieldKeys:F(i,t.errors)}),true}function z(t,e){t.validationEpoch++,t.currentStepIndex=e,t.notify({structureChanged:true});}function Et(t){return t.isLastStep?false:(z(t,t.currentStepIndex+1),true)}function Rt(t){return t.isMultiStep?(L(t),!it(t)&&Et(t)):false}function It(t){return !t.isMultiStep||!H(t)?false:($(t),Et(t))}async function Vt(t,e){if(!t.isMultiStep||t.stepValidating||t.submitting)return false;if(H(t))return W(t,"next","skip");let r=t.currentStep;if(!e||!r)return false;let i=t.values,n={...t.errors},s=false,a=$(t),o=t.values,l=C(t,{...o});try{return await _(t,async(u,d)=>{await e(u,d),s=!0;},!0)}finally{!s&&t.values===o&&!l()&&(t.values=i,t.errors={...n,...t.errors},t.skipped.delete(r.id),t.notify({fieldKeys:a,structureChanged:true,valuesChanged:true}));}}async function W(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&&L(t),s&&it(t))return false;let a={...t.lifecycle},o=t.onStepValidate,l=false,d=t.currentStepIndex+(e==="next"?1:-1),h=i?H(t):t.visibleSteps[d];if(!h)return false;let f={fromStepId:n.id,toStepId:h.id,direction:e,reason:r,values:{...V(t)}},jt=t.validationEpoch,at=++t.operationEpoch,Tt=C(t,f.values),A=()=>jt!==t.validationEpoch||at!==t.operationEpoch||t.currentStep?.id!==n.id||Tt();t.stepValidating=true,t.notify();try{if(A())return !1;if(s&&o){let S=await o(n.id,f.values);if(A())return !1;if(S&&Object.keys(S).length>0)return q(t,S),!1}if(a.onBeforeStepChange){let S=await a.onBeforeStepChange(f);if(A()||S===!1)return !1}return A()||s&&it(t)?!1:(l=!0,i&&$(t),z(t,d),await B("afterStepChange",()=>a.onAfterStepChange?.(f)),!0)}catch(S){if(!l&&A())return false;throw S}finally{at===t.operationEpoch&&(t.stepValidating=false,t.notify());}}function Mt(t){t.isMultiStep&&!t.isFirstStep&&z(t,t.currentStepIndex-1);}function At(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 Y=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){let i=this.fieldListeners.get(e)??new Set;return i.add(r),this.fieldListeners.set(e,i),()=>{i.delete(r),i.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: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){this.fieldVersions.set(e,(this.fieldVersions.get(e)??0)+1);for(let r of this.fieldListeners.get(e)??[])r();}notifyStructure(){this.structureVersion++;for(let e of this.structureListeners)e();}};function nt(t,e){for(let r of m(t)){let i=e.get(r)??new Set;i.add(t),e.set(r,i);}}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};this.allFields=y(e),this.fieldByKey=new Map(this.allFields.map(r=>[r.key,r])),this.path=new N(e);for(let r of e.steps??[])for(let i of r.fields)this.stepByFieldKey.set(i.key,r);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?w(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(a=>a.fields.some(o=>o.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),a=new Set,o=l=>{delete r[l],delete i[l],this.path.invalidate(),a.add(l),!s.has(l)&&(s.add(l),n.push(l));};for(let l=0;l<n.length;l++){let u=n[l];s.delete(u),this.clearHiddenFields(this.fieldDependents.get(u),r,o),this.clearHiddenSteps(this.stepDependents.get(u),r,o);}return a}isFieldVisible(e,r){let i=this.fieldByKey.get(e);if(!i||!c(i,this.conditionValues(r)))return false;let n=this.stepByFieldKey.get(e);return !n||this.path.steps(r).includes(n)}getVisibleFieldKeys(e,r){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(s=>s.fields):this.definition.fields??[];for(let s of n)c(s,this.conditionValues(e))&&i.add(s.key);return i}conditionValues(e){return this.hasRoutes?this.path.values(e):e}get hasRoutes(){return this.path.enabled}get isMultiStep(){return (this.definition.steps??[]).length>0}buildIndexes(){for(let e of this.allFields)nt(e,this.fieldDependents);for(let e of this.definition.steps??[]){nt(e,this.stepDependents);for(let r of e.routes??[])for(let i of m(r))this.routeFields.add(i);}}recomputeVisibility(e,r){if(!this.visibilityDirty)return;if(this.visibilityDirty=false,!this.isMultiStep){this.cache.visibleSteps=[],this.cache.currentStep=null,this.cache.visibleFields=(this.definition.fields??[]).filter(s=>c(s,this.conditionValues(e)));return}this.cache.visibleSteps=this.path.steps(e);let i=this.cache.visibleSteps;this.cache.currentStep=i[r]??i[i.length-1]??null;let n=this.cache.currentStep;this.cache.visibleFields=n?n.fields.filter(s=>c(s,this.conditionValues(e))):[];}clearHiddenFields(e,r,i){for(let n of e??[]){let s=this.stepByFieldKey.get(n.key);this.hasRoutes&&s&&!this.path.steps(r).includes(s)||c(n,this.conditionValues(r))||r[n.key]===void 0||i(n.key);}}clearHiddenSteps(e,r,i){for(let n of e??[])if(!v(n,this.conditionValues(r)))for(let s of n.fields)r[s.key]!==void 0&&i(s.key);}};var st=new WeakSet,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 Y;let n=R(e),s=n.length?n:x(e);if(s.length)throw new Error(s.join(`
3
- `));this.lifecycle=i??{},this.validators=i?.validators??{},this.visibility=new X(e),st.has(this.lifecycle)||this.warnAboutDefinition(),this.values=k(this.visibility.allFields,r),this.visibility.reconcileHidden(this.values,this.errors);}get onStepValidate(){return this.lifecycle.onStepValidate}get isMultiStep(){return (this.definition.steps??[]).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[h,f]of this.skipped)n&&f.includes(e)&&this.skipped.delete(h);let a=this.visibility.cascadeHiddenFields(e,this.values,this.errors),o=bt(this.internals,e),l=new Set([...a,...o]);(n||s)&&l.add(e);let u=n||a.size>0,d=u&&this.visibility.affectsStructure(e,a);if(i&&d){this.visibility.markChanged(true,true),this.currentStepIndex=dt(i,this.visibleSteps,this.currentStepIndex);for(let h of St(this.internals))l.add(h);}this.notify({fieldKeys:l,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 Rt(this.internals)}nextStepAsync(e="next"){return W(this.internals,"next",e)}prevStepAsync(){return W(this.internals,"back")}skipStep(){return It(this.internals)}skipStepAsync(e){return Vt(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}submitAsync(e){return _(this.internals,e)}prevStep(){Mt(this.internals);}validate(){return O(this.internals)}validateField(e){return Ft(this.internals,e)}getSubmitValues(){return M(this.internals)}goToStepWithField(e){At(this.internals,e);}reset(e){wt(this.internals,e);}warnAboutDefinition(){let e=D(this.definition);for(let{key:r,validation:i}of this.visibility.allFields){let n=i?.validator;n&&!this.validators[n]&&e.push(`Field "${r}" references unknown validator "${n}".`);}for(let r of e)console.warn(`[FormEngine] ${r}`);}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};var j=1e4,Ht=254,_t=1e3,zt=/^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/,Wt=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,Dt="\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",Yt=new RegExp(`^${Dt}$`),Xt=new RegExp(`^${Dt}T(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d{1,3})?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d)?$`),Qt=new Set(["text","phone","password","textarea","autocomplete"]),Zt=new Map([["email",[zt,p.email,Ht]],["date",[Yt,p.date,j]],["datetime",[Xt,p.datetime,j]]]);function Ct(t,e){if(t.type!=="number"||typeof e!="string"||!Wt.test(e))return e;let r=Number(e);return Number.isFinite(r)?r:e}function Ot(t,e){return !t.options||t.options.some(r=>r.value===e)}function $t(t,e){let r=Math.min(j,t.validation?.maxLength??j);return e.length<=r?null:t.validation?.maxLengthMessage??b("maxLength",{max:r})}function Jt(t,e){return Array.isArray(e)?e.length>(t.options?.length??_t)?p.option:e.every(i=>typeof i=="string"&&i.length<=j&&Ot(t,i))?null:p.option:p.options}function Z(t,e,r){return typeof e=="string"?$t(t,e):r}function Ut(t,e,[r,i,n]){return typeof e!="string"?i:$t(t,e)??(e.length<=n&&r.test(e)?null:i)}function te(t,e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)?null:Z(t,e,p.value)}function ee(t,e){return e==null||e===""||t.type==="multiselect"&&Array.isArray(e)&&!e.length}function Lt(t,e){if(ee(t,e))return null;if(rt.has(t.type))return typeof e=="boolean"?null:p.boolean;if(t.type==="number")return typeof e=="number"&&Number.isFinite(e)?null:p.number;if(t.type==="multiselect")return Jt(t,e);if(t.type==="file")return Z(t,e,p.file);let r=Zt.get(t.type);return r?Ut(t,e,r):t.type==="select"||t.type==="radio"?Z(t,e,p.option)??(Ot(t,e)?null:p.option):Qt.has(t.type)?Z(t,e,p.string):te(t,e)}var re=()=>null,ot=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);function ie(t,e){let r=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{},i={};for(let n of t)ot(r,n.key)&&(i[n.key]=Ct(n,r[n.key]));return i}function ne(t,e){let r=new Map;for(let i of t){let n=ot(e,i.key)?Lt(i,e[i.key]):null;n&&r.set(i.key,n);}return r}function se(t,e){let r=n=>n.map(s=>e.has(s.key)?{...s,validation:void 0}:s),i=t.steps?.map(n=>({...n,fields:r(n.fields)}));return {...t,...t.fields&&{fields:r(t.fields)},...i&&{steps:i}}}function oe(t){let e={};for(let{validation:r}of t)r?.validator&&(e[r.validator]=re);return e}function ae(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)&&xt(t,i);}}function le(t,e,r={}){let i=y(t),n=ie(i,e),s=ne(i,n),a={validators:oe(i)};st.add(a);let o=new Q(se(t,s),n,a);ae(o,r.skippedSteps);let l=o.validate(),u=o.getSubmitValues();for(let[d,h]of s)ot(u,d)&&(l[d]=h);return {values:u,errors:l}}export{Bt as checkDefinition,le as validateSubmission};//# sourceMappingURL=server.js.map
1
+ import {c,e}from'./chunk-OMINRKEL.js';export{a as FormDefinitionError,b as checkDefinition,c as parseDefinition}from'./chunk-OMINRKEL.js';import {d,i,j,w as w$1}from'./chunk-BXI5P7PF.js';var w='Pass the values object as the second argument, not the request body with "values" and "skippedSteps".',S=()=>null,s=(e,n)=>Object.prototype.hasOwnProperty.call(e,n);function R(e,n){let t=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{},o={};for(let r of e)s(t,r.key)&&(o[r.key]=i(r,t[r.key]));return o}function h(e,n){let t=new Map;for(let o of e){let r=s(n,o.key)?j(o,n[o.key]):null;r&&t.set(o.key,r);}return t}function D(e,n){let t=r=>r.map(i=>n.has(i.key)?{...i,validation:void 0}:i),o=e.steps?.map(r=>({...r,fields:t(r.fields)}));return {...e,...e.fields&&{fields:t(e.fields)},...o&&{steps:o}}}function V(e,n={}){let t={};for(let{validation:o}of e)o?.validator&&(t[o.validator]=S);return {...t,...n}}function E(e,n){return n===null||typeof n!="object"||!s(n,"values")?false:!e.some(t=>t.key==="values"||t.key==="skippedSteps")}function O(e,n){if(!Array.isArray(n))return;let t=new Set(n);for(let o=0;o<e.visibleSteps.length;o++){let r=e.visibleSteps[o];r.skip&&t.has(r.id)&&w$1(e,o);}}function A(e$1,n,t={}){c(e$1);let o=d(e$1),r=R(o,n),i=h(o,r),k={validators:V(o,t.validators),onWarning:()=>{}},a=new e(D(e$1,i),r,k);O(a,t.skippedSteps);let l=a.validate(),p=a.getSubmitValues();for(let[c,F]of i)s(p,c)&&(l[c]=F);return E(o,n)&&(l.values=w),{values:p,errors:l}}export{A as validateSubmission};//# sourceMappingURL=server.js.map
4
2
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/visibility/evaluate-condition.ts","../src/visibility/is-visible.ts","../src/visibility/is-step-visible.ts","../src/engine/engine-utils.ts","../src/engine/step-routes.ts","../src/definition-validation/definition-analysis.ts","../src/definition-validation/shape-errors.ts","../src/definition-validation/validate-definition.ts","../src/server/check-definition.ts","../src/engine/lifecycle-error.ts","../src/engine/pending-inputs.ts","../src/validation/default-messages.ts","../src/validation/validate-field.ts","../src/validation/validate-step.ts","../src/engine/validation-state.ts","../src/engine/step-skip.ts","../src/engine/submission.ts","../src/engine/navigation.ts","../src/engine/subscriptions.ts","../src/engine/visibility-index.ts","../src/engine/visibility-state.ts","../src/engine/runtime.ts","../src/server/type-checks.ts","../src/server/validate-submission.ts"],"names":["isBlank","value","evaluateCondition","condition","values","isVisible","field","matches","isStepVisible","hasFieldsAndSteps","definition","hasRoutes","step","conditionFields","source","getAllFields","createValues","fields","initialValues","getChangedKeys","previous","next","keys","key","definitionErrors","steps","warnings","stepIndexes","fieldIndexes","index","route","target","routeFallthroughWarnings","targets","to","candidate","sibling","exits","activeSteps","indexes","result","available","stepValues","reconcileStepIndex","previousStep","preserved","nextIds","before","predecessor","candidates","ActivePath","analyzeDefinition","graph","fieldKeys","depend","owner","id","dependencies","dependency","pattern","earlier","isEntry","listOf","path","check","required","item","entry","name","conditions","shapeErrors","detectCycles","visiting","cycles","start","stack","frame","neighbor","nodes","node","validateDefinition","input","shape","cycle","checkDefinition","errors","rejected","message","FormLifecycleError","phase","cause","afterCommit","callback","error","activePath","engine","watchCheckedInputs","checked","TYPE_MESSAGES","getDefaultMessage","rule","params","BOOLEAN_TYPES","isEmpty","boundError","size","rules","unit","min","max","patternError","validateField","allValues","validators","sizeError","matchError","validateStep","validateFields","applyValidationErrors","navigate","previousErrors","structureChanged","moveToFirstError","firstErrorKey","targetIndex","clearResolvedMatchErrors","cleared","getValidationValues","pruneOffPathErrors","pathFields","pruned","getSubmitValues","withoutSkipped","validateForm","validateOne","previousError","visibleKeys","resetEngine","previousValues","loadingFields","changedValues","changedFields","resetValues","skipTarget","skipCurrentStep","includeCurrentStep","skipStepAt","submitAsync","submit","keepSkipped","lifecycle","dispatched","epoch","operation","inputsChanged","stale","allowed","hasStepErrors","moveTo","advance","nextStep","skipStep","skipStepAsync","changeStep","committed","skippedValues","edited","submitted","skipped","direction","reason","skipping","validating","validate","toIndex","context","prevStep","goToStepWithField","fieldKey","FormSubscriptions","listener","listeners","indexConditions","dependent","dependents","VisibilityState","valuesChanged","stepIndex","clearedFields","changedKey","seed","queue","queued","clear","current","quietEngines","FormEngine","options","total","previousSteps","valueChanged","hadError","stepId","revalidated","loading","validation","warning","MAX_STRING_LENGTH","MAX_EMAIL_LENGTH","MAX_ITEMS","EMAIL","DECIMAL","DATE","DATE_ONLY","DATE_TIME","TEXT_TYPES","FORMATS","normalizeValue","parsed","isOption","option","lengthError","multiselectError","stringError","formatError","format","primitiveError","typeError","allow","hasOwn","knownValues","typeErrors","withoutRules","invalid","strip","ignoredValidators","applySkips","skippedSteps","requested","validateSubmission","engineOptions"],"mappings":"AAEO,SAASA,CAAAA,CAAQC,EAAyB,CAC/C,OAAOA,GAAS,IAAA,EAAQA,CAAAA,GAAU,IAAO,KAAA,CAAM,OAAA,CAAQA,CAAK,CAAA,EA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A,CAAO,iBAAgB,CACtC,IAAA,GAAW,CAACxE,CAAAA,CAAKsE,CAAK,CAAA,GAAK4I,CAAAA,CAAaJ,EAAAA,CAAOjO,CAAAA,CAAQmB,CAAG,CAAA,GAAG8D,CAAAA,CAAO9D,CAAG,CAAA,CAAIsE,GAC3E,OAAO,CAAE,OAAAzF,CAAAA,CAAQ,MAAA,CAAAiF,CAAO,CAC1B","file":"server.js","sourcesContent":["import type { ShowCondition } from '../types';\n\nexport function isBlank(value: unknown): boolean {\n return value == null || value === '' || (Array.isArray(value) && !value.length);\n}\n\nexport function evaluateCondition(\n condition: ShowCondition,\n values: Record<string, unknown>,\n): boolean {\n const value = values[condition.field];\n\n if (condition.eq !== undefined) {\n return value === condition.eq;\n }\n\n if (condition.neq !== undefined) {\n return value !== condition.neq;\n }\n\n if (condition.in !== undefined) {\n return condition.in.includes(value as string | number);\n }\n\n if (condition.notIn !== undefined) {\n return !condition.notIn.includes(value as string | number);\n }\n\n if (condition.notEmpty === true) {\n return !isBlank(value);\n }\n\n return true;\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 { FormStep } from '../types';\nimport { isVisible } from './is-visible';\n\nexport const isStepVisible: (step: FormStep, values: Record<string, unknown>) => boolean = isVisible;\n","import type { FormDefinition, FormField } from '../types';\n\nexport function hasFieldsAndSteps(definition: FormDefinition): boolean {\n return !!definition.fields?.length && !!definition.steps?.length;\n}\n\nexport function hasRoutes(definition: FormDefinition): boolean {\n return !!definition.steps?.some((step) => step.routes?.length);\n}\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 { FormDefinition, FormStep } from '../types';\nimport { isStepVisible, isVisible } from '../visibility';\nimport { conditionFields, getAllFields, hasFieldsAndSteps, hasRoutes } from './engine-utils';\n\nexport function definitionErrors(definition: FormDefinition): string[] {\n const steps = definition.steps ?? [];\n const warnings = hasFieldsAndSteps(definition) ? ['FormEngine rejects a definition with both \"fields\" and \"steps\".'] : [];\n const stepIndexes = new Map<string, number>();\n const fieldIndexes = new Map<string, number>();\n steps.forEach((step, index) => {\n if (stepIndexes.has(step.id)) warnings.push(`Duplicate step id \"${step.id}\".`);\n stepIndexes.set(step.id, index);\n for (const field of step.fields) fieldIndexes.set(field.key, index);\n });\n for (const { key } of getAllFields(definition)) {\n if (key in Object.prototype || key === 'prototype') warnings.push(`Reserved field key \"${key}\".`);\n }\n if (!hasRoutes(definition)) return warnings;\n steps.forEach((step, index) => {\n for (const route of step.routes ?? []) {\n const target = route.to === null ? null : stepIndexes.get(route.to);\n if (target === undefined || (target !== null && target <= index)) {\n warnings.push(`Invalid route from \"${step.id}\" to \"${route.to}\": targets must be later steps or null.`);\n }\n for (const field of conditionFields(route)) {\n if (!((fieldIndexes.get(field) ?? Infinity) <= index)) {\n warnings.push(`Invalid route on \"${step.id}\": condition field \"${field}\" must belong to this or an earlier step.`);\n }\n }\n }\n });\n return warnings;\n}\n\nexport function routeFallthroughWarnings(definition: FormDefinition): string[] {\n const steps = definition.steps ?? [];\n const warnings: string[] = [];\n for (const step of steps) {\n const targets = new Set((step.routes ?? []).map((route) => route.to).filter((to) => to !== null));\n for (const target of targets) {\n const index = steps.findIndex((candidate) => candidate.id === target);\n const sibling = steps[index + 1];\n const exits = steps[index]?.routes?.some((route) => !route.show?.length && !route.showAny?.length);\n if (sibling && targets.has(sibling.id) && !exits) {\n warnings.push(`Route branch \"${target}\" from \"${step.id}\" continues into sibling branch \"${sibling.id}\". Add an unconditional route where it should continue.`);\n }\n }\n }\n return warnings;\n}\n\nexport function activeSteps(definition: FormDefinition, values: Record<string, unknown>): FormStep[] {\n const steps = definition.steps ?? [];\n if (!hasRoutes(definition)) return steps.filter((step) => isStepVisible(step, values));\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 (!isStepVisible(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 && isStepVisible(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: FormStep, 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 readonly enabled: boolean;\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 this.enabled = hasRoutes(definition);\n }\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 for (const step of this.activeStepList) Object.assign(result, stepValues(step, values, result));\n this.activeValueMap = result;\n }\n}\n","import { conditionFields, getAllFields, hasRoutes } from '../engine/engine-utils';\nimport type { FormDefinition, FormField } from '../types';\n\nexport interface DefinitionAnalysis {\n graph: Map<string, string[]>;\n warnings: string[];\n}\n\nexport function analyzeDefinition(definition: FormDefinition): DefinitionAnalysis {\n const warnings: string[] = [];\n const graph = new Map<string, string[]>();\n const fields = getAllFields(definition);\n const fieldKeys = new Set<string>();\n for (const { key } of fields) {\n if (fieldKeys.has(key)) warnings.push(`Duplicate field key \"${key}\" — fields will share state and overwrite each other`);\n fieldKeys.add(key);\n }\n const depend = (owner: string, id: string, source: Pick<FormField, 'show' | 'showAny'>, keys: string[]) => {\n const dependencies = conditionFields(source);\n for (const dependency of dependencies) {\n if (typeof dependency !== 'string') warnings.push(`${owner} \"${id}\" has a show condition without a \"field\" name`);\n else if (!fieldKeys.has(dependency)) warnings.push(`${owner} \"${id}\" has show condition referencing non-existent field \"${dependency}\"`);\n }\n if (dependencies.length) for (const key of keys) graph.set(key, [...(graph.get(key) ?? []), ...dependencies]);\n };\n for (const field of fields) {\n depend('Field', field.key, field, [field.key]);\n const pattern = field.validation?.pattern;\n if (pattern === undefined) continue;\n try {\n new RegExp(pattern);\n } catch {\n warnings.push(`Field \"${field.key}\" has invalid regex pattern: \"${pattern}\"`);\n }\n }\n const earlier = new Set<string>();\n for (const step of definition.steps ?? []) {\n depend('Step', step.id, step, step.fields.map((field) => field.key));\n for (const field of conditionFields(step)) {\n if (hasRoutes(definition) && fieldKeys.has(field) && !earlier.has(field)) {\n warnings.push(`Step \"${step.id}\" condition field \"${field}\" must belong to an earlier step.`);\n }\n }\n for (const { key } of step.fields) earlier.add(key);\n if (step.skip && (step.next === false || !definition.steps![1])) {\n warnings.push(`Step \"${step.id}\" has \"skip\" but no Next button or later step.`);\n }\n }\n return { graph, warnings };\n}\n","type Entry = Record<string, unknown>;\ntype Check = (value: unknown, path: string) => string[];\n\nexport const isEntry = (value: unknown): value is Entry =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nfunction listOf(value: unknown, path: string, check: Check, required = false): string[] {\n if (value == null && !required) return [];\n if (!Array.isArray(value)) return [`${path} must be an array.`];\n return value.flatMap((item, index) => check(item, `${path}[${index}]`));\n}\n\nfunction entry(name: string, check: (value: Entry, path: string) => string[]): Check {\n return (value, path) => (isEntry(value) ? check(value, path) : [`${path} must be ${name}.`]);\n}\n\nconst condition = entry('a condition object', () => []);\n\nfunction conditions(value: Entry, path: string): string[] {\n return [...listOf(value.show, `${path}.show`, condition), ...listOf(value.showAny, `${path}.showAny`, condition)];\n}\n\nconst field = entry('a field object', conditions);\nconst route = entry('a route object', conditions);\nconst step = entry('a step object', (value, path) => [\n ...listOf(value.fields, `${path}.fields`, field, true),\n ...conditions(value, path),\n ...listOf(value.routes, `${path}.routes`, route),\n]);\n\nexport function shapeErrors(definition: unknown): string[] {\n if (!isEntry(definition)) return ['Form definition must be an object.'];\n return [...listOf(definition.fields, 'fields', field), ...listOf(definition.steps, 'steps', step)];\n}\n","import { definitionErrors, routeFallthroughWarnings } from '../engine/step-routes';\nimport type { FormDefinition } from '../types';\nimport { analyzeDefinition } from './definition-analysis';\nimport { isEntry, shapeErrors } from './shape-errors';\n\nfunction detectCycles(graph: Map<string, string[]>): string[][] {\n const visiting = new Map<string, boolean>();\n const cycles: string[][] = [];\n for (const start of graph.keys()) {\n if (visiting.has(start)) continue;\n visiting.set(start, true);\n const stack: [string, number][] = [[start, 0]];\n while (stack.length > 0) {\n const frame = stack[stack.length - 1];\n const neighbor = graph.get(frame[0])?.[frame[1]++];\n if (neighbor === undefined) {\n visiting.set(frame[0], false);\n stack.pop();\n } else if (visiting.get(neighbor)) {\n const nodes = stack.map(([node]) => node);\n cycles.push([...nodes.slice(nodes.indexOf(neighbor)), neighbor]);\n } else if (!visiting.has(neighbor)) {\n visiting.set(neighbor, true);\n stack.push([neighbor, 0]);\n }\n }\n }\n return cycles;\n}\n\nexport function validateDefinition(input: unknown): string[] {\n const shape = shapeErrors(input);\n if (shape.length) return shape;\n const definition = input as FormDefinition;\n const { graph, warnings } = analyzeDefinition(definition);\n if (!isEntry(definition.submit)) warnings.unshift('Form definition is missing the \"submit\" action.');\n for (const cycle of detectCycles(graph)) {\n warnings.push(`Circular show condition detected: ${cycle.join(' -> ')}`);\n }\n return [...definitionErrors(definition), ...warnings, ...routeFallthroughWarnings(definition)];\n}\n","import { validateDefinition } from '../definition-validation';\nimport { shapeErrors } from '../definition-validation/shape-errors';\nimport { definitionErrors } from '../engine/step-routes';\nimport type { FormDefinition } from '../types';\n\nexport interface DefinitionCheck {\n errors: string[];\n warnings: string[];\n}\n\nexport function checkDefinition(input: unknown): DefinitionCheck {\n const shape = shapeErrors(input);\n if (shape.length) return { errors: shape, warnings: [] };\n const definition = input as FormDefinition;\n const errors = definitionErrors(definition);\n const rejected = new Set(errors);\n return { errors, warnings: validateDefinition(definition).filter((message) => !rejected.has(message)) };\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","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","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 function getDefaultMessage(rule: string, 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 { FieldValidation, FormField } from '../types';\nimport { isBlank } from '../visibility';\nimport { getDefaultMessage } from './default-messages';\n\nexport type ValidatorFn = (\n value: unknown,\n allValues: Record<string, unknown>,\n) => string | null;\n\nexport const BOOLEAN_TYPES = new Set(['checkbox', 'switch']);\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 validateField(\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 if (!rules) return null;\n if (isEmpty(value, field)) {\n if (!rules.required) return null;\n return typeof rules.required === 'string' ? rules.required : getDefaultMessage('required');\n }\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]\n ? rules.matchFieldMessage ?? getDefaultMessage('matchField')\n : 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, validateField } 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 = validateField(field, values[field.key], values, validators);\n if (error) {\n errors[field.key] = error;\n }\n }\n\n return errors;\n}\n","import { validateField, validateFields, validateStep } from '../validation';\nimport { createValues, getChangedKeys, hasRoutes } 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.errors = {};\n engine.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.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 (validateField(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 hasRoutes(engine.definition) ? getSubmitValues(engine) : withoutSkipped(engine, { ...engine.values });\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 ?? [], engine.values, engine.validators),\n );\n }\n engine.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.fieldByKey.get(key);\n if (!field || !engine.visibility.isFieldVisible(key, engine.values)) return null;\n const previousError = engine.errors[key];\n const error = validateField(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 const result: Record<string, unknown> = {};\n const visibleKeys = engine.visibility.getVisibleFieldKeys(\n engine.values,\n engine.currentStepIndex,\n );\n for (const key of visibleKeys) {\n if (engine.values[key] !== undefined) result[key] = engine.values[key];\n }\n return withoutSkipped(engine, result);\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.submitting = false;\n engine.values = createValues(engine.visibility.allFields, values);\n engine.errors = {};\n engine.topLevelErrors = [];\n engine.fieldLoading = {};\n engine.stepValidating = false;\n engine.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 { FormStep } from '../types';\nimport { createValues } from './engine-utils';\nimport type { EngineInternals } from './runtime-internals';\nimport { activeSteps } from './step-routes';\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.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.notify({ fieldKeys, 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.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 submitAsync(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.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 await submit(values, [...engine.skipped.keys()]);\n if (operation !== engine.operationEpoch) return true;\n await afterCommit('afterSubmit', () => lifecycle.onAfterSubmit?.(values));\n return true;\n } catch (error) {\n if (!dispatched && stale()) return false;\n throw error;\n } finally {\n if (operation === engine.operationEpoch) {\n engine.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 { submitAsync } 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.currentStepIndex = index;\n engine.notify({ structureChanged: true });\n}\n\nfunction advance(engine: EngineInternals): boolean {\n if (engine.isLastStep) return false;\n moveTo(engine, engine.currentStepIndex + 1);\n return true;\n}\n\nexport function nextStep(engine: EngineInternals): boolean {\n if (!engine.isMultiStep) return false;\n includeCurrentStep(engine);\n return !hasStepErrors(engine) && advance(engine);\n}\n\nexport function skipStep(engine: EngineInternals): boolean {\n if (!engine.isMultiStep || !skipTarget(engine)) return false;\n skipCurrentStep(engine);\n return advance(engine);\n}\n\nexport async function skipStepAsync(engine: EngineInternals, submit?: SubmitFn): Promise<boolean> {\n if (!engine.isMultiStep || engine.stepValidating || engine.submitting) 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 submitAsync(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.values = values;\n engine.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 = { fromStepId: step.id, toStepId: target.id, direction, 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.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.stepValidating = false;\n engine.notify();\n }\n }\n}\n\nexport function prevStep(engine: EngineInternals): void {\n if (engine.isMultiStep && !engine.isFirstStep) moveTo(engine, engine.currentStepIndex - 1);\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","export interface NotifyOptions {\n fieldKeys?: Iterable<string>;\n structureChanged?: boolean;\n}\n\nexport class FormSubscriptions {\n private version = 0;\n private listeners = new Set<() => void>();\n private fieldVersions = new Map<string, number>();\n private fieldListeners = new Map<string, Set<() => void>>();\n private structureVersion = 0;\n private structureListeners = new Set<() => void>();\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n getSnapshot(): number {\n return this.version;\n }\n\n subscribeField(key: string, listener: () => void): () => void {\n const listeners = this.fieldListeners.get(key) ?? new Set();\n listeners.add(listener);\n this.fieldListeners.set(key, listeners);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) this.fieldListeners.delete(key);\n };\n }\n\n getFieldSnapshot(key: string): number {\n return this.fieldVersions.get(key) ?? 0;\n }\n\n subscribeStructure(listener: () => void): () => void {\n this.structureListeners.add(listener);\n return () => this.structureListeners.delete(listener);\n }\n\n getStructureSnapshot(): number {\n return this.structureVersion;\n }\n\n notify({ fieldKeys = [], structureChanged = false }: NotifyOptions = {}): void {\n for (const key of new Set(fieldKeys)) this.notifyField(key);\n if (structureChanged) this.notifyStructure();\n\n this.version++;\n for (const listener of this.listeners) listener();\n }\n\n private notifyField(key: string): void {\n this.fieldVersions.set(key, (this.fieldVersions.get(key) ?? 0) + 1);\n for (const listener of this.fieldListeners.get(key) ?? []) listener();\n }\n\n private notifyStructure(): void {\n this.structureVersion++;\n for (const listener of this.structureListeners) listener();\n }\n}\n","import type { FormField, FormStep } from '../types';\nimport { conditionFields } from './engine-utils';\n\nexport function indexConditions<T extends FormField | FormStep>(dependent: T, index: Map<string, Set<T>>): void {\n for (const field of conditionFields(dependent)) {\n const dependents = index.get(field) ?? new Set<T>();\n dependents.add(dependent);\n index.set(field, dependents);\n }\n}\n","import { conditionFields, getAllFields } from './engine-utils';\nimport { indexConditions } from './visibility-index';\nimport { ActivePath } from './step-routes';\nimport type { ValidatorFn } from '../validation';\nimport { validateStep } from '../validation';\nimport type { FormDefinition, FormField, FormStep } from '../types';\nimport { isStepVisible, isVisible } from '../visibility';\n\ninterface VisibilityCache {\n visibleSteps: FormStep[];\n currentStep: FormStep | null;\n visibleFields: FormField[];\n canGoNext: boolean;\n}\n\nexport class VisibilityState {\n readonly allFields: FormField[];\n readonly fieldByKey: Map<string, FormField>;\n private routeFields = new Set<string>();\n private readonly path: ActivePath;\n private fieldDependents = new Map<string, Set<FormField>>();\n private stepDependents = new Map<string, Set<FormStep>>();\n private stepByFieldKey = new Map<string, FormStep>();\n private visibilityDirty = true;\n private canGoNextDirty = true;\n private cache: VisibilityCache = {\n visibleSteps: [],\n currentStep: null,\n visibleFields: [],\n canGoNext: false,\n };\n\n constructor(private definition: FormDefinition) {\n this.allFields = getAllFields(definition);\n this.fieldByKey = new Map(this.allFields.map((field) => [field.key, field]));\n this.path = new ActivePath(definition);\n for (const step of definition.steps ?? []) {\n for (const field of step.fields) this.stepByFieldKey.set(field.key, step);\n }\n this.buildIndexes();\n }\n\n markChanged(structureChanged: boolean, valuesChanged: boolean): void {\n if (structureChanged || valuesChanged) this.path.invalidate();\n if (structureChanged) {\n this.visibilityDirty = true;\n this.canGoNextDirty = true;\n } else if (valuesChanged) {\n this.canGoNextDirty = true;\n }\n }\n\n state(values: Record<string, unknown>, stepIndex: number): VisibilityCache {\n this.recomputeVisibility(values, stepIndex);\n return this.cache;\n }\n\n getCanGoNext(\n values: Record<string, unknown>,\n stepIndex: number,\n validators: Record<string, ValidatorFn>,\n ): boolean {\n this.recomputeVisibility(values, stepIndex);\n if (!this.canGoNextDirty) return this.cache.canGoNext;\n this.canGoNextDirty = false;\n const step = this.cache.currentStep;\n const errors = step ? validateStep(step, this.conditionValues(values), validators) : {};\n this.cache.canGoNext = this.isMultiStep && Object.keys(errors).length === 0;\n return this.cache.canGoNext;\n }\n\n findStepIndex(fieldKey: string, values: Record<string, unknown>, stepIndex: number): number | null {\n const steps = this.state(values, stepIndex).visibleSteps;\n const target = steps.findIndex((step) => step.fields.some((field) => field.key === fieldKey));\n return target === -1 ? null : target;\n }\n\n affectsStructure(key: string, clearedFields: Set<string>): boolean {\n return this.routeFields.has(key) || this.fieldDependents.has(key) || this.stepDependents.has(key) || clearedFields.size > 0;\n }\n\n cascadeHiddenFields(\n changedKey: string,\n values: Record<string, unknown>,\n errors: Record<string, string>,\n ): Set<string> {\n this.path.invalidate();\n if (this.hasRoutes) return this.reconcileHidden(values, errors);\n return this.drainQueue(new Set([changedKey]), values, errors);\n }\n\n reconcileHidden(values: Record<string, unknown>, errors: Record<string, string>): Set<string> {\n this.path.invalidate();\n const seed = new Set([...this.fieldDependents.keys(), ...this.stepDependents.keys()]);\n return this.drainQueue(seed, values, errors);\n }\n private drainQueue(\n seed: Set<string>,\n values: Record<string, unknown>,\n errors: Record<string, string>,\n ): Set<string> {\n const queue = [...seed];\n const queued = new Set(queue);\n const cleared = new Set<string>();\n const clear = (key: string) => {\n delete values[key];\n delete errors[key];\n this.path.invalidate();\n cleared.add(key);\n if (queued.has(key)) return;\n queued.add(key);\n queue.push(key);\n };\n\n for (let index = 0; index < queue.length; index++) {\n const key = queue[index];\n queued.delete(key);\n this.clearHiddenFields(this.fieldDependents.get(key), values, clear);\n this.clearHiddenSteps(this.stepDependents.get(key), values, clear);\n }\n return cleared;\n }\n\n isFieldVisible(key: string, values: Record<string, unknown>): boolean {\n const field = this.fieldByKey.get(key);\n if (!field || !isVisible(field, this.conditionValues(values))) return false;\n const step = this.stepByFieldKey.get(key);\n return !step || this.path.steps(values).includes(step);\n }\n\n getVisibleFieldKeys(values: Record<string, unknown>, stepIndex: number): Set<string> {\n if (this.hasRoutes) return new Set(Object.keys(this.path.values(values)));\n const keys = new Set<string>();\n const fields = this.isMultiStep\n ? this.state(values, stepIndex).visibleSteps.flatMap((step) => step.fields)\n : this.definition.fields ?? [];\n for (const field of fields) {\n if (isVisible(field, this.conditionValues(values))) keys.add(field.key);\n }\n return keys;\n }\n private conditionValues(values: Record<string, unknown>) { return this.hasRoutes ? this.path.values(values) : values; }\n private get hasRoutes(): boolean { return this.path.enabled; }\n private get isMultiStep(): boolean { return (this.definition.steps ?? []).length > 0; }\n private buildIndexes(): void {\n for (const field of this.allFields) {\n indexConditions(field, this.fieldDependents);\n }\n for (const step of this.definition.steps ?? []) {\n indexConditions(step, this.stepDependents);\n for (const route of step.routes ?? []) {\n for (const field of conditionFields(route)) this.routeFields.add(field);\n }\n }\n }\n private recomputeVisibility(values: Record<string, unknown>, stepIndex: number): void {\n if (!this.visibilityDirty) return;\n this.visibilityDirty = false;\n if (!this.isMultiStep) {\n this.cache.visibleSteps = [];\n this.cache.currentStep = null;\n this.cache.visibleFields = (this.definition.fields ?? []).filter((field) => isVisible(field, this.conditionValues(values)));\n return;\n }\n this.cache.visibleSteps = this.path.steps(values);\n const steps = this.cache.visibleSteps;\n this.cache.currentStep = steps[stepIndex] ?? steps[steps.length - 1] ?? null;\n const current = this.cache.currentStep;\n this.cache.visibleFields = current\n ? current.fields.filter((field) => isVisible(field, this.conditionValues(values)))\n : [];\n }\n private clearHiddenFields(\n fields: Iterable<FormField> | undefined,\n values: Record<string, unknown>,\n clear: (key: string) => void,\n ): void {\n for (const field of fields ?? []) {\n const step = this.stepByFieldKey.get(field.key);\n if (this.hasRoutes && step && !this.path.steps(values).includes(step)) continue;\n if (isVisible(field, this.conditionValues(values)) || values[field.key] === undefined) continue;\n clear(field.key);\n }\n }\n private clearHiddenSteps(\n steps: Iterable<FormStep> | undefined,\n values: Record<string, unknown>,\n clear: (key: string) => void,\n ): void {\n for (const step of steps ?? []) {\n if (isStepVisible(step, this.conditionValues(values))) continue;\n for (const field of step.fields) {\n if (values[field.key] === undefined) continue;\n clear(field.key);\n }\n }\n }\n}\n","import { validateDefinition } from '../definition-validation';\nimport { shapeErrors } from '../definition-validation/shape-errors';\nimport type { ValidatorFn } from '../validation';\nimport type { FormDefinition, FormField, FormStep } from '../types';\nimport type { FormEngineOptions, StepValidateFn, SubmitFn } from './engine-options';\nimport { createValues } from './engine-utils';\nimport { changeStep, goToStepWithField, nextStep, prevStep, skipStep, skipStepAsync } from './navigation';\nimport type { EngineInternals, RuntimeNotifyOptions } from './runtime-internals';\nimport { FormSubscriptions, type NotifyOptions } from './subscriptions';\nimport {\n applyValidationErrors,\n getSubmitValues,\n resetEngine,\n validateForm,\n validateOne,\n clearResolvedMatchErrors,\n pruneOffPathErrors,\n} from './validation-state';\nimport { submitAsync } from './submission';\nimport { definitionErrors, reconcileStepIndex } from './step-routes';\nimport { VisibilityState } from './visibility-state';\n\nexport const quietEngines = new WeakSet<FormEngineOptions>();\n\nexport class FormEngine {\n values: Record<string, unknown>;\n errors: Record<string, string> = {};\n topLevelErrors: string[] = [];\n currentStepIndex = 0;\n fieldLoading: Record<string, boolean> = {};\n stepValidating = false;\n submitting = false;\n private readonly skipped = new Map<string, string[]>();\n private validationEpoch = 0;\n private operationEpoch = 0;\n private readonly lifecycle: FormEngineOptions;\n\n private readonly validators: Record<string, ValidatorFn>;\n private get onStepValidate(): StepValidateFn | undefined { return this.lifecycle.onStepValidate; }\n private readonly visibility: VisibilityState;\n private readonly subscriptions = new FormSubscriptions();\n\n constructor(\n readonly definition: FormDefinition,\n initialValues?: Record<string, unknown>,\n options?: FormEngineOptions,\n ) {\n const shape = shapeErrors(definition);\n const errors = shape.length ? shape : definitionErrors(definition);\n if (errors.length) throw new Error(errors.join('\\n'));\n this.lifecycle = options ?? {};\n this.validators = options?.validators ?? {};\n this.visibility = new VisibilityState(definition);\n if (!quietEngines.has(this.lifecycle)) this.warnAboutDefinition();\n this.values = createValues(this.visibility.allFields, initialValues);\n this.visibility.reconcileHidden(this.values, this.errors);\n }\n\n get isMultiStep(): boolean {\n return (this.definition.steps ?? []).length > 0;\n }\n\n get visibleSteps(): FormStep[] {\n return this.visibility.state(this.values, this.currentStepIndex).visibleSteps;\n }\n\n get currentStep(): FormStep | null {\n return this.visibility.state(this.values, this.currentStepIndex).currentStep;\n }\n\n get visibleFields(): FormField[] {\n return this.visibility.state(this.values, this.currentStepIndex).visibleFields;\n }\n\n get isFirstStep(): boolean {\n return this.currentStepIndex === 0;\n }\n\n get isLastStep(): boolean {\n return this.currentStepIndex >= this.visibleSteps.length - 1;\n }\n\n get canGoNext(): boolean {\n return this.visibility.getCanGoNext(this.values, this.currentStepIndex, this.validators);\n }\n\n get progress(): { current: number; total: number } {\n const total = this.visibleSteps.length;\n return { current: Math.min(this.currentStepIndex + 1, total), total };\n }\n\n subscribe(listener: () => void): () => void {\n return this.subscriptions.subscribe(listener);\n }\n\n getSnapshot(): number {\n return this.subscriptions.getSnapshot();\n }\n\n subscribeField(key: string, listener: () => void): () => void {\n return this.subscriptions.subscribeField(key, listener);\n }\n\n getFieldSnapshot(key: string): number {\n return this.subscriptions.getFieldSnapshot(key);\n }\n\n subscribeStructure(listener: () => void): () => void {\n return this.subscriptions.subscribeStructure(listener);\n }\n\n getStructureSnapshot(): number {\n return this.subscriptions.getStructureSnapshot();\n }\n\n setValue(key: string, value: unknown): void {\n const previousSteps = this.isMultiStep ? this.visibleSteps : null;\n const valueChanged = !Object.is(this.values[key], value);\n const hadError = this.errors[key] !== undefined;\n this.values[key] = value;\n delete this.errors[key];\n for (const [stepId, keys] of this.skipped) if (valueChanged && keys.includes(key)) this.skipped.delete(stepId);\n const clearedFields = this.visibility.cascadeHiddenFields(key, this.values, this.errors);\n const revalidated = clearResolvedMatchErrors(this.internals, key);\n const changedFields = new Set([...clearedFields, ...revalidated]);\n if (valueChanged || hadError) changedFields.add(key);\n const valuesChanged = valueChanged || clearedFields.size > 0;\n const structureChanged = valuesChanged && this.visibility.affectsStructure(key, clearedFields);\n if (previousSteps && structureChanged) {\n this.visibility.markChanged(true, true);\n this.currentStepIndex = reconcileStepIndex(previousSteps, this.visibleSteps, this.currentStepIndex);\n for (const pruned of pruneOffPathErrors(this.internals)) changedFields.add(pruned);\n }\n this.notify({ fieldKeys: changedFields, structureChanged, valuesChanged });\n }\n\n setErrors(errors: Record<string, string>): void {\n applyValidationErrors(this.internals, errors, true);\n }\n\n setFieldLoading(key: string, loading: boolean): void {\n const previous = this.fieldLoading[key] === true;\n if (loading) this.fieldLoading[key] = true;\n else delete this.fieldLoading[key];\n this.notify({ fieldKeys: previous === loading ? [] : [key] });\n }\n\n cancelPendingActions(): void {\n this.validationEpoch++;\n this.operationEpoch++;\n this.stepValidating = false;\n this.submitting = false;\n this.notify();\n }\n\n nextStep(): boolean { return nextStep(this.internals); }\n nextStepAsync(reason: 'next' | 'autoAdvance' = 'next'): Promise<boolean> { return changeStep(this.internals, 'next', reason); }\n prevStepAsync(): Promise<boolean> { return changeStep(this.internals, 'back'); }\n skipStep(): boolean { return skipStep(this.internals); }\n skipStepAsync(submit?: SubmitFn): Promise<boolean> { return skipStepAsync(this.internals, submit); }\n isStepSkipped(stepId: string): boolean { return this.skipped.has(stepId); }\n submitAsync(submit: SubmitFn): Promise<boolean> { return submitAsync(this.internals, submit); }\n prevStep(): void { prevStep(this.internals); }\n validate(): Record<string, string> { return validateForm(this.internals); }\n validateField(key: string): string | null { return validateOne(this.internals, key); }\n getSubmitValues(): Record<string, unknown> { return getSubmitValues(this.internals); }\n goToStepWithField(key: string): void { goToStepWithField(this.internals, key); }\n reset(values?: Record<string, unknown>): void { resetEngine(this.internals, values); }\n\n private warnAboutDefinition(): void {\n const warnings = validateDefinition(this.definition);\n for (const { key, validation } of this.visibility.allFields) {\n const name = validation?.validator;\n if (name && !this.validators[name]) warnings.push(`Field \"${key}\" references unknown validator \"${name}\".`);\n }\n for (const warning of warnings) console.warn(`[FormEngine] ${warning}`);\n }\n\n private get internals(): EngineInternals {\n return this as unknown as EngineInternals;\n }\n\n private notify(options: RuntimeNotifyOptions = {}): void {\n this.visibility.markChanged(!!options.structureChanged, !!options.valuesChanged);\n this.subscriptions.notify(options);\n }\n}\n","import type { FormField } from '../types';\nimport { getDefaultMessage, TYPE_MESSAGES } from '../validation/default-messages';\nimport { BOOLEAN_TYPES } from '../validation/validate-field';\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","import type { FormDefinition, FormField } from '../types';\nimport type { ValidatorFn } from '../validation';\nimport { getAllFields } from '../engine/engine-utils';\nimport type { EngineInternals } from '../engine/runtime-internals';\nimport { FormEngine, quietEngines } from '../engine/runtime';\nimport { skipStepAt } from '../engine/step-skip';\nimport { normalizeValue, typeError } from './type-checks';\n\nexport interface SubmissionOptions {\n skippedSteps?: string[];\n}\n\nexport interface SubmissionResult {\n values: Record<string, unknown>;\n errors: Record<string, string>;\n}\n\nconst allow: ValidatorFn = () => null;\n\nconst hasOwn = (source: object, key: string) => Object.prototype.hasOwnProperty.call(source, key);\n\nfunction knownValues(fields: FormField[], input: unknown): Record<string, unknown> {\n const source = input !== null && typeof input === 'object' && !Array.isArray(input) ? input as Record<string, unknown> : {};\n const values: Record<string, unknown> = {};\n for (const field of fields) {\n if (hasOwn(source, field.key)) values[field.key] = normalizeValue(field, source[field.key]);\n }\n return values;\n}\n\nfunction typeErrors(fields: FormField[], values: Record<string, unknown>): Map<string, string> {\n const errors = new Map<string, string>();\n for (const field of fields) {\n const error = hasOwn(values, field.key) ? typeError(field, values[field.key]) : null;\n if (error) errors.set(field.key, error);\n }\n return errors;\n}\n\nfunction withoutRules(definition: FormDefinition, invalid: Map<string, string>): FormDefinition {\n const strip = (fields: FormField[]) => fields.map((field) => (invalid.has(field.key) ? { ...field, validation: undefined } : field));\n const steps = definition.steps?.map((step) => ({ ...step, fields: strip(step.fields) }));\n return { ...definition, ...(definition.fields && { fields: strip(definition.fields) }), ...(steps && { steps }) };\n}\n\nfunction ignoredValidators(fields: FormField[]): Record<string, ValidatorFn> {\n const validators: Record<string, ValidatorFn> = {};\n for (const { validation } of fields) if (validation?.validator) validators[validation.validator] = allow;\n return validators;\n}\n\nfunction applySkips(engine: FormEngine, skippedSteps: unknown): void {\n if (!Array.isArray(skippedSteps)) return;\n const requested = new Set(skippedSteps);\n for (let index = 0; index < engine.visibleSteps.length; index++) {\n const step = engine.visibleSteps[index];\n if (step.skip && requested.has(step.id)) skipStepAt(engine as unknown as EngineInternals, index);\n }\n}\n\nexport function validateSubmission(\n definition: FormDefinition,\n input: unknown,\n options: SubmissionOptions = {},\n): SubmissionResult {\n const fields = getAllFields(definition);\n const initialValues = knownValues(fields, input);\n const invalid = typeErrors(fields, initialValues);\n const engineOptions = { validators: ignoredValidators(fields) };\n quietEngines.add(engineOptions);\n const engine = new FormEngine(withoutRules(definition, invalid), initialValues, engineOptions);\n applySkips(engine, options.skippedSteps);\n const errors = engine.validate();\n const values = engine.getSubmitValues();\n for (const [key, error] of invalid) if (hasOwn(values, key)) errors[key] = error;\n return { values, errors };\n}\n"]}
1
+ {"version":3,"sources":["../src/server/validate-submission.ts"],"names":["BODY_MESSAGE","allow","hasOwn","source","key","knownValues","fields","input","values","field","normalizeValue","typeErrors","errors","error","typeError","withoutRules","definition","invalid","strip","steps","step","ignoredValidators","given","validators","validation","isBody","applySkips","engine","skippedSteps","requested","index","skipStepAt","validateSubmission","options","parseDefinition","getAllFields","initialValues","engineOptions","FormEngine","submitted"],"mappings":"2LAcA,IAAMA,EAAe,uGAAA,CAOfC,CAAAA,CAAqB,IAAM,IAAA,CAE3BC,CAAAA,CAAS,CAACC,CAAAA,CAAgBC,CAAAA,GAAgB,MAAA,CAAO,SAAA,CAAU,eAAe,IAAA,CAAKD,CAAAA,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dhB,GAAAA,CACAR,EACAyB,CAAAA,CAA6B,GACX,CAClBC,CAAAA,CAAgBlB,GAAU,CAAA,CAC1B,IAAMV,CAAAA,CAAS6B,CAAAA,CAAanB,GAAU,CAAA,CAChCoB,CAAAA,CAAgB/B,EAAYC,CAAAA,CAAQE,CAAM,EAC1CS,CAAAA,CAAUN,CAAAA,CAAWL,CAAAA,CAAQ8B,CAAa,EAC1CC,CAAAA,CAAgB,CAAE,WAAYhB,CAAAA,CAAkBf,CAAAA,CAAQ2B,EAAQ,UAAU,CAAA,CAAG,UAAW,IAAM,CAAC,CAAE,CAAA,CACjGN,CAAAA,CAAS,IAAIW,CAAAA,CAAWvB,CAAAA,CAAaC,IAAYC,CAAO,CAAA,CAAGmB,CAAAA,CAAeC,CAAa,EAC7FX,CAAAA,CAAWC,CAAAA,CAAQM,EAAQ,YAAY,CAAA,CACvC,IAAMrB,CAAAA,CAASe,CAAAA,CAAO,UAAS,CACzBY,CAAAA,CAAYZ,EAAO,eAAA,EAAgB,CACzC,OAAW,CAACvB,CAAAA,CAAKS,CAAK,CAAA,GAAKI,CAAAA,CAAaf,CAAAA,CAAOqC,CAAAA,CAAWnC,CAAG,CAAA,GAAGQ,CAAAA,CAAOR,CAAG,CAAA,CAAIS,CAAAA,CAAAA,CAC9E,OAAIY,CAAAA,CAAOnB,CAAAA,CAAQE,CAAM,CAAA,GAAGI,CAAAA,CAAO,OAASZ,CAAAA,CAAAA,CACrC,CAAE,OAAQuC,CAAAA,CAAW,MAAA,CAAA3B,CAAO,CACrC","file":"server.js","sourcesContent":["import type { FormDefinition, FormField } from '../types';\nimport type { ValidatorFn } from '../validation';\nimport { parseDefinition } from '../definition-validation';\nimport { getAllFields } from '../engine/engine-utils';\nimport type { EngineInternals } from '../engine/runtime-internals';\nimport { FormEngine } from '../engine/runtime';\nimport { skipStepAt } from '../engine/step-skip';\nimport { normalizeValue, typeError } from '../validation/type-checks';\n\nexport interface SubmissionOptions {\n skippedSteps?: string[];\n validators?: Record<string, ValidatorFn>;\n}\n\nconst BODY_MESSAGE = 'Pass the values object as the second argument, not the request body with \"values\" and \"skippedSteps\".';\n\nexport interface SubmissionResult {\n values: Record<string, unknown>;\n errors: Record<string, string>;\n}\n\nconst allow: ValidatorFn = () => null;\n\nconst hasOwn = (source: object, key: string) => Object.prototype.hasOwnProperty.call(source, key);\n\nfunction knownValues(fields: FormField[], input: unknown): Record<string, unknown> {\n const source = input !== null && typeof input === 'object' && !Array.isArray(input) ? input as Record<string, unknown> : {};\n const values: Record<string, unknown> = {};\n for (const field of fields) {\n if (hasOwn(source, field.key)) values[field.key] = normalizeValue(field, source[field.key]);\n }\n return values;\n}\n\nfunction typeErrors(fields: FormField[], values: Record<string, unknown>): Map<string, string> {\n const errors = new Map<string, string>();\n for (const field of fields) {\n const error = hasOwn(values, field.key) ? typeError(field, values[field.key]) : null;\n if (error) errors.set(field.key, error);\n }\n return errors;\n}\n\nfunction withoutRules(definition: FormDefinition, invalid: Map<string, string>): FormDefinition {\n const strip = (fields: FormField[]) => fields.map((field) => (invalid.has(field.key) ? { ...field, validation: undefined } : field));\n const steps = definition.steps?.map((step) => ({ ...step, fields: strip(step.fields) }));\n return { ...definition, ...(definition.fields && { fields: strip(definition.fields) }), ...(steps && { steps }) };\n}\n\nfunction ignoredValidators(fields: FormField[], given: Record<string, ValidatorFn> = {}): Record<string, ValidatorFn> {\n const validators: Record<string, ValidatorFn> = {};\n for (const { validation } of fields) if (validation?.validator) validators[validation.validator] = allow;\n return { ...validators, ...given };\n}\n\nfunction isBody(fields: FormField[], input: unknown): boolean {\n if (input === null || typeof input !== 'object' || !hasOwn(input, 'values')) return false;\n return !fields.some((field) => field.key === 'values' || field.key === 'skippedSteps');\n}\n\nfunction applySkips(engine: FormEngine, skippedSteps: unknown): void {\n if (!Array.isArray(skippedSteps)) return;\n const requested = new Set(skippedSteps);\n for (let index = 0; index < engine.visibleSteps.length; index++) {\n const step = engine.visibleSteps[index];\n if (step.skip && requested.has(step.id)) skipStepAt(engine as unknown as EngineInternals, index);\n }\n}\n\nexport function validateSubmission(\n definition: FormDefinition,\n values: unknown,\n options: SubmissionOptions = {},\n): SubmissionResult {\n parseDefinition(definition);\n const fields = getAllFields(definition);\n const initialValues = knownValues(fields, values);\n const invalid = typeErrors(fields, initialValues);\n const engineOptions = { validators: ignoredValidators(fields, options.validators), onWarning: () => {} };\n const engine = new FormEngine(withoutRules(definition, invalid), initialValues, engineOptions);\n applySkips(engine, options.skippedSteps);\n const errors = engine.validate();\n const submitted = engine.getSubmitValues();\n for (const [key, error] of invalid) if (hasOwn(submitted, key)) errors[key] = error;\n if (isBody(fields, values)) errors.values = BODY_MESSAGE;\n return { values: submitted, errors };\n}\n"]}
@@ -0,0 +1,19 @@
1
+ import { F as FormField } from './definition-Bufih_Bx.js';
2
+
3
+ type DefinitionIssueCode = 'invalid-type' | 'missing-property' | 'fields-and-steps' | 'duplicate-step-id' | 'duplicate-key' | 'reserved-key' | 'route-target' | 'unknown-field' | 'forward-reference' | 'condition-operator-count' | 'unknown-operator' | 'condition-value-mismatch' | 'condition-cycle' | 'invalid-pattern' | 'invalid-range' | 'rule-not-applicable' | 'missing-options' | 'default-not-in-options' | 'unknown-field-type' | 'unknown-validator' | 'skip-unreachable' | 'route-fallthrough';
4
+ interface DefinitionIssue {
5
+ code: DefinitionIssueCode;
6
+ severity: 'error' | 'warning';
7
+ path: string;
8
+ message: string;
9
+ hint?: string;
10
+ }
11
+ declare class FormDefinitionError extends Error {
12
+ readonly issues: DefinitionIssue[];
13
+ constructor(issues: DefinitionIssue[]);
14
+ }
15
+
16
+ type ValidatorFn = (value: unknown, allValues: Record<string, unknown>) => string | null;
17
+ declare function validateFieldValue(field: FormField, value: unknown, allValues: Record<string, unknown>, validators?: Record<string, ValidatorFn>): string | null;
18
+
19
+ export { type DefinitionIssue as D, FormDefinitionError as F, type ValidatorFn as V, type DefinitionIssueCode as a, validateFieldValue as v };