@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.
Files changed (64) hide show
  1. package/README.md +17 -0
  2. package/dist/angular/index.cjs +1 -1
  3. package/dist/angular/index.js +1 -1
  4. package/dist/chunk-6NH6MUXA.js +2 -0
  5. package/dist/chunk-6NH6MUXA.js.map +1 -0
  6. package/dist/{chunk-ZKAFHJPU.cjs → chunk-C2GGB5NF.cjs} +2 -2
  7. package/dist/{chunk-ZKAFHJPU.cjs.map → chunk-C2GGB5NF.cjs.map} +1 -1
  8. package/dist/chunk-CGJRZJ62.js +2 -0
  9. package/dist/chunk-CGJRZJ62.js.map +1 -0
  10. package/dist/chunk-IDJIIPCS.js +2 -0
  11. package/dist/chunk-IDJIIPCS.js.map +1 -0
  12. package/dist/chunk-JPOZKCPR.cjs +2 -0
  13. package/dist/chunk-JPOZKCPR.cjs.map +1 -0
  14. package/dist/{chunk-2AFWJAQG.js → chunk-LZTWNUKZ.js} +2 -2
  15. package/dist/{chunk-IVPCXKYW.cjs → chunk-MZNHMPTF.cjs} +2 -2
  16. package/dist/{chunk-IVPCXKYW.cjs.map → chunk-MZNHMPTF.cjs.map} +1 -1
  17. package/dist/chunk-OR5AGYQT.cjs +2 -0
  18. package/dist/chunk-OR5AGYQT.cjs.map +1 -0
  19. package/dist/{chunk-NVFZ22A7.cjs → chunk-QZBJ4WRU.cjs} +2 -2
  20. package/dist/{chunk-NVFZ22A7.cjs.map → chunk-QZBJ4WRU.cjs.map} +1 -1
  21. package/dist/chunk-RGMUXQ2K.cjs +2 -0
  22. package/dist/chunk-RGMUXQ2K.cjs.map +1 -0
  23. package/dist/{chunk-OPC7HFNN.js → chunk-S3DJPXMV.js} +2 -2
  24. package/dist/{chunk-LX4GSDUV.js → chunk-ZWWXPYEL.js} +2 -2
  25. package/dist/core/bindings.cjs +1 -1
  26. package/dist/core/bindings.js +1 -1
  27. package/dist/core/store.cjs +1 -1
  28. package/dist/core/store.js +1 -1
  29. package/dist/core/utils.cjs +1 -1
  30. package/dist/core/utils.d.cts +1 -1
  31. package/dist/core/utils.d.ts +1 -1
  32. package/dist/core/utils.js +1 -1
  33. package/dist/core.cjs +1 -1
  34. package/dist/core.js +1 -1
  35. package/dist/devtools/bridge.cjs +1 -1
  36. package/dist/devtools/bridge.js +1 -1
  37. package/dist/devtools/index.cjs +2 -2
  38. package/dist/devtools/index.js +1 -1
  39. package/dist/index.cjs +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/react/index.cjs +1 -1
  42. package/dist/react/index.js +1 -1
  43. package/dist/react-native/index.cjs +1 -1
  44. package/dist/react-native/index.js +1 -1
  45. package/dist/utils.cjs +1 -1
  46. package/dist/utils.js +1 -1
  47. package/dist/vue/index.cjs +1 -1
  48. package/dist/vue/index.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-4RQFECC7.cjs +0 -2
  51. package/dist/chunk-4RQFECC7.cjs.map +0 -1
  52. package/dist/chunk-FLFIOW75.js +0 -2
  53. package/dist/chunk-FLFIOW75.js.map +0 -1
  54. package/dist/chunk-G2FQQDRK.js +0 -2
  55. package/dist/chunk-G2FQQDRK.js.map +0 -1
  56. package/dist/chunk-GPMAT4PT.cjs +0 -2
  57. package/dist/chunk-GPMAT4PT.cjs.map +0 -1
  58. package/dist/chunk-GQ2QJCBF.js +0 -2
  59. package/dist/chunk-GQ2QJCBF.js.map +0 -1
  60. package/dist/chunk-VBX5I5XG.cjs +0 -2
  61. package/dist/chunk-VBX5I5XG.cjs.map +0 -1
  62. /package/dist/{chunk-2AFWJAQG.js.map → chunk-LZTWNUKZ.js.map} +0 -0
  63. /package/dist/{chunk-OPC7HFNN.js.map → chunk-S3DJPXMV.js.map} +0 -0
  64. /package/dist/{chunk-LX4GSDUV.js.map → chunk-ZWWXPYEL.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{d as M}from"./chunk-CGJRZJ62.js";import{a as A,b as C,d as R,e as D,g as U,i as j,j as I,k as q}from"./chunk-LZTWNUKZ.js";import{b as F}from"./chunk-UIKO6GGW.js";import{a as k}from"./chunk-S3DJPXMV.js";import{c as y,f as w}from"./chunk-6NH6MUXA.js";import{createContext as G,useContext as H}from"react";import{jsx as J}from"react/jsx-runtime";var L=G(null),ft=({store:t,children:e})=>J(L.Provider,{value:M(t),children:e}),l=()=>{let t=H(L);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};import{useCallback as p,useSyncExternalStore as K,useMemo as W,useRef as Q,useState as O}from"react";function Pt(){let t=l(),[e,r]=O(null),[i,s]=O(null),o=Q(null),c=p(S=>C(t,S),[t]),m=p(()=>{let S=A(t);return o.current&&o.current.isValid===S.isValid&&o.current.isDirty===S.isDirty&&o.current.isSubmitting===S.isSubmitting?o.current:(o.current=S,S)},[t]),n=K(c,m,m),d=W(()=>j(t,{clearSubmissionState:()=>{r(null),s(null)},setSubmissionResult:S=>{s(S)},setSubmissionError:S=>{r(S)}}),[t]),{controller:a,actions:x}=d,v=p(a.submit,[a]),T=p(a.onSubmit,[a]),E=p(a.reset,[a]),u=p(a.getValues,[a]),b=p(a.getErrors,[a]),B=p(a.getTouched,[a]),g=p(a.getDirtyValues,[a]);return{meta:W(()=>({...n,submitError:e,lastResponse:i}),[n,e,i]),getValues:u,getErrors:b,getTouched:B,getDirtyValues:g,submit:v,onSubmit:T,reset:E,...x}}import{useCallback as _,useEffect as X,useMemo as $,useRef as Y,useSyncExternalStore as Z}from"react";function Rt(t){let e=l(),r=$(()=>U(e,t),[e,t]),i=Y(null),s=_(()=>{let n=r.readItems();return i.current&&y(i.current,n)?i.current:(i.current=n,n)},[r]),o=_(n=>e.observe.subscribePath(t,()=>n()),[e,t]),c=Z(o,s,s),m=$(()=>r.getFields(c),[r,c]);return X(()=>()=>{q(e,`${t}.`)},[e,t]),{fields:m,length:c.length,append:r.append,prepend:r.prepend,insert:r.insert,remove:r.remove,move:r.move,swap:r.swap,replace:r.replace,clear:r.clear}}import{useCallback as P,useRef as N,useSyncExternalStore as tt}from"react";function At(t){let e=l(),r=N(null),i=P(()=>{let n=e.read.getScopeStatus(t);return r.current&&F(r.current,n)?r.current:(r.current=n,n)},[e,t]),s=P(n=>e.observe.subscribeScopeStatus(t,()=>n()),[e,t]),o=tt(s,i,i),c=P(async()=>{let n=await e.feature.validate({scope:t}),d=e.read.getScopeErrors(t);return{valid:n,errors:d}},[e,t]),m=P(()=>e.read.getScopeErrors(t),[e,t]);return{scopeName:t,status:o,errors:o.errors,validate:c,getErrors:m,isValid:!o.hasErrors,isDirty:o.isDirty}}import{useCallback as f,useRef as et,useState as rt,useSyncExternalStore as st}from"react";function It(t){let e=l(),[r,i]=rt(0),s=t[r]??"",o=et(null),c=f(()=>{let u=e.read.getScopeStatus(s);return o.current&&F(o.current,u)?o.current:(o.current=u,u)},[e,s]),m=st(f(u=>e.observe.subscribeScopeStatus(s,()=>u()),[e,s]),c,c),n=f(async()=>{let u=await e.feature.validate({scope:s}),b=e.read.getScopeErrors(s);return{valid:u,errors:b}},[e,s]),d=f(()=>e.read.getScopeErrors(s),[e,s]),a=f(async()=>{let u=e.read.getScopeFields(s);if(e.feature.hasValidationsInProgress(u))return!1;let b=await e.feature.validate({scope:s});if(b)i(B=>Math.min(B+1,t.length-1));else{let B=e.read.getScopeErrors(s),g=Object.keys(B);g.length>0&&e.write.markFieldsTouched(g)}return b},[e,s,t.length]),x=f(()=>{i(u=>Math.max(u-1,0))},[]),v=f(u=>{i(Math.max(0,Math.min(u-1,t.length-1)))},[t.length]),T=r===0,E=r>=t.length-1;return{step:r+1,stepIndex:r,scope:s,next:a,prev:x,goTo:v,isFirst:T,isLast:E,status:m,errors:m.errors,isValid:!m.hasErrors,isDirty:m.isDirty,validate:n,getErrors:d}}import{useCallback as z,useSyncExternalStore as ot,useRef as nt}from"react";function zt(t){let e=l(),r=nt(null),i=z(()=>{let o=w(e.read.getState().values,t);return r.current!==null&&y(r.current,o)?r.current:(r.current=o,o)},[e,t]),s=z(o=>e.observe.subscribePath(t,()=>o()),[e,t]);return ot(s,i,i)}import{useCallback as V,useMemo as it,useSyncExternalStore as at}from"react";function Qt(){let t=l(),e=at(c=>D(t,c),()=>R(t),()=>R(t)),r=V(async()=>t.feature.restorePersisted(),[t]),i=V(async()=>{await t.feature.forceSave()},[t]),s=V(async()=>{await t.feature.clearPersisted()},[t]),o=it(()=>({isSaving:e.isSaving,isRestoring:e.isRestoring,error:e.error}),[e]);return{restore:r,save:i,clear:s,meta:o}}import{useCallback as h,useEffect as ut,useRef as ct,useSyncExternalStore as lt}from"react";function se(t){let e=l(),r=ct(null);ut(()=>()=>I(e,t),[e,t]);let i=h(()=>{let n=e.read.getFieldState(t),d=k(n,r.current);return r.current=d,d},[e,t]),s=h(n=>e.observe.subscribeFieldState(t,()=>n()),[e,t]),o=lt(s,i,i),c=h(n=>e.write.setField(t,n),[e,t]),m=h(()=>e.write.blurField(t),[e,t]);return{fieldState:o,setValue:c,setBlur:m,store:e}}export{ft as a,l as b,Pt as c,se as d,Rt as e,At as f,It as g,zt as h,Qt as i};
2
+ //# sourceMappingURL=chunk-IDJIIPCS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts","../src/react/use-bit-scope.ts","../src/react/use-bit-steps.ts","../src/react/use-bit-watch.ts","../src/react/use-bit-persist.ts","../src/react/use-bit-field-base.ts"],"sourcesContent":["import React, { createContext, useContext } from \"react\";\nimport type { BitFrameworkStoreApi, BitStoreApi } from \"../core\";\nimport { createFrameworkStoreAdapter } from \"../core\";\n\nconst BitContext = createContext<BitFrameworkStoreApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitFrameworkStoreApi<any> | BitStoreApi<any>;\n children: React.ReactNode;\n}) => (\n <BitContext.Provider value={createFrameworkStoreAdapter(store)}>\n {children}\n </BitContext.Provider>\n);\n\nexport const useBitStore = <T extends object>() => {\n const store = useContext(BitContext);\n if (!store)\n throw new Error(\n \"BitForm hooks devem ser usados dentro de um BitFormProvider\",\n );\n return store as BitFrameworkStoreApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n createFrameworkFormBinding,\n readFormMetaSnapshot,\n subscribeFormMetaSnapshot,\n} from \"../core\";\nimport type { UseBitFormResult } from \"./types\";\n\nexport function useBitForm<T extends object>(): UseBitFormResult<T> {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<ReturnType<typeof readFormMetaSnapshot<T>> | null>(\n null,\n );\n\n const subscribeMeta = useCallback(\n (cb: () => void) => subscribeFormMetaSnapshot(store, cb),\n [store],\n );\n const getMetaSnapshot = useCallback(() => {\n const nextMeta = readFormMetaSnapshot(store);\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const metaState = useSyncExternalStore(\n subscribeMeta,\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const binding = useMemo(\n () =>\n createFrameworkFormBinding(store, {\n clearSubmissionState: () => {\n setSubmitError(null);\n setLastResponse(null);\n },\n setSubmissionResult: (result) => {\n setLastResponse(result);\n },\n setSubmissionError: (error) => {\n setSubmitError(error);\n },\n }),\n [store],\n );\n\n const { controller, actions } = binding;\n\n const submit = useCallback(controller.submit, [controller]);\n const onSubmit = useCallback(controller.onSubmit, [controller]);\n const reset = useCallback(controller.reset, [controller]);\n\n const getValues = useCallback(controller.getValues, [controller]);\n const getErrors = useCallback(controller.getErrors, [controller]);\n const getTouched = useCallback(controller.getTouched, [controller]);\n const getDirtyValues = useCallback(controller.getDirtyValues, [controller]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n ...actions,\n };\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport {\n BitArrayPath,\n cleanupRegisteredPrefix,\n createArrayBinding,\n valueEqual,\n} from \"../core\";\nimport { useBitStore } from \"./context\";\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n const controller = useMemo(\n () => createArrayBinding<TForm, P>(store, path),\n [store, path],\n );\n type ArraySnapshot = ReturnType<typeof controller.readItems>;\n const lastSnapshotRef = useRef<ArraySnapshot | null>(null);\n\n const getSnapshot = useCallback(() => {\n const next = controller.readItems();\n\n if (lastSnapshotRef.current && valueEqual(lastSnapshotRef.current, next)) {\n return lastSnapshotRef.current;\n }\n\n lastSnapshotRef.current = next;\n return next;\n }, [controller]);\n\n const subscribeArray = useCallback(\n (cb: () => void) => store.observe.subscribePath(path, () => cb()),\n [store, path],\n );\n\n const data = useSyncExternalStore(subscribeArray, getSnapshot, getSnapshot);\n\n const fields = useMemo(() => controller.getFields(data), [controller, data]);\n\n useEffect(() => {\n return () => {\n cleanupRegisteredPrefix(store, `${path as string}.`);\n };\n }, [store, path]);\n\n return {\n fields,\n length: data.length,\n append: controller.append,\n prepend: controller.prepend,\n insert: controller.insert,\n remove: controller.remove,\n move: controller.move,\n swap: controller.swap,\n replace: controller.replace,\n clear: controller.clear,\n };\n}\n","import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport type { ScopeStatus, ValidateScopeResult } from \"../core\";\nimport { isScopeStatusEqual } from \"../core\";\nimport { useBitStore } from \"./context\";\n\nexport type { ScopeStatus, ValidateScopeResult };\n\nexport function useBitScope(scopeName: string) {\n const store = useBitStore();\n\n const lastStatus = useRef<ScopeStatus | null>(null);\n\n const getStatusSnapshot = useCallback(() => {\n const nextStatus = store.read.getScopeStatus(scopeName);\n\n if (\n lastStatus.current &&\n isScopeStatusEqual(lastStatus.current, nextStatus)\n ) {\n return lastStatus.current;\n }\n\n lastStatus.current = nextStatus;\n return nextStatus;\n }, [store, scopeName]);\n\n // Assina apenas os slices de estado relevantes para o escopo (errors e\n // isDirty), evitando execuções desnecessárias do getStatusSnapshot em\n // mudanças não relacionadas (isSubmitting, isValidating de outros campos…)\n const subscribe = useCallback(\n (cb: () => void) =>\n store.observe.subscribeScopeStatus(scopeName, () => cb()),\n [store, scopeName],\n );\n\n const status = useSyncExternalStore(\n subscribe,\n getStatusSnapshot,\n getStatusSnapshot,\n );\n\n const validate = useCallback(async (): Promise<ValidateScopeResult> => {\n const valid = await store.feature.validate({ scope: scopeName });\n const errors = store.read.getScopeErrors(scopeName);\n return { valid, errors };\n }, [store, scopeName]);\n\n const getErrors = useCallback(() => {\n return store.read.getScopeErrors(scopeName);\n }, [store, scopeName]);\n\n return {\n scopeName,\n status,\n errors: status.errors,\n validate,\n getErrors,\n isValid: !status.hasErrors,\n isDirty: status.isDirty,\n };\n}\n","import { useCallback, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { ScopeStatus, ValidateScopeResult } from \"../core\";\nimport { isScopeStatusEqual } from \"../core\";\nimport { useBitStore } from \"./context\";\nimport type { UseBitStepsResult } from \"./types\";\n\nexport function useBitSteps(scopeNames: string[]): UseBitStepsResult {\n const store = useBitStore();\n const [stepIndex, setStepIndex] = useState(0);\n\n const scope = scopeNames[stepIndex] ?? \"\";\n const lastStatus = useRef<ScopeStatus | null>(null);\n\n const getStatusSnapshot = useCallback(() => {\n const nextStatus = store.read.getScopeStatus(scope);\n\n if (\n lastStatus.current &&\n isScopeStatusEqual(lastStatus.current, nextStatus)\n ) {\n return lastStatus.current;\n }\n\n lastStatus.current = nextStatus;\n return nextStatus;\n }, [store, scope]);\n\n const status = useSyncExternalStore(\n useCallback(\n (cb: () => void) => store.observe.subscribeScopeStatus(scope, () => cb()),\n [store, scope],\n ),\n getStatusSnapshot,\n getStatusSnapshot,\n );\n\n const validate = useCallback(async (): Promise<ValidateScopeResult> => {\n const valid = await store.feature.validate({ scope });\n const errors = store.read.getScopeErrors(scope);\n return { valid, errors };\n }, [store, scope]);\n\n const getErrors = useCallback(() => {\n return store.read.getScopeErrors(scope);\n }, [store, scope]);\n\n const next = useCallback(async (): Promise<boolean> => {\n const scopeFields = store.read.getScopeFields(scope);\n\n if (store.feature.hasValidationsInProgress(scopeFields)) {\n return false;\n }\n\n const valid = await store.feature.validate({ scope });\n if (valid) {\n setStepIndex((s) => Math.min(s + 1, scopeNames.length - 1));\n } else {\n const errors = store.read.getScopeErrors(scope);\n const pathsWithErrors = Object.keys(errors);\n if (pathsWithErrors.length > 0) {\n store.write.markFieldsTouched(pathsWithErrors);\n }\n }\n return valid;\n }, [store, scope, scopeNames.length]);\n\n const prev = useCallback(() => {\n setStepIndex((s) => Math.max(s - 1, 0));\n }, []);\n\n const goTo = useCallback(\n (targetStep: number) => {\n setStepIndex(\n Math.max(0, Math.min(targetStep - 1, scopeNames.length - 1)),\n );\n },\n [scopeNames.length],\n );\n\n const isFirst = stepIndex === 0;\n const isLast = stepIndex >= scopeNames.length - 1;\n\n return {\n step: stepIndex + 1,\n stepIndex,\n scope,\n next,\n prev,\n goTo,\n isFirst,\n isLast,\n status,\n errors: status.errors,\n isValid: !status.hasErrors,\n isDirty: status.isDirty,\n validate,\n getErrors,\n };\n}\n","import { useCallback, useSyncExternalStore, useRef } from \"react\";\nimport { useBitStore } from \"./context\";\nimport { getDeepValue, valueEqual, BitPath, BitPathValue } from \"../core\";\n\nexport function useBitWatch<\n TForm extends object = any,\n P extends BitPath<TForm> = BitPath<TForm>,\n>(path: P): BitPathValue<TForm, P> {\n const store = useBitStore<TForm>();\n const lastValue = useRef<BitPathValue<TForm, P> | null>(null);\n\n const getSnapshot = useCallback(() => {\n const value = getDeepValue(\n store.read.getState().values,\n path as string,\n ) as BitPathValue<TForm, P>;\n\n if (lastValue.current !== null && valueEqual(lastValue.current, value)) {\n return lastValue.current;\n }\n\n lastValue.current = value;\n return value;\n }, [store, path]);\n\n // Assina apenas o path monitorado → evita executar getSnapshot em toda\n // mudança de estado do store (blur, validation, outros campos, etc.)\n const subscribe = useCallback(\n (cb: () => void) => store.observe.subscribePath(path, () => cb()),\n [store, path],\n );\n\n return useSyncExternalStore(\n subscribe,\n getSnapshot,\n getSnapshot,\n ) as BitPathValue<TForm, P>;\n}\n","import { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { useBitStore } from \"./context\";\nimport { readPersistMetaSnapshot, subscribePersistMetaSnapshot } from \"../core\";\nimport type { UseBitPersistResult } from \"./types\";\n\nexport function useBitPersist(): UseBitPersistResult {\n const store = useBitStore<any>();\n\n const persistMeta = useSyncExternalStore(\n (cb) => subscribePersistMetaSnapshot(store, cb),\n () => readPersistMetaSnapshot(store),\n () => readPersistMetaSnapshot(store),\n );\n\n const restore = useCallback(async () => {\n return store.feature.restorePersisted();\n }, [store]);\n\n const save = useCallback(async () => {\n await store.feature.forceSave();\n }, [store]);\n\n const clear = useCallback(async () => {\n await store.feature.clearPersisted();\n }, [store]);\n\n const meta = useMemo(\n () => ({\n isSaving: persistMeta.isSaving,\n isRestoring: persistMeta.isRestoring,\n error: persistMeta.error,\n }),\n [persistMeta],\n );\n\n return {\n restore,\n save,\n clear,\n meta,\n };\n}\n","import { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\nimport {\n BitFieldSnapshot,\n BitPath,\n BitPathValue,\n cleanupRegisteredField,\n createFieldStateSnapshot,\n} from \"../core\";\nimport { useBitStore } from \"./context\";\n\nexport function useBitFieldBase<\n _TValue = any,\n TForm extends object = any,\n P extends BitPath<TForm> = BitPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n const lastSnapshot = useRef<BitFieldSnapshot<BitPathValue<TForm, P>> | null>(\n null,\n );\n\n useEffect(() => {\n return () => cleanupRegisteredField(store, path as string);\n }, [store, path]);\n\n const getSnapshot = useCallback(() => {\n const nextState = store.read.getFieldState(path);\n const snapshot = createFieldStateSnapshot(nextState, lastSnapshot.current);\n lastSnapshot.current = snapshot;\n return snapshot;\n }, [store, path]);\n\n const subscribe = useCallback(\n (cb: () => void) => store.observe.subscribeFieldState(path, () => cb()),\n [store, path],\n );\n\n const fieldState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const setValue = useCallback(\n (val: BitPathValue<TForm, P>) => store.write.setField(path, val),\n [store, path],\n );\n\n const setBlur = useCallback(() => store.write.blurField(path), [store, path]);\n\n return { fieldState, setValue, setBlur, store };\n}\n"],"mappings":"gQAAA,OAAgB,iBAAAA,EAAe,cAAAC,MAAkB,QAa/C,cAAAC,MAAA,oBATF,IAAMC,EAAaC,EAAgD,IAAI,EAE1DC,GAAkB,CAAC,CAC9B,MAAAC,EACA,SAAAC,CACF,IAIEL,EAACC,EAAW,SAAX,CAAoB,MAAOK,EAA4BF,CAAK,EAC1D,SAAAC,EACH,EAGWE,EAAc,IAAwB,CACjD,IAAMH,EAAQI,EAAWP,CAAU,EACnC,GAAI,CAACG,EACH,MAAM,IAAI,MACR,6DACF,EACF,OAAOA,CACT,ECzBA,OACE,eAAAK,EACA,wBAAAC,EACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QASA,SAASC,IAAoD,CAClE,IAAMC,EAAQC,EAAe,EAEvB,CAACC,EAAaC,CAAc,EAAIC,EAAuB,IAAI,EAC3D,CAACC,EAAcC,CAAe,EAAIF,EAAkB,IAAI,EACxDG,EAAWC,EACf,IACF,EAEMC,EAAgBC,EACnBC,GAAmBC,EAA0BZ,EAAOW,CAAE,EACvD,CAACX,CAAK,CACR,EACMa,EAAkBH,EAAY,IAAM,CACxC,IAAMI,EAAWC,EAAq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C,GAAQ,wBAAAC,OAA4B,QAU9D,SAASC,GAIdC,EAAS,CACT,IAAMC,EAAQC,EAAmB,EAC3BC,EAAeC,GACnB,IACF,EAEAC,GAAU,IACD,IAAMC,EAAuBL,EAAOD,CAAc,EACxD,CAACC,EAAOD,CAAI,CAAC,EAEhB,IAAMO,EAAcC,EAAY,IAAM,CACpC,IAAMC,EAAYR,EAAM,KAAK,cAAcD,CAAI,EACzCU,EAAWC,EAAyBF,EAAWN,EAAa,OAAO,EACzE,OAAAA,EAAa,QAAUO,EAChBA,CACT,EAAG,CAACT,EAAOD,CAAI,CAAC,EAEVY,EAAYJ,EACfK,GAAmBZ,EAAM,QAAQ,oBAAoBD,EAAM,IAAMa,EAAG,CAAC,EACtE,CAACZ,EAAOD,CAAI,CACd,EAEMc,EAAaC,GAAqBH,EAAWL,EAAaA,CAAW,EAErES,EAAWR,EACdS,GAAgChB,EAAM,MAAM,SAASD,EAAMiB,CAAG,EAC/D,CAAChB,EAAOD,CAAI,CACd,EAEMkB,EAAUV,EAAY,IAAMP,EAAM,MAAM,UAAUD,CAAI,EAAG,CAACC,EAAOD,CAAI,CAAC,EAE5E,MAAO,CAAE,WAAAc,EAAY,SAAAE,EAAU,QAAAE,EAAS,MAAAjB,CAAM,CAChD","names":["createContext","useContext","jsx","BitContext","createContext","BitFormProvider","store","children","createFrameworkStoreAdapter","useBitStore","useContext","useCallback","useSyncExternalStore","useMemo","useRef","useState","useBitForm","store","useBitStore","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","subscribeMeta","useCallback","cb","subscribeFormMetaSnapshot","getMetaSnapshot","nextMeta","readFormMetaSnapshot","metaState","useSyncExternalStore","binding","useMemo","createFrameworkFormBinding","result","error","controller","actions","submit","onSubmit","reset","getValues","getErrors","getTouched","getDirtyValues","useCallback","useEffect","useMemo","useRef","useSyncExternalStore","useBitArray","path","store","useBitStore","controller","useMemo","createArrayBinding","lastSnapshotRef","useRef","getSnapshot","useCallback","next","valueEqual","subscribeArray","cb","data","useSyncExternalStore","fields","useEffect","cleanupRegisteredPrefix","useCallback","useRef","useSyncExternalStore","useBitScope","scopeName","store","useBitStore","lastStatus","useRef","getStatusSnapshot","useCallback","nextStatus","isScopeStatusEqual","subscribe","cb","status","useSyncExternalStore","validate","valid","errors","getErrors","useCallback","useRef","useState","useSyncExternalStore","useBitSteps","scopeNames","store","useBitStore","stepIndex","setStepIndex","useState","scope","lastStatus","useRef","getStatusSnapshot","useCallback","nextStatus","isScopeStatusEqual","status","useSyncExternalStore","cb","validate","valid","errors","getErrors","next","scopeFields","s","pathsWithErrors","prev","goTo","targetStep","isFirst","isLast","useCallback","useSyncExternalStore","useRef","useBitWatch","path","store","useBitStore","lastValue","useRef","getSnapshot","useCallback","value","getDeepValue","valueEqual","subscribe","cb","useSyncExternalStore","useCallback","useMemo","useSyncExternalStore","useBitPersist","store","useBitStore","persistMeta","useSyncExternalStore","cb","subscribePersistMetaSnapshot","readPersistMetaSnapshot","restore","useCallback","save","clear","meta","useMemo","useCallback","useEffect","useRef","useSyncExternalStore","useBitFieldBase","path","store","useBitStore","lastSnapshot","useRef","useEffect","cleanupRegisteredField","getSnapshot","useCallback","nextState","snapshot","createFieldStateSnapshot","subscribe","cb","fieldState","useSyncExternalStore","setValue","val","setBlur"]}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkOR5AGYQTcjs = require('./chunk-OR5AGYQT.cjs');var _chunkQZBJ4WRUcjs = require('./chunk-QZBJ4WRU.cjs');var _chunkRHMJPKNVcjs = require('./chunk-RHMJPKNV.cjs');var _chunkC2GGB5NFcjs = require('./chunk-C2GGB5NF.cjs');var _chunkRGMUXQ2Kcjs = require('./chunk-RGMUXQ2K.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var L=_react.createContext.call(void 0, null),ft= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, L.Provider,{value:_chunkOR5AGYQTcjs.d.call(void 0, t),children:e}),l= exports.b =()=>{let t=_react.useContext.call(void 0, L);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function Pt(){let t=l(),[e,r]=_react.useState.call(void 0, null),[i,s]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, null),c=_react.useCallback.call(void 0, S=>_chunkQZBJ4WRUcjs.b.call(void 0, t,S),[t]),m=_react.useCallback.call(void 0, ()=>{let S=_chunkQZBJ4WRUcjs.a.call(void 0, t);return o.current&&o.current.isValid===S.isValid&&o.current.isDirty===S.isDirty&&o.current.isSubmitting===S.isSubmitting?o.current:(o.current=S,S)},[t]),n=_react.useSyncExternalStore.call(void 0, c,m,m),d=_react.useMemo.call(void 0, ()=>_chunkQZBJ4WRUcjs.i.call(void 0, t,{clearSubmissionState:()=>{r(null),s(null)},setSubmissionResult:S=>{s(S)},setSubmissionError:S=>{r(S)}}),[t]),{controller:a,actions:x}=d,v=_react.useCallback.call(void 0, a.submit,[a]),T=_react.useCallback.call(void 0, a.onSubmit,[a]),E=_react.useCallback.call(void 0, a.reset,[a]),u=_react.useCallback.call(void 0, a.getValues,[a]),b=_react.useCallback.call(void 0, a.getErrors,[a]),B=_react.useCallback.call(void 0, a.getTouched,[a]),g=_react.useCallback.call(void 0, a.getDirtyValues,[a]);return{meta:_react.useMemo.call(void 0, ()=>({...n,submitError:e,lastResponse:i}),[n,e,i]),getValues:u,getErrors:b,getTouched:B,getDirtyValues:g,submit:v,onSubmit:T,reset:E,...x}}function Rt(t){let e=l(),r=_react.useMemo.call(void 0, ()=>_chunkQZBJ4WRUcjs.g.call(void 0, e,t),[e,t]),i=_react.useRef.call(void 0, null),s=_react.useCallback.call(void 0, ()=>{let n=r.readItems();return i.current&&_chunkRGMUXQ2Kcjs.c.call(void 0, i.current,n)?i.current:(i.current=n,n)},[r]),o=_react.useCallback.call(void 0, n=>e.observe.subscribePath(t,()=>n()),[e,t]),c=_react.useSyncExternalStore.call(void 0, o,s,s),m=_react.useMemo.call(void 0, ()=>r.getFields(c),[r,c]);return _react.useEffect.call(void 0, ()=>()=>{_chunkQZBJ4WRUcjs.k.call(void 0, e,`${t}.`)},[e,t]),{fields:m,length:c.length,append:r.append,prepend:r.prepend,insert:r.insert,remove:r.remove,move:r.move,swap:r.swap,replace:r.replace,clear:r.clear}}function At(t){let e=l(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let n=e.read.getScopeStatus(t);return r.current&&_chunkRHMJPKNVcjs.b.call(void 0, r.current,n)?r.current:(r.current=n,n)},[e,t]),s=_react.useCallback.call(void 0, n=>e.observe.subscribeScopeStatus(t,()=>n()),[e,t]),o=_react.useSyncExternalStore.call(void 0, s,i,i),c=_react.useCallback.call(void 0, async()=>{let n=await e.feature.validate({scope:t}),d=e.read.getScopeErrors(t);return{valid:n,errors:d}},[e,t]),m=_react.useCallback.call(void 0, ()=>e.read.getScopeErrors(t),[e,t]);return{scopeName:t,status:o,errors:o.errors,validate:c,getErrors:m,isValid:!o.hasErrors,isDirty:o.isDirty}}function It(t){let e=l(),[r,i]=_react.useState.call(void 0, 0),s=_nullishCoalesce(t[r], () => ("")),o=_react.useRef.call(void 0, null),c=_react.useCallback.call(void 0, ()=>{let u=e.read.getScopeStatus(s);return o.current&&_chunkRHMJPKNVcjs.b.call(void 0, o.current,u)?o.current:(o.current=u,u)},[e,s]),m=_react.useSyncExternalStore.call(void 0, _react.useCallback.call(void 0, u=>e.observe.subscribeScopeStatus(s,()=>u()),[e,s]),c,c),n=_react.useCallback.call(void 0, async()=>{let u=await e.feature.validate({scope:s}),b=e.read.getScopeErrors(s);return{valid:u,errors:b}},[e,s]),d=_react.useCallback.call(void 0, ()=>e.read.getScopeErrors(s),[e,s]),a=_react.useCallback.call(void 0, async()=>{let u=e.read.getScopeFields(s);if(e.feature.hasValidationsInProgress(u))return!1;let b=await e.feature.validate({scope:s});if(b)i(B=>Math.min(B+1,t.length-1));else{let B=e.read.getScopeErrors(s),g=Object.keys(B);g.length>0&&e.write.markFieldsTouched(g)}return b},[e,s,t.length]),x=_react.useCallback.call(void 0, ()=>{i(u=>Math.max(u-1,0))},[]),v=_react.useCallback.call(void 0, u=>{i(Math.max(0,Math.min(u-1,t.length-1)))},[t.length]),T=r===0,E=r>=t.length-1;return{step:r+1,stepIndex:r,scope:s,next:a,prev:x,goTo:v,isFirst:T,isLast:E,status:m,errors:m.errors,isValid:!m.hasErrors,isDirty:m.isDirty,validate:n,getErrors:d}}function zt(t){let e=l(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let o=_chunkRGMUXQ2Kcjs.f.call(void 0, e.read.getState().values,t);return r.current!==null&&_chunkRGMUXQ2Kcjs.c.call(void 0, r.current,o)?r.current:(r.current=o,o)},[e,t]),s=_react.useCallback.call(void 0, o=>e.observe.subscribePath(t,()=>o()),[e,t]);return _react.useSyncExternalStore.call(void 0, s,i,i)}function Qt(){let t=l(),e=_react.useSyncExternalStore.call(void 0, c=>_chunkQZBJ4WRUcjs.e.call(void 0, t,c),()=>_chunkQZBJ4WRUcjs.d.call(void 0, t),()=>_chunkQZBJ4WRUcjs.d.call(void 0, t)),r=_react.useCallback.call(void 0, async()=>t.feature.restorePersisted(),[t]),i=_react.useCallback.call(void 0, async()=>{await t.feature.forceSave()},[t]),s=_react.useCallback.call(void 0, async()=>{await t.feature.clearPersisted()},[t]),o=_react.useMemo.call(void 0, ()=>({isSaving:e.isSaving,isRestoring:e.isRestoring,error:e.error}),[e]);return{restore:r,save:i,clear:s,meta:o}}function se(t){let e=l(),r=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>()=>_chunkQZBJ4WRUcjs.j.call(void 0, e,t),[e,t]);let i=_react.useCallback.call(void 0, ()=>{let n=e.read.getFieldState(t),d=_chunkC2GGB5NFcjs.a.call(void 0, n,r.current);return r.current=d,d},[e,t]),s=_react.useCallback.call(void 0, n=>e.observe.subscribeFieldState(t,()=>n()),[e,t]),o=_react.useSyncExternalStore.call(void 0, s,i,i),c=_react.useCallback.call(void 0, n=>e.write.setField(t,n),[e,t]),m=_react.useCallback.call(void 0, ()=>e.write.blurField(t),[e,t]);return{fieldState:o,setValue:c,setBlur:m,store:e}}exports.a = ft; exports.b = l; exports.c = Pt; exports.d = se; exports.e = Rt; exports.f = At; exports.g = It; exports.h = zt; exports.i = Qt;
2
+ //# sourceMappingURL=chunk-JPOZKCPR.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-JPOZKCPR.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","createFrameworkStoreAdapter","useBitStore","useContext","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","subscribeMeta","useCallback","cb","subscribeFormMetaSnapshot","getMetaSnapshot","nextMeta","readFormMetaSnapshot","metaState","useSyncExternalStore","binding","useMemo","createFrameworkFormBinding","result","error","controller","actions","submit","onSubmit","reset","getValues","getErrors","getTouched","getDirtyValues","useBitArray","path","createArrayBinding","lastSnapshotRef","getSnapshot","next","valueEqual","subscribeArray","data","fields","useEffect","cleanupRegisteredPrefix"],"mappings":"AAAA,qOAAwC,wDAA0F,wDAAyC,wDAAyC,wDAAgD,8BCAnN,+CAa/C,IATIA,CAAAA,CAAaC,kCAAAA,IAAoD,CAAA,CAE1DC,EAAAA,aAAkB,CAAC,CAC9B,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,EAIEC,6BAAAA,CAACL,CAAW,QAAA,CAAX,CAAoB,KAAA,CAAOM,iCAAAA,CAAiC,CAAA,CAC1D,QAAA,CAAAF,CAAAA,CACH,CAAA,CAGWG,CAAAA,aAAc,CAAA,CAAA,EAAwB,CACjD,IAAMJ,CAAAA,CAAQK,+BAAAA,CAAqB,CAAA,CACnC,EAAA,CAAI,CAACL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C,CAAAA,CAAQI,CAAAA,CAAmB,CAAA,CAC3BwB,CAAAA,CAAaJ,4BAAAA,CACjB,CAAA,EAAMe,iCAAAA,CAA6BvC,CAAOsC,CAAI,CAAA,CAC9C,CAACtC,CAAAA,CAAOsC,CAAI,CACd,CAAA,CAEME,CAAAA,CAAkB3B,2BAAAA,IAAiC,CAAA,CAEnD4B,CAAAA,CAAc1B,gCAAAA,CAAY,CAAA,EAAM,CACpC,IAAM2B,CAAAA,CAAOd,CAAAA,CAAW,SAAA,CAAU,CAAA,CAElC,OAAIY,CAAAA,CAAgB,OAAA,EAAWG,iCAAAA,CAAWH,CAAgB,OAAA,CAASE,CAAI,CAAA,CAC9DF,CAAAA,CAAgB,OAAA,CAAA,CAGzBA,CAAAA,CAAgB,OAAA,CAAUE,CAAAA,CACnBA,CAAAA,CACT,CAAA,CAAG,CAACd,CAAU,CAAC,CAAA,CAETgB,CAAAA,CAAiB7B,gCAAAA,CACpBC,EAAmBhB,CAAAA,CAAM,OAAA,CAAQ,aAAA,CAAcsC,CAAAA,CAAM,CAAA,CAAA,EAAMtB,CAAAA,CAAG,CAAC,CAAA,CAChE,CAAChB,CAAAA,CAAOsC,CAAI,CACd,CAAA,CAEMO,CAAAA,CAAOvB,yCAAAA,CAAqBsB,CAAgBH,CAAAA,CAAaA,CAAW,CAAA,CAEpEK,CAAAA,CAAStB,4BAAAA,CAAQ,CAAA,EAAMI,CAAAA,CAAW,SAAA,CAAUiB,CAAI,CAAA,CAAG,CAACjB,CAAAA,CAAYiB,CAAI,CAAC,CAAA,CAE3E,OAAAE,8BAAAA,CAAU,CAAA,EACD,CAAA,CAAA,EAAM,CACXC,iCAAAA,CAAwBhD,CAAO,CAAA,EAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-JPOZKCPR.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport type { BitFrameworkStoreApi, BitStoreApi } from \"../core\";\nimport { createFrameworkStoreAdapter } from \"../core\";\n\nconst BitContext = createContext<BitFrameworkStoreApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitFrameworkStoreApi<any> | BitStoreApi<any>;\n children: React.ReactNode;\n}) => (\n <BitContext.Provider value={createFrameworkStoreAdapter(store)}>\n {children}\n </BitContext.Provider>\n);\n\nexport const useBitStore = <T extends object>() => {\n const store = useContext(BitContext);\n if (!store)\n throw new Error(\n \"BitForm hooks devem ser usados dentro de um BitFormProvider\",\n );\n return store as BitFrameworkStoreApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n createFrameworkFormBinding,\n readFormMetaSnapshot,\n subscribeFormMetaSnapshot,\n} from \"../core\";\nimport type { UseBitFormResult } from \"./types\";\n\nexport function useBitForm<T extends object>(): UseBitFormResult<T> {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<ReturnType<typeof readFormMetaSnapshot<T>> | null>(\n null,\n );\n\n const subscribeMeta = useCallback(\n (cb: () => void) => subscribeFormMetaSnapshot(store, cb),\n [store],\n );\n const getMetaSnapshot = useCallback(() => {\n const nextMeta = readFormMetaSnapshot(store);\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const metaState = useSyncExternalStore(\n subscribeMeta,\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const binding = useMemo(\n () =>\n createFrameworkFormBinding(store, {\n clearSubmissionState: () => {\n setSubmitError(null);\n setLastResponse(null);\n },\n setSubmissionResult: (result) => {\n setLastResponse(result);\n },\n setSubmissionError: (error) => {\n setSubmitError(error);\n },\n }),\n [store],\n );\n\n const { controller, actions } = binding;\n\n const submit = useCallback(controller.submit, [controller]);\n const onSubmit = useCallback(controller.onSubmit, [controller]);\n const reset = useCallback(controller.reset, [controller]);\n\n const getValues = useCallback(controller.getValues, [controller]);\n const getErrors = useCallback(controller.getErrors, [controller]);\n const getTouched = useCallback(controller.getTouched, [controller]);\n const getDirtyValues = useCallback(controller.getDirtyValues, [controller]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n ...actions,\n };\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport {\n BitArrayPath,\n cleanupRegisteredPrefix,\n createArrayBinding,\n valueEqual,\n} from \"../core\";\nimport { useBitStore } from \"./context\";\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n const controller = useMemo(\n () => createArrayBinding<TForm, P>(store, path),\n [store, path],\n );\n type ArraySnapshot = ReturnType<typeof controller.readItems>;\n const lastSnapshotRef = useRef<ArraySnapshot | null>(null);\n\n const getSnapshot = useCallback(() => {\n const next = controller.readItems();\n\n if (lastSnapshotRef.current && valueEqual(lastSnapshotRef.current, next)) {\n return lastSnapshotRef.current;\n }\n\n lastSnapshotRef.current = next;\n return next;\n }, [controller]);\n\n const subscribeArray = useCallback(\n (cb: () => void) => store.observe.subscribePath(path, () => cb()),\n [store, path],\n );\n\n const data = useSyncExternalStore(subscribeArray, getSnapshot, getSnapshot);\n\n const fields = useMemo(() => controller.getFields(data), [controller, data]);\n\n useEffect(() => {\n return () => {\n cleanupRegisteredPrefix(store, `${path as string}.`);\n };\n }, [store, path]);\n\n return {\n fields,\n length: data.length,\n append: controller.append,\n prepend: controller.prepend,\n insert: controller.insert,\n remove: controller.remove,\n move: controller.move,\n swap: controller.swap,\n replace: controller.replace,\n clear: controller.clear,\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- import{f as c}from"./chunk-FLFIOW75.js";import{b as u,c as d}from"./chunk-3NUJVIAM.js";function m(e){let t=e.read.getState();return{isValid:t.isValid,isDirty:t.isDirty,isSubmitting:t.isSubmitting}}function f(e,t){return e.observe.subscribeFormMeta(()=>t())}function g(e,t){return t(m(e)),f(e,()=>{t(m(e))})}function B(e){return e.read.getPersistMetadata()}function v(e,t){return e.observe.subscribePersistMeta(()=>t())}function x(e,t){return t(B(e)),e.observe.subscribePersistMeta(o=>{t(o)})}function M(e,t){let o=!1,a=r=>Array.isArray(r)?r:r==null?[]:((!(typeof process<"u")||process.env.NODE_ENV!=="production")&&!o&&(o=!0,console.warn(`[bit-form] createArrayBinding expected an array at path "${String(t)}" but received ${typeof r}. Returning an empty array.`)),[]),p=r=>e.feature.getArrayItemIds(t,r);return{readItems(){let r=c(e.read.getState().values,t);return a(r)},getFields(r){let i=p(r.length);return r.map((s,n)=>({key:i[n]||`temp-${n}`,value:s,index:n}))},append(r){e.feature.pushItem(t,r)},prepend(r){e.feature.prependItem(t,r)},insert(r,i){e.feature.insertItem(t,r,i)},remove(r){e.feature.removeItem(t,r)},move(r,i){e.feature.moveItem(t,r,i)},swap(r,i){e.feature.swapItems(t,r,i)},replace(r){e.feature.replaceItems(t,r)},clear(){e.feature.clearItems(t)}}}function b(e,t,o){return{setValue:i=>{let s=o();e.setField(t,d(i,s))},setBlur:()=>e.blurField(t),displayValue:i=>u(i,o())}}function w(e,t){return{fieldController:b({setField(a,p){e.write.setField(a,p)},blurField(a){e.write.blurField(a)}},t,()=>e.feature.resolveMask(t))}}function F(e,t){e?.preventDefault?.(),t?.stopPropagation&&e?.stopPropagation?.()}function y(e,t,o){return{submit:i=>async s=>{F(s,o),await e.submit(i)},onSubmit:i=>async s=>{F(s,o),t.setSubmissionError(null);let n,l=await e.submit(async(P,S)=>{n=await i(P,S)});if(l.status==="submitted"){t.setSubmissionResult(n),t.setSubmissionError(null);return}l.status==="failed"&&t.setSubmissionError(l.error instanceof Error?l.error:new Error(String(l.error)))},reset:()=>{e.reset(),t.clearSubmissionState()},getValues:()=>e.getState().values,getErrors:()=>e.getState().errors,getTouched:()=>e.getState().touched,getDirtyValues:()=>e.getDirtyValues()}}function T(e,t,o){let a={getState:e.read.getState,getDirtyValues:e.read.getDirtyValues,submit:e.write.submit,reset:e.write.reset,setServerErrors:e.write.setServerErrors};return{controller:y(a,t,o),actions:{setField:e.write.setField.bind(e.write),blurField:e.write.blurField.bind(e.write),setValues:e.write.setValues.bind(e.write),setError:e.write.setError.bind(e.write),setErrors:e.write.setErrors.bind(e.write),setServerErrors:e.write.setServerErrors.bind(e.write),validate:e.feature.validate.bind(e.feature),transaction:e.write.transaction.bind(e.write)}}}function A(e,t){e.feature?.unregisterField?.(t)}function k(e,t){e.feature?.unregisterPrefix?.(t)}export{m as a,f as b,g as c,B as d,v as e,x as f,M as g,w as h,T as i,A as j,k};
2
- //# sourceMappingURL=chunk-2AFWJAQG.js.map
1
+ import{f as c}from"./chunk-6NH6MUXA.js";import{b as u,c as d}from"./chunk-3NUJVIAM.js";function m(e){let t=e.read.getState();return{isValid:t.isValid,isDirty:t.isDirty,isSubmitting:t.isSubmitting}}function f(e,t){return e.observe.subscribeFormMeta(()=>t())}function g(e,t){return t(m(e)),f(e,()=>{t(m(e))})}function B(e){return e.read.getPersistMetadata()}function v(e,t){return e.observe.subscribePersistMeta(()=>t())}function x(e,t){return t(B(e)),e.observe.subscribePersistMeta(o=>{t(o)})}function M(e,t){let o=!1,a=r=>Array.isArray(r)?r:r==null?[]:((!(typeof process<"u")||process.env.NODE_ENV!=="production")&&!o&&(o=!0,console.warn(`[bit-form] createArrayBinding expected an array at path "${String(t)}" but received ${typeof r}. Returning an empty array.`)),[]),p=r=>e.feature.getArrayItemIds(t,r);return{readItems(){let r=c(e.read.getState().values,t);return a(r)},getFields(r){let i=p(r.length);return r.map((s,n)=>({key:i[n]||`temp-${n}`,value:s,index:n}))},append(r){e.feature.pushItem(t,r)},prepend(r){e.feature.prependItem(t,r)},insert(r,i){e.feature.insertItem(t,r,i)},remove(r){e.feature.removeItem(t,r)},move(r,i){e.feature.moveItem(t,r,i)},swap(r,i){e.feature.swapItems(t,r,i)},replace(r){e.feature.replaceItems(t,r)},clear(){e.feature.clearItems(t)}}}function b(e,t,o){return{setValue:i=>{let s=o();e.setField(t,d(i,s))},setBlur:()=>e.blurField(t),displayValue:i=>u(i,o())}}function w(e,t){return{fieldController:b({setField(a,p){e.write.setField(a,p)},blurField(a){e.write.blurField(a)}},t,()=>e.feature.resolveMask(t))}}function F(e,t){e?.preventDefault?.(),t?.stopPropagation&&e?.stopPropagation?.()}function y(e,t,o){return{submit:i=>async s=>{F(s,o),await e.submit(i)},onSubmit:i=>async s=>{F(s,o),t.setSubmissionError(null);let n,l=await e.submit(async(P,S)=>{n=await i(P,S)});if(l.status==="submitted"){t.setSubmissionResult(n),t.setSubmissionError(null);return}l.status==="failed"&&t.setSubmissionError(l.error instanceof Error?l.error:new Error(String(l.error)))},reset:()=>{e.reset(),t.clearSubmissionState()},getValues:()=>e.getState().values,getErrors:()=>e.getState().errors,getTouched:()=>e.getState().touched,getDirtyValues:()=>e.getDirtyValues()}}function T(e,t,o){let a={getState:e.read.getState,getDirtyValues:e.read.getDirtyValues,submit:e.write.submit,reset:e.write.reset,setServerErrors:e.write.setServerErrors};return{controller:y(a,t,o),actions:{setField:e.write.setField.bind(e.write),blurField:e.write.blurField.bind(e.write),setValues:e.write.setValues.bind(e.write),setError:e.write.setError.bind(e.write),setErrors:e.write.setErrors.bind(e.write),setServerErrors:e.write.setServerErrors.bind(e.write),validate:e.feature.validate.bind(e.feature),transaction:e.write.transaction.bind(e.write)}}}function A(e,t){e.feature?.unregisterField?.(t)}function k(e,t){e.feature?.unregisterPrefix?.(t)}export{m as a,f as b,g as c,B as d,v as e,x as f,M as g,w as h,T as i,A as j,k};
2
+ //# sourceMappingURL=chunk-LZTWNUKZ.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkQKGTVKBUcjs = require('./chunk-QKGTVKBU.cjs');var _chunk4RQFECC7cjs = require('./chunk-4RQFECC7.cjs');function R(e){return{values:e.values,errors:e.errors,touched:e.touched,isValid:e.isValid,isDirty:e.isDirty,isSubmitting:e.isSubmitting,isValidating:e.isValidating,persist:e.persist}}function k(e){let o=e.getHistoryMetadata();return{...R(e.getState()),_meta:{canUndo:o.canUndo,canRedo:o.canRedo,totalSteps:o.historySize,currentIndex:o.historyIndex}}}function b(e){let o={};for(let[t,i]of Object.entries(e))o[t]=k(i);return o}function w(e){if(!e||typeof e!="object")return!1;let o=e;return typeof o.getState=="function"&&typeof o.getHistoryMetadata=="function"}function I(e){if(!w(e))return!1;let o=e;return typeof o.undo=="function"&&typeof o.redo=="function"&&typeof o.reset=="function"}function B(e,o){let t=e[o];return I(t)?t:null}var S=null,O=50;function N(e,o=_chunk4RQFECC7cjs.a){S&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),S());let t=null,i=null,f,n=null,a=new Set,T=!1,u=r=>{_optionalChain([t, 'optionalAccess', _ => _.readyState])===WebSocket.OPEN&&t.send(JSON.stringify(r))},h=()=>{if(a.size===0)return;let r=b(Array.from(a).reduce((s,l)=>{let d=o.stores[l];return d&&(s[l]=d),s},{}));a.clear(),n=null,Object.keys(r).length>0&&u({type:"STATE_UPDATE",protocolVersion:1,payload:r})},D=()=>{n||(n=setTimeout(()=>{h()},O))},y=()=>{T=!1,t=new WebSocket(e),t.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket."),u({type:"HELLO",protocolVersion:1,payload:{role:"server",protocolVersion:1}});let r=b(o.stores);Object.keys(r).length>0&&u({type:"STATE_UPDATE",protocolVersion:1,payload:r}),i=o.subscribe((s,l)=>{a.add(s),D()}),f=setInterval(()=>{u({type:"PING",protocolVersion:1})},3e4)},t.onmessage=r=>{try{let s=JSON.parse(r.data);if(_chunkQKGTVKBUcjs.c.call(void 0, s)){let{storeId:l,action:d}=s.payload,p=B(o.stores,l);if(!p)return;switch(d){case"undo":p.undo();break;case"redo":p.redo();break;case"reset":p.reset();break}}}catch(s){console.warn("[bit-form] Erro ao processar comando do CLI:",s)}},t.onclose=()=>{i&&i(),clearInterval(f),n&&(clearTimeout(n),n=null),a.clear(),T?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(y,3e3))}};y();let m=()=>{T=!0,i&&i(),clearInterval(f),n&&(clearTimeout(n),n=null),a.clear(),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),S=null};return S=m,m}exports.a = b; exports.b = B; exports.c = N;
2
- //# sourceMappingURL=chunk-IVPCXKYW.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkQKGTVKBUcjs = require('./chunk-QKGTVKBU.cjs');var _chunkOR5AGYQTcjs = require('./chunk-OR5AGYQT.cjs');function R(e){return{values:e.values,errors:e.errors,touched:e.touched,isValid:e.isValid,isDirty:e.isDirty,isSubmitting:e.isSubmitting,isValidating:e.isValidating,persist:e.persist}}function k(e){let o=e.getHistoryMetadata();return{...R(e.getState()),_meta:{canUndo:o.canUndo,canRedo:o.canRedo,totalSteps:o.historySize,currentIndex:o.historyIndex}}}function b(e){let o={};for(let[t,i]of Object.entries(e))o[t]=k(i);return o}function w(e){if(!e||typeof e!="object")return!1;let o=e;return typeof o.getState=="function"&&typeof o.getHistoryMetadata=="function"}function I(e){if(!w(e))return!1;let o=e;return typeof o.undo=="function"&&typeof o.redo=="function"&&typeof o.reset=="function"}function B(e,o){let t=e[o];return I(t)?t:null}var S=null,O=50;function N(e,o=_chunkOR5AGYQTcjs.a){S&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),S());let t=null,i=null,f,n=null,a=new Set,T=!1,u=r=>{_optionalChain([t, 'optionalAccess', _ => _.readyState])===WebSocket.OPEN&&t.send(JSON.stringify(r))},h=()=>{if(a.size===0)return;let r=b(Array.from(a).reduce((s,l)=>{let d=o.stores[l];return d&&(s[l]=d),s},{}));a.clear(),n=null,Object.keys(r).length>0&&u({type:"STATE_UPDATE",protocolVersion:1,payload:r})},D=()=>{n||(n=setTimeout(()=>{h()},O))},y=()=>{T=!1,t=new WebSocket(e),t.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket."),u({type:"HELLO",protocolVersion:1,payload:{role:"server",protocolVersion:1}});let r=b(o.stores);Object.keys(r).length>0&&u({type:"STATE_UPDATE",protocolVersion:1,payload:r}),i=o.subscribe((s,l)=>{a.add(s),D()}),f=setInterval(()=>{u({type:"PING",protocolVersion:1})},3e4)},t.onmessage=r=>{try{let s=JSON.parse(r.data);if(_chunkQKGTVKBUcjs.c.call(void 0, s)){let{storeId:l,action:d}=s.payload,p=B(o.stores,l);if(!p)return;switch(d){case"undo":p.undo();break;case"redo":p.redo();break;case"reset":p.reset();break}}}catch(s){console.warn("[bit-form] Erro ao processar comando do CLI:",s)}},t.onclose=()=>{i&&i(),clearInterval(f),n&&(clearTimeout(n),n=null),a.clear(),T?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(y,3e3))}};y();let m=()=>{T=!0,i&&i(),clearInterval(f),n&&(clearTimeout(n),n=null),a.clear(),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),S=null};return S=m,m}exports.a = b; exports.b = B; exports.c = N;
2
+ //# sourceMappingURL=chunk-MZNHMPTF.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-IVPCXKYW.cjs","../src/devtools/store-snapshot.ts","../src/devtools/store-port.ts","../src/devtools/bridge.ts"],"names":["normalizeStoreState","state","createDevToolsStoreSnapshot","store","historyMeta","createDevToolsSnapshotMap","stores","snapshots","storeId","instance","isDevToolsReadableStore","value","candidate","isDevToolsActionableStore","getDevToolsActionableStore","activeBridgeCleanup","STATE_BATCH_INTERVAL_MS","setupRemoteBridge","url","bus","bitBus","socket","unsubscribeBus","heartbeatInterval","batchFlushTimeout","pendingStoreIds","isIntentionalDisconnect","sendWhenOpen","message","flushPendingStoreUpdates","payload","acc","storeInstance","scheduleStoreFlush","connect","initialState","_newState","event","isDevToolsActionMessage","action","e","cleanup"],"mappings":"AAAA,qoBAA+C,wDAAyC,SCG/EA,CAAAA,CACPC,CAAAA,CACsC,CACtC,MAAO,CACL,MAAA,CAAQA,CAAAA,CAAM,MAAA,CACd,MAAA,CAAQA,CAAAA,CAAM,MAAA,CACd,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,YAAA,CAAcA,CAAAA,CAAM,YAAA,CACpB,YAAA,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AAA,CAAQ,GAAA,CAAI,sDAAmD,CAAA,CAC/D,UAAA,CAAWQ,CAAAA,CAAS,GAAI,CAAA,CAI5B,CACF,CAAA,CAEAA,CAAAA,CAAQ,CAAA,CAER,IAAMO,CAAAA,CAAU,CAAA,CAAA,EAAM,CACpBf,CAAAA,CAA0B,CAAA,CAAA,CAEtBJ,CAAAA,EAAgBA,CAAAA,CAAe,CAAA,CACnC,aAAA,CAAcC,CAAiB,CAAA,CAC3BC,CAAAA,EAAAA,CACF,YAAA,CAAaA,CAAiB,CAAA,CAC9BA,CAAAA,CAAoB,IAAA,CAAA,CAEtBC,CAAAA,CAAgB,KAAA,CAAM,CAAA,CAEpBJ,CAAAA,EAAAA,CACCA,CAAAA,CAAO,UAAA,GAAe,SAAA,CAAU,IAAA,EAC/BA,CAAAA,CAAO,UAAA,GAAe,SAAA,CAAU,UAAA,CAAA,EAElCA,CAAAA,CAAO,KAAA,CAAM,CAAA,CAEfN,CAAAA,CAAsB,IACxB,CAAA,CAEA,OAAAA,CAAAA,CAAsB0B,CAAAA,CAEfA,CACT,CAAA,4CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-IVPCXKYW.cjs","sourcesContent":[null,"import type { BitBusStorePort, BitState } from \"../core\";\nimport type { DevToolsStoreSnapshot, DevToolsStoreSnapshots } from \"./protocol\";\n\nfunction normalizeStoreState<T extends object>(\n state: Readonly<BitState<T>>,\n): Omit<DevToolsStoreSnapshot, \"_meta\"> {\n return {\n values: state.values,\n errors: state.errors as Record<string, unknown>,\n touched: state.touched as Record<string, unknown>,\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n isValidating: state.isValidating as Record<string, unknown>,\n persist: state.persist,\n };\n}\n\nexport function createDevToolsStoreSnapshot<T extends object>(store: {\n getState: () => Readonly<BitState<T>>;\n getHistoryMetadata: () => {\n canUndo: boolean;\n canRedo: boolean;\n historySize: number;\n historyIndex: number;\n };\n}): DevToolsStoreSnapshot {\n const historyMeta = store.getHistoryMetadata();\n\n return {\n ...normalizeStoreState(store.getState()),\n _meta: {\n canUndo: historyMeta.canUndo,\n canRedo: historyMeta.canRedo,\n totalSteps: historyMeta.historySize,\n currentIndex: historyMeta.historyIndex,\n },\n };\n}\n\nexport function createDevToolsSnapshotMap(\n stores: Record<string, BitBusStorePort<object>>,\n): DevToolsStoreSnapshots {\n const snapshots: DevToolsStoreSnapshots = {};\n\n for (const [storeId, instance] of Object.entries(stores)) {\n snapshots[storeId] = createDevToolsStoreSnapshot(instance);\n }\n\n return snapshots;\n}\n","import type { BitBusStorePort } from \"../core\";\n\nexport type BitDevToolsReadableStore<T extends object = object> =\n BitBusStorePort<T>;\n\nexport type BitDevToolsActionableStore<T extends object = object> =\n BitBusStorePort<T>;\n\nexport function isDevToolsReadableStore(\n value: unknown,\n): value is BitDevToolsReadableStore<object> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const candidate = value as unknown as Record<string, unknown>;\n\n return (\n typeof candidate.getState === \"function\" &&\n typeof candidate.getHistoryMetadata === \"function\"\n );\n}\n\nexport function isDevToolsActionableStore(\n value: unknown,\n): value is BitDevToolsActionableStore<object> {\n if (!isDevToolsReadableStore(value)) {\n return false;\n }\n\n const candidate = value as unknown as Record<string, unknown>;\n\n return (\n typeof candidate.undo === \"function\" &&\n typeof candidate.redo === \"function\" &&\n typeof candidate.reset === \"function\"\n );\n}\n\nexport function getDevToolsActionableStore(\n stores: Record<string, unknown>,\n storeId: string,\n): BitDevToolsActionableStore<object> | null {\n const candidate = stores[storeId];\n return isDevToolsActionableStore(candidate) ? candidate : null;\n}\n","import { bitBus } from \"../core\";\nimport type { BitBus } from \"../core\";\nimport type { BitBusStorePort } from \"../core\";\nimport { DEVTOOLS_PROTOCOL_VERSION, isDevToolsActionMessage } from \"./protocol\";\nimport { createDevToolsSnapshotMap } from \"./store-snapshot\";\nimport { getDevToolsActionableStore } from \"./store-port\";\n\nlet activeBridgeCleanup: (() => void) | null = null;\nconst STATE_BATCH_INTERVAL_MS = 50;\n\nexport function setupRemoteBridge(url: string, bus: BitBus = bitBus) {\n if (activeBridgeCleanup) {\n console.warn(\n \"[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado).\",\n );\n activeBridgeCleanup();\n }\n\n let socket: WebSocket | null = null;\n let unsubscribeBus: (() => void) | null = null;\n let heartbeatInterval: ReturnType<typeof setInterval>;\n let batchFlushTimeout: ReturnType<typeof setTimeout> | null = null;\n const pendingStoreIds = new Set<string>();\n let isIntentionalDisconnect = false;\n\n const sendWhenOpen = (message: Record<string, unknown>) => {\n if (socket?.readyState !== WebSocket.OPEN) {\n return;\n }\n\n socket.send(JSON.stringify(message));\n };\n\n const flushPendingStoreUpdates = () => {\n if (pendingStoreIds.size === 0) {\n return;\n }\n\n const payload = createDevToolsSnapshotMap(\n Array.from(pendingStoreIds).reduce<\n Record<string, BitBusStorePort<object>>\n >((acc, storeId) => {\n const storeInstance = bus.stores[storeId];\n if (storeInstance) {\n acc[storeId] = storeInstance;\n }\n return acc;\n }, {}),\n );\n\n pendingStoreIds.clear();\n batchFlushTimeout = null;\n\n if (Object.keys(payload).length > 0) {\n sendWhenOpen({\n type: \"STATE_UPDATE\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n payload,\n });\n }\n };\n\n const scheduleStoreFlush = () => {\n if (batchFlushTimeout) {\n return;\n }\n\n batchFlushTimeout = setTimeout(() => {\n flushPendingStoreUpdates();\n }, STATE_BATCH_INTERVAL_MS);\n };\n\n const connect = () => {\n isIntentionalDisconnect = false;\n socket = new WebSocket(url);\n\n socket.onopen = () => {\n console.log(\"[bit-form] 🔌 Conectado ao CLI DevTools via WebSocket.\");\n\n sendWhenOpen({\n type: \"HELLO\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n payload: { role: \"server\", protocolVersion: DEVTOOLS_PROTOCOL_VERSION },\n });\n\n const initialState = createDevToolsSnapshotMap(bus.stores);\n if (Object.keys(initialState).length > 0) {\n sendWhenOpen({\n type: \"STATE_UPDATE\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n payload: initialState,\n });\n }\n\n unsubscribeBus = bus.subscribe((storeId, _newState) => {\n pendingStoreIds.add(storeId);\n scheduleStoreFlush();\n });\n\n heartbeatInterval = setInterval(() => {\n sendWhenOpen({\n type: \"PING\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n });\n }, 30000);\n };\n\n socket.onmessage = (event) => {\n try {\n const message = JSON.parse(event.data) as unknown;\n\n if (isDevToolsActionMessage(message)) {\n const { storeId, action } = message.payload;\n const store = getDevToolsActionableStore(bus.stores, storeId);\n\n if (!store) {\n return;\n }\n\n switch (action) {\n case \"undo\":\n store.undo();\n break;\n case \"redo\":\n store.redo();\n break;\n case \"reset\":\n store.reset();\n break;\n }\n }\n } catch (e) {\n console.warn(\"[bit-form] Erro ao processar comando do CLI:\", e);\n }\n };\n\n socket.onclose = () => {\n if (unsubscribeBus) unsubscribeBus();\n clearInterval(heartbeatInterval);\n if (batchFlushTimeout) {\n clearTimeout(batchFlushTimeout);\n batchFlushTimeout = null;\n }\n pendingStoreIds.clear();\n\n if (!isIntentionalDisconnect) {\n console.log(\"[bit-form] Conexão perdida. Reconectando em 3s...\");\n setTimeout(connect, 3000);\n } else {\n console.log(\"[bit-form] Ponte antiga encerrada com sucesso.\");\n }\n };\n };\n\n connect();\n\n const cleanup = () => {\n isIntentionalDisconnect = true;\n\n if (unsubscribeBus) unsubscribeBus();\n clearInterval(heartbeatInterval);\n if (batchFlushTimeout) {\n clearTimeout(batchFlushTimeout);\n batchFlushTimeout = null;\n }\n pendingStoreIds.clear();\n if (\n socket &&\n (socket.readyState === WebSocket.OPEN ||\n socket.readyState === WebSocket.CONNECTING)\n ) {\n socket.close();\n }\n activeBridgeCleanup = null;\n };\n\n activeBridgeCleanup = cleanup;\n\n return cleanup;\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-MZNHMPTF.cjs","../src/devtools/store-snapshot.ts","../src/devtools/store-port.ts","../src/devtools/bridge.ts"],"names":["normalizeStoreState","state","createDevToolsStoreSnapshot","store","historyMeta","createDevToolsSnapshotMap","stores","snapshots","storeId","instance","isDevToolsReadableStore","value","candidate","isDevToolsActionableStore","getDevToolsActionableStore","activeBridgeCleanup","STATE_BATCH_INTERVAL_MS","setupRemoteBridge","url","bus","bitBus","socket","unsubscribeBus","heartbeatInterval","batchFlushTimeout","pendingStoreIds","isIntentionalDisconnect","sendWhenOpen","message","flushPendingStoreUpdates","payload","acc","storeInstance","scheduleStoreFlush","connect","initialState","_newState","event","isDevToolsActionMessage","action","e","cleanup"],"mappings":"AAAA,qoBAA+C,wDAAyC,SCG/EA,CAAAA,CACPC,CAAAA,CACsC,CACtC,MAAO,CACL,MAAA,CAAQA,CAAAA,CAAM,MAAA,CACd,MAAA,CAAQA,CAAAA,CAAM,MAAA,CACd,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,YAAA,CAAcA,CAAAA,CAAM,YAAA,CACpB,YAAA,CAAcA,CAAAA,CAAM,YAAA,CACpB,OAAA,CAASA,CAAAA,CAAM,OACjB,CACF,CAEO,SAASC,CAAAA,CAA8CC,CAAAA,CAQpC,CACxB,IAAMC,CAAAA,CAAcD,CAAAA,CAAM,kBAAA,CAAmB,CAAA,CAE7C,MAAO,CACL,GAAGH,CAAAA,CAAoBG,CAAAA,CAAM,QAAA,CAAS,CAAC,CAAA,CACvC,KAAA,CAAO,CACL,OAAA,CAASC,CAAAA,CAAY,OAAA,CACrB,OAAA,CAASA,CAAAA,CAAY,OAAA,CACrB,UAAA,CAAYA,CAAAA,CAAY,WAAA,CACxB,YAAA,CAAcA,CAAAA,CAAY,YAC5B,CACF,CACF,CAEO,SAASC,CAAAA,CACdC,CAAAA,CACwB,CACxB,IAAMC,CAAAA,CAAoC,CAAC,CAAA,CAE3C,GAAA,CAAA,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,CAAU,UAAA,CAAA,EAElCA,CAAAA,CAAO,KAAA,CAAM,CAAA,CAEfN,CAAAA,CAAsB,IACxB,CAAA,CAEA,OAAAA,CAAAA,CAAsB0B,CAAAA,CAEfA,CACT,CAAA,4CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-MZNHMPTF.cjs","sourcesContent":[null,"import type { BitBusStorePort, BitState } from \"../core\";\nimport type { DevToolsStoreSnapshot, DevToolsStoreSnapshots } from \"./protocol\";\n\nfunction normalizeStoreState<T extends object>(\n state: Readonly<BitState<T>>,\n): Omit<DevToolsStoreSnapshot, \"_meta\"> {\n return {\n values: state.values,\n errors: state.errors as Record<string, unknown>,\n touched: state.touched as Record<string, unknown>,\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n isValidating: state.isValidating as Record<string, unknown>,\n persist: state.persist,\n };\n}\n\nexport function createDevToolsStoreSnapshot<T extends object>(store: {\n getState: () => Readonly<BitState<T>>;\n getHistoryMetadata: () => {\n canUndo: boolean;\n canRedo: boolean;\n historySize: number;\n historyIndex: number;\n };\n}): DevToolsStoreSnapshot {\n const historyMeta = store.getHistoryMetadata();\n\n return {\n ...normalizeStoreState(store.getState()),\n _meta: {\n canUndo: historyMeta.canUndo,\n canRedo: historyMeta.canRedo,\n totalSteps: historyMeta.historySize,\n currentIndex: historyMeta.historyIndex,\n },\n };\n}\n\nexport function createDevToolsSnapshotMap(\n stores: Record<string, BitBusStorePort<object>>,\n): DevToolsStoreSnapshots {\n const snapshots: DevToolsStoreSnapshots = {};\n\n for (const [storeId, instance] of Object.entries(stores)) {\n snapshots[storeId] = createDevToolsStoreSnapshot(instance);\n }\n\n return snapshots;\n}\n","import type { BitBusStorePort } from \"../core\";\n\nexport type BitDevToolsReadableStore<T extends object = object> =\n BitBusStorePort<T>;\n\nexport type BitDevToolsActionableStore<T extends object = object> =\n BitBusStorePort<T>;\n\nexport function isDevToolsReadableStore(\n value: unknown,\n): value is BitDevToolsReadableStore<object> {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const candidate = value as unknown as Record<string, unknown>;\n\n return (\n typeof candidate.getState === \"function\" &&\n typeof candidate.getHistoryMetadata === \"function\"\n );\n}\n\nexport function isDevToolsActionableStore(\n value: unknown,\n): value is BitDevToolsActionableStore<object> {\n if (!isDevToolsReadableStore(value)) {\n return false;\n }\n\n const candidate = value as unknown as Record<string, unknown>;\n\n return (\n typeof candidate.undo === \"function\" &&\n typeof candidate.redo === \"function\" &&\n typeof candidate.reset === \"function\"\n );\n}\n\nexport function getDevToolsActionableStore(\n stores: Record<string, unknown>,\n storeId: string,\n): BitDevToolsActionableStore<object> | null {\n const candidate = stores[storeId];\n return isDevToolsActionableStore(candidate) ? candidate : null;\n}\n","import { bitBus } from \"../core\";\nimport type { BitBus } from \"../core\";\nimport type { BitBusStorePort } from \"../core\";\nimport { DEVTOOLS_PROTOCOL_VERSION, isDevToolsActionMessage } from \"./protocol\";\nimport { createDevToolsSnapshotMap } from \"./store-snapshot\";\nimport { getDevToolsActionableStore } from \"./store-port\";\n\nlet activeBridgeCleanup: (() => void) | null = null;\nconst STATE_BATCH_INTERVAL_MS = 50;\n\nexport function setupRemoteBridge(url: string, bus: BitBus = bitBus) {\n if (activeBridgeCleanup) {\n console.warn(\n \"[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado).\",\n );\n activeBridgeCleanup();\n }\n\n let socket: WebSocket | null = null;\n let unsubscribeBus: (() => void) | null = null;\n let heartbeatInterval: ReturnType<typeof setInterval>;\n let batchFlushTimeout: ReturnType<typeof setTimeout> | null = null;\n const pendingStoreIds = new Set<string>();\n let isIntentionalDisconnect = false;\n\n const sendWhenOpen = (message: Record<string, unknown>) => {\n if (socket?.readyState !== WebSocket.OPEN) {\n return;\n }\n\n socket.send(JSON.stringify(message));\n };\n\n const flushPendingStoreUpdates = () => {\n if (pendingStoreIds.size === 0) {\n return;\n }\n\n const payload = createDevToolsSnapshotMap(\n Array.from(pendingStoreIds).reduce<\n Record<string, BitBusStorePort<object>>\n >((acc, storeId) => {\n const storeInstance = bus.stores[storeId];\n if (storeInstance) {\n acc[storeId] = storeInstance;\n }\n return acc;\n }, {}),\n );\n\n pendingStoreIds.clear();\n batchFlushTimeout = null;\n\n if (Object.keys(payload).length > 0) {\n sendWhenOpen({\n type: \"STATE_UPDATE\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n payload,\n });\n }\n };\n\n const scheduleStoreFlush = () => {\n if (batchFlushTimeout) {\n return;\n }\n\n batchFlushTimeout = setTimeout(() => {\n flushPendingStoreUpdates();\n }, STATE_BATCH_INTERVAL_MS);\n };\n\n const connect = () => {\n isIntentionalDisconnect = false;\n socket = new WebSocket(url);\n\n socket.onopen = () => {\n console.log(\"[bit-form] 🔌 Conectado ao CLI DevTools via WebSocket.\");\n\n sendWhenOpen({\n type: \"HELLO\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n payload: { role: \"server\", protocolVersion: DEVTOOLS_PROTOCOL_VERSION },\n });\n\n const initialState = createDevToolsSnapshotMap(bus.stores);\n if (Object.keys(initialState).length > 0) {\n sendWhenOpen({\n type: \"STATE_UPDATE\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n payload: initialState,\n });\n }\n\n unsubscribeBus = bus.subscribe((storeId, _newState) => {\n pendingStoreIds.add(storeId);\n scheduleStoreFlush();\n });\n\n heartbeatInterval = setInterval(() => {\n sendWhenOpen({\n type: \"PING\",\n protocolVersion: DEVTOOLS_PROTOCOL_VERSION,\n });\n }, 30000);\n };\n\n socket.onmessage = (event) => {\n try {\n const message = JSON.parse(event.data) as unknown;\n\n if (isDevToolsActionMessage(message)) {\n const { storeId, action } = message.payload;\n const store = getDevToolsActionableStore(bus.stores, storeId);\n\n if (!store) {\n return;\n }\n\n switch (action) {\n case \"undo\":\n store.undo();\n break;\n case \"redo\":\n store.redo();\n break;\n case \"reset\":\n store.reset();\n break;\n }\n }\n } catch (e) {\n console.warn(\"[bit-form] Erro ao processar comando do CLI:\", e);\n }\n };\n\n socket.onclose = () => {\n if (unsubscribeBus) unsubscribeBus();\n clearInterval(heartbeatInterval);\n if (batchFlushTimeout) {\n clearTimeout(batchFlushTimeout);\n batchFlushTimeout = null;\n }\n pendingStoreIds.clear();\n\n if (!isIntentionalDisconnect) {\n console.log(\"[bit-form] Conexão perdida. Reconectando em 3s...\");\n setTimeout(connect, 3000);\n } else {\n console.log(\"[bit-form] Ponte antiga encerrada com sucesso.\");\n }\n };\n };\n\n connect();\n\n const cleanup = () => {\n isIntentionalDisconnect = true;\n\n if (unsubscribeBus) unsubscribeBus();\n clearInterval(heartbeatInterval);\n if (batchFlushTimeout) {\n clearTimeout(batchFlushTimeout);\n batchFlushTimeout = null;\n }\n pendingStoreIds.clear();\n if (\n socket &&\n (socket.readyState === WebSocket.OPEN ||\n socket.readyState === WebSocket.CONNECTING)\n ) {\n socket.close();\n }\n activeBridgeCleanup = null;\n };\n\n activeBridgeCleanup = cleanup;\n\n return cleanup;\n}\n"]}
@@ -0,0 +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 _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22;var _chunkRHMJPKNVcjs = require('./chunk-RHMJPKNV.cjs');var _chunkC2GGB5NFcjs = require('./chunk-C2GGB5NF.cjs');var _chunkRGMUXQ2Kcjs = require('./chunk-RGMUXQ2K.cjs');function _t(r){let{path:t,getFieldConfig:e,masks:i}=r,s=_optionalChain([e, 'call', _2 => _2(t), 'optionalAccess', _3 => _3.mask]);if(s)return typeof s=="string"?_optionalChain([i, 'optionalAccess', _4 => _4[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=_chunkRGMUXQ2Kcjs.a.call(void 0, t)}getValues(){return this.baselineSnapshot||(this.baselineSnapshot=Object.freeze(_chunkRGMUXQ2Kcjs.a.call(void 0, this.baselineValues))),this.baselineSnapshot}setValues(t){this.baselineValues=_chunkRGMUXQ2Kcjs.a.call(void 0, t),this.baselineSnapshot=void 0}};var z= (_class =class{constructor(t,e){;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);_class.prototype.__init7.call(this);this.getComputedEntries=t;this.onError=e}__init() {this.equalityCache=new Map}__init2() {this.reverseDepsCache=null}__init3() {this.childDepsIndex=null}__init4() {this.validatedEntriesSignature=null}__init5() {this.validatedEntriesRef=null}__init6() {this.orderedAllEntriesCache=null}__init7() {this.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){_optionalChain([this, 'access', _5 => _5.onError, 'optionalCall', _6 => _6(h,a.path)]),n.add(a.path);continue}let u=_chunkRGMUXQ2Kcjs.f.call(void 0, 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=_chunkRGMUXQ2Kcjs.d.call(void 0, u,c),p?this.equalityCache.set(a.path,{current:u,next:c,equal:d}):this.equalityCache.delete(a.path)),d||(o=_chunkRGMUXQ2Kcjs.g.call(void 0, 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=_nullishCoalesce(s.get(c), () => (new Set));u.has(a.path)||(u.add(a.path),s.set(c,u),i.set(a.path,(_nullishCoalesce(i.get(a.path), () => (0)))+1))})});let o=t.filter(a=>(_nullishCoalesce(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=(_nullishCoalesce(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=_optionalChain([this, 'access', _7 => _7.childDepsIndex, 'optionalAccess', _8 => _8.get, 'call', _9 => _9(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.`)}}, _class);var U= (_class2 =class{constructor() { _class2.prototype.__init8.call(this);_class2.prototype.__init9.call(this);_class2.prototype.__init10.call(this);_class2.prototype.__init11.call(this); }__init8() {this.dirtyPaths=new Set}__init9() {this.dirtyPathIndex=new Set}__init10() {this.dirtyPrefixRefCount=new Map}__init11() {this.childrenByPrefix=new Map}updateForPath(t,e,i){this.removeDirtyChildren(t);let s=_chunkRGMUXQ2Kcjs.f.call(void 0, e,t),o=_chunkRGMUXQ2Kcjs.f.call(void 0, i,t);return _chunkRGMUXQ2Kcjs.c.call(void 0, s,o)?this.removeDirtyPath(t):this.addDirtyPath(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=_chunkRGMUXQ2Kcjs.e.call(void 0, 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((_nullishCoalesce(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=_chunkRGMUXQ2Kcjs.f.call(void 0, t,u);e.push([u,l]),o.add(u)}else{let u=_chunkRGMUXQ2Kcjs.f.call(void 0, t,a);e.push([a,u]),o.add(a)}}return e.length===0?{}:_chunkRGMUXQ2Kcjs.h.call(void 0, {},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,(_nullishCoalesce(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,(_nullishCoalesce(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=(_nullishCoalesce(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=>{_optionalChain([this, 'access', _10 => _10.childrenByPrefix, 'access', _11 => _11.get, 'call', _12 => _12(e), 'optionalAccess', _13 => _13.delete, 'call', _14 => _14(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)}}, _class2);var q= (_class3 =class{constructor() { _class3.prototype.__init12.call(this); }__init12() {this.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()}}, _class3);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= (_class4 =class{constructor() { _class4.prototype.__init13.call(this);_class4.prototype.__init14.call(this);_class4.prototype.__init15.call(this);_class4.prototype.__init16.call(this);_class4.prototype.__init17.call(this); }__init13() {this.fieldConfigs=new Map}__init14() {this.scopeFieldsIndex=null}__init15() {this.computedEntriesCache=null}__init16() {this.normalizerEntriesCache=null}__init17() {this.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=_nullishCoalesce(e.get(i.scope), () => (new Set));o.add(s),e.set(i.scope,o)}),this.scopeFieldsIndex=e}return Array.from(_nullishCoalesce(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:_optionalChain([e, 'access', _15 => _15.normalizeDependsOn, 'optionalAccess', _16 => _16.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=_nullishCoalesce(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:_optionalChain([e, 'access', _17 => _17.normalizeDependsOn, 'optionalAccess', _18 => _18.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))}}, _class4);var _= (_class5 =class{constructor(t,e){;_class5.prototype.__init18.call(this);_class5.prototype.__init19.call(this);_class5.prototype.__init20.call(this);_class5.prototype.__init21.call(this);_class5.prototype.__init22.call(this);_class5.prototype.__init23.call(this);_class5.prototype.__init24.call(this);this.getFieldConfig=t;this.onConditionError=e}__init18() {this.dependencies=new Map}__init19() {this.hiddenFields=new Set}__init20() {this.conditionalVisibilityPaths=new Set}__init21() {this.requiredPathsByDependency=new Map}__init22() {this.requiredConditionalPaths=new Set}__init23() {this.requiredEvaluationVersion=0}__init24() {this.requiredEvaluationCache=new Map}getHiddenFields(){return this.hiddenFields}onRegister(t,e,i){let s=!!_optionalChain([e, 'access', _19 => _19.conditional, 'optionalAccess', _20 => _20.showIf]),o=_optionalChain([e, 'access', _21 => _21.conditional, 'optionalAccess', _22 => _22.dependsOn]);if(o){if(this.wouldCreateCycle(t,o)){let n=new Error(`Circular dependency detected: "${t}" \u2192 [${o.join(", ")}]`);return _optionalChain([this, 'access', _23 => _23.onConditionError, 'optionalCall', _24 => _24({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&&_optionalChain([e, 'access', _25 => _25.conditional, 'optionalAccess', _26 => _26.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),_optionalChain([i, 'optionalAccess', _27 => _27.preserveIncomingDependents])||this.dependencies.delete(t),this.requiredEvaluationVersion+=1,this.requiredEvaluationCache.clear(),this.requiredConditionalPaths.delete(t),_optionalChain([e, 'optionalAccess', _28 => _28.conditional, 'optionalAccess', _29 => _29.dependsOn, 'optionalAccess', _30 => _30.forEach, 'call', _31 => _31(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(_nullishCoalesce(_optionalChain([this, 'access', _32 => _32.dependencies, 'access', _33 => _33.get, 'call', _34 => _34(t), 'optionalAccess', _35 => _35.size]), () => (0)))>0}isRequired(t,e){let i=this.getFieldConfig(t);if(!i||this.isHidden(t)||!_optionalChain([i, 'access', _36 => _36.conditional, 'optionalAccess', _37 => _37.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){_optionalChain([this, 'access', _38 => _38.onConditionError, 'optionalCall', _39 => _39({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=_chunkRGMUXQ2Kcjs.f.call(void 0, t,i);this.isEmpty(o)&&(e[i]=_nullishCoalesce(_optionalChain([s, 'access', _40 => _40.conditional, 'optionalAccess', _41 => _41.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=_optionalChain([this, 'access', _42 => _42.getFieldConfig, 'call', _43 => _43(t), 'optionalAccess', _44 => _44.conditional, 'optionalAccess', _45 => _45.showIf]);if(s)try{s(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t)}catch(o){_optionalChain([this, 'access', _46 => _46.onConditionError, 'optionalCall', _47 => _47({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}}, _class5);var N= (_class6 =class{__init25() {this.catalog=new L}constructor(t){;_class6.prototype.__init25.call(this);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()}}, _class6);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=_nullishCoalesce(r.initialValues, () => ({})),e=r.validation,i=r.history,s=r.name?`bit-form:${r.name}:draft`:"bit-form:draft",o=_nullishCoalesce(r.onUnhandledError, () => (oi)),n=_optionalChain([r, 'access', _48 => _48.persist, 'optionalAccess', _49 => _49.onError]),a={enabled:_nullishCoalesce(_optionalChain([r, 'access', _50 => _50.persist, 'optionalAccess', _51 => _51.enabled]), () => (!1)),key:_nullishCoalesce(_optionalChain([r, 'access', _52 => _52.persist, 'optionalAccess', _53 => _53.key]), () => (s)),storage:_optionalChain([r, 'access', _54 => _54.persist, 'optionalAccess', _55 => _55.storage]),autoSave:_nullishCoalesce(_optionalChain([r, 'access', _56 => _56.persist, 'optionalAccess', _57 => _57.autoSave]), () => (!0)),debounceMs:_nullishCoalesce(_optionalChain([r, 'access', _58 => _58.persist, 'optionalAccess', _59 => _59.debounceMs]), () => (300)),mode:_nullishCoalesce(_optionalChain([r, 'access', _60 => _60.persist, 'optionalAccess', _61 => _61.mode]), () => ("values")),serialize:_nullishCoalesce(_optionalChain([r, 'access', _62 => _62.persist, 'optionalAccess', _63 => _63.serialize]), () => (JSON.stringify)),deserialize:_nullishCoalesce(_optionalChain([r, 'access', _64 => _64.persist, 'optionalAccess', _65 => _65.deserialize]), () => ((c=>JSON.parse(c)))),onError:c=>{if(n){n(c);return}o(c,"persist")}};return{name:r.name,initialValues:_chunkRGMUXQ2Kcjs.a.call(void 0, t),resolver:_optionalChain([e, 'optionalAccess', _66 => _66.resolver]),validationDelay:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _67 => _67.delay]), () => (300)),history:{enabled:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _68 => _68.enabled]), () => (!1)),limit:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _69 => _69.limit]), () => (50))},masks:r.masks,fields:r.fields,devTools:r.devTools,persist:a,idFactory:_nullishCoalesce(r.idFactory, () => (ni)),plugins:_nullishCoalesce(r.plugins, () => ([])),scheduler:r.scheduler,subscriptionCacheSize:r.subscriptionCacheSize,trackedSubscriptions:_nullishCoalesce(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(_nullishCoalesce(r, () => ([])));return _optionalChain([t, 'optionalAccess', _70 => _70.forEach, 'call', _71 => _71(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=_chunkRGMUXQ2Kcjs.f.call(void 0, t,n.path),c;try{c=i(n,a)}catch(u){_optionalChain([s, 'optionalCall', _72 => _72(u,n.path)]);continue}_chunkRGMUXQ2Kcjs.c.call(void 0, a,c)||o.push([n.path,c])}return o}function ai(r){let t=_nullishCoalesce(_optionalChain([r, 'optionalAccess', _73 => _73.includes, 'call', _74 => _74("*")]), () => (!1)),e=new Set(_nullishCoalesce(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?_chunkRGMUXQ2Kcjs.h.call(void 0, 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:_chunkRGMUXQ2Kcjs.h.call(void 0, t,o)}var $=class{constructor(t){this.effects=t.getAll()}attachStorePort(t){this.effects.forEach(e=>_optionalChain([e, 'access', _75 => _75.attachStorePort, 'optionalCall', _76 => _76(t)]))}initialize(){this.effects.forEach(t=>_optionalChain([t, 'access', _77 => _77.initialize, 'optionalCall', _78 => _78()]))}onStateUpdated(t,e){this.effects.forEach(i=>_optionalChain([i, 'access', _79 => _79.onStateUpdated, 'optionalCall', _80 => _80(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{_optionalChain([e, 'access', _81 => _81.onFieldChange, 'optionalCall', _82 => _82(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)_optionalChain([this, 'access', _83 => _83.effects, 'access', _84 => _84[t], 'access', _85 => _85.destroy, 'optionalCall', _86 => _86()])}};var J=class{constructor(t,e,i=!0,s){this.storeId=t;this.bus=e;this.enableBusDispatch=i;this.storeBusPort=s}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= (_class7 =class{constructor() { _class7.prototype.__init26.call(this); }__init26() {this.effects=new Map}register(t){this.effects.set(t.name,t)}getAll(){return Array.from(this.effects.values())}}, _class7);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=_nullishCoalesce(globalThis.localStorage, () => (void 0))}catch (e2){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}getStorage(){return this.config.storage||ci()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(t){_optionalChain([this, 'access', _87 => _87.config, 'access', _88 => _88.onError, 'optionalCall', _89 => _89(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,_optionalChain([this, 'access', _90 => _90.callbacks, 'access', _91 => _91.onAutoSaveStart, 'optionalCall', _92 => _92()]),this.saveNow().then(()=>{_optionalChain([this, 'access', _93 => _93.callbacks, 'access', _94 => _94.onAutoSaveSuccess, 'optionalCall', _95 => _95()])}).catch(t=>{_optionalChain([this, 'access', _96 => _96.callbacks, 'access', _97 => _97.onAutoSaveError, 'optionalCall', _98 => _98(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= (_class8 =class{constructor(t,e){;_class8.prototype.__init27.call(this);_class8.prototype.__init28.call(this);_class8.prototype.__init29.call(this);_class8.prototype.__init30.call(this);this.plugins=t;this.contextFactory=e}__init27() {this.teardownFns=[]}__init28() {this.notifyingError=!1}__init29() {this.pendingErrorQueue=[]}__init30() {this.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=_optionalChain([i, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.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=_optionalChain([a, 'access', _101 => _101.hooks, 'optionalAccess', _102 => _102.onError]);if(c)try{await c(n,o)}catch (e3){}}}}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=_optionalChain([s, 'access', _103 => _103.hooks, 'optionalAccess', _104 => _104[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}}, _class8);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:()=>_optionalChain([u, 'optionalCall', _105 => _105({isSaving:!0,error:null})]),onAutoSaveSuccess:()=>_optionalChain([u, 'optionalCall', _106 => _106({isSaving:!1,error:null})]),onAutoSaveError:B=>_optionalChain([u, 'optionalCall', _107 => _107({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?_nullishCoalesce(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:_optionalChain([e, 'optionalAccess', _108 => _108.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=_chunkRGMUXQ2Kcjs.a.call(void 0, _chunkRGMUXQ2Kcjs.b.call(void 0, 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,[_chunkRHMJPKNVcjs.d.call(void 0, 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),_optionalChain([u, 'optionalAccess', _109 => _109.scope])&&o.notify(e,[_chunkRHMJPKNVcjs.d.call(void 0, 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,[_chunkRHMJPKNVcjs.d.call(void 0, u)])})}var it= (_class9 =class{constructor(t,e=500){;_class9.prototype.__init31.call(this);_class9.prototype.__init32.call(this);_class9.prototype.__init33.call(this);_class9.prototype.__init34.call(this);_class9.prototype.__init35.call(this);_class9.prototype.__init36.call(this);_class9.prototype.__init37.call(this);_class9.prototype.__init38.call(this);_class9.prototype.__init39.call(this);this.getState=t;this.MAX_PATH_EXPANSION_CACHE_SIZE=e}__init31() {this.listeners=new Set}__init32() {this.pathScopedSubscriptions=new Map}__init33() {this.pathSelectorIndex=new Map}__init34() {this.pathExpansionCache=new Map}__init35() {this.subscriptionSeenVersion=new Map}__init36() {this.notifyVersion=0}__init37() {this.cacheHits=0}__init38() {this.cacheMisses=0}__init39() {this.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=_nullishCoalesce(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=>{(_nullishCoalesce(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=>{(_nullishCoalesce(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)}}, _class9);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= (_class10 =class{constructor(t){;_class10.prototype.__init40.call(this);this.store=t}__init40() {this.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)),_optionalChain([this, 'access', _110 => _110.store, 'access', _111 => _111.unregisterPrefix, 'optionalCall', _112 => _112(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=_chunkRGMUXQ2Kcjs.f.call(void 0, 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=_chunkRGMUXQ2Kcjs.f.call(void 0, 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=_chunkRGMUXQ2Kcjs.f.call(void 0, 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){_optionalChain([this, 'access', _113 => _113.store, 'access', _114 => _114.unregisterPrefix, 'optionalCall', _115 => _115(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=_chunkRGMUXQ2Kcjs.f.call(void 0, 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=_nullishCoalesce(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=_chunkRGMUXQ2Kcjs.f.call(void 0, 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=_chunkRGMUXQ2Kcjs.k.call(void 0, n,e,o);this.store.dispatch(m({errors:a.errors,touched:a.touched,isValidating:n.isValidating},[e])),this.store.internalSaveSnapshot()}}, _class10);var st=class{constructor(t,e,i){this.getState=t;this.dispatch=e;this.reportError=i}reportInvalidInput(t,e){_optionalChain([this, 'access', _116 => _116.reportError, 'optionalCall', _117 => _117(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=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _118 => _118.arrayStrategy]), () => ("first")),s=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _119 => _119.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= (_class11 =class{constructor(t,e,i){;_class11.prototype.__init41.call(this);this.fieldMetadataProvider=t;this.getState=e;this.isPathDirty=i}__init41() {this.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]}}, _class11);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&&_chunkRGMUXQ2Kcjs.d.call(void 0, o,n))){if(o!==null&&typeof o=="object"&&n!==null&&typeof n=="object"){let l=i.get(o);if(_optionalChain([l, 'optionalAccess', _120 => _120.has, 'call', _121 => _121(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:_chunkRGMUXQ2Kcjs.a.call(void 0, o),nextValue:_chunkRGMUXQ2Kcjs.a.call(void 0, 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=_chunkRGMUXQ2Kcjs.h.call(void 0, i,s)),o.length>0&&(i=_chunkRGMUXQ2Kcjs.i.call(void 0, i,o)),i}var at= (_class12 =class{constructor(t,e){;_class12.prototype.__init42.call(this);_class12.prototype.__init43.call(this);_class12.prototype.__init44.call(this);_class12.prototype.__init45.call(this);_class12.prototype.__init46.call(this);this.enableHistory=t;this.maxHistory=e}__init42() {this.baseSnapshot=null}__init43() {this.currentSnapshot=null}__init44() {this.patches=[]}__init45() {this.historyIndex=-1}__init46() {this.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=_chunkRGMUXQ2Kcjs.a.call(void 0, 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)}}, _class12);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)}])}updateField(t,e,i={origin:"setField"}){let s=this.store.getState(),o=_chunkRGMUXQ2Kcjs.f.call(void 0, s.values,t),n={path:t,value:e,meta:i,previousValue:o,nextValues:_chunkRGMUXQ2Kcjs.g.call(void 0, 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"?_optionalChain([this, 'access', _122 => _122.store, 'access', _123 => _123.getFieldConfig, 'call', _124 => _124(t.path), 'optionalAccess', _125 => _125.validation, 'optionalAccess', _126 => _126.asyncValidateOn]):void 0)==="change"&&this.store.handleFieldAsyncValidation(t.path,t.value)}};var dt= (_class13 =class{constructor() { _class13.prototype.__init47.call(this); }__init47() {this.executors=new Map}register(t,e){let i=_nullishCoalesce(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[..._nullishCoalesce(this.executors.get(t), () => ([]))].sort((i,s)=>i.phase-s.phase)}}, _class13);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)}])}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:_chunkRGMUXQ2Kcjs.a.call(void 0, 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=_chunkRGMUXQ2Kcjs.h.call(void 0, 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(_chunkRGMUXQ2Kcjs.l.call(void 0, e)){this.store.setServerErrors(_chunkRGMUXQ2Kcjs.m.call(void 0, 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(_optionalChain([e, 'optionalAccess', _127 => _127.rebase])){this.rebaseValues(t);return}if(_optionalChain([e, 'optionalAccess', _128 => _128.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?_chunkRGMUXQ2Kcjs.h.call(void 0, 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=_chunkRGMUXQ2Kcjs.a.call(void 0, 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=>{_optionalChain([this, 'access', _129 => _129.store, 'access', _130 => _130.config, 'optionalAccess', _131 => _131.onUnhandledError, 'call', _132 => _132(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=_chunkRGMUXQ2Kcjs.a.call(void 0, 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=_chunkRGMUXQ2Kcjs.a.call(void 0, 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=>{_optionalChain([this, 'access', _133 => _133.store, 'access', _134 => _134.config, 'optionalAccess', _135 => _135.onUnhandledError, 'call', _136 => _136(a,"replaceValuesInternal")])}),this.store.emitFieldChange({path:"*",previousValue:s,nextValue:o,values:this.store.getState().values,state:this.store.getState(),meta:{origin:e}})}};var ht= (_class14 =class{constructor(t){;_class14.prototype.__init48.call(this);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,_nullishCoalesce(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()})}__init48() {this.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"})}}, _class14);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= (_class15 =class{constructor(t){;_class15.prototype.__init49.call(this);_class15.prototype.__init50.call(this);this.port=t}__init49() {this.abortControllers=new Map}__init50() {this.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 (e4){}finally{this.cancelSchedulerTimeout=void 0}this.abortControllers.forEach(t=>{try{t.abort()}catch (e5){}}),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=_chunkRGMUXQ2Kcjs.f.call(void 0, this.port.getValues(),t);if(!_chunkRGMUXQ2Kcjs.c.call(void 0, 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)}}}, _class15);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= (_class16 =class{constructor() { _class16.prototype.__init51.call(this);_class16.prototype.__init52.call(this); }__init51() {this.currentValidationId=0}__init52() {this.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()}}, _class16);var yt= (_class17 =class{constructor(t){;_class17.prototype.__init53.call(this);this.port=t}__init53() {this.pendingScopeFields=null}trigger(t,e){this.cancelTimeout&&(this.cancelTimeout(),this.cancelTimeout=void 0);let i=_nullishCoalesce(this.port.validationDelay, () => (300)),s=_optionalChain([e, 'optionalAccess', _137 => _137.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}}, _class17);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;_optionalChain([i, 'call', _138 => _138(n), 'optionalAccess', _139 => _139.validation, 'optionalAccess', _140 => _140.asyncValidate])&&o.push(n)}return o}return s&&s((n,a)=>{!_optionalChain([n, 'access', _141 => _141.validation, 'optionalAccess', _142 => _142.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=_optionalChain([o, 'call', _143 => _143(t), 'optionalAccess', _144 => _144.validation, 'optionalAccess', _145 => _145.asyncValidate]);if(!h){p(t);return}n(t),p(t);let y=a();c(t,y),l(t,!0);try{let v=_optionalChain([o, 'call', _146 => _146(t), 'optionalAccess', _147 => _147.validation, 'optionalAccess', _148 => _148.asyncValidateTimeout]),f=h(_chunkRGMUXQ2Kcjs.f.call(void 0, 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(_optionalChain([i, 'optionalAccess', _149 => _149.scope])&&_optionalChain([i, 'access', _150 => _150.scopeFields, 'optionalAccess', _151 => _151.length])){e.store.config.onUnhandledError(new Error("validate received both 'scope' and 'scopeFields'. 'scopeFields' takes precedence."),"validation");return}if(!_optionalChain([t, 'access', _152 => _152.options, 'optionalAccess', _153 => _153.scopeFields, 'optionalAccess', _154 => _154.length])&&_optionalChain([t, 'access', _155 => _155.options, 'optionalAccess', _156 => _156.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:_optionalChain([t, 'access', _157 => _157.options, 'optionalAccess', _158 => _158.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:_optionalChain([t, 'access', _159 => _159.options, 'optionalAccess', _160 => _160.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})}])}async run(t){await this.runner.run(t)}};var bt= (_class18 =class{constructor(t){;_class18.prototype.__init54.call(this);_class18.prototype.__init55.call(this);_class18.prototype.__init56.call(this);this.store=t;this.schedule=_nullishCoalesce(_optionalChain([t, 'access', _161 => _161.config, 'access', _162 => _162.scheduler, 'optionalAccess', _163 => _163.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:_nullishCoalesce(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)}__init54() {this.validatingCount=0}__init55() {this.asyncErrors=new Map}__init56() {this.coordinator=new mt}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=_optionalChain([i, 'optionalAccess', _164 => _164.validation, 'optionalAccess', _165 => _165.asyncValidate]),o=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _166 => _166.validation, 'optionalAccess', _167 => _167.asyncValidateOn]), () => ("blur"));if(!s||o!=="change"){this.cancelFieldAsync(t),this.updateFieldValidating(t,!1);return}let n=_nullishCoalesce(_optionalChain([i, 'access', _168 => _168.validation, 'optionalAccess', _169 => _169.asyncValidateDelay]), () => (500)),a=_optionalChain([i, 'access', _170 => _170.validation, 'optionalAccess', _171 => _171.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{_optionalChain([t, 'optionalAccess', _172 => _172.scopeFields, 'optionalAccess', _173 => _173.length])&&t.scopeFields.forEach(i=>this.cancelFieldAsync(i));let e={options:t,validationId:this.coordinator.beginValidation(),currentState:this.store.getState(),targetFields:_optionalChain([t, 'optionalAccess', _174 => _174.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:_optionalChain([e, 'access', _175 => _175.options, 'optionalAccess', _176 => _176.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)}})}}, _class18);var Dt= (_class19 =class{constructor() { _class19.prototype.__init57.call(this); }__init57() {this.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")}}}, _class19);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,_nullishCoalesce(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=_chunkRGMUXQ2Kcjs.a.call(void 0, 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 _nullishCoalesce(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=_nullishCoalesce(r.changedPathSet, () => (new Set)),i=_nullishCoalesce(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=_nullishCoalesce(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:_nullishCoalesce(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=_nullishCoalesce(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=_nullishCoalesce(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= (_class20 =class{constructor(t){;_class20.prototype.__init58.call(this);this.args=t;this.state=t.state,this.subscriptions=t.subscriptions,this.effects=t.effects,this.capabilityRegistry=t.capabilityRegistry,this.capabilities=t.capabilityRegistry.toCapabilities()}__init58() {this.batchState=Ee()}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(),[_chunkRHMJPKNVcjs.h.call(void 0, )])}}, _class20);function je(r){let{rawConfig:t,overrides:e}=r,i=Wt(t),s=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _177 => _177.baselineManager]), () => (new H(i.initialValues))),o=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _178 => _178.fieldRegistry]), () => (new N(({error:f})=>{i.onUnhandledError(f,"validation")}))),n=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _179 => _179.computedManager]), () => (new z(()=>o.getComputedEntries(),f=>i.onUnhandledError(f,"computed")))),a=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _180 => _180.dirtyManager]), () => (new U)),c=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _181 => _181.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:_optionalChain([t, 'optionalAccess', _182 => _182.emitImmediately]),equalityFn:_optionalChain([t, 'optionalAccess', _183 => _183.equalityFn]),mode:"scoped",paths:["*"]}:{emitImmediately:_optionalChain([t, 'optionalAccess', _184 => _184.emitImmediately]),equalityFn:_optionalChain([t, 'optionalAccess', _185 => _185.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&&(_optionalChain([n, 'optionalCall', _186 => _186()]),l(a))})))},vi(d,o)),_optionalChain([p, 'optionalCall', _187 => _187()])};return l(a),()=>{c=!0,_optionalChain([n, 'optionalCall', _188 => _188()]),n=null}}function Ke(r){let{getState:t,subscriptions:e,selector:i,listener:s,options:o,trackedSubscriptionsEnabled:n}=r,a=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _189 => _189.equalityFn]), () => (_chunkRGMUXQ2Kcjs.c));if(_optionalChain([o, 'optionalAccess', _190 => _190.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=[..._nullishCoalesce(_optionalChain([i, 'optionalAccess', _191 => _191.paths]), () => ([])),t];return s(n=>_chunkRGMUXQ2Kcjs.f.call(void 0, 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:_chunkC2GGB5NFcjs.c})}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:[_chunkRHMJPKNVcjs.h.call(void 0, )],equalityFn:(s,o)=>_chunkRHMJPKNVcjs.e.call(void 0, s,o)})}function Qe(r){let{scopeName:t,getScopeFields:e,readScopeStatus:i,subscribeSelector:s,listener:o}=r,n=_chunkRHMJPKNVcjs.d.call(void 0, t),a=i(t),c=()=>{},u=()=>{c();let d=_chunkRHMJPKNVcjs.c.call(void 0, e(t));c=s(()=>i(t),p=>{_chunkRHMJPKNVcjs.b.call(void 0, a,p)||(a=p,o(p))},{paths:[...d,n]})};u();let l=s(()=>e(t).length,()=>{u();let d=i(t);_chunkRHMJPKNVcjs.b.call(void 0, 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:()=>_chunkRGMUXQ2Kcjs.a.call(void 0, o.getState()),getFieldState:l=>_chunkRGMUXQ2Kcjs.a.call(void 0, 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:!!_optionalChain([e, 'access', _192 => _192.fields, 'optionalAccess', _193 => _193[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= (_class21 =class{constructor(t){;_class21.prototype.__init59.call(this);this.deps=t}__init59() {this.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=_chunkRGMUXQ2Kcjs.f.call(void 0, 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)}}, _class21);var Pt= (_class22 =class{__init60() {this[M]=!0}__init61() {this[k]=!0}constructor(t={}){;_class22.prototype.__init60.call(this);_class22.prototype.__init61.call(this);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()})}}, _class22);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}exports.a = Ct; exports.b = ui; exports.c = Ti; exports.d = Ei; exports.e = Ci; exports.f = Fi; exports.g = Vi; exports.h = wi; exports.i = Ai; exports.j = Ii;
2
+ //# sourceMappingURL=chunk-OR5AGYQT.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-OR5AGYQT.cjs","../src/core/store/engines/store-field-query-engine.ts","../src/core/store/orchestration/framework-store-brand.ts","../src/core/store/orchestration/hook-brand.ts","../src/core/store/managers/core/baseline-manager.ts","../src/core/store/managers/core/computed-manager.ts"],"names":["resolveFieldMask","args","path","getFieldConfig","masks","maskOption","createFieldStateSnapshot","state","value","isHidden","isRequired","isDirty","isValidating","pathKey","BIT_FRAMEWORK_STORE_SYMBOL","BIT_HOOKS_API_SYMBOL","BitBaselineManager","baselineValues","deepClone","values","BitComputedManager","getComputedEntries","onError","changedPaths","computedEntries","entriesToRun","nextValues","failedPaths","entry","dep","newValue","error","currentValue","getDeepValue","cached","valuesEqual","canUseScalarCache","deepEqual","setDeepValue","entries","map","dependents","childIdx","segments","len","prefix","children","reverseDependencies","affectedPaths","queue","queueIndex","currentPath","dependentPath","orderedAllEntries","indexByPath","affectedEntries","entryIndex","left","right","item","entryByPath","inDegree","dependencyPath","nextDependents","orderedPaths","nextDegree","signature","ordered","orderedEntries","index"],"mappings":"AAAA,mhCAAuE,wDAA0C,wDAA4H,SCU7NA,EAAAA,CAAmCC,CAAAA,CAI3B,CACtB,GAAM,CAAE,IAAA,CAAAC,CAAAA,CAAM,cAAA,CAAAC,CAAAA,CAAgB,KAAA,CAAAC,CAAM,CAAA,CAAIH,CAAAA,CAClCI,CAAAA,iBAAaF,CAAAA,mBAAeD,CAAI,CAAA,6BAAG,MAAA,CAEzC,EAAA,CAAKG,CAAAA,CAIL,OAAI,OAAOA,CAAAA,EAAe,QAAA,iBACjBD,CAAAA,4BAAAA,CAAQC,CAAgC,GAAA,CAG1CA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AC/B,MAAA,CAGF,IAAM2B,CAAAA,CAAY,IAAA,CAAK,sBAAA,CAAuB3B,CAAO,CAAA,CACrD,EAAA,CAAI,IAAA,CAAK,yBAAA,GAA8B2B,CAAAA,CAAW,CAChD,IAAA,CAAK,mBAAA,CAAsB3B,CAAAA,CAC3B,MACF,CAEAA,CAAAA,CAAQ,OAAA,CAASX,CAAAA,EAAU,IAAA,CAAK,kBAAA,CAAmBA,CAAK,CAAC,CAAA,CACzD,IAAA,CAAK,qBAAA,CAAsB,CAAA,CAC3B,IAAA,CAAK,yBAAA,CAA4BsC,CAAAA,CACjC,IAAA,CAAK,mBAAA,CAAsB3B,CAC7B,CAEQ,sBAAA,CAAuBA,CAAAA,CAAwC,CACrE,OAAOA,CAAAA,CACJ,GAAA,CAAKX,CAAAA,EAAU,CAAA,EAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-OR5AGYQT.cjs","sourcesContent":[null,"import type { BitMask, BitMaskName } from \"../../mask/types\";\nimport type {\n BitErrors,\n BitFieldDefinition,\n BitFieldState,\n BitPath,\n BitPathValue,\n BitState,\n} from \"../contracts/types\";\n\nexport function resolveFieldMask<T extends object>(args: {\n path: string;\n getFieldConfig: (path: string) => BitFieldDefinition<T> | undefined;\n masks: Record<BitMaskName, BitMask> | undefined;\n}): BitMask | undefined {\n const { path, getFieldConfig, masks } = args;\n const maskOption = getFieldConfig(path)?.mask;\n\n if (!maskOption) {\n return undefined;\n }\n\n if (typeof maskOption === \"string\") {\n return masks?.[maskOption as keyof typeof masks];\n }\n\n return maskOption;\n}\n\nexport function createFieldStateSnapshot<\n TForm extends object,\n P extends BitPath<TForm>,\n>(args: {\n state: Readonly<BitState<TForm>>;\n path: P;\n value: BitPathValue<TForm, P>;\n isHidden: boolean;\n isRequired: boolean;\n isDirty: boolean;\n isValidating: boolean;\n}): BitFieldState<TForm, BitPathValue<TForm, P>> {\n const { state, path, value, isHidden, isRequired, isDirty, isValidating } =\n args;\n const pathKey = path as string;\n\n return {\n value,\n error: state.errors[pathKey as keyof BitErrors<TForm>],\n touched: !!state.touched[pathKey as keyof typeof state.touched],\n isHidden,\n isRequired,\n isDirty,\n isValidating,\n };\n}\n","export const BIT_FRAMEWORK_STORE_SYMBOL = Symbol.for(\n \"bit-form.framework-store-api\",\n);\n","export const BIT_HOOKS_API_SYMBOL = Symbol.for(\"bit-form.hooks-api\");\n","import { deepClone } from \"../../../utils\";\n\nexport class BitBaselineManager<T extends object> {\n constructor(baselineValues: T) {\n this.baselineValues = deepClone(baselineValues);\n }\n\n private baselineValues: T;\n private baselineSnapshot?: Readonly<T>;\n\n getValues(): T {\n if (!this.baselineSnapshot) {\n this.baselineSnapshot = Object.freeze(deepClone(this.baselineValues));\n }\n\n return this.baselineSnapshot as T;\n }\n\n setValues(values: T): void {\n this.baselineValues = deepClone(values);\n this.baselineSnapshot = undefined;\n }\n}\n","import { deepEqual, getDeepValue, setDeepValue } from \"../../../utils\";\nimport type { BitComputedFn } from \"../../contracts/types\";\n\nexport interface BitComputedEntry<T extends object> {\n path: string;\n compute: BitComputedFn<T>;\n dependsOn: readonly string[];\n}\n\nexport class BitComputedManager<T extends object> {\n private equalityCache = new Map<\n string,\n { current: unknown; next: unknown; equal: boolean }\n >();\n private reverseDepsCache: Map<string, Set<string>> | null = null;\n private childDepsIndex: Map<string, Set<string>> | null = null;\n private validatedEntriesSignature: string | null = null;\n private validatedEntriesRef: BitComputedEntry<T>[] | null = null;\n private orderedAllEntriesCache: {\n signature: string;\n ordered: BitComputedEntry<T>[];\n } | null = null;\n private orderedIndexByPathCache: {\n signature: string;\n indexByPath: Map<string, number>;\n } | null = null;\n\n constructor(\n private getComputedEntries: () => BitComputedEntry<T>[],\n private onError?: (error: unknown, path: string) => void,\n ) {}\n\n private isCacheableScalar(value: unknown): boolean {\n return (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n );\n }\n\n invalidateReverseDeps(): void {\n this.reverseDepsCache = null;\n this.childDepsIndex = null;\n this.orderedAllEntriesCache = null;\n this.validatedEntriesSignature = null;\n this.validatedEntriesRef = null;\n this.orderedIndexByPathCache = null;\n this.equalityCache.clear();\n }\n\n apply(values: T, changedPaths?: readonly string[]): T {\n const computedEntries = this.getComputedEntries();\n if (computedEntries.length === 0) return values;\n\n this.ensureEntriesAreValid(computedEntries);\n\n const entriesToRun = this.resolveEntriesToRun(\n computedEntries,\n changedPaths,\n );\n\n if (entriesToRun.length === 0) {\n return values;\n }\n\n let nextValues = values;\n const failedPaths = new Set<string>();\n\n for (const entry of entriesToRun) {\n // Skip this entry if any of its declared dependencies failed in this run.\n if (entry.dependsOn.some((dep) => failedPaths.has(dep))) {\n failedPaths.add(entry.path);\n continue;\n }\n\n let newValue: unknown;\n try {\n newValue = entry.compute(nextValues);\n } catch (error) {\n this.onError?.(error, entry.path);\n failedPaths.add(entry.path);\n continue;\n }\n const currentValue = getDeepValue(nextValues, entry.path);\n\n const cached = this.equalityCache.get(entry.path);\n let valuesEqual: boolean;\n const canUseScalarCache =\n this.isCacheableScalar(currentValue) &&\n this.isCacheableScalar(newValue);\n\n if (\n canUseScalarCache &&\n cached &&\n cached.current === currentValue &&\n cached.next === newValue\n ) {\n valuesEqual = cached.equal;\n } else {\n valuesEqual = deepEqual(currentValue, newValue);\n\n if (canUseScalarCache) {\n this.equalityCache.set(entry.path, {\n current: currentValue,\n next: newValue,\n equal: valuesEqual,\n });\n } else {\n this.equalityCache.delete(entry.path);\n }\n }\n\n if (!valuesEqual) {\n nextValues = setDeepValue(nextValues, entry.path, newValue);\n }\n }\n return nextValues;\n }\n\n private getReverseDependencies(\n entries: BitComputedEntry<T>[],\n ): Map<string, Set<string>> {\n if (this.reverseDepsCache) return this.reverseDepsCache;\n\n const map = new Map<string, Set<string>>();\n\n for (const entry of entries) {\n for (const dep of entry.dependsOn) {\n let dependents = map.get(dep);\n if (!dependents) {\n dependents = new Set();\n map.set(dep, dependents);\n }\n dependents.add(entry.path);\n }\n }\n\n const childIdx = new Map<string, Set<string>>();\n\n for (const dep of map.keys()) {\n const segments = dep.split(\".\");\n for (let len = 1; len < segments.length; len++) {\n const prefix = segments.slice(0, len).join(\".\");\n let children = childIdx.get(prefix);\n if (!children) {\n children = new Set();\n childIdx.set(prefix, children);\n }\n children.add(dep);\n }\n }\n\n this.reverseDepsCache = map;\n this.childDepsIndex = childIdx;\n return map;\n }\n\n private resolveEntriesToRun(\n entries: BitComputedEntry<T>[],\n changedPaths?: readonly string[],\n ): BitComputedEntry<T>[] {\n if (\n !changedPaths ||\n changedPaths.length === 0 ||\n changedPaths.includes(\"*\")\n ) {\n return this.getOrderedAllEntries(entries);\n }\n\n const reverseDependencies = this.getReverseDependencies(entries);\n const affectedPaths = new Set<string>();\n const queue = [...changedPaths];\n let queueIndex = 0;\n\n while (queueIndex < queue.length) {\n const currentPath = queue[queueIndex++]!;\n const dependents = this.getDependentsForPath(\n reverseDependencies,\n currentPath,\n );\n\n if (!dependents) {\n continue;\n }\n\n for (const dependentPath of dependents) {\n if (affectedPaths.has(dependentPath)) {\n continue;\n }\n\n affectedPaths.add(dependentPath);\n queue.push(dependentPath);\n }\n }\n\n if (affectedPaths.size === 0) {\n return [];\n }\n\n const orderedAllEntries = this.getOrderedAllEntries(entries);\n const indexByPath = this.getOrderedIndexByPath(entries, orderedAllEntries);\n const affectedEntries: Array<{\n index: number;\n entry: BitComputedEntry<T>;\n }> = [];\n\n affectedPaths.forEach((path) => {\n const entryIndex = indexByPath.get(path);\n if (entryIndex === undefined) {\n return;\n }\n\n const entry = orderedAllEntries[entryIndex];\n if (!entry) {\n return;\n }\n\n affectedEntries.push({ index: entryIndex, entry });\n });\n\n affectedEntries.sort((left, right) => left.index - right.index);\n return affectedEntries.map((item) => item.entry);\n }\n\n private orderEntries(entries: BitComputedEntry<T>[]) {\n if (entries.length <= 1) {\n return entries;\n }\n\n const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n\n entries.forEach((entry) => inDegree.set(entry.path, 0));\n\n entries.forEach((entry) => {\n entry.dependsOn.forEach((dependencyPath) => {\n if (!entryByPath.has(dependencyPath)) {\n return;\n }\n\n const nextDependents = dependents.get(dependencyPath) ?? new Set();\n if (!nextDependents.has(entry.path)) {\n nextDependents.add(entry.path);\n dependents.set(dependencyPath, nextDependents);\n inDegree.set(entry.path, (inDegree.get(entry.path) ?? 0) + 1);\n }\n });\n });\n\n const queue = entries\n .filter((entry) => (inDegree.get(entry.path) ?? 0) === 0)\n .map((entry) => entry.path);\n const orderedPaths: string[] = [];\n\n while (queue.length > 0) {\n const currentPath = queue.shift()!;\n orderedPaths.push(currentPath);\n\n const nextDependents = dependents.get(currentPath);\n if (!nextDependents) {\n continue;\n }\n\n nextDependents.forEach((dependentPath) => {\n const nextDegree = (inDegree.get(dependentPath) ?? 0) - 1;\n inDegree.set(dependentPath, nextDegree);\n\n if (nextDegree === 0) {\n queue.push(dependentPath);\n }\n });\n }\n\n if (orderedPaths.length !== entries.length) {\n throw new Error(\n \"BitStore: cyclic computed dependencies detected. Check computedDependsOn definitions.\",\n );\n }\n\n return orderedPaths.map((path) => entryByPath.get(path)!);\n }\n\n private getOrderedAllEntries(entries: BitComputedEntry<T>[]) {\n const signature = this.createEntriesSignature(entries);\n if (\n this.orderedAllEntriesCache &&\n this.orderedAllEntriesCache.signature === signature\n ) {\n return this.orderedAllEntriesCache.ordered;\n }\n\n const ordered = this.orderEntries(entries);\n this.orderedAllEntriesCache = { signature, ordered };\n return ordered;\n }\n\n private getOrderedIndexByPath(\n entries: BitComputedEntry<T>[],\n orderedEntries: BitComputedEntry<T>[],\n ): Map<string, number> {\n const signature = this.createEntriesSignature(entries);\n if (\n this.orderedIndexByPathCache &&\n this.orderedIndexByPathCache.signature === signature\n ) {\n return this.orderedIndexByPathCache.indexByPath;\n }\n\n const indexByPath = new Map<string, number>();\n orderedEntries.forEach((entry, index) => {\n indexByPath.set(entry.path, index);\n });\n\n this.orderedIndexByPathCache = { signature, indexByPath };\n return indexByPath;\n }\n\n private ensureEntriesAreValid(entries: BitComputedEntry<T>[]) {\n if (this.validatedEntriesRef === entries) {\n return;\n }\n\n const signature = this.createEntriesSignature(entries);\n if (this.validatedEntriesSignature === signature) {\n this.validatedEntriesRef = entries;\n return;\n }\n\n entries.forEach((entry) => this.assertDependencies(entry));\n this.invalidateReverseDeps();\n this.validatedEntriesSignature = signature;\n this.validatedEntriesRef = entries;\n }\n\n private createEntriesSignature(entries: BitComputedEntry<T>[]): string {\n return entries\n .map((entry) => `${entry.path}:${entry.dependsOn.join(\",\")}`)\n .join(\"|\");\n }\n\n private getDependentsForPath(\n reverseDependencies: Map<string, Set<string>>,\n changedPath: string,\n ) {\n const dependents = new Set<string>();\n\n const collect = (dependencyPath: string) => {\n const listeners = reverseDependencies.get(dependencyPath);\n if (!listeners) {\n return;\n }\n\n listeners.forEach((path) => dependents.add(path));\n };\n\n collect(changedPath);\n\n const parentSegments = changedPath.split(\".\");\n while (parentSegments.length > 1) {\n parentSegments.pop();\n collect(parentSegments.join(\".\"));\n }\n\n const childKeys = this.childDepsIndex?.get(changedPath);\n if (childKeys) {\n for (const childDep of childKeys) {\n collect(childDep);\n }\n }\n\n return dependents;\n }\n\n private assertDependencies(entry: BitComputedEntry<T>) {\n if (entry.dependsOn.length === 0) {\n throw new Error(\n `BitStore: computed field \\`${entry.path}\\` requires explicit computedDependsOn in v4.`,\n );\n }\n\n if (entry.dependsOn.includes(entry.path)) {\n throw new Error(\n `BitStore: computed field \\`${entry.path}\\` cannot depend on itself.`,\n );\n }\n }\n}\n"]}