@lehnihon/bit-form 2.2.10 → 2.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/angular/index.cjs +1 -1
- package/dist/angular/index.js +1 -1
- package/dist/chunk-6NH6MUXA.js +2 -0
- package/dist/chunk-6NH6MUXA.js.map +1 -0
- package/dist/{chunk-ZKAFHJPU.cjs → chunk-C2GGB5NF.cjs} +2 -2
- package/dist/{chunk-ZKAFHJPU.cjs.map → chunk-C2GGB5NF.cjs.map} +1 -1
- package/dist/chunk-CGJRZJ62.js +2 -0
- package/dist/chunk-CGJRZJ62.js.map +1 -0
- package/dist/chunk-IDJIIPCS.js +2 -0
- package/dist/chunk-IDJIIPCS.js.map +1 -0
- package/dist/chunk-JPOZKCPR.cjs +2 -0
- package/dist/chunk-JPOZKCPR.cjs.map +1 -0
- package/dist/{chunk-2AFWJAQG.js → chunk-LZTWNUKZ.js} +2 -2
- package/dist/{chunk-IVPCXKYW.cjs → chunk-MZNHMPTF.cjs} +2 -2
- package/dist/{chunk-IVPCXKYW.cjs.map → chunk-MZNHMPTF.cjs.map} +1 -1
- package/dist/chunk-OR5AGYQT.cjs +2 -0
- package/dist/chunk-OR5AGYQT.cjs.map +1 -0
- package/dist/{chunk-NVFZ22A7.cjs → chunk-QZBJ4WRU.cjs} +2 -2
- package/dist/{chunk-NVFZ22A7.cjs.map → chunk-QZBJ4WRU.cjs.map} +1 -1
- package/dist/chunk-RGMUXQ2K.cjs +2 -0
- package/dist/chunk-RGMUXQ2K.cjs.map +1 -0
- package/dist/{chunk-OPC7HFNN.js → chunk-S3DJPXMV.js} +2 -2
- package/dist/{chunk-LX4GSDUV.js → chunk-ZWWXPYEL.js} +2 -2
- package/dist/core/bindings.cjs +1 -1
- package/dist/core/bindings.js +1 -1
- package/dist/core/store.cjs +1 -1
- package/dist/core/store.js +1 -1
- package/dist/core/utils.cjs +1 -1
- package/dist/core/utils.d.cts +1 -1
- package/dist/core/utils.d.ts +1 -1
- package/dist/core/utils.js +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/devtools/bridge.cjs +1 -1
- package/dist/devtools/bridge.js +1 -1
- package/dist/devtools/index.cjs +2 -2
- package/dist/devtools/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.js +1 -1
- package/dist/react-native/index.cjs +1 -1
- package/dist/react-native/index.js +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.js +1 -1
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4RQFECC7.cjs +0 -2
- package/dist/chunk-4RQFECC7.cjs.map +0 -1
- package/dist/chunk-FLFIOW75.js +0 -2
- package/dist/chunk-FLFIOW75.js.map +0 -1
- package/dist/chunk-G2FQQDRK.js +0 -2
- package/dist/chunk-G2FQQDRK.js.map +0 -1
- package/dist/chunk-GPMAT4PT.cjs +0 -2
- package/dist/chunk-GPMAT4PT.cjs.map +0 -1
- package/dist/chunk-GQ2QJCBF.js +0 -2
- package/dist/chunk-GQ2QJCBF.js.map +0 -1
- package/dist/chunk-VBX5I5XG.cjs +0 -2
- package/dist/chunk-VBX5I5XG.cjs.map +0 -1
- /package/dist/{chunk-2AFWJAQG.js.map → chunk-LZTWNUKZ.js.map} +0 -0
- /package/dist/{chunk-OPC7HFNN.js.map → chunk-S3DJPXMV.js.map} +0 -0
- /package/dist/{chunk-LX4GSDUV.js.map → chunk-ZWWXPYEL.js.map} +0 -0
package/README.md
CHANGED
|
@@ -172,6 +172,8 @@ npm install @lehnihon/bit-form
|
|
|
172
172
|
|
|
173
173
|
The complete documentation is available in the `/docs` folder. Explore the guides below to get started:
|
|
174
174
|
|
|
175
|
+
- **[Documentation Hub](./docs/README.md)**: Start here to navigate by goal (onboarding, troubleshooting, API).
|
|
176
|
+
|
|
175
177
|
### 🚀 Getting Started
|
|
176
178
|
|
|
177
179
|
- **[Introduction & Installation](./docs/01-getting-started.md)**: Overview and basic setup.
|
|
@@ -202,8 +204,22 @@ The complete documentation is available in the `/docs` folder. Explore the guide
|
|
|
202
204
|
### 📖 Guides & Examples
|
|
203
205
|
|
|
204
206
|
- **[When to Use What](./docs/guides/when-to-use-what.md)**: Quick reference for resolver vs asyncValidate vs setServerErrors, computed vs transform, and conditional fields.
|
|
207
|
+
- **[Troubleshooting](./docs/guides/troubleshooting.md)**: Debug common form setup, validation, and devtools issues.
|
|
208
|
+
- **[Migration Guide](./docs/guides/migration.md)**: Plan upgrades and breaking-change checks safely.
|
|
209
|
+
- **[Testing Guide](./docs/guides/testing.md)**: Unit, integration, and e2e testing strategies.
|
|
210
|
+
- **[Performance Guide](./docs/guides/performance.md)**: Optimize large forms and subscription patterns.
|
|
211
|
+
- **[Accessibility Guide](./docs/guides/accessibility.md)**: Build accessible form experiences across frameworks.
|
|
212
|
+
- **[Compatibility Matrix](./docs/guides/compatibility-matrix.md)**: Runtime and framework target baseline.
|
|
213
|
+
- **[Release Gates](./docs/guides/release-gates.md)**: Pre-release quality and docs synchronization checks.
|
|
214
|
+
- **[FAQ](./docs/guides/faq.md)**: Quick answers for common implementation questions.
|
|
215
|
+
- **[Example Template](./docs/guides/example-template.md)**: Editorial template for consistent, copy-paste-ready examples.
|
|
205
216
|
- **[Complete Form Example](./docs/examples/complete-form-example.md)**: End-to-end example with masks, asyncValidate, conditional logic, scopes, history, and DevTools.
|
|
217
|
+
- **[Conditional + Server Validation Example](./docs/examples/conditional-server-validation-example.md)**: Dynamic fields with 422/server mapping workflow.
|
|
218
|
+
- **[Multi-Step + Draft Example](./docs/examples/multi-step-draft-example.md)**: Scope-based wizard with persistence controls.
|
|
219
|
+
- **[Array Reorder Example](./docs/examples/array-reorder-example.md)**: Stable keys and automatic error reallocation during reorder/remove.
|
|
220
|
+
- **[Plugin + DevTools Example](./docs/examples/plugin-devtools-lifecycle-example.md)**: Lifecycle audit logs with local timeline inspection.
|
|
206
221
|
- **[Upload Integration Example](./docs/examples/upload-integration-example.md)**: Backend-first upload example using `useBitUpload`/`injectBitUpload`.
|
|
222
|
+
- **[E-commerce Checkout Example](./docs/examples/ecommerce-checkout-example.md)**: Advanced nested + arrays + computed + async shipping quote flow.
|
|
207
223
|
- **[Server Errors](./docs/examples/server-errors.md)**: Client validation (resolver/asyncValidate) vs API 422 handling (setServerErrors, onSubmit).
|
|
208
224
|
|
|
209
225
|
### 🔍 DevTools & CLI
|
|
@@ -217,6 +233,7 @@ The complete documentation is available in the `/docs` folder. Explore the guide
|
|
|
217
233
|
|
|
218
234
|
- **[API Reference](./docs/api-reference/bit-store.md)**: Full `BitStore` class documentation.
|
|
219
235
|
- **[Type Definitions](./docs/api-reference/types.md)**: Core TypeScript interfaces and types.
|
|
236
|
+
- **[Advanced Core API](./docs/api-reference/advanced-core.md)**: Public advanced exports for custom adapters and tooling.
|
|
220
237
|
|
|
221
238
|
## ⚠️ Breaking Changes (dev branch)
|
|
222
239
|
|
package/dist/angular/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkPA43XYOWcjs = require('../chunk-PA43XYOW.cjs');require('../chunk-W5CLDRRE.cjs');var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkPA43XYOWcjs = require('../chunk-PA43XYOW.cjs');require('../chunk-W5CLDRRE.cjs');var _chunkOR5AGYQTcjs = require('../chunk-OR5AGYQT.cjs');var _chunkQZBJ4WRUcjs = require('../chunk-QZBJ4WRU.cjs');var _chunkBSGJ3T5Scjs = require('../chunk-BSGJ3T5S.cjs');var _chunkRHMJPKNVcjs = require('../chunk-RHMJPKNV.cjs');var _chunk3KI3GEU3cjs = require('../chunk-3KI3GEU3.cjs');require('../chunk-C2GGB5NF.cjs');var _chunkRGMUXQ2Kcjs = require('../chunk-RGMUXQ2K.cjs');var _chunkPFPGASVZcjs = require('../chunk-PFPGASVZ.cjs');var _core = require('@angular/core');var B=new (0, _core.InjectionToken)("BIT_STORE");function at(t){return{provide:B,useValue:_chunkOR5AGYQTcjs.d.call(void 0, t)}}function l(){let t=_core.inject.call(void 0, B,{optional:!0});if(!t)throw new Error('BitForm: N\xE3o foi poss\xEDvel encontrar a BitStore. Certifique-se de que voc\xEA adicionou "provideBitStore(store)" nos providers do seu componente.');return t}function lt(){let t=l(),e=_core.inject.call(void 0, _core.DestroyRef),r=_core.signal.call(void 0, {isValid:!0,isDirty:!1,isSubmitting:!1}),o=_core.signal.call(void 0, null),s=_core.signal.call(void 0, null),i=_chunkQZBJ4WRUcjs.c.call(void 0, t,m=>{r.set(m)});e.onDestroy(()=>i());let p=_core.computed.call(void 0, ()=>r().isValid),a=_core.computed.call(void 0, ()=>r().isSubmitting),d=_core.computed.call(void 0, ()=>r().isDirty),{controller:c,actions:n}=_chunkQZBJ4WRUcjs.i.call(void 0, t,{clearSubmissionState:()=>{o.set(null),s.set(null)},setSubmissionResult:m=>{s.set(m)},setSubmissionError:m=>{o.set(m)}},{stopPropagation:!0});return{meta:{isValid:p,isDirty:d,isSubmitting:a,submitError:o.asReadonly(),lastResponse:s.asReadonly()},getValues:c.getValues,getErrors:c.getErrors,getTouched:c.getTouched,getDirtyValues:c.getDirtyValues,submit:c.submit,onSubmit:c.onSubmit,reset:c.reset,...n}}function E(t){let e=_core.inject.call(void 0, B),r=_core.signal.call(void 0, e.read.getFieldState(t)),o=e.observe.subscribeFieldState(t,y=>{r.set(y)});_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>{o(),_chunkQZBJ4WRUcjs.j.call(void 0, e,t)});let s=_core.computed.call(void 0, ()=>r().value),i=_core.computed.call(void 0, ()=>_chunk3KI3GEU3cjs.a.call(void 0, r())),p=_core.computed.call(void 0, ()=>i().error),a=_core.computed.call(void 0, ()=>i().touched),d=_core.computed.call(void 0, ()=>i().invalid),c=_core.computed.call(void 0, ()=>i().isDirty),n=_core.computed.call(void 0, ()=>i().isValidating),f=_core.computed.call(void 0, ()=>i().isHidden),m=_core.computed.call(void 0, ()=>i().isRequired),{fieldController:j}=_chunkQZBJ4WRUcjs.h.call(void 0, e,t),T=_core.computed.call(void 0, ()=>j.displayValue(s())),v=y=>{j.setValue(y)},h=()=>j.setBlur(),x=_core.computed.call(void 0, ()=>i().hasError);return{value:s,displayValue:T,setValue:v,setBlur:h,update:y=>v(_chunkPFPGASVZcjs.a.call(void 0, y)?_nullishCoalesce(_optionalChain([y, 'access', _2 => _2.target, 'optionalAccess', _3 => _3.value]), () => (null)):y),meta:{error:p,touched:a,invalid:d,isDirty:c,isValidating:n,isHidden:f,isRequired:m,hasError:x}}}function ft(t){let e=_core.inject.call(void 0, B),r=_core.inject.call(void 0, _core.DestroyRef),o=_chunkQZBJ4WRUcjs.g.call(void 0, e,t),s=_core.signal.call(void 0, o.readItems()),i=e.observe.subscribePath(t,()=>{s.set(o.readItems())});return r.onDestroy(()=>{i(),_chunkQZBJ4WRUcjs.k.call(void 0, e,`${t}.`)}),{fields:_core.computed.call(void 0, ()=>o.getFields(s())),length:_core.computed.call(void 0, ()=>s().length),append:o.append,prepend:o.prepend,remove:o.remove,insert:o.insert,swap:o.swap,move:o.move,replace:o.replace,clear:o.clear}}function Rt(){let t=l(),e=_core.inject.call(void 0, _core.DestroyRef),r=_core.signal.call(void 0, _chunkRHMJPKNVcjs.f.call(void 0, t)),o=_chunkRHMJPKNVcjs.g.call(void 0, t,s=>{r.set(s)});return e.onDestroy(()=>o()),{canUndo:_core.computed.call(void 0, ()=>r().canUndo),canRedo:_core.computed.call(void 0, ()=>r().canRedo),historyIndex:_core.computed.call(void 0, ()=>r().historyIndex),historySize:_core.computed.call(void 0, ()=>r().historySize),undo:()=>t.feature.undo(),redo:()=>t.feature.redo()}}function Ft(t){let e=l(),r=e.read.getScopeStatus(t),o=_core.signal.call(void 0, r),s=_chunkBSGJ3T5Scjs.a.call(void 0, e,t,f=>{o.set(f)});_optionalChain([_core.inject.call(void 0, _core.DestroyRef,{optional:!0}), 'optionalAccess', _4 => _4.onDestroy, 'call', _5 => _5(()=>s())]);let p=async()=>{let f=await e.feature.validate({scope:t}),m=e.read.getScopeErrors(t);return{valid:f,errors:m}},a=()=>e.read.getScopeErrors(t),d=_core.computed.call(void 0, ()=>!o().hasErrors),c=_core.computed.call(void 0, ()=>o().isDirty),n=_core.computed.call(void 0, ()=>o().errors);return{scopeName:t,status:o,errors:n,validate:p,getErrors:a,isValid:d,isDirty:c,unsubscribe:s}}function ht(t){let e=l(),r=_core.signal.call(void 0, 0),o=_core.computed.call(void 0, ()=>_nullishCoalesce(t[r()], () => (""))),s=()=>_nullishCoalesce(t[r()], () => ("")),i=_core.signal.call(void 0, e.read.getScopeStatus(s())),p=()=>{let u=s(),g=e.read.getScopeStatus(u),b=i();_chunkRHMJPKNVcjs.b.call(void 0, b,g)||i.set(g)},a=e.observe.subscribeScopeStatus(s(),p),d=()=>{a(),a=e.observe.subscribeScopeStatus(s(),p)};_optionalChain([_core.inject.call(void 0, _core.DestroyRef,{optional:!0}), 'optionalAccess', _6 => _6.onDestroy, 'call', _7 => _7(()=>a())]);let n=async()=>{let u=s(),g=await e.feature.validate({scope:u}),b=e.read.getScopeErrors(u);return{valid:g,errors:b}},f=()=>e.read.getScopeErrors(s()),m=async()=>{let u=s(),g=e.read.getScopeFields(u);if(e.feature.hasValidationsInProgress(g))return!1;let b=await e.feature.validate({scope:u});if(b){let F=Math.min(r()+1,t.length-1);r.set(F),i.set(e.read.getScopeStatus(_nullishCoalesce(t[F], () => ("")))),d()}else{let F=e.read.getScopeErrors(u),U=Object.keys(F);U.length>0&&e.write.markFieldsTouched(U)}return b},j=()=>{let u=Math.max(r()-1,0);r.set(u),i.set(e.read.getScopeStatus(_nullishCoalesce(t[u], () => ("")))),d()},T=u=>{let g=Math.max(0,Math.min(u-1,t.length-1));r.set(g),i.set(e.read.getScopeStatus(_nullishCoalesce(t[g], () => ("")))),d()},v=_core.computed.call(void 0, ()=>r()+1),h=_core.computed.call(void 0, ()=>r()===0),x=_core.computed.call(void 0, ()=>r()>=t.length-1),A=_core.computed.call(void 0, ()=>!i().hasErrors),y=_core.computed.call(void 0, ()=>i().isDirty),st=_core.computed.call(void 0, ()=>i().errors);return{step:v,stepIndex:r,scope:o,next:m,prev:j,goTo:T,isFirst:h,isLast:x,status:i,errors:st,isValid:A,isDirty:y,validate:n,getErrors:f}}function Et(t){let e=l(),r=_core.inject.call(void 0, _core.DestroyRef),o=_core.signal.call(void 0, _chunkRGMUXQ2Kcjs.f.call(void 0, e.read.getState().values,t),{equal:_chunkRGMUXQ2Kcjs.c}),s=e.observe.subscribePath(t,i=>{o.set(i)});return r.onDestroy(s),o.asReadonly()}function kt(t,e,r){let o=_core.inject.call(void 0, B),s=E(t),i=null,p=_core.signal.call(void 0, !1),a={setLoading:n=>p.set(n),setError:(n,f)=>o.write.setError(n,f),setValue:n=>s.setValue(n),getUploadKey:()=>i,setUploadKey:n=>{i=n}},d=_chunkPA43XYOWcjs.a.call(void 0, t,e,a),c=_chunkPA43XYOWcjs.b.call(void 0, t,r,a);return{value:_core.computed.call(void 0, ()=>s.value()),setValue:s.setValue,error:_core.computed.call(void 0, ()=>s.meta.error()),isValidating:_core.computed.call(void 0, ()=>!!s.meta.isValidating()||p()),upload:d,remove:c}}function Ht(){let t=l(),e=_core.signal.call(void 0, t.read.getPersistMetadata()),r=_chunkQZBJ4WRUcjs.f.call(void 0, t,a=>{e.set(a)});return _optionalChain([_core.inject.call(void 0, _core.DestroyRef,{optional:!0}), 'optionalAccess', _8 => _8.onDestroy, 'call', _9 => _9(()=>r())]),{restore:async()=>t.feature.restorePersisted(),save:async()=>{await t.feature.forceSave()},clear:async()=>{await t.feature.clearPersisted()},meta:{isSaving:_core.computed.call(void 0, ()=>e().isSaving),isRestoring:_core.computed.call(void 0, ()=>e().isRestoring),error:_core.computed.call(void 0, ()=>e().error)}}}exports.injectBitArray = ft; exports.injectBitField = E; exports.injectBitForm = lt; exports.injectBitHistory = Rt; exports.injectBitPersist = Ht; exports.injectBitScope = Ft; exports.injectBitSteps = ht; exports.injectBitUpload = kt; exports.injectBitWatch = Et; exports.provideBitStore = at; exports.useBitStore = l;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/angular/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as Z,b as N}from"../chunk-PG7ZH32Z.js";import"../chunk-5NA2TFPG.js";import{d as K}from"../chunk-
|
|
1
|
+
import{a as Z,b as N}from"../chunk-PG7ZH32Z.js";import"../chunk-5NA2TFPG.js";import{d as K}from"../chunk-CGJRZJ62.js";import{c as C,f as W,g as z,h as $,i as G,j as J,k as Q}from"../chunk-LZTWNUKZ.js";import{a as X}from"../chunk-W2E5UIXT.js";import{b as O,f as _,g as q}from"../chunk-UIKO6GGW.js";import{a as Y}from"../chunk-ICYXODTQ.js";import"../chunk-S3DJPXMV.js";import{c as M,f as H}from"../chunk-6NH6MUXA.js";import{a as L}from"../chunk-3NUJVIAM.js";import{inject as it,InjectionToken as nt}from"@angular/core";var B=new nt("BIT_STORE");function at(t){return{provide:B,useValue:K(t)}}function l(){let t=it(B,{optional:!0});if(!t)throw new Error('BitForm: N\xE3o foi poss\xEDvel encontrar a BitStore. Certifique-se de que voc\xEA adicionou "provideBitStore(store)" nos providers do seu componente.');return t}import{signal as V,computed as I,inject as ct,DestroyRef as ut}from"@angular/core";function lt(){let t=l(),e=ct(ut),r=V({isValid:!0,isDirty:!1,isSubmitting:!1}),o=V(null),s=V(null),i=C(t,m=>{r.set(m)});e.onDestroy(()=>i());let p=I(()=>r().isValid),a=I(()=>r().isSubmitting),d=I(()=>r().isDirty),{controller:c,actions:n}=G(t,{clearSubmissionState:()=>{o.set(null),s.set(null)},setSubmissionResult:m=>{s.set(m)},setSubmissionError:m=>{o.set(m)}},{stopPropagation:!0});return{meta:{isValid:p,isDirty:d,isSubmitting:a,submitError:o.asReadonly(),lastResponse:s.asReadonly()},getValues:c.getValues,getErrors:c.getErrors,getTouched:c.getTouched,getDirtyValues:c.getDirtyValues,submit:c.submit,onSubmit:c.onSubmit,reset:c.reset,...n}}import{DestroyRef as pt,computed as S,inject as tt,signal as dt}from"@angular/core";function E(t){let e=tt(B),r=dt(e.read.getFieldState(t)),o=e.observe.subscribeFieldState(t,y=>{r.set(y)});tt(pt).onDestroy(()=>{o(),J(e,t)});let s=S(()=>r().value),i=S(()=>Y(r())),p=S(()=>i().error),a=S(()=>i().touched),d=S(()=>i().invalid),c=S(()=>i().isDirty),n=S(()=>i().isValidating),f=S(()=>i().isHidden),m=S(()=>i().isRequired),{fieldController:j}=$(e,t),T=S(()=>j.displayValue(s())),v=y=>{j.setValue(y)},h=()=>j.setBlur(),x=S(()=>i().hasError);return{value:s,displayValue:T,setValue:v,setBlur:h,update:y=>v(L(y)?y.target?.value??null:y),meta:{error:p,touched:a,invalid:d,isDirty:c,isValidating:n,isHidden:f,isRequired:m,hasError:x}}}import{computed as et,DestroyRef as mt,inject as rt,signal as St}from"@angular/core";function ft(t){let e=rt(B),r=rt(mt),o=z(e,t),s=St(o.readItems()),i=e.observe.subscribePath(t,()=>{s.set(o.readItems())});return r.onDestroy(()=>{i(),Q(e,`${t}.`)}),{fields:et(()=>o.getFields(s())),length:et(()=>s().length),append:o.append,prepend:o.prepend,remove:o.remove,insert:o.insert,swap:o.swap,move:o.move,replace:o.replace,clear:o.clear}}import{computed as P,DestroyRef as yt,inject as gt,signal as Bt}from"@angular/core";function Rt(){let t=l(),e=gt(yt),r=Bt(_(t)),o=q(t,s=>{r.set(s)});return e.onDestroy(()=>o()),{canUndo:P(()=>r().canUndo),canRedo:P(()=>r().canRedo),historyIndex:P(()=>r().historyIndex),historySize:P(()=>r().historySize),undo:()=>t.feature.undo(),redo:()=>t.feature.redo()}}import{computed as D,DestroyRef as bt,inject as jt,signal as vt}from"@angular/core";function Ft(t){let e=l(),r=e.read.getScopeStatus(t),o=vt(r),s=X(e,t,f=>{o.set(f)});jt(bt,{optional:!0})?.onDestroy(()=>s());let p=async()=>{let f=await e.feature.validate({scope:t}),m=e.read.getScopeErrors(t);return{valid:f,errors:m}},a=()=>e.read.getScopeErrors(t),d=D(()=>!o().hasErrors),c=D(()=>o().isDirty),n=D(()=>o().errors);return{scopeName:t,status:o,errors:n,validate:p,getErrors:a,isValid:d,isDirty:c,unsubscribe:s}}import{computed as R,DestroyRef as Pt,inject as Tt,signal as ot}from"@angular/core";function ht(t){let e=l(),r=ot(0),o=R(()=>t[r()]??""),s=()=>t[r()]??"",i=ot(e.read.getScopeStatus(s())),p=()=>{let u=s(),g=e.read.getScopeStatus(u),b=i();O(b,g)||i.set(g)},a=e.observe.subscribeScopeStatus(s(),p),d=()=>{a(),a=e.observe.subscribeScopeStatus(s(),p)};Tt(Pt,{optional:!0})?.onDestroy(()=>a());let n=async()=>{let u=s(),g=await e.feature.validate({scope:u}),b=e.read.getScopeErrors(u);return{valid:g,errors:b}},f=()=>e.read.getScopeErrors(s()),m=async()=>{let u=s(),g=e.read.getScopeFields(u);if(e.feature.hasValidationsInProgress(g))return!1;let b=await e.feature.validate({scope:u});if(b){let F=Math.min(r()+1,t.length-1);r.set(F),i.set(e.read.getScopeStatus(t[F]??"")),d()}else{let F=e.read.getScopeErrors(u),U=Object.keys(F);U.length>0&&e.write.markFieldsTouched(U)}return b},j=()=>{let u=Math.max(r()-1,0);r.set(u),i.set(e.read.getScopeStatus(t[u]??"")),d()},T=u=>{let g=Math.max(0,Math.min(u-1,t.length-1));r.set(g),i.set(e.read.getScopeStatus(t[g]??"")),d()},v=R(()=>r()+1),h=R(()=>r()===0),x=R(()=>r()>=t.length-1),A=R(()=>!i().hasErrors),y=R(()=>i().isDirty),st=R(()=>i().errors);return{step:v,stepIndex:r,scope:o,next:m,prev:j,goTo:T,isFirst:h,isLast:x,status:i,errors:st,isValid:A,isDirty:y,validate:n,getErrors:f}}import{DestroyRef as xt,signal as Vt,inject as It}from"@angular/core";function Et(t){let e=l(),r=It(xt),o=Vt(H(e.read.getState().values,t),{equal:M}),s=e.observe.subscribePath(t,i=>{o.set(i)});return r.onDestroy(s),o.asReadonly()}import{computed as w,inject as Dt,signal as wt}from"@angular/core";function kt(t,e,r){let o=Dt(B),s=E(t),i=null,p=wt(!1),a={setLoading:n=>p.set(n),setError:(n,f)=>o.write.setError(n,f),setValue:n=>s.setValue(n),getUploadKey:()=>i,setUploadKey:n=>{i=n}},d=Z(t,e,a),c=N(t,r,a);return{value:w(()=>s.value()),setValue:s.setValue,error:w(()=>s.meta.error()),isValidating:w(()=>!!s.meta.isValidating()||p()),upload:d,remove:c}}import{computed as k,DestroyRef as At,inject as Ut,signal as Mt}from"@angular/core";function Ht(){let t=l(),e=Mt(t.read.getPersistMetadata()),r=W(t,a=>{e.set(a)});return Ut(At,{optional:!0})?.onDestroy(()=>r()),{restore:async()=>t.feature.restorePersisted(),save:async()=>{await t.feature.forceSave()},clear:async()=>{await t.feature.clearPersisted()},meta:{isSaving:k(()=>e().isSaving),isRestoring:k(()=>e().isRestoring),error:k(()=>e().error)}}}export{ft as injectBitArray,E as injectBitField,lt as injectBitForm,Rt as injectBitHistory,Ht as injectBitPersist,Ft as injectBitScope,ht as injectBitSteps,kt as injectBitUpload,Et as injectBitWatch,at as provideBitStore,l as useBitStore};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function l(e,n=new WeakMap){if(e===null||typeof e!="object")return e;if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(n.has(e))return n.get(e);if(e instanceof Map){let s=new Map;return n.set(e,s),e.forEach((t,o)=>{s.set(l(o,n),l(t,n))}),s}if(e instanceof Set){let s=new Set;return n.set(e,s),e.forEach(t=>{s.add(l(t,n))}),s}if(Array.isArray(e)){let s=[];n.set(e,s);for(let t of e)s.push(l(t,n));return s}let r=Object.getPrototypeOf(e);if(!(r===Object.prototype||r===null)){let s=Object.create(r);n.set(e,s);for(let t of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,t);o&&("value"in o&&(o.value=l(o.value,n)),Object.defineProperty(s,t,o))}return s}let c={};n.set(e,c);for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&(c[s]=l(e[s],n));return c}function d(e){return l(e)}function m(e,n,r=new WeakMap){if(n===void 0)return d(e);if(n===null||typeof n!="object"||n instanceof Date||n instanceof RegExp||Array.isArray(n))return d(n);let a=n;if(r.has(a))return r.get(a);let c=e&&typeof e=="object"&&!Array.isArray(e)?d(e):{};r.set(a,c);try{for(let s of Object.keys(n)){let t=n[s],o=c[s];if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date)&&!(t instanceof RegExp)){c[s]=m(o,t,r);continue}c[s]=d(t)}}finally{r.delete(a)}return c}function A(e,n){return e===n?!0:e===null||typeof e!="object"||n===null||typeof n!="object"?!1:R(e,n)}function R(e,n){return x(e,n,new WeakMap)}function x(e,n,r){if(e===n)return!0;if(e===null||typeof e!="object"||n===null||typeof n!="object")return!1;let a=r.get(e);if(a?.has(n))return!0;if(a?a.add(n):r.set(e,new WeakSet([n])),Array.isArray(e)!==Array.isArray(n))return!1;if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime();if(e instanceof RegExp&&n instanceof RegExp)return e.toString()===n.toString();let c=Object.keys(e),s=Object.keys(n);if(c.length!==s.length)return!1;for(let t of c)if(!Object.prototype.hasOwnProperty.call(n,t)||!x(e[t],n[t],r))return!1;return!0}function b(e,n,r="",a=new Set,c=new WeakMap){if(A(e,n))return a;if(e===null||typeof e!="object"||n===null||typeof n!="object")return r&&a.add(r),a;let s=c.get(e);if(s?.has(n))return a;if(s?s.add(n):c.set(e,new WeakSet([n])),Array.isArray(e)||Array.isArray(n))return!A(e,n)&&r&&a.add(r),a;let t=new Set;for(let o of Object.keys(e||{}))t.add(o);for(let o of Object.keys(n||{}))t.add(o);for(let o of t){let i=r?`${r}.${o}`:o;b(e?.[o],n?.[o],i,a,c)}return a}var p=new Map;function T(e,n){if(p.has(e))p.delete(e);else if(p.size>=5e3){let r=p.keys().next().value;r!==void 0&&p.delete(r)}p.set(e,n)}function k(e){let n=p.get(e);if(n)return n;let r=e.split(".");return T(e,r),r}function V(e,n){if(!n)return e;let r=k(n),a=e;for(let c of r){if(a==null)return;a=a[c]}return a}function K(e,n,r){if(!n)return r;let a=k(n),c=Array.isArray(e)?[...e]:{...e},s=c;for(let t=0;t<a.length-1;t++){let o=a[t],i=a[t+1],u=Number(i),f=Number.isInteger(u)&&String(u)===i,y=s[o];y==null?s[o]=f?[]:{}:s[o]=Array.isArray(y)?[...y]:{...y},s=s[o]}return s[a[a.length-1]]=r,c}function E(e,n){if(n.length===0)return e;let r=Array.isArray(e)?[...e]:{...e},a=new WeakSet;r&&typeof r=="object"&&a.add(r);for(let[c,s]of n){let t=k(c),o=r;for(let i=0;i<t.length-1;i++){let u=t[i],f=t[i+1],y=Number(f),w=Number.isInteger(y)&&String(y)===f,g=o[u];g==null?(o[u]=w?[]:{},a.add(o[u])):typeof g=="object"?a.has(g)||(o[u]=Array.isArray(g)?[...g]:{...g},a.add(o[u])):(o[u]=w?[]:{},a.add(o[u])),o=o[u]}o[t[t.length-1]]=s}return r}function D(e,n){if(n.length===0)return e;let r=Array.isArray(e)?[...e]:{...e},a=new WeakSet;r&&typeof r=="object"&&a.add(r);for(let c of n){if(!c)return Array.isArray(e)?[]:{};let s=k(c),t=r;for(let i=0;i<s.length-1;i++){let u=s[i],f=t?.[u];if(f==null){t=void 0;break}if(typeof f=="object")a.has(f)||(t[u]=Array.isArray(f)?[...f]:{...f},a.add(t[u]));else{t=void 0;break}t=t[u]}if(!t)continue;let o=s[s.length-1];Array.isArray(t)?t.splice(Number(o),1):t&&typeof t=="object"&&delete t[o]}return r}function S(e,n){let r={},a=`${n}.`;for(let c in e)c!==n&&!c.startsWith(a)&&(r[c]=e[c]);return r}function N(e,n,r){let a={},c={},s={},t=`${n}.`;for(let o of Object.keys(e.errors)){let i=h(o,t,r);i&&(a[i]=e.errors[o])}for(let o of Object.keys(e.touched)){let i=h(o,t,r);i&&(c[i]=e.touched[o])}for(let o of Object.keys(e.isValidating)){let i=h(o,t,r);i&&(s[i]=e.isValidating[o])}return{errors:a,touched:c,isValidating:s}}function h(e,n,r){if(!e.startsWith(n))return e;let c=e.substring(n.length).split("."),s=Number(c[0]);if(!Number.isInteger(s)||s<0)return e;let t=r(s);if(t===null)return null;let o=c.slice(1).join(".");return o?`${n}${t}.${o}`:`${n}${t}`}function O(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let n=e.errors??e;if(typeof n!="object"||n===null||Array.isArray(n))return!1;let r=Object.entries(n);return r.length===0?!1:r.every(([a,c])=>a.length>0&&(typeof c=="string"||Array.isArray(c)&&c.every(s=>typeof s=="string")))}function W(e){return O(e)?e.errors??e:{}}export{d as a,m as b,A as c,R as d,b as e,V as f,K as g,E as h,D as i,S as j,N as k,O as l,W as m};
|
|
2
|
+
//# sourceMappingURL=chunk-6NH6MUXA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/utils/clone.ts","../src/core/utils/structural.ts","../src/core/utils/path-value.ts","../src/core/utils/array-meta.ts","../src/core/utils/server-errors.ts"],"sourcesContent":["export function cloneValue<T>(\n obj: T,\n visited: WeakMap<object, unknown> = new WeakMap(),\n): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(obj);\n } catch {\n // Alguns runtimes lançam para payloads não suportados (ex.: funções).\n // Nesses casos, seguimos para o clone recursivo para manter fail-open.\n }\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (visited.has(obj as object)) {\n return visited.get(obj as object) as T;\n }\n\n if (obj instanceof Map) {\n const clone = new Map<unknown, unknown>();\n visited.set(obj as object, clone);\n\n obj.forEach((value, key) => {\n clone.set(cloneValue(key, visited), cloneValue(value, visited));\n });\n\n return clone as T;\n }\n\n if (obj instanceof Set) {\n const clone = new Set<unknown>();\n visited.set(obj as object, clone);\n\n obj.forEach((value) => {\n clone.add(cloneValue(value, visited));\n });\n\n return clone as T;\n }\n\n if (Array.isArray(obj)) {\n const clone: unknown[] = [];\n visited.set(obj as object, clone);\n\n for (const item of obj) {\n clone.push(cloneValue(item, visited));\n }\n\n return clone as T;\n }\n\n const prototype = Object.getPrototypeOf(obj);\n const isPlainObject = prototype === Object.prototype || prototype === null;\n\n if (!isPlainObject) {\n const clone = Object.create(prototype) as Record<PropertyKey, unknown>;\n visited.set(obj as object, clone);\n\n for (const key of Reflect.ownKeys(obj as object)) {\n const descriptor = Object.getOwnPropertyDescriptor(obj as object, key);\n if (!descriptor) {\n continue;\n }\n\n if (\"value\" in descriptor) {\n descriptor.value = cloneValue(descriptor.value, visited);\n }\n\n Object.defineProperty(clone, key, descriptor);\n }\n\n return clone as T;\n }\n\n const clone: any = {};\n visited.set(obj as object, clone);\n\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = cloneValue((obj as any)[key], visited);\n }\n }\n\n return clone as T;\n}\n","import { cloneValue } from \"./clone\";\n\nexport function deepClone<T>(obj: T): T {\n return cloneValue(obj);\n}\n\nexport function deepMerge<T>(\n target: T,\n source: any,\n activeMerges: WeakMap<object, unknown> = new WeakMap(),\n): T {\n if (source === undefined) {\n return deepClone(target);\n }\n\n if (\n source === null ||\n typeof source !== \"object\" ||\n source instanceof Date ||\n source instanceof RegExp ||\n Array.isArray(source)\n ) {\n return deepClone(source as T);\n }\n\n const sourceObject = source as object;\n if (activeMerges.has(sourceObject)) {\n return activeMerges.get(sourceObject) as T;\n }\n\n const base =\n target && typeof target === \"object\" && !Array.isArray(target)\n ? deepClone(target as any)\n : ({} as Record<string, unknown>);\n\n activeMerges.set(sourceObject, base);\n\n try {\n for (const key of Object.keys(source)) {\n const sourceValue = source[key];\n const baseValue = (base as Record<string, unknown>)[key];\n\n if (\n sourceValue !== null &&\n typeof sourceValue === \"object\" &&\n !Array.isArray(sourceValue) &&\n !(sourceValue instanceof Date) &&\n !(sourceValue instanceof RegExp)\n ) {\n (base as Record<string, unknown>)[key] = deepMerge(\n baseValue,\n sourceValue,\n activeMerges,\n );\n continue;\n }\n\n (base as Record<string, unknown>)[key] = deepClone(sourceValue);\n }\n } finally {\n activeMerges.delete(sourceObject);\n }\n\n return base as T;\n}\n\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n return deepEqualInner(a, b, new WeakMap());\n}\n\nfunction deepEqualInner(\n a: any,\n b: any,\n visitedPairs: WeakMap<object, WeakSet<object>>,\n): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n const visitedTargets = visitedPairs.get(a);\n if (visitedTargets?.has(b)) return true;\n\n if (visitedTargets) {\n visitedTargets.add(b);\n } else {\n visitedPairs.set(a, new WeakSet([b]));\n }\n\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqualInner(a[key], b[key], visitedPairs)\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n visitedPairs: WeakMap<object, WeakSet<object>> = new WeakMap(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n\n const visitedInitials = visitedPairs.get(obj as object);\n if (visitedInitials?.has(initial as object)) {\n return result;\n }\n\n if (visitedInitials) {\n visitedInitials.add(initial as object);\n } else {\n visitedPairs.set(obj as object, new WeakSet([initial as object]));\n }\n\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set<string>();\n for (const key of Object.keys(obj || {})) {\n allKeys.add(key);\n }\n for (const key of Object.keys(initial || {})) {\n allKeys.add(key);\n }\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths(\n (obj as any)?.[k],\n (initial as any)?.[k],\n p,\n result,\n visitedPairs,\n );\n }\n return result;\n}\n","const PATH_CACHE_MAX = 5000;\nconst pathCache = new Map<string, string[]>();\n\nfunction setPathCacheEntry(path: string, keys: string[]) {\n if (pathCache.has(path)) {\n pathCache.delete(path);\n } else if (pathCache.size >= PATH_CACHE_MAX) {\n const oldestKey = pathCache.keys().next().value;\n if (oldestKey !== undefined) {\n pathCache.delete(oldestKey);\n }\n }\n\n pathCache.set(path, keys);\n}\n\nfunction getPathKeys(path: string): string[] {\n const cached = pathCache.get(path);\n if (cached) {\n return cached;\n }\n\n const keys = path.split(\".\");\n setPathCacheEntry(path, keys);\n return keys;\n}\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = getPathKeys(path);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = getPathKeys(path);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function setDeepValues(\n obj: any,\n updates: ReadonlyArray<readonly [path: string, value: any]>,\n): any {\n if (updates.length === 0) {\n return obj;\n }\n\n const root = Array.isArray(obj) ? [...obj] : { ...obj };\n const clonedNodes = new WeakSet<object>();\n if (root && typeof root === \"object\") {\n clonedNodes.add(root);\n }\n\n for (const [path, value] of updates) {\n const keys = getPathKeys(path);\n let current: any = root;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n clonedNodes.add(current[key]);\n } else if (typeof currentValue === \"object\") {\n if (!clonedNodes.has(currentValue)) {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n clonedNodes.add(current[key]);\n }\n } else {\n current[key] = isNextNumeric ? [] : {};\n clonedNodes.add(current[key]);\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n }\n\n return root;\n}\n\nexport function unsetDeepValue(obj: any, path: string): any {\n if (!path) {\n return Array.isArray(obj) ? [] : {};\n }\n\n const keys = getPathKeys(path);\n const root = Array.isArray(obj) ? [...obj] : { ...obj };\n let current: any = root;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const currentValue = current?.[key];\n\n if (currentValue === null || currentValue === undefined) {\n return root;\n }\n\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n\n current = current[key];\n }\n\n const leafKey = keys[keys.length - 1];\n\n if (Array.isArray(current)) {\n current.splice(Number(leafKey), 1);\n } else if (current && typeof current === \"object\") {\n delete current[leafKey];\n }\n\n return root;\n}\n\nexport function unsetDeepValues(obj: any, paths: ReadonlyArray<string>): any {\n if (paths.length === 0) {\n return obj;\n }\n\n const root = Array.isArray(obj) ? [...obj] : { ...obj };\n const clonedNodes = new WeakSet<object>();\n if (root && typeof root === \"object\") {\n clonedNodes.add(root);\n }\n\n for (const path of paths) {\n if (!path) {\n return Array.isArray(obj) ? [] : {};\n }\n\n const keys = getPathKeys(path);\n let current: any = root;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const currentValue = current?.[key];\n\n if (currentValue === null || currentValue === undefined) {\n current = undefined;\n break;\n }\n\n if (typeof currentValue === \"object\") {\n if (!clonedNodes.has(currentValue)) {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n clonedNodes.add(current[key]);\n }\n } else {\n current = undefined;\n break;\n }\n\n current = current[key];\n }\n\n if (!current) {\n continue;\n }\n\n const leafKey = keys[keys.length - 1];\n\n if (Array.isArray(current)) {\n current.splice(Number(leafKey), 1);\n } else if (current && typeof current === \"object\") {\n delete current[leafKey];\n }\n }\n\n return root;\n}\n","export function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === removedIndex) {\n return null;\n }\n\n return currentIdx > removedIndex ? currentIdx - 1 : currentIdx;\n });\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === indexA) {\n return indexB;\n }\n\n if (currentIdx === indexB) {\n return indexA;\n }\n\n return currentIdx;\n });\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === from) {\n return to;\n }\n\n if (from < to && currentIdx > from && currentIdx <= to) {\n return currentIdx - 1;\n }\n\n if (from > to && currentIdx >= to && currentIdx < from) {\n return currentIdx + 1;\n }\n\n return currentIdx;\n });\n};\n\nexport function reindexFieldArrayMeta(\n state: {\n errors: Record<string, any>;\n touched: Record<string, any>;\n isValidating: Record<string, any>;\n },\n path: string,\n remapIndex: (index: number) => number | null,\n) {\n const nextErrors: Record<string, any> = {};\n const nextTouched: Record<string, any> = {};\n const nextIsValidating: Record<string, any> = {};\n\n const prefix = `${path}.`;\n\n for (const key of Object.keys(state.errors)) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (nextKey) nextErrors[nextKey] = state.errors[key];\n }\n\n for (const key of Object.keys(state.touched)) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (nextKey) nextTouched[nextKey] = state.touched[key];\n }\n\n for (const key of Object.keys(state.isValidating)) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (nextKey) nextIsValidating[nextKey] = state.isValidating[key];\n }\n\n return {\n errors: nextErrors,\n touched: nextTouched,\n isValidating: nextIsValidating,\n };\n}\n\nfunction remapIndexedPath(\n key: string,\n prefix: string,\n remapIndex: (index: number) => number | null,\n) {\n if (!key.startsWith(prefix)) {\n return key;\n }\n\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = Number(parts[0]);\n if (!Number.isInteger(currentIdx) || currentIdx < 0) {\n return key;\n }\n const nextIdx = remapIndex(currentIdx);\n\n if (nextIdx === null) {\n return null;\n }\n\n const rest = parts.slice(1).join(\".\");\n return rest ? `${prefix}${nextIdx}.${rest}` : `${prefix}${nextIdx}`;\n}\n\nfunction reindexObjectKeys(\n obj: Record<string, any>,\n path: string,\n remapIndex: (index: number) => number | null,\n) {\n const nextObject: Record<string, any> = {};\n const prefix = `${path}.`;\n\n for (const key of Object.keys(obj)) {\n if (!key.startsWith(prefix)) {\n nextObject[key] = obj[key];\n continue;\n }\n\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = Number(parts[0]);\n if (!Number.isInteger(currentIdx) || currentIdx < 0) {\n nextObject[key] = obj[key];\n continue;\n }\n const nextIdx = remapIndex(currentIdx);\n\n if (nextIdx === null) {\n continue;\n }\n\n const rest = parts.slice(1).join(\".\");\n const nextKey = rest\n ? `${prefix}${nextIdx}.${rest}`\n : `${prefix}${nextIdx}`;\n nextObject[nextKey] = obj[key];\n }\n\n return nextObject;\n}\n","export function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) {\n return false;\n }\n\n const entries = Object.entries(obj as Record<string, unknown>);\n if (entries.length === 0) {\n return false;\n }\n\n return entries.every(\n ([key, v]) =>\n key.length > 0 &&\n (typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\"))),\n );\n}\n\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n"],"mappings":"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","names":["cloneValue","obj","visited","clone","value","key","item","prototype","descriptor","deepClone","obj","cloneValue","deepMerge","target","source","activeMerges","sourceObject","base","key","sourceValue","baseValue","valueEqual","a","b","deepEqual","deepEqualInner","visitedPairs","visitedTargets","keysA","keysB","collectDirtyPaths","initial","prefix","result","visitedInitials","allKeys","k","p","pathCache","setPathCacheEntry","path","keys","oldestKey","getPathKeys","cached","getDeepValue","obj","current","key","setDeepValue","value","result","i","nextKey","nextAsNumber","isNextNumeric","currentValue","setDeepValues","updates","root","clonedNodes","unsetDeepValues","obj","paths","root","clonedNodes","path","keys","getPathKeys","current","key","currentValue","leafKey","cleanPrefixedKeys","obj","prefix","newObj","prefixWithDot","key","reindexFieldArrayMeta","state","path","remapIndex","nextErrors","nextTouched","nextIsValidating","prefix","key","nextKey","remapIndexedPath","parts","currentIdx","nextIdx","rest","isValidationErrorShape","x","obj","entries","key","v","i","extractServerErrors"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkRGMUXQ2Kcjs = require('./chunk-RGMUXQ2K.cjs');function o(i,e){return e&&e.value===i.value&&e.error===i.error&&e.touched===i.touched&&e.isHidden===i.isHidden&&e.isRequired===i.isRequired&&e.isDirty===i.isDirty&&e.isValidating===i.isValidating?e:{value:i.value,error:i.error,touched:i.touched,isHidden:i.isHidden,isRequired:i.isRequired,isDirty:i.isDirty,isValidating:i.isValidating}}function d(i,e){return i===e?!0:!i||!e?!1:_chunkRGMUXQ2Kcjs.d.call(void 0, i.value,e.value)&&i.error===e.error&&i.touched===e.touched&&i.isHidden===e.isHidden&&i.isRequired===e.isRequired&&i.isDirty===e.isDirty&&i.isValidating===e.isValidating}var n=d;exports.a = o; exports.b = d; exports.c = n;
|
|
2
|
+
//# sourceMappingURL=chunk-C2GGB5NF.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-C2GGB5NF.cjs","../src/core/utils/field-state-snapshot.ts"],"names":["createFieldStateSnapshot","nextState","lastSnapshot","areFieldSnapshotsEqual","snapshotA","snapshotB","deepEqual","areFieldStatesEqual"],"mappings":"AAAA,iIAAwC,SCqCxBA,CAAAA,CACdC,CAAAA,CASAC,CAAAA,CAC0B,CAE1B,OAAIA,CAAAA,EAEAA,CAAAA,CAAa,KAAA,GAAUD,CAAAA,CAAU,KAAA,EACjCC,CAAAA,CAAa,KAAA,GAAUD,CAAAA,CAAU,KAAA,EACjCC,CAAAA,CAAa,OAAA,GAAYD,CAAAA,CAAU,OAAA,EACnCC,CAAAA,CAAa,QAAA,GAAaD,CAAAA,CAAU,QAAA,EACpCC,CAAAA,CAAa,UAAA,GAAeD,CAAAA,CAAU,UAAA,EACtCC,CAAAA,CAAa,OAAA,GAAYD,CAAAA,CAAU,OAAA,EACnCC,CAAAA,CAAa,YAAA,GAAiBD,CAAAA,CAAU,YAAA,CAGjCC,CAAAA,CAIJ,CACL,KAAA,CAAOD,CAAAA,CAAU,KAAA,CACjB,KAAA,CAAOA,CAAAA,CAAU,KAAA,CACjB,OAAA,CAASA,CAAAA,CAAU,OAAA,CACnB,QAAA,CAAUA,CAAAA,CAAU,QAAA,CACpB,UAAA,CAAYA,CAAAA,CAAU,UAAA,CACtB,OAAA,CAASA,CAAAA,CAAU,OAAA,CACnB,YAAA,CAAcA,CAAAA,CAAU,YAC1B,CACF,CAUO,SAASE,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACS,CACT,OAAID,CAAAA,GAAcC,CAAAA,CAAkB,CAAA,CAAA,CAChC,CAACD,CAAAA,EAAa,CAACC,CAAAA,CAAkB,CAAA,CAAA,CAGnCC,iCAAAA,CAAUF,CAAU,KAAA,CAAOC,CAAAA,CAAU,KAAK,CAAA,EAC1CD,CAAAA,CAAU,KAAA,GAAUC,CAAAA,CAAU,KAAA,EAC9BD,CAAAA,CAAU,OAAA,GAAYC,CAAAA,CAAU,OAAA,EAChCD,CAAAA,CAAU,QAAA,GAAaC,CAAAA,CAAU,QAAA,EACjCD,CAAAA,CAAU,UAAA,GAAeC,CAAAA,CAAU,UAAA,EACnCD,CAAAA,CAAU,OAAA,GAAYC,CAAAA,CAAU,OAAA,EAChCD,CAAAA,CAAU,YAAA,GAAiBC,CAAAA,CAAU,YAEzC,CAEO,IAAME,CAAAA,CAAsBJ,CAAAA,CAAAA,4CAAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-C2GGB5NF.cjs","sourcesContent":[null,"/**\n * Field State Snapshot Utilities\n *\n * Shared utilities for creating and managing field state snapshots across frameworks\n * (React, Vue, Angular). Reduces code duplication while maintaining type safety.\n */\n\nimport type { BitFieldState } from \"../store/contracts/types\";\nimport { deepEqual } from \"../utils\";\n\n/**\n * Represents a stable snapshot of field state that can be compared for equality.\n */\nexport type BitFieldSnapshot<TValue = unknown> = BitFieldState<\n Record<string, unknown>,\n TValue\n>;\n\n/**\n * Creates or reuses a field state snapshot with shallow equality checking.\n *\n * This function prevents unnecessary re-renders in frameworks like React by\n * returning the same object reference when field state hasn't changed.\n *\n * @param nextState - The new field state from the store\n * @param lastSnapshot - The previous snapshot (can be null on first call)\n * @returns A stable snapshot object that can be used for equality comparison\n *\n * @example\n * ```typescript\n * const snapshot = createFieldStateSnapshot(store.getFieldState(\"email\"), lastSnapshot);\n * if (snapshot !== lastSnapshot) {\n * // Field state changed, update component\n * render(snapshot);\n * }\n * ```\n */\nexport function createFieldStateSnapshot<TValue = unknown>(\n nextState: {\n value: TValue;\n error: string | undefined;\n touched: boolean;\n isHidden: boolean;\n isRequired: boolean;\n isDirty: boolean;\n isValidating: boolean;\n },\n lastSnapshot: BitFieldSnapshot<TValue> | null,\n): BitFieldSnapshot<TValue> {\n // Use shallow equality: return cached if all fields are equal by reference\n if (lastSnapshot) {\n const shallowEqual =\n lastSnapshot.value === nextState.value &&\n lastSnapshot.error === nextState.error &&\n lastSnapshot.touched === nextState.touched &&\n lastSnapshot.isHidden === nextState.isHidden &&\n lastSnapshot.isRequired === nextState.isRequired &&\n lastSnapshot.isDirty === nextState.isDirty &&\n lastSnapshot.isValidating === nextState.isValidating;\n\n if (shallowEqual) {\n return lastSnapshot;\n }\n }\n\n return {\n value: nextState.value,\n error: nextState.error,\n touched: nextState.touched,\n isHidden: nextState.isHidden,\n isRequired: nextState.isRequired,\n isDirty: nextState.isDirty,\n isValidating: nextState.isValidating,\n };\n}\n\n/**\n * Deep comparison utility for field state snapshots.\n * Useful for scenarios where shallow comparison isn't sufficient (e.g., object/array values).\n *\n * @param snapshotA - First snapshot\n * @param snapshotB - Second snapshot\n * @returns true if snapshots are deeply equal\n */\nexport function areFieldSnapshotsEqual(\n snapshotA: BitFieldSnapshot | null | undefined,\n snapshotB: BitFieldSnapshot | null | undefined,\n): boolean {\n if (snapshotA === snapshotB) return true;\n if (!snapshotA || !snapshotB) return false;\n\n return (\n deepEqual(snapshotA.value, snapshotB.value) &&\n snapshotA.error === snapshotB.error &&\n snapshotA.touched === snapshotB.touched &&\n snapshotA.isHidden === snapshotB.isHidden &&\n snapshotA.isRequired === snapshotB.isRequired &&\n snapshotA.isDirty === snapshotB.isDirty &&\n snapshotA.isValidating === snapshotB.isValidating\n );\n}\n\nexport const areFieldStatesEqual = areFieldSnapshotsEqual;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as Et,c as Ut,d as A,e as qt,h as j}from"./chunk-UIKO6GGW.js";import{c as Lt}from"./chunk-S3DJPXMV.js";import{a as b,b as Mt,c as F,d as R,e as Rt,f as S,g as O,h as P,i as Ot,k as jt,l as Ht,m as zt}from"./chunk-6NH6MUXA.js";function _t(r){let{path:t,getFieldConfig:e,masks:i}=r,s=e(t)?.mask;if(s)return typeof s=="string"?i?.[s]:s}function Nt(r){let{state:t,path:e,value:i,isHidden:s,isRequired:o,isDirty:n,isValidating:a}=r,c=e;return{value:i,error:t.errors[c],touched:!!t.touched[c],isHidden:s,isRequired:o,isDirty:n,isValidating:a}}var k=Symbol.for("bit-form.framework-store-api");var M=Symbol.for("bit-form.hooks-api");var H=class{constructor(t){this.baselineValues=b(t)}baselineValues;baselineSnapshot;getValues(){return this.baselineSnapshot||(this.baselineSnapshot=Object.freeze(b(this.baselineValues))),this.baselineSnapshot}setValues(t){this.baselineValues=b(t),this.baselineSnapshot=void 0}};var z=class{constructor(t,e){this.getComputedEntries=t;this.onError=e}equalityCache=new Map;reverseDepsCache=null;childDepsIndex=null;validatedEntriesSignature=null;validatedEntriesRef=null;orderedAllEntriesCache=null;orderedIndexByPathCache=null;isCacheableScalar(t){return t===null||typeof t!="object"&&typeof t!="function"}invalidateReverseDeps(){this.reverseDepsCache=null,this.childDepsIndex=null,this.orderedAllEntriesCache=null,this.validatedEntriesSignature=null,this.validatedEntriesRef=null,this.orderedIndexByPathCache=null,this.equalityCache.clear()}apply(t,e){let i=this.getComputedEntries();if(i.length===0)return t;this.ensureEntriesAreValid(i);let s=this.resolveEntriesToRun(i,e);if(s.length===0)return t;let o=t,n=new Set;for(let a of s){if(a.dependsOn.some(h=>n.has(h))){n.add(a.path);continue}let c;try{c=a.compute(o)}catch(h){this.onError?.(h,a.path),n.add(a.path);continue}let u=S(o,a.path),l=this.equalityCache.get(a.path),d,p=this.isCacheableScalar(u)&&this.isCacheableScalar(c);p&&l&&l.current===u&&l.next===c?d=l.equal:(d=R(u,c),p?this.equalityCache.set(a.path,{current:u,next:c,equal:d}):this.equalityCache.delete(a.path)),d||(o=O(o,a.path,c))}return o}getReverseDependencies(t){if(this.reverseDepsCache)return this.reverseDepsCache;let e=new Map;for(let s of t)for(let o of s.dependsOn){let n=e.get(o);n||(n=new Set,e.set(o,n)),n.add(s.path)}let i=new Map;for(let s of e.keys()){let o=s.split(".");for(let n=1;n<o.length;n++){let a=o.slice(0,n).join("."),c=i.get(a);c||(c=new Set,i.set(a,c)),c.add(s)}}return this.reverseDepsCache=e,this.childDepsIndex=i,e}resolveEntriesToRun(t,e){if(!e||e.length===0||e.includes("*"))return this.getOrderedAllEntries(t);let i=this.getReverseDependencies(t),s=new Set,o=[...e],n=0;for(;n<o.length;){let l=o[n++],d=this.getDependentsForPath(i,l);if(d)for(let p of d)s.has(p)||(s.add(p),o.push(p))}if(s.size===0)return[];let a=this.getOrderedAllEntries(t),c=this.getOrderedIndexByPath(t,a),u=[];return s.forEach(l=>{let d=c.get(l);if(d===void 0)return;let p=a[d];p&&u.push({index:d,entry:p})}),u.sort((l,d)=>l.index-d.index),u.map(l=>l.entry)}orderEntries(t){if(t.length<=1)return t;let e=new Map(t.map(a=>[a.path,a])),i=new Map,s=new Map;t.forEach(a=>i.set(a.path,0)),t.forEach(a=>{a.dependsOn.forEach(c=>{if(!e.has(c))return;let u=s.get(c)??new Set;u.has(a.path)||(u.add(a.path),s.set(c,u),i.set(a.path,(i.get(a.path)??0)+1))})});let o=t.filter(a=>(i.get(a.path)??0)===0).map(a=>a.path),n=[];for(;o.length>0;){let a=o.shift();n.push(a);let c=s.get(a);c&&c.forEach(u=>{let l=(i.get(u)??0)-1;i.set(u,l),l===0&&o.push(u)})}if(n.length!==t.length)throw new Error("BitStore: cyclic computed dependencies detected. Check computedDependsOn definitions.");return n.map(a=>e.get(a))}getOrderedAllEntries(t){let e=this.createEntriesSignature(t);if(this.orderedAllEntriesCache&&this.orderedAllEntriesCache.signature===e)return this.orderedAllEntriesCache.ordered;let i=this.orderEntries(t);return this.orderedAllEntriesCache={signature:e,ordered:i},i}getOrderedIndexByPath(t,e){let i=this.createEntriesSignature(t);if(this.orderedIndexByPathCache&&this.orderedIndexByPathCache.signature===i)return this.orderedIndexByPathCache.indexByPath;let s=new Map;return e.forEach((o,n)=>{s.set(o.path,n)}),this.orderedIndexByPathCache={signature:i,indexByPath:s},s}ensureEntriesAreValid(t){if(this.validatedEntriesRef===t)return;let e=this.createEntriesSignature(t);if(this.validatedEntriesSignature===e){this.validatedEntriesRef=t;return}t.forEach(i=>this.assertDependencies(i)),this.invalidateReverseDeps(),this.validatedEntriesSignature=e,this.validatedEntriesRef=t}createEntriesSignature(t){return t.map(e=>`${e.path}:${e.dependsOn.join(",")}`).join("|")}getDependentsForPath(t,e){let i=new Set,s=a=>{let c=t.get(a);c&&c.forEach(u=>i.add(u))};s(e);let o=e.split(".");for(;o.length>1;)o.pop(),s(o.join("."));let n=this.childDepsIndex?.get(e);if(n)for(let a of n)s(a);return i}assertDependencies(t){if(t.dependsOn.length===0)throw new Error(`BitStore: computed field \`${t.path}\` requires explicit computedDependsOn in v4.`);if(t.dependsOn.includes(t.path))throw new Error(`BitStore: computed field \`${t.path}\` cannot depend on itself.`)}};var U=class{dirtyPaths=new Set;dirtyPathIndex=new Set;dirtyPrefixRefCount=new Map;childrenByPrefix=new Map;updateForPath(t,e,i){this.removeDirtyChildren(t);let s=S(e,t),o=S(i,t);return F(s,o)?this.removeDirtyPath(t):this.addDirtyPath(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=Rt(t,e),this.dirtyPrefixRefCount.clear(),this.rebuildIndex(),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear(),this.dirtyPathIndex.clear(),this.dirtyPrefixRefCount.clear(),this.childrenByPrefix.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}isPathDirty(t){if(this.dirtyPathIndex.has(t))return!0;let e=t.lastIndexOf(".");for(;e>-1;){let i=t.slice(0,e);if((this.dirtyPrefixRefCount.get(i)??0)>0)return!0;e=t.lastIndexOf(".",e-1)}return!1}buildDirtyValues(t){if(this.dirtyPaths.size===0)return{};let e=[],i=[...this.dirtyPaths].sort(),s=new Set,o=new Set,n=a=>{let c=a.lastIndexOf(".");for(;c>-1;){if(o.has(a.slice(0,c)))return!0;c=a.lastIndexOf(".",c-1)}return!1};for(let a of i){if(n(a))continue;let c=a.match(/^(.+)\.\d+/);if(c){let u=c[1];if(s.has(u))continue;s.add(u);let l=S(t,u);e.push([u,l]),o.add(u)}else{let u=S(t,a);e.push([a,u]),o.add(a)}}return e.length===0?{}:P({},e)}rebuildIndex(){let t=new Set,e=new Map,i=new Map;for(let s of this.dirtyPaths)this.forEachPathPrefix(s,o=>{t.add(o),e.set(o,(e.get(o)??0)+1)}),this.forEachAncestorPrefix(s,o=>{let n=i.get(o);n?n.add(s):i.set(o,new Set([s]))});this.dirtyPathIndex=t,this.dirtyPrefixRefCount=e,this.childrenByPrefix=i}removeDirtyChildren(t){let e=this.childrenByPrefix.get(t);if(!(!e||e.size===0))for(let i of[...e])this.removeDirtyPath(i)}addDirtyPath(t){this.dirtyPaths.has(t)||(this.dirtyPaths.add(t),this.forEachPathPrefix(t,e=>{this.dirtyPathIndex.add(e),this.dirtyPrefixRefCount.set(e,(this.dirtyPrefixRefCount.get(e)??0)+1)}),this.forEachAncestorPrefix(t,e=>{let i=this.childrenByPrefix.get(e);i?i.add(t):this.childrenByPrefix.set(e,new Set([t]))}))}removeDirtyPath(t){this.dirtyPaths.has(t)&&(this.dirtyPaths.delete(t),this.forEachPathPrefix(t,e=>{let i=(this.dirtyPrefixRefCount.get(e)??0)-1;if(i<=0){this.dirtyPrefixRefCount.delete(e),this.dirtyPathIndex.delete(e);return}this.dirtyPrefixRefCount.set(e,i)}),this.forEachAncestorPrefix(t,e=>{this.childrenByPrefix.get(e)?.delete(t)}))}forEachPathPrefix(t,e){let i=t.split("."),s="";for(let o of i)s=s?`${s}.${o}`:o,e(s)}forEachAncestorPrefix(t,e){let i=t.split("."),s="";for(let o=0;o<i.length-1;o++)s=s?`${s}.${i[o]}`:i[o],e(s)}};var q=class{masks=new Map;registerMask(t,e){this.masks.set(t,e)}unregisterMask(t){this.masks.has(t)&&this.masks.delete(t)}resolveMask(t){return this.masks.get(t)}getAllMasks(){return Object.fromEntries(this.masks.entries())}clear(){this.masks.clear()}};function si(r){return r.replace(/\.+$/g,"")}function w(r){return si(r.trim())}function E(r,t){let e=w(t);return e.length===0?!1:r===e||r.startsWith(`${e}.`)}function x(r,t){return w(t===void 0?r:`${r}.${t}`)}var L=class{fieldConfigs=new Map;scopeFieldsIndex=null;computedEntriesCache=null;normalizerEntriesCache=null;transformEntriesCache=null;get(t){return this.fieldConfigs.get(t)}set(t,e){this.fieldConfigs.set(t,e),this.registerCachedIndexes(t,e)}delete(t){let e=this.fieldConfigs.get(t);return this.fieldConfigs.delete(t),this.unregisterCachedIndexes(t,e),e}has(t){return this.fieldConfigs.has(t)}forEach(t){this.fieldConfigs.forEach((e,i)=>t(e,i))}entries(){return Array.from(this.fieldConfigs.entries())}getScopeFields(t){if(!this.scopeFieldsIndex){let e=new Map;this.forEach((i,s)=>{if(!i.scope)return;let o=e.get(i.scope)??new Set;o.add(s),e.set(i.scope,o)}),this.scopeFieldsIndex=e}return Array.from(this.scopeFieldsIndex.get(t)??[])}getComputedEntries(){if(!this.computedEntriesCache){let t=[];this.forEach((e,i)=>{e.computed&&t.push({path:i,compute:e.computed,dependsOn:e.computedDependsOn})}),this.computedEntriesCache=t}return this.computedEntriesCache}getTransformEntries(){if(!this.transformEntriesCache){let t=[];this.forEach((e,i)=>{e.transform&&t.push([i,e.transform])}),this.transformEntriesCache=t}return this.transformEntriesCache}getNormalizerEntries(){if(!this.normalizerEntriesCache){let t=[];this.forEach((e,i)=>{e.normalize&&t.push({path:i,normalize:e.normalize,dependsOn:e.normalizeDependsOn?.length?e.normalizeDependsOn:[i]})}),this.normalizerEntriesCache=t}return this.normalizerEntriesCache}invalidateIndexes(){this.scopeFieldsIndex=null,this.computedEntriesCache=null,this.normalizerEntriesCache=null,this.transformEntriesCache=null}registerCachedIndexes(t,e){if(this.scopeFieldsIndex&&e.scope){let i=this.scopeFieldsIndex.get(e.scope)??new Set;i.add(t),this.scopeFieldsIndex.set(e.scope,i)}this.computedEntriesCache&&e.computed&&this.computedEntriesCache.push({path:t,compute:e.computed,dependsOn:e.computedDependsOn}),this.normalizerEntriesCache&&e.normalize&&this.normalizerEntriesCache.push({path:t,normalize:e.normalize,dependsOn:e.normalizeDependsOn?.length?e.normalizeDependsOn:[t]}),this.transformEntriesCache&&e.transform&&this.transformEntriesCache.push([t,e.transform])}unregisterCachedIndexes(t,e){if(!e){this.invalidateIndexes();return}if(this.scopeFieldsIndex&&e.scope){let i=this.scopeFieldsIndex.get(e.scope);i&&(i.delete(t),i.size>0?this.scopeFieldsIndex.set(e.scope,i):this.scopeFieldsIndex.delete(e.scope))}this.computedEntriesCache&&e.computed&&(this.computedEntriesCache=this.computedEntriesCache.filter(i=>i.path!==t)),this.normalizerEntriesCache&&e.normalize&&(this.normalizerEntriesCache=this.normalizerEntriesCache.filter(i=>i.path!==t)),this.transformEntriesCache&&e.transform&&(this.transformEntriesCache=this.transformEntriesCache.filter(([i])=>i!==t))}};var _=class{constructor(t,e){this.getFieldConfig=t;this.onConditionError=e}dependencies=new Map;hiddenFields=new Set;conditionalVisibilityPaths=new Set;requiredPathsByDependency=new Map;requiredConditionalPaths=new Set;requiredEvaluationVersion=0;requiredEvaluationCache=new Map;getHiddenFields(){return this.hiddenFields}onRegister(t,e,i){let s=!!e.conditional?.showIf,o=e.conditional?.dependsOn;if(o){if(this.wouldCreateCycle(t,o)){let n=new Error(`Circular dependency detected: "${t}" \u2192 [${o.join(", ")}]`);return this.onConditionError?.({path:t,kind:"showIf",error:n}),s&&this.hiddenFields.add(t),this.conditionalVisibilityPaths.delete(t),this.requiredConditionalPaths.delete(t),!1}o.forEach(n=>{this.dependencies.has(n)||this.dependencies.set(n,new Set),this.dependencies.get(n).add(t)})}return s&&this.conditionalVisibilityPaths.add(t),o&&e.conditional?.requiredIf&&(this.requiredConditionalPaths.add(t),o.forEach(n=>{this.requiredPathsByDependency.has(n)||this.requiredPathsByDependency.set(n,new Set),this.requiredPathsByDependency.get(n).add(t)})),this.requiredEvaluationVersion+=1,this.requiredEvaluationCache.clear(),this.evaluateFieldCondition(t,i),!0}onUnregister(t,e,i){this.hiddenFields.delete(t),this.conditionalVisibilityPaths.delete(t),i?.preserveIncomingDependents||this.dependencies.delete(t),this.requiredEvaluationVersion+=1,this.requiredEvaluationCache.clear(),this.requiredConditionalPaths.delete(t),e?.conditional?.dependsOn?.forEach(s=>{let o=this.requiredPathsByDependency.get(s);o&&(o.delete(t),o.size===0&&this.requiredPathsByDependency.delete(s))}),this.dependencies.forEach(s=>{s.delete(t)})}isHidden(t){return this.hiddenFields.has(t)}hasDependents(t){return(this.dependencies.get(t)?.size??0)>0}isRequired(t,e){let i=this.getFieldConfig(t);if(!i||this.isHidden(t)||!i.conditional?.requiredIf)return!1;let s=this.requiredEvaluationCache.get(t);if(s&&s.version===this.requiredEvaluationVersion&&s.valuesRef===e)return s.result;let o=!1;try{o=!!i.conditional.requiredIf(e)}catch(n){this.onConditionError?.({path:t,kind:"requiredIf",error:n})}return this.requiredEvaluationCache.set(t,{version:this.requiredEvaluationVersion,valuesRef:e,result:o}),o}getRequiredErrors(t){let e={};return this.requiredConditionalPaths.forEach(i=>{let s=this.getFieldConfig(i);if(s&&!this.isHidden(i)&&this.isRequired(i,t)){let o=S(t,i);this.isEmpty(o)&&(e[i]=s.conditional?.requiredMessage??"required field")}}),e}evaluateAll(t){this.conditionalVisibilityPaths.forEach(e=>{this.evaluateFieldCondition(e,t)})}updateDependencies(t,e,i){let s=new Set,o=new Set,n=new Set,a=[t],c=new Set;for(;a.length>0;){let u=a.shift();if(c.has(u))continue;c.add(u);let l=this.dependencies.get(u);l&&l.forEach(d=>{s.add(d);let p=this.isHidden(d),h=this.isRequired(d,e);this.evaluateFieldCondition(d,i);let y=this.isHidden(d),v=this.isRequired(d,i);p!==y&&o.add(d),h!==v&&n.add(d),a.push(d)})}return{affectedFields:Array.from(s),visibilityChanged:Array.from(o),requiredChanged:Array.from(n)}}evaluateFieldCondition(t,e){let s=this.getFieldConfig(t)?.conditional?.showIf;if(s)try{s(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t)}catch(o){this.onConditionError?.({path:t,kind:"showIf",error:o})}}wouldCreateCycle(t,e){for(let i of e){let s=[t],o=new Set;for(;s.length>0;){let n=s.shift();if(n===i)return!0;if(o.has(n))continue;o.add(n);let a=this.dependencies.get(n);a&&s.push(...a)}}return!1}isEmpty(t){return t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0}};var N=class{catalog=new L;conditions;constructor(t){this.conditions=new _(e=>this.catalog.get(e),t)}getFieldConfig(t){return this.catalog.get(t)}forEachFieldConfig(t){this.catalog.forEach((e,i)=>t(e,i))}hasFieldConfig(t){return this.catalog.has(t)}getHiddenFields(){return this.conditions.getHiddenFields()}register(t,e,i){let s=this.catalog.get(t);s&&this.conditions.onUnregister(t,s,{preserveIncomingDependents:!0}),this.catalog.set(t,e),!(this.conditions.onRegister(t,e,i)||!s)&&(this.catalog.set(t,s),this.conditions.onRegister(t,s,i))}unregister(t){let e=this.catalog.delete(t);this.conditions.onUnregister(t,e)}unregisterPrefix(t){let e=[],i=w(t);return i.length===0||(this.catalog.forEach((s,o)=>{E(o,i)&&e.push([o,s])}),e.forEach(([s,o])=>{this.catalog.delete(s),this.conditions.onUnregister(s,o)})),e}isHidden(t){return this.conditions.isHidden(t)}hasDependents(t){return this.conditions.hasDependents(t)}isRequired(t,e){return this.conditions.isRequired(t,e)}getRequiredErrors(t){return this.conditions.getRequiredErrors(t)}evaluateAll(t){this.conditions.evaluateAll(t)}updateDependencies(t,e,i){return this.conditions.updateDependencies(t,e,i)}getScopeFields(t){return this.catalog.getScopeFields(t)}getComputedEntries(){return this.catalog.getComputedEntries()}getTransformEntries(){return this.catalog.getTransformEntries()}getNormalizerEntries(){return this.catalog.getNormalizerEntries()}invalidateIndexes(){this.catalog.invalidateIndexes()}};function ni(){return`bit-form-${Math.random().toString(36).slice(2,9)}`}function oi(r){typeof console<"u"&&typeof console.error=="function"&&console.error(r)}function Wt(r={}){let t=r.initialValues??{},e=r.validation,i=r.history,s=r.name?`bit-form:${r.name}:draft`:"bit-form:draft",o=r.onUnhandledError??oi,n=r.persist?.onError,a={enabled:r.persist?.enabled??!1,key:r.persist?.key??s,storage:r.persist?.storage,autoSave:r.persist?.autoSave??!0,debounceMs:r.persist?.debounceMs??300,mode:r.persist?.mode??"values",serialize:r.persist?.serialize??JSON.stringify,deserialize:r.persist?.deserialize??(c=>JSON.parse(c)),onError:c=>{if(n){n(c);return}o(c,"persist")}};return{name:r.name,initialValues:b(t),resolver:e?.resolver,validationDelay:e?.delay??300,history:{enabled:i?.enabled??!1,limit:i?.limit??50},masks:r.masks,fields:r.fields,devTools:r.devTools,persist:a,idFactory:r.idFactory??ni,plugins:r.plugins??[],scheduler:r.scheduler,subscriptionCacheSize:r.subscriptionCacheSize,trackedSubscriptions:r.trackedSubscriptions??!1,bus:r.bus,onUnhandledError:o}}function W(r,t){if((!r||r.length===0)&&(!t||t.length===0))return;let e=new Set(r??[]);return t?.forEach(i=>e.add(i)),Array.from(e)}function Kt(r){let{values:t,entries:e,deriveValue:i,onError:s}=r,o=[];for(let n of e){let a=S(t,n.path),c;try{c=i(n,a)}catch(u){s?.(u,n.path);continue}F(a,c)||o.push([n.path,c])}return o}function ai(r){let t=r?.includes("*")??!1,e=new Set(r??[]),i=new Set;for(let s of e){i.add(s);let o=s.lastIndexOf(".");for(;o>-1;)i.add(s.slice(0,o)),o=s.lastIndexOf(".",o-1)}return s=>{if(!r||r.length===0||t||e.has(s)||i.has(s))return!0;let o=s.lastIndexOf(".");for(;o>-1;){if(e.has(s.slice(0,o)))return!0;o=s.lastIndexOf(".",o-1)}return!1}}function li(r,t){if(!t||t.length===0||t.includes("*"))return r;let e=ai(t);return r.filter(i=>i.dependsOn.some(s=>e(s)))}function K(r){let{values:t,changedPaths:e,normalizerEntries:i,applyComputed:s,onError:o}=r,n=li(i,e);if(n.length===0)return s(t,e);let a=Kt({values:t,entries:n,deriveValue:(l,d)=>l.normalize(d,t),onError:o}),c=a.length>0?P(t,a):t,u=W(e,a.map(([l])=>l));return s(c,u)}function $t(r){let{values:t,sourceValues:e,transformEntries:i,onError:s}=r;if(i.length===0)return t;let o=Kt({values:t,entries:i.map(([n,a])=>({path:n,transform:a})),deriveValue:(n,a)=>n.transform(a,e),onError:s});return o.length===0?t:P(t,o)}var $=class{effects;constructor(t){this.effects=t.getAll()}attachStorePort(t){this.effects.forEach(e=>e.attachStorePort?.(t))}initialize(){this.effects.forEach(t=>t.initialize?.())}onStateUpdated(t,e){this.effects.forEach(i=>i.onStateUpdated?.(t,e))}async restorePersisted(){let t=!1;for(let e of this.effects)e.restorePersisted&&(t=await e.restorePersisted()||t);return t}async savePersistedNow(){for(let t of this.effects)t.savePersistedNow&&await t.savePersistedNow()}async clearPersisted(){for(let t of this.effects)t.clearPersisted&&await t.clearPersisted()}async beforeValidate(t){for(let e of this.effects)if(e.beforeValidate)try{await e.beforeValidate(t)}catch(i){this.logEffectHookError(e.name,"beforeValidate",i)}}async afterValidate(t){for(let e of this.effects)if(e.afterValidate)try{await e.afterValidate(t)}catch(i){this.logEffectHookError(e.name,"afterValidate",i)}}async beforeSubmit(t){for(let e of this.effects)if(e.beforeSubmit)try{await e.beforeSubmit(t)}catch(i){this.logEffectHookError(e.name,"beforeSubmit",i)}}async afterSubmit(t){for(let e of this.effects)if(e.afterSubmit)try{await e.afterSubmit(t)}catch(i){this.logEffectHookError(e.name,"afterSubmit",i)}}onFieldChange(t){this.effects.forEach(e=>{try{e.onFieldChange?.(t)}catch(i){this.logEffectHookError(e.name,"onFieldChange",i)}})}async reportOperationalError(t){for(let e of this.effects)if(e.reportOperationalError)try{await e.reportOperationalError(t)}catch(i){this.logEffectHookError(e.name,"reportOperationalError",i)}}logEffectHookError(t,e,i){console.error(`BitStoreEffectEngine: effect "${t}" failed in hook "${e}"`,i)}destroy(){for(let t=this.effects.length-1;t>=0;t-=1)this.effects[t].destroy?.()}};var J=class{constructor(t,e,i=!0,s){this.storeId=t;this.bus=e;this.enableBusDispatch=i;this.storeBusPort=s}storeBusPort;attachStorePort(t){this.storeBusPort=t,this.enableBusDispatch&&(this.bus.stores[this.storeId]=t)}initialize(){!this.enableBusDispatch||!this.storeBusPort||(this.bus.stores[this.storeId]=this.storeBusPort)}onStateUpdated(t){this.enableBusDispatch&&this.bus.dispatch(this.storeId,t)}destroy(){this.enableBusDispatch&&delete this.bus.stores[this.storeId]}};var Y=class{effects=new Map;register(t){this.effects.set(t.name,t)}getAll(){return Array.from(this.effects.values())}};var G=class{constructor(t){this.persistManager=t}onStateUpdated(t,e){e&&this.persistManager.queueSave()}restorePersisted(){return this.persistManager.restore()}savePersistedNow(){return this.persistManager.saveNow()}clearPersisted(){return this.persistManager.clear()}destroy(){this.persistManager.destroy()}};var X=class{constructor(t){this.pluginManager=t}initialize(){this.pluginManager.setupAll()}beforeValidate(t){return this.pluginManager.beforeValidate(t)}afterValidate(t){return this.pluginManager.afterValidate(t)}beforeSubmit(t){return this.pluginManager.beforeSubmit(t)}afterSubmit(t){return this.pluginManager.afterSubmit(t)}onFieldChange(t){this.pluginManager.onFieldChange(t)}reportOperationalError(t){return this.pluginManager.reportError(t.source,t.error,t.payload)}destroy(){this.pluginManager.destroy()}};function ci(){if(typeof globalThis>"u")return;let r;try{r=globalThis.localStorage??void 0}catch{return}if(r)return{getItem:t=>r.getItem(t),setItem:(t,e)=>r.setItem(t,e),removeItem:t=>r.removeItem(t)}}var Q=class{constructor(t,e,i,s,o={}){this.config=t;this.getValues=e;this.getDirtyValues=i;this.applyRestoredValues=s;this.callbacks=o}timer;getStorage(){return this.config.storage||ci()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(t){this.config.onError?.(t)}async persistPayload(){let t=this.getStorage();if(!t)return;let e=this.config.mode==="dirtyValues"?this.getDirtyValues():this.getValues(),i=this.config.serialize(e);await t.setItem(this.config.key,i)}async saveNow(){if(this.canPersist())try{await this.persistPayload()}catch(t){throw this.handleError(t),t}}queueSave(){!this.canPersist()||!this.config.autoSave||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.callbacks.onAutoSaveStart?.(),this.saveNow().then(()=>{this.callbacks.onAutoSaveSuccess?.()}).catch(t=>{this.callbacks.onAutoSaveError?.(t)})},this.config.debounceMs))}async restore(){if(!this.canPersist())return!1;let t=this.getStorage();if(!t)return!1;try{let e=await t.getItem(this.config.key);if(!e)return!1;let i=this.config.deserialize(e);return!i||typeof i!="object"?!1:(this.applyRestoredValues(i),!0)}catch(e){return this.handleError(e),!1}}async clear(){if(!this.canPersist())return;let t=this.getStorage();if(t)try{await t.removeItem(this.config.key)}catch(e){this.handleError(e)}}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}};var Z=class{constructor(t,e){this.plugins=t;this.contextFactory=e}teardownFns=[];notifyingError=!1;pendingErrorQueue=[];cachedContext=null;setupAll(){let t=this.getContext();this.plugins.forEach(e=>{if(e.setup)try{let i=e.setup(t);typeof i=="function"&&this.teardownFns.push(i)}catch(i){this.reportError("setup",i,void 0,e.name)}})}async beforeValidate(t){await this.emitHook("beforeValidate",t)}async afterValidate(t){await this.emitHook("afterValidate",t)}async beforeSubmit(t){await this.emitHook("beforeSubmit",t)}async afterSubmit(t){await this.emitHook("afterSubmit",t)}onFieldChange(t){let e=this.getContext();this.plugins.forEach(i=>{let s=i.hooks?.onFieldChange;if(s)try{let o=s(t,e);Promise.resolve(o).catch(n=>{this.reportError("onFieldChange",n,t,i.name)})}catch(o){this.reportError("onFieldChange",o,t,i.name)}})}async reportError(t,e,i,s){let o=this.getContext();if(this.pendingErrorQueue.push({source:t,pluginName:s,error:e,event:i,values:o.getState().values,state:o.getState()}),!this.notifyingError){this.notifyingError=!0;try{for(;this.pendingErrorQueue.length>0;){let n=this.pendingErrorQueue.shift();if(!n)break;for(let a of this.plugins){let c=a.hooks?.onError;if(c)try{await c(n,o)}catch{}}}}finally{this.notifyingError=!1}}}destroy(){for(let t=this.teardownFns.length-1;t>=0;t-=1){let e=this.teardownFns[t];try{e()}catch(i){this.reportError("teardown",i)}}this.teardownFns=[],this.cachedContext=null}async emitHook(t,e){let i=this.getContext();for(let s of this.plugins){let o=s.hooks?.[t];if(o)try{await o(e,i)}catch(n){await this.reportError(t,n,e,s.name)}}}getContext(){return this.cachedContext||(this.cachedContext=this.contextFactory()),this.cachedContext}};var xt=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;xt.__BIT_FORM__||(xt.__BIT_FORM__={stores:{},listeners:new Set,dispatch(r,t){this.listeners.forEach(e=>e(r,t))},subscribe(r){return this.listeners.add(r),()=>{this.listeners.delete(r)}}});var Ct=xt.__BIT_FORM__,di={stores:{},listeners:new Set,dispatch:()=>{},subscribe:()=>()=>{}};function Ft(){return di}function ui(){let r=new Set;return{stores:{},listeners:r,dispatch(t,e){r.forEach(i=>i(t,e))},subscribe(t){return r.add(t),()=>r.delete(t)}}}function pi(r){return r.bus?!0:typeof r.devTools=="boolean"?r.devTools:r.devTools&&typeof r.devTools=="object"?r.devTools.enabled!==!1:!1}function Jt(r){let{storeId:t,storeBusPort:e,config:i,getState:s,getConfig:o,getValues:n,getDirtyValues:a,applyPersistedValues:c,setPersistMetadata:u}=r,l=new Q(i.persist,n,a,c,{onAutoSaveStart:()=>u?.({isSaving:!0,error:null}),onAutoSaveSuccess:()=>u?.({isSaving:!1,error:null}),onAutoSaveError:B=>u?.({isSaving:!1,error:B instanceof Error?B:new Error(String(B))})}),d=new Z([...i.plugins],()=>({storeId:t,getState:()=>s(),getConfig:()=>o()})),p=pi(i),h=typeof process<"u"&&typeof process.env<"u"&&process.env.VITEST==="true",y=p?i.bus??(h?Ft():Ct):Ft(),v=new Y,f=new G(l);v.register({name:"persist",onStateUpdated:(B,ri)=>f.onStateUpdated(B,ri),restorePersisted:()=>f.restorePersisted(),savePersistedNow:()=>f.savePersistedNow(),clearPersisted:()=>f.clearPersisted(),destroy:()=>f.destroy()});let g=new X(d);v.register({name:"plugins",initialize:()=>g.initialize(),beforeValidate:B=>g.beforeValidate(B),afterValidate:B=>g.afterValidate(B),beforeSubmit:B=>g.beforeSubmit(B),afterSubmit:B=>g.afterSubmit(B),onFieldChange:B=>g.onFieldChange(B),reportOperationalError:B=>g.reportOperationalError(B),destroy:()=>g.destroy()});let T=new J(t,y,p,e);v.register({name:"bus",attachStorePort:B=>T.attachStorePort(B),initialize:()=>T.initialize(),onStateUpdated:B=>T.onStateUpdated(B),destroy:()=>T.destroy()});let V=new $(v);return V.initialize(),V}function m(r,t,e){return{kind:"state.patch",partialState:r,changedPaths:t,skipComputed:e?.skipComputed}}function Vt(r){return{kind:"field.touchMany",paths:r}}function C(r){return{kind:"form.persistMeta",patch:r}}function tt(r,t){return{kind:"validation.commit",errors:r,isValid:t}}async function Yt(r){let{dispatch:t,effects:e}=r;t(C({isRestoring:!0,error:null}));try{return await e.restorePersisted()}catch(i){return t(C({isRestoring:!1,error:i instanceof Error?i:new Error(String(i))})),!1}finally{t(C({isRestoring:!1}))}}async function Gt(r){let{dispatch:t,effects:e}=r;t(C({isSaving:!0,error:null}));try{await e.savePersistedNow()}catch(i){t(C({isSaving:!1,error:i instanceof Error?i:new Error(String(i))}));return}t(C({isSaving:!1}))}async function Xt(r){let{dispatch:t,effects:e}=r;t(C({error:null}));try{await e.clearPersisted()}catch(i){t(C({error:i instanceof Error?i:new Error(String(i))}))}}function Qt(r){let{values:t,state:e,initialValues:i,validation:s,fieldRegistry:o,dirtyManager:n,dispatch:a,saveHistorySnapshot:c}=r,u=b(Mt(i,t));s.cancelAll(),o.evaluateAll(u);let l=n.rebuild(u,i);a(m({values:u,errors:{},touched:{},isValidating:{},persist:{...e.persist,error:null},isValid:!0,isDirty:l})),c(),s.validate()}function Zt(r){let{state:t,path:e}=r,i={...t.errors},s={...t.touched},o=!1;return i[e]&&(delete i[e],o=!0),s[e]&&(delete s[e],o=!0),o?{errors:i,touched:s}:null}function te(r){let{path:t,config:e,state:i,fieldRegistry:s,subscriptions:o,stateReader:n,invalidateFieldIndexes:a}=r;s.register(t,e,i.values),a(),o.invalidatePathExpansionCache(t),n.invalidatePath(t),e.scope&&o.notify(i,[A(e.scope)]),s.isHidden(t)&&o.notify(i,[t])}function ee(r){let{path:t,state:e,hasStaticConfig:i,fieldRegistry:s,subscriptions:o,validationCleanupField:n,invalidateFieldIndexes:a,dispatch:c}=r;if(i)return;let u=s.getFieldConfig(t);n(t),s.unregister(t),a(),o.invalidatePathExpansionCache(t),u?.scope&&o.notify(e,[A(u.scope)]);let l=Zt({state:e,path:t});l&&c(m({errors:l.errors,touched:l.touched}))}function et(r){let{prefix:t,state:e,fieldRegistry:i,subscriptions:s,validationCleanupPrefix:o,invalidateFieldIndexes:n}=r;o(t);let a=i.unregisterPrefix(t);n(),s.invalidatePathExpansionCache(t),new Set(a.map(([,u])=>u.scope).filter(u=>!!u)).forEach(u=>{s.notify(e,[A(u)])})}var it=class{constructor(t,e=500){this.getState=t;this.MAX_PATH_EXPANSION_CACHE_SIZE=e}listeners=new Set;pathScopedSubscriptions=new Map;pathSelectorIndex=new Map;pathExpansionCache=new Map;subscriptionSeenVersion=new Map;notifyVersion=0;MAX_PATH_EXPANSION_CACHE_SIZE;cacheHits=0;cacheMisses=0;cacheEvictions=0;subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}subscribeSelector(t,e,i,s){let o=t(this.getState()),n={notify:c=>{let u=t(c);s(o,u)||(o=u,e(u))}},a=this.normalizeSubscriptionPaths(i.paths);return this.pathScopedSubscriptions.set(n,a),a.forEach(c=>{this.forEachIndexPath(c,u=>{let l=this.pathSelectorIndex.get(u)??new Set;l.add(n),this.pathSelectorIndex.set(u,l)})}),i.emitImmediately&&e(o),()=>{this.subscriptionSeenVersion.delete(n);let c=this.pathScopedSubscriptions.get(n);c&&(c.forEach(u=>{this.forEachIndexPath(u,l=>{let d=this.pathSelectorIndex.get(l);d&&(d.delete(n),d.size===0&&this.pathSelectorIndex.delete(l))})}),this.pathScopedSubscriptions.delete(n))}}notify(t,e){if(this.listeners.forEach(o=>{try{o()}catch(n){console.error("Subscription listener error:",n)}}),this.pathScopedSubscriptions.size===0)return;let i=this.normalizeChangedPathIterable(e);if(i.length===0||i.includes("*")){this.pathScopedSubscriptions.forEach((o,n)=>{try{n.notify(t)}catch(a){console.error("Path subscription notify error:",a)}});return}if(i.length===1&&this.isSimplePath(i[0])){this.collectSubscribersForSingleChangedPath(i[0]).forEach(n=>{try{n.notify(t)}catch(a){console.error("Path subscription notify error:",a)}});return}this.collectSubscribersForChangedPaths(i).forEach(o=>{try{o.notify(t)}catch(n){console.error("Path subscription notify error:",n)}})}destroy(){this.listeners.clear(),this.pathScopedSubscriptions.clear(),this.pathSelectorIndex.clear(),this.pathExpansionCache.clear(),this.subscriptionSeenVersion.clear()}getPathExpansionCacheStats(){return{cacheSize:this.pathExpansionCache.size,cacheLimit:this.MAX_PATH_EXPANSION_CACHE_SIZE,cacheHits:this.cacheHits,cacheMisses:this.cacheMisses,cacheEvictions:this.cacheEvictions}}getActiveSubscribersCount(){return this.pathScopedSubscriptions.size}invalidatePathExpansionCache(t){if(!t){this.pathExpansionCache.clear();return}let e=w(t);if(e.length===0){this.pathExpansionCache.clear();return}for(let i of this.pathExpansionCache.keys())(E(i,e)||E(e,i))&&this.pathExpansionCache.delete(i)}normalizeSubscriptionPaths(t){if(!t||t.length===0)return[];let e=new Set,i=[];for(let s of t){let o=s.trim();o.length===0||e.has(o)||(e.add(o),i.push(o))}return i}normalizeChangedPathIterable(t){if(!t)return[];let e=new Set,i=[];for(let s of t){let o=s.trim();o.length===0||e.has(o)||(e.add(o),i.push(o))}return i}collectSubscribersForChangedPaths(t){let e=[],i=++this.notifyVersion,s=o=>{let n=this.pathSelectorIndex.get(o);n&&n.forEach(a=>{(this.subscriptionSeenVersion.get(a)??0)>=i||(this.subscriptionSeenVersion.set(a,i),e.push(a))})};return t.forEach(o=>{this.forEachLookupPath(o,s)}),e}collectSubscribersForSingleChangedPath(t){let e=[],i=++this.notifyVersion,s=o=>{let n=this.pathSelectorIndex.get(o);n&&n.forEach(a=>{(this.subscriptionSeenVersion.get(a)??0)>=i||(this.subscriptionSeenVersion.set(a,i),e.push(a))})};return this.forEachLookupPath(t,s),e}expandChangedPathForLookup(t){return this.expandPathGeneric(t)}expandPathForIndexing(t){return this.expandPathGeneric(t)}forEachIndexPath(t,e){if(!this.isSimplePath(t)){this.expandPathForIndexing(t).forEach(e);return}let i=t.split("."),s="";for(let o=0;o<i.length;o+=1)s=s?`${s}.${i[o]}`:i[o],e(s)}forEachLookupPath(t,e){if(!this.isSimplePath(t)){this.expandChangedPathForLookup(t).forEach(e);return}e(t);let i=t.lastIndexOf(".");for(;i>-1;)e(t.slice(0,i)),i=t.lastIndexOf(".",i-1)}isSimplePath(t){return!t.includes("*")&&!t.includes("[")&&!t.includes("]")}expandPathGeneric(t){let e=this.pathExpansionCache.get(t);if(e)return this.cacheHits+=1,e;this.cacheMisses+=1;let i=t.split("."),s=[];for(let o=1;o<=i.length;o++)s.push(i.slice(0,o).join("."));return this.setBoundedCacheEntry(this.pathExpansionCache,t,s,this.MAX_PATH_EXPANSION_CACHE_SIZE),s}setBoundedCacheEntry(t,e,i,s){if(t.size>=s){let o=t.keys().next().value;o!==void 0&&(t.delete(o),this.cacheEvictions+=1)}t.set(e,i)}};function ie(r){let t=[],e=new Map,i=new Set(r.map(a=>a.path));for(let a of r)if(e.has(a.path)||e.set(a.path,new Set),a.dependsOn)for(let c of a.dependsOn)i.has(c)&&e.get(a.path).add(c);let s=new Set,o=new Set,n=(a,c)=>{s.add(a),o.add(a),c.push(a);let u=e.get(a)||new Set;for(let l of u)if(s.has(l)){if(o.has(l)){let d=c.indexOf(l),p=[...c.slice(d),l];return{cycle:p,paths:Array.from(e.keys()).filter(h=>p.includes(h)),message:`Circular dependency detected: ${p.join(" \u2192 ")}. Check your computed field definitions.`}}}else{let d=n(l,[...c]);if(d)return d}return o.delete(a),null};for(let a of e.keys())if(!s.has(a)){let c=n(a,[]);c&&!t.some(u=>u.message===c.message)&&t.push(c)}return t}var rt=class{constructor(t){this.store=t}pathIds=new Map;getItemIds(t,e){let i=typeof e=="number"?Math.max(0,e):this.getCurrentArrayLength(t);return[...this.ensureIds(t,i)]}pushItem(t,e){this.withPathIds(t,i=>(i.push(this.store.createArrayItemId(t,i.length)),i)),this.mutateArrayWithSetField(t,i=>[...i,e],{origin:"array",operation:"push"})}prependItem(t,e){this.withPathIds(t,i=>(i.unshift(this.store.createArrayItemId(t,0)),i)),this.store.unregisterPrefix?.(x(t)),this.mutateArrayWithSetField(t,i=>[e,...i],{origin:"array",operation:"prepend"})}insertItem(t,e,i){let s=this.getCurrentArrayLength(t),o=Math.max(0,Math.min(e,s));if(this.withPathIds(t,n=>{let a=[...n];return a.splice(o,0,this.store.createArrayItemId(t,o)),a}),this.store.unregisterPrefix)for(let n=o;n<s;n++)this.store.unregisterPrefix(x(t,n));this.mutateArrayWithSetField(t,n=>{let a=[...n];return a.splice(o,0,i),a},{origin:"array",operation:"insert",index:o})}removeItem(t,e){let i=this.store.getState(),s=S(i.values,t);if(!Array.isArray(s)||e<0||e>=s.length)return;this.withPathIds(t,n=>{let a=[...n];return a.splice(e,1),a}),this.store.unregisterPrefix&&this.store.unregisterPrefix(x(t,e));let o=s.filter((n,a)=>a!==e);this.commitArrayMutationWithFieldPipeline({path:t,nextArray:o,meta:{origin:"array",operation:"remove",index:e},reindex:n=>n===e?null:n>e?n-1:n})}swapItems(t,e,i){let s=this.store.getState(),o=S(s.values,t);if(!Array.isArray(o)||e<0||e>=o.length||i<0||i>=o.length)return;this.withPathIds(t,a=>{let c=[...a];return[c[e],c[i]]=[c[i],c[e]],c});let n=[...o];[n[e],n[i]]=[n[i],n[e]],this.store.unregisterPrefix&&(this.store.unregisterPrefix(x(t,e)),this.store.unregisterPrefix(x(t,i))),this.commitArrayMutationWithFieldPipeline({path:t,nextArray:n,meta:{origin:"array",operation:"swap",from:e,to:i},reindex:a=>a===e?i:a===i?e:a})}moveItem(t,e,i){let s=this.store.getState(),o=S(s.values,t);if(!Array.isArray(o)||e<0||e>=o.length||i<0||i>=o.length)return;this.withPathIds(t,c=>{let u=[...c],[l]=u.splice(e,1);return u.splice(i,0,l),u});let n=[...o],[a]=n.splice(e,1);if(n.splice(i,0,a),this.store.unregisterPrefix){let c=Math.min(e,i),u=Math.max(e,i);for(let l=c;l<=u;l+=1)this.store.unregisterPrefix(x(t,l))}this.commitArrayMutationWithFieldPipeline({path:t,nextArray:n,meta:{origin:"array",operation:"move",from:e,to:i},reindex:c=>c===e?i:e<i&&c>e&&c<=i?c-1:e>i&&c>=i&&c<e?c+1:c})}replaceItems(t,e){this.store.unregisterPrefix?.(x(t)),this.pathIds.set(t,e.map((i,s)=>this.store.createArrayItemId(t,s))),this.commitArrayMutationWithFieldPipeline({path:t,nextArray:e,meta:{origin:"array",operation:"replace"},reindex:i=>i<e.length?i:null})}clearItems(t){this.pathIds.set(t,[]),this.store.unregisterPrefix&&this.store.unregisterPrefix(x(t)),this.commitArrayMutationWithFieldPipeline({path:t,nextArray:[],meta:{origin:"array",operation:"clear"},reindex:()=>null})}mutateArrayWithSetField(t,e,i){let s=S(this.store.getState().values,t)||[];this.store.setFieldWithMeta(t,e(s),i),this.store.internalSaveSnapshot()}withPathIds(t,e){let i=this.getCurrentArrayLength(t),s=this.ensureIds(t,i);this.pathIds.set(t,e(s))}ensureIds(t,e){let i=this.pathIds.get(t)??[];if(i.length===e)return i;if(i.length<e){let o=[...i];for(let n=i.length;n<e;n+=1)o.push(this.store.createArrayItemId(t,n));return this.pathIds.set(t,o),o}let s=i.slice(0,e);return this.pathIds.set(t,s),s}getCurrentArrayLength(t){let e=S(this.store.getState().values,t);return Array.isArray(e)?e.length:0}commitArrayMutationWithFieldPipeline(t){let{path:e,nextArray:i,meta:s,reindex:o}=t,n=this.store.getState();this.store.setFieldWithMeta(e,i,s);let a=jt(n,e,o);this.store.dispatch(m({errors:a.errors,touched:a.touched,isValidating:n.isValidating},[e])),this.store.internalSaveSnapshot()}};var st=class{constructor(t,e,i){this.getState=t;this.dispatch=e;this.reportError=i}reportInvalidInput(t,e){this.reportError?.(new Error(e===void 0?t:`${t}: ${String(e)}`))}setError(t,e){if(!t||typeof t!="string"){this.reportInvalidInput("setError received an invalid path",t);return}if(e!==void 0&&typeof e!="string"){this.reportInvalidInput("setError received an invalid message",e);return}let i={...this.getState().errors,[t]:e};e||delete i[t],this.dispatch(m({errors:i}))}setErrors(t){if(!t||typeof t!="object"){this.reportInvalidInput("setErrors received an invalid payload");return}let e={};Object.entries(t).forEach(([i,s])=>{if(!i){this.reportInvalidInput("setErrors ignored an empty path");return}if(s!==void 0&&typeof s!="string"){this.reportInvalidInput("setErrors ignored a non-string message",i);return}e[i]=s}),this.dispatch(m({errors:{...this.getState().errors,...e}}))}setServerErrors(t,e){let i=e?.arrayStrategy??"first",s=e?.joinSeparator??"; ",o={};for(let[n,a]of Object.entries(t)){if(!n){this.reportInvalidInput("setServerErrors ignored an empty path");continue}if(Array.isArray(a)){let c=a.filter(u=>typeof u=="string"&&u.length>0);if(c.length===0)continue;o[n]=i==="join"?c.join(s):c[0];continue}o[n]=a}this.setErrors(o)}};var nt=class{constructor(t,e,i){this.fieldMetadataProvider=t;this.getState=e;this.isPathDirty=i}requiredValuesRef=null;isHidden(t){return this.fieldMetadataProvider.isHidden(t)}isRequired(t){let e=this.getState().values;return this.requiredValuesRef!==e&&(this.requiredValuesRef=e),this.fieldMetadataProvider.isRequired(t,e)}isFieldDirty(t){return this.isPathDirty(t)}isFieldValidating(t){return!!this.getState().isValidating[t]}isTouched(t){return!!this.getState().touched[t]}};function re(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp)}function se(r,t){let e=[],i=new WeakMap,s=(o,n,a,c,u)=>{if(!(c&&u&&R(o,n))){if(o!==null&&typeof o=="object"&&n!==null&&typeof n=="object"){let l=i.get(o);if(l?.has(n))return;l?l.add(n):i.set(o,new WeakSet([n]))}if(re(o)&&re(n)&&c&&u){let l=new Set([...Object.keys(o),...Object.keys(n)]);for(let d of l){let p=a?`${a}.${d}`:d,h=Object.prototype.hasOwnProperty.call(o,d),y=Object.prototype.hasOwnProperty.call(n,d);s(o[d],n[d],p,h,y)}return}e.push({path:a,previousValue:b(o),nextValue:b(n),hadPreviousValue:c,hasNextValue:u})}};return s(r,t,"",!0,!0),{operations:e}}function ot(r,t,e){let i=r,s=[],o=[];for(let n of t.operations){let a=e==="undo"?n.hadPreviousValue:n.hasNextValue,c=e==="undo"?n.previousValue:n.nextValue;if(!n.path){i=a?c:{},s.length=0,o.length=0;continue}if(a){s.push([n.path,c]);continue}o.push(n.path)}return s.length>0&&(i=P(i,s)),o.length>0&&(i=Ot(i,o)),i}var at=class{constructor(t,e){this.enableHistory=t;this.maxHistory=e}baseSnapshot=null;currentSnapshot=null;patches=[];historyIndex=-1;historySize=0;saveSnapshot(t){if(!this.enableHistory)return;if(!this.currentSnapshot||this.baseSnapshot===null){this.reset(t);return}let e=se(this.currentSnapshot,t);if(e.operations.length!==0)for(this.historyIndex<this.historySize-1&&(this.patches.splice(this.historyIndex),this.historySize=this.historyIndex+1),this.patches.push(e),this.currentSnapshot=t,this.historyIndex+=1,this.historySize=this.historyIndex+1;this.historySize>this.getCapacity();)this.compactOldestSnapshot()}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.historySize-1:!1}undo(){if(!this.canUndo||!this.currentSnapshot)return null;let t=this.patches[this.historyIndex-1],e=ot(this.currentSnapshot,t,"undo");return this.currentSnapshot=e,this.historyIndex-=1,e}redo(){if(!this.canRedo||!this.currentSnapshot)return null;let t=this.patches[this.historyIndex],e=ot(this.currentSnapshot,t,"redo");return this.currentSnapshot=e,this.historyIndex+=1,e}reset(t){if(!this.enableHistory){this.baseSnapshot=null,this.currentSnapshot=null,this.patches=[],this.historyIndex=-1,this.historySize=0;return}this.baseSnapshot=b(t),this.currentSnapshot=this.baseSnapshot,this.patches=[],this.historyIndex=0,this.historySize=1}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.historySize}}compactOldestSnapshot(){let t=this.patches.shift();!t||this.baseSnapshot===null||(this.baseSnapshot=ot(this.baseSnapshot,t,"redo"),this.historySize=Math.max(1,this.historySize-1),this.historyIndex=Math.max(0,this.historyIndex-1))}getCapacity(){return Math.max(1,this.maxHistory)}};function wt(r,t,e){if(!Object.prototype.hasOwnProperty.call(r,t))return[r,e];let s=r,o=e;return o||(s={...r},o=!0),delete s[t],[s,o]}var I=class{constructor(t){this.steps=t}async run(t){for(let e of this.steps){if(t.halted)break;await e.run(t)}}},lt=class{constructor(t){this.steps=t}run(t){for(let e of this.steps){if(t.halted)break;let i=e.run(t);if(i!=null&&typeof i.then=="function")throw new Error(`BitSyncPipelineRunner: step "${e.name}" returned a Promise. Use BitPipelineRunner for async steps.`)}}};var ct=class{constructor(t){this.store=t;this.fieldUpdatePipeline=new lt([{name:"field:clear-current-error",run:e=>this.clearCurrentError(e)},{name:"field:update-dependencies",run:e=>this.updateDependencies(e)},{name:"field:update-dirty",run:e=>this.updateDirtyState(e)},{name:"field:commit-state",run:e=>this.commitFieldState(e)},{name:"field:emit-change",run:e=>this.emitFieldChange(e)},{name:"field:trigger-validate",run:e=>this.triggerResolverValidation(e)},{name:"field:trigger-async-validate",run:e=>this.triggerAsyncValidation(e)}])}fieldUpdatePipeline;updateField(t,e,i={origin:"setField"}){let s=this.store.getState(),o=S(s.values,t),n={path:t,value:e,meta:i,previousValue:o,nextValues:O(s.values,t,e),nextErrors:s.errors,hasMutatedErrors:!1,dependencyDiff:{affectedFields:[],visibilityChanged:[],requiredChanged:[]},isDirty:!1};this.fieldUpdatePipeline.run(n)}clearCurrentError(t){[t.nextErrors,t.hasMutatedErrors]=wt(t.nextErrors,t.path,t.hasMutatedErrors),this.store.clearFieldValidation(t.path)}updateDependencies(t){if(typeof this.store.hasDependentFields=="function"&&!this.store.hasDependentFields(t.path)){t.dependencyDiff.affectedFields.length=0,t.dependencyDiff.visibilityChanged.length=0,t.dependencyDiff.requiredChanged.length=0;return}t.dependencyDiff=this.store.updateDependencies(t.path,this.store.getState().values,t.nextValues),new Set([...t.dependencyDiff.visibilityChanged,...t.dependencyDiff.requiredChanged]).forEach(i=>{[t.nextErrors,t.hasMutatedErrors]=wt(t.nextErrors,i,t.hasMutatedErrors),this.store.clearFieldValidation(i)})}updateDirtyState(t){t.isDirty=this.store.updateDirtyForPath(t.path,t.nextValues,this.store.getBaselineValues())}commitFieldState(t){let e=Array.from(new Set([t.path,...t.dependencyDiff.visibilityChanged,...t.dependencyDiff.requiredChanged]));this.store.dispatch(m({values:t.nextValues,errors:t.nextErrors,isDirty:t.isDirty},e))}emitFieldChange(t){this.store.emitFieldChange({path:t.path,previousValue:t.previousValue,nextValue:t.value,values:this.store.getState().values,state:this.store.getState(),meta:t.meta})}triggerResolverValidation(t){let e=Array.from(new Set([t.path,...t.dependencyDiff.visibilityChanged,...t.dependencyDiff.requiredChanged]));(this.store.config.resolver||t.dependencyDiff.visibilityChanged.length>0||t.dependencyDiff.requiredChanged.length>0)&&this.store.triggerValidation(e)}triggerAsyncValidation(t){(typeof this.store.getFieldConfig=="function"?this.store.getFieldConfig(t.path)?.validation?.asyncValidateOn:void 0)==="change"&&this.store.handleFieldAsyncValidation(t.path,t.value)}};var dt=class{executors=new Map;register(t,e){let i=this.executors.get(t)??[];i.push(e),this.executors.set(t,i)}async execute(t){let e=this.getOrderedExecutors(t.kind);for(let i of e)await i.execute(t)}executeSync(t){let e=this.getOrderedExecutors(t.kind);for(let i of e){let s=i.execute(t);if(s&&typeof s.then=="function")throw new Error(`BitLifecycleOrchestrator: executor async em modo sync para kind "${t.kind}".`)}}getOrderedExecutors(t){return[...this.executors.get(t)??[]].sort((i,s)=>i.phase-s.phase)}};var ut=class{constructor(t){this.store=t;this.submitPipeline=new I([{name:"submit:start",run:async e=>this.startSubmit(e)},{name:"submit:invalid",run:async e=>this.handleInvalidSubmit(e)},{name:"submit:prepare",run:e=>this.prepareSubmitValues(e)},{name:"submit:before-hooks",run:async e=>this.runBeforeSubmitHooks(e)},{name:"submit:user-handler",run:async e=>this.runSubmitHandler(e)},{name:"submit:after-hooks",run:async e=>this.runAfterSubmitHooks(e)}])}submitPipeline;async submit(t){if(this.store.getState().isSubmitting)return{status:"blocked",reason:"isSubmitting"};if(this.store.hasValidationsInProgress())return{status:"blocked",reason:"validating"};this.store.cancelAllValidations();let i={onSuccess:t,isValid:!1,valuesToSubmit:b(this.store.getState().values),dirtyValues:{}};try{return await this.submitPipeline.run(i),i.invalid?{status:"invalid"}:{status:"submitted"}}catch(s){return i.error=s,await this.store.emitOperationalError({source:"submit",error:s}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,error:s}),this.store.config.onUnhandledError(s,"submit"),{status:"failed",error:s}}finally{this.store.dispatch(m({isSubmitting:!1}))}}async startSubmit(t){this.store.dispatch(m({isSubmitting:!0})),t.isValid=await this.store.validateNow()}async handleInvalidSubmit(t){if(t.isValid)return;let e=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(e).forEach(s=>{i[s]=!0}),this.store.batchStateUpdates(()=>{this.store.dispatch(m({touched:i}))}),t.dirtyValues=this.store.buildDirtyValues(this.store.getState().values),t.invalid=!0,await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:t.dirtyValues,state:this.store.getState(),success:!1,invalid:!0}),t.halted=!0}prepareSubmitValues(t){let e=[];this.store.getHiddenFields().forEach(i=>{e.push([i,void 0])}),t.valuesToSubmit=$t({values:t.valuesToSubmit,sourceValues:this.store.getState().values,transformEntries:this.store.getTransformEntries()}),e.length>0&&(t.valuesToSubmit=P(t.valuesToSubmit,e)),t.dirtyValues=this.store.buildDirtyValues(t.valuesToSubmit)}async runBeforeSubmitHooks(t){await this.store.emitBeforeSubmit({values:t.valuesToSubmit,dirtyValues:t.dirtyValues,state:this.store.getState()})}async runSubmitHandler(t){try{await t.onSuccess(t.valuesToSubmit,t.dirtyValues)}catch(e){if(Ht(e)){this.store.setServerErrors(zt(e)),await this.store.emitAfterSubmit({values:t.valuesToSubmit,dirtyValues:t.dirtyValues,state:this.store.getState(),success:!1,invalid:!0}),t.invalid=!0,t.halted=!0;return}throw e}}async runAfterSubmitHooks(t){await this.store.emitAfterSubmit({values:t.valuesToSubmit,dirtyValues:t.dirtyValues,state:this.store.getState(),success:!0})}};var pt=class{constructor(t){this.store=t}collectChangedUpdates(t,e="",i=[],s=new WeakSet){if(t&&typeof t=="object"){if(s.has(t))return i;s.add(t)}try{Object.entries(t).forEach(([o,n])=>{let a=e?`${e}.${o}`:o;if(n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length>0){if(s.has(n))return;this.collectChangedUpdates(n,a,i,s);return}i.push([a,n])})}finally{t&&typeof t=="object"&&s.delete(t)}return i}setValues(t,e){if(e?.rebase){this.rebaseValues(t);return}if(e?.partial){this.hydrateValues(t);return}this.replaceValuesInternal(t,"replaceValues")}hydrateValues(t){let e=this.collectChangedUpdates(t),i=e.map(([o])=>o),s=e.length>0?P(this.store.getState().values,e):this.store.getState().values;this.replaceValuesInternal(s,"hydrate",i.length>0?i:["*"])}rebaseValues(t){let e=this.store.getState().values,i=b(t);this.store.setBaselineValues(t),this.store.cancelAllValidations(),this.store.evaluateAllDependencies(i),this.store.clearDirtyState(),this.store.dispatch(m({values:i,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1},["*"])),this.store.resetHistory(i),this.store.validateNow().catch(s=>{this.store.config?.onUnhandledError(s,"rebaseValues")}),this.store.emitFieldChange({path:"*",previousValue:e,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"rebase"}})}applyHistoryState(t){this.store.cancelAllValidations();let e=this.store.rebuildDirtyState(t,this.store.getBaselineValues());this.store.dispatch(m({values:t,isDirty:e},["*"])),this.store.triggerValidation(void 0,{forceDebounce:!0})}reset(){this.store.cancelAllValidations();let t=b(this.store.getBaselineValues());this.store.evaluateAllDependencies(t),this.store.clearDirtyState(),this.store.dispatch(m({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1},["*"])),this.store.resetHistory(t)}replaceValuesInternal(t,e="replaceValues",i=["*"]){let s=this.store.getState().values,o=b(t);this.store.cancelAllValidations(),this.store.evaluateAllDependencies(o);let n=this.store.rebuildDirtyState(o,this.store.getBaselineValues());this.store.dispatch(m({values:o,errors:{},isValidating:{},isValid:!0,isDirty:n},i)),this.store.internalSaveSnapshot(),this.store.validateNow().catch(a=>{this.store.config?.onUnhandledError(a,"replaceValuesInternal")}),this.store.emitFieldChange({path:"*",previousValue:s,nextValue:o,values:this.store.getState().values,state:this.store.getState(),meta:{origin:e}})}};var ht=class{constructor(t){this.ports=t;this.fieldUpdate=new ct(t.fieldUpdate),this.values=new pt(t.values),this.submitFlow=new ut(t.submit),this.orchestrator.register("updateField",{phase:1,execute:e=>this.fieldUpdate.updateField(e.path,e.value,e.meta??{origin:"setField"})}),this.orchestrator.register("setValues",{phase:2,execute:e=>this.values.setValues(e.newValues,e.options)}),this.orchestrator.register("hydrateValues",{phase:2,execute:e=>this.values.hydrateValues(e.newValues)}),this.orchestrator.register("rebaseValues",{phase:2,execute:e=>this.values.rebaseValues(e.newValues)}),this.orchestrator.register("applyHistoryState",{phase:2,execute:e=>this.values.applyHistoryState(e.snapshot)}),this.orchestrator.register("submit",{phase:3,execute:async e=>{e.submitResult=await this.submitFlow.submit(e.onSuccess)}}),this.orchestrator.register("reset",{phase:4,execute:()=>this.values.reset()})}fieldUpdate;values;submitFlow;orchestrator=new dt;updateField(t,e,i={origin:"setField"}){this.orchestrator.executeSync({kind:"updateField",path:t,value:e,meta:i})}setValues(t,e){this.orchestrator.executeSync({kind:"setValues",newValues:t,options:e})}hydrateValues(t){this.orchestrator.executeSync({kind:"hydrateValues",newValues:t})}rebaseValues(t){this.orchestrator.executeSync({kind:"rebaseValues",newValues:t})}applyHistoryState(t){this.orchestrator.executeSync({kind:"applyHistoryState",snapshot:t})}async submit(t){let e={kind:"submit",onSuccess:t};return await this.orchestrator.execute(e),e.submitResult}reset(){this.orchestrator.executeSync({kind:"reset"})}};var ft=class{constructor(t,e,i,s){this.getState=t;this.getInitialValues=e;this.getScopeFields=i;this.isPathDirty=s}getScopeStatus(t){let e=this.getScopeFields(t),i=this.getState(),s=e.some(a=>!!i.errors[a]),o=e.some(a=>this.isPathDirty(a)),n=this.getScopeErrors(t);return{hasErrors:s,isDirty:o,errors:n}}getScopeErrors(t){let e=this.getScopeFields(t),i=this.getState(),s={};for(let o of e){let n=i.errors[o];n&&(s[o]=n)}return s}};var ne=Symbol("bit.async.validation.timeout"),gt=class{constructor(t){this.port=t}cancelSchedulerTimeout;abortControllers=new Map;pendingJobs=new Map;handle(t,e,i,s,o){if(!i){this.cancel(t),this.port.setFieldValidating(t,!1);return}this.cancel(t),this.port.clearAsyncError(t),this.port.setFieldValidating(t,!0);let n=new AbortController;this.abortControllers.set(t,n),this.pendingJobs.set(t,{value:e,dueAt:Date.now()+s,validate:i,controller:n,timeoutMs:o}),this.schedulePendingJobs()}cancel(t){this.cancelInternal(t,!0)}cancelInternal(t,e){this.pendingJobs.has(t)&&(this.pendingJobs.delete(t),e&&this.schedulePendingJobs());let i=this.abortControllers.get(t);i&&(i.abort(),this.abortControllers.delete(t))}cleanupPrefix(t){let e=!1,i=new Set([...this.pendingJobs.keys(),...this.abortControllers.keys()]);for(let s of i)E(s,t)&&(this.cancelInternal(s,!1),e=!0,this.port.clearAsyncError(s),this.port.setFieldValidating(s,!1));e&&this.schedulePendingJobs()}cancelAll(){if(this.cancelSchedulerTimeout)try{this.cancelSchedulerTimeout()}catch{}finally{this.cancelSchedulerTimeout=void 0}this.abortControllers.forEach(t=>{try{t.abort()}catch{}}),this.pendingJobs.clear(),this.abortControllers.clear()}schedulePendingJobs(){this.cancelSchedulerTimeout&&(this.cancelSchedulerTimeout(),this.cancelSchedulerTimeout=void 0);let t=Number.POSITIVE_INFINITY;for(let e of this.pendingJobs.values())e.dueAt<t&&(t=e.dueAt);Number.isFinite(t)&&(this.cancelSchedulerTimeout=this.port.schedule(()=>{this.cancelSchedulerTimeout=void 0,this.flushPendingJobs().catch(e=>{this.port.onError(e)})},Math.max(0,t-Date.now())))}async flushPendingJobs(){this.cancelSchedulerTimeout=void 0;let t=Date.now(),e=[];for(let[s,o]of this.pendingJobs.entries())o.dueAt<=t&&e.push([s,o]);if(e.length===0){this.schedulePendingJobs();return}e.forEach(([s])=>{this.pendingJobs.delete(s)});let i=await Promise.allSettled(e.map(([s,o])=>this.runJob(s,o)));for(let s of i)s.status==="rejected"&&this.port.onError(s.reason);this.schedulePendingJobs()}async runJob(t,e){if(!e.controller.signal.aborted)try{let i=e.validate(e.value,this.port.getValues());if(typeof e.timeoutMs=="number"&&e.timeoutMs>0){let n;i=Promise.race([i,new Promise(a=>{n=setTimeout(()=>a(ne),e.timeoutMs)})]).finally(()=>{n&&clearTimeout(n)})}let s=await i;if(e.controller.signal.aborted)return;let o=S(this.port.getValues(),t);if(!F(o,e.value)||s===ne)return;s?this.port.setAsyncError(t,s):(this.port.clearAsyncError(t),await this.port.onValidationPassed(t))}finally{e.controller.signal.aborted||this.port.setFieldValidating(t,!1),this.abortControllers.get(t)===e.controller&&this.abortControllers.delete(t)}}};function D(r){for(let t in r)return!0;return!1}async function At(r){let{scopeFields:t,store:e,asyncErrors:i}=r,s=e.getState(),o=e.config.resolver?await e.config.resolver(s.values,{scopeFields:t}):{},n=e.getState();if(!Object.is(s.values,n.values))return;let c=e.getRequiredErrors(n.values),u={...o,...c};e.getHiddenFields().forEach(d=>{delete u[d],i.delete(d)});let l={...n.errors};t.forEach(d=>{u[d]?l[d]=u[d]:i.has(d)?l[d]=i.get(d):delete l[d]}),e.dispatch(tt(l,!D(l)))}var mt=class{currentValidationId=0;immediateAbortControllers=new Map;beginValidation(){return this.currentValidationId+=1,this.currentValidationId}getCurrentValidationId(){return this.currentValidationId}isValidationCurrent(t){return t===this.currentValidationId}setImmediateController(t,e){this.immediateAbortControllers.set(t,e)}clearImmediateController(t,e){this.immediateAbortControllers.get(t)===e&&this.immediateAbortControllers.delete(t)}cancelImmediate(t){let e=this.immediateAbortControllers.get(t);e&&(e.abort(),this.immediateAbortControllers.delete(t))}cancelImmediatePrefix(t,e){for(let i of this.immediateAbortControllers.keys())E(i,t)&&(this.cancelImmediate(i),e(i))}cancelAllImmediate(){this.immediateAbortControllers.forEach(t=>{t.abort()}),this.immediateAbortControllers.clear()}};var yt=class{constructor(t){this.port=t}cancelTimeout;pendingScopeFields=null;trigger(t,e){this.cancelTimeout&&(this.cancelTimeout(),this.cancelTimeout=void 0);let i=this.port.validationDelay??300,s=e?.forceDebounce?Math.max(1,i):i;if(s>0){if(t&&t.length>0)if(!this.pendingScopeFields)this.pendingScopeFields=new Set(t);else for(let n of t)this.pendingScopeFields.add(n);else this.pendingScopeFields=null;let o=this.pendingScopeFields?Array.from(this.pendingScopeFields):void 0;this.cancelTimeout=this.port.schedule(()=>{this.pendingScopeFields=null,this.cancelTimeout=void 0,this.validateWithOptionalScopeFields(o)},s)}else this.pendingScopeFields=null,this.validateWithOptionalScopeFields(t)}validateWithOptionalScopeFields(t){return t&&t.length>0?this.port.validate({scopeFields:t}):this.port.validate()}cancelPending(){this.cancelTimeout&&(this.cancelTimeout(),this.cancelTimeout=void 0),this.pendingScopeFields=null}};var oe=Symbol("bit.async.validation.timeout");function ae(r){let{targetFields:t,currentErrors:e,allErrors:i,asyncErrors:s}=r;if(t&&t.length>0){let n=e,a=!1,c=()=>(a||(n={...e},a=!0),n);t.forEach(l=>{let d=l,p=e[d];if(i[l])p!==i[l]&&(c()[d]=i[l]);else if(s.has(l)){let h=s.get(l);p!==h&&(c()[d]=h)}else p!==void 0&&delete c()[d]});let u=t.every(l=>!i[l]&&!s.has(l));return{committedErrors:a?n:e,result:u,mode:"scoped"}}let o={};return s.forEach((n,a)=>{o[a]=n}),Object.entries(i).forEach(([n,a])=>{o[n]=a}),{committedErrors:o,result:void 0,mode:"global"}}function le(r){let{targetFields:t,hiddenFields:e,getFieldConfig:i,forEachFieldConfig:s}=r,o=[];if(t&&t.length>0){for(let n of t){if(e.has(n))continue;i(n)?.validation?.asyncValidate&&o.push(n)}return o}return s&&s((n,a)=>{!n.validation?.asyncValidate||e.has(a)||o.push(a)}),o}async function ce(r){let{path:t,values:e,validationId:i,getCurrentValidationId:s,getFieldConfig:o,cancelFieldAsync:n,createAbortController:a,setAbortController:c,clearAbortController:u,setFieldValidating:l,setAsyncError:d,clearAsyncError:p}=r,h=o(t)?.validation?.asyncValidate;if(!h){p(t);return}n(t),p(t);let y=a();c(t,y),l(t,!0);try{let v=o(t)?.validation?.asyncValidateTimeout,f=h(S(e,t),e);if(typeof v=="number"&&v>0){let T;f=Promise.race([f,new Promise(V=>{T=setTimeout(()=>V(oe),v)})]).finally(()=>{T&&clearTimeout(T)})}let g=await f;if(y.signal.aborted||i!==s())return;g===oe||(g?d(t,g):p(t))}finally{!y.signal.aborted&&i===s()&&l(t,!1),u(t,y)}}function de(r){let{ctx:t,deps:e}=r,i=t.options;if(i?.scope&&i.scopeFields?.length){e.store.config.onUnhandledError(new Error("validate received both 'scope' and 'scopeFields'. 'scopeFields' takes precedence."),"validation");return}if(!t.options?.scopeFields?.length&&t.options?.scope){let s=e.store.getScopeFields(t.options.scope);s.length>0&&(t.targetFields=s)}}async function ue(r){let{ctx:t,deps:e}=r;await e.store.emitBeforeValidate({values:t.currentState.values,state:t.currentState,scope:t.options?.scope,scopeFields:t.targetFields})}async function pe(r){let{ctx:t,deps:e}=r,i=e.store.config.resolver?await e.store.config.resolver(t.currentState.values,{scopeFields:t.targetFields}):{},s=e.store.getRequiredErrors(t.currentState.values);t.allErrors={...i,...s},e.store.getHiddenFields().forEach(o=>{delete t.allErrors[o],e.asyncErrors.delete(o)})}async function he(r){let{ctx:t,deps:e}=r,i=le({targetFields:t.targetFields,hiddenFields:e.store.getHiddenFields(),getFieldConfig:s=>e.store.getFieldConfig(s),forEachFieldConfig:e.store.forEachFieldConfig});i.length!==0&&await Promise.all(i.map(s=>e.runImmediateAsyncValidation(s,t.currentState.values,t.validationId)))}function fe(r){let{ctx:t,deps:e}=r,i=ae({targetFields:t.targetFields,currentErrors:t.currentState.errors,allErrors:t.allErrors,asyncErrors:e.asyncErrors});t.committedErrors=i.committedErrors,t.isValid=!D(i.committedErrors),t.result=i.mode==="scoped"?i.result:t.isValid}async function It(r){let{ctx:t,deps:e}=r;t.validationId!==e.getCurrentValidationId()&&(t.aborted=!0,t.result=e.store.getState().isValid,t.halted=!0)}async function ge(r){let{ctx:t,deps:e}=r;e.store.dispatch(tt(t.committedErrors,t.isValid)),await e.store.emitAfterValidate({values:e.store.getState().values,state:e.store.getState(),scope:t.options?.scope,scopeFields:t.targetFields,errors:t.committedErrors,result:t.result}),t.halted=!0}var St=class{constructor(t){this.deps=t;this.runner=new I([{name:"validate:resolve-target-fields",run:e=>de({ctx:e,deps:this.deps})},{name:"validate:before-hooks",run:async e=>ue({ctx:e,deps:this.deps})},{name:"validate:sync-track",run:async e=>pe({ctx:e,deps:this.deps})},{name:"validate:abort-check-pre-async",run:async e=>It({ctx:e,deps:this.deps})},{name:"validate:async-track",run:async e=>he({ctx:e,deps:this.deps})},{name:"validate:abort-check",run:async e=>It({ctx:e,deps:this.deps})},{name:"validate:async-track-merge",run:e=>fe({ctx:e,deps:this.deps})},{name:"validate:commit",run:async e=>ge({ctx:e,deps:this.deps})}])}runner;async run(t){await this.runner.run(t)}};var bt=class{constructor(t){this.store=t;this.schedule=t.config.scheduler?.schedule??((i,s)=>{let o=setTimeout(i,s);return()=>clearTimeout(o)}),this.debouncer=new yt({schedule:(i,s)=>this.schedule(i,s),validate:i=>this.validate(i),validationDelay:t.config.validationDelay??300}),this.pipelineStore={getState:()=>this.store.getState(),dispatch:i=>this.store.dispatch(i),config:this.store.config,getFieldConfig:i=>this.store.getFieldConfig(i),forEachFieldConfig:i=>this.store.forEachFieldConfig(i),getScopeFields:i=>this.store.getScopeFields(i),getRequiredErrors:i=>this.store.getRequiredErrors(i),getHiddenFields:()=>this.store.getHiddenFields(),emitBeforeValidate:i=>this.store.emitBeforeValidate(i),emitAfterValidate:i=>this.store.emitAfterValidate(i)},this.asyncScheduler=new gt({schedule:(i,s)=>this.schedule(i,s),getValues:()=>this.store.getState().values,setFieldValidating:(i,s)=>this.updateFieldValidating(i,s),setAsyncError:(i,s)=>{this.asyncErrors.set(i,s),this.store.setError(i,s)},clearAsyncError:i=>{let s=this.asyncErrors.get(i);this.asyncErrors.delete(i),s&&!this.store.config.resolver&&this.store.getState().errors[i]===s&&this.store.setError(i,void 0),At({scopeFields:[i],store:this.pipelineStore,asyncErrors:this.asyncErrors}).catch(o=>{this.store.config.onUnhandledError(o,"validation")})},onValidationPassed:async i=>{await At({scopeFields:[i],store:this.pipelineStore,asyncErrors:this.asyncErrors})},onError:i=>{this.store.config.onUnhandledError(i,"validation")}});let e={store:this.pipelineStore,asyncErrors:this.asyncErrors,getCurrentValidationId:()=>this.coordinator.getCurrentValidationId(),runImmediateAsyncValidation:(i,s,o)=>this.runImmediateAsyncValidation(i,s,o)};this.validationPipeline=new St(e)}validatingCount=0;asyncErrors=new Map;coordinator=new mt;validationPipeline;pipelineStore;schedule;asyncScheduler;debouncer;updateFieldValidating(t,e){let i=this.store.getState();if(!!i.isValidating[t]===e)return;let o={...i.isValidating};e?(o[t]=!0,this.validatingCount+=1):(delete o[t],this.validatingCount=Math.max(0,this.validatingCount-1)),this.store.dispatch(m({isValidating:o}))}cancelFieldAsync(t){this.asyncScheduler.cancel(t),this.coordinator.cancelImmediate(t)}cleanupField(t){this.cancelFieldAsync(t),this.asyncErrors.delete(t),this.updateFieldValidating(t,!1)}cleanupPrefix(t){this.asyncScheduler.cleanupPrefix(t),this.coordinator.cancelImmediatePrefix(t,e=>{this.asyncErrors.delete(e),this.updateFieldValidating(e,!1)})}beginExternalValidation(t){this.cancelFieldAsync(t),this.updateFieldValidating(t,!0)}endExternalValidation(t){this.updateFieldValidating(t,!1)}async setExternalError(t,e){if(e){this.asyncErrors.set(t,e),this.store.setError(t,e);return}this.cancelFieldAsync(t),this.asyncErrors.delete(t),this.store.setError(t,void 0),await this.validate({scopeFields:[t]})}handleAsync(t,e){let i=this.store.getFieldConfig(t),s=i?.validation?.asyncValidate,o=i?.validation?.asyncValidateOn??"blur";if(!s||o!=="change"){this.cancelFieldAsync(t),this.updateFieldValidating(t,!1);return}let n=i.validation?.asyncValidateDelay??500,a=i.validation?.asyncValidateTimeout;this.asyncScheduler.handle(t,e,s,n,a)}hasValidationsInProgress(t){let e=this.store.getState();return t&&t.length>0?t.some(i=>!!e.isValidating[i]):Object.keys(e.isValidating).length>0}trigger(t,e){this.debouncer.trigger(t,e)}async validate(t){try{t?.scopeFields?.length&&t.scopeFields.forEach(i=>this.cancelFieldAsync(i));let e={options:t,validationId:this.coordinator.beginValidation(),currentState:this.store.getState(),targetFields:t?.scopeFields,allErrors:{},committedErrors:{},isValid:!0,result:!0,aborted:!1};if(await this.validationPipeline.run(e),e.aborted){let i=this.store.getState();await this.store.emitAfterValidate({values:i.values,state:i,scope:e.options?.scope,scopeFields:e.targetFields,errors:i.errors,result:i.isValid,aborted:!0})}return e.result}catch(e){return this.store.config.onUnhandledError(e,"validation"),!1}}clear(t){this.cancelFieldAsync(t),this.updateFieldValidating(t,!1),this.asyncErrors.delete(t)}cancelAll(){this.validatingCount=0,this.debouncer.cancelPending(),this.asyncScheduler.cancelAll(),this.asyncErrors.clear(),this.coordinator.cancelAllImmediate(),this.store.dispatch(m({isValidating:{}}))}async runImmediateAsyncValidation(t,e,i){await ce({path:t,values:e,validationId:i,getCurrentValidationId:()=>this.coordinator.getCurrentValidationId(),getFieldConfig:s=>this.store.getFieldConfig(s),cancelFieldAsync:s=>this.cancelFieldAsync(s),createAbortController:()=>new AbortController,setAbortController:(s,o)=>{this.coordinator.setImmediateController(s,o)},clearAbortController:(s,o)=>{this.coordinator.clearImmediateController(s,o)},setFieldValidating:(s,o)=>this.updateFieldValidating(s,o),setAsyncError:(s,o)=>{this.asyncErrors.set(s,o)},clearAsyncError:s=>{this.asyncErrors.delete(s)}})}};var Dt=class{entries=new Map;register(t,e){this.entries.set(t,e)}resolve(t){let e=this.entries.get(t);if(!e)throw new Error(`BitStore capability "${String(t)}" n\xE3o foi registrada.`);return e}toCapabilities(){return{validation:this.resolve("validation"),lifecycle:this.resolve("lifecycle"),history:this.resolve("history"),arrays:this.resolve("arrays"),scope:this.resolve("scope"),query:this.resolve("query"),error:this.resolve("error")}}};function me(){return new Dt}function hi(r){let{registry:t,ports:e,fieldRegistry:i}=r;t.register("validation",new bt(e.validationPort)),t.register("lifecycle",new ht(e.lifecyclePorts)),t.register("history",new at(!!e.config.history.enabled,e.config.history.limit??50)),t.register("arrays",new rt(e.arrayPort)),t.register("scope",new ft(()=>e.getState(),()=>e.getBaselineValues(),s=>e.getScopeFields(s),s=>e.isPathDirty(s))),t.register("query",new nt(i,()=>e.getState(),s=>e.isPathDirty(s))),t.register("error",new st(()=>e.getState(),s=>e.dispatch(s),s=>e.config.onUnhandledError(s,"errors")))}function ye(r){let{ports:t,fieldRegistry:e}=r,i=me();return hi({registry:i,ports:t,fieldRegistry:e}),{registry:i,capabilities:i.toCapabilities()}}function Se(r){let{config:t,fieldRegistry:e,computedManager:i}=r,s=b(t.initialValues);t.fields&&Object.entries(t.fields).forEach(([a,c])=>{e.register(a,c,s)});let o=ie(e.getComputedEntries());if(o.length>0)throw new Error(o[0].message);return{values:K({values:s,normalizerEntries:e.getNormalizerEntries(),applyComputed:(a,c)=>i.apply(a,c),onError:(a,c)=>{t.onUnhandledError(a,"derivation")}}),errors:{},touched:{},isValidating:{},persist:{isSaving:!1,isRestoring:!1,error:null},isValid:!0,isSubmitting:!1,isDirty:!1}}function be(r){return{getState:r.getState,dispatch:r.dispatch,setError:r.setError,getFieldConfig:r.getFieldConfig,forEachFieldConfig:t=>r.fieldRegistry.forEachFieldConfig((e,i)=>t(e,i)),getScopeFields:r.getScopeFields,config:r.config,getRequiredErrors:t=>r.fieldRegistry.getRequiredErrors(t),getHiddenFields:()=>r.fieldRegistry.getHiddenFields(),emitBeforeValidate:t=>r.getEffects().beforeValidate(t),emitAfterValidate:t=>r.getEffects().afterValidate(t)}}function Be(r){let t={getState:r.getState,dispatch:r.dispatch,config:r.config,getFieldConfig:s=>r.fieldRegistry.getFieldConfig(s),updateDependencies:(s,o,n)=>r.fieldRegistry.updateDependencies(s,o,n),hasDependentFields:s=>r.fieldRegistry.hasDependents(s),isFieldHidden:s=>r.fieldRegistry.isHidden(s),clearFieldValidation:s=>r.getValidation().clear(s),triggerValidation:(s,o)=>r.getValidation().trigger(s,o),handleFieldAsyncValidation:(s,o)=>r.getValidation().handleAsync(s,o),updateDirtyForPath:(s,o,n)=>r.dirtyManager.updateForPath(s,o,n),getBaselineValues:r.getBaselineValues,emitFieldChange:s=>r.getEffects().onFieldChange(s)},e={getState:r.getState,dispatch:r.dispatch,config:r.config,internalSaveSnapshot:r.saveHistorySnapshot,evaluateAllDependencies:s=>r.fieldRegistry.evaluateAll(s),cancelAllValidations:()=>r.getValidation().cancelAll(),validateNow:s=>r.getValidation().validate(s),rebuildDirtyState:(s,o)=>r.dirtyManager.rebuild(s,o),clearDirtyState:r.dirtyManager.clear.bind(r.dirtyManager),getBaselineValues:r.getBaselineValues,setBaselineValues:r.setBaselineValues,resetHistory:s=>r.getHistory().reset(s),emitFieldChange:s=>r.getEffects().onFieldChange(s),triggerValidation:(s,o)=>r.getValidation().trigger(s,o)},i={getState:r.getState,dispatch:r.dispatch,batchStateUpdates:r.runStateBatch,config:r.config,getTransformEntries:r.getTransformEntries,getHiddenFields:()=>r.fieldRegistry.getHiddenFields(),cancelAllValidations:()=>r.getValidation().cancelAll(),validateNow:s=>r.getValidation().validate(s),hasValidationsInProgress:s=>r.getValidation().hasValidationsInProgress(s),buildDirtyValues:s=>r.dirtyManager.buildDirtyValues(s),setServerErrors:(s,o)=>r.setServerErrors(s,o),emitBeforeSubmit:s=>r.getEffects().beforeSubmit(s),emitAfterSubmit:s=>r.getEffects().afterSubmit(s),emitOperationalError:s=>r.getEffects().reportOperationalError(s)};return{fieldUpdate:t,values:e,submit:i}}function ve(r){return{getState:r.getState,setFieldWithMeta:r.setFieldWithMeta,dispatch:r.dispatch,internalSaveSnapshot:r.saveHistorySnapshot,unregisterPrefix:r.unregisterPrefix,createArrayItemId:r.createArrayItemId}}function Te(r){let{config:t,fieldRegistry:e,dirtyManager:i,baselineManager:s,runtimeContext:o}=r,{stateAccess:n,fieldAccess:a,featureAccess:c,actions:u}=o,l=be({config:t,fieldRegistry:e,getState:n.getState,dispatch:n.dispatch,setError:u.setError,getFieldConfig:a.getFieldConfig,getScopeFields:a.getScopeFields,getEffects:c.getEffects}),d=Be({config:t,fieldRegistry:e,dirtyManager:i,getState:n.getState,dispatch:n.dispatch,setServerErrors:u.setServerErrors,saveHistorySnapshot:n.saveHistorySnapshot,runStateBatch:n.runStateBatch,getTransformEntries:a.getTransformEntries,getBaselineValues:()=>s.getValues(),setBaselineValues:h=>s.setValues(h),getValidation:c.getValidation,getHistory:c.getHistory,getEffects:c.getEffects}),p=ve({getState:n.getState,dispatch:n.dispatch,setFieldWithMeta:(h,y,v)=>u.setFieldWithMeta(h,y,v),unregisterPrefix:u.unregisterPrefix,saveHistorySnapshot:n.saveHistorySnapshot,createArrayItemId:(h,y)=>t.idFactory({scope:"array",path:h,index:y})});return ye({ports:{validationPort:l,lifecyclePorts:d,arrayPort:p,config:t,getScopeFields:a.getScopeFields,getState:n.getState,dispatch:n.dispatch,getBaselineValues:()=>s.getValues(),isPathDirty:h=>i.isPathDirty(h)},fieldRegistry:e})}function Pe(r){let{config:t,fieldRegistry:e,dirtyManager:i,computedManager:s,rawConfig:o,baselineManager:n,runtimeContext:a}=r,{stateAccess:c,fieldAccess:u,featureAccess:l,actions:d}=a,p=Te({config:t,fieldRegistry:e,dirtyManager:i,baselineManager:n,runtimeContext:{stateAccess:c,fieldAccess:u,featureAccess:l,actions:d}}),h=Se({config:t,fieldRegistry:e,computedManager:s}),y=new it(c.getState,t.subscriptionCacheSize),v=o.storeId||t.name||t.idFactory({scope:"store",storeName:t.name});return{state:h,subscriptions:y,capabilityRegistry:p.registry,storeId:v}}function Ee(){return{depth:0,pendingState:null,changedPathSet:null,changedPathList:null,valuesChanged:!1,pendingHistorySnapshot:!1}}function xe(r){r.depth+=1}function Ce(r){return r.depth-=1,r.depth===0}function Bt(r,t){return t.pendingState??r}function Fe(r,t){if(r.pendingState=t.nextState,r.valuesChanged||=t.valuesChanged,t.valuesChanged&&(r.pendingHistorySnapshot=!0),t.changedPaths&&t.changedPaths.length>0){let e=r.changedPathSet??new Set,i=r.changedPathList??[];t.changedPaths.forEach(s=>{if(e.has("*")||e.has(s))return;if(s==="*"){e.clear(),i.length=0,e.add("*"),i.push("*");return}if(!i.some(n=>n!=="*"&&s.startsWith(`${n}.`))){for(let n=i.length-1;n>=0;n-=1){let a=i[n];a==="*"||!a.startsWith(`${s}.`)||(e.delete(a),i.splice(n,1))}e.add(s),i.push(s)}}),r.changedPathSet=e,r.changedPathList=i}}function Ve(r){let{currentState:t,batchState:e,applyValueDerivations:i}=r;if(!e.pendingState)return e.pendingHistorySnapshot=!1,null;let s=e.pendingState,o=e.changedPathList??void 0,n=e.valuesChanged;return n&&(s={...s,values:i(s.values,o)}),e.pendingState=null,e.changedPathSet=null,e.changedPathList=null,e.valuesChanged=!1,{nextState:s??t,changedPaths:o,valuesChanged:n}}function fi(r){let t=!1;for(let i of Object.values(r))if(i===void 0){t=!0;break}if(!t)return r;let e={};return Object.entries(r).forEach(([i,s])=>{let o=s;o!==void 0&&(e[i]=o)}),e}function kt(r){let{currentState:t,partialState:e,changedPaths:i,applyValueDerivations:s,applyComputedValues:o}=r,n=s??(p=>o?o(p):p),a={...t,...e},c=!!e.values;e.values&&(a.values=n(e.values,i)),e.errors&&(a.errors=fi(e.errors),a.isValid=!D(a.errors));let u=i&&i.length>0?i:void 0,l=gi(e),d=W(u,l);return{nextState:a,changedPaths:d,valuesChanged:c}}function gi(r){let t=new Set,e=[r.errors,r.touched,r.isValidating];for(let i of e)if(i)for(let s in i)t.add(s);return r.persist&&t.add("persist"),"isValid"in r&&t.add("isValid"),"isDirty"in r&&t.add("isDirty"),"isSubmitting"in r&&t.add("isSubmitting"),t.size>0?Array.from(t):void 0}function mi(r){throw new Error(`BitStore: unsupported operation kind: ${String(r.kind)}`)}function yi(r,t){switch(t.kind){case"state.patch":return t;case"field.touchMany":{if(t.paths.length===0)return null;let e={...r.touched};for(let i of t.paths)e[i]=!0;return m({touched:e},t.paths)}case"form.persistMeta":return m({persist:{...r.persist,...t.patch}});case"history.apply":return m({values:t.values,isDirty:t.isDirty},["*"]);case"validation.commit":return m({errors:t.errors,isValid:t.isValid});default:return mi(t)}}function Si(r){let{currentState:t,operation:e,applyValueDerivations:i}=r,s=Object.prototype.hasOwnProperty.call(e.partialState,"values"),o=e.changedPaths??(s?["*"]:void 0),n;try{n=kt({currentState:t,partialState:e.partialState,changedPaths:o,applyValueDerivations:i})}catch(a){console.error("Derivation error during state patch:",a),n=kt({currentState:t,partialState:e.partialState,changedPaths:o,applyValueDerivations:c=>c})}return n}function we(r){let{currentState:t,operation:e,applyValueDerivations:i}=r,s=yi(t,e);return s?Si({currentState:t,operation:s,applyValueDerivations:(o,n)=>s.skipComputed?o:i(o,n)}):null}function Ae(r){let{state:t,batchState:e,operation:i,applyValueDerivations:s,onStateCommitted:o}=r,n=Bt(t,e);if(e.depth>0){let c=we({currentState:n,operation:i,applyValueDerivations:u=>u});return c&&Fe(e,c),t}let a=we({currentState:t,operation:i,applyValueDerivations:s});return a?(o({nextState:a.nextState,changedPaths:a.changedPaths,valuesChanged:a.valuesChanged}),a.nextState):t}function Ie(r){let{state:t,batchState:e,applyValueDerivations:i,onStateCommitted:s}=r,o=Ve({currentState:t,batchState:e,applyValueDerivations:i});return o?(s({nextState:o.nextState,changedPaths:o.changedPaths,valuesChanged:o.valuesChanged}),o.nextState):t}function De(r){let{batchState:t,callback:e,flushBatchedStateUpdates:i}=r;xe(t);try{return e()}finally{Ce(t)&&i()}}function ke(r){let{payload:t,setState:e,notifySubscriptions:i,notifyEffects:s}=r;e(t.nextState),i(t.nextState,t.changedPaths),s(t.nextState,t.valuesChanged)}function Me(r){let{state:t,batchState:e,operation:i,applyValueDerivations:s,onStateCommitted:o}=r;return Ae({state:t,batchState:e,operation:i,applyValueDerivations:s,onStateCommitted:o})}function Re(r){let{batchState:t,values:e,saveHistory:i}=r;if(t.depth>0){t.pendingHistorySnapshot=!0;return}i(e)}function Oe(r){let{state:t,batchState:e,applyValueDerivations:i,onStateCommitted:s,saveHistory:o}=r,n=Ie({state:t,batchState:e,applyValueDerivations:i,onStateCommitted:s});return e.pendingHistorySnapshot&&(e.pendingHistorySnapshot=!1,o(n.values)),n}var vt=class{constructor(t){this.args=t;this.state=t.state,this.subscriptions=t.subscriptions,this.effects=t.effects,this.capabilityRegistry=t.capabilityRegistry,this.capabilities=t.capabilityRegistry.toCapabilities()}state;batchState=Ee();subscriptions;effects;capabilityRegistry;capabilities;getCapability(t){return this.capabilityRegistry.resolve(t)}getState(){return Bt(this.state,this.batchState)}runBatch(t){return De({batchState:this.batchState,callback:t,flushBatchedStateUpdates:()=>this.flushBatchedStateUpdates()})}dispatch(t){this.state=Me({state:this.state,batchState:this.batchState,operation:t,applyValueDerivations:(e,i)=>this.applyValueDerivations(e,i),onStateCommitted:e=>this.onStateCommitted(e)})}saveHistorySnapshot(){let t=this.capabilities.history.getMetadata();Re({batchState:this.batchState,values:this.state.values,saveHistory:i=>this.capabilities.history.saveSnapshot(i)});let e=this.capabilities.history.getMetadata();this.notifyIfHistoryChanged(t,e)}cleanup(){this.subscriptions.destroy(),this.capabilities.validation.cancelAll(),this.effects.destroy()}onStateCommitted(t){ke({payload:t,setState:e=>{this.state=e},notifySubscriptions:(e,i)=>this.subscriptions.notify(e,i),notifyEffects:(e,i)=>this.effects.onStateUpdated(e,i)})}flushBatchedStateUpdates(){let t=this.capabilities.history.getMetadata();this.state=Oe({state:this.state,batchState:this.batchState,applyValueDerivations:(i,s)=>this.applyValueDerivations(i,s),onStateCommitted:i=>this.onStateCommitted(i),saveHistory:i=>this.capabilities.history.saveSnapshot(i)});let e=this.capabilities.history.getMetadata();this.notifyIfHistoryChanged(t,e)}applyValueDerivations(t,e){return this.args.applyValueDerivations?this.args.applyValueDerivations(t,e):t}notifyIfHistoryChanged(t,e){t.canUndo===e.canUndo&&t.canRedo===e.canRedo&&t.historyIndex===e.historyIndex&&t.historySize===e.historySize||this.subscriptions.notify(this.getState(),[j()])}};function je(r){let{rawConfig:t,overrides:e}=r,i=Wt(t),s=e?.baselineManager??new H(i.initialValues),o=e?.fieldRegistry??new N(({error:f})=>{i.onUnhandledError(f,"validation")}),n=e?.computedManager??new z(()=>o.getComputedEntries(),f=>i.onUnhandledError(f,"computed")),a=e?.dirtyManager??new U,c=e?.maskManager??new q;i.masks&&Object.entries(i.masks).forEach(([f,g])=>{c.registerMask(f,g)});let u=()=>{o.invalidateIndexes(),n.invalidateReverseDeps()},l,d=()=>{if(!l)throw new Error("BitStore runtime kernel is not initialized yet.");return l},p=Pe({rawConfig:t,config:i,fieldRegistry:o,computedManager:n,dirtyManager:a,baselineManager:s,runtimeContext:{stateAccess:{getState:()=>d().getState(),dispatch:f=>d().dispatch(f),saveHistorySnapshot:()=>d().saveHistorySnapshot(),runStateBatch:f=>d().runBatch(f)},fieldAccess:{getFieldConfig:f=>o.getFieldConfig(f),getScopeFields:f=>o.getScopeFields(f),getNormalizerEntries:()=>o.getNormalizerEntries(),getTransformEntries:()=>o.getTransformEntries()},featureAccess:{getEffects:()=>d().effects,getHistory:()=>d().getCapability("history"),getValidation:()=>d().getCapability("validation")},actions:{setError:(f,g)=>{d().getCapability("error").setError(f,g)},setServerErrors:(f,g)=>{d().getCapability("error").setServerErrors(f,g)},validate:f=>d().getCapability("validation").validate(f),setFieldWithMeta:(f,g,T={origin:"setField"})=>{d().runBatch(()=>{d().getCapability("lifecycle").updateField(f,g,T)})},unregisterPrefix:f=>{et({prefix:f,state:d().getState(),fieldRegistry:o,subscriptions:d().subscriptions,validationCleanupPrefix:g=>d().getCapability("validation").cleanupPrefix(g),invalidateFieldIndexes:u})},triggerValidation:(f,g)=>{d().getCapability("validation").trigger(f,g)}}}}),h=()=>{let f=d().getState();return a.buildDirtyValues(f.values)},y=f=>{Qt({values:f,state:d().getState(),initialValues:s.getValues(),validation:d().getCapability("validation"),fieldRegistry:o,dirtyManager:a,dispatch:g=>d().dispatch(g),saveHistorySnapshot:()=>d().saveHistorySnapshot()})},v=Jt({storeId:p.storeId,config:i,getState:()=>d().getState(),getConfig:()=>i,getValues:()=>d().getState().values,getDirtyValues:h,applyPersistedValues:y,setPersistMetadata:f=>d().dispatch({kind:"form.persistMeta",patch:f})});return l=new vt({state:p.state,subscriptions:p.subscriptions,effects:v,capabilityRegistry:p.capabilityRegistry,applyValueDerivations:(f,g)=>K({values:f,changedPaths:g,normalizerEntries:o.getNormalizerEntries(),applyComputed:(T,V)=>n.apply(T,V),onError:(T,V)=>{i.onUnhandledError(T,"derivation")}})}),l.saveHistorySnapshot(),{config:i,storeId:p.storeId,runtime:l,fieldRegistry:o,computedManager:n,dirtyManager:a,maskManager:c,baselineManager:s}}function He(r){let{dispatch:t,effects:e}=r;return Yt({dispatch:t,effects:e})}function ze(r){let{dispatch:t,effects:e}=r;return Gt({dispatch:t,effects:e})}function Ue(r){let{dispatch:t,effects:e}=r;return Xt({dispatch:t,effects:e})}function qe(r){let{history:t,applyHistoryState:e}=r,i=t.undo();i&&e(i)}function Le(r){let{history:t,applyHistoryState:e}=r,i=t.redo();i&&e(i)}function _e(r){return r.history.getMetadata()}function Ne(r,t){let e=new Set,i=(n,a)=>n===null||typeof n!="object"?n:new Proxy(n,{get:(c,u,l)=>{if(typeof u=="symbol")return Reflect.get(c,u,l);let d=String(u),p=a?`${a}.${d}`:d;e.add(p);let h=Reflect.get(c,u,l);return i(h,p)}}),s=i(r,"");t(s);let o=new Set;return e.forEach(n=>{let a=bi(n);a&&o.add(a)}),Array.from(o)}function bi(r){if(r)return r==="values"?"*":r.startsWith("values.")?r.slice(7):r==="errors"||r==="touched"||r==="isValidating"?"*":r.startsWith("errors.")?r.slice(7):r.startsWith("touched.")?r.slice(8):r.startsWith("isValidating.")?r.slice(13):r==="persist"||r.startsWith("persist.")?"persist":r}function Bi(r,t){if(r.length!==t.length)return!1;let e=new Set(t);for(let i of r)if(!e.has(i))return!1;return!0}function vi(r,t){return r.length===0?{emitImmediately:t?.emitImmediately,equalityFn:t?.equalityFn,mode:"scoped",paths:["*"]}:{emitImmediately:t?.emitImmediately,equalityFn:t?.equalityFn,mode:"scoped",paths:r}}function We(r){let{getState:t,subscribeSelector:e,selector:i,listener:s,options:o}=r,n=null,a=Ne(t(),i),c=!1,u=!1,l=d=>{let p=n;n=e(i,h=>{s(h);let y=Ne(t(),i);Bi(a,y)||(a=y,!(u||c)&&(u=!0,queueMicrotask(()=>{u=!1,!c&&(n?.(),l(a))})))},vi(d,o)),p?.()};return l(a),()=>{c=!0,n?.(),n=null}}function Ke(r){let{getState:t,subscriptions:e,selector:i,listener:s,options:o,trackedSubscriptionsEnabled:n}=r,a=o?.equalityFn??F;if(o?.mode==="tracked"){if(!n)throw new Error('BitForm: subscribeSelector com mode="tracked" est\xE1 desabilitado por padr\xE3o. Ative config.trackedSubscriptions=true para habilitar o modo avan\xE7ado.');return We({getState:t,subscribeSelector:(c,u,l)=>e.subscribeSelector(c,u,l,a),selector:i,listener:s,options:o})}return e.subscribeSelector(i,s,o,a)}function $e(r){let{path:t,listener:e,options:i,subscribeSelector:s}=r,o=[...i?.paths??[],t];return s(n=>S(n.values,t),e,{...i,paths:o})}function Je(r){let{path:t,listener:e,getFieldState:i,subscribeSelector:s}=r;return s(()=>i(t),e,{paths:[t],equalityFn:Lt})}function Ye(r){let{listener:t,subscribeSelector:e}=r;return e(i=>({isValid:i.isValid,isDirty:i.isDirty,isSubmitting:i.isSubmitting}),t,{paths:["isValid","isDirty","isSubmitting"],equalityFn:(i,s)=>i.isValid===s.isValid&&i.isDirty===s.isDirty&&i.isSubmitting===s.isSubmitting})}function Ge(r){let{listener:t,subscribeSelector:e}=r;return e(i=>i.persist,t,{paths:["persist"],equalityFn:(i,s)=>i.isSaving===s.isSaving&&i.isRestoring===s.isRestoring&&i.error===s.error})}function Xe(r){let{readHistoryMeta:t,subscribeSelector:e,listener:i}=r;return e(()=>t(),i,{paths:[j()],equalityFn:(s,o)=>qt(s,o)})}function Qe(r){let{scopeName:t,getScopeFields:e,readScopeStatus:i,subscribeSelector:s,listener:o}=r,n=A(t),a=i(t),c=()=>{},u=()=>{c();let d=Ut(e(t));c=s(()=>i(t),p=>{Et(a,p)||(a=p,o(p))},{paths:[...d,n]})};u();let l=s(()=>e(t).length,()=>{u();let d=i(t);Et(a,d)||(a=d,o(d))},{paths:[n]});return()=>{c(),l()}}function Ze(r){let{runtime:t,config:e,fieldRegistry:i,dirtyManager:s,stateReader:o}=r,n={getState:()=>b(o.getState()),getFieldState:l=>b(o.getFieldState(l)),getIsValid:()=>o.getFlag("isValid"),getIsSubmitting:()=>o.getFlag("isSubmitting"),getIsDirty:()=>o.getFlag("isDirty"),isHidden:l=>t.capabilities.query.isHidden(l),isRequired:l=>t.capabilities.query.isRequired(l),isFieldDirty:l=>t.capabilities.query.isFieldDirty(l),isFieldValidating:l=>t.capabilities.query.isFieldValidating(l),getDirtyValues:()=>s.buildDirtyValues(o.getState().values),getPersistMetadata:()=>o.getPersistMetadata(),getHistoryMetadata:()=>_e({history:t.capabilities.history}),getScopeStatus:l=>t.capabilities.scope.getScopeStatus(l),getScopeErrors:l=>t.capabilities.scope.getScopeErrors(l),getCanUndo:()=>t.capabilities.history.canUndo,getCanRedo:()=>t.capabilities.history.canRedo,getScopeFields:l=>i.getScopeFields(l)},a={subscribe:l=>t.subscriptions.subscribe(l),subscribePersistMeta:l=>Ge({listener:l,subscribeSelector:(d,p,h)=>a.subscribeSelector(d,p,h)}),subscribeHistoryMeta:l=>Xe({readHistoryMeta:()=>n.getHistoryMetadata(),subscribeSelector:(d,p,h)=>a.subscribeSelector(d,p,h),listener:l}),subscribeScopeStatus:(l,d)=>Qe({scopeName:l,getScopeFields:p=>n.getScopeFields(p),readScopeStatus:p=>n.getScopeStatus(p),subscribeSelector:(p,h,y)=>a.subscribeSelector(p,h,y),listener:d}),subscribeSelector:(l,d,p)=>Ke({getState:()=>n.getState(),subscriptions:t.subscriptions,selector:l,listener:d,options:p,trackedSubscriptionsEnabled:!!e.trackedSubscriptions}),subscribePath:(l,d,p)=>$e({path:l,listener:d,options:p,subscribeSelector:(h,y,v)=>a.subscribeSelector(h,y,v)}),subscribeFieldState:(l,d)=>Je({path:l,listener:d,getFieldState:p=>n.getFieldState(p),subscribeSelector:(p,h,y)=>a.subscribeSelector(p,h,y)}),subscribeFormMeta:l=>Ye({listener:l,subscribeSelector:(d,p,h)=>a.subscribeSelector(d,p,h)})};return{read:n,observe:a,write:{registerField:(l,d)=>{te({path:l,config:d,state:t.getState(),fieldRegistry:i,subscriptions:t.subscriptions,stateReader:o,invalidateFieldIndexes:()=>{i.invalidateIndexes()}})},unregisterField:l=>{ee({path:l,state:t.getState(),hasStaticConfig:!!e.fields?.[l],fieldRegistry:i,subscriptions:t.subscriptions,validationCleanupField:d=>t.capabilities.validation.cleanupField(d),invalidateFieldIndexes:()=>{i.invalidateIndexes()},dispatch:d=>t.dispatch(d)})},unregisterPrefix:l=>{et({prefix:l,state:t.getState(),fieldRegistry:i,subscriptions:t.subscriptions,validationCleanupPrefix:d=>t.capabilities.validation.cleanupPrefix(d),invalidateFieldIndexes:()=>{i.invalidateIndexes()}})},setField:(l,d)=>{t.runBatch(()=>{t.capabilities.lifecycle.updateField(l,d,{origin:"setField"})})},blurField:l=>{t.capabilities.query.isTouched(l)||t.runBatch(()=>{t.dispatch(Vt([l]))}),t.capabilities.validation.trigger([l])},markFieldsTouched:l=>{l.length!==0&&t.dispatch(Vt(l))},setValues:(l,d)=>{t.capabilities.lifecycle.setValues(l,d)},setError:(l,d)=>{t.capabilities.error.setError(l,d)},setErrors:l=>{t.capabilities.error.setErrors(l)},setServerErrors:(l,d)=>{t.capabilities.error.setServerErrors(l,d)},reset:()=>{t.runBatch(()=>{t.capabilities.lifecycle.reset()})},transaction:l=>t.runBatch(l),submit:l=>t.capabilities.lifecycle.submit(l),pushItem:(l,d)=>t.capabilities.arrays.pushItem(l,d),prependItem:(l,d)=>t.capabilities.arrays.prependItem(l,d),insertItem:(l,d,p)=>t.capabilities.arrays.insertItem(l,d,p),removeItem:(l,d)=>t.capabilities.arrays.removeItem(l,d),swapItems:(l,d,p)=>t.capabilities.arrays.swapItems(l,d,p),moveItem:(l,d,p)=>t.capabilities.arrays.moveItem(l,d,p),replaceItems:(l,d)=>t.capabilities.arrays.replaceItems(l,d),clearItems:l=>t.capabilities.arrays.clearItems(l)},feature:{undo:()=>{qe({history:t.capabilities.history,applyHistoryState:l=>t.capabilities.lifecycle.applyHistoryState(l)})},redo:()=>{Le({history:t.capabilities.history,applyHistoryState:l=>t.capabilities.lifecycle.applyHistoryState(l)})},validate:l=>t.capabilities.validation.validate(l),hasValidationsInProgress:l=>t.capabilities.validation.hasValidationsInProgress(l),triggerValidation:(l,d)=>t.capabilities.validation.trigger(l,d),restorePersisted:()=>He({dispatch:l=>t.dispatch(l),effects:t.effects}),forceSave:()=>ze({dispatch:l=>t.dispatch(l),effects:t.effects}),clearPersisted:()=>Ue({dispatch:l=>t.dispatch(l),effects:t.effects}),getArrayItemIds:(l,d)=>t.capabilities.arrays.getItemIds(l,d),cleanup:()=>t.cleanup()}}}function ti(r){let t=()=>r.read.getState();return{read:{get storeId(){return r.identity.storeId},get config(){return r.identity.config},get isValid(){return r.read.getIsValid()},get isSubmitting(){return r.read.getIsSubmitting()},get isDirty(){return r.read.getIsDirty()},getState:t,getFieldConfig:n=>r.getFieldConfig(n),getFieldState:n=>r.read.getFieldState(n),isHidden:n=>r.read.isHidden(n),isRequired:n=>r.read.isRequired(n),isFieldDirty:n=>r.read.isFieldDirty(n),isFieldValidating:n=>r.read.isFieldValidating(n),getDirtyValues:()=>r.read.getDirtyValues(),getPersistMetadata:()=>r.read.getPersistMetadata(),getHistoryMetadata:()=>r.read.getHistoryMetadata(),getScopeStatus:n=>r.read.getScopeStatus(n),getScopeErrors:n=>r.read.getScopeErrors(n),getScopeFields:n=>r.read.getScopeFields(n)},observe:{getState:t,subscribe:n=>r.observe.subscribe(n),subscribePersistMeta:n=>r.observe.subscribePersistMeta(n),subscribeHistoryMeta:n=>r.observe.subscribeHistoryMeta(n),subscribeScopeStatus:(n,a)=>r.observe.subscribeScopeStatus(n,a),subscribeFormMeta:n=>r.observe.subscribeFormMeta(n),subscribeSelector:(n,a,c)=>r.observe.subscribeSelector(n,a,c),subscribePath:(n,a,c)=>r.observe.subscribePath(n,a,c),subscribeFieldState:(n,a)=>r.observe.subscribeFieldState(n,a)},write:{setField:(n,a)=>r.write.setField(n,a),blurField:n=>r.write.blurField(n),markFieldsTouched:n=>r.write.markFieldsTouched(n),setValues:(n,a)=>r.write.setValues(n,a),setError:(n,a)=>r.write.setError(n,a),setErrors:n=>r.write.setErrors(n),setServerErrors:(n,a)=>r.write.setServerErrors(n,a),reset:()=>r.write.reset(),transaction:n=>r.write.transaction(n),submit:n=>r.write.submit(n)},feature:{cleanup:()=>r.feature.cleanup(),validate:n=>r.feature.validate(n),triggerValidation:(n,a)=>r.feature.triggerValidation(n,a),restorePersisted:()=>r.feature.restorePersisted(),forceSave:()=>r.feature.forceSave(),clearPersisted:()=>r.feature.clearPersisted(),registerField:(n,a)=>r.write.registerField(n,a),unregisterField:n=>r.write.unregisterField(n),unregisterPrefix:n=>r.write.unregisterPrefix(n),pushItem:(n,a)=>r.write.pushItem(n,a),prependItem:(n,a)=>r.write.prependItem(n,a),insertItem:(n,a,c)=>r.write.insertItem(n,a,c),removeItem:(n,a)=>r.write.removeItem(n,a),moveItem:(n,a,c)=>r.write.moveItem(n,a,c),swapItems:(n,a,c)=>r.write.swapItems(n,a,c),replaceItems:(n,a)=>r.write.replaceItems(n,a),clearItems:n=>r.write.clearItems(n),getArrayItemIds:(n,a)=>r.feature.getArrayItemIds(n,a),get canUndo(){return r.read.getCanUndo()},get canRedo(){return r.read.getCanRedo()},hasValidationsInProgress:n=>r.feature.hasValidationsInProgress(n),resolveMask:n=>r.resolveMask(n),createArrayItemId:(n,a)=>r.createArrayItemId(n,a),undo:()=>r.feature.undo(),redo:()=>r.feature.redo()}}}var Tt=class{constructor(t){this.deps=t}fieldStateCache=new Map;getState(){return this.deps.getState()}getUserLayer(){let t=this.deps.getState();return{values:t.values,touched:t.touched}}getValidationLayer(){let t=this.deps.getState();return{errors:t.errors,isValidating:t.isValidating,isValid:t.isValid}}getDerivedLayer(){return{isDirty:this.deps.getState().isDirty}}getFeatureLayer(){let t=this.deps.getState();return{persist:t.persist,isSubmitting:t.isSubmitting}}getFlag(t){return this.deps.getState()[t]}getPersistMetadata(){return this.deps.getState().persist}getFieldState(t){let e=t,i=this.deps.getState(),s=this.fieldStateCache.get(e),o=S(i.values,e),n=i.errors[e],a=!!i.touched[e],c=this.deps.isHidden(e),u=this.deps.isRequired(e),l=this.deps.isFieldDirty(e),d=this.deps.isFieldValidating(e);if(s){let h=s.snapshot;if(h.value===o&&h.error===n&&h.touched===a&&h.isHidden===c&&h.isRequired===u&&h.isDirty===l&&h.isValidating===d)return h}let p=Nt({state:i,path:t,value:o,isHidden:c,isRequired:u,isDirty:l,isValidating:d});return this.fieldStateCache.set(e,{state:i,snapshot:p}),p}invalidatePath(t){this.fieldStateCache.delete(t)}};var Pt=class{[M]=!0;[k]=!0;storeId;_config;read;observe;write;feature;constructor(t={}){let e=je({rawConfig:t});this._config=e.config,this.storeId=e.storeId;let i=new Tt({getState:()=>e.runtime.getState(),isHidden:n=>e.runtime.capabilities.query.isHidden(n),isRequired:n=>e.runtime.capabilities.query.isRequired(n),isFieldDirty:n=>e.runtime.capabilities.query.isFieldDirty(n),isFieldValidating:n=>e.runtime.capabilities.query.isFieldValidating(n)}),s=Ze({runtime:e.runtime,config:this._config,fieldRegistry:e.fieldRegistry,dirtyManager:e.dirtyManager,stateReader:i}),o=ti({identity:{storeId:this.storeId,config:this._config},read:s.read,observe:s.observe,write:s.write,feature:s.feature,getFieldConfig:n=>e.fieldRegistry.getFieldConfig(n),resolveMask:n=>_t({path:n,getFieldConfig:a=>e.fieldRegistry.getFieldConfig(a),masks:e.maskManager.getAllMasks()}),createArrayItemId:(n,a)=>this._config.idFactory({scope:"array",path:n,index:a})});this.read=o.read,this.observe=o.observe,this.write=o.write,this.feature=o.feature,e.runtime.effects.attachStorePort({getState:()=>this.read.getState(),getHistoryMetadata:()=>this.read.getHistoryMetadata(),undo:()=>this.feature.undo(),redo:()=>this.feature.redo(),reset:()=>this.write.reset()})}};function ei(r={}){return new Pt(r)}function ii(r){if(!r||typeof r!="object")return!1;let t=r;return t[M]===!0&&!!t.read&&!!t.observe&&!!t.write&&!!t.feature}function Ti(r){if(ii(r))return r;throw new Error("BitForm: o store informado n\xE3o exp\xF5e a API necess\xE1ria para hooks/framework bindings.")}function Pi(r){return!r||typeof r!="object"?!1:r[k]===!0}function Ei(r){if(!ii(r))throw new Error("BitForm: o store informado n\xE3o possui branding de hooks (BIT_HOOKS_API_SYMBOL).");if(!Pi(r))throw new Error("BitForm: o store informado n\xE3o possui branding de framework (BIT_FRAMEWORK_STORE_SYMBOL).");return r}function xi(r){return Object.defineProperty(r,M,{value:!0,enumerable:!1,configurable:!1,writable:!1}),Object.defineProperty(r,k,{value:!0,enumerable:!1,configurable:!1,writable:!1}),r}function Ci(r={}){let t=ei(r),e={read:t.read,observe:t.observe,write:t.write,feature:t.feature};return xi(e)}function Fi(r){return r.read}function Vi(r){return r.observe}function wi(r){return r.write}function Ai(r){return r.feature}function Ii(r,t){let e={};for(let i of t)e[i]=r[i];return e}export{Ct as a,ui as b,Ti as c,Ei as d,Ci as e,Fi as f,Vi as g,wi as h,Ai as i,Ii as j};
|
|
2
|
+
//# sourceMappingURL=chunk-CGJRZJ62.js.map
|