@lehnihon/bit-form 2.2.3 → 2.2.5

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 (137) hide show
  1. package/dist/angular/index.cjs +1 -1
  2. package/dist/angular/index.cjs.map +1 -1
  3. package/dist/angular/index.d.cts +7 -5
  4. package/dist/angular/index.d.ts +7 -5
  5. package/dist/angular/index.js +1 -1
  6. package/dist/angular/index.js.map +1 -1
  7. package/dist/{bus-DHQHDwUp.d.ts → bus-B4zZmB9C.d.ts} +23 -10
  8. package/dist/{bus-CILR-ENq.d.cts → bus-BeAeZwWu.d.cts} +23 -10
  9. package/dist/chunk-2FDEJYA5.js +2 -0
  10. package/dist/chunk-2FDEJYA5.js.map +1 -0
  11. package/dist/chunk-3CARTBEN.cjs +2 -0
  12. package/dist/chunk-3CARTBEN.cjs.map +1 -0
  13. package/dist/chunk-3NUJVIAM.js +2 -0
  14. package/dist/chunk-3NUJVIAM.js.map +1 -0
  15. package/dist/chunk-64KSP4TP.js +2 -0
  16. package/dist/chunk-64KSP4TP.js.map +1 -0
  17. package/dist/chunk-77PK7U73.cjs +2 -0
  18. package/dist/chunk-77PK7U73.cjs.map +1 -0
  19. package/dist/chunk-CTURHI75.cjs +2 -0
  20. package/dist/chunk-CTURHI75.cjs.map +1 -0
  21. package/dist/chunk-DD6XWUMR.cjs +2 -0
  22. package/dist/chunk-DD6XWUMR.cjs.map +1 -0
  23. package/dist/chunk-FGJB4DHQ.js +2 -0
  24. package/dist/chunk-FGJB4DHQ.js.map +1 -0
  25. package/dist/chunk-FQLJOSF7.js +1 -0
  26. package/dist/chunk-FQLJOSF7.js.map +1 -0
  27. package/dist/chunk-GDRNKTHO.js +2 -0
  28. package/dist/chunk-GDRNKTHO.js.map +1 -0
  29. package/dist/chunk-GUU6EXFN.js +2 -0
  30. package/dist/chunk-GUU6EXFN.js.map +1 -0
  31. package/dist/chunk-JIWR4KSZ.cjs +2 -0
  32. package/dist/chunk-JIWR4KSZ.cjs.map +1 -0
  33. package/dist/chunk-M2XR4C7T.js +2 -0
  34. package/dist/chunk-M2XR4C7T.js.map +1 -0
  35. package/dist/chunk-MFSDDSVG.cjs +1 -0
  36. package/dist/chunk-MFSDDSVG.cjs.map +1 -0
  37. package/dist/chunk-OZKLQRO6.cjs +2 -0
  38. package/dist/chunk-OZKLQRO6.cjs.map +1 -0
  39. package/dist/chunk-PFPGASVZ.cjs +2 -0
  40. package/dist/chunk-PFPGASVZ.cjs.map +1 -0
  41. package/dist/chunk-QWH2NBVB.js +2 -0
  42. package/dist/chunk-QWH2NBVB.js.map +1 -0
  43. package/dist/chunk-UMKOKAPD.js +2 -0
  44. package/dist/chunk-UMKOKAPD.js.map +1 -0
  45. package/dist/chunk-UT63HKR6.cjs +2 -0
  46. package/dist/chunk-UT63HKR6.cjs.map +1 -0
  47. package/dist/chunk-VQ7MK5VB.cjs +2 -0
  48. package/dist/chunk-VQ7MK5VB.cjs.map +1 -0
  49. package/dist/devtools/bridge.cjs +1 -1
  50. package/dist/devtools/bridge.cjs.map +1 -1
  51. package/dist/devtools/bridge.js +1 -1
  52. package/dist/devtools/bridge.js.map +1 -1
  53. package/dist/devtools/index.cjs +2 -2
  54. package/dist/devtools/index.cjs.map +1 -1
  55. package/dist/devtools/index.js +1 -1
  56. package/dist/devtools/index.js.map +1 -1
  57. package/dist/field-binding-BXw0Ku2c.d.cts +12 -0
  58. package/dist/field-binding-BXw0Ku2c.d.ts +12 -0
  59. package/dist/index.cjs +1 -1
  60. package/dist/index.cjs.map +1 -1
  61. package/dist/index.d.cts +37 -58
  62. package/dist/index.d.ts +37 -58
  63. package/dist/index.js +1 -1
  64. package/dist/mask.cjs +1 -1
  65. package/dist/mask.cjs.map +1 -1
  66. package/dist/mask.js +1 -1
  67. package/dist/mask.js.map +1 -1
  68. package/dist/{public-types-SU17BarA.d.cts → public-types-BQXaxmAE.d.cts} +9 -9
  69. package/dist/{public-types-Bgws0aVJ.d.ts → public-types-CVgFf_qY.d.ts} +9 -9
  70. package/dist/react/index.cjs +1 -1
  71. package/dist/react/index.cjs.map +1 -1
  72. package/dist/react/index.d.cts +7 -6
  73. package/dist/react/index.d.ts +7 -6
  74. package/dist/react/index.js +1 -1
  75. package/dist/react/index.js.map +1 -1
  76. package/dist/react-native/index.cjs +1 -1
  77. package/dist/react-native/index.d.cts +5 -4
  78. package/dist/react-native/index.d.ts +5 -4
  79. package/dist/react-native/index.js +1 -1
  80. package/dist/resolvers/index.cjs +2 -0
  81. package/dist/resolvers/index.cjs.map +1 -0
  82. package/dist/resolvers/index.d.cts +9 -0
  83. package/dist/resolvers/index.d.ts +9 -0
  84. package/dist/resolvers/index.js +2 -0
  85. package/dist/resolvers/index.js.map +1 -0
  86. package/dist/resolvers/joi.cjs +1 -1
  87. package/dist/resolvers/joi.cjs.map +1 -1
  88. package/dist/resolvers/joi.d.cts +1 -1
  89. package/dist/resolvers/joi.d.ts +1 -1
  90. package/dist/resolvers/joi.js +1 -1
  91. package/dist/resolvers/joi.js.map +1 -1
  92. package/dist/resolvers/types.cjs +2 -1
  93. package/dist/resolvers/types.cjs.map +1 -1
  94. package/dist/resolvers/types.js +1 -0
  95. package/dist/resolvers/yup.cjs +1 -1
  96. package/dist/resolvers/yup.cjs.map +1 -1
  97. package/dist/resolvers/yup.d.cts +1 -1
  98. package/dist/resolvers/yup.d.ts +1 -1
  99. package/dist/resolvers/yup.js +1 -1
  100. package/dist/resolvers/yup.js.map +1 -1
  101. package/dist/resolvers/zod.cjs +1 -1
  102. package/dist/resolvers/zod.cjs.map +1 -1
  103. package/dist/resolvers/zod.d.cts +1 -1
  104. package/dist/resolvers/zod.d.ts +1 -1
  105. package/dist/resolvers/zod.js +1 -1
  106. package/dist/resolvers/zod.js.map +1 -1
  107. package/dist/{types-C2mpfhp1.d.cts → upload-EXnJLq8k.d.cts} +1 -1
  108. package/dist/{types-C2mpfhp1.d.ts → upload-EXnJLq8k.d.ts} +1 -1
  109. package/dist/{use-bit-persist-BlR-hHk6.d.ts → use-bit-persist-CIVN-oIi.d.cts} +8 -6
  110. package/dist/{use-bit-persist-DEWMhvit.d.cts → use-bit-persist-iPWLbD8l.d.ts} +8 -6
  111. package/dist/vue/index.cjs +1 -1
  112. package/dist/vue/index.cjs.map +1 -1
  113. package/dist/vue/index.d.cts +4 -3
  114. package/dist/vue/index.d.ts +4 -3
  115. package/dist/vue/index.js +1 -1
  116. package/dist/vue/index.js.map +1 -1
  117. package/package.json +25 -1
  118. package/dist/chunk-3MUULXXZ.js +0 -2
  119. package/dist/chunk-3MUULXXZ.js.map +0 -1
  120. package/dist/chunk-7MBRAKBL.js +0 -2
  121. package/dist/chunk-7MBRAKBL.js.map +0 -1
  122. package/dist/chunk-ER2DNS7T.cjs +0 -2
  123. package/dist/chunk-ER2DNS7T.cjs.map +0 -1
  124. package/dist/chunk-FEW3ABPD.js +0 -2
  125. package/dist/chunk-FEW3ABPD.js.map +0 -1
  126. package/dist/chunk-JO37BU2C.cjs +0 -2
  127. package/dist/chunk-JO37BU2C.cjs.map +0 -1
  128. package/dist/chunk-NNKZFXEK.cjs +0 -2
  129. package/dist/chunk-NNKZFXEK.cjs.map +0 -1
  130. package/dist/chunk-PA6T2CBR.cjs +0 -2
  131. package/dist/chunk-PA6T2CBR.cjs.map +0 -1
  132. package/dist/chunk-T3XN5O7V.cjs +0 -2
  133. package/dist/chunk-T3XN5O7V.cjs.map +0 -1
  134. package/dist/chunk-ULC4OPIQ.js +0 -2
  135. package/dist/chunk-ULC4OPIQ.js.map +0 -1
  136. package/dist/chunk-VDWCFNA6.js +0 -2
  137. package/dist/chunk-VDWCFNA6.js.map +0 -1
@@ -3,19 +3,28 @@ import { B as BitMask, a as BitMaskName } from './types-D8DgIUhJ.cjs';
3
3
  type DeepPartial<T> = T extends object ? {
4
4
  [P in keyof T]?: DeepPartial<T[P]>;
5
5
  } : T;
6
- type BitErrors<T> = {
7
- [key: string]: string | undefined;
8
- };
9
- type BitTouched<T> = {
10
- [key: string]: boolean | undefined;
11
- };
6
+ type BitErrors<T extends object> = Partial<Record<BitPath<T>, string | undefined>>;
7
+ type BitTouched<T extends object> = Partial<Record<BitPath<T>, boolean | undefined>>;
12
8
  type BitComputedFn<T> = (values: T) => any;
13
9
  type BitTransformFn<T> = (value: any, allValues: T) => any;
