@formhaus/core 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- import { F as FormField, a as FormStep, b as FormDefinition, S as ShowCondition } from './definition-H3WUR596.js';
2
- export { D as DefaultFieldType, c as FieldOption, d as FieldType, e as FieldValidation, f as FormAction, g as StepRoute } from './definition-H3WUR596.js';
1
+ import { F as FormField, a as FormStep, S as ShowCondition } from './definition-Bufih_Bx.js';
2
+ export { D as DefaultFieldType, b as FieldOption, c as FieldType, d as FieldValidation, e as FormAction, f as FormDefinition, g as StepRoute } from './definition-Bufih_Bx.js';
3
+ export { A as AfterStepChangeFn, B as BeforeStepChangeFn, a as BeforeSubmitFn, F as FormEngine, b as FormEngineOptions, S as StepChangeContext, c as StepValidateFn, d as SubmitFn } from './runtime-DOIq-Zce.js';
4
+ import { V as ValidatorFn } from './validate-field-glVVoN3E.js';
5
+ export { D as DefinitionIssue, a as DefinitionIssueCode, F as FormDefinitionError, v as validateFieldValue } from './validate-field-glVVoN3E.js';
6
+ export { C as CheckDefinitionOptions, c as checkDefinition, p as parseDefinition } from './check-definition-BTMV3Ziq.js';
3
7
 
