/*!
Copyright (c) 2026 Lenovo SSG BASD. All rights reserved.
@license Proprietary

This software is the confidential and proprietary property of Lenovo SSG BASD.
You shall not disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement.

--- Build Info ---
Version: 1.1.1
Build Time: 2026/2/26 17:21:00
Build Commit: 81e556ed827e2f043668506dae6fae8dbb9ef395
*/
import{Derived as t}from"../../../store/dist/esm/derived.js";import{Store as e}from"../../../store/dist/esm/store.js";import{batch as s}from"../../../store/dist/esm/scheduler.js";import{throttleFormState as i,evaluate as a,getSyncValidatorArray as r,getAsyncValidatorArray as o,determineFormLevelErrorSourceAndValue as l,getBy as n,functionalUpdate as d,deleteBy as u,mergeOpts as h,setBy as c,uuid as f,isGlobalFormValidationError as m,isNonEmptyArray as p}from"./utils.js";import{defaultValidationLogic as v}from"./ValidationLogic.js";import{standardSchemaValidators as M,isStandardSchemaValidator as S}from"./standardSchemaValidator.js";import{defaultFieldMeta as b,metaHelper as V}from"./metaHelper.js";import{formEventClient as F}from"./EventClient.js";function g(t){return{values:t.values??{},errorMap:t.errorMap??{},fieldMetaBase:t.fieldMetaBase??{},isSubmitted:t.isSubmitted??!1,isSubmitting:t.isSubmitting??!1,isValidating:t.isValidating??!1,submissionAttempts:t.submissionAttempts??0,isSubmitSuccessful:t.isSubmitSuccessful??!1,validationMetaMap:t.validationMetaMap??{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}}}class y{constructor(S){this.options={},this.fieldInfo={},this.mount=()=>{const t=this.fieldMetaDerived.mount(),e=this.store.mount(),s=this.store.subscribe(()=>{i(this)}),a=F.on("request-form-state",t=>{t.payload.id===this._formId&&F.emit("form-api",{id:this._formId,state:this.store.state,options:this.options})}),r=F.on("request-form-reset",t=>{t.payload.id===this._formId&&this.reset()}),o=F.on("request-form-force-submit",t=>{t.payload.id===this._formId&&(this._devtoolsSubmissionOverride=!0,this.handleSubmit(),this._devtoolsSubmissionOverride=!1)}),l=()=>{o(),r(),a(),s(),t(),e(),F.emit("form-unmounted",{id:this._formId})};this.options.listeners?.onMount?.({formApi:this});const{onMount:n}=this.options.validators||{};return F.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}),n?(this.validateSync("mount"),l):l},this.update=t=>{if(!t)return;const e=this.options;this.options=t;const i=t.defaultValues&&!a(t.defaultValues,e.defaultValues)&&!this.state.isTouched,r=!a(t.defaultState,e.defaultState)&&!this.state.isTouched;(i||r)&&(s(()=>{this.baseStore.setState(()=>g(Object.assign({},this.state,r?t.defaultState:{},i?{values:t.defaultValues}:{})))}),F.emit("form-api",{id:this._formId,state:this.store.state,options:this.options}))},this.reset=(t,e)=>{const{fieldMeta:s}=this.state,i=this.resetFieldMeta(s);t&&!e?.keepDefaultValues&&(this.options={...this.options,defaultValues:t}),this.baseStore.setState(()=>g({...this.options.defaultState,values:t??this.options.defaultValues??this.options.defaultState?.values,fieldMetaBase:i}))},this.validateAllFields=async t=>{const e=[];s(()=>{Object.values(this.fieldInfo).forEach(s=>{if(!s.instance)return;const i=s.instance;e.push(Promise.resolve().then(()=>i.validate(t,{skipFormValidation:!0}))),s.instance.state.meta.isTouched||s.instance.setMeta(t=>({...t,isTouched:!0}))})});return(await Promise.all(e)).flat()},this.validateArrayFieldsStartingFrom=async(t,e,i)=>{const a=this.getFieldValue(t),r=Array.isArray(a)?Math.max(a.length-1,0):null,o=[`${t}[${e}]`];for(let s=e+1;s<=(r??0);s++)o.push(`${t}[${s}]`);const l=Object.keys(this.fieldInfo).filter(t=>o.some(e=>t.startsWith(e))),n=[];s(()=>{l.forEach(t=>{n.push(Promise.resolve().then(()=>this.validateField(t,i)))})});return(await Promise.all(n)).flat()},this.validateField=(t,e)=>{const s=this.fieldInfo[t]?.instance;if(!s){const{hasErrored:s}=this.validateSync(e);return s&&!this.options.asyncAlways?this.getFieldMeta(t)?.errors??[]:this.validateAsync(e).then(()=>this.getFieldMeta(t)?.errors??[])}return s.state.meta.isTouched||s.setMeta(t=>({...t,isTouched:!0})),s.validate(e)},this.validateSync=t=>{const e=r(t,{...this.options,form:this,validationLogic:this.options.validationLogic||v});let i=!1;const a={};return s(()=>{for(const t of e){if(!t.validate)continue;const e=this.runValidator({validate:t.validate,value:{value:this.state.values,formApi:this,validationSource:"form"},type:"validate"}),{formError:s,fieldErrors:r}=A(e),o=E(t.cause),n=/* @__PURE__ */new Set([...Object.keys(this.state.fieldMeta),...Object.keys(r||{})]);for(const t of n){if(void 0===this.baseStore.state.fieldMetaBase[t]&&!r?.[t])continue;const e=this.getFieldMeta(t)??b,{errorMap:s,errorSourceMap:i}=e,n=r?.[t],{newErrorValue:d,newSource:u}=l({newFormValidatorError:n,isPreviousErrorFromFormValidator:"form"===i?.[o],previousErrorValue:s?.[o]});"form"===u&&(a[t]={...a[t],[o]:n}),s?.[o]!==d&&this.setFieldMeta(t,(t=b)=>({...t,errorMap:{...t.errorMap,[o]:d},errorSourceMap:{...t.errorSourceMap,[o]:u}}))}this.state.errorMap?.[o]!==s&&this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[o]:s}})),(s||r)&&(i=!0)}const s=E("submit");this.state.errorMap?.[s]&&"submit"!==t&&!i&&this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[s]:void 0}}));const r=E("server");this.state.errorMap?.[r]&&"server"!==t&&!i&&this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[r]:void 0}}))}),{hasErrored:i,fieldsErrorMap:a}},this.validateAsync=async t=>{const e=o(t,{...this.options,form:this,validationLogic:this.options.validationLogic||v});this.state.isFormValidating||this.baseStore.setState(t=>({...t,isFormValidating:!0}));const s=[];let i;for(const o of e){if(!o.validate)continue;const t=E(o.cause),e=this.state.validationMetaMap[t];e?.lastAbortController.abort();const a=new AbortController;this.state.validationMetaMap[t]={lastAbortController:a},s.push(new Promise(async t=>{let e;try{e=await new Promise((t,e)=>{setTimeout(async()=>{if(a.signal.aborted)return t(void 0);try{t(await this.runValidator({validate:o.validate,value:{value:this.state.values,formApi:this,validationSource:"form",signal:a.signal},type:"validateAsync"}))}catch(s){e(s)}},o.debounceMs)})}catch(d){e=d}const{formError:s,fieldErrors:r}=A(e);r&&(i=i?{...i,...r}:r);const n=E(o.cause);for(const a of Object.keys(this.state.fieldMeta)){if(void 0===this.baseStore.state.fieldMetaBase[a])continue;const t=this.getFieldMeta(a);if(!t)continue;const{errorMap:e,errorSourceMap:s}=t,r=i?.[a],{newErrorValue:o,newSource:d}=l({newFormValidatorError:r,isPreviousErrorFromFormValidator:"form"===s?.[n],previousErrorValue:e?.[n]});e?.[n]!==o&&this.setFieldMeta(a,t=>({...t,errorMap:{...t.errorMap,[n]:o},errorSourceMap:{...t.errorSourceMap,[n]:d}}))}this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[n]:s}})),t(i?{fieldErrors:i,errorMapKey:n}:void 0)}))}let a=[];const r={};if(s.length){a=await Promise.all(s);for(const t of a)if(t?.fieldErrors){const{errorMapKey:e}=t;for(const[s,i]of Object.entries(t.fieldErrors)){const t={...r[s]||{},[e]:i};r[s]=t}}}return this.baseStore.setState(t=>({...t,isFormValidating:!1})),r},this.validate=t=>{const{hasErrored:e,fieldsErrorMap:s}=this.validateSync(t);return e&&!this.options.asyncAlways?s:this.validateAsync(t)},this._handleSubmit=async t=>{this.baseStore.setState(t=>({...t,isSubmitted:!1,submissionAttempts:t.submissionAttempts+1,isSubmitSuccessful:!1})),s(()=>{Object.values(this.fieldInfo).forEach(t=>{t.instance&&(t.instance.state.meta.isTouched||t.instance.setMeta(t=>({...t,isTouched:!0})))})});const e=t??this.options.onSubmitMeta;if(!this.state.canSubmit&&!this._devtoolsSubmissionOverride)return void this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:e});this.baseStore.setState(t=>({...t,isSubmitting:!0}));const i=()=>{this.baseStore.setState(t=>({...t,isSubmitting:!1}))};if(await this.validateAllFields("submit"),!this.state.isFieldsValid)return i(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:e}),void F.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validateAllFields",errors:Object.values(this.state.fieldMeta).map(t=>t.errors).flat()});if(await this.validate("submit"),!this.state.isValid)return i(),this.options.onSubmitInvalid?.({value:this.state.values,formApi:this,meta:e}),void F.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"validate",errors:this.state.errors});s(()=>{Object.values(this.fieldInfo).forEach(t=>{t.instance?.options.listeners?.onSubmit?.({value:t.instance.state.value,fieldApi:t.instance})})}),this.options.listeners?.onSubmit?.({formApi:this,meta:e});try{await(this.options.onSubmit?.({value:this.state.values,formApi:this,meta:e})),s(()=>{this.baseStore.setState(t=>({...t,isSubmitted:!0,isSubmitSuccessful:!0})),F.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!0}),i()})}catch(a){throw this.baseStore.setState(t=>({...t,isSubmitSuccessful:!1})),F.emit("form-submission",{id:this._formId,submissionAttempt:this.state.submissionAttempts,successful:!1,stage:"inflight",onError:a}),i(),a}},this.getFieldValue=t=>n(this.state.values,t),this.getFieldMeta=t=>this.state.fieldMeta[t],this.getFieldInfo=t=>this.fieldInfo[t]||={instance:null,validationMetaMap:{onChange:void 0,onBlur:void 0,onSubmit:void 0,onMount:void 0,onServer:void 0,onDynamic:void 0}},this.setFieldMeta=(t,e)=>{this.baseStore.setState(s=>({...s,fieldMetaBase:{...s.fieldMetaBase,[t]:d(e,s.fieldMetaBase[t])}}))},this.resetFieldMeta=t=>Object.keys(t).reduce((t,e)=>(t[e]=b,t),{}),this.setFieldValue=(t,e,i)=>{const a=i?.dontUpdateMeta??!1,r=i?.dontRunListeners??!1,o=i?.dontValidate??!1;s(()=>{a||this.setFieldMeta(t,t=>({...t,isTouched:!0,isDirty:!0,errorMap:{...t?.errorMap,onMount:void 0}})),this.baseStore.setState(s=>({...s,values:c(s.values,t,e)}))}),r||this.getFieldInfo(t).instance?.triggerOnChangeListener(),o||this.validateField(t,"change")},this.deleteField=t=>{const e=[...Object.keys(this.fieldInfo).filter(e=>{const s=t.toString();return e!==s&&e.startsWith(s)}),t];this.baseStore.setState(t=>{const s={...t};return e.forEach(t=>{s.values=u(s.values,t),delete this.fieldInfo[t],delete s.fieldMetaBase[t]}),s})},this.pushFieldValue=(t,e,s)=>{this.setFieldValue(t,t=>[...Array.isArray(t)?t:[],e],s)},this.insertFieldValue=async(t,e,s,i)=>{this.setFieldValue(t,t=>[...t.slice(0,e),s,...t.slice(e)],h(i,{dontValidate:!0}));const a=i?.dontValidate??!1;a||await this.validateField(t,"change"),V(this).handleArrayInsert(t,e),a||await this.validateArrayFieldsStartingFrom(t,e,"change")},this.replaceFieldValue=async(t,e,s,i)=>{this.setFieldValue(t,t=>t.map((t,i)=>i===e?s:t),h(i,{dontValidate:!0}));(i?.dontValidate??!1)||(await this.validateField(t,"change"),await this.validateArrayFieldsStartingFrom(t,e,"change"))},this.removeFieldValue=async(t,e,s)=>{const i=this.getFieldValue(t),a=Array.isArray(i)?Math.max(i.length-1,0):null;if(this.setFieldValue(t,t=>t.filter((t,s)=>s!==e),h(s,{dontValidate:!0})),V(this).handleArrayRemove(t,e),null!==a){const e=`${t}[${a}]`;this.deleteField(e)}(s?.dontValidate??!1)||(await this.validateField(t,"change"),await this.validateArrayFieldsStartingFrom(t,e,"change"))},this.swapFieldValues=(t,e,s,i)=>{this.setFieldValue(t,t=>{const i=t[e],a=t[s];return c(c(t,`${e}`,a),`${s}`,i)},h(i,{dontValidate:!0})),V(this).handleArraySwap(t,e,s);(i?.dontValidate??!1)||(this.validateField(t,"change"),this.validateField(`${t}[${e}]`,"change"),this.validateField(`${t}[${s}]`,"change"))},this.moveFieldValues=(t,e,s,i)=>{this.setFieldValue(t,t=>{const i=[...t];return i.splice(s,0,i.splice(e,1)[0]),i},h(i,{dontValidate:!0})),V(this).handleArrayMove(t,e,s);(i?.dontValidate??!1)||(this.validateField(t,"change"),this.validateField(`${t}[${e}]`,"change"),this.validateField(`${t}[${s}]`,"change"))},this.clearFieldValues=(t,e)=>{const s=this.getFieldValue(t),i=Array.isArray(s)?Math.max(s.length-1,0):null;if(this.setFieldValue(t,[],h(e,{dontValidate:!0})),null!==i)for(let a=0;a<=i;a++){const e=`${t}[${a}]`;this.deleteField(e)}(e?.dontValidate??!1)||this.validateField(t,"change")},this.resetField=t=>{this.baseStore.setState(e=>({...e,fieldMetaBase:{...e.fieldMetaBase,[t]:b},values:this.options.defaultValues?c(e.values,t,n(this.options.defaultValues,t)):e.values}))},this.setErrorMap=t=>{s(()=>{Object.entries(t).forEach(([t,e])=>{const s=t;if(m(e)){const{formError:t,fieldErrors:i}=A(e);for(const e of Object.keys(this.fieldInfo)){this.getFieldMeta(e)&&this.setFieldMeta(e,t=>({...t,errorMap:{...t.errorMap,[s]:i?.[e]},errorSourceMap:{...t.errorSourceMap,[s]:"form"}}))}this.baseStore.setState(e=>({...e,errorMap:{...e.errorMap,[s]:t}}))}else this.baseStore.setState(t=>({...t,errorMap:{...t.errorMap,[s]:e}}))})})},this.getAllErrors=()=>({form:{errors:this.state.errors,errorMap:this.state.errorMap},fields:Object.entries(this.state.fieldMeta).reduce((t,[e,s])=>(Object.keys(s).length&&s.errors.length&&(t[e]={errors:s.errors,errorMap:s.errorMap}),t),{})}),this.parseValuesWithSchema=t=>M.validate({value:this.state.values,validationSource:"form"},t),this.parseValuesWithSchemaAsync=t=>M.validateAsync({value:this.state.values,validationSource:"form"},t),this.timeoutIds={validations:{},listeners:{},formListeners:{}},this._formId=S?.formId??f(),this._devtoolsSubmissionOverride=!1;let y=g({...S?.defaultState,values:S?.defaultValues??S?.defaultState?.values});if(S?.transform){y=S.transform({state:y}).state;for(const t of Object.keys(y.errorMap)){const e=y.errorMap[t];if(void 0!==e&&m(e))for(const s of Object.keys(e.fields)){const i=e.fields[s];if(void 0===i)continue;const a=y.fieldMetaBase[s];y.fieldMetaBase[s]={isTouched:!1,isValidating:!1,isBlurred:!1,isDirty:!1,...a??{},errorSourceMap:{...a?.errorSourceMap??{},onChange:"form"},errorMap:{...a?.errorMap??{},[t]:i}}}}}this.baseStore=new e(y),this.fieldMetaDerived=new t({deps:[this.baseStore],fn:({prevDepVals:t,currDepVals:e,prevVal:s})=>{const i=s,r=t?.[0],o=e[0];let l=0;const d={};for(const u of Object.keys(o.fieldMetaBase)){const t=o.fieldMetaBase[u],e=r?.fieldMetaBase[u],s=i?.[u],h=n(o.values,u);let c=s?.errors;if(!e||t.errorMap!==e.errorMap){c=Object.values(t.errorMap??{}).filter(t=>void 0!==t);const e=this.getFieldInfo(u)?.instance;e&&e.options.disableErrorFlat||(c=c.flat(1))}const f=!p(c),m=!t.isDirty,v=a(h,n(this.options.defaultValues,u))||a(h,this.getFieldInfo(u)?.instance?.options.defaultValue);s&&s.isPristine===m&&s.isValid===f&&s.isDefaultValue===v&&s.errors===c&&t===e?(d[u]=s,l++):d[u]={...t,errors:c??[],isPristine:m,isValid:f,isDefaultValue:v}}return Object.keys(o.fieldMetaBase).length&&i&&l===Object.keys(o.fieldMetaBase).length?i:d}}),this.store=new t({deps:[this.baseStore,this.fieldMetaDerived],fn:({prevDepVals:t,currDepVals:e,prevVal:s})=>{const i=s,r=t?.[0],o=e[0],l=e[1],n=Object.values(l).filter(Boolean),d=n.some(t=>t.isValidating),u=n.every(t=>t.isValid),h=n.some(t=>t.isTouched),c=n.some(t=>t.isBlurred),f=n.every(t=>t.isDefaultValue),p=h&&o.errorMap?.onMount,v=n.some(t=>t.isDirty),M=!v,S=Boolean(o.errorMap?.onMount||n.some(t=>t?.errorMap?.onMount)),b=!!d;let V=i?.errors??[];r&&o.errorMap===r.errorMap||(V=Object.values(o.errorMap).reduce((t,e)=>void 0===e?t:e&&m(e)?(t.push(e.form),t):(t.push(e),t),[]));const F=0===V.length,g=u&&F,y=this.options.canSubmitWhenInvalid??!1,A=0===o.submissionAttempts&&!h&&!S||!b&&!o.isSubmitting&&g||y;let E=o.errorMap;if(p&&(V=V.filter(t=>t!==o.errorMap.onMount),E=Object.assign(E,{onMount:void 0})),i&&r&&i.errorMap===E&&i.fieldMeta===this.fieldMetaDerived.state&&i.errors===V&&i.isFieldsValidating===d&&i.isFieldsValid===u&&i.isFormValid===F&&i.isValid===g&&i.canSubmit===A&&i.isTouched===h&&i.isBlurred===c&&i.isPristine===M&&i.isDefaultValue===f&&i.isDirty===v&&a(r,o))return i;return{...o,errorMap:E,fieldMeta:this.fieldMetaDerived.state,errors:V,isFieldsValidating:d,isFieldsValid:u,isFormValid:F,isValid:g,canSubmit:A,isTouched:h,isBlurred:c,isPristine:M,isDefaultValue:f,isDirty:v}}}),this.handleSubmit=this.handleSubmit.bind(this),this.update(S||{})}get state(){return this.store.state}get formId(){return this._formId}runValidator(t){return S(t.validate)?M[t.type](t.value,t.validate):t.validate(t.value)}handleSubmit(t){return this._handleSubmit(t)}}function A(t){if(t){if(m(t)){return{formError:A(t.form).formError,fieldErrors:t.fields}}return{formError:t}}return{formError:void 0}}function E(t){switch(t){case"submit":return"onSubmit";case"blur":return"onBlur";case"mount":return"onMount";case"server":return"onServer";case"dynamic":return"onDynamic";default:return"onChange"}}export{y as FormApi};