14
- interface BitState<T> {
10
+ interface BitPersistMetadata {
11
+ isSaving: boolean;
12
+ isRestoring: boolean;
13
+ error: Error | null;
14
+ }
15
+ interface BitIdFactoryContext {
16
+ scope: "store" | "array";
17
+ path?: string;
18
+ index?: number;
19
+ storeName?: string;
20
+ }
21
+ type BitIdFactory = (context: BitIdFactoryContext) => string;
22
+ interface BitState<T extends object> {
15
23
  values: T;
16
24
  errors: BitErrors<T>;
17
25
  touched: BitTouched<T>;
18
26
  isValidating: Record<string, boolean>;
27
+ persist: BitPersistMetadata;
19
28
  isValid: boolean;
20
29
  isSubmitting: boolean;
21
30
  isDirty: boolean;
@@ -29,7 +38,7 @@ interface BitFieldState<T extends object = any, TValue = unknown> {
29
38
  isDirty: boolean;
30
39
  isValidating: boolean;
31
40
  }
32
- type ValidatorFn<T> = (values: T, options?: {
41
+ type ValidatorFn<T extends object> = (values: T, options?: {
33
42
  scopeFields?: string[];
34
43
  }) => Promise<BitErrors<T>> | BitErrors<T>;
35
44
  /** Conditional logic: visibility and dynamic required. */
@@ -51,6 +60,8 @@ interface BitFieldDefinition<T extends object = any> {
51
60
  validation?: BitFieldValidation<T>;
52
61
  transform?: BitTransformFn<T>;
53
62
  computed?: BitComputedFn<T>;
63
+ /** Explicit dependencies for computed optimization. Falls back to conditional.dependsOn when omitted. */
64
+ computedDependsOn?: string[];
54
65
  /** Mask name (built-in or custom registry key) or BitMask instance. */
55
66
  mask?: BitMask | BitMaskName;
56
67
  /** Scope name (e.g. wizard step). */
@@ -163,7 +174,7 @@ interface BitPersistResolvedConfig<T extends object = any> {
163
174
  onError?: (error: unknown) => void;
164
175
  }
165
176
  /** Validation config. */
166
- interface BitValidationConfig<T> {
177
+ interface BitValidationConfig<T extends object> {
167
178
  resolver?: ValidatorFn<T>;
168
179
  delay?: number;
169
180
  }
@@ -180,7 +191,9 @@ interface BitConfig<T extends object = any> {
180
191
  /** Core */
181
192
  name?: string;
182
193
  storeId?: string;
194
+ idFactory?: BitIdFactory;
183
195
  initialValues?: T;
196
+ masks?: Record<string, BitMask>;
184
197
  /** Central field config: conditional, validation, transform, computed, mask, scope. */
185
198
  fields?: Record<string, BitFieldDefinition<T>>;
186
199
  /** Schema-level validation */
@@ -231,4 +244,4 @@ declare global {
231
244
  }
232
245
  declare const bitBus: BitFormGlobal;
233
246
 
234
- export { type BitTouched as A, type BitState as B, type BitValidationConfig as C, type DeepPartial as D, type ValidatorFn as E, bitBus as F, type DevToolsOptions as G, type BitPersistResolvedConfig as H, type ScopeStatus as S, type ValidateScopeResult as V, type BitTransformFn as a, type BitFieldChangeEvent as b, type BitBeforeSubmitEvent as c, type BitAfterSubmitEvent as d, type BitFieldDefinition as e, type BitErrors as f, type BitBeforeValidateEvent as g, type BitAfterValidateEvent as h, type BitConfig as i, type BitComputedFn as j, type BitPath as k, type BitFieldState as l, type BitPathValue as m, type BitFieldChangeMeta as n, type BitArrayPath as o, type BitArrayItem as p, type BitFieldConditional as q, type BitFieldValidation as r, type BitHistoryConfig as s, type BitPersistConfig as t, type BitPersistMode as u, type BitPersistStorageAdapter as v, type BitPlugin as w, type BitPluginContext as x, type BitPluginErrorEvent as y, type BitPluginHooks as z };
247
+ export { type BitPersistMode as A, type BitConfig as B, type BitPersistStorageAdapter as C, type DevToolsOptions as D, type BitPluginContext as E, type BitPluginErrorEvent as F, type BitPluginHooks as G, type BitTouched as H, type BitValidationConfig as I, bitBus as J, type ScopeStatus as S, type ValidatorFn as V, type BitFieldDefinition as a, type BitPersistResolvedConfig as b, type BitIdFactory as c, type BitPlugin as d, type BitState as e, type BitPath as f, type BitPathValue as g, type DeepPartial as h, type BitErrors as i, type BitPersistMetadata as j, type BitArrayPath as k, type BitArrayItem as l, type BitFieldState as m, type ValidateScopeResult as n, type BitComputedFn as o, type BitTransformFn as p, type BitFieldChangeMeta as q, type BitBeforeValidateEvent as r, type BitAfterValidateEvent as s, type BitBeforeSubmitEvent as t, type BitAfterSubmitEvent as u, type BitFieldChangeEvent as v, type BitFieldConditional as w, type BitFieldValidation as x, type BitHistoryConfig as y, type BitPersistConfig as z };
@@ -0,0 +1,2 @@
1
+ import{h as l,i as u}from"./chunk-64KSP4TP.js";import{b as d,c}from"./chunk-3NUJVIAM.js";async function m(e,r,o,i){try{let t=await e(r,o);i.onSuccess(t)}catch(t){if(l(t)){i.onServerErrors(u(t));return}i.onUnhandledError(t instanceof Error?t:new Error(String(t)))}}function E(e){return{setField:(r,o)=>e.setField(r,o),blurField:r=>e.blurField(r),replaceValues:r=>e.replaceValues(r),hydrate:r=>e.hydrate(r),rebase:r=>e.rebase(r),setError:(r,o)=>e.setError(r,o),setErrors:r=>e.setErrors(r),setServerErrors:r=>e.setServerErrors(r),validate:r=>e.validate(r),transaction:r=>e.transaction(r)}}function p(e,r){e?.preventDefault?.(),r?.stopPropagation&&e?.stopPropagation?.()}function f(e,r,o){return{submit:s=>a=>(p(a,o),e.submit(s)),onSubmit:s=>a=>(p(a,o),r.setSubmissionError(null),e.submit(async(b,F)=>{await m(s,b,F,{onSuccess:n=>{r.setSubmissionResult(n),r.setSubmissionError(null)},onServerErrors:n=>{e.setServerErrors(n)},onUnhandledError:n=>{r.setSubmissionError(n)}})})),reset:()=>{e.reset(),r.clearSubmissionState()},getValues:()=>e.getState().values,getErrors:()=>e.getState().errors,getTouched:()=>e.getState().touched,getDirtyValues:()=>e.getDirtyValues()}}function k(e,r,o){return e.subscribeSelector(()=>e.getFieldState(r),o,{paths:[r],autoTrackPaths:!1,equalityFn:(i,t)=>i.value===t.value&&i.error===t.error&&i.touched===t.touched&&i.isHidden===t.isHidden&&i.isRequired===t.isRequired&&i.isDirty===t.isDirty&&i.isValidating===t.isValidating})}function h(e,r,o){return{setValue:s=>{e.setField(r,c(s,o))},setBlur:()=>e.blurField(r),displayValue:s=>d(s,o)}}function P(e,r){let o=Object.keys(e),i=Object.keys(r);return o.length!==i.length?!1:o.every(t=>e[t]===r[t])}function x(e,r){return e.hasErrors===r.hasErrors&&e.isDirty===r.isDirty&&P(e.errors,r.errors)}function H(e){return[...e,"isDirty"]}export{E as a,f as b,k as c,h as d,x as e,H as f};
2
+ //# sourceMappingURL=chunk-2FDEJYA5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/submit-handler.ts","../src/core/form-controller.ts","../src/core/field-controller.ts","../src/core/scope-status.ts"],"sourcesContent":["import { extractServerErrors, isValidationErrorShape } from \"./utils\";\n\nexport interface BitSubmitExecutionHandlers {\n onServerErrors: (errors: Record<string, string[] | string>) => void;\n onUnhandledError: (error: Error) => void;\n onSuccess: (result: unknown) => void;\n}\n\nexport async function executeSubmitHandler<T extends object>(\n handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>,\n values: T,\n dirtyValues: Partial<T> | undefined,\n handlers: BitSubmitExecutionHandlers,\n): Promise<void> {\n try {\n const result = await handler(values, dirtyValues);\n handlers.onSuccess(result);\n } catch (error) {\n if (isValidationErrorShape(error)) {\n handlers.onServerErrors(extractServerErrors(error));\n return;\n }\n\n handlers.onUnhandledError(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n}\n","import { executeSubmitHandler } from \"./submit-handler\";\nimport type { BitStoreHooksApi } from \"./store/contracts/public-types\";\n\nexport type BitFormDomEvent = {\n preventDefault?: () => void;\n stopPropagation?: () => void;\n};\n\nexport interface BitFormControllerRuntime {\n clearSubmissionState: () => void;\n setSubmissionResult: (result: unknown) => void;\n setSubmissionError: (error: Error | null) => void;\n}\n\nexport interface BitFormControllerOptions {\n stopPropagation?: boolean;\n}\n\nexport function createStoreFormActions<T extends object>(\n store: BitStoreHooksApi<T>,\n) {\n return {\n setField: <P extends Parameters<BitStoreHooksApi<T>[\"setField\"]>[0]>(\n path: P,\n value: Parameters<BitStoreHooksApi<T>[\"setField\"]>[1],\n ) => store.setField(path, value),\n blurField: <P extends Parameters<BitStoreHooksApi<T>[\"blurField\"]>[0]>(\n path: P,\n ) => store.blurField(path),\n replaceValues: (values: T) => store.replaceValues(values),\n hydrate: (values: Parameters<BitStoreHooksApi<T>[\"hydrate\"]>[0]) =>\n store.hydrate(values),\n rebase: (values: T) => store.rebase(values),\n setError: (path: string, message: string | undefined) =>\n store.setError(path, message),\n setErrors: (errors: Parameters<BitStoreHooksApi<T>[\"setErrors\"]>[0]) =>\n store.setErrors(errors),\n setServerErrors: (\n serverErrors: Parameters<BitStoreHooksApi<T>[\"setServerErrors\"]>[0],\n ) => store.setServerErrors(serverErrors),\n validate: (options?: Parameters<BitStoreHooksApi<T>[\"validate\"]>[0]) =>\n store.validate(options),\n transaction: <TResult>(callback: () => TResult) =>\n store.transaction(callback),\n };\n}\n\nexport function preventFormEvent(\n event?: BitFormDomEvent,\n options?: BitFormControllerOptions,\n) {\n event?.preventDefault?.();\n if (options?.stopPropagation) {\n event?.stopPropagation?.();\n }\n}\n\nexport function createFormController<T extends object>(\n store: BitStoreHooksApi<T>,\n runtime: BitFormControllerRuntime,\n options?: BitFormControllerOptions,\n) {\n const submit = (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (event?: BitFormDomEvent) => {\n preventFormEvent(event, options);\n return store.submit(onSuccess);\n };\n };\n\n const onSubmit = (\n handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>,\n ) => {\n return (event?: BitFormDomEvent) => {\n preventFormEvent(event, options);\n runtime.setSubmissionError(null);\n\n return store.submit(async (values, dirtyValues) => {\n await executeSubmitHandler(handler, values, dirtyValues, {\n onSuccess: (result) => {\n runtime.setSubmissionResult(result);\n runtime.setSubmissionError(null);\n },\n onServerErrors: (serverErrors) => {\n store.setServerErrors(serverErrors);\n },\n onUnhandledError: (error) => {\n runtime.setSubmissionError(error);\n },\n });\n });\n };\n };\n\n const reset = () => {\n store.reset();\n runtime.clearSubmissionState();\n };\n\n return {\n submit,\n onSubmit,\n reset,\n getValues: () => store.getState().values,\n getErrors: () => store.getState().errors,\n getTouched: () => store.getState().touched,\n getDirtyValues: () => store.getDirtyValues(),\n };\n}\n","import { formatMaskedValue, parseMaskedInput } from \"./mask/field-binding\";\nimport type { BitMask } from \"./mask/types\";\nimport type { BitStoreHooksApi } from \"./store/contracts/public-types\";\nimport type {\n BitFieldState,\n BitPath,\n BitPathValue,\n} from \"./store/contracts/types\";\n\nexport function subscribeFieldState<\n TForm extends object,\n P extends BitPath<TForm>,\n>(\n store: BitStoreHooksApi<TForm>,\n path: P,\n listener: (\n value: Readonly<BitFieldState<TForm, BitPathValue<TForm, P>>>,\n ) => void,\n) {\n return store.subscribeSelector(\n () =>\n store.getFieldState(path) as Readonly<\n BitFieldState<TForm, BitPathValue<TForm, P>>\n >,\n listener,\n {\n paths: [path as string],\n autoTrackPaths: false,\n equalityFn: (prev, next) =>\n prev.value === next.value &&\n prev.error === next.error &&\n prev.touched === next.touched &&\n prev.isHidden === next.isHidden &&\n prev.isRequired === next.isRequired &&\n prev.isDirty === next.isDirty &&\n prev.isValidating === next.isValidating,\n },\n );\n}\n\nexport function createMaskedFieldController<\n TForm extends object,\n P extends BitPath<TForm>,\n>(store: BitStoreHooksApi<TForm>, path: P, mask: BitMask | undefined) {\n const setValue = (value: unknown) => {\n store.setField(\n path,\n parseMaskedInput(value, mask) as BitPathValue<TForm, P>,\n );\n };\n\n const setBlur = () => store.blurField(path);\n\n const displayValue = (value: unknown) => formatMaskedValue(value, mask);\n\n return {\n setValue,\n setBlur,\n displayValue,\n };\n}\n","import type { ScopeStatus } from \"./store/contracts/types\";\n\nexport function areScopeErrorsEqual(\n currentErrors: Record<string, string>,\n nextErrors: Record<string, string>,\n): boolean {\n const currentKeys = Object.keys(currentErrors);\n const nextKeys = Object.keys(nextErrors);\n\n if (currentKeys.length !== nextKeys.length) {\n return false;\n }\n\n return currentKeys.every((key) => currentErrors[key] === nextErrors[key]);\n}\n\nexport function isScopeStatusEqual(\n currentStatus: ScopeStatus,\n nextStatus: ScopeStatus,\n): boolean {\n return (\n currentStatus.hasErrors === nextStatus.hasErrors &&\n currentStatus.isDirty === nextStatus.isDirty &&\n areScopeErrorsEqual(currentStatus.errors, nextStatus.errors)\n );\n}\n\nexport function getScopeSubscriptionPaths(scopeFields: readonly string[]) {\n return [...scopeFields, \"isDirty\"];\n}\n"],"mappings":"yFAQA,eAAsBA,EACpBC,EACAC,EACAC,EACAC,EACe,CACf,GAAI,CACF,IAAMC,EAAS,MAAMJ,EAAQC,EAAQC,CAAW,EAChDC,EAAS,UAAUC,CAAM,CAC3B,OAASC,EAAO,CACd,GAAIC,EAAuBD,CAAK,EAAG,CACjCF,EAAS,eAAeI,EAAoBF,CAAK,CAAC,EAClD,MACF,CAEAF,EAAS,iBACPE,aAAiB,MAAQA,EAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC,CAC1D,CACF,CACF,CCTO,SAASG,EACdC,EACA,CACA,MAAO,CACL,SAAU,CACRC,EACAC,IACGF,EAAM,SAASC,EAAMC,CAAK,EAC/B,UACED,GACGD,EAAM,UAAUC,CAAI,EACzB,cAAgBE,GAAcH,EAAM,cAAcG,CAAM,EACxD,QAAUA,GACRH,EAAM,QAAQG,CAAM,EACtB,OAASA,GAAcH,EAAM,OAAOG,CAAM,EAC1C,SAAU,CAACF,EAAcG,IACvBJ,EAAM,SAASC,EAAMG,CAAO,EAC9B,UAAYC,GACVL,EAAM,UAAUK,CAAM,EACxB,gBACEC,GACGN,EAAM,gBAAgBM,CAAY,EACvC,SAAWC,GACTP,EAAM,SAASO,CAAO,EACxB,YAAuBC,GACrBR,EAAM,YAAYQ,CAAQ,CAC9B,CACF,CAEO,SAASC,EACdC,EACAH,EACA,CACAG,GAAO,iBAAiB,EACpBH,GAAS,iBACXG,GAAO,kBAAkB,CAE7B,CAEO,SAASC,EACdX,EACAY,EACAL,EACA,CAuCA,MAAO,C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AAmBE,EAAkBF,EAAOD,CAAI,CAMtE,CACF,CC1DO,SAASI,EACdC,EACAC,EACS,CACT,IAAMC,EAAc,OAAO,KAAKF,CAAa,EACvCG,EAAW,OAAO,KAAKF,CAAU,EAEvC,OAAIC,EAAY,SAAWC,EAAS,OAC3B,GAGFD,EAAY,MAAOE,GAAQJ,EAAcI,CAAG,IAAMH,EAAWG,CAAG,CAAC,CAC1E,CAEO,SAASC,EACdC,EACAC,EACS,CACT,OACED,EAAc,YAAcC,EAAW,WACvCD,EAAc,UAAYC,EAAW,SACrCR,EAAoBO,EAAc,OAAQC,EAAW,MAAM,CAE/D,CAEO,SAASC,EAA0BC,EAAgC,CACxE,MAAO,CAAC,GAAGA,EAAa,SAAS,CACnC","names":["executeSubmitHandler","handler","values","dirtyValues","handlers","result","error","isValidationErrorShape","extractServerErrors","createStoreFormActions","store","path","value","values","message","errors","serverErrors","options","callback","preventFormEvent","event","createFormController","runtime","onSuccess","handler","dirtyValues","executeSubmitHandler","result","error","subscribeFieldState","store","path","listener","prev","next","createMaskedFieldController","mask","value","parseMaskedInput","formatMaskedValue","areScopeErrorsEqual","currentErrors","nextErrors","currentKeys","nextKeys","key","isScopeStatusEqual","currentStatus","nextStatus","getScopeSubscriptionPaths","scopeFields"]}
@@ -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 _chunkJIWR4KSZcjs = require('./chunk-JIWR4KSZ.cjs');var _chunkOZKLQRO6cjs = require('./chunk-OZKLQRO6.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var q=_react.createContext.call(void 0, null),lt= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, q.Provider,{value:_chunkOZKLQRO6cjs.k.call(void 0, t),children:e}),S= exports.b =()=>{let t=_react.useContext.call(void 0, q);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};var G=t=>({isValid:t.isValid,isDirty:t.isDirty,isSubmitting:t.isSubmitting});function bt(){let t=S(),[e,o]=_react.useState.call(void 0, null),[s,n]=_react.useState.call(void 0, null),c=_react.useRef.call(void 0, null),l=_react.useCallback.call(void 0, ()=>{let p=t.getState(),P={isValid:p.isValid,isDirty:p.isDirty,isSubmitting:p.isSubmitting};return c.current&&c.current.isValid===P.isValid&&c.current.isDirty===P.isDirty&&c.current.isSubmitting===P.isSubmitting?c.current:(c.current=P,P)},[t]),d=_react.useCallback.call(void 0, p=>t.subscribeSelector(G,()=>p(),{paths:["isValid","isDirty","isSubmitting"]}),[t]),i=_react.useSyncExternalStore.call(void 0, d,l,l),r=_react.useMemo.call(void 0, ()=>_chunkJIWR4KSZcjs.b.call(void 0, t,{clearSubmissionState:()=>{o(null),n(null)},setSubmissionResult:p=>{n(p)},setSubmissionError:p=>{o(p)}}),[t]),u=_react.useMemo.call(void 0, ()=>_chunkJIWR4KSZcjs.a.call(void 0, t),[t]),a=_react.useCallback.call(void 0, r.submit,[r]),y=_react.useCallback.call(void 0, r.onSubmit,[r]),h=_react.useCallback.call(void 0, r.reset,[r]),B=_react.useCallback.call(void 0, r.getValues,[r]),E=_react.useCallback.call(void 0, r.getErrors,[r]),m=_react.useCallback.call(void 0, r.getTouched,[r]),g=_react.useCallback.call(void 0, r.getDirtyValues,[r]);return{meta:_react.useMemo.call(void 0, ()=>({...i,submitError:e,lastResponse:s}),[i,e,s]),getValues:B,getErrors:E,getTouched:m,getDirtyValues:g,submit:a,onSubmit:y,reset:h,...u}}function Tt(t){let e=S(),o=_react.useCallback.call(void 0, r=>e.config.idFactory({scope:"array",path:t,index:r}),[e,t]),s=_react.useRef.call(void 0, []),n=_react.useCallback.call(void 0, ()=>{let r=e.getState(),u=_chunkOZKLQRO6cjs.e.call(void 0, r.values,t),a=Array.isArray(u)?u:[];if(a.length!==s.current.length)if(a.length>s.current.length){let y=a.length-s.current.length;s.current=[...s.current,...Array(y).fill(null).map((h,B)=>o(s.current.length+B))]}else s.current=s.current.slice(0,a.length);return a},[e,t,o]),c=_react.useCallback.call(void 0, r=>e.subscribePath(t,()=>r()),[e,t]),l=_react.useSyncExternalStore.call(void 0, c,n,n),d=_react.useMemo.call(void 0, ()=>({append:r=>{s.current=[...s.current,o(s.current.length)],e.pushItem(t,r)},prepend:r=>{s.current=[o(0),...s.current],e.prependItem(t,r)},insert:(r,u)=>{let a=[...s.current];a.splice(r,0,o(r)),s.current=a,e.insertItem(t,r,u)},remove:r=>{s.current=s.current.filter((u,a)=>a!==r),e.removeItem(t,r)},move:(r,u)=>{let a=[...s.current],[y]=a.splice(r,1);a.splice(u,0,y),s.current=a,e.moveItem(t,r,u)},swap:(r,u)=>{let a=[...s.current];[a[r],a[u]]=[a[u],a[r]],s.current=a,e.swapItems(t,r,u)},replace:r=>{s.current=r.map((u,a)=>o(a)),e.setField(t,r)},clear:()=>{s.current=[],e.setField(t,[])}}),[e,t,o]);return{fields:_react.useMemo.call(void 0, ()=>l.map((r,u)=>({key:s.current[u]||`temp-${u}`,value:r,index:u})),[l]),length:l.length,...d}}function It(t){let e=S(),o=e.getScopeFields(t),s=_react.useRef.call(void 0, null),n=_react.useCallback.call(void 0, ()=>{let r=e.getStepStatus(t);return s.current&&_chunkJIWR4KSZcjs.e.call(void 0, s.current,r)?s.current:(s.current=r,r)},[e,t]),c=_react.useCallback.call(void 0, r=>e.subscribeSelector(u=>({errors:u.errors,isDirty:u.isDirty}),()=>r(),{paths:_chunkJIWR4KSZcjs.f.call(void 0, o)}),[e,o]),l=_react.useSyncExternalStore.call(void 0, c,n,n),d=_react.useCallback.call(void 0, async()=>{let r=await e.validate({scope:t}),u=e.getStepErrors(t);return{valid:r,errors:u}},[e,t]),i=_react.useCallback.call(void 0, ()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:l,errors:l.errors,validate:d,getErrors:i,isValid:!l.hasErrors,isDirty:l.isDirty}}function Ct(t){let e=S(),[o,s]=_react.useState.call(void 0, 0),n=_nullishCoalesce(t[o], () => ("")),c=e.getScopeFields(n),l=_react.useRef.call(void 0, null),d=_react.useCallback.call(void 0, ()=>{let m=e.getStepStatus(n);return l.current&&_chunkJIWR4KSZcjs.e.call(void 0, l.current,m)?l.current:(l.current=m,m)},[e,n]),i=_react.useSyncExternalStore.call(void 0, _react.useCallback.call(void 0, m=>e.subscribeSelector(g=>({errors:g.errors,isDirty:g.isDirty}),()=>m(),{paths:_chunkJIWR4KSZcjs.f.call(void 0, c)}),[e,c]),d,d),r=_react.useCallback.call(void 0, async()=>{let m=await e.validate({scope:n}),g=e.getStepErrors(n);return{valid:m,errors:g}},[e,n]),u=_react.useCallback.call(void 0, ()=>e.getStepErrors(n),[e,n]),a=_react.useCallback.call(void 0, async()=>{let m=e.getScopeFields(n);if(e.hasValidationsInProgress(m))return!1;let g=await e.validate({scope:n});if(g)s(F=>Math.min(F+1,t.length-1));else{let F=e.getStepErrors(n),p=Object.keys(F);p.length>0&&e.markFieldsTouched(p)}return g},[e,n,t.length]),y=_react.useCallback.call(void 0, ()=>{s(m=>Math.max(m-1,0))},[]),h=_react.useCallback.call(void 0, m=>{s(Math.max(0,Math.min(m-1,t.length-1)))},[t.length]),B=o===0,E=o>=t.length-1;return{step:o+1,stepIndex:o,scope:n,next:a,prev:y,goTo:h,isFirst:B,isLast:E,status:i,errors:i.errors,isValid:!i.hasErrors,isDirty:i.isDirty,validate:r,getErrors:u}}function Wt(t){let e=S(),o=_react.useRef.call(void 0, null),s=_react.useCallback.call(void 0, ()=>{let c=_chunkOZKLQRO6cjs.e.call(void 0, e.getState().values,t);return o.current!==null&&_chunkOZKLQRO6cjs.c.call(void 0, o.current,c)?o.current:(o.current=c,c)},[e,t]),n=_react.useCallback.call(void 0, c=>e.subscribePath(t,()=>c()),[e,t]);return _react.useSyncExternalStore.call(void 0, n,s,s)}function Gt(){let t=S(),e=_react.useSyncExternalStore.call(void 0, l=>t.subscribeSelector(d=>d.persist,()=>l(),{paths:["persist"]}),()=>t.getPersistMetadata(),()=>t.getPersistMetadata()),o=_react.useCallback.call(void 0, async()=>t.restorePersisted(),[t]),s=_react.useCallback.call(void 0, async()=>{await t.forceSave()},[t]),n=_react.useCallback.call(void 0, async()=>{await t.clearPersisted()},[t]),c=_react.useMemo.call(void 0, ()=>({isSaving:e.isSaving,isRestoring:e.isRestoring,error:e.error}),[e]);return{restore:o,save:s,clear:n,meta:c}}function Yt(t){let e=S(),o=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>()=>{e.unregisterField&&e.unregisterField(t)},[e,t]);let s=_react.useCallback.call(void 0, ()=>{let i=e.getFieldState(t);if(o.current&&o.current.value===i.value&&o.current.error===i.error&&o.current.touched===i.touched&&o.current.isHidden===i.isHidden&&o.current.isRequired===i.isRequired&&o.current.isDirty===i.isDirty&&o.current.isValidating===i.isValidating)return o.current;let r={value:i.value,error:i.error,touched:i.touched,isHidden:i.isHidden,isRequired:i.isRequired,isDirty:i.isDirty,isValidating:i.isValidating};return o.current=r,r},[e,t]),n=_react.useCallback.call(void 0, i=>_chunkJIWR4KSZcjs.c.call(void 0, e,t,()=>i()),[e,t]),c=_react.useSyncExternalStore.call(void 0, n,s,s),l=_react.useCallback.call(void 0, i=>e.setField(t,i),[e,t]),d=_react.useCallback.call(void 0, ()=>e.blurField(t),[e,t]);return{fieldState:c,setValue:l,setBlur:d,store:e}}exports.a = lt; exports.b = S; exports.c = bt; exports.d = Yt; exports.e = Tt; exports.f = It; exports.g = Ct; exports.h = Wt; exports.i = Gt;
2
+ //# sourceMappingURL=chunk-3CARTBEN.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-3CARTBEN.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","resolveBitStoreForHooks","useBitStore","useContext","selectFormMeta","state","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","nextMeta","subscribeMeta","cb","metaState","useSyncExternalStore","controller","useMemo","createFormController","result","error","actions","createStoreFormActions","submit","onSubmit","reset","getValues","getErrors","getTouched","getDirtyValues","useBitArray","path","createId","index","idsRef","getSnapshot","value","getDeepValue","arrayValue","diff","_","i","subscribeArray","data","methods","newIds","from","to","item","indexA","indexB","items"],"mappings":"AAAA,qOAAoE,wDAAuD,8BCA1E,+CAa/C,IATIA,CAAAA,CAAaC,kCAAAA,IAAgD,CAAA,CAEtDC,EAAAA,aAAkB,CAAC,CAC9B,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,EAIEC,6BAAAA,CAACL,CAAW,QAAA,CAAX,CAAoB,KAAA,CAAOM,iCAAAA,CAA6B,CAAA,CACtD,QAAA,CAAAF,CAAAA,CACH,CAAA,CAGWG,CAAAA,aAAc,CAAA,CAAA,EAAwB,CACjD,IAAMJ,CAAAA,CAAQK,+BAAAA,CAAqB,CAAA,CACnC,EAAA,CAAI,CAACL,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,6DACF,CAAA,CACF,OAAOA,CACT,CAAA,CCzBA,IAcMM,CAAAA,CAAoCC,CAAAA,EAAAA,CAInC,CACL,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,YAAA,CAAcA,CAAAA,CAAM,YACtB,CAAA,CAAA,CAEO,SAASC,EAAAA,CAAAA,CAAoD,CAClE,IAAMR,CAAAA,CAAQI,CAAAA,CAAe,CAAA,CAEvB,CAACK,CAAAA,CAAaC,CAAc,CAAA,CAAIC,6BAAAA,IAA2B,CAAA,CAC3D,CAACC,CAAAA,CAAcC,CAAe,CAAA,CAAIF,6BAAAA,IAAsB,CAAA,CACxDG,CAAAA,CAAWC,2BAAAA,IAIH,CAAA,CAERC,CAAAA,CAAkBC,gCAAAA,CAAY,CAAA,EAAM,CACxC,IAAMV,CAAAA,CAAQP,CAAAA,CAAM,QAAA,C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CACA,CAACtC,CAAAA,CAAOsC,CAAAA,CAAMC,CAAQ,CACxB,CAAA,CAYA,MAAO,CACL,MAAA,CAXaf,4BAAAA,CACb,CAAA,EACG0B,CAAAA,CAAgB,GAAA,CAAI,CAACK,CAAAA,CAAYf,CAAAA,CAAAA,EAAAA,CAAmB,CACnD,GAAA,CAAKC,CAAAA,CAAO,OAAA,CAAQD,CAAK,CAAA,EAAK,CAAA,KAAA,EAAQA,CAAK,CAAA,CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-3CARTBEN.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport type { BitStoreApi, BitStoreHooksApi } from \"../core\";\nimport { resolveBitStoreForHooks } from \"../core\";\n\nconst BitContext = createContext<BitStoreHooksApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStoreApi<any>;\n children: React.ReactNode;\n}) => (\n <BitContext.Provider value={resolveBitStoreForHooks(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 BitStoreHooksApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n createFormController,\n createStoreFormActions,\n} from \"../core/form-controller\";\nimport type { UseBitFormResult } from \"./types\";\n\nconst selectFormMeta = <T extends object>(state: {\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n}) => ({\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n});\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<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const nextMeta = {\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n };\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 subscribeMeta = useCallback(\n (cb: () => void) =>\n store.subscribeSelector(selectFormMeta, () => cb(), {\n paths: [\"isValid\", \"isDirty\", \"isSubmitting\"],\n }),\n [store],\n );\n\n const metaState = useSyncExternalStore(\n subscribeMeta,\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const controller = useMemo(\n () =>\n createFormController(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 actions = useMemo(() => createStoreFormActions(store), [store]);\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 { useCallback, useSyncExternalStore, useRef, useMemo } from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\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 createId = useCallback(\n (index?: number) =>\n store.config.idFactory({\n scope: \"array\",\n path: path as string,\n index,\n }),\n [store, path],\n );\n const idsRef = useRef<string[]>([]);\n\n type Item = BitArrayItem<BitPathValue<TForm, P>>;\n\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const value = getDeepValue(state.values, path as string) as\n | BitPathValue<TForm, P>\n | undefined;\n const arrayValue = Array.isArray(value) ? (value as Item[]) : [];\n\n if (arrayValue.length !== idsRef.current.length) {\n if (arrayValue.length > idsRef.current.length) {\n const diff = arrayValue.length - idsRef.current.length;\n idsRef.current = [\n ...idsRef.current,\n ...Array(diff)\n .fill(null)\n .map((_, i) => createId(idsRef.current.length + i)),\n ];\n } else {\n idsRef.current = idsRef.current.slice(0, arrayValue.length);\n }\n }\n\n return arrayValue;\n }, [store, path, createId]);\n\n const subscribeArray = useCallback(\n (cb: () => void) => store.subscribePath(path, () => cb()),\n [store, path],\n );\n\n const data = useSyncExternalStore(subscribeArray, getSnapshot, getSnapshot);\n\n const methods = useMemo(\n () => ({\n append: (value: Item) => {\n idsRef.current = [...idsRef.current, createId(idsRef.current.length)];\n store.pushItem(path, value);\n },\n prepend: (value: Item) => {\n idsRef.current = [createId(0), ...idsRef.current];\n store.prependItem(path, value);\n },\n insert: (index: number, value: Item) => {\n const newIds = [...idsRef.current];\n newIds.splice(index, 0, createId(index));\n idsRef.current = newIds;\n store.insertItem(path, index, value);\n },\n remove: (index: number) => {\n idsRef.current = idsRef.current.filter((_, i) => i !== index);\n store.removeItem(path, index);\n },\n move: (from: number, to: number) => {\n const newIds = [...idsRef.current];\n const [item] = newIds.splice(from, 1);\n newIds.splice(to, 0, item);\n idsRef.current = newIds;\n store.moveItem(path, from, to);\n },\n swap: (indexA: number, indexB: number) => {\n const newIds = [...idsRef.current];\n [newIds[indexA], newIds[indexB]] = [newIds[indexB], newIds[indexA]];\n idsRef.current = newIds;\n store.swapItems(path, indexA, indexB);\n },\n replace: (items: Item[]) => {\n idsRef.current = items.map((_, index) => createId(index));\n store.setField(\n path as unknown as BitPath<TForm>,\n items as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n clear: () => {\n idsRef.current = [];\n store.setField(\n path as unknown as BitPath<TForm>,\n [] as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n }),\n [store, path, createId],\n );\n\n const fields = useMemo(\n () =>\n (data as Item[]).map((item: Item, index: number) => ({\n key: idsRef.current[index] || `temp-${index}`,\n value: item,\n index,\n })),\n [data],\n );\n\n return {\n fields,\n length: data.length,\n ...methods,\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ function e(t){return t!=null&&typeof t=="object"&&"target"in t}var r=(t,n)=>t==null||t===""?"":n?n.format(t):String(t),i=(t,n)=>n?n.parse(String(t??"")):t;export{e as a,r as b,i as c};
2
+ //# sourceMappingURL=chunk-3NUJVIAM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/mask/field-binding.ts"],"sourcesContent":["import type { BitMask } from \"./types\";\n\n/**\n * Tipo de entrada aceito pelos handlers de campo.\n * Cobre eventos nativos (`e.target.value`), eventos sintéticos e valores diretos.\n * Definido aqui para ser compartilhado entre todos os frameworks.\n */\nexport type BitFieldInputEvent =\n | { target?: { value?: string | number | null } }\n | string\n | number\n | null\n | undefined;\n\n/**\n * Type guard: verifica se o valor de entrada é um objeto de evento\n * (com propriedade `target`), diferenciando-o de um valor direto.\n */\nexport function isBitFieldInputEventObject(\n value: BitFieldInputEvent,\n): value is Extract<\n BitFieldInputEvent,\n { target?: { value?: string | number | null } }\n> {\n return value != null && typeof value === \"object\" && \"target\" in value;\n}\n\nexport const formatMaskedValue = (value: unknown, mask?: BitMask): string => {\n if (value === undefined || value === null || value === \"\") {\n return \"\";\n }\n\n return mask ? mask.format(value) : String(value);\n};\n\nexport const parseMaskedInput = (value: unknown, mask?: BitMask): unknown => {\n if (!mask) {\n return value;\n }\n\n return mask.parse(String(value ?? \"\"));\n};\n"],"mappings":"AAkBO,SAASA,EACdC,EAIA,CACA,OAAOA,GAAS,MAAQ,OAAOA,GAAU,UAAY,WAAYA,CACnE,CAEO,IAAMC,EAAoB,CAACD,EAAgBE,IACrBF,GAAU,MAAQA,IAAU,GAC9C,GAGFE,EAAOA,EAAK,OAAOF,CAAK,EAAI,OAAOA,CAAK,EAGpCG,EAAmB,CAACH,EAAgBE,IAC1CA,EAIEA,EAAK,MAAM,OAAOF,GAAS,EAAE,CAAC,EAH5BA","names":["isBitFieldInputEventObject","value","formatMaskedValue","mask","parseMaskedInput"]}
@@ -0,0 +1,2 @@
1
+ function h(s){if(s===null||typeof s!="object")return s;if(typeof structuredClone=="function")return structuredClone(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(Array.isArray(s))return s.map(t=>h(t));let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=h(s[t]));return e}function P(s,e){if(e===void 0)return h(s);if(e===null||typeof e!="object"||e instanceof Date||e instanceof RegExp||Array.isArray(e))return h(e);let t=s&&typeof s=="object"&&!Array.isArray(s)?h(s):{};for(let i of Object.keys(e)){let r=e[i],n=t[i];if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp)){t[i]=P(n,r);continue}t[i]=h(r)}return t}function S(s,e){return s===e?!0:s===null||typeof s!="object"||e===null||typeof e!="object"?!1:m(s,e)}function m(s,e){if(s===e)return!0;if(s===null||typeof s!="object"||e===null||typeof e!="object")return!1;if(s instanceof Date&&e instanceof Date)return s.getTime()===e.getTime();if(s instanceof RegExp&&e instanceof RegExp)return s.toString()===e.toString();let t=Object.keys(s),i=Object.keys(e);if(t.length!==i.length)return!1;for(let r of t)if(!Object.prototype.hasOwnProperty.call(e,r)||!m(s[r],e[r]))return!1;return!0}function N(s,e,t="",i=new Set){if(S(s,e))return i;if(s===null||typeof s!="object"||e===null||typeof e!="object")return t&&i.add(t),i;if(Array.isArray(s)||Array.isArray(e))return!S(s,e)&&t&&i.add(t),i;let r=new Set;for(let n of Object.keys(s||{}))r.add(n);for(let n of Object.keys(e||{}))r.add(n);for(let n of r){let o=t?`${t}.${n}`:n;N(s?.[n],e?.[n],o,i)}return i}var ie=1e3,B=new Map;function _(s){let e=B.get(s);if(e)return e;let t=s.split(".");return B.size>=ie&&B.clear(),B.set(s,t),t}function p(s,e){if(!e)return s;let t=_(e),i=s;for(let r of t){if(i==null)return;i=i[r]}return i}function y(s,e,t){if(!e)return t;let i=_(e),r=Array.isArray(s)?[...s]:{...s},n=r;for(let o=0;o<i.length-1;o++){let a=i[o],l=i[o+1],d=Number(l),c=Number.isInteger(d)&&String(d)===l,u=n[a];u==null?n[a]=c?[]:{}:n[a]=Array.isArray(u)?[...u]:{...u},n=n[a]}return n[i[i.length-1]]=t,r}function W(s,e){if(e.length===0)return s;let t=Array.isArray(s)?[...s]:{...s},i=new WeakSet;t&&typeof t=="object"&&i.add(t);for(let[r,n]of e){let o=_(r),a=t;for(let l=0;l<o.length-1;l++){let d=o[l],c=o[l+1],u=Number(c),g=Number.isInteger(u)&&String(u)===c,f=a[d];f==null?(a[d]=g?[]:{},i.add(a[d])):typeof f=="object"?i.has(f)||(a[d]=Array.isArray(f)?[...f]:{...f},i.add(a[d])):(a[d]=g?[]:{},i.add(a[d])),a=a[d]}a[o[o.length-1]]=n}return t}function re(s,e){let t={},i=`${e}.`;for(let r in s)r!==e&&!r.startsWith(i)&&(t[r]=s[r]);return t}function E(s,e,t){let i={},r={},n={},o=new Set;Object.keys(s.errors).forEach(l=>o.add(l)),Object.keys(s.touched).forEach(l=>o.add(l)),Object.keys(s.isValidating).forEach(l=>o.add(l));let a=`${e}.`;for(let l of o){let d=se(l,a,t);d&&(Object.prototype.hasOwnProperty.call(s.errors,l)&&(i[d]=s.errors[l]),Object.prototype.hasOwnProperty.call(s.touched,l)&&(r[d]=s.touched[l]),Object.prototype.hasOwnProperty.call(s.isValidating,l)&&(n[d]=s.isValidating[l]))}return{errors:i,touched:r,isValidating:n}}function se(s,e,t){if(!s.startsWith(e))return s;let r=s.substring(e.length).split("."),n=parseInt(r[0],10),o=t(n);if(o===null)return null;let a=r.slice(1).join(".");return a?`${e}${o}.${a}`:`${e}${o}`}function G(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let e=s.errors??s;return typeof e!="object"||e===null||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string"))}function ne(s){return G(s)?s.errors??s:{}}var $=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;$.__BIT_FORM__||($.__BIT_FORM__={stores:{},listeners:new Set,dispatch(s,e){this.listeners.forEach(t=>t(s,e))},subscribe(s){return this.listeners.add(s),()=>{this.listeners.delete(s)}}});var T=$.__BIT_FORM__;function ae(){return`bit-form-${Math.random().toString(36).slice(2,9)}`}function J(s={}){let e=s.initialValues??{},t=s.validation,i=s.history,r=s.name?`bit-form:${s.name}:draft`:"bit-form:draft",n={enabled:s.persist?.enabled??!1,key:s.persist?.key??r,storage:s.persist?.storage,autoSave:s.persist?.autoSave??!0,debounceMs:s.persist?.debounceMs??300,mode:s.persist?.mode??"values",serialize:s.persist?.serialize??JSON.stringify,deserialize:s.persist?.deserialize??(o=>JSON.parse(o)),onError:s.persist?.onError};return{name:s.name,initialValues:h(e),resolver:t?.resolver,validationDelay:t?.delay??300,enableHistory:i?.enabled??!1,historyLimit:i?.limit??15,masks:s.masks,fields:s.fields,devTools:s.devTools,persist:n,idFactory:s.idFactory??ae,plugins:s.plugins??[]}}var V=class{fieldConfigs=new Map;dependencies=new Map;hiddenFields=new Set;conditionalVisibilityPaths=new Set;requiredPathsByDependency=new Map;requiredConditionalPaths=new Set;requiredEvaluationCache=new WeakMap;requiredEvaluationCacheDirty=!1;getFieldConfig(e){return this.fieldConfigs.get(e)}forEachFieldConfig(e){this.fieldConfigs.forEach((t,i)=>e(t,i))}hasFieldConfig(e){return this.fieldConfigs.has(e)}getHiddenFields(){return this.hiddenFields}register(e,t,i){this.fieldConfigs.set(e,t),t.conditional?.showIf&&this.conditionalVisibilityPaths.add(e);let r=t.conditional?.dependsOn;r&&r.forEach(o=>{this.dependencies.has(o)||this.dependencies.set(o,new Set),this.dependencies.get(o).add(e)});let n=t.conditional?.dependsOn;n&&t.conditional?.requiredIf&&(this.requiredConditionalPaths.add(e),n.forEach(o=>{this.requiredPathsByDependency.has(o)||this.requiredPathsByDependency.set(o,new Set),this.requiredPathsByDependency.get(o).add(e)})),this.requiredEvaluationCacheDirty=!0,this.evaluateFieldCondition(e,i)}isHidden(e){return this.hiddenFields.has(e)}isRequired(e,t){let i=this.fieldConfigs.get(e);if(!i||this.isHidden(e)||!i.conditional?.requiredIf)return!1;this.requiredEvaluationCacheDirty&&(this.requiredEvaluationCache=new WeakMap,this.requiredEvaluationCacheDirty=!1);let r=this.requiredEvaluationCache.get(t);if(r||(r=new Map,this.requiredEvaluationCache.set(t,r)),r.has(e))return r.get(e);let n=!!i.conditional.requiredIf(t);return r.set(e,n),n}getRequiredErrors(e){let t={};return this.requiredConditionalPaths.forEach(i=>{let r=this.fieldConfigs.get(i);if(r&&this.isRequired(i,e)){let n=p(e,i);this.isEmpty(n)&&(t[i]=r.conditional?.requiredMessage??"required field")}}),t}evaluateAll(e){this.conditionalVisibilityPaths.forEach(t=>{this.evaluateFieldCondition(t,e)})}updateDependencies(e,t){let i=[],r=[e],n=new Set;for(;r.length>0;){let o=r.shift();if(n.has(o))continue;n.add(o);let a=this.dependencies.get(o);a&&a.forEach(l=>{let d=this.isHidden(l);this.evaluateFieldCondition(l,t);let c=this.isHidden(l);d!==c&&i.push(l),r.push(l)})}return i}unregister(e){let t=this.fieldConfigs.get(e);this.fieldConfigs.delete(e),this.hiddenFields.delete(e),this.conditionalVisibilityPaths.delete(e),this.dependencies.delete(e),this.requiredEvaluationCacheDirty=!0,this.requiredConditionalPaths.delete(e),t?.conditional?.dependsOn?.forEach(i=>{let r=this.requiredPathsByDependency.get(i);r&&(r.delete(e),r.size===0&&this.requiredPathsByDependency.delete(i))}),this.dependencies.forEach(i=>{i.delete(e)})}unregisterPrefix(e){let t=[];return this.fieldConfigs.forEach((i,r)=>{r.startsWith(e)&&t.push([r,i])}),t.forEach(([i])=>this.unregister(i)),t}evaluateFieldCondition(e,t){let r=this.fieldConfigs.get(e)?.conditional?.showIf;r&&(r(t)?this.hiddenFields.delete(e):this.hiddenFields.add(e))}isEmpty(e){return e==null||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0}};var C=class s{constructor(e){this.getComputedEntries=e}static MIN_PASSES=4;computedDependencyCache=new Map;reverseDepsCache=null;childDepsIndex=null;invalidateReverseDeps(){this.reverseDepsCache=null,this.childDepsIndex=null}getReverseDependencies(e){if(this.reverseDepsCache)return this.reverseDepsCache;let t=new Map;for(let r of e){let n=this.getDependenciesForEntry(r);for(let o of n){let a=t.get(o);a||(a=new Set,t.set(o,a)),a.add(r.path)}}let i=new Map;for(let r of t.keys()){let n=r.split(".");for(let o=1;o<n.length;o++){let a=n.slice(0,o).join("."),l=i.get(a);l||(l=new Set,i.set(a,l)),l.add(r)}}return this.reverseDepsCache=t,this.childDepsIndex=i,t}apply(e,t){let i=this.normalizeEntries(this.getComputedEntries());if(i.length===0)return e;let r=this.resolveEntriesToRun(i,t),n=r.entries;if(n.length===0)return e;let o=e,a=r.requiresStabilizationPasses?Math.max(s.MIN_PASSES,n.length*2):1;for(let l=0;l<a;l++){let d=!1;for(let c of n){let{newValue:u,trackedDependencies:g}=this.computeWithTracking(c,o,r.shouldTrackDependencies),f=p(o,c.path);if(m(f,u)||(o=y(o,c.path,u),d=!0),g){let L=this.computedDependencyCache.get(c.path);this.computedDependencyCache.set(c.path,g),(!L||L.size!==g.size||Array.from(L).some(te=>!g.has(te)))&&this.invalidateReverseDeps()}}if(!d)break;if(r.requiresStabilizationPasses&&l===a-1)throw new Error("BitStore: computed fields did not stabilize. Check for cyclic computed definitions.")}return o}resolveEntriesToRun(e,t){if(!t||t.length===0||t.includes("*"))return{entries:this.orderEntries(e),shouldTrackDependencies:!0,requiresStabilizationPasses:!0};let i=this.getReverseDependencies(e),r=!1;for(let l of e)this.getDependenciesForEntry(l).length===0&&(r=!0);let n=new Set,o=[...t];for(;o.length>0;){let l=o.shift(),d=this.getDependentsForPath(i,l);if(d)for(let c of d)n.has(c)||(n.add(c),o.push(c))}if(n.size===0)return{entries:[],shouldTrackDependencies:r,requiresStabilizationPasses:!1};let a=e.filter(l=>n.has(l.path));return{entries:this.orderEntries(a),shouldTrackDependencies:r,requiresStabilizationPasses:r}}normalizeEntries(e){return e.length===0||!Array.isArray(e[0])?e:e.map(t=>Array.isArray(t)?{path:t[0],compute:t[1]}:t)}getDependenciesForEntry(e){return e.dependsOn??Array.from(this.computedDependencyCache.get(e.path)??[])}orderEntries(e){if(e.length<=1)return e;let t=new Map(e.map(a=>[a.path,a])),i=new Map,r=new Map;e.forEach(a=>i.set(a.path,0)),e.forEach(a=>{this.getDependenciesForEntry(a).forEach(d=>{if(!t.has(d))return;let c=r.get(d)??new Set;c.has(a.path)||(c.add(a.path),r.set(d,c),i.set(a.path,(i.get(a.path)??0)+1))})});let n=e.filter(a=>(i.get(a.path)??0)===0).map(a=>a.path),o=[];for(;n.length>0;){let a=n.shift();o.push(a);let l=r.get(a);l&&l.forEach(d=>{let c=(i.get(d)??0)-1;i.set(d,c),c===0&&n.push(d)})}if(o.length!==e.length)throw new Error("BitStore: cyclic computed dependencies detected. Check computedDependsOn definitions.");return o.map(a=>t.get(a))}getDependentsForPath(e,t){let i=new Set,r=a=>{let l=e.get(a);l&&l.forEach(d=>i.add(d))};r(t);let n=t.split(".");for(;n.length>1;)n.pop(),r(n.join("."));let o=this.childDepsIndex?.get(t);if(o)for(let a of o)r(a);return i}computeWithTracking(e,t,i){let r=this.getDependenciesForEntry(e);if(!i||r.length>0)return{newValue:e.compute(t),trackedDependencies:null};let n=new Set,o=this.createTrackedValues(t,n);return{newValue:e.compute(o),trackedDependencies:n}}createTrackedValues(e,t){let i=(r,n)=>!r||typeof r!="object"?r:new Proxy(r,{get:(o,a)=>{if(typeof a!="string")return Reflect.get(o,a);let l=n?`${n}.${a}`:a;t.add(l);let d=Reflect.get(o,a);return i(d,l)}});return i(e,"")}};var F=class{dirtyPaths=new Set;dirtyPathIndex=new Set;dirtyPrefixRefCount=new Map;updateForPath(e,t,i){this.removeDirtyChildren(e);let r=p(t,e),n=p(i,e);return S(r,n)?this.removeDirtyPath(e):this.addDirtyPath(e),this.dirtyPaths.size>0}rebuild(e,t){return this.dirtyPaths=N(e,t),this.dirtyPrefixRefCount.clear(),this.rebuildIndex(),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear(),this.dirtyPathIndex.clear(),this.dirtyPrefixRefCount.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}isPathDirty(e){if(this.dirtyPathIndex.has(e))return!0;let t=e.split(".");for(;t.length>1;)if(t.pop(),this.dirtyPaths.has(t.join(".")))return!0;return!1}buildDirtyValues(e){if(this.dirtyPaths.size===0)return{};let t={},i=new Set;for(let r of this.dirtyPaths){let n=r.match(/^(.+)\.\d+/);if(n){let o=n[1];if(i.has(o))continue;i.add(o);let a=p(e,o);t=y(t,o,a)}else{let o=p(e,r);t=y(t,r,o)}}return t}rebuildIndex(){let e=new Set,t=new Map;for(let i of this.dirtyPaths)this.forEachPathPrefix(i,r=>{e.add(r),t.set(r,(t.get(r)??0)+1)});this.dirtyPathIndex=e,this.dirtyPrefixRefCount=t}removeDirtyChildren(e){let t=[];for(let i of this.dirtyPaths)i.startsWith(`${e}.`)&&t.push(i);t.forEach(i=>this.removeDirtyPath(i))}addDirtyPath(e){this.dirtyPaths.has(e)||(this.dirtyPaths.add(e),this.forEachPathPrefix(e,t=>{this.dirtyPathIndex.add(t),this.dirtyPrefixRefCount.set(t,(this.dirtyPrefixRefCount.get(t)??0)+1)}))}removeDirtyPath(e){this.dirtyPaths.has(e)&&(this.dirtyPaths.delete(e),this.forEachPathPrefix(e,t=>{let i=(this.dirtyPrefixRefCount.get(t)??0)-1;if(i<=0){this.dirtyPrefixRefCount.delete(t),this.dirtyPathIndex.delete(t);return}this.dirtyPrefixRefCount.set(t,i)}))}forEachPathPrefix(e,t){let i=e.split("."),r="";for(let n of i)r=r?`${r}.${n}`:n,t(r)}};var x=class{constructor(e){this.getState=e}listeners=new Set;selectorListeners=new Set;pathScopedSubscriptions=new Map;pathSelectorIndex=new Map;expandedPathCache=new Map;notifyScopedSubscribers=new Set;subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}subscribeSelector(e,t,i,r){let n=e(this.getState()),o={notify:d=>{let c=e(d);r(n,c)||(n=c,t(c))}},a=i?.autoTrackPaths?this.collectTrackedSelectorPaths(e):[],l=this.normalizeSubscriptionPaths([...i?.paths??[],...a]);return l.length>0?(this.pathScopedSubscriptions.set(o,l),l.forEach(d=>{this.expandPathForIndexing(d).forEach(c=>{let u=this.pathSelectorIndex.get(c)??new Set;u.add(o),this.pathSelectorIndex.set(c,u)})})):this.selectorListeners.add(o),i?.emitImmediately&&t(n),()=>{this.selectorListeners.delete(o);let d=this.pathScopedSubscriptions.get(o);d&&(d.forEach(c=>{this.expandPathForIndexing(c).forEach(u=>{let g=this.pathSelectorIndex.get(u);g&&(g.delete(o),g.size===0&&this.pathSelectorIndex.delete(u))})}),this.pathScopedSubscriptions.delete(o))}}notify(e,t){if(this.listeners.forEach(r=>r()),this.selectorListeners.forEach(r=>{r.notify(e)}),this.pathScopedSubscriptions.size===0)return;if(!t||t.length===0||t.includes("*")){this.pathScopedSubscriptions.forEach((r,n)=>{n.notify(e)});return}this.collectSubscribersForChangedPaths(t).forEach(r=>{r.notify(e)})}destroy(){this.listeners.clear(),this.selectorListeners.clear(),this.pathScopedSubscriptions.clear(),this.pathSelectorIndex.clear(),this.expandedPathCache.clear(),this.notifyScopedSubscribers.clear()}normalizeSubscriptionPaths(e){if(!e||e.length===0)return[];let t=new Set,i=[];for(let r of e){let n=r.trim();n.length===0||t.has(n)||(t.add(n),i.push(n))}return i}collectTrackedSelectorPaths(e){let t=new Set,i=(n,o)=>!n||typeof n!="object"?n:new Proxy(n,{get:(a,l)=>{if(typeof l!="string")return Reflect.get(a,l);let d=o?`${o}.${l}`:l;t.add(d);let c=Reflect.get(a,l);return i(c,d)}}),r=new Proxy(this.getState(),{get:(n,o)=>{if(typeof o!="string")return Reflect.get(n,o);let a=Reflect.get(n,o);return o==="values"?i(a,""):a}});try{return e(r),Array.from(t)}catch{return[]}}collectSubscribersForChangedPaths(e){let t=this.notifyScopedSubscribers;t.clear();let i=n=>{let o=this.pathSelectorIndex.get(n);o&&o.forEach(a=>t.add(a))};return this.normalizeSubscriptionPaths(e).forEach(n=>{i(n);let o=n.split(".");for(;o.length>1;)o.pop(),i(o.join("."))}),t}expandPathForIndexing(e){let t=this.expandedPathCache.get(e);if(t)return t;let i=e.split("."),r=[];for(let n=1;n<=i.length;n++)r.push(i.slice(0,n).join("."));return this.expandedPathCache.set(e,r),r}};function oe(s){let e=!1;for(let i of Object.values(s))if(i===void 0){e=!0;break}if(!e)return s;let t={};return Object.entries(s).forEach(([i,r])=>{r!==void 0&&(t[i]=r)}),t}function le(s){for(let e in s)return!0;return!1}function K(s){let{currentState:e,partialState:t,changedPaths:i,applyComputedValues:r}=s,n={...e,...t},o=!!t.values;t.values&&(n.values=r(t.values)),t.errors&&(n.errors=oe(t.errors),n.isValid=!le(n.errors));let a=i&&i.length>0?i:void 0,l=de(t,!a),d=ce(a,l);return{nextState:n,changedPaths:d,valuesChanged:o}}function de(s,e){if(e&&s.values)return["*"];let t=new Set,i=[s.errors,s.touched,s.isValidating];for(let r of i)if(r)for(let n in r)t.add(n);return s.persist&&t.add("persist"),"isValid"in s&&t.add("isValid"),"isDirty"in s&&t.add("isDirty"),"isSubmitting"in s&&t.add("isSubmitting"),t.size>0?Array.from(t):void 0}function ce(s,e){if(!s?.length)return e;if(!e?.length)return s;let t=new Set;for(let i of s)t.add(i);for(let i of e)t.add(i);return Array.from(t)}function ue(s){return typeof s=="boolean"?{enabled:s,mode:"local"}:{enabled:!!s,mode:s?.mode??"local",url:s?.url}}function X(s){let e=ue(s);return e.enabled?{name:"bit-devtools",setup:()=>{let t=null,i=!1;return(async()=>{try{if(e.mode==="remote"){let{setupRemoteBridge:r}=await import("./devtools/bridge.js");t=r(e.url||"ws://localhost:3000")}else{let{initDevTools:r}=await import("./devtools/index.js"),n=r();t=n&&typeof n.destroy=="function"?n.destroy:null}i&&t&&(t(),t=null)}catch{}})(),()=>{i=!0,t&&(t(),t=null)}}}:null}function he(){if(typeof globalThis>"u")return;let s=globalThis.localStorage;if(s)return{getItem:e=>s.getItem(e),setItem:(e,t)=>s.setItem(e,t),removeItem:e=>s.removeItem(e)}}var w=class{constructor(e,t,i,r){this.config=e;this.getValues=t;this.getDirtyValues=i;this.applyRestoredValues=r}timer;getStorage(){return this.config.storage||he()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(e){this.config.onError?.(e)}async saveNow(){if(!this.canPersist())return;let e=this.getStorage();if(e)try{let t=this.config.mode==="dirtyValues"?this.getDirtyValues():this.getValues(),i=this.config.serialize(t);await e.setItem(this.config.key,i)}catch(t){this.handleError(t)}}queueSave(){!this.canPersist()||!this.config.autoSave||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.saveNow()},this.config.debounceMs))}async restore(){if(!this.canPersist())return!1;let e=this.getStorage();if(!e)return!1;try{let t=await e.getItem(this.config.key);if(!t)return!1;let i=this.config.deserialize(t);return!i||typeof i!="object"?!1:(this.applyRestoredValues(i),!0)}catch(t){return this.handleError(t),!1}}async clear(){if(!this.canPersist())return;let e=this.getStorage();if(e)try{await e.removeItem(this.config.key)}catch(t){this.handleError(t)}}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}};var D=class{constructor(e,t){this.plugins=e;this.contextFactory=t}teardownFns=[];notifyingError=!1;setupAll(){this.plugins.forEach(e=>{if(e.setup)try{let t=e.setup(this.contextFactory());typeof t=="function"&&this.teardownFns.push(t)}catch(t){this.reportError("setup",t,void 0,e.name)}})}async beforeValidate(e){await this.emitHook("beforeValidate",e)}async afterValidate(e){await this.emitHook("afterValidate",e)}async beforeSubmit(e){await this.emitHook("beforeSubmit",e)}async afterSubmit(e){await this.emitHook("afterSubmit",e)}onFieldChange(e){this.plugins.forEach(t=>{let i=t.hooks?.onFieldChange;if(i)try{let r=i(e,this.contextFactory());Promise.resolve(r).catch(n=>{this.reportError("onFieldChange",n,e,t.name)})}catch(r){this.reportError("onFieldChange",r,e,t.name)}})}async reportError(e,t,i,r){if(this.notifyingError)return;this.notifyingError=!0;let n=this.contextFactory(),o={source:e,pluginName:r,error:t,event:i,values:n.getState().values,state:n.getState()};for(let a of this.plugins){let l=a.hooks?.onError;if(l)try{await l(o,n)}catch{}}this.notifyingError=!1}destroy(){for(let e=this.teardownFns.length-1;e>=0;e-=1){let t=this.teardownFns[e];try{t()}catch(i){this.reportError("teardown",i)}}this.teardownFns=[]}async emitHook(e,t){let i=this.contextFactory();for(let r of this.plugins){let n=r.hooks?.[e];if(n)try{await n(t,i)}catch(o){await this.reportError(e,o,t,r.name)}}}};var k=class{constructor(e,t,i,r){this.storeId=e;this.storeInstance=t;this.persistManager=i;this.pluginManager=r}initialize(){this.pluginManager.setupAll(),T.stores[this.storeId]=this.storeInstance}onStateUpdated(e,t){t&&this.persistManager.queueSave(),T.dispatch(this.storeId,e)}restorePersisted(){return this.persistManager.restore()}savePersistedNow(){return this.persistManager.saveNow()}clearPersisted(){return this.persistManager.clear()}beforeValidate(e){return this.pluginManager.beforeValidate(e)}afterValidate(e){return this.pluginManager.afterValidate(e)}beforeSubmit(e){return this.pluginManager.beforeSubmit(e)}afterSubmit(e){return this.pluginManager.afterSubmit(e)}onFieldChange(e){this.pluginManager.onFieldChange(e)}reportOperationalError(e){return this.pluginManager.reportError(e.source,e.error,e.payload)}destroy(){this.persistManager.destroy(),this.pluginManager.destroy(),delete T.stores[this.storeId]}};var v=class{constructor(e){this.steps=e}async run(e){for(let t of this.steps){if(e.halted)break;await t.run(e)}}},M=class{constructor(e){this.steps=e}run(e){for(let t of this.steps){if(e.halted)break;t.run(e)}}};function A(s){for(let e in s)return!0;return!1}var R=class{constructor(e){this.store=e;this.validationPipeline=new v([{name:"validate:resolve-target-fields",run:t=>this.resolveTargetFields(t)},{name:"validate:before-hooks",run:async t=>this.runBeforeValidateHooks(t)},{name:"validate:resolver",run:async t=>this.runResolver(t)},{name:"validate:required-and-hidden",run:t=>this.applyRequiredAndHiddenRules(t)},{name:"validate:abort-check",run:async t=>this.abortIfOutdated(t)},{name:"validate:commit-scoped",run:async t=>this.commitScopedValidation(t)},{name:"validate:commit-global",run:async t=>this.commitGlobalValidation(t)}])}validationTimeout;currentValidationId=0;asyncEpoch=0;validatingCount=0;pendingScopeFields=null;asyncTimers=new Map;asyncRequests=new Map;asyncErrors=new Map;validationPipeline;updateFieldValidating(e,t){let i=this.store.getState();if(!!i.isValidating[e]===t)return;let n={...i.isValidating};t?(n[e]=!0,this.validatingCount+=1):(delete n[e],this.validatingCount=Math.max(0,this.validatingCount-1)),this.store.internalUpdateState({isValidating:n})}cancelFieldAsync(e){let t=this.asyncTimers.get(e);t&&(clearTimeout(t),this.asyncTimers.delete(e)),this.asyncRequests.set(e,(this.asyncRequests.get(e)||0)+1)}cleanupField(e){this.cancelFieldAsync(e),this.asyncTimers.delete(e),this.asyncRequests.delete(e),this.asyncErrors.delete(e),this.updateFieldValidating(e,!1)}cleanupPrefix(e){for(let t of this.asyncTimers.keys())(t===e||t.startsWith(`${e}.`))&&this.cleanupField(t)}beginExternalValidation(e){this.cancelFieldAsync(e),this.updateFieldValidating(e,!0)}endExternalValidation(e){this.updateFieldValidating(e,!1)}async setExternalError(e,t){if(t){this.asyncErrors.set(e,t),this.store.setError(e,t);return}if(this.asyncErrors.delete(e),this.store.validate){await this.store.validate({scopeFields:[e]});return}let i={...this.store.getState().errors};delete i[e],this.store.internalUpdateState({errors:i,isValid:!A(i)})}handleAsync(e,t){let i=this.store.getFieldConfig(e),r=i?.validation?.asyncValidate;if(!r){this.updateFieldValidating(e,!1);return}let n=this.asyncTimers.get(e);n&&clearTimeout(n);let o=i.validation?.asyncValidateDelay??500;this.updateFieldValidating(e,!0),this.asyncTimers.set(e,setTimeout(async()=>{this.asyncTimers.delete(e);let a=this.asyncEpoch,l=(this.asyncRequests.get(e)||0)+1;this.asyncRequests.set(e,l);try{let d=await r(t,this.store.getState().values);if(this.asyncRequests.get(e)!==l||a!==this.asyncEpoch)return;if(d)this.asyncErrors.set(e,d),this.store.setError(e,d);else if(this.asyncErrors.delete(e),this.store.validate)await this.store.validate({scopeFields:[e]});else{let c={...this.store.getState().errors};delete c[e],this.store.internalUpdateState({errors:c,isValid:!A(c)})}}finally{this.asyncRequests.get(e)===l&&a===this.asyncEpoch&&this.updateFieldValidating(e,!1)}},o))}hasValidationsInProgress(e){let t=this.store.getState();return e&&e.length>0?e.some(i=>!!t.isValidating[i]):this.validatingCount>0}trigger(e,t){this.validationTimeout&&clearTimeout(this.validationTimeout);let i=this.store.config.validationDelay??300,r=t?.forceDebounce?Math.max(1,i):i;if(r>0){if(e&&e.length>0)if(!this.pendingScopeFields)this.pendingScopeFields=new Set(e);else for(let o of e)this.pendingScopeFields.add(o);else this.pendingScopeFields=null;let n=this.pendingScopeFields?Array.from(this.pendingScopeFields):void 0;this.validationTimeout=setTimeout(()=>{this.pendingScopeFields=null,this.validate({scopeFields:n})},r)}else this.pendingScopeFields=null,this.validate({scopeFields:e})}async validate(e){let t={options:e,validationId:++this.currentValidationId,currentState:this.store.getState(),targetFields:e?.scopeFields,allErrors:{},isValid:!0,result:!0,aborted:!1};return await this.validationPipeline.run(t),t.result}clear(e){let t=this.asyncTimers.get(e);t&&clearTimeout(t),this.asyncTimers.delete(e),this.updateFieldValidating(e,!1),this.asyncErrors.delete(e)}cancelAll(){this.asyncEpoch+=1,this.validatingCount=0,this.pendingScopeFields=null,this.validationTimeout&&clearTimeout(this.validationTimeout),this.asyncTimers.forEach(e=>clearTimeout(e)),this.asyncTimers.clear(),this.asyncRequests.clear(),this.asyncErrors.clear(),this.store.internalUpdateState({isValidating:{}})}resolveTargetFields(e){if(e.options?.scope){let t=this.store.getScopeFields(e.options.scope);t.length>0&&(e.targetFields=t)}}async runBeforeValidateHooks(e){await this.store.emitBeforeValidate({values:e.currentState.values,state:e.currentState,scope:e.options?.scope,scopeFields:e.targetFields})}async runResolver(e){e.allErrors=this.store.config.resolver?await this.store.config.resolver(e.currentState.values,{scopeFields:e.targetFields}):{}}applyRequiredAndHiddenRules(e){let t=this.store.getRequiredErrors(e.currentState.values);e.allErrors={...e.allErrors,...t},this.store.getHiddenFields().forEach(i=>{delete e.allErrors[i],this.asyncErrors.delete(i)})}async abortIfOutdated(e){e.validationId!==this.currentValidationId&&(e.aborted=!0,e.result=e.currentState.isValid,await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:e.options?.scope,scopeFields:e.targetFields,errors:this.store.getState().errors,result:e.currentState.isValid,aborted:!0}),e.halted=!0)}async commitScopedValidation(e){if(!e.targetFields)return;let t={...e.currentState.errors};e.targetFields.forEach(i=>{e.allErrors[i]?t[i]=e.allErrors[i]:this.asyncErrors.has(i)?t[i]=this.asyncErrors.get(i):delete t[i]}),e.isValid=!A(t),e.result=e.targetFields.every(i=>!e.allErrors[i]&&!this.asyncErrors.has(i)),this.store.internalUpdateState({errors:t,isValid:e.isValid}),await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:e.options?.scope,scopeFields:e.targetFields,errors:t,result:e.result}),e.halted=!0}async commitGlobalValidation(e){e.allErrors={...Object.fromEntries(this.asyncErrors.entries()),...e.allErrors},e.isValid=!A(e.allErrors),e.result=e.isValid,this.store.internalUpdateState({errors:e.allErrors,isValid:e.isValid}),await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:e.options?.scope,scopeFields:e.targetFields,errors:e.allErrors,result:e.isValid})}};var I=class{constructor(e){this.store=e;this.fieldUpdatePipeline=new M([{name:"field:clear-current-error",run:t=>this.clearCurrentError(t)},{name:"field:update-dependencies",run:t=>this.updateDependencies(t)},{name:"field:update-dirty",run:t=>this.updateDirtyState(t)},{name:"field:commit-state",run:t=>this.commitFieldState(t)},{name:"field:emit-change",run:t=>this.emitFieldChange(t)},{name:"field:trigger-validate",run:t=>this.triggerResolverValidation(t)},{name:"field:trigger-async-validate",run:t=>this.triggerAsyncValidation(t)}]),this.submitPipeline=new v([{name:"submit:start",run:async t=>this.startSubmit(t)},{name:"submit:invalid",run:async t=>this.handleInvalidSubmit(t)},{name:"submit:prepare",run:t=>this.prepareSubmitValues(t)},{name:"submit:before-hooks",run:async t=>this.runBeforeSubmitHooks(t)},{name:"submit:user-handler",run:async t=>this.runSubmitHandler(t)},{name:"submit:after-hooks",run:async t=>this.runAfterSubmitHooks(t)}])}fieldUpdatePipeline;submitPipeline;updateField(e,t,i={origin:"setField"}){let r=this.store.getState(),n={path:e,value:t,meta:i,previousValue:p(r.values,e),nextValues:y(r.values,e,t),nextErrors:r.errors,hasMutatedErrors:!1,toggledFields:[],isDirty:!1};this.fieldUpdatePipeline.run(n)}replaceValues(e,t="replaceValues"){let i=this.store.getState().values,r=h(e);this.store.cancelAllValidations(),this.store.evaluateAllDependencies(r);let n=this.store.rebuildDirtyState(r,this.store.config.initialValues);this.store.internalUpdateState({values:r,errors:{},isValidating:{},isValid:!0,isDirty:n,isSubmitting:!1},["*"]),this.store.internalSaveSnapshot(),this.store.validateNow(),this.store.emitFieldChange({path:"*",previousValue:i,nextValue:r,values:this.store.getState().values,state:this.store.getState(),meta:{origin:t}})}hydrateValues(e){let t=P(this.store.getState().values,e);this.replaceValues(t,"hydrate")}rebaseValues(e){let t=this.store.getState().values,i=h(e);this.store.config.initialValues=h(i),this.store.cancelAllValidations(),this.store.evaluateAllDependencies(i),this.store.clearDirtyState(),this.store.internalUpdateState({values:i,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1},["*"]),this.store.internalSaveSnapshot(),this.store.validateNow(),this.store.emitFieldChange({path:"*",previousValue:t,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"rebase"}})}async submit(e){if(this.store.getState().isSubmitting||this.store.hasValidationsInProgress())return;this.store.cancelAllValidations();let i={onSuccess:e,isValid:!1,valuesToSubmit:h(this.store.getState().values),dirtyValues:{}};try{await this.submitPipeline.run(i)}catch(r){i.error=r,await this.store.emitOperationalError({source:"submit",error:r}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,error:r}),console.error(r)}finally{this.store.internalUpdateState({isSubmitting:!1})}}reset(){this.store.cancelAllValidations();let e=h(this.store.config.initialValues);this.store.evaluateAllDependencies(e),this.store.clearDirtyState(),this.store.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1},["*"]),this.store.resetHistory(e)}clearCurrentError(e){let t=Object.prototype.hasOwnProperty.call(e.nextErrors,e.path);t&&!e.hasMutatedErrors&&(e.nextErrors={...e.nextErrors},e.hasMutatedErrors=!0),t&&delete e.nextErrors[e.path],this.store.clearFieldValidation(e.path)}updateDependencies(e){e.toggledFields=this.store.updateDependencies(e.path,e.nextValues),e.toggledFields.forEach(t=>{if(this.store.isFieldHidden(t)){let i=Object.prototype.hasOwnProperty.call(e.nextErrors,t);i&&!e.hasMutatedErrors&&(e.nextErrors={...e.nextErrors},e.hasMutatedErrors=!0),i&&delete e.nextErrors[t],this.store.clearFieldValidation(t)}})}updateDirtyState(e){e.isDirty=this.store.updateDirtyForPath(e.path,e.nextValues,this.store.config.initialValues)}commitFieldState(e){this.store.internalUpdateState({values:e.nextValues,errors:e.nextErrors,isDirty:e.isDirty},[e.path,...e.toggledFields])}emitFieldChange(e){this.store.emitFieldChange({path:e.path,previousValue:e.previousValue,nextValue:e.value,values:this.store.getState().values,state:this.store.getState(),meta:e.meta})}triggerResolverValidation(e){this.store.config.resolver&&this.store.triggerValidation([e.path])}triggerAsyncValidation(e){this.store.handleFieldAsyncValidation(e.path,e.value)}async startSubmit(e){this.store.internalUpdateState({isSubmitting:!0}),e.isValid=await this.store.validateNow()}async handleInvalidSubmit(e){if(e.isValid)return;let t=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(t).forEach(r=>{i[r]=!0}),this.store.batchStateUpdates(()=>{this.store.internalUpdateState({touched:i})}),e.dirtyValues=this.store.buildDirtyValues(this.store.getState().values),e.invalid=!0,await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:e.dirtyValues,state:this.store.getState(),success:!1,invalid:!0}),e.halted=!0}prepareSubmitValues(e){let t=[];this.store.getHiddenFields().forEach(i=>{t.push([i,void 0])});for(let[i,r]of this.store.getTransformEntries()){let n=p(e.valuesToSubmit,i);t.push([i,r(n,this.store.getState().values)])}t.length>0&&(e.valuesToSubmit=W(e.valuesToSubmit,t)),e.dirtyValues=this.store.buildDirtyValues(e.valuesToSubmit)}async runBeforeSubmitHooks(e){await this.store.emitBeforeSubmit({values:e.valuesToSubmit,dirtyValues:e.dirtyValues,state:this.store.getState()})}async runSubmitHandler(e){await e.onSuccess(e.valuesToSubmit,e.dirtyValues)}async runAfterSubmitHooks(e){await this.store.emitAfterSubmit({values:e.valuesToSubmit,dirtyValues:e.dirtyValues,state:this.store.getState(),success:!0})}};var q=class{constructor(e,t=15){this.enableHistory=e;this.maxHistory=t}history=[];historyIndex=-1;historySize=0;historyHead=0;saveSnapshot(e){if(!this.enableHistory)return;let t=this.getSnapshotAt(this.historyIndex);if(t&&m(t,e))return;let i=h(e),r=this.getCapacity();this.historyIndex<this.historySize-1&&(this.historySize=this.historyIndex+1);let n=this.historyIndex+1;n<r?(this.history[this.toPhysicalIndex(n)]=i,this.historySize=Math.max(this.historySize,n+1),this.historyIndex=n):(this.historyHead=(this.historyHead+1)%r,this.history[this.toPhysicalIndex(r-1)]=i,this.historySize=r,this.historyIndex=r-1)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.historySize-1:!1}undo(){return this.canUndo?(this.historyIndex--,h(this.getSnapshotAt(this.historyIndex))):null}redo(){return this.canRedo?(this.historyIndex++,h(this.getSnapshotAt(this.historyIndex))):null}reset(e){this.history=[],this.historyIndex=-1,this.historySize=0,this.historyHead=0,this.saveSnapshot(e)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.historySize}}getCapacity(){return Math.max(1,this.maxHistory)}toPhysicalIndex(e){return(this.historyHead+e)%this.getCapacity()}getSnapshotAt(e){if(!(e<0||e>=this.historySize))return this.history[this.toPhysicalIndex(e)]}};var O=class{constructor(e){this.store=e}pushItem(e,t){let i=p(this.store.getState().values,e)||[];this.store.setFieldWithMeta(e,[...i,t],{origin:"array",operation:"push"}),this.store.internalSaveSnapshot()}prependItem(e,t){let i=p(this.store.getState().values,e)||[];this.store.setFieldWithMeta(e,[t,...i],{origin:"array",operation:"prepend"}),this.store.internalSaveSnapshot()}insertItem(e,t,i){let r=[...p(this.store.getState().values,e)||[]];r.splice(t,0,i),this.store.setFieldWithMeta(e,r,{origin:"array",operation:"insert",index:t}),this.store.internalSaveSnapshot()}removeItem(e,t){let i=this.store.getState(),r=p(i.values,e);if(!Array.isArray(r))return;let n=[...r];this.store.unregisterPrefix&&this.store.unregisterPrefix(`${e}.${t}.`);let o=r.filter((c,u)=>u!==t),a=y(i.values,e,o),l=this.store.updateDirtyForPath(e,a,this.store.getConfig().initialValues),d=E(i,e,c=>c===t?null:c>t?c-1:c);this.store.internalUpdateState({values:a,errors:d.errors,touched:d.touched,isValidating:d.isValidating,isDirty:l}),this.store.emitFieldChange({path:e,previousValue:n,nextValue:o,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"remove",index:t}}),this.store.internalSaveSnapshot(),this.revalidate(e)}swapItems(e,t,i){let r=this.store.getState(),n=[...p(r.values,e)||[]],o=[...n];[n[t],n[i]]=[n[i],n[t]];let a=y(r.values,e,n),l=this.store.updateDirtyForPath(e,a,this.store.getConfig().initialValues),d=E(r,e,c=>c===t?i:c===i?t:c);this.store.internalUpdateState({values:a,errors:d.errors,touched:d.touched,isValidating:d.isValidating,isDirty:l}),this.store.emitFieldChange({path:e,previousValue:o,nextValue:n,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"swap",from:t,to:i}}),this.store.internalSaveSnapshot(),this.revalidate(e)}moveItem(e,t,i){let r=this.store.getState(),n=[...p(r.values,e)||[]],o=[...n],[a]=n.splice(t,1);n.splice(i,0,a);let l=y(r.values,e,n),d=this.store.updateDirtyForPath(e,l,this.store.getConfig().initialValues),c=E(r,e,u=>u===t?i:t<i&&u>t&&u<=i?u-1:t>i&&u>=i&&u<t?u+1:u);this.store.internalUpdateState({values:l,errors:c.errors,touched:c.touched,isValidating:c.isValidating,isDirty:d}),this.store.emitFieldChange({path:e,previousValue:o,nextValue:n,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"move",from:t,to:i}}),this.store.internalSaveSnapshot(),this.revalidate(e)}revalidate(e){this.store.triggerValidation([e])}};var H=class{constructor(e,t,i,r){this.getState=e;this.getInitialValues=t;this.getScopeFields=i;this.isPathDirty=r}getStepStatus(e){let t=this.getScopeFields(e),i=this.getState(),r=t.some(a=>!!i.errors[a]),n=t.some(a=>this.isPathDirty(a)),o=this.getStepErrors(e);return{hasErrors:r,isDirty:n,errors:o}}getStepErrors(e){let t=this.getScopeFields(e),i=this.getState(),r={};for(let n of t){let o=i.errors[n];o&&(r[n]=o)}return r}};var U=class{constructor(e,t,i,r){this.dependencyManager=e;this.getState=t;this.getConfig=i;this.isPathDirty=r}requiredValuesRef=null;isHidden(e){return this.dependencyManager.isHidden(e)}isRequired(e){let t=this.getState().values;return this.requiredValuesRef!==t&&(this.requiredValuesRef=t),this.dependencyManager.isRequired(e,t)}isFieldDirty(e){return this.isPathDirty(e)}isFieldValidating(e){return!!this.getState().isValidating[e]}};var j=class{constructor(e,t){this.getState=e;this.internalUpdateState=t}setError(e,t){let i={...this.getState().errors,[e]:t};t||delete i[e],this.internalUpdateState({errors:i})}setErrors(e){this.internalUpdateState({errors:{...this.getState().errors,...e}})}setServerErrors(e){let t={};for(let[i,r]of Object.entries(e))t[i]=Array.isArray(r)?r[0]:r;this.setErrors(t)}};var z=class{capabilities=new Map;register(e,t){this.capabilities.set(e,t)}get(e){let t=this.capabilities.get(e);if(!t)throw new Error(`Capability "${String(e)}" is not registered`);return t}has(e){return this.capabilities.has(e)}clear(){this.capabilities.clear()}};function Y(s){let{store:e,dependencyManager:t,dirtyManager:i}=s,r=new z,n={getState:()=>e.getState(),internalUpdateState:a=>e.internalUpdateState(a),setError:(a,l)=>e.setError(a,l),validate:a=>e.validate(a),getFieldConfig:a=>e.getFieldConfig(a),getScopeFields:a=>e.getScopeFields(a),config:e.config,getRequiredErrors:a=>e.getRequiredErrors(a),getHiddenFields:()=>e.getHiddenFields(),emitBeforeValidate:a=>e.emitBeforeValidate(a),emitAfterValidate:a=>e.emitAfterValidate(a)},o={getState:()=>e.getState(),internalUpdateState:(a,l)=>e.internalUpdateState(a,l),internalSaveSnapshot:()=>e.internalSaveSnapshot(),batchStateUpdates:a=>e.batchStateUpdates(a),config:e.config,getTransformEntries:()=>e.getTransformEntries(),updateDependencies:(a,l)=>e.updateDependencies(a,l),isFieldHidden:a=>e.isFieldHidden(a),evaluateAllDependencies:a=>e.evaluateAllDependencies(a),getHiddenFields:()=>e.getHiddenFields(),clearFieldValidation:a=>e.clearFieldValidation(a),triggerValidation:(a,l)=>e.triggerValidation(a,l),handleFieldAsyncValidation:(a,l)=>e.handleFieldAsyncValidation(a,l),cancelAllValidations:()=>e.cancelAllValidations(),validateNow:a=>e.validateNow(a),hasValidationsInProgress:a=>e.hasValidationsInProgress(a),updateDirtyForPath:(a,l,d)=>e.updateDirtyForPath(a,l,d),rebuildDirtyState:(a,l)=>e.rebuildDirtyState(a,l),clearDirtyState:()=>e.clearDirtyState(),buildDirtyValues:a=>e.buildDirtyValues(a),resetHistory:a=>e.resetHistory(a),emitFieldChange:a=>e.emitFieldChange(a),emitBeforeSubmit:a=>e.emitBeforeSubmit(a),emitAfterSubmit:a=>e.emitAfterSubmit(a),emitOperationalError:a=>e.emitOperationalError(a)};return r.register("validation",new R(n)),r.register("lifecycle",new I(o)),r.register("history",new q(!!e.config.enableHistory,e.config.historyLimit??15)),r.register("arrays",new O(e)),r.register("scope",new H(()=>e.getState(),()=>e.config.initialValues,a=>e.getScopeFields(a),a=>i.isPathDirty(a))),r.register("query",new U(t,()=>e.getState(),()=>e.config,a=>i.isPathDirty(a))),r.register("error",new j(()=>e.getState(),a=>e.internalUpdateState(a))),r}function Q(s){let{storeId:e,storeInstance:t,config:i,getState:r,getConfig:n,getValues:o,getDirtyValues:a,applyPersistedValues:l}=s,d=new w(i.persist,o,a,l),c=[...i.plugins],u=X(i.devTools);u&&c.push(u);let g=new D(c,()=>({storeId:e,getState:()=>r(),getConfig:()=>n()})),f=new k(e,t,d,g);return f.initialize(),f}function Z(s){let{config:e,dependencyManager:t,computedManager:i}=s,r=h(e.initialValues);return e.fields&&Object.entries(e.fields).forEach(([o,a])=>{t.register(o,a,r)}),{values:i.apply(r),errors:{},touched:{},isValidating:{},persist:{isSaving:!1,isRestoring:!1,error:null},isValid:!0,isSubmitting:!1,isDirty:!1}}var b=class{state;subscriptions;effects;capabilities;config;storeId;dependencyManager;computedManager;dirtyManager;scopeFieldsIndex=null;computedEntriesCache=null;transformEntriesCache=null;batchDepth=0;batchedState=null;batchedChangedPaths=null;batchedValuesChanged=!1;invalidateFieldIndexes(){this.scopeFieldsIndex=null,this.computedEntriesCache=null,this.transformEntriesCache=null,this.computedManager.invalidateReverseDeps()}registerCachedFieldIndexes(e,t){if(this.scopeFieldsIndex&&t.scope){let i=this.scopeFieldsIndex.get(t.scope)??[];i.includes(e)||(i.push(e),this.scopeFieldsIndex.set(t.scope,i))}this.computedEntriesCache&&t.computed&&this.computedEntriesCache.push({path:e,compute:t.computed,dependsOn:t.computedDependsOn??t.conditional?.dependsOn}),this.transformEntriesCache&&t.transform&&this.transformEntriesCache.push([e,t.transform])}unregisterCachedFieldIndexes(e,t){if(!t){this.invalidateFieldIndexes();return}if(this.scopeFieldsIndex&&t.scope){let i=this.scopeFieldsIndex.get(t.scope);if(i){let r=i.filter(n=>n!==e);r.length>0?this.scopeFieldsIndex.set(t.scope,r):this.scopeFieldsIndex.delete(t.scope)}}this.computedEntriesCache&&t.computed&&(this.computedEntriesCache=this.computedEntriesCache.filter(i=>i.path!==e)),this.transformEntriesCache&&t.transform&&(this.transformEntriesCache=this.transformEntriesCache.filter(([i])=>i!==e))}getCapability(e){return this.capabilities.get(e)}get validation(){return this.getCapability("validation")}get lifecycle(){return this.getCapability("lifecycle")}get history(){return this.getCapability("history")}get arrays(){return this.getCapability("arrays")}get scope(){return this.getCapability("scope")}get query(){return this.getCapability("query")}get error(){return this.getCapability("error")}constructor(e={}){this.config=J(e),this.dependencyManager=new V,this.computedManager=new C(()=>this.getComputedEntries()),this.dirtyManager=new F,this.capabilities=Y({store:this,dependencyManager:this.dependencyManager,dirtyManager:this.dirtyManager}),this.state=Z({config:this.config,dependencyManager:this.dependencyManager,computedManager:this.computedManager}),this.subscriptions=new x(()=>this.state),this.internalSaveSnapshot(),this.storeId=e.storeId||this.config.name||this.config.idFactory({scope:"store",storeName:this.config.name}),this.effects=Q({storeId:this.storeId,storeInstance:this,config:this.config,getState:()=>this.getState(),getConfig:()=>this.getConfig(),getValues:()=>this.state.values,getDirtyValues:()=>this.getDirtyValues(),applyPersistedValues:t=>this.applyPersistedValues(t)})}getConfig(){return this.config}getFieldConfig(e){return this.dependencyManager.getFieldConfig(e)||this.config.fields?.[e]}getScopeFields(e){if(!this.scopeFieldsIndex){let t=new Map;this.dependencyManager.forEachFieldConfig((i,r)=>{if(!i.scope)return;let n=t.get(i.scope)??[];n.push(r),t.set(i.scope,n)}),this.scopeFieldsIndex=t}return this.scopeFieldsIndex.get(e)??[]}getComputedEntries(){if(!this.computedEntriesCache){let e=[];this.dependencyManager.forEachFieldConfig((t,i)=>{t.computed&&e.push({path:i,compute:t.computed,dependsOn:t.computedDependsOn??t.conditional?.dependsOn})}),this.computedEntriesCache=e}return this.computedEntriesCache}getTransformEntries(){if(!this.transformEntriesCache){let e=[];this.dependencyManager.forEachFieldConfig((t,i)=>{t.transform&&e.push([i,t.transform])}),this.transformEntriesCache=e}return this.transformEntriesCache}resolveMask(e){let t=this.getFieldConfig(e)?.mask;if(t)return typeof t=="string"?this.config.masks?.[t]:t}getState(){return this.batchedState??this.state}getFieldState(e){return{value:p(this.state.values,e),error:this.state.errors[e],touched:!!this.state.touched[e],isHidden:this.isHidden(e),isRequired:this.isRequired(e),isDirty:this.isFieldDirty(e),isValidating:this.isFieldValidating(e)}}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}registerField(e,t){this.dependencyManager.register(e,t,this.state.values),this.registerCachedFieldIndexes(e,t),this.dependencyManager.isHidden(e)&&this.subscriptions.notify(this.state,["*"])}unregisterField(e){if(this.config.fields?.[e])return;let t=this.getFieldConfig(e);this.validation.cleanupField(e),this.dependencyManager.unregister(e),this.unregisterCachedFieldIndexes(e,t);let i={...this.state.errors},r={...this.state.touched},n=!1;i[e]&&(delete i[e],n=!0),r[e]&&(delete r[e],n=!0),n&&this.internalUpdateState({errors:i,touched:r})}unregisterPrefix(e){this.validation.cleanupPrefix(e),this.dependencyManager.unregisterPrefix(e).forEach(([i,r])=>{this.unregisterCachedFieldIndexes(i,r)})}isHidden(e){return this.query.isHidden(e)}isRequired(e){return this.query.isRequired(e)}isFieldDirty(e){return this.query.isFieldDirty(e)}isFieldValidating(e){return this.query.isFieldValidating(e)}subscribe(e){return this.subscriptions.subscribe(e)}subscribeSelector(e,t,i){let r=i?.equalityFn??S;return this.subscriptions.subscribeSelector(e,t,i,r)}subscribePath(e,t,i){let r=[...i?.paths??[],e];return this.subscribeSelector(n=>p(n.values,e),t,{...i,paths:r})}watch(e,t){return this.subscribePath(e,t,{equalityFn:m})}setField(e,t){this.setFieldWithMeta(e,t,{origin:"setField"})}setFieldWithMeta(e,t,i={origin:"setField"}){this.lifecycle.updateField(e,t,i)}blurField(e){this.internalSaveSnapshot(),this.state.touched[e]||this.batchStateUpdates(()=>{this.internalUpdateState({touched:{...this.state.touched,[e]:!0}})}),this.validation.trigger([e])}markFieldsTouched(e){if(e.length===0)return;let t={...this.state.touched};e.forEach(i=>{t[i]=!0}),this.internalUpdateState({touched:t})}replaceValues(e){this.lifecycle.replaceValues(e)}hydrate(e){this.lifecycle.hydrateValues(e)}rebase(e){this.lifecycle.rebaseValues(e)}setError(e,t){this.error.setError(e,t)}setErrors(e){this.error.setErrors(e)}setServerErrors(e){this.error.setServerErrors(e)}reset(){this.lifecycle.reset()}transaction(e){return this.batchStateUpdates(e)}async submit(e){return this.lifecycle.submit(e)}registerMask(e,t){this.config.masks={...this.config.masks||{},[e]:t}}getDirtyValues(){return this.dirtyManager.buildDirtyValues(this.state.values)}getPersistMetadata(){return this.state.persist}async restorePersisted(){this.internalUpdateState({persist:{...this.state.persist,isRestoring:!0,error:null}});try{return await this.effects.restorePersisted()}catch(e){return this.internalUpdateState({persist:{...this.state.persist,isRestoring:!1,error:e instanceof Error?e:new Error(String(e))}}),!1}finally{this.internalUpdateState({persist:{...this.state.persist,isRestoring:!1}})}}async forceSave(){this.internalUpdateState({persist:{...this.state.persist,isSaving:!0,error:null}});try{await this.effects.savePersistedNow()}catch(e){this.internalUpdateState({persist:{...this.state.persist,isSaving:!1,error:e instanceof Error?e:new Error(String(e))}});return}this.internalUpdateState({persist:{...this.state.persist,isSaving:!1}})}async clearPersisted(){this.internalUpdateState({persist:{...this.state.persist,error:null}});try{await this.effects.clearPersisted()}catch(e){this.internalUpdateState({persist:{...this.state.persist,error:e instanceof Error?e:new Error(String(e))}})}}pushItem(e,t){this.arrays.pushItem(e,t)}prependItem(e,t){this.arrays.prependItem(e,t)}insertItem(e,t,i){this.arrays.insertItem(e,t,i)}removeItem(e,t){this.arrays.removeItem(e,t)}swapItems(e,t,i){this.arrays.swapItems(e,t,i)}moveItem(e,t,i){this.arrays.moveItem(e,t,i)}get canUndo(){return this.history.canUndo}get canRedo(){return this.history.canRedo}undo(){let e=this.history.undo();if(e){let t=this.dirtyManager.rebuild(e,this.config.initialValues);this.internalUpdateState({values:e,isDirty:t}),this.validation.trigger(void 0,{forceDebounce:!0})}}redo(){let e=this.history.redo();if(e){let t=this.dirtyManager.rebuild(e,this.config.initialValues);this.internalUpdateState({values:e,isDirty:t}),this.validation.trigger(void 0,{forceDebounce:!0})}}getHistoryMetadata(){return this.history.getMetadata()}validate(e){return this.validation.validate(e)}emitBeforeValidate(e){return this.effects.beforeValidate(e)}emitAfterValidate(e){return this.effects.afterValidate(e)}emitBeforeSubmit(e){return this.effects.beforeSubmit(e)}emitAfterSubmit(e){return this.effects.afterSubmit(e)}emitFieldChange(e){this.effects.onFieldChange(e)}emitOperationalError(e){return this.effects.reportOperationalError(e)}hasValidationsInProgress(e){return this.validation.hasValidationsInProgress(e)}triggerValidation(e,t){this.validation.trigger(e,t)}getStepStatus(e){return this.scope.getStepStatus(e)}getStepErrors(e){return this.scope.getStepErrors(e)}updateDependencies(e,t){return this.dependencyManager.updateDependencies(e,t)}isFieldHidden(e){return this.dependencyManager.isHidden(e)}evaluateAllDependencies(e){this.dependencyManager.evaluateAll(e)}getHiddenFields(){return this.dependencyManager.getHiddenFields()}getRequiredErrors(e){return this.dependencyManager.getRequiredErrors(e)}clearFieldValidation(e){this.validation.clear(e)}handleFieldAsyncValidation(e,t){this.validation.handleAsync(e,t)}cancelAllValidations(){this.validation.cancelAll()}validateNow(e){return this.validation.validate(e)}updateDirtyForPath(e,t,i){return this.dirtyManager.updateForPath(e,t,i)}rebuildDirtyState(e,t){return this.dirtyManager.rebuild(e,t)}clearDirtyState(){this.dirtyManager.clear()}buildDirtyValues(e){return this.dirtyManager.buildDirtyValues(e)}batchStateUpdates(e){this.batchDepth+=1;try{return e()}finally{this.batchDepth-=1,this.batchDepth===0&&this.flushBatchedStateUpdates()}}resetHistory(e){this.history.reset(e)}internalUpdateState(e,t){if(this.batchDepth>0){let r=K({currentState:this.batchedState??this.state,partialState:e,changedPaths:t,applyComputedValues:n=>n});if(this.batchedState=r.nextState,this.batchedValuesChanged||=r.valuesChanged,r.changedPaths&&r.changedPaths.length>0){let n=this.batchedChangedPaths??new Set;r.changedPaths.forEach(o=>n.add(o)),this.batchedChangedPaths=n}return}let i=K({currentState:this.state,partialState:e,changedPaths:t,applyComputedValues:r=>this.computedManager.apply(r,t)});this.state=i.nextState,this.subscriptions.notify(this.state,i.changedPaths),this.effects.onStateUpdated(this.state,i.valuesChanged)}internalSaveSnapshot(){this.history.saveSnapshot(this.state.values)}applyPersistedValues(e){let t=h({...this.config.initialValues,...e});this.validation.cancelAll(),this.dependencyManager.evaluateAll(t);let i=this.dirtyManager.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},persist:{...this.state.persist,error:null},isValid:!0,isDirty:i,isSubmitting:!1}),this.internalSaveSnapshot(),this.validation.validate()}cleanup(){this.subscriptions.destroy(),this.validation.cancelAll(),this.capabilities.clear(),this.effects.destroy()}flushBatchedStateUpdates(){if(!this.batchedState)return;let e=this.batchedState,t=this.batchedChangedPaths?Array.from(this.batchedChangedPaths):void 0,i=this.batchedValuesChanged;i&&(e={...e,values:this.computedManager.apply(e.values,t)}),this.batchedState=null,this.batchedChangedPaths=null,this.batchedValuesChanged=!1,this.state=e,this.subscriptions.notify(this.state,t),this.effects.onStateUpdated(this.state,i)}};var ee=new Set(["config","getConfig","getState","subscribe","setField","blurField","replaceValues","hydrate","rebase","setError","setErrors","setServerErrors","validate","reset","transaction","submit","registerMask","getDirtyValues","getPersistMetadata","restorePersisted","forceSave","clearPersisted","cleanup","registerField","unregisterField","isHidden","isRequired","isFieldDirty","isFieldValidating","watch","pushItem","prependItem","insertItem","removeItem","moveItem","swapItems","getHistoryMetadata","undo","redo","getStepStatus","getStepErrors","getFieldState","subscribePath","subscribeSelector","unregisterPrefix","markFieldsTouched","hasValidationsInProgress","resolveMask","getScopeFields"]);function pe(s){return new Proxy(s,{get(e,t){if(typeof t=="string"&&!ee.has(t))return;let i=Reflect.get(e,t,e);return typeof i=="function"?i.bind(e):i},has(e,t){return typeof t=="string"&&ee.has(t)},set(){return!1}})}function ge(s){return typeof s.getFieldState=="function"&&typeof s.subscribePath=="function"&&typeof s.subscribeSelector=="function"&&typeof s.markFieldsTouched=="function"&&typeof s.hasValidationsInProgress=="function"&&typeof s.resolveMask=="function"&&typeof s.getScopeFields=="function"}function fe(s){if(s instanceof b||ge(s))return s;throw new Error("BitForm: o store informado n\xE3o exp\xF5e a API necess\xE1ria para hooks/framework bindings.")}function ye(s={}){return pe(new b(s))}export{h as a,P as b,S as c,m as d,p as e,y as f,re as g,G as h,ne as i,T as j,fe as k,ye as l};
2
+ //# sourceMappingURL=chunk-64KSP4TP.js.map