4
8
  type FormAnalyticsEvent = {
5
9
  type: 'step_viewed';
@@ -25,105 +29,20 @@ type FormAnalyticsEvent = {
25
29
  } | {
26
30
  type: 'form_submitted';
27
31
  fieldCount: number;
28
- } | {
29
- type: 'form_abandoned';
30
- lastStepId: string;
31
- filledFields: number;
32
32
  };
33
33
 
34
- declare function getDefaultMessage(rule: string, params?: Record<string, unknown>): string;
34
+ declare function validateDefinition(input: unknown): string[];
35
35
 
36
- type ValidatorFn = (value: unknown, allValues: Record<string, unknown>) => string | null;
37
- declare function validateField(field: FormField, value: unknown, allValues: Record<string, unknown>, validators?: Record<string, ValidatorFn>): string | null;
36
+ type ValidationRule = 'required' | 'minLength' | 'maxLength' | 'min' | 'max' | 'pattern' | 'matchField';
37
+ declare function getDefaultMessage(rule: ValidationRule, params?: Record<string, unknown>): string;
38
38
 
39
39
  declare function validateStep(step: FormStep, values: Record<string, unknown>, validators?: Record<string, ValidatorFn>): Record<string, string>;
40
40
  declare function validateFields(fields: FormField[], values: Record<string, unknown>, validators?: Record<string, ValidatorFn>): Record<string, string>;
41
41
 
42
- type StepValidateFn = (stepId: string, values: Record<string, unknown>) => Promise<Record<string, string> | null | void>;
43
- interface StepChangeContext {
44
- fromStepId: string;
45
- toStepId: string;
46
- direction: 'next' | 'back';
47
- reason: 'next' | 'back' | 'autoAdvance' | 'skip';
48
- values: Record<string, unknown>;
49
- }
50
- type BeforeStepChangeFn = (context: StepChangeContext) => boolean | void | Promise<boolean | void>;
51
- type AfterStepChangeFn = (context: StepChangeContext) => void | Promise<void>;
52
- type BeforeSubmitFn = (values: Record<string, unknown>) => boolean | void | Promise<boolean | void>;
53
- type SubmitFn = (values: Record<string, unknown>, skippedSteps?: string[]) => void | Promise<void>;
54
- interface FormEngineOptions {
55
- onBeforeStepChange?: BeforeStepChangeFn;
56
- onAfterStepChange?: AfterStepChangeFn;
57
- onBeforeSubmit?: BeforeSubmitFn;
58
- onAfterSubmit?: SubmitFn;
59
- validators?: Record<string, ValidatorFn>;
60
- onStepValidate?: StepValidateFn;
61
- }
62
-
63
- declare class FormEngine {
64
- readonly definition: FormDefinition;
65
- values: Record<string, unknown>;
66
- errors: Record<string, string>;
67
- topLevelErrors: string[];
68
- currentStepIndex: number;
69
- fieldLoading: Record<string, boolean>;
70
- stepValidating: boolean;
71
- submitting: boolean;
72
- private readonly skipped;
73
- private validationEpoch;
74
- private operationEpoch;
75
- private readonly lifecycle;
76
- private readonly validators;
77
- private get onStepValidate();
78
- private readonly visibility;
79
- private readonly subscriptions;
80
- constructor(definition: FormDefinition, initialValues?: Record<string, unknown>, options?: FormEngineOptions);
81
- get isMultiStep(): boolean;
82
- get visibleSteps(): FormStep[];
83
- get currentStep(): FormStep | null;
84
- get visibleFields(): FormField[];
85
- get isFirstStep(): boolean;
86
- get isLastStep(): boolean;
87
- get canGoNext(): boolean;
88
- get progress(): {
89
- current: number;
90
- total: number;
91
- };
92
- subscribe(listener: () => void): () => void;
93
- getSnapshot(): number;
94
- subscribeField(key: string, listener: () => void): () => void;
95
- getFieldSnapshot(key: string): number;
96
- subscribeStructure(listener: () => void): () => void;
97
- getStructureSnapshot(): number;
98
- setValue(key: string, value: unknown): void;
99
- setErrors(errors: Record<string, string>): void;
100
- setFieldLoading(key: string, loading: boolean): void;
101
- cancelPendingActions(): void;
102
- nextStep(): boolean;
103
- nextStepAsync(reason?: 'next' | 'autoAdvance'): Promise<boolean>;
104
- prevStepAsync(): Promise<boolean>;
105
- skipStep(): boolean;
106
- skipStepAsync(submit?: SubmitFn): Promise<boolean>;
107
- isStepSkipped(stepId: string): boolean;
108
- submitAsync(submit: SubmitFn): Promise<boolean>;
109
- prevStep(): void;
110
- validate(): Record<string, string>;
111
- validateField(key: string): string | null;
112
- getSubmitValues(): Record<string, unknown>;
113
- goToStepWithField(key: string): void;
114
- reset(values?: Record<string, unknown>): void;
115
- private get internals();
116
- private notify;
117
- }
118
-
119
42
  declare function evaluateCondition(condition: ShowCondition, values: Record<string, unknown>): boolean;
120
43
 
121
- declare const isStepVisible: (step: FormStep, values: Record<string, unknown>) => boolean;
122
-
123
44
  declare function isVisible(field: Pick<FormField, 'show' | 'showAny'>, values: Record<string, unknown>): boolean;
124
45
 
125
- declare function validateDefinition(definition: FormDefinition): string[];
126
-
127
46
  declare class FormLifecycleError extends Error {
128
47
  readonly phase: 'afterStepChange' | 'afterSubmit';
129
48
  readonly committed = true;
@@ -131,6 +50,4 @@ declare class FormLifecycleError extends Error {
131
50
  constructor(phase: 'afterStepChange' | 'afterSubmit', cause: unknown);
132
51
  }
133
52
 
134
- declare function shouldApplyExternalErrors(engine: FormEngine, previous: Record<string, string> | undefined, next: Record<string, string>): boolean;
135
-
136
- export { type AfterStepChangeFn, type BeforeStepChangeFn, type BeforeSubmitFn, type FormAnalyticsEvent, FormDefinition, FormEngine, type FormEngineOptions, FormField, FormLifecycleError, FormStep, ShowCondition, type StepChangeContext, type StepValidateFn, type SubmitFn, type ValidatorFn, evaluateCondition, getDefaultMessage, isStepVisible, isVisible, shouldApplyExternalErrors, validateDefinition, validateField, validateFields, validateStep };
53
+ export { type FormAnalyticsEvent, FormField, FormLifecycleError, FormStep, ShowCondition, type ValidationRule, ValidatorFn, evaluateCondition, getDefaultMessage, isVisible, validateDefinition, validateFields, validateStep };
package/dist/index.js CHANGED
@@ -1,4 +1,2 @@
1
- function O(t){return t==null||t===""||Array.isArray(t)&&!t.length}function A(t,e){let i=e[t.field];return t.eq!==void 0?i===t.eq:t.neq!==void 0?i!==t.neq:t.in!==void 0?t.in.includes(i):t.notIn!==void 0?!t.notIn.includes(i):t.notEmpty===true?!O(i):true}function u(t,e){let i=r=>A(r,e);return (t.show??[]).every(i)&&(!t.showAny?.length||t.showAny.some(i))}var m=u;function U(t){return !!t.fields?.length&&!!t.steps?.length}function y(t){return !!t.steps?.some(e=>e.routes?.length)}function h(t){return [...t.show??[],...t.showAny??[]].map(e=>e.field)}function x(t){return t.steps?.length?t.steps.flatMap(e=>e.fields):t.fields??[]}function w(t,e){let i={};for(let r of t)r.defaultValue!==void 0&&(i[r.key]=r.defaultValue);return Object.assign(i,e)}function v(t,e){let i=new Set([...Object.keys(t),...Object.keys(e)]);return new Set([...i].filter(r=>!Object.is(t[r],e[r])))}function L(t){let e=t.steps??[],i=U(t)?['FormEngine rejects a definition with both "fields" and "steps".']:[],r=new Map,n=new Map;e.forEach((s,a)=>{r.has(s.id)&&i.push(`Duplicate step id "${s.id}".`),r.set(s.id,a);for(let o of s.fields)n.set(o.key,a);});for(let{key:s}of x(t))(s in Object.prototype||s==="prototype")&&i.push(`Reserved field key "${s}".`);return y(t)&&e.forEach((s,a)=>{for(let o of s.routes??[]){let l=o.to===null?null:r.get(o.to);(l===void 0||l!==null&&l<=a)&&i.push(`Invalid route from "${s.id}" to "${o.to}": targets must be later steps or null.`);for(let d of h(o))(n.get(d)??1/0)<=a||i.push(`Invalid route on "${s.id}": condition field "${d}" must belong to this or an earlier step.`);}}),i}function X(t){let e=t.steps??[],i=[];for(let r of e){let n=new Set((r.routes??[]).map(s=>s.to).filter(s=>s!==null));for(let s of n){let a=e.findIndex(d=>d.id===s),o=e[a+1],l=e[a]?.routes?.some(d=>!d.show?.length&&!d.showAny?.length);o&&n.has(o.id)&&!l&&i.push(`Route branch "${s}" from "${r.id}" continues into sibling branch "${o.id}". Add an unconditional route where it should continue.`);}}return i}function Q(t,e){let i=t.steps??[];if(!y(t))return i.filter(a=>m(a,e));let r=new Map(i.map((a,o)=>[a.id,o])),n=[],s={};for(let a=0;a<i.length;){let o=i[a];if(!m(o,s)){a++;continue}n.push(o),Object.assign(s,tt(o,e,s));let l=o.routes?.find(d=>u(d,s)&&(d.to===null||(r.get(d.to)??-1)>a&&m(i[r.get(d.to)],s)));if(l?.to===null)break;a=l?r.get(l.to):a+1;}return n}function Z(t,e,i){let r=t[i]??t[t.length-1],n=e.findIndex(a=>a.id===r?.id);if(n!==-1)return n;let s=new Map(e.map((a,o)=>[a.id,o]));for(let a=Math.min(i-1,t.length-1);a>=0;a--){let o=s.get(t[a].id);if(o!==void 0)return o}return 0}function tt(t,e,i){let r={...i};for(let s of t.fields)r[s.key]=e[s.key];let n={};for(let s of t.fields)u(s,r)&&e[s.key]!==void 0&&(n[s.key]=e[s.key]);return n}var $=class{constructor(e){this.definition=e;this.source=null;this.activeStepList=[];this.activeValueMap={};this.enabled=y(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=Q(this.definition,e);let i={};for(let r of this.activeStepList)Object.assign(i,tt(r,e,i));this.activeValueMap=i;}};function et(t){let e=[],i=new Map,r=x(t),n=new Set;for(let{key:o}of r)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,d,p)=>{let f=h(d);for(let c of f)n.has(c)||e.push(`${o} "${l}" has show condition referencing non-existent field "${c}"`);if(f.length)for(let c of p)i.set(c,[...i.get(c)??[],...f]);};for(let o of r){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 h(o))y(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:i,warnings:e}}function bt(t){let e=new Map,i=[];for(let r of t.keys()){if(e.has(r))continue;e.set(r,true);let n=[[r,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);i.push([...o.slice(o.indexOf(a)),a]);}else e.has(a)||(e.set(a,true),n.push([a,0]));}}return i}function j(t){let{graph:e,warnings:i}=et(t);for(let r of bt(e))i.push(`Circular show condition detected: ${r.join(" -> ")}`);return [...L(t),...i,...X(t)]}var K=class extends Error{constructor(i,r){super(`The action completed, but ${i} failed: ${r instanceof Error?r.message:String(r)}`);this.phase=i;this.committed=true;this.name="FormLifecycleError",this.cause=r;}};async function B(t,e){try{await e();}catch(i){throw new K(t,i)}}function it(t){return t.visibleSteps.map(e=>e.id).join(`
2
- `)}function I(t,e){let i=it(t);return ()=>it(t)!==i||Object.keys(e).some(r=>e[r]!==void 0&&!Object.is(t.values[r],e[r]))}function S(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 gt=new Set(["checkbox","switch"]);function vt(t,e){return O(t)||t===false&&gt.has(e.type)}function rt(t,e,i,r){let n=i[`min${e}`],s=i[`max${e}`];if(n!==void 0&&t<n)return i[`min${e}Message`]??S(`min${e}`,{min:n,unit:r});if(s!==void 0&&t>s)return i[`max${e}Message`]??S(`max${e}`,{max:s,unit:r})}function Ft(t,e){if(e.pattern!==void 0)try{return new RegExp(e.pattern).test(String(t))?void 0:e.patternMessage??S("pattern")}catch{return}}function F(t,e,i,r){let n=t.validation;if(!n)return null;if(vt(e,t))return n.required?typeof n.required=="string"?n.required:S("required"):null;let s=typeof e=="string"||Array.isArray(e)?rt(e.length,"Length",n,Array.isArray(e)?"items":void 0):typeof e=="number"?rt(e,"",n):void 0,a=n.matchField!==void 0&&e!==i[n.matchField]?n.matchFieldMessage??S("matchField"):void 0;return (s??Ft(e,n)??a??(n.validator?r?.[n.validator]?.(e,i):void 0))||null}function b(t,e,i){return R(t.fields,e,i)}function R(t,e,i){let r={};for(let n of t){if(!u(n,e))continue;let s=F(n,e[n.key],e,i);s&&(r[n.key]=s);}return r}function N(t,e,i=false){let r=t.errors;t.errors={},t.topLevelErrors=[];for(let[o,l]of Object.entries(e))t.visibility.isFieldVisible(o,t.values)?t.errors[o]=l:t.topLevelErrors.push(l);let n=Object.keys(e).find(o=>t.errors[o]!==void 0),s=i&&n&&t.isMultiStep?t.visibility.findStepIndex(n,t.values,t.currentStepIndex):null,a=s!==null&&s!==t.currentStepIndex;s!==null&&(t.currentStepIndex=s),t.notify({fieldKeys:v(r,t.errors),structureChanged:a});}function nt(t,e){let i=[];for(let r of t.visibility.allFields)r.validation?.matchField!==e||t.errors[r.key]===void 0||F(r,t.values[r.key],k(t),t.validators)||(delete t.errors[r.key],i.push(r.key));return i}function st(t){let e=new Set(t.visibleSteps.flatMap(r=>r.fields.map(n=>n.key))),i=Object.keys(t.errors).filter(r=>!e.has(r));for(let r of i)delete t.errors[r];return i}function k(t){return y(t.definition)?E(t):ot(t,{...t.values})}function ot(t,e){for(let i of [...t.skipped.values()].flat())delete e[i];return e}function C(t){let e=t.errors,i={};if(t.isMultiStep)for(let r of t.visibleSteps)t.skipped.has(r.id)||Object.assign(i,b(r,k(t),t.validators));else Object.assign(i,R(t.definition.fields??[],t.values,t.validators));return t.errors=i,t.notify({fieldKeys:v(e,i)}),i}function at(t,e){let i=t.visibility.fieldByKey.get(e);if(!i||!t.visibility.isFieldVisible(e,t.values))return null;let r=t.errors[e],n=F(i,t.values[e],k(t),t.validators);n?t.errors[e]=n:delete t.errors[e];let s=Object.is(r,t.errors[e])?[]:[e];return t.notify({fieldKeys:s}),n}function E(t){let e={},i=t.visibility.getVisibleFieldKeys(t.values,t.currentStepIndex);for(let r of i)t.values[r]!==void 0&&(e[r]=t.values[r]);return ot(t,e)}function lt(t,e){let i=t.values,r=t.errors,n=Object.keys(t.fieldLoading);t.validationEpoch++,t.operationEpoch++,t.submitting=false,t.values=w(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=v(i,t.values),a=new Set([...s,...v(r,t.errors),...n]);t.notify({fieldKeys:a,structureChanged:true,valuesChanged:s.size>0});}function dt(t){let e=t.currentStep?.fields??[],i={...t.values};for(let{key:r}of e)delete i[r];return Object.assign(i,w(e))}function P(t){return Q(t.definition,dt(t))[t.currentStepIndex+1]}function T(t){let e=t.currentStep,i=e.fields.map(({key:r})=>r);t.values=dt(t);for(let r of i)delete t.errors[r];return t.skipped.set(e.id,i),t.visibility.reconcileHidden(t.values,t.errors),t.notify({fieldKeys:i,structureChanged:true,valuesChanged:true}),i}function M(t){let e=t.currentStep;e&&t.skipped.delete(e.id);}async function G(t,e,i=false){if(t.submitting||t.stepValidating)return false;i||M(t);let r={...t.lifecycle},n=false,s=t.validationEpoch,a=++t.operationEpoch,o=E(t),l=I(t,o),d=()=>s!==t.validationEpoch||a!==t.operationEpoch||l();t.submitting=true,t.notify();try{if(d()||Object.keys(C(t)).length>0||d())return !1;if(r.onBeforeSubmit){let p=await r.onBeforeSubmit(o);if(d()||p===!1)return !1}if(d())return !1;if(r.onBeforeSubmit){if(Object.keys(C(t)).length>0||d())return !1;o=E(t);}return n=!0,await e(o,[...t.skipped.keys()]),a!==t.operationEpoch||await B("afterSubmit",()=>r.onAfterSubmit?.(o)),!0}catch(p){if(!n&&d())return false;throw p}finally{a===t.operationEpoch&&(t.submitting=false,t.notify());}}function Y(t){let e=t.currentStep;if(!e)return true;let i=b(e,k(t),t.validators);if(Object.keys(i).length===0)return false;let r={...t.errors};return Object.assign(t.errors,i),t.notify({fieldKeys:v(r,t.errors)}),true}function q(t,e){t.validationEpoch++,t.currentStepIndex=e,t.notify({structureChanged:true});}function ut(t){return t.isLastStep?false:(q(t,t.currentStepIndex+1),true)}function pt(t){return t.isMultiStep?(M(t),!Y(t)&&ut(t)):false}function ct(t){return !t.isMultiStep||!P(t)?false:(T(t),ut(t))}async function ft(t,e){if(!t.isMultiStep||t.stepValidating||t.submitting)return false;if(P(t))return H(t,"next","skip");let i=t.currentStep;if(!e||!i)return false;let r=t.values,n={...t.errors},s=false,a=T(t),o=t.values,l=I(t,{...o});try{return await G(t,async(d,p)=>{await e(d,p),s=!0;},!0)}finally{!s&&t.values===o&&!l()&&(t.values=r,t.errors={...n,...t.errors},t.skipped.delete(i.id),t.notify({fieldKeys:a,structureChanged:true,valuesChanged:true}));}}async function H(t,e,i=e){let r=i==="skip";if(!t.isMultiStep||t.stepValidating||t.submitting||!r&&(e==="next"?t.isLastStep:t.isFirstStep))return false;let n=t.currentStep,s=e==="next"&&!r;if(s&&M(t),s&&Y(t))return false;let a={...t.lifecycle},o=t.onStepValidate,l=false,p=t.currentStepIndex+(e==="next"?1:-1),f=r?P(t):t.visibleSteps[p];if(!f)return false;let c={fromStepId:n.id,toStepId:f.id,direction:e,reason:i,values:{...k(t)}},yt=t.validationEpoch,J=++t.operationEpoch,St=I(t,c.values),V=()=>yt!==t.validationEpoch||J!==t.operationEpoch||t.currentStep?.id!==n.id||St();t.stepValidating=true,t.notify();try{if(V())return !1;if(s&&o){let g=await o(n.id,c.values);if(V())return !1;if(g&&Object.keys(g).length>0)return N(t,g),!1}if(a.onBeforeStepChange){let g=await a.onBeforeStepChange(c);if(V()||g===!1)return !1}return V()||s&&Y(t)?!1:(l=!0,r&&T(t),q(t,p),await B("afterStepChange",()=>a.onAfterStepChange?.(c)),!0)}catch(g){if(!l&&V())return false;throw g}finally{J===t.operationEpoch&&(t.stepValidating=false,t.notify());}}function ht(t){t.isMultiStep&&!t.isFirstStep&&q(t,t.currentStepIndex-1);}function mt(t,e){if(!t.isMultiStep)return;let i=t.visibility.findStepIndex(e,t.values,t.currentStepIndex);i===t.currentStepIndex?t.notify():i!==null&&q(t,i);}var z=class{constructor(){this.version=0;this.listeners=new Set;this.fieldVersions=new Map;this.fieldListeners=new Map;this.structureVersion=0;this.structureListeners=new Set;}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getSnapshot(){return this.version}subscribeField(e,i){let r=this.fieldListeners.get(e)??new Set;return r.add(i),this.fieldListeners.set(e,r),()=>{r.delete(i),r.size===0&&this.fieldListeners.delete(e);}}getFieldSnapshot(e){return this.fieldVersions.get(e)??0}subscribeStructure(e){return this.structureListeners.add(e),()=>this.structureListeners.delete(e)}getStructureSnapshot(){return this.structureVersion}notify({fieldKeys:e=[],structureChanged:i=false}={}){for(let r of new Set(e))this.notifyField(r);i&&this.notifyStructure(),this.version++;for(let r of this.listeners)r();}notifyField(e){this.fieldVersions.set(e,(this.fieldVersions.get(e)??0)+1);for(let i of this.fieldListeners.get(e)??[])i();}notifyStructure(){this.structureVersion++;for(let e of this.structureListeners)e();}};function _(t,e){for(let i of h(t)){let r=e.get(i)??new Set;r.add(t),e.set(i,r);}}var W=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=x(e),this.fieldByKey=new Map(this.allFields.map(i=>[i.key,i])),this.path=new $(e);for(let i of e.steps??[])for(let r of i.fields)this.stepByFieldKey.set(r.key,i);this.buildIndexes();}markChanged(e,i){(e||i)&&this.path.invalidate(),e?(this.visibilityDirty=true,this.canGoNextDirty=true):i&&(this.canGoNextDirty=true);}state(e,i){return this.recomputeVisibility(e,i),this.cache}getCanGoNext(e,i,r){if(this.recomputeVisibility(e,i),!this.canGoNextDirty)return this.cache.canGoNext;this.canGoNextDirty=false;let n=this.cache.currentStep,s=n?b(n,this.conditionValues(e),r):{};return this.cache.canGoNext=this.isMultiStep&&Object.keys(s).length===0,this.cache.canGoNext}findStepIndex(e,i,r){let s=this.state(i,r).visibleSteps.findIndex(a=>a.fields.some(o=>o.key===e));return s===-1?null:s}affectsStructure(e,i){return this.routeFields.has(e)||this.fieldDependents.has(e)||this.stepDependents.has(e)||i.size>0}cascadeHiddenFields(e,i,r){return this.path.invalidate(),this.hasRoutes?this.reconcileHidden(i,r):this.drainQueue(new Set([e]),i,r)}reconcileHidden(e,i){this.path.invalidate();let r=new Set([...this.fieldDependents.keys(),...this.stepDependents.keys()]);return this.drainQueue(r,e,i)}drainQueue(e,i,r){let n=[...e],s=new Set(n),a=new Set,o=l=>{delete i[l],delete r[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 d=n[l];s.delete(d),this.clearHiddenFields(this.fieldDependents.get(d),i,o),this.clearHiddenSteps(this.stepDependents.get(d),i,o);}return a}isFieldVisible(e,i){let r=this.fieldByKey.get(e);if(!r||!u(r,this.conditionValues(i)))return false;let n=this.stepByFieldKey.get(e);return !n||this.path.steps(i).includes(n)}getVisibleFieldKeys(e,i){if(this.hasRoutes)return new Set(Object.keys(this.path.values(e)));let r=new Set,n=this.isMultiStep?this.state(e,i).visibleSteps.flatMap(s=>s.fields):this.definition.fields??[];for(let s of n)u(s,this.conditionValues(e))&&r.add(s.key);return r}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)_(e,this.fieldDependents);for(let e of this.definition.steps??[]){_(e,this.stepDependents);for(let i of e.routes??[])for(let r of h(i))this.routeFields.add(r);}}recomputeVisibility(e,i){if(!this.visibilityDirty)return;if(this.visibilityDirty=false,!this.isMultiStep){this.cache.visibleSteps=[],this.cache.currentStep=null,this.cache.visibleFields=(this.definition.fields??[]).filter(s=>u(s,this.conditionValues(e)));return}this.cache.visibleSteps=this.path.steps(e);let r=this.cache.visibleSteps;this.cache.currentStep=r[i]??r[r.length-1]??null;let n=this.cache.currentStep;this.cache.visibleFields=n?n.fields.filter(s=>u(s,this.conditionValues(e))):[];}clearHiddenFields(e,i,r){for(let n of e??[]){let s=this.stepByFieldKey.get(n.key);this.hasRoutes&&s&&!this.path.steps(i).includes(s)||u(n,this.conditionValues(i))||i[n.key]===void 0||r(n.key);}}clearHiddenSteps(e,i,r){for(let n of e??[])if(!m(n,this.conditionValues(i)))for(let s of n.fields)i[s.key]!==void 0&&r(s.key);}};var D=class{constructor(e,i,r){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 z;let n=L(e);if(n.length)throw new Error(n.join(`
3
- `));this.lifecycle=r??{},this.validators=r?.validators??{},this.visibility=new W(e);let s=j(e);for(let{key:a,validation:o}of this.visibility.allFields){let l=o?.validator;l&&!this.validators[l]&&s.push(`Field "${a}" references unknown validator "${l}".`);}for(let a of s)console.warn(`[FormEngine] ${a}`);this.values=w(this.visibility.allFields,i),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,i){return this.subscriptions.subscribeField(e,i)}getFieldSnapshot(e){return this.subscriptions.getFieldSnapshot(e)}subscribeStructure(e){return this.subscriptions.subscribeStructure(e)}getStructureSnapshot(){return this.subscriptions.getStructureSnapshot()}setValue(e,i){let r=this.isMultiStep?this.visibleSteps:null,n=!Object.is(this.values[e],i),s=this.errors[e]!==void 0;this.values[e]=i,delete this.errors[e];for(let[f,c]of this.skipped)n&&c.includes(e)&&this.skipped.delete(f);let a=this.visibility.cascadeHiddenFields(e,this.values,this.errors),o=nt(this.internals,e),l=new Set([...a,...o]);(n||s)&&l.add(e);let d=n||a.size>0,p=d&&this.visibility.affectsStructure(e,a);if(r&&p){this.visibility.markChanged(true,true),this.currentStepIndex=Z(r,this.visibleSteps,this.currentStepIndex);for(let f of st(this.internals))l.add(f);}this.notify({fieldKeys:l,structureChanged:p,valuesChanged:d});}setErrors(e){N(this.internals,e,true);}setFieldLoading(e,i){let r=this.fieldLoading[e]===true;i?this.fieldLoading[e]=true:delete this.fieldLoading[e],this.notify({fieldKeys:r===i?[]:[e]});}cancelPendingActions(){this.validationEpoch++,this.operationEpoch++,this.stepValidating=false,this.submitting=false,this.notify();}nextStep(){return pt(this.internals)}nextStepAsync(e="next"){return H(this.internals,"next",e)}prevStepAsync(){return H(this.internals,"back")}skipStep(){return ct(this.internals)}skipStepAsync(e){return ft(this.internals,e)}isStepSkipped(e){return this.skipped.has(e)}submitAsync(e){return G(this.internals,e)}prevStep(){ht(this.internals);}validate(){return C(this.internals)}validateField(e){return at(this.internals,e)}getSubmitValues(){return E(this.internals)}goToStepWithField(e){mt(this.internals,e);}reset(e){lt(this.internals,e);}get internals(){return this}notify(e={}){this.visibility.markChanged(!!e.structureChanged,!!e.valuesChanged),this.subscriptions.notify(e);}};function xt(t,e){let i=Object.keys(e);return i.length===Object.keys(t).length&&i.every(r=>t[r]===e[r])}function wt(t,e){return Object.entries(e).every(([i,r])=>t.errors[i]===r||t.topLevelErrors.includes(r))}function kt(t,e,i){return !e||!xt(e,i)||!wt(t,i)}export{D as FormEngine,K as FormLifecycleError,A as evaluateCondition,S as getDefaultMessage,m as isStepVisible,u as isVisible,kt as shouldApplyExternalErrors,j as validateDefinition,F as validateField,R as validateFields,b as validateStep};//# sourceMappingURL=index.js.map
1
+ export{a as FormDefinitionError,e as FormEngine,b as checkDefinition,c as parseDefinition,d as validateDefinition}from'./chunk-OMINRKEL.js';export{f as FormLifecycleError,b as evaluateCondition,g as getDefaultMessage,h as isVisible,k as validateFieldValue,m as validateFields,l as validateStep}from'./chunk-BXI5P7PF.js';//# sourceMappingURL=index.js.map
4
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -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/validate-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/engine/external-errors.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","detectCycles","visiting","cycles","start","stack","frame","neighbor","nodes","node","validateDefinition","cycle","FormLifecycleError","phase","cause","afterCommit","callback","error","activePath","engine","watchCheckedInputs","checked","path","getDefaultMessage","rule","params","BOOLEAN_TYPES","isEmpty","boundError","size","rules","unit","min","max","patternError","validateField","allValues","validators","sizeError","matchError","validateStep","validateFields","errors","applyValidationErrors","navigate","previousErrors","message","firstErrorKey","targetIndex","structureChanged","clearResolvedMatchErrors","cleared","getValidationValues","pruneOffPathErrors","pathFields","pruned","getSubmitValues","withoutSkipped","validateForm","validateOne","previousError","visibleKeys","resetEngine","previousValues","loadingFields","changedValues","changedFields","resetValues","skipTarget","skipCurrentStep","includeCurrentStep","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","FormEngine","options","validation","name","warning","total","previousSteps","valueChanged","hadError","stepId","revalidated","loading","sameErrors","holdsErrors","shouldApplyExternalErrors"],"mappings":"AAEO,SAASA,EAAQC,CAAAA,CAAyB,CAC/C,OAA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,CAAQ,aAAa,CAAA,CAC/E,KAAK,aAAA,CAAc,MAAA,CAAOA,CAAO,EACnC,CACF,EChLA,SAASW,EAAAA,CAAW3K,CAAAA,CAAkCC,EAAuC,CAC3F,IAAMC,EAAO,MAAA,CAAO,IAAA,CAAKD,CAAI,CAAA,CAC7B,OAAOC,CAAAA,CAAK,MAAA,GAAW,OAAO,IAAA,CAAKF,CAAQ,EAAE,MAAA,EAAUE,CAAAA,CAAK,MAAOC,CAAAA,EAAQH,CAAAA,CAASG,CAAG,CAAA,GAAMF,EAAKE,CAAG,CAAC,CACxG,CAEA,SAASyK,GAAYjH,CAAAA,CAAoBuB,CAAAA,CAAyC,CAChF,OAAO,OAAO,OAAA,CAAQA,CAAM,EAAE,KAAA,CAAM,CAAC,CAAC/E,CAAAA,CAAKmF,CAAO,CAAA,GAChD3B,CAAAA,CAAO,OAAOxD,CAAG,CAAA,GAAMmF,GAAW3B,CAAAA,CAAO,cAAA,CAAe,SAAS2B,CAAO,CACzE,CACH,CAEO,SAASuF,EAAAA,CACdlH,CAAAA,CACA3D,EACAC,CAAAA,CACS,CACT,OAAO,CAACD,CAAAA,EAAY,CAAC2K,EAAAA,CAAW3K,EAAUC,CAAI,CAAA,EAAK,CAAC2K,EAAAA,CAAYjH,CAAAA,CAAQ1D,CAAI,CAC9E","file":"index.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 (!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","import { definitionErrors, routeFallthroughWarnings } from '../engine/step-routes';\nimport type { FormDefinition } from '../types';\nimport { analyzeDefinition } from './definition-analysis';\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(definition: FormDefinition): string[] {\n const { graph, warnings } = analyzeDefinition(definition);\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","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 firstErrorKey = Object.keys(errors).find((key) => engine.errors[key] !== undefined);\n const targetIndex = navigate && firstErrorKey && engine.isMultiStep\n ? engine.visibility.findStepIndex(firstErrorKey, engine.values, engine.currentStepIndex)\n : null;\n const structureChanged = targetIndex !== null && targetIndex !== engine.currentStepIndex;\n if (targetIndex !== null) engine.currentStepIndex = targetIndex;\n engine.notify({ fieldKeys: getChangedKeys(previousErrors, engine.errors), structureChanged });\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): 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 engine.notify({ fieldKeys: getChangedKeys(previousErrors, errors) });\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)).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)).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 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 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 errors = 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 const warnings = validateDefinition(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 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 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 { FormEngine } from './runtime';\n\nfunction sameErrors(previous: Record<string, string>, next: Record<string, string>): boolean {\n const keys = Object.keys(next);\n return keys.length === Object.keys(previous).length && keys.every((key) => previous[key] === next[key]);\n}\n\nfunction holdsErrors(engine: FormEngine, errors: Record<string, string>): boolean {\n return Object.entries(errors).every(([key, message]) => (\n engine.errors[key] === message || engine.topLevelErrors.includes(message)\n ));\n}\n\nexport function shouldApplyExternalErrors(\n engine: FormEngine,\n previous: Record<string, string> | undefined,\n next: Record<string, string>,\n): boolean {\n return !previous || !sameErrors(previous, next) || !holdsErrors(engine, next);\n}\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,25 @@
1
+ export { j as CloudCallbacks, k as CloudControllerOptions, l as CloudState, m as cloudStateFor, n as createCloudController, o as initialCloudState } from './controller-x_emKgtv.js';
2
+ import { F as FormEngine } from './runtime-DOIq-Zce.js';
3
+ import './definition-Bufih_Bx.js';
4
+ import './validate-field-glVVoN3E.js';
5
+
6
+ interface Searchable {
7
+ querySelector(selector: string): unknown;
8
+ }
9
+ interface Focusable extends Searchable {
10
+ focus(options?: {
11
+ preventScroll?: boolean;
12
+ }): void;
13
+ scrollIntoView?(options?: {
14
+ block?: 'center' | 'nearest';
15
+ }): void;
16
+ matches(selector: string): boolean;
17
+ }
18
+ declare function focusProblem(root: Searchable | null, notice?: Focusable | null): void;
19
+
20
+ declare function shouldApplyExternalErrors(engine: FormEngine, previous: Record<string, string> | undefined, next: Record<string, string>): boolean;
21
+
22
+ declare function autoAdvance(engine: FormEngine): Promise<boolean>;
23
+ declare function fieldDomId(formId: string | undefined, key: string): string;
24
+
25
+ export { autoAdvance, fieldDomId, focusProblem, shouldApplyExternalErrors };
@@ -0,0 +1,2 @@
1
+ import {f,i,j,g,d,e,a,c,b}from'./chunk-EPXEKDCK.js';import {z as z$1}from'./chunk-BXI5P7PF.js';var q={multiselect:"list",checkbox:"flag",switch:"flag",number:"number",file:"file"};function p(e){return [...e.fields??[],...(e.steps??[]).flatMap(n=>n.fields)]}function k(e){return q[e.type]??"text"}function G(e,n){if(!Array.isArray(e.options))return true;let r=new Set(e.options.map(i=>String(i.value)));return (Array.isArray(n)?n:[n]).every(i=>r.has(String(i)))}function L(e,n,r){if(e&&k(e)!==k(n))return false;switch(k(n)){case "list":return Array.isArray(r);case "flag":return typeof r=="boolean";case "number":return typeof r=="number";case "text":return typeof r=="string";default:return e!==void 0}}function D(e,n,r){let i=new Map(r?p(r).map(o=>[o.key,o]):[]),u={};for(let o of p(n)){let s=e[o.key];s!=null&&L(i.get(o.key),o,s)&&G(o,s)&&(u[o.key]=s);}return u}function O(e,n){let r=new Set(p(e).map(o=>o.key)),i={},u=new Set;for(let[o,s]of Object.entries(n))r.has(o)?i[o]=s:u.add(s);return {fields:i,other:[...u]}}function P(e,n,r,i){let u={};for(let o of p(e)){let s=n[o.key]!==void 0&&n[o.key]!==null&&n[o.key]!=="";s&&!(o.key in r)?u[o.key]=b:i[o.key]&&(!s||o.key in r)&&(u[o.key]=i[o.key]);}return u}var y={definition:null,version:null,settings:{},loadError:null,errors:{},notice:null,initialValues:null,revision:0,attempt:0,done:false};function N(e){return e?{...y,definition:e.definition,version:e.version??null,settings:f(e.settings)}:y}function V(e,n=[]){return {tone:"error",message:e.message,action:e.action,details:n}}function $(e$1,n){let r=new AbortController,i$1=t=>i({...e$1,version:t.version,renderToken:t.renderToken}),u=i(e$1),o=e$1.initialForm,s=()=>!r.signal.aborted,l=y,f$1=t=>{l={...l,...t},n.onChange(l);},g$1=t=>f$1({...t,attempt:l.attempt+1});function h(t){u=i$1(t);let c=e$1.draftStore?.load(e$1.id,t.version)??null;f$1({...N(t),revision:l.revision,attempt:l.attempt,initialValues:c});}async function T(t,c$1){let a$1=l.definition;try{let d$1=await g(e$1,r.signal,t.version);if(!s())return;if(d$1.version===void 0||d$1.version<(t.version??0))throw new d(409,"form_updated");let m=a$1?D(c$1,d$1.definition,a$1):{};u=i$1(d$1),g$1({definition:d$1.definition,version:d$1.version,settings:f(d$1.settings),initialValues:m,revision:l.revision+1,errors:P(d$1.definition,c$1,m,t.errors??{}),notice:{tone:"info",message:a,action:null,details:[]}});}catch{s()&&g$1({notice:{tone:"error",...c(409,"form_updated"),details:[]}});}}async function j$1(t,c){let a=t instanceof d?t:e(t);if(a.code==="form_updated"&&a.version!==void 0)return T(a,c);if(a.status!==422)return g$1({notice:V(a)});let d$1=a.errors??{},m=l.definition?O(l.definition,d$1):{fields:d$1,other:[]};g$1({errors:m.fields,notice:m.other.length>0?V(a,m.other):null});}return {start(){if(l.loadError&&f$1({loadError:null}),o){h(o),o=void 0;return}g(e$1,r.signal).then(t=>{s()&&h(t);},t=>{s()&&(f$1({loadError:t}),n.onError?.(t));});},dispose(){r.abort();},saveDraft(t){l.definition&&!l.done&&e$1.draftStore?.save(e$1.id,l.version??void 0,j(l.definition,t));},again(){f$1({done:false,errors:{},notice:null,initialValues:null,revision:l.revision+1});},async submit(t,c){l.notice&&f$1({notice:null});try{let a=await u(t,c);if(!s())return;e$1.draftStore?.clear(e$1.id),f$1({done:!0}),n.onSuccess?.(a);}catch(a){throw s()&&(await j$1(a,t),n.onError?.(a)),a}}}}var _='input:not([type="hidden"]):not(:disabled), select:not(:disabled), textarea:not(:disabled), button:not(:disabled)';function I(e,n){n.scrollIntoView?.({block:"center"}),e.focus({preventScroll:true});}function z(e,n){if(n)return I(n,n);let r=e?.querySelector('[aria-invalid="true"]');r&&I(r.matches(_)?r:r.querySelector(_)??r,r);}function B(e,n){let r=Object.keys(n);return r.length===Object.keys(e).length&&r.every(i=>e[i]===n[i])}function H(e,n){return Object.entries(n).every(([r,i])=>e.errors[r]===i||e.topLevelErrors.includes(i))}function U(e,n,r){return !n||!B(n,r)||!H(e,r)}function ie(e){return z$1(e,"next","autoAdvance")}var M=e=>e.replace(/[^A-Za-z0-9_-]/g,"-");function se(e,n){return `${e?M(e):"fh"}-${M(n)}`}export{ie as autoAdvance,N as cloudStateFor,$ as createCloudController,se as fieldDomId,z as focusProblem,y as initialCloudState,U as shouldApplyExternalErrors};//# sourceMappingURL=internal.js.map
2
+ //# sourceMappingURL=internal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cloud/carry.ts","../src/cloud/controller.ts","../src/cloud/focus.ts","../src/engine/external-errors.ts","../src/internal/index.ts"],"names":["SHAPES","fieldsOf","definition","step","shapeOf","field","allowed","value","options","option","item","fits","previous","next","carryValues","values","before","kept","splitErrors","errors","known","fields","other","key","message","updatedErrors","sent","rejected","answered","ANSWER_AGAIN","initialCloudState","cloudStateFor","form","parseSettings","errorNotice","error","details","createCloudController","callbacks","controller","submitterFor","createSubmitter","submitter","initial","alive","state","update","patch","report","show","draft","refresh","fetchForm","CloudError","FORM_UPDATED_MESSAGE","failureFor","fail","cloud","networkError","split","draftValues","skippedSteps","submission","CONTROLS","reveal","target","scrollTo","focusProblem","root","notice","invalid","sameErrors","keys","holdsErrors","engine","shouldApplyExternalErrors","autoAdvance","changeStep","clean","fieldDomId","formId"],"mappings":"+FAGA,IAAMA,CAAAA,CAAiC,CACrC,WAAA,CAAa,MAAA,CACb,QAAA,CAAU,MAAA,CACV,MAAA,CAAQ,MAAA,CACR,MAAA,CAAQ,QAAA,CACR,IAAA,CAAM,MACR,CAAA,CAEA,SAASC,CAAAA,CAASC,CAAAA,CAAyC,CACzD,OAAO,CAAC,GAAIA,CAAAA,CAAW,MAAA,EAAU,EAAC,CAAI,GAAA,CAAIA,CAAAA,CAAW,KAAA,EAAS,EAAC,EAAG,OAAA,CAASC,CAAAA,EAASA,CAAAA,CAAK,MAAM,CAAC,CAClG,CAEA,SAASC,CAAAA,CAAQC,CAAAA,CAA0B,CACzC,OAAOL,CAAAA,CAAOK,CAAAA,CAAM,IAAI,CAAA,EAAK,MAC/B,CAEA,SAASC,CAAAA,CAAQD,CAAAA,CAAkBE,CAAAA,CAAyB,CAC1D,GAAI,CAAC,KAAA,CAAM,OAAA,CAAQF,CAAAA,CAAM,OAAO,CAAA,CAAG,OAAO,MAC1C,IAAMG,CAAAA,CAAU,IAAI,GAAA,CAAIH,CAAAA,CAAM,OAAA,CAAQ,GAAA,CAAKI,CAAAA,EAAW,MAAA,CAAOA,CAAAA,CAAO,KAAK,CAAC,CAAC,CAAA,CAC3E,OAAA,CAAQ,KAAA,CAAM,OAAA,CAAQF,CAAK,CAAA,CAAIA,CAAAA,CAAQ,CAACA,CAAK,CAAA,EAAG,KAAA,CAAOG,CAAAA,EAASF,CAAAA,CAAQ,GAAA,CAAI,MAAA,CAAO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,CAAAA,CAASvE,CAAAA,EAAkBA,CAAAA,CAAM,OAAA,CAAQ,iBAAA,CAAmB,GAAG,CAAA,CAE9D,SAASwE,EAAAA,CAAWC,CAAAA,CAA4BzD,CAAAA,CAAqB,CAC1E,OAAO,CAAA,EAAGyD,CAAAA,CAASF,CAAAA,CAAME,CAAM,CAAA,CAAI,IAAI,CAAA,CAAA,EAAIF,CAAAA,CAAMvD,CAAG,CAAC,CAAA,CACvD","file":"internal.js","sourcesContent":["import type { FormDefinition, FormField } from '../types';\nimport { ANSWER_AGAIN } from './failures';\n\nconst SHAPES: Record<string, string> = {\n multiselect: 'list',\n checkbox: 'flag',\n switch: 'flag',\n number: 'number',\n file: 'file',\n};\n\nfunction fieldsOf(definition: FormDefinition): FormField[] {\n return [...(definition.fields ?? []), ...(definition.steps ?? []).flatMap((step) => step.fields)];\n}\n\nfunction shapeOf(field: FormField): string {\n return SHAPES[field.type] ?? 'text';\n}\n\nfunction allowed(field: FormField, value: unknown): boolean {\n if (!Array.isArray(field.options)) return true;\n const options = new Set(field.options.map((option) => String(option.value)));\n return (Array.isArray(value) ? value : [value]).every((item) => options.has(String(item)));\n}\n\nfunction fits(previous: FormField | undefined, next: FormField, value: unknown): boolean {\n if (previous && shapeOf(previous) !== shapeOf(next)) return false;\n switch (shapeOf(next)) {\n case 'list': return Array.isArray(value);\n case 'flag': return typeof value === 'boolean';\n case 'number': return typeof value === 'number';\n case 'text': return typeof value === 'string';\n default: return previous !== undefined;\n }\n}\n\nexport function carryValues(\n values: Record<string, unknown>,\n next: FormDefinition,\n previous?: FormDefinition,\n): Record<string, unknown> {\n const before = new Map(previous ? fieldsOf(previous).map((field) => [field.key, field]) : []);\n const kept: Record<string, unknown> = {};\n for (const field of fieldsOf(next)) {\n const value = values[field.key];\n if (value === undefined || value === null) continue;\n if (fits(before.get(field.key), field, value) && allowed(field, value)) kept[field.key] = value;\n }\n return kept;\n}\n\nexport function splitErrors(definition: FormDefinition, errors: Record<string, string>) {\n const known = new Set(fieldsOf(definition).map((field) => field.key));\n const fields: Record<string, string> = {};\n const other = new Set<string>();\n for (const [key, message] of Object.entries(errors)) {\n if (known.has(key)) fields[key] = message;\n else other.add(message);\n }\n return { fields, other: [...other] };\n}\n\nexport function updatedErrors(\n next: FormDefinition,\n sent: Record<string, unknown>,\n kept: Record<string, unknown>,\n rejected: Record<string, string>,\n): Record<string, string> {\n const errors: Record<string, string> = {};\n for (const field of fieldsOf(next)) {\n const answered = sent[field.key] !== undefined && sent[field.key] !== null && sent[field.key] !== '';\n if (answered && !(field.key in kept)) errors[field.key] = ANSWER_AGAIN;\n else if (rejected[field.key] && (!answered || field.key in kept)) errors[field.key] = rejected[field.key];\n }\n return errors;\n}\n","import type { FormDefinition } from '../types';\nimport { carryValues, splitErrors, updatedErrors } from './carry';\nimport { createSubmitter, fetchForm, type CloudClientOptions, type CloudSubmission } from './client';\nimport { draftValues, type DraftStore } from './draft';\nimport { parseSettings, type CloudSettings, type PublishedForm } from './envelope';\nimport { CloudError, networkError } from './error';\nimport { FORM_UPDATED_MESSAGE, failureFor, type CloudAction } from './failures';\n\nexport interface CloudNotice {\n tone: 'error' | 'info';\n message: string;\n action: CloudAction;\n details: string[];\n}\n\nexport interface CloudState {\n definition: FormDefinition | null;\n version: number | null;\n settings: CloudSettings;\n loadError: Error | null;\n errors: Record<string, string>;\n notice: CloudNotice | null;\n initialValues: Record<string, unknown> | null;\n revision: number;\n attempt: number;\n done: boolean;\n}\n\nexport interface CloudCallbacks {\n onChange(state: CloudState): void;\n onSuccess?(submission: CloudSubmission): void;\n onError?(error: unknown): void;\n}\n\nexport interface CloudControllerOptions extends CloudClientOptions {\n initialForm?: PublishedForm;\n extraBody?: () => Record<string, unknown>;\n draftStore?: DraftStore;\n}\n\nexport const initialCloudState: CloudState = {\n definition: null, version: null, settings: {}, loadError: null, errors: {}, notice: null,\n initialValues: null, revision: 0, attempt: 0, done: false,\n};\n\nexport function cloudStateFor(form?: PublishedForm): CloudState {\n if (!form) return initialCloudState;\n return { ...initialCloudState, definition: form.definition, version: form.version ?? null, settings: parseSettings(form.settings) };\n}\n\nfunction errorNotice(error: CloudError, details: string[] = []): CloudNotice {\n return { tone: 'error', message: error.message, action: error.action, details };\n}\n\nexport function createCloudController(options: CloudControllerOptions, callbacks: CloudCallbacks) {\n const controller = new AbortController();\n const submitterFor = (form: PublishedForm) => createSubmitter({ ...options, version: form.version, renderToken: form.renderToken });\n let submitter = createSubmitter(options);\n let initial = options.initialForm;\n const alive = () => !controller.signal.aborted;\n let state = initialCloudState;\n const update = (patch: Partial<CloudState>) => {\n state = { ...state, ...patch };\n callbacks.onChange(state);\n };\n const report = (patch: Partial<CloudState>) => update({ ...patch, attempt: state.attempt + 1 });\n\n function show(form: PublishedForm) {\n submitter = submitterFor(form);\n const draft = options.draftStore?.load(options.id, form.version) ?? null;\n update({ ...cloudStateFor(form), revision: state.revision, attempt: state.attempt, initialValues: draft });\n }\n\n async function refresh(error: CloudError, sent: Record<string, unknown>) {\n const before = state.definition;\n try {\n const next = await fetchForm(options, controller.signal, error.version);\n if (!alive()) return;\n if (next.version === undefined || next.version < (error.version ?? 0)) throw new CloudError(409, 'form_updated');\n const kept = before ? carryValues(sent, next.definition, before) : {};\n submitter = submitterFor(next);\n report({\n definition: next.definition,\n version: next.version,\n settings: parseSettings(next.settings),\n initialValues: kept,\n revision: state.revision + 1,\n errors: updatedErrors(next.definition, sent, kept, error.errors ?? {}),\n notice: { tone: 'info', message: FORM_UPDATED_MESSAGE, action: null, details: [] },\n });\n } catch {\n if (alive()) report({ notice: { tone: 'error', ...failureFor(409, 'form_updated'), details: [] } });\n }\n }\n\n async function fail(error: unknown, values: Record<string, unknown>) {\n const cloud = error instanceof CloudError ? error : networkError(error);\n if (cloud.code === 'form_updated' && cloud.version !== undefined) return refresh(cloud, values);\n if (cloud.status !== 422) return report({ notice: errorNotice(cloud) });\n const errors = cloud.errors ?? {};\n const split = state.definition ? splitErrors(state.definition, errors) : { fields: errors, other: [] };\n report({ errors: split.fields, notice: split.other.length > 0 ? errorNotice(cloud, split.other) : null });\n }\n\n return {\n start() {\n if (state.loadError) update({ loadError: null });\n if (initial) {\n show(initial);\n initial = undefined;\n return;\n }\n fetchForm(options, controller.signal).then(\n (form) => { if (alive()) show(form); },\n (error: Error) => {\n if (!alive()) return;\n update({ loadError: error });\n callbacks.onError?.(error);\n },\n );\n },\n dispose() {\n controller.abort();\n },\n saveDraft(values: Record<string, unknown>) {\n if (state.definition && !state.done) options.draftStore?.save(options.id, state.version ?? undefined, draftValues(state.definition, values));\n },\n again() {\n update({ done: false, errors: {}, notice: null, initialValues: null, revision: state.revision + 1 });\n },\n async submit(values: Record<string, unknown>, skippedSteps?: string[]) {\n if (state.notice) update({ notice: null });\n try {\n const submission = await submitter(values, skippedSteps);\n if (!alive()) return;\n options.draftStore?.clear(options.id);\n update({ done: true });\n callbacks.onSuccess?.(submission);\n } catch (error) {\n if (!alive()) throw error;\n await fail(error, values);\n callbacks.onError?.(error);\n throw error;\n }\n },\n };\n}\n","interface Searchable {\n querySelector(selector: string): unknown;\n}\n\ninterface Focusable extends Searchable {\n focus(options?: { preventScroll?: boolean }): void;\n scrollIntoView?(options?: { block?: 'center' | 'nearest' }): void;\n matches(selector: string): boolean;\n}\n\nconst CONTROLS = 'input:not([type=\"hidden\"]):not(:disabled), select:not(:disabled), textarea:not(:disabled), button:not(:disabled)';\n\nfunction reveal(target: Focusable, scrollTo: Focusable): void {\n scrollTo.scrollIntoView?.({ block: 'center' });\n target.focus({ preventScroll: true });\n}\n\nexport function focusProblem(root: Searchable | null, notice?: Focusable | null): void {\n if (notice) return reveal(notice, notice);\n const invalid = root?.querySelector('[aria-invalid=\"true\"]') as Focusable | null | undefined;\n if (invalid) reveal(invalid.matches(CONTROLS) ? invalid : (invalid.querySelector(CONTROLS) as Focusable | null) ?? invalid, invalid);\n}\n","import type { FormEngine } from './runtime';\n\nfunction sameErrors(previous: Record<string, string>, next: Record<string, string>): boolean {\n const keys = Object.keys(next);\n return keys.length === Object.keys(previous).length && keys.every((key) => previous[key] === next[key]);\n}\n\nfunction holdsErrors(engine: FormEngine, errors: Record<string, string>): boolean {\n return Object.entries(errors).every(([key, message]) => (\n engine.errors[key] === message || engine.topLevelErrors.includes(message)\n ));\n}\n\nexport function shouldApplyExternalErrors(\n engine: FormEngine,\n previous: Record<string, string> | undefined,\n next: Record<string, string>,\n): boolean {\n return !previous || !sameErrors(previous, next) || !holdsErrors(engine, next);\n}\n","export { cloudStateFor, createCloudController, initialCloudState, type CloudCallbacks, type CloudControllerOptions, type CloudState } from '../cloud/controller';\nexport { focusProblem } from '../cloud/focus';\nexport { shouldApplyExternalErrors } from '../engine/external-errors';\nimport type { FormEngine } from '../engine';\nimport { changeStep } from '../engine/navigation';\nimport type { EngineInternals } from '../engine/runtime-internals';\n\nexport function autoAdvance(engine: FormEngine): Promise<boolean> {\n return changeStep(engine as unknown as EngineInternals, 'next', 'autoAdvance');\n}\n\nconst clean = (value: string) => value.replace(/[^A-Za-z0-9_-]/g, '-');\n\nexport function fieldDomId(formId: string | undefined, key: string): string {\n return `${formId ? clean(formId) : 'fh'}-${clean(key)}`;\n}\n"]}
@@ -0,0 +1,79 @@
1
+ import { f as FormDefinition, a as FormStep, F as FormField } from './definition-Bufih_Bx.js';
2
+ import { V as ValidatorFn, D as DefinitionIssue } from './validate-field-glVVoN3E.js';
3
+
4
+ type StepValidateFn = (stepId: string, values: Record<string, unknown>) => Promise<Record<string, string> | null | void>;
5
+ interface StepChangeContext {
6
+ fromStepId: string;
7
+ toStepId: string;
8
+ reason: 'next' | 'back' | 'autoAdvance' | 'skip';
9
+ values: Record<string, unknown>;
10
+ }
11
+ type BeforeStepChangeFn = (context: StepChangeContext) => boolean | void | Promise<boolean | void>;
12
+ type AfterStepChangeFn = (context: StepChangeContext) => void | Promise<void>;
13
+ type BeforeSubmitFn = (values: Record<string, unknown>) => boolean | void | Promise<boolean | void>;
14
+ type SubmitFn = (values: Record<string, unknown>, skippedSteps: string[]) => void | Promise<void>;
15
+ interface FormEngineOptions {
16
+ onBeforeStepChange?: BeforeStepChangeFn;
17
+ onAfterStepChange?: AfterStepChangeFn;
18
+ onBeforeSubmit?: BeforeSubmitFn;
19
+ onAfterSubmit?: SubmitFn;
20
+ validators?: Record<string, ValidatorFn>;
21
+ onStepValidate?: StepValidateFn;
22
+ onWarning?: (issue: DefinitionIssue) => void;
23
+ }
24
+
25
+ declare class FormEngine<TValues extends object = Record<string, unknown>> {
26
+ readonly definition: FormDefinition;
27
+ private readonly state;
28
+ private readonly skipped;
29
+ private validationEpoch;
30
+ private operationEpoch;
31
+ private readonly lifecycle;
32
+ private readonly validators;
33
+ private get onStepValidate();
34
+ private readonly visibility;
35
+ private readonly subscriptions;
36
+ constructor(definition: FormDefinition, initialValues?: Partial<NoInfer<TValues>>, options?: FormEngineOptions);
37
+ get values(): Readonly<Partial<TValues>>;
38
+ get errors(): Readonly<Record<string, string>>;
39
+ get topLevelErrors(): readonly string[];
40
+ get currentStepIndex(): number;
41
+ get fieldLoading(): Readonly<Record<string, boolean>>;
42
+ get stepValidating(): boolean;
43
+ get submitting(): boolean;
44
+ get isMultiStep(): boolean;
45
+ get visibleSteps(): FormStep[];
46
+ get currentStep(): FormStep | null;
47
+ get visibleFields(): FormField[];
48
+ get isFirstStep(): boolean;
49
+ get isLastStep(): boolean;
50
+ get canGoNext(): boolean;
51
+ get progress(): {
52
+ current: number;
53
+ total: number;
54
+ };
55
+ subscribe(listener: () => void): () => void;
56
+ getSnapshot(): number;
57
+ subscribeField(key: string, listener: () => void): () => void;
58
+ getFieldSnapshot(key: string): number;
59
+ subscribeStructure(listener: () => void): () => void;
60
+ getStructureSnapshot(): number;
61
+ setValue(key: string, value: unknown): void;
62
+ setErrors(errors: Record<string, string>): void;
63
+ setFieldLoading(key: string, loading: boolean): void;
64
+ cancelPendingActions(): void;
65
+ next(): Promise<boolean>;
66
+ back(): Promise<boolean>;
67
+ skip(submit?: SubmitFn): Promise<boolean>;
68
+ submit(handler: SubmitFn): Promise<boolean>;
69
+ isStepSkipped(stepId: string): boolean;
70
+ validate(): Record<string, string>;
71
+ validateField(key: string): string | null;
72
+ getSubmitValues(): Partial<TValues>;
73
+ goToStepWithField(key: string): void;
74
+ reset(values?: Record<string, unknown>): void;
75
+ private get internals();
76
+ private notify;
77
+ }
78
+
79
+ export { type AfterStepChangeFn as A, type BeforeStepChangeFn as B, FormEngine as F, type StepChangeContext as S, type BeforeSubmitFn as a, type FormEngineOptions as b, type StepValidateFn as c, type SubmitFn as d };