@lehnihon/bit-form 2.2.5 → 2.2.6

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 (46) hide show
  1. package/dist/angular/index.cjs +1 -1
  2. package/dist/angular/index.d.cts +1 -1
  3. package/dist/angular/index.d.ts +1 -1
  4. package/dist/angular/index.js +1 -1
  5. package/dist/{chunk-2FDEJYA5.js → chunk-2CVKNPWX.js} +2 -2
  6. package/dist/{chunk-3CARTBEN.cjs → chunk-3EDD3V43.cjs} +2 -2
  7. package/dist/{chunk-3CARTBEN.cjs.map → chunk-3EDD3V43.cjs.map} +1 -1
  8. package/dist/chunk-PX6WKENM.js +2 -0
  9. package/dist/chunk-PX6WKENM.js.map +1 -0
  10. package/dist/{chunk-UMKOKAPD.js → chunk-T3FR7D5V.js} +2 -2
  11. package/dist/{chunk-JIWR4KSZ.cjs → chunk-Y2ONHDRE.cjs} +2 -2
  12. package/dist/{chunk-JIWR4KSZ.cjs.map → chunk-Y2ONHDRE.cjs.map} +1 -1
  13. package/dist/chunk-YCSWULEN.cjs +2 -0
  14. package/dist/{chunk-OZKLQRO6.cjs.map → chunk-YCSWULEN.cjs.map} +1 -1
  15. package/dist/devtools/bridge.cjs +1 -1
  16. package/dist/devtools/bridge.js +1 -1
  17. package/dist/devtools/index.cjs +2 -2
  18. package/dist/devtools/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.d.cts +23 -2
  21. package/dist/index.d.ts +23 -2
  22. package/dist/index.js +1 -1
  23. package/dist/{public-types-BQXaxmAE.d.cts → public-types-Cd9ai20P.d.cts} +3 -0
  24. package/dist/{public-types-CVgFf_qY.d.ts → public-types-DdZxD6Op.d.ts} +3 -0
  25. package/dist/react/index.cjs +1 -1
  26. package/dist/react/index.cjs.map +1 -1
  27. package/dist/react/index.d.cts +3 -3
  28. package/dist/react/index.d.ts +3 -3
  29. package/dist/react/index.js +1 -1
  30. package/dist/react/index.js.map +1 -1
  31. package/dist/react-native/index.cjs +1 -1
  32. package/dist/react-native/index.d.cts +2 -2
  33. package/dist/react-native/index.d.ts +2 -2
  34. package/dist/react-native/index.js +1 -1
  35. package/dist/{use-bit-persist-CIVN-oIi.d.cts → use-bit-persist-D_gimC9A.d.cts} +1 -1
  36. package/dist/{use-bit-persist-iPWLbD8l.d.ts → use-bit-persist-Dk3fUrds.d.ts} +1 -1
  37. package/dist/vue/index.cjs +1 -1
  38. package/dist/vue/index.d.cts +1 -1
  39. package/dist/vue/index.d.ts +1 -1
  40. package/dist/vue/index.js +1 -1
  41. package/package.json +1 -1
  42. package/dist/chunk-64KSP4TP.js +0 -2
  43. package/dist/chunk-64KSP4TP.js.map +0 -1
  44. package/dist/chunk-OZKLQRO6.cjs +0 -2
  45. /package/dist/{chunk-2FDEJYA5.js.map → chunk-2CVKNPWX.js.map} +0 -0
  46. /package/dist/{chunk-UMKOKAPD.js.map → chunk-T3FR7D5V.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkOZKLQRO6cjs = require('./chunk-OZKLQRO6.cjs');var _chunkPFPGASVZcjs = require('./chunk-PFPGASVZ.cjs');async function m(e,r,o,i){try{let t=await e(r,o);i.onSuccess(t)}catch(t){if(_chunkOZKLQRO6cjs.h.call(void 0, t)){i.onServerErrors(_chunkOZKLQRO6cjs.i.call(void 0, 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){_optionalChain([e, 'optionalAccess', _ => _.preventDefault, 'optionalCall', _2 => _2()]),_optionalChain([r, 'optionalAccess', _3 => _3.stopPropagation])&&_optionalChain([e, 'optionalAccess', _4 => _4.stopPropagation, 'optionalCall', _5 => _5()])}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,_chunkPFPGASVZcjs.c.call(void 0, s,o))},setBlur:()=>e.blurField(r),displayValue:s=>_chunkPFPGASVZcjs.b.call(void 0, 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"]}exports.a = E; exports.b = f; exports.c = k; exports.d = h; exports.e = x; exports.f = H;
2
- //# sourceMappingURL=chunk-JIWR4KSZ.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkYCSWULENcjs = require('./chunk-YCSWULEN.cjs');var _chunkPFPGASVZcjs = require('./chunk-PFPGASVZ.cjs');async function m(e,r,o,i){try{let t=await e(r,o);i.onSuccess(t)}catch(t){if(_chunkYCSWULENcjs.h.call(void 0, t)){i.onServerErrors(_chunkYCSWULENcjs.i.call(void 0, 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){_optionalChain([e, 'optionalAccess', _ => _.preventDefault, 'optionalCall', _2 => _2()]),_optionalChain([r, 'optionalAccess', _3 => _3.stopPropagation])&&_optionalChain([e, 'optionalAccess', _4 => _4.stopPropagation, 'optionalCall', _5 => _5()])}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,_chunkPFPGASVZcjs.c.call(void 0, s,o))},setBlur:()=>e.blurField(r),displayValue:s=>_chunkPFPGASVZcjs.b.call(void 0, 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"]}exports.a = E; exports.b = f; exports.c = k; exports.d = h; exports.e = x; exports.f = H;
2
+ //# sourceMappingURL=chunk-Y2ONHDRE.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-JIWR4KSZ.cjs","../src/core/submit-handler.ts","../src/core/form-controller.ts","../src/core/field-controller.ts","../src/core/scope-status.ts"],"names":["executeSubmitHandler","handler","values","dirtyValues","handlers","result","error","isValidationErrorShape","extractServerErrors","createStoreFormActions","store","path","value","message","errors","serverErrors","options","callback","preventFormEvent","event","createFormController","runtime","onSuccess","subscribeFieldState","listener","prev","next","createMaskedFieldController","mask","parseMaskedInput","formatMaskedValue","areScopeErrorsEqual","currentErrors","nextErrors","currentKeys","nextKeys","key","isScopeStatusEqual","currentStatus","nextStatus","getScopeSubscriptionPaths","scopeFields"],"mappings":"AAAA,qoBAA+C,wDAA2C,MCQ1F,SAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACe,CACf,GAAI,CACF,IAAMC,CAAAA,CAAS,MAAMJ,CAAAA,CAAQC,CAAAA,CAAQC,CAAW,CAAA,CAChDC,CAAAA,CAAS,SAAA,CAAUC,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CC1DO,SAASG,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACS,CACT,IAAMC,CAAAA,CAAc,MAAA,CAAO,IAAA,CAAKF,CAAa,CAAA,CACvCG,CAAAA,CAAW,MAAA,CAAO,IAAA,CAAKF,CAAU,CAAA,CAEvC,OAAIC,CAAAA,CAAY,MAAA,GAAWC,CAAAA,CAAS,MAAA,CAC3B,CAAA,CAAA,CAGFD,CAAAA,CAAY,KAAA,CAAOE,CAAAA,EAAQJ,CAAAA,CAAcI,CAAG,CAAA,GAAMH,CAAAA,CAAWG,CAAG,CAAC,CAC1E,CAEO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACS,CACT,OACED,CAAAA,CAAc,SAAA,GAAcC,CAAAA,CAAW,SAAA,EACvCD,CAAAA,CAAc,OAAA,GAAYC,CAAAA,CAAW,OAAA,EACrCR,CAAAA,CAAoBO,CAAAA,CAAc,MAAA,CAAQC,CAAAA,CAAW,MAAM,CAE/D,CAEO,SAASC,CAAAA,CAA0BC,CAAAA,CAAgC,CACxE,MAAO,CAAC,GAAGA,CAAAA,CAAa,SAAS,CACnC,CAAA,yFAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-JIWR4KSZ.cjs","sourcesContent":[null,"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"]}
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-Y2ONHDRE.cjs","../src/core/submit-handler.ts","../src/core/form-controller.ts","../src/core/field-controller.ts","../src/core/scope-status.ts"],"names":["executeSubmitHandler","handler","values","dirtyValues","handlers","result","error","isValidationErrorShape","extractServerErrors","createStoreFormActions","store","path","value","message","errors","serverErrors","options","callback","preventFormEvent","event","createFormController","runtime","onSuccess","subscribeFieldState","listener","prev","next","createMaskedFieldController","mask","parseMaskedInput","formatMaskedValue","areScopeErrorsEqual","currentErrors","nextErrors","currentKeys","nextKeys","key","isScopeStatusEqual","currentStatus","nextStatus","getScopeSubscriptionPaths","scopeFields"],"mappings":"AAAA,qoBAA+C,wDAA2C,MCQ1F,SAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACe,CACf,GAAI,CACF,IAAMC,CAAAA,CAAS,M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CAOxC,YAAA,CALoBC,CAAAA,EAAmBkB,iCAAAA,CAAkBlB,CAAOgB,CAAI,CAMtE,CACF,CC1DO,SAASG,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACS,CACT,IAAMC,CAAAA,CAAc,MAAA,CAAO,IAAA,CAAKF,CAAa,CAAA,CACvCG,CAAAA,CAAW,MAAA,CAAO,IAAA,CAAKF,CAAU,CAAA,CAEvC,OAAIC,CAAAA,CAAY,MAAA,GAAWC,CAAAA,CAAS,MAAA,CAC3B,CAAA,CAAA,CAGFD,CAAAA,CAAY,KAAA,CAAOE,CAAAA,EAAQJ,CAAAA,CAAcI,CAAG,CAAA,GAAMH,CAAAA,CAAWG,CAAG,CAAC,CAC1E,CAEO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACS,CACT,OACED,CAAAA,CAAc,SAAA,GAAcC,CAAAA,CAAW,SAAA,EACvCD,CAAAA,CAAc,OAAA,GAAYC,CAAAA,CAAW,OAAA,EACrCR,CAAAA,CAAoBO,CAAAA,CAAc,MAAA,CAAQC,CAAAA,CAAW,MAAM,CAE/D,CAEO,SAASC,CAAAA,CAA0BC,CAAAA,CAAgC,CACxE,MAAO,CAAC,GAAGA,CAAAA,CAAa,SAAS,CACnC,CAAA,yFAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-Y2ONHDRE.cjs","sourcesContent":[null,"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"]}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10;function h(n){if(n===null||typeof n!="object")return n;if(typeof structuredClone=="function")return structuredClone(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(Array.isArray(n))return n.map(t=>h(t));let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=h(n[t]));return e}function P(n,e){if(e===void 0)return h(n);if(e===null||typeof e!="object"||e instanceof Date||e instanceof RegExp||Array.isArray(e))return h(e);let t=n&&typeof n=="object"&&!Array.isArray(n)?h(n):{};for(let i of Object.keys(e)){let r=e[i],s=t[i];if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp)){t[i]=P(s,r);continue}t[i]=h(r)}return t}function S(n,e){return n===e?!0:n===null||typeof n!="object"||e===null||typeof e!="object"?!1:m(n,e)}function m(n,e){if(n===e)return!0;if(n===null||typeof n!="object"||e===null||typeof e!="object")return!1;if(n instanceof Date&&e instanceof Date)return n.getTime()===e.getTime();if(n instanceof RegExp&&e instanceof RegExp)return n.toString()===e.toString();let t=Object.keys(n),i=Object.keys(e);if(t.length!==i.length)return!1;for(let r of t)if(!Object.prototype.hasOwnProperty.call(e,r)||!m(n[r],e[r]))return!1;return!0}function N(n,e,t="",i=new Set){if(S(n,e))return i;if(n===null||typeof n!="object"||e===null||typeof e!="object")return t&&i.add(t),i;if(Array.isArray(n)||Array.isArray(e))return!S(n,e)&&t&&i.add(t),i;let r=new Set;for(let s of Object.keys(n||{}))r.add(s);for(let s of Object.keys(e||{}))r.add(s);for(let s of r){let o=t?`${t}.${s}`:s;N(_optionalChain([n, 'optionalAccess', _2 => _2[s]]),_optionalChain([e, 'optionalAccess', _3 => _3[s]]),o,i)}return i}var se=1e3,B=new Map;function K(n){let e=B.get(n);if(e)return e;let t=n.split(".");return B.size>=se&&B.clear(),B.set(n,t),t}function p(n,e){if(!e)return n;let t=K(e),i=n;for(let r of t){if(i==null)return;i=i[r]}return i}function y(n,e,t){if(!e)return t;let i=K(e),r=Array.isArray(n)?[...n]:{...n},s=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=s[a];u==null?s[a]=c?[]:{}:s[a]=Array.isArray(u)?[...u]:{...u},s=s[a]}return s[i[i.length-1]]=t,r}function G(n,e){if(e.length===0)return n;let t=Array.isArray(n)?[...n]:{...n},i=new WeakSet;t&&typeof t=="object"&&i.add(t);for(let[r,s]of e){let o=K(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]]=s}return t}function ne(n,e){let t={},i=`${e}.`;for(let r in n)r!==e&&!r.startsWith(i)&&(t[r]=n[r]);return t}function E(n,e,t){let i={},r={},s={},o=`${e}.`;for(let a of Object.keys(n.errors)){let l=L(a,o,t);l&&(i[l]=n.errors[a])}for(let a of Object.keys(n.touched)){let l=L(a,o,t);l&&(r[l]=n.touched[a])}for(let a of Object.keys(n.isValidating)){let l=L(a,o,t);l&&(s[l]=n.isValidating[a])}return{errors:i,touched:r,isValidating:s}}function L(n,e,t){if(!n.startsWith(e))return n;let r=n.substring(e.length).split("."),s=parseInt(r[0],10),o=t(s);if(o===null)return null;let a=r.slice(1).join(".");return a?`${e}${o}.${a}`:`${e}${o}`}function J(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let e=_nullishCoalesce(n.errors, () => (n));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 ae(n){return J(n)?_nullishCoalesce(n.errors, () => (n)):{}}var $=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;$.__BIT_FORM__||($.__BIT_FORM__={stores:{},listeners:new Set,dispatch(n,e){this.listeners.forEach(t=>t(n,e))},subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}});var T=$.__BIT_FORM__;function oe(){return`bit-form-${Math.random().toString(36).slice(2,9)}`}function X(n={}){let e=_nullishCoalesce(n.initialValues, () => ({})),t=n.validation,i=n.history,r=n.name?`bit-form:${n.name}:draft`:"bit-form:draft",s={enabled:_nullishCoalesce(_optionalChain([n, 'access', _4 => _4.persist, 'optionalAccess', _5 => _5.enabled]), () => (!1)),key:_nullishCoalesce(_optionalChain([n, 'access', _6 => _6.persist, 'optionalAccess', _7 => _7.key]), () => (r)),storage:_optionalChain([n, 'access', _8 => _8.persist, 'optionalAccess', _9 => _9.storage]),autoSave:_nullishCoalesce(_optionalChain([n, 'access', _10 => _10.persist, 'optionalAccess', _11 => _11.autoSave]), () => (!0)),debounceMs:_nullishCoalesce(_optionalChain([n, 'access', _12 => _12.persist, 'optionalAccess', _13 => _13.debounceMs]), () => (300)),mode:_nullishCoalesce(_optionalChain([n, 'access', _14 => _14.persist, 'optionalAccess', _15 => _15.mode]), () => ("values")),serialize:_nullishCoalesce(_optionalChain([n, 'access', _16 => _16.persist, 'optionalAccess', _17 => _17.serialize]), () => (JSON.stringify)),deserialize:_nullishCoalesce(_optionalChain([n, 'access', _18 => _18.persist, 'optionalAccess', _19 => _19.deserialize]), () => ((o=>JSON.parse(o)))),onError:_optionalChain([n, 'access', _20 => _20.persist, 'optionalAccess', _21 => _21.onError])};return{name:n.name,initialValues:h(e),resolver:_optionalChain([t, 'optionalAccess', _22 => _22.resolver]),validationDelay:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _23 => _23.delay]), () => (300)),enableHistory:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _24 => _24.enabled]), () => (!1)),historyLimit:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _25 => _25.limit]), () => (15)),masks:n.masks,fields:n.fields,devTools:n.devTools,persist:s,idFactory:_nullishCoalesce(n.idFactory, () => (oe)),plugins:_nullishCoalesce(n.plugins, () => ([]))}}var V= (_class =class{constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);_class.prototype.__init7.call(this);_class.prototype.__init8.call(this); }__init() {this.fieldConfigs=new Map}__init2() {this.dependencies=new Map}__init3() {this.hiddenFields=new Set}__init4() {this.conditionalVisibilityPaths=new Set}__init5() {this.requiredPathsByDependency=new Map}__init6() {this.requiredConditionalPaths=new Set}__init7() {this.requiredEvaluationCache=new WeakMap}__init8() {this.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),_optionalChain([t, 'access', _26 => _26.conditional, 'optionalAccess', _27 => _27.showIf])&&this.conditionalVisibilityPaths.add(e);let r=_optionalChain([t, 'access', _28 => _28.conditional, 'optionalAccess', _29 => _29.dependsOn]);r&&r.forEach(o=>{this.dependencies.has(o)||this.dependencies.set(o,new Set),this.dependencies.get(o).add(e)});let s=_optionalChain([t, 'access', _30 => _30.conditional, 'optionalAccess', _31 => _31.dependsOn]);s&&_optionalChain([t, 'access', _32 => _32.conditional, 'optionalAccess', _33 => _33.requiredIf])&&(this.requiredConditionalPaths.add(e),s.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)||!_optionalChain([i, 'access', _34 => _34.conditional, 'optionalAccess', _35 => _35.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 s=!!i.conditional.requiredIf(t);return r.set(e,s),s}getRequiredErrors(e){let t={};return this.requiredConditionalPaths.forEach(i=>{let r=this.fieldConfigs.get(i);if(r&&this.isRequired(i,e)){let s=p(e,i);this.isEmpty(s)&&(t[i]=_nullishCoalesce(_optionalChain([r, 'access', _36 => _36.conditional, 'optionalAccess', _37 => _37.requiredMessage]), () => ("required field")))}}),t}evaluateAll(e){this.conditionalVisibilityPaths.forEach(t=>{this.evaluateFieldCondition(t,e)})}updateDependencies(e,t){let i=[],r=[e],s=new Set;for(;r.length>0;){let o=r.shift();if(s.has(o))continue;s.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),_optionalChain([t, 'optionalAccess', _38 => _38.conditional, 'optionalAccess', _39 => _39.dependsOn, 'optionalAccess', _40 => _40.forEach, 'call', _41 => _41(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=_optionalChain([this, 'access', _42 => _42.fieldConfigs, 'access', _43 => _43.get, 'call', _44 => _44(e), 'optionalAccess', _45 => _45.conditional, 'optionalAccess', _46 => _46.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}}, _class);var C= (_class2 =class n{constructor(e){;_class2.prototype.__init9.call(this);_class2.prototype.__init10.call(this);_class2.prototype.__init11.call(this);this.getComputedEntries=e}static __initStatic() {this.MIN_PASSES=4}__init9() {this.computedDependencyCache=new Map}__init10() {this.reverseDepsCache=null}__init11() {this.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 s=this.getDependenciesForEntry(r);for(let o of s){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 s=r.split(".");for(let o=1;o<s.length;o++){let a=s.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),s=r.entries;if(s.length===0)return e;let o=e,a=r.requiresStabilizationPasses?Math.max(n.MIN_PASSES,s.length*2):1;for(let l=0;l<a;l++){let d=!1;for(let c of s){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 _=this.computedDependencyCache.get(c.path);this.computedDependencyCache.set(c.path,g),(!_||_.size!==g.size||Array.from(_).some(re=>!g.has(re)))&&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("*")){let l=e.every(d=>d.dependsOn!==void 0||this.computedDependencyCache.has(d.path));return{entries:this.orderEntries(e),shouldTrackDependencies:!l,requiresStabilizationPasses:!l}}let i=this.getReverseDependencies(e),r=!1;for(let l of e)this.getDependenciesForEntry(l).length===0&&(r=!0);let s=new Set,o=[...t];for(;o.length>0;){let l=o.shift(),d=this.getDependentsForPath(i,l);if(d)for(let c of d)s.has(c)||(s.add(c),o.push(c))}if(s.size===0)return{entries:[],shouldTrackDependencies:r,requiresStabilizationPasses:!1};let a=e.filter(l=>s.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 _nullishCoalesce(e.dependsOn, () => (Array.from(_nullishCoalesce(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=_nullishCoalesce(r.get(d), () => (new Set));c.has(a.path)||(c.add(a.path),r.set(d,c),i.set(a.path,(_nullishCoalesce(i.get(a.path), () => (0)))+1))})});let s=e.filter(a=>(_nullishCoalesce(i.get(a.path), () => (0)))===0).map(a=>a.path),o=[];for(;s.length>0;){let a=s.shift();o.push(a);let l=r.get(a);l&&l.forEach(d=>{let c=(_nullishCoalesce(i.get(d), () => (0)))-1;i.set(d,c),c===0&&s.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 s=t.split(".");for(;s.length>1;)s.pop(),r(s.join("."));let o=_optionalChain([this, 'access', _47 => _47.childDepsIndex, 'optionalAccess', _48 => _48.get, 'call', _49 => _49(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 s=new Set,o=this.createTrackedValues(t,s);return{newValue:e.compute(o),trackedDependencies:s}}createTrackedValues(e,t){let i=(r,s)=>!r||typeof r!="object"?r:new Proxy(r,{get:(o,a)=>{if(typeof a!="string")return Reflect.get(o,a);let l=s?`${s}.${a}`:a;t.add(l);let d=Reflect.get(o,a);return i(d,l)}});return i(e,"")}}, _class2.__initStatic(), _class2);var F= (_class3 =class{constructor() { _class3.prototype.__init12.call(this);_class3.prototype.__init13.call(this);_class3.prototype.__init14.call(this);_class3.prototype.__init15.call(this); }__init12() {this.dirtyPaths=new Set}__init13() {this.dirtyPathIndex=new Set}__init14() {this.dirtyPrefixRefCount=new Map}__init15() {this.childrenByPrefix=new Map}updateForPath(e,t,i){this.removeDirtyChildren(e);let r=p(t,e),s=p(i,e);return S(r,s)?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(),this.childrenByPrefix.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 s=r.match(/^(.+)\.\d+/);if(s){let o=s[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,i=new Map;for(let r of this.dirtyPaths)this.forEachPathPrefix(r,s=>{e.add(s),t.set(s,(_nullishCoalesce(t.get(s), () => (0)))+1)}),this.forEachAncestorPrefix(r,s=>{let o=i.get(s);o?o.add(r):i.set(s,new Set([r]))});this.dirtyPathIndex=e,this.dirtyPrefixRefCount=t,this.childrenByPrefix=i}removeDirtyChildren(e){let t=this.childrenByPrefix.get(e);if(!(!t||t.size===0))for(let i of[...t])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,(_nullishCoalesce(this.dirtyPrefixRefCount.get(t), () => (0)))+1)}),this.forEachAncestorPrefix(e,t=>{let i=this.childrenByPrefix.get(t);i?i.add(e):this.childrenByPrefix.set(t,new Set([e]))}))}removeDirtyPath(e){this.dirtyPaths.has(e)&&(this.dirtyPaths.delete(e),this.forEachPathPrefix(e,t=>{let i=(_nullishCoalesce(this.dirtyPrefixRefCount.get(t), () => (0)))-1;if(i<=0){this.dirtyPrefixRefCount.delete(t),this.dirtyPathIndex.delete(t);return}this.dirtyPrefixRefCount.set(t,i)}),this.forEachAncestorPrefix(e,t=>{_optionalChain([this, 'access', _50 => _50.childrenByPrefix, 'access', _51 => _51.get, 'call', _52 => _52(t), 'optionalAccess', _53 => _53.delete, 'call', _54 => _54(e)])}))}forEachPathPrefix(e,t){let i=e.split("."),r="";for(let s of i)r=r?`${r}.${s}`:s,t(r)}forEachAncestorPrefix(e,t){let i=e.split("."),r="";for(let s=0;s<i.length-1;s++)r=r?`${r}.${i[s]}`:i[s],t(r)}}, _class3);var x= (_class4 =class{constructor(e){;_class4.prototype.__init16.call(this);_class4.prototype.__init17.call(this);_class4.prototype.__init18.call(this);_class4.prototype.__init19.call(this);_class4.prototype.__init20.call(this);this.getState=e}__init16() {this.listeners=new Set}__init17() {this.selectorListeners=new Set}__init18() {this.pathScopedSubscriptions=new Map}__init19() {this.pathSelectorIndex=new Map}__init20() {this.expandedPathCache=new Map}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}subscribeSelector(e,t,i,r){let s=e(this.getState()),o={notify:d=>{let c=e(d);r(s,c)||(s=c,t(c))}},a=_optionalChain([i, 'optionalAccess', _55 => _55.autoTrackPaths])?this.collectTrackedSelectorPaths(e):[];_optionalChain([i, 'optionalAccess', _56 => _56.autoTrackPaths])&&typeof process<"u"&&_optionalChain([process, 'access', _57 => _57.env, 'optionalAccess', _58 => _58.NODE_ENV])!=="production"&&console.warn("[bit-form] subscribeSelector: autoTrackPaths creates Proxy wrappers to detect accessed paths at subscription time. For high-frequency or dynamically-rendered fields (e.g. field arrays), prefer explicit `paths: [...]` to avoid mount-time overhead.");let l=this.normalizeSubscriptionPaths([..._nullishCoalesce(_optionalChain([i, 'optionalAccess', _59 => _59.paths]), () => ([])),...a]);return l.length>0?(this.pathScopedSubscriptions.set(o,l),l.forEach(d=>{this.expandPathForIndexing(d).forEach(c=>{let u=_nullishCoalesce(this.pathSelectorIndex.get(c), () => (new Set));u.add(o),this.pathSelectorIndex.set(c,u)})})):this.selectorListeners.add(o),_optionalChain([i, 'optionalAccess', _60 => _60.emitImmediately])&&t(s),()=>{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,s)=>{s.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()}normalizeSubscriptionPaths(e){if(!e||e.length===0)return[];let t=new Set,i=[];for(let r of e){let s=r.trim();s.length===0||t.has(s)||(t.add(s),i.push(s))}return i}collectTrackedSelectorPaths(e){let t=new Set,i=(s,o)=>!s||typeof s!="object"?s:new Proxy(s,{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:(s,o)=>{if(typeof o!="string")return Reflect.get(s,o);let a=Reflect.get(s,o);return o==="values"?i(a,""):a}});try{return e(r),Array.from(t)}catch (e2){return[]}}collectSubscribersForChangedPaths(e){let t=new Set,i=s=>{let o=this.pathSelectorIndex.get(s);o&&o.forEach(a=>t.add(a))};return this.normalizeSubscriptionPaths(e).forEach(s=>{i(s);let o=s.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 s=1;s<=i.length;s++)r.push(i.slice(0,s).join("."));return this.expandedPathCache.set(e,r),r}}, _class4);function le(n){let e=!1;for(let i of Object.values(n))if(i===void 0){e=!0;break}if(!e)return n;let t={};return Object.entries(n).forEach(([i,r])=>{r!==void 0&&(t[i]=r)}),t}function de(n){for(let e in n)return!0;return!1}function W(n){let{currentState:e,partialState:t,changedPaths:i,applyComputedValues:r}=n,s={...e,...t},o=!!t.values;t.values&&(s.values=r(t.values)),t.errors&&(s.errors=le(t.errors),s.isValid=!de(s.errors));let a=i&&i.length>0?i:void 0,l=ce(t,!a),d=ue(a,l);return{nextState:s,changedPaths:d,valuesChanged:o}}function ce(n,e){if(e&&n.values)return["*"];let t=new Set,i=[n.errors,n.touched,n.isValidating];for(let r of i)if(r)for(let s in r)t.add(s);return n.persist&&t.add("persist"),"isValid"in n&&t.add("isValid"),"isDirty"in n&&t.add("isDirty"),"isSubmitting"in n&&t.add("isSubmitting"),t.size>0?Array.from(t):void 0}function ue(n,e){if(!_optionalChain([n, 'optionalAccess', _61 => _61.length]))return e;if(!_optionalChain([e, 'optionalAccess', _62 => _62.length]))return n;let t=new Set;for(let i of n)t.add(i);for(let i of e)t.add(i);return Array.from(t)}function he(n){return typeof n=="boolean"?{enabled:n,mode:"local"}:{enabled:!!n,mode:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _63 => _63.mode]), () => ("local")),url:_optionalChain([n, 'optionalAccess', _64 => _64.url])}}function Y(n){let e=he(n);return e.enabled?{name:"bit-devtools",setup:()=>{let t=null,i=!1;return(async()=>{try{if(e.mode==="remote"){let{setupRemoteBridge:r}=await Promise.resolve().then(() => _interopRequireWildcard(require("./devtools/bridge.cjs")));t=r(e.url||"ws://localhost:3000")}else{let{initDevTools:r}=await Promise.resolve().then(() => _interopRequireWildcard(require("./devtools/index.cjs"))),s=r();t=s&&typeof s.destroy=="function"?s.destroy:null}i&&t&&(t(),t=null)}catch (e3){}})(),()=>{i=!0,t&&(t(),t=null)}}}:null}function pe(){if(typeof globalThis>"u")return;let n=globalThis.localStorage;if(n)return{getItem:e=>n.getItem(e),setItem:(e,t)=>n.setItem(e,t),removeItem:e=>n.removeItem(e)}}var w=class{constructor(e,t,i,r){this.config=e;this.getValues=t;this.getDirtyValues=i;this.applyRestoredValues=r}getStorage(){return this.config.storage||pe()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(e){_optionalChain([this, 'access', _65 => _65.config, 'access', _66 => _66.onError, 'optionalCall', _67 => _67(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= (_class5 =class{constructor(e,t){;_class5.prototype.__init21.call(this);_class5.prototype.__init22.call(this);this.plugins=e;this.contextFactory=t}__init21() {this.teardownFns=[]}__init22() {this.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=_optionalChain([t, 'access', _68 => _68.hooks, 'optionalAccess', _69 => _69.onFieldChange]);if(i)try{let r=i(e,this.contextFactory());Promise.resolve(r).catch(s=>{this.reportError("onFieldChange",s,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 s=this.contextFactory(),o={source:e,pluginName:r,error:t,event:i,values:s.getState().values,state:s.getState()};for(let a of this.plugins){let l=_optionalChain([a, 'access', _70 => _70.hooks, 'optionalAccess', _71 => _71.onError]);if(l)try{await l(o,s)}catch (e4){}}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 s=_optionalChain([r, 'access', _72 => _72.hooks, 'optionalAccess', _73 => _73[e]]);if(s)try{await s(t,i)}catch(o){await this.reportError(e,o,t,r.name)}}}}, _class5);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(n){for(let e in n)return!0;return!1}var R= (_class6 =class{constructor(e){;_class6.prototype.__init23.call(this);_class6.prototype.__init24.call(this);_class6.prototype.__init25.call(this);_class6.prototype.__init26.call(this);_class6.prototype.__init27.call(this);_class6.prototype.__init28.call(this);_class6.prototype.__init29.call(this);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)}])}__init23() {this.currentValidationId=0}__init24() {this.asyncEpoch=0}__init25() {this.validatingCount=0}__init26() {this.pendingScopeFields=null}__init27() {this.asyncTimers=new Map}__init28() {this.asyncRequests=new Map}__init29() {this.asyncErrors=new Map}updateFieldValidating(e,t){let i=this.store.getState();if(!!i.isValidating[e]===t)return;let s={...i.isValidating};t?(s[e]=!0,this.validatingCount+=1):(delete s[e],this.validatingCount=Math.max(0,this.validatingCount-1)),this.store.internalUpdateState({isValidating:s})}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=_optionalChain([i, 'optionalAccess', _74 => _74.validation, 'optionalAccess', _75 => _75.asyncValidate]);if(!r){this.updateFieldValidating(e,!1);return}let s=this.asyncTimers.get(e);s&&clearTimeout(s);let o=_nullishCoalesce(_optionalChain([i, 'access', _76 => _76.validation, 'optionalAccess', _77 => _77.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=_nullishCoalesce(this.store.config.validationDelay, () => (300)),r=_optionalChain([t, 'optionalAccess', _78 => _78.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 s=this.pendingScopeFields?Array.from(this.pendingScopeFields):void 0;this.validationTimeout=setTimeout(()=>{this.pendingScopeFields=null,this.validate({scopeFields:s})},r)}else this.pendingScopeFields=null,this.validate({scopeFields:e})}async validate(e){let t={options:e,validationId:++this.currentValidationId,currentState:this.store.getState(),targetFields:_optionalChain([e, 'optionalAccess', _79 => _79.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(_optionalChain([e, 'access', _80 => _80.options, 'optionalAccess', _81 => _81.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:_optionalChain([e, 'access', _82 => _82.options, 'optionalAccess', _83 => _83.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:_optionalChain([e, 'access', _84 => _84.options, 'optionalAccess', _85 => _85.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:_optionalChain([e, 'access', _86 => _86.options, 'optionalAccess', _87 => _87.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:_optionalChain([e, 'access', _88 => _88.options, 'optionalAccess', _89 => _89.scope]),scopeFields:e.targetFields,errors:e.allErrors,result:e.isValid})}}, _class6);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)}])}updateField(e,t,i={origin:"setField"}){let r=this.store.getState(),s={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(s)}replaceValues(e,t="replaceValues"){let i=this.store.getState().values,r=h(e);this.store.cancelAllValidations(),this.store.evaluateAllDependencies(r);let s=this.store.rebuildDirtyState(r,this.store.getInitialValues());this.store.internalUpdateState({values:r,errors:{},isValidating:{},isValid:!0,isDirty:s,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.setInitialValues(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.getInitialValues());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.getInitialValues())}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 s=p(e.valuesToSubmit,i);t.push([i,r(s,this.store.getState().values)])}t.length>0&&(e.valuesToSubmit=G(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= (_class7 =class{constructor(e,t=15){;_class7.prototype.__init30.call(this);_class7.prototype.__init31.call(this);_class7.prototype.__init32.call(this);_class7.prototype.__init33.call(this);this.enableHistory=e;this.maxHistory=t}__init30() {this.history=[]}__init31() {this.historyIndex=-1}__init32() {this.historySize=0}__init33() {this.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 s=this.historyIndex+1;s<r?(this.history[this.toPhysicalIndex(s)]=i,this.historySize=Math.max(this.historySize,s+1),this.historyIndex=s):(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)]}}, _class7);var H=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 s=[...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:s,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(),s=[...p(r.values,e)||[]],o=[...s];[s[t],s[i]]=[s[i],s[t]];let a=y(r.values,e,s),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:s,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(),s=[...p(r.values,e)||[]],o=[...s],[a]=s.splice(t,1);s.splice(i,0,a);let l=y(r.values,e,s),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:s,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 O=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]),s=t.some(a=>this.isPathDirty(a)),o=this.getStepErrors(e);return{hasErrors:r,isDirty:s,errors:o}}getStepErrors(e){let t=this.getScopeFields(e),i=this.getState(),r={};for(let s of t){let o=i.errors[s];o&&(r[s]=o)}return r}};var U= (_class8 =class{constructor(e,t,i,r){;_class8.prototype.__init34.call(this);this.dependencyManager=e;this.getState=t;this.getConfig=i;this.isPathDirty=r}__init34() {this.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]}}, _class8);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= (_class9 =class{constructor() { _class9.prototype.__init35.call(this); }__init35() {this.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()}}, _class9);function Q(n){let{store:e,dependencyManager:t,dirtyManager:i}=n,r=new z,s={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),getInitialValues:()=>e.getInitialValues(),setInitialValues:a=>e.setInitialValues(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(s)),r.register("lifecycle",new I(o)),r.register("history",new q(!!e.config.enableHistory,_nullishCoalesce(e.config.historyLimit, () => (15)))),r.register("arrays",new H(e)),r.register("scope",new O(()=>e.getState(),()=>e.getInitialValues(),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 Z(n){let{storeId:e,storeInstance:t,config:i,getState:r,getConfig:s,getValues:o,getDirtyValues:a,applyPersistedValues:l}=n,d=new w(i.persist,o,a,l),c=[...i.plugins],u=Y(i.devTools);u&&c.push(u);let g=new D(c,()=>({storeId:e,getState:()=>r(),getConfig:()=>s()})),f=new k(e,t,d,g);return f.initialize(),f}function ee(n){let{config:e,dependencyManager:t,computedManager:i}=n,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= (_class10 =class{__init36() {this._masksVersion=0}__init37() {this.scopeFieldsIndex=null}__init38() {this.computedEntriesCache=null}__init39() {this.transformEntriesCache=null}__init40() {this.batchDepth=0}__init41() {this.batchedState=null}__init42() {this.batchedChangedPaths=null}__init43() {this.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=_nullishCoalesce(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:_nullishCoalesce(t.computedDependsOn, () => (_optionalChain([t, 'access', _90 => _90.conditional, 'optionalAccess', _91 => _91.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(s=>s!==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={}){;_class10.prototype.__init36.call(this);_class10.prototype.__init37.call(this);_class10.prototype.__init38.call(this);_class10.prototype.__init39.call(this);_class10.prototype.__init40.call(this);_class10.prototype.__init41.call(this);_class10.prototype.__init42.call(this);_class10.prototype.__init43.call(this);this.config=X(e),this._initialValues=this.config.initialValues,this.dependencyManager=new V,this.computedManager=new C(()=>this.getComputedEntries()),this.dirtyManager=new F,this.capabilities=Q({store:this,dependencyManager:this.dependencyManager,dirtyManager:this.dirtyManager}),this.state=ee({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=Z({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)||_optionalChain([this, 'access', _92 => _92.config, 'access', _93 => _93.fields, 'optionalAccess', _94 => _94[e]])}getScopeFields(e){if(!this.scopeFieldsIndex){let t=new Map;this.dependencyManager.forEachFieldConfig((i,r)=>{if(!i.scope)return;let s=_nullishCoalesce(t.get(i.scope), () => ([]));s.push(r),t.set(i.scope,s)}),this.scopeFieldsIndex=t}return _nullishCoalesce(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:_nullishCoalesce(t.computedDependsOn, () => (_optionalChain([t, 'access', _95 => _95.conditional, 'optionalAccess', _96 => _96.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=_optionalChain([this, 'access', _97 => _97.getFieldConfig, 'call', _98 => _98(e), 'optionalAccess', _99 => _99.mask]);if(t)return typeof t=="string"?_optionalChain([this, 'access', _100 => _100.config, 'access', _101 => _101.masks, 'optionalAccess', _102 => _102[t]]):t}getState(){return _nullishCoalesce(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,[e])}unregisterField(e){if(_optionalChain([this, 'access', _103 => _103.config, 'access', _104 => _104.fields, 'optionalAccess', _105 => _105[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},s=!1;i[e]&&(delete i[e],s=!0),r[e]&&(delete r[e],s=!0),s&&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=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _106 => _106.equalityFn]), () => (S));return this.subscriptions.subscribeSelector(e,t,i,r)}subscribePath(e,t,i){let r=[..._nullishCoalesce(_optionalChain([i, 'optionalAccess', _107 => _107.paths]), () => ([])),e];return this.subscribeSelector(s=>p(s.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},this._masksVersion+=1,this.subscriptions.notify(this.state,["__masks__"])}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._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._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)}get initialValues(){return this._initialValues}getInitialValues(){return this._initialValues}setInitialValues(e){this._initialValues=e,this.config.initialValues=e}getMasksVersion(){return this._masksVersion}internalUpdateState(e,t){if(this.batchDepth>0){let r=W({currentState:_nullishCoalesce(this.batchedState, () => (this.state)),partialState:e,changedPaths:t,applyComputedValues:s=>s});if(this.batchedState=r.nextState,this.batchedValuesChanged||=r.valuesChanged,r.changedPaths&&r.changedPaths.length>0){let s=_nullishCoalesce(this.batchedChangedPaths, () => (new Set));r.changedPaths.forEach(o=>s.add(o)),this.batchedChangedPaths=s}return}let i=W({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._initialValues,...e});this.validation.cancelAll(),this.dependencyManager.evaluateAll(t);let i=this.dirtyManager.rebuild(t,this._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)}}, _class10);var te=new Set(["config","getConfig","getState","subscribe","setField","blurField","replaceValues","hydrate","rebase","setError","setErrors","setServerErrors","validate","reset","transaction","submit","registerMask","getMasksVersion","getDirtyValues","getPersistMetadata","restorePersisted","forceSave","clearPersisted","cleanup","registerField","unregisterField","isHidden","isRequired","isFieldDirty","isFieldValidating","watch","pushItem","prependItem","insertItem","removeItem","moveItem","swapItems","getHistoryMetadata","undo","redo","getStepStatus","getStepErrors"]),ie=new WeakMap;function ge(n){let e=new Proxy(n,{get(t,i){if(typeof i=="string"&&!te.has(i))return;let r=Reflect.get(t,i,t);return typeof r=="function"?r.bind(t):r},has(t,i){return typeof i=="string"&&te.has(i)},set(){return!1}});return ie.set(e,n),e}function fe(n){return typeof n.getFieldState=="function"&&typeof n.subscribePath=="function"&&typeof n.subscribeSelector=="function"&&typeof n.markFieldsTouched=="function"&&typeof n.hasValidationsInProgress=="function"&&typeof n.resolveMask=="function"&&typeof n.getScopeFields=="function"}function ye(n){let e=ie.get(n);if(e)return e;if(n instanceof b||fe(n))return n;throw new Error("BitForm: o store informado n\xE3o exp\xF5e a API necess\xE1ria para hooks/framework bindings.")}function me(n={}){return ge(new b(n))}exports.a = h; exports.b = P; exports.c = S; exports.d = m; exports.e = p; exports.f = y; exports.g = ne; exports.h = J; exports.i = ae; exports.j = T; exports.k = ye; exports.l = me;
2
+ //# sourceMappingURL=chunk-YCSWULEN.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/utils.ts"],"names":["deepClone","obj","item","clone","key","deepMerge","target","source","base","sourceValue","baseValue","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAAO,8kCAASA,CAAAA,CAAaC,CAAAA,CAAW,CACtC,EAAA,CAAIA,CAAAA,GAAQ,IAAA,EAAQ,OAAOA,CAAAA,EAAQ,QAAA,CACjC,OAAOA,CAAAA,CAGT,EAAA,CAAI,OAAO,eAAA,EAAoB,UAAA,CAC7B,OAAO,eAAA,CAAgBA,CAAG,CAAA,CAG5B,EAAA,CAAIA,EAAAA,WAAe,IAAA,CACjB,OAAO,IAAI,IAAA,CAAKA,CAAAA,CAAI,OAAA,CAAQ,CAAC,CAAA,CAE/B,EAAA,CAAIA,EAAAA,WAAe,MAAA,CACjB,OAAO,IAAI,MAAA,CAAOA,CAAAA,CAAI,MAAA,CAAQA,CAAAA,CAAI,KAAK,CAAA,CAGzC,EAAA,CAAI,KAAA,CAAM,OAAA,CAAQA,CAAG,CAAA,CACnB,OAAOA,CAAAA,CAAI,GAAA,CAAKC,CAAAA,EAASF,CAAAA,CAAUE,CAAI,CAAC,CAAA,CAG1C,IAAMC,CAAAA,CAAa,CAAC,CAAA,CACpB,GAAA,CAAA,IAAWC,EAAAA,GAAOH,CAAAA,CACZ,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,I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work/bit-form/bit-form/dist/chunk-OZKLQRO6.cjs","sourcesContent":["export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (typeof structuredClone === \"function\") {\n return structuredClone(obj);\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\nexport function deepMerge<T>(target: T, source: any): T {\n if (source === undefined) {\n return deepClone(target);\n }\n\n if (\n source === null ||\n typeof source !== \"object\" ||\n source instanceof Date ||\n source instanceof RegExp ||\n Array.isArray(source)\n ) {\n return deepClone(source as T);\n }\n\n const base =\n target && typeof target === \"object\" && !Array.isArray(target)\n ? deepClone(target as any)\n : ({} as Record<string, unknown>);\n\n for (const key of Object.keys(source)) {\n const sourceValue = source[key];\n const baseValue = (base as Record<string, unknown>)[key];\n\n if (\n sourceValue !== null &&\n typeof sourceValue === \"object\" &&\n !Array.isArray(sourceValue) &&\n !(sourceValue instanceof Date) &&\n !(sourceValue instanceof RegExp)\n ) {\n (base as Record<string, unknown>)[key] = deepMerge(\n baseValue,\n sourceValue,\n );\n continue;\n }\n\n (base as Record<string, unknown>)[key] = deepClone(sourceValue);\n }\n\n return base as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set<string>();\n for (const key of Object.keys(obj || {})) {\n allKeys.add(key);\n }\n for (const key of Object.keys(initial || {})) {\n allKeys.add(key);\n }\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst PATH_CACHE_MAX = 1000;\nconst pathCache = new Map<string, string[]>();\n\nfunction getPathKeys(path: string): string[] {\n const cached = pathCache.get(path);\n if (cached) {\n return cached;\n }\n\n const keys = path.split(\".\");\n if (pathCache.size >= PATH_CACHE_MAX) {\n pathCache.clear();\n }\n pathCache.set(path, keys);\n return keys;\n}\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = getPathKeys(path);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = getPathKeys(path);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function setDeepValues(\n obj: any,\n updates: ReadonlyArray<readonly [path: string, value: any]>,\n): any {\n if (updates.length === 0) {\n return obj;\n }\n\n const root = Array.isArray(obj) ? [...obj] : { ...obj };\n const clonedNodes = new WeakSet<object>();\n if (root && typeof root === \"object\") {\n clonedNodes.add(root);\n }\n\n for (const [path, value] of updates) {\n const keys = getPathKeys(path);\n let current: any = root;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n clonedNodes.add(current[key]);\n } else if (typeof currentValue === \"object\") {\n if (!clonedNodes.has(currentValue)) {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n clonedNodes.add(current[key]);\n }\n } else {\n current[key] = isNextNumeric ? [] : {};\n clonedNodes.add(current[key]);\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n }\n\n return root;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === removedIndex) {\n return null;\n }\n\n return currentIdx > removedIndex ? currentIdx - 1 : currentIdx;\n });\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === indexA) {\n return indexB;\n }\n\n if (currentIdx === indexB) {\n return indexA;\n }\n\n return currentIdx;\n });\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === from) {\n return to;\n }\n\n if (from < to && currentIdx > from && currentIdx <= to) {\n return currentIdx - 1;\n }\n\n if (from > to && currentIdx >= to && currentIdx < from) {\n return currentIdx + 1;\n }\n\n return currentIdx;\n });\n};\n\nexport function reindexFieldArrayMeta(\n state: {\n errors: Record<string, any>;\n touched: Record<string, any>;\n isValidating: Record<string, any>;\n },\n path: string,\n remapIndex: (index: number) => number | null,\n) {\n const nextErrors: Record<string, any> = {};\n const nextTouched: Record<string, any> = {};\n const nextIsValidating: Record<string, any> = {};\n\n const allKeys = new Set<string>();\n Object.keys(state.errors).forEach((key) => allKeys.add(key));\n Object.keys(state.touched).forEach((key) => allKeys.add(key));\n Object.keys(state.isValidating).forEach((key) => allKeys.add(key));\n\n const prefix = `${path}.`;\n\n for (const key of allKeys) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (!nextKey) {\n continue;\n }\n\n if (Object.prototype.hasOwnProperty.call(state.errors, key)) {\n nextErrors[nextKey] = state.errors[key];\n }\n\n if (Object.prototype.hasOwnProperty.call(state.touched, key)) {\n nextTouched[nextKey] = state.touched[key];\n }\n\n if (Object.prototype.hasOwnProperty.call(state.isValidating, key)) {\n nextIsValidating[nextKey] = state.isValidating[key];\n }\n }\n\n return {\n errors: nextErrors,\n touched: nextTouched,\n isValidating: nextIsValidating,\n };\n}\n\nfunction remapIndexedPath(\n key: string,\n prefix: string,\n remapIndex: (index: number) => number | null,\n) {\n if (!key.startsWith(prefix)) {\n return key;\n }\n\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const nextIdx = remapIndex(currentIdx);\n\n if (nextIdx === null) {\n return null;\n }\n\n const rest = parts.slice(1).join(\".\");\n return rest ? `${prefix}${nextIdx}.${rest}` : `${prefix}${nextIdx}`;\n}\n\nfunction reindexObjectKeys(\n obj: Record<string, any>,\n path: string,\n remapIndex: (index: number) => number | null,\n) {\n const nextObject: Record<string, any> = {};\n const prefix = `${path}.`;\n\n for (const key of Object.keys(obj)) {\n if (!key.startsWith(prefix)) {\n nextObject[key] = obj[key];\n continue;\n }\n\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const nextIdx = remapIndex(currentIdx);\n\n if (nextIdx === null) {\n continue;\n }\n\n const rest = parts.slice(1).join(\".\");\n const nextKey = rest\n ? `${prefix}${nextIdx}.${rest}`\n : `${prefix}${nextIdx}`;\n nextObject[nextKey] = obj[key];\n }\n\n return nextObject;\n}\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj))\n return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n"]}
1
+ {"version":3,"sources":["../src/core/utils.ts"],"names":["deepClone","obj","item","clone","key","deepMerge","target","source","base","sourceValue","baseValue","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAAO,8kCAASA,CAAAA,CAAaC,CAAAA,CAAW,CACtC,EAAA,CAAIA,CAAAA,GAAQ,IAAA,EAAQ,OAAOA,CAAAA,EAAQ,QAAA,CACjC,OAAOA,CAAAA,CAGT,EAAA,CAAI,OAAO,eAAA,EAAoB,UAAA,CAC7B,OAAO,eAAA,CAAgBA,CAAG,CAAA,CAG5B,EAAA,CAAIA,EAAAA,WAAe,IAAA,CACjB,OAAO,IAAI,IAAA,CAAKA,CAAAA,CAAI,OAAA,CAAQ,CAAC,CAAA,CAE/B,EAAA,CAAIA,EAAAA,WAAe,MAAA,CACjB,OAAO,IAAI,MAAA,CAAOA,CAAAA,CAAI,MAAA,CAAQA,CAAAA,CAAI,KAAK,CAAA,CAGzC,EAAA,CAAI,KAAA,CAAM,OAAA,CAAQA,CAAG,CAAA,CACnB,OAAOA,CAAAA,CAAI,GAAA,CAAKC,CAAAA,EAASF,CAAAA,CAAUE,CAAI,CAAC,CAAA,CAG1C,IAAMC,CAAAA,CAAa,CAAC,CAAA,CACpB,GAAA,CAAA,IAAWC,EAAAA,GAAOH,CAAAA,CACZ,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAKA,CAAAA,CAAKG,CAAG,CAAA,EAAA,CAC/CD,CAAAA,CAAMC,CAAG,CAAA,CAAIJ,CAAAA,CAAWC,CAAAA,CAAYG,CAAG,CAAC,CAAA,CAAA,CAG5C,OAAOD,CACT,CAEO,SAASE,CAAAA,CAAaC,CAAAA,CAAWC,CAAAA,CAA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AS,EAAA,CACTC,CAAAA,CAAsB,IAAI,GAAA,CACb,CACb,EAAA,CAAIT,CAAAA,CAAWV,CAAAA,CAAKiB,CAAO,CAAA,CAAG,OAAOE,CAAAA,CACrC,EAAA,CACEnB,CAAAA,GAAQ,IAAA,EACR,OAAOA,CAAAA,EAAQ,QAAA,EACfiB,CAAAA,GAAY,IAAA,EACZ,OAAOA,CAAAA,EAAY,QAAA,CAEnB,OAAIC,CAAAA,EAAQC,CAAAA,CAAO,GAAA,CAAID,CAAM,CAAA,CACtBC,CAAAA,CAET,EAAA,CAAI,KAAA,CAAM,OAAA,CAAQnB,CAAG,CAAA,EAAK,KAAA,CAAM,OAAA,CAAQiB,CAAO,CAAA,CAC7C,MAAI,CAACP,CAAAA,CAAWV,CAAAA,CAAKiB,CAAO,CAAA,EAAKC,CAAAA,EAAQC,CAAAA,CAAO,GAAA,CAAID,CAAM,CAAA,CACnDC,CAAAA,CAET,IAAMC,CAAAA,CAAU,IAAI,GAAA,CACpB,GAAA,CAAA,IAAWjB,EAAAA,GAAO,MAAA,CAAO,IAAA,CAAKH,CAAAA,EAAO,CAAC,CAAC,CAAA,CACrCoB,CAAAA,CAAQ,GAAA,CAAIjB,CAAG,CAAA,CAEjB,GAAA,CAAA,IAAWA,EAAAA,GAAO,MAAA,CAAO,IAAA,CAAKc,CAAAA,EAAW,CAAC,CAAC,CAAA,CACzCG,CAAAA,CAAQ,GAAA,CAAIjB,CAAG,CAAA,CAEjB,GAAA,CAAA,IAAWkB,EAAAA,GAAKD,CAAAA,CAAS,CACvB,IAAME,CAAAA,CAAIJ,CAAAA,CAAS,CAAA,EAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-YCSWULEN.cjs","sourcesContent":["export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (typeof structuredClone === \"function\") {\n return structuredClone(obj);\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\nexport function deepMerge<T>(target: T, source: any): T {\n if (source === undefined) {\n return deepClone(target);\n }\n\n if (\n source === null ||\n typeof source !== \"object\" ||\n source instanceof Date ||\n source instanceof RegExp ||\n Array.isArray(source)\n ) {\n return deepClone(source as T);\n }\n\n const base =\n target && typeof target === \"object\" && !Array.isArray(target)\n ? deepClone(target as any)\n : ({} as Record<string, unknown>);\n\n for (const key of Object.keys(source)) {\n const sourceValue = source[key];\n const baseValue = (base as Record<string, unknown>)[key];\n\n if (\n sourceValue !== null &&\n typeof sourceValue === \"object\" &&\n !Array.isArray(sourceValue) &&\n !(sourceValue instanceof Date) &&\n !(sourceValue instanceof RegExp)\n ) {\n (base as Record<string, unknown>)[key] = deepMerge(\n baseValue,\n sourceValue,\n );\n continue;\n }\n\n (base as Record<string, unknown>)[key] = deepClone(sourceValue);\n }\n\n return base as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set<string>();\n for (const key of Object.keys(obj || {})) {\n allKeys.add(key);\n }\n for (const key of Object.keys(initial || {})) {\n allKeys.add(key);\n }\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst PATH_CACHE_MAX = 1000;\nconst pathCache = new Map<string, string[]>();\n\nfunction getPathKeys(path: string): string[] {\n const cached = pathCache.get(path);\n if (cached) {\n return cached;\n }\n\n const keys = path.split(\".\");\n if (pathCache.size >= PATH_CACHE_MAX) {\n pathCache.clear();\n }\n pathCache.set(path, keys);\n return keys;\n}\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = getPathKeys(path);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = getPathKeys(path);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function setDeepValues(\n obj: any,\n updates: ReadonlyArray<readonly [path: string, value: any]>,\n): any {\n if (updates.length === 0) {\n return obj;\n }\n\n const root = Array.isArray(obj) ? [...obj] : { ...obj };\n const clonedNodes = new WeakSet<object>();\n if (root && typeof root === \"object\") {\n clonedNodes.add(root);\n }\n\n for (const [path, value] of updates) {\n const keys = getPathKeys(path);\n let current: any = root;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n clonedNodes.add(current[key]);\n } else if (typeof currentValue === \"object\") {\n if (!clonedNodes.has(currentValue)) {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n clonedNodes.add(current[key]);\n }\n } else {\n current[key] = isNextNumeric ? [] : {};\n clonedNodes.add(current[key]);\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n }\n\n return root;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === removedIndex) {\n return null;\n }\n\n return currentIdx > removedIndex ? currentIdx - 1 : currentIdx;\n });\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === indexA) {\n return indexB;\n }\n\n if (currentIdx === indexB) {\n return indexA;\n }\n\n return currentIdx;\n });\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n return reindexObjectKeys(obj, path, (currentIdx) => {\n if (currentIdx === from) {\n return to;\n }\n\n if (from < to && currentIdx > from && currentIdx <= to) {\n return currentIdx - 1;\n }\n\n if (from > to && currentIdx >= to && currentIdx < from) {\n return currentIdx + 1;\n }\n\n return currentIdx;\n });\n};\n\nexport function reindexFieldArrayMeta(\n state: {\n errors: Record<string, any>;\n touched: Record<string, any>;\n isValidating: Record<string, any>;\n },\n path: string,\n remapIndex: (index: number) => number | null,\n) {\n const nextErrors: Record<string, any> = {};\n const nextTouched: Record<string, any> = {};\n const nextIsValidating: Record<string, any> = {};\n\n const prefix = `${path}.`;\n\n // Iterate each dictionary directly to avoid building a union Set of all keys.\n for (const key of Object.keys(state.errors)) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (nextKey) nextErrors[nextKey] = state.errors[key];\n }\n\n for (const key of Object.keys(state.touched)) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (nextKey) nextTouched[nextKey] = state.touched[key];\n }\n\n for (const key of Object.keys(state.isValidating)) {\n const nextKey = remapIndexedPath(key, prefix, remapIndex);\n if (nextKey) nextIsValidating[nextKey] = state.isValidating[key];\n }\n\n return {\n errors: nextErrors,\n touched: nextTouched,\n isValidating: nextIsValidating,\n };\n}\n\nfunction remapIndexedPath(\n key: string,\n prefix: string,\n remapIndex: (index: number) => number | null,\n) {\n if (!key.startsWith(prefix)) {\n return key;\n }\n\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const nextIdx = remapIndex(currentIdx);\n\n if (nextIdx === null) {\n return null;\n }\n\n const rest = parts.slice(1).join(\".\");\n return rest ? `${prefix}${nextIdx}.${rest}` : `${prefix}${nextIdx}`;\n}\n\nfunction reindexObjectKeys(\n obj: Record<string, any>,\n path: string,\n remapIndex: (index: number) => number | null,\n) {\n const nextObject: Record<string, any> = {};\n const prefix = `${path}.`;\n\n for (const key of Object.keys(obj)) {\n if (!key.startsWith(prefix)) {\n nextObject[key] = obj[key];\n continue;\n }\n\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const nextIdx = remapIndex(currentIdx);\n\n if (nextIdx === null) {\n continue;\n }\n\n const rest = parts.slice(1).join(\".\");\n const nextKey = rest\n ? `${prefix}${nextIdx}.${rest}`\n : `${prefix}${nextIdx}`;\n nextObject[nextKey] = obj[key];\n }\n\n return nextObject;\n}\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj))\n return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkOZKLQRO6cjs = require('../chunk-OZKLQRO6.cjs');var S=o=>{let e=typeof o.getState=="function"?o.getState():o,t=_optionalChain([o, 'optionalAccess', _ => _.getHistoryMetadata, 'optionalCall', _2 => _2()])||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...e,_meta:{canUndo:t.canUndo,canRedo:t.canRedo,totalSteps:t.historySize,currentIndex:t.historyIndex}}},l=null,m=o=>{if(!o||typeof o!="object")return!1;let{storeId:e,action:t}=o;return typeof e=="string"&&(t==="undo"||t==="redo"||t==="reset")};function v(o){l&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),l());let e=null,t=null,d,f=!1,u=()=>{f=!1,e=new WebSocket(o),e.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let i=Object.entries(_chunkOZKLQRO6cjs.j.stores);if(i.length>0){let n=i.reduce((r,[s,a])=>(r[s]=S(a),r),{});_optionalChain([e, 'optionalAccess', _3 => _3.send, 'call', _4 => _4(JSON.stringify({type:"STATE_UPDATE",payload:n}))])}t=_chunkOZKLQRO6cjs.j.subscribe((n,r)=>{if(_optionalChain([e, 'optionalAccess', _5 => _5.readyState])===WebSocket.OPEN){let s=_chunkOZKLQRO6cjs.j.stores[n];s&&e.send(JSON.stringify({type:"STATE_UPDATE",payload:{[n]:S(s)}}))}}),d=setInterval(()=>{_optionalChain([e, 'optionalAccess', _6 => _6.readyState])===WebSocket.OPEN&&e.send(JSON.stringify({type:"PING"}))},3e4)},e.onmessage=i=>{try{let n=JSON.parse(i.data);if(n.type==="ACTION"){if(!m(n.payload))return;let{storeId:r,action:s}=n.payload,a=_chunkOZKLQRO6cjs.j.stores[r];if(!a||typeof a!="object")return;let p=a[{undo:"undo",redo:"redo",reset:"reset"}[s]];typeof p=="function"&&p.call(a)}}catch(n){console.warn("[bit-form] Erro ao processar comando do CLI:",n)}},e.onclose=()=>{t&&t(),clearInterval(d),f?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(u,3e3))}};u();let y=()=>{f=!0,t&&t(),clearInterval(d),e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(),l=null};return l=y,y}exports.setupRemoteBridge = v;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkYCSWULENcjs = require('../chunk-YCSWULEN.cjs');var S=o=>{let e=typeof o.getState=="function"?o.getState():o,t=_optionalChain([o, 'optionalAccess', _ => _.getHistoryMetadata, 'optionalCall', _2 => _2()])||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...e,_meta:{canUndo:t.canUndo,canRedo:t.canRedo,totalSteps:t.historySize,currentIndex:t.historyIndex}}},l=null,m=o=>{if(!o||typeof o!="object")return!1;let{storeId:e,action:t}=o;return typeof e=="string"&&(t==="undo"||t==="redo"||t==="reset")};function v(o){l&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),l());let e=null,t=null,d,f=!1,u=()=>{f=!1,e=new WebSocket(o),e.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let i=Object.entries(_chunkYCSWULENcjs.j.stores);if(i.length>0){let n=i.reduce((r,[s,a])=>(r[s]=S(a),r),{});_optionalChain([e, 'optionalAccess', _3 => _3.send, 'call', _4 => _4(JSON.stringify({type:"STATE_UPDATE",payload:n}))])}t=_chunkYCSWULENcjs.j.subscribe((n,r)=>{if(_optionalChain([e, 'optionalAccess', _5 => _5.readyState])===WebSocket.OPEN){let s=_chunkYCSWULENcjs.j.stores[n];s&&e.send(JSON.stringify({type:"STATE_UPDATE",payload:{[n]:S(s)}}))}}),d=setInterval(()=>{_optionalChain([e, 'optionalAccess', _6 => _6.readyState])===WebSocket.OPEN&&e.send(JSON.stringify({type:"PING"}))},3e4)},e.onmessage=i=>{try{let n=JSON.parse(i.data);if(n.type==="ACTION"){if(!m(n.payload))return;let{storeId:r,action:s}=n.payload,a=_chunkYCSWULENcjs.j.stores[r];if(!a||typeof a!="object")return;let p=a[{undo:"undo",redo:"redo",reset:"reset"}[s]];typeof p=="function"&&p.call(a)}}catch(n){console.warn("[bit-form] Erro ao processar comando do CLI:",n)}},e.onclose=()=>{t&&t(),clearInterval(d),f?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(u,3e3))}};u();let y=()=>{f=!0,t&&t(),clearInterval(d),e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(),l=null};return l=y,y}exports.setupRemoteBridge = v;
2
2
  //# sourceMappingURL=bridge.cjs.map
@@ -1,2 +1,2 @@
1
- import{j as c}from"../chunk-64KSP4TP.js";var S=o=>{let e=typeof o.getState=="function"?o.getState():o,t=o?.getHistoryMetadata?.()||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...e,_meta:{canUndo:t.canUndo,canRedo:t.canRedo,totalSteps:t.historySize,currentIndex:t.historyIndex}}},l=null,m=o=>{if(!o||typeof o!="object")return!1;let{storeId:e,action:t}=o;return typeof e=="string"&&(t==="undo"||t==="redo"||t==="reset")};function v(o){l&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),l());let e=null,t=null,d,f=!1,u=()=>{f=!1,e=new WebSocket(o),e.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let i=Object.entries(c.stores);if(i.length>0){let n=i.reduce((r,[s,a])=>(r[s]=S(a),r),{});e?.send(JSON.stringify({type:"STATE_UPDATE",payload:n}))}t=c.subscribe((n,r)=>{if(e?.readyState===WebSocket.OPEN){let s=c.stores[n];s&&e.send(JSON.stringify({type:"STATE_UPDATE",payload:{[n]:S(s)}}))}}),d=setInterval(()=>{e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"PING"}))},3e4)},e.onmessage=i=>{try{let n=JSON.parse(i.data);if(n.type==="ACTION"){if(!m(n.payload))return;let{storeId:r,action:s}=n.payload,a=c.stores[r];if(!a||typeof a!="object")return;let p=a[{undo:"undo",redo:"redo",reset:"reset"}[s]];typeof p=="function"&&p.call(a)}}catch(n){console.warn("[bit-form] Erro ao processar comando do CLI:",n)}},e.onclose=()=>{t&&t(),clearInterval(d),f?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(u,3e3))}};u();let y=()=>{f=!0,t&&t(),clearInterval(d),e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(),l=null};return l=y,y}export{v as setupRemoteBridge};
1
+ import{j as c}from"../chunk-PX6WKENM.js";var S=o=>{let e=typeof o.getState=="function"?o.getState():o,t=o?.getHistoryMetadata?.()||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...e,_meta:{canUndo:t.canUndo,canRedo:t.canRedo,totalSteps:t.historySize,currentIndex:t.historyIndex}}},l=null,m=o=>{if(!o||typeof o!="object")return!1;let{storeId:e,action:t}=o;return typeof e=="string"&&(t==="undo"||t==="redo"||t==="reset")};function v(o){l&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),l());let e=null,t=null,d,f=!1,u=()=>{f=!1,e=new WebSocket(o),e.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let i=Object.entries(c.stores);if(i.length>0){let n=i.reduce((r,[s,a])=>(r[s]=S(a),r),{});e?.send(JSON.stringify({type:"STATE_UPDATE",payload:n}))}t=c.subscribe((n,r)=>{if(e?.readyState===WebSocket.OPEN){let s=c.stores[n];s&&e.send(JSON.stringify({type:"STATE_UPDATE",payload:{[n]:S(s)}}))}}),d=setInterval(()=>{e?.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"PING"}))},3e4)},e.onmessage=i=>{try{let n=JSON.parse(i.data);if(n.type==="ACTION"){if(!m(n.payload))return;let{storeId:r,action:s}=n.payload,a=c.stores[r];if(!a||typeof a!="object")return;let p=a[{undo:"undo",redo:"redo",reset:"reset"}[s]];typeof p=="function"&&p.call(a)}}catch(n){console.warn("[bit-form] Erro ao processar comando do CLI:",n)}},e.onclose=()=>{t&&t(),clearInterval(d),f?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(u,3e3))}};u();let y=()=>{f=!0,t&&t(),clearInterval(d),e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(),l=null};return l=y,y}export{v as setupRemoteBridge};
2
2
  //# sourceMappingURL=bridge.js.map
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _chunkOZKLQRO6cjs = require('../chunk-OZKLQRO6.cjs');function b(){return`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var _chunkYCSWULENcjs = require('../chunk-YCSWULEN.cjs');function b(){return`
2
2
  .bit-devtools-container {
3
3
  position: fixed;
4
4
  bottom: 20px;
@@ -129,5 +129,5 @@
129
129
  <button class="bit-devtools-trigger" style="transform: ${this.isOpen?"scale(0.9)":"scale(1)"};" title="Abrir DevTools">
130
130
  ${this.isOpen?"\u2716":"Bit"}
131
131
  </button>
132
- `;this.rootElement.innerHTML=r+e}}, _class);function g(a){let i=new c(a,{onUndo:s=>_optionalChain([_chunkOZKLQRO6cjs.j, 'access', _ => _.stores, 'access', _2 => _2[s], 'optionalAccess', _3 => _3.undo, 'call', _4 => _4()]),onRedo:s=>_optionalChain([_chunkOZKLQRO6cjs.j, 'access', _5 => _5.stores, 'access', _6 => _6[s], 'optionalAccess', _7 => _7.redo, 'call', _8 => _8()]),onReset:s=>_optionalChain([_chunkOZKLQRO6cjs.j, 'access', _9 => _9.stores, 'access', _10 => _10[s], 'optionalAccess', _11 => _11.reset, 'call', _12 => _12()])}),r=()=>{let s={};for(let[t,o]of Object.entries(_chunkOZKLQRO6cjs.j.stores)){let n=o,p=n.getState(),l=_optionalChain([n, 'optionalAccess', _13 => _13.getHistoryMetadata, 'optionalCall', _14 => _14()])||{enabled:!1,canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};s[t]={...p,_meta:{canUndo:l.canUndo,canRedo:l.canRedo,totalSteps:l.historySize,currentIndex:l.historyIndex}}}return s};i.updateState(r());let e=_chunkOZKLQRO6cjs.j.subscribe(()=>{i.updateState(r())});return{ui:i,destroy:()=>{e(),a.innerHTML=""}}}function f(a,i="ws://localhost:3000"){let r=new WebSocket(i),e=o=>{r.readyState===WebSocket.OPEN?r.send(JSON.stringify(o)):console.warn("[bit-form] Tentativa de envio falhou. WebSocket n\xE3o est\xE1 aberto.")},s=(o,n)=>{e({type:"ACTION",payload:{storeId:o,action:n}})},t=new c(a,{onUndo:o=>s(o,"undo"),onRedo:o=>s(o,"redo"),onReset:o=>s(o,"reset")});return r.addEventListener("open",()=>{console.log(`[bit-form] Conectado ao DevTools remoto em ${i}`)}),r.addEventListener("message",o=>{try{let n=JSON.parse(o.data);n.type==="STATE_UPDATE"&&t.updateState(n.payload)}catch(n){console.error("[bit-form] Erro ao processar mensagem do WebSocket:",n)}}),r.addEventListener("error",o=>{console.error("[bit-form] Erro na conex\xE3o do DevTools remoto:",o)}),{ui:t,destroy:()=>{(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close(),a.innerHTML=""}}}function m(a={}){let{mode:i="local",url:r}=a,e,s=!1;if(typeof a.container=="string"){let o=document.querySelector(a.container);if(!o)throw new Error(`[bit-form] Container '${a.container}' n\xE3o encontrado na p\xE1gina.`);e=o}else a.container instanceof HTMLElement?e=a.container:(e=document.createElement("div"),e.id="bit-form-devtools-root",e.style.position="fixed",e.style.bottom="20px",e.style.right="20px",e.style.zIndex="9999",e.style.maxHeight="80vh",e.style.overflowY="auto",e.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(e),s=!0);let t;if(i==="local")console.log("[bit-form] DevTools iniciado em modo Local."),t=g(e);else if(i==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),t=f(e,r);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${i}`);return{...t,destroy:()=>{t&&typeof t.destroy=="function"&&t.destroy(),s&&e.parentNode?e.parentNode.removeChild(e):e.innerHTML=""}}}exports.initDevTools = m;
132
+ `;this.rootElement.innerHTML=r+e}}, _class);function g(a){let i=new c(a,{onUndo:s=>_optionalChain([_chunkYCSWULENcjs.j, 'access', _ => _.stores, 'access', _2 => _2[s], 'optionalAccess', _3 => _3.undo, 'call', _4 => _4()]),onRedo:s=>_optionalChain([_chunkYCSWULENcjs.j, 'access', _5 => _5.stores, 'access', _6 => _6[s], 'optionalAccess', _7 => _7.redo, 'call', _8 => _8()]),onReset:s=>_optionalChain([_chunkYCSWULENcjs.j, 'access', _9 => _9.stores, 'access', _10 => _10[s], 'optionalAccess', _11 => _11.reset, 'call', _12 => _12()])}),r=()=>{let s={};for(let[t,o]of Object.entries(_chunkYCSWULENcjs.j.stores)){let n=o,p=n.getState(),l=_optionalChain([n, 'optionalAccess', _13 => _13.getHistoryMetadata, 'optionalCall', _14 => _14()])||{enabled:!1,canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};s[t]={...p,_meta:{canUndo:l.canUndo,canRedo:l.canRedo,totalSteps:l.historySize,currentIndex:l.historyIndex}}}return s};i.updateState(r());let e=_chunkYCSWULENcjs.j.subscribe(()=>{i.updateState(r())});return{ui:i,destroy:()=>{e(),a.innerHTML=""}}}function f(a,i="ws://localhost:3000"){let r=new WebSocket(i),e=o=>{r.readyState===WebSocket.OPEN?r.send(JSON.stringify(o)):console.warn("[bit-form] Tentativa de envio falhou. WebSocket n\xE3o est\xE1 aberto.")},s=(o,n)=>{e({type:"ACTION",payload:{storeId:o,action:n}})},t=new c(a,{onUndo:o=>s(o,"undo"),onRedo:o=>s(o,"redo"),onReset:o=>s(o,"reset")});return r.addEventListener("open",()=>{console.log(`[bit-form] Conectado ao DevTools remoto em ${i}`)}),r.addEventListener("message",o=>{try{let n=JSON.parse(o.data);n.type==="STATE_UPDATE"&&t.updateState(n.payload)}catch(n){console.error("[bit-form] Erro ao processar mensagem do WebSocket:",n)}}),r.addEventListener("error",o=>{console.error("[bit-form] Erro na conex\xE3o do DevTools remoto:",o)}),{ui:t,destroy:()=>{(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close(),a.innerHTML=""}}}function m(a={}){let{mode:i="local",url:r}=a,e,s=!1;if(typeof a.container=="string"){let o=document.querySelector(a.container);if(!o)throw new Error(`[bit-form] Container '${a.container}' n\xE3o encontrado na p\xE1gina.`);e=o}else a.container instanceof HTMLElement?e=a.container:(e=document.createElement("div"),e.id="bit-form-devtools-root",e.style.position="fixed",e.style.bottom="20px",e.style.right="20px",e.style.zIndex="9999",e.style.maxHeight="80vh",e.style.overflowY="auto",e.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(e),s=!0);let t;if(i==="local")console.log("[bit-form] DevTools iniciado em modo Local."),t=g(e);else if(i==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),t=f(e,r);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${i}`);return{...t,destroy:()=>{t&&typeof t.destroy=="function"&&t.destroy(),s&&e.parentNode?e.parentNode.removeChild(e):e.innerHTML=""}}}exports.initDevTools = m;
133
133
  //# sourceMappingURL=index.cjs.map
@@ -1,4 +1,4 @@
1
- import{j as d}from"../chunk-64KSP4TP.js";function b(){return`
1
+ import{j as d}from"../chunk-PX6WKENM.js";function b(){return`
2
2
  .bit-devtools-container {
3
3
  position: fixed;
4
4
  bottom: 20px;
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkOZKLQRO6cjs = require('./chunk-OZKLQRO6.cjs');exports.bitBus = _chunkOZKLQRO6cjs.j; exports.cleanPrefixedKeys = _chunkOZKLQRO6cjs.g; exports.createBitStore = _chunkOZKLQRO6cjs.l; exports.deepClone = _chunkOZKLQRO6cjs.a; exports.deepEqual = _chunkOZKLQRO6cjs.d; exports.deepMerge = _chunkOZKLQRO6cjs.b; exports.extractServerErrors = _chunkOZKLQRO6cjs.i; exports.getDeepValue = _chunkOZKLQRO6cjs.e; exports.isValidationErrorShape = _chunkOZKLQRO6cjs.h; exports.resolveBitStoreForHooks = _chunkOZKLQRO6cjs.k; exports.setDeepValue = _chunkOZKLQRO6cjs.f; exports.valueEqual = _chunkOZKLQRO6cjs.c;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYCSWULENcjs = require('./chunk-YCSWULEN.cjs');exports.bitBus = _chunkYCSWULENcjs.j; exports.cleanPrefixedKeys = _chunkYCSWULENcjs.g; exports.createBitStore = _chunkYCSWULENcjs.l; exports.deepClone = _chunkYCSWULENcjs.a; exports.deepEqual = _chunkYCSWULENcjs.d; exports.deepMerge = _chunkYCSWULENcjs.b; exports.extractServerErrors = _chunkYCSWULENcjs.i; exports.getDeepValue = _chunkYCSWULENcjs.e; exports.isValidationErrorShape = _chunkYCSWULENcjs.h; exports.resolveBitStoreForHooks = _chunkYCSWULENcjs.k; exports.setDeepValue = _chunkYCSWULENcjs.f; exports.valueEqual = _chunkYCSWULENcjs.c;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { B as BitMask, a as BitMaskName } from './types-D8DgIUhJ.cjs';
2
2
  import { o as BitComputedFn, B as BitConfig, a as BitFieldDefinition, p as BitTransformFn, e as BitState, f as BitPath, m as BitFieldState, g as BitPathValue, q as BitFieldChangeMeta, h as DeepPartial, i as BitErrors, j as BitPersistMetadata, k as BitArrayPath, l as BitArrayItem, r as BitBeforeValidateEvent, s as BitAfterValidateEvent, t as BitBeforeSubmitEvent, u as BitAfterSubmitEvent, v as BitFieldChangeEvent } from './bus-BeAeZwWu.cjs';
3
3
  export { w as BitFieldConditional, x as BitFieldValidation, y as BitHistoryConfig, z as BitPersistConfig, A as BitPersistMode, C as BitPersistStorageAdapter, d as BitPlugin, E as BitPluginContext, F as BitPluginErrorEvent, G as BitPluginHooks, H as BitTouched, I as BitValidationConfig, S as ScopeStatus, n as ValidateScopeResult, V as ValidatorFn, J as bitBus } from './bus-BeAeZwWu.cjs';
4
- import { B as BitFrameworkConfig, a as BitSelector, b as BitSelectorSubscriptionOptions, c as BitHistoryMetadata, d as BitValidationOptions, e as BitStoreApi, f as BitStoreHooksApi } from './public-types-BQXaxmAE.cjs';
5
- export { g as BitEqualityFn } from './public-types-BQXaxmAE.cjs';
4
+ import { B as BitFrameworkConfig, a as BitSelector, b as BitSelectorSubscriptionOptions, c as BitHistoryMetadata, d as BitValidationOptions, e as BitStoreApi, f as BitStoreHooksApi } from './public-types-Cd9ai20P.cjs';
5
+ export { g as BitEqualityFn } from './public-types-Cd9ai20P.cjs';
6
6
  export { a as BitDeleteUploadFn, B as BitUploadFn, b as BitUploadResult } from './upload-EXnJLq8k.cjs';
7
7
 
8
8
  interface BitComputedEntry<T extends object> {
@@ -30,6 +30,13 @@ declare class BitStore<T extends object = any> {
30
30
  private readonly subscriptions;
31
31
  private readonly effects;
32
32
  private readonly capabilities;
33
+ /** Baseline for dirty tracking. Decoupled from config so that rebaseValues
34
+ * can update it without mutating the user-provided config object. */
35
+ private _initialValues;
36
+ /** Incremented on every registerMask() call so React hooks can track mask
37
+ * configuration changes via useSyncExternalStore without putting masks in
38
+ * BitState and triggering a full re-render of all fields. */
39
+ private _masksVersion;
33
40
  config: BitFrameworkConfig<T>;
34
41
  readonly storeId: string;
35
42
  private readonly dependencyManager;
@@ -140,6 +147,20 @@ declare class BitStore<T extends object = any> {
140
147
  buildDirtyValues(values: T): Partial<T>;
141
148
  batchStateUpdates<TResult>(callback: () => TResult): TResult;
142
149
  resetHistory(initialValues: T): void;
150
+ /** Current baseline used for dirty-state comparisons. */
151
+ get initialValues(): T;
152
+ /** Returns the current baseline (usable as a port method). */
153
+ getInitialValues(): T;
154
+ /**
155
+ * Updates the baseline used for dirty comparisons.
156
+ * Called by rebaseValues so that config is never mutated directly by managers.
157
+ * Also syncs config.initialValues so getConfig() reflects the new baseline.
158
+ */
159
+ setInitialValues(values: T): void;
160
+ /** Returns a monotonically increasing counter that increments every time a
161
+ * mask is registered via registerMask(). Used by React components to track
162
+ * mask configuration changes reactively without storing masks in BitState. */
163
+ getMasksVersion(): number;
143
164
  internalUpdateState(partialState: Partial<BitState<T>>, changedPaths?: string[]): void;
144
165
  internalSaveSnapshot(): void;
145
166
  private applyPersistedValues;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { B as BitMask, a as BitMaskName } from './types-D8DgIUhJ.js';
2
2
  import { o as BitComputedFn, B as BitConfig, a as BitFieldDefinition, p as BitTransformFn, e as BitState, f as BitPath, m as BitFieldState, g as BitPathValue, q as BitFieldChangeMeta, h as DeepPartial, i as BitErrors, j as BitPersistMetadata, k as BitArrayPath, l as BitArrayItem, r as BitBeforeValidateEvent, s as BitAfterValidateEvent, t as BitBeforeSubmitEvent, u as BitAfterSubmitEvent, v as BitFieldChangeEvent } from './bus-B4zZmB9C.js';
3
3
  export { w as BitFieldConditional, x as BitFieldValidation, y as BitHistoryConfig, z as BitPersistConfig, A as BitPersistMode, C as BitPersistStorageAdapter, d as BitPlugin, E as BitPluginContext, F as BitPluginErrorEvent, G as BitPluginHooks, H as BitTouched, I as BitValidationConfig, S as ScopeStatus, n as ValidateScopeResult, V as ValidatorFn, J as bitBus } from './bus-B4zZmB9C.js';
4
- import { B as BitFrameworkConfig, a as BitSelector, b as BitSelectorSubscriptionOptions, c as BitHistoryMetadata, d as BitValidationOptions, e as BitStoreApi, f as BitStoreHooksApi } from './public-types-CVgFf_qY.js';
5
- export { g as BitEqualityFn } from './public-types-CVgFf_qY.js';
4
+ import { B as BitFrameworkConfig, a as BitSelector, b as BitSelectorSubscriptionOptions, c as BitHistoryMetadata, d as BitValidationOptions, e as BitStoreApi, f as BitStoreHooksApi } from './public-types-DdZxD6Op.js';
5
+ export { g as BitEqualityFn } from './public-types-DdZxD6Op.js';
6
6
  export { a as BitDeleteUploadFn, B as BitUploadFn, b as BitUploadResult } from './upload-EXnJLq8k.js';
7
7
 
8
8
  interface BitComputedEntry<T extends object> {
@@ -30,6 +30,13 @@ declare class BitStore<T extends object = any> {
30
30
  private readonly subscriptions;
31
31
  private readonly effects;
32
32
  private readonly capabilities;
33
+ /** Baseline for dirty tracking. Decoupled from config so that rebaseValues
34
+ * can update it without mutating the user-provided config object. */
35
+ private _initialValues;
36
+ /** Incremented on every registerMask() call so React hooks can track mask
37
+ * configuration changes via useSyncExternalStore without putting masks in
38
+ * BitState and triggering a full re-render of all fields. */
39
+ private _masksVersion;
33
40
  config: BitFrameworkConfig<T>;
34
41
  readonly storeId: string;
35
42
  private readonly dependencyManager;
@@ -140,6 +147,20 @@ declare class BitStore<T extends object = any> {
140
147
  buildDirtyValues(values: T): Partial<T>;
141
148
  batchStateUpdates<TResult>(callback: () => TResult): TResult;
142
149
  resetHistory(initialValues: T): void;
150
+ /** Current baseline used for dirty-state comparisons. */
151
+ get initialValues(): T;
152
+ /** Returns the current baseline (usable as a port method). */
153
+ getInitialValues(): T;
154
+ /**
155
+ * Updates the baseline used for dirty comparisons.
156
+ * Called by rebaseValues so that config is never mutated directly by managers.
157
+ * Also syncs config.initialValues so getConfig() reflects the new baseline.
158
+ */
159
+ setInitialValues(values: T): void;
160
+ /** Returns a monotonically increasing counter that increments every time a
161
+ * mask is registered via registerMask(). Used by React components to track
162
+ * mask configuration changes reactively without storing masks in BitState. */
163
+ getMasksVersion(): number;
143
164
  internalUpdateState(partialState: Partial<BitState<T>>, changedPaths?: string[]): void;
144
165
  internalSaveSnapshot(): void;
145
166
  private applyPersistedValues;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d}from"./chunk-64KSP4TP.js";export{b as bitBus,t as cleanPrefixedKeys,d as createBitStore,o as deepClone,f as deepEqual,r as deepMerge,a as extractServerErrors,m as getDeepValue,x as isValidationErrorShape,c as resolveBitStoreForHooks,p as setDeepValue,e as valueEqual};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d}from"./chunk-PX6WKENM.js";export{b as bitBus,t as cleanPrefixedKeys,d as createBitStore,o as deepClone,f as deepEqual,r as deepMerge,a as extractServerErrors,m as getDeepValue,x as isValidationErrorShape,c as resolveBitStoreForHooks,p as setDeepValue,e as valueEqual};
2
2
  //# sourceMappingURL=index.js.map
@@ -88,6 +88,9 @@ interface BitStoreHooksApi<T extends object = any> extends BitStoreApi<T> {
88
88
  markFieldsTouched(paths: string[]): void;
89
89
  hasValidationsInProgress(scopeFields?: string[]): boolean;
90
90
  resolveMask(path: string): BitMask | undefined;
91
+ /** Returns a version counter that increments on every registerMask() call.
92
+ * Used by React hooks to track mask config changes reactively. */
93
+ getMasksVersion(): number;
91
94
  getScopeFields(scopeName: string): string[];
92
95
  }
93
96
 
@@ -88,6 +88,9 @@ interface BitStoreHooksApi<T extends object = any> extends BitStoreApi<T> {
88
88
  markFieldsTouched(paths: string[]): void;
89
89
  hasValidationsInProgress(scopeFields?: string[]): boolean;
90
90
  resolveMask(path: string): BitMask | undefined;
91
+ /** Returns a version counter that increments on every registerMask() call.
92
+ * Used by React hooks to track mask config changes reactively. */
93
+ getMasksVersion(): number;
91
94
  getScopeFields(scopeName: string): string[];
92
95
  }
93
96
 
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk3CARTBENcjs = require('../chunk-3CARTBEN.cjs');var _chunkVQ7MK5VBcjs = require('../chunk-VQ7MK5VB.cjs');require('../chunk-JIWR4KSZ.cjs');require('../chunk-OZKLQRO6.cjs');var _chunkPFPGASVZcjs = require('../chunk-PFPGASVZ.cjs');var _react = require('react');function U(e){let{fieldState:o,setValue:a,setBlur:s,store:t}=_chunk3CARTBENcjs.d.call(void 0, e),i=_react.useMemo.call(void 0, ()=>t.resolveMask(e),[t.config.masks,t.config.fields,e]),u=_react.useMemo.call(void 0, ()=>_chunkPFPGASVZcjs.b.call(void 0, o.value,_nullishCoalesce(i, () => (void 0))),[o.value,i]),r=_react.useCallback.call(void 0, p=>a(_chunkPFPGASVZcjs.c.call(void 0, p,_nullishCoalesce(i, () => (void 0)))),[i,a]),{isHidden:l,isRequired:B,value:f,error:n,touched:d,isDirty:h,isValidating:T}=o,k=!!(d&&n),E=d?n:void 0,F=_react.useCallback.call(void 0, p=>{let I=_chunkPFPGASVZcjs.a.call(void 0, p)?_optionalChain([p, 'access', _ => _.target, 'optionalAccess', _2 => _2.value]):p;r(I)},[r]),x=_react.useCallback.call(void 0, ()=>{s()},[s]);return{value:f,displayValue:u,setValue:r,setBlur:s,onChange:F,onBlur:x,props:{value:u,onChange:F,onBlur:x},meta:{error:E,touched:d,invalid:k,isDirty:h,isValidating:T,isHidden:l,isRequired:B,hasError:!!n}}}function O(){let e=_chunk3CARTBENcjs.b.call(void 0, ),o=_react.useRef.call(void 0, null),a=_react.useCallback.call(void 0, ()=>{let r=e.getHistoryMetadata();if(o.current&&_chunkVQ7MK5VBcjs.a.call(void 0, o.current,r))return o.current;let l={canUndo:r.canUndo,canRedo:r.canRedo,historyIndex:r.historyIndex,historySize:r.historySize};return o.current=l,l},[e]),s=_react.useCallback.call(void 0, r=>e.subscribe(r),[e]),t=_react.useSyncExternalStore.call(void 0, s,a,a),i=_react.useCallback.call(void 0, ()=>{e.undo()},[e]),u=_react.useCallback.call(void 0, ()=>{e.redo()},[e]);return{...t,undo:i,redo:u}}function J(e,o,a){let s=_chunk3CARTBENcjs.b.call(void 0, ),t=U(e),i=_react.useRef.call(void 0, null),[u,r]=_react.useState.call(void 0, !1),l={setLoading:r,setError:(n,d)=>s.setError(n,d),setValue:n=>t.setValue(n),getUploadKey:()=>i.current,setUploadKey:n=>{i.current=n}},B=_react.useCallback.call(void 0, _chunkVQ7MK5VBcjs.b.call(void 0, e,o,l),[o,t,e,s]),f=_react.useCallback.call(void 0, _chunkVQ7MK5VBcjs.c.call(void 0, e,a,l),[a,t,e,s]);return{value:t.value,setValue:t.setValue,error:_optionalChain([t, 'access', _3 => _3.meta, 'optionalAccess', _4 => _4.error]),isValidating:!!_optionalChain([t, 'access', _5 => _5.meta, 'optionalAccess', _6 => _6.isValidating])||u,upload:B,remove:f}}exports.BitFormProvider = _chunk3CARTBENcjs.a; exports.useBitArray = _chunk3CARTBENcjs.e; exports.useBitField = U; exports.useBitForm = _chunk3CARTBENcjs.c; exports.useBitHistory = O; exports.useBitPersist = _chunk3CARTBENcjs.i; exports.useBitScope = _chunk3CARTBENcjs.f; exports.useBitSteps = _chunk3CARTBENcjs.g; exports.useBitStore = _chunk3CARTBENcjs.b; exports.useBitUpload = J; exports.useBitWatch = _chunk3CARTBENcjs.h;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk3EDD3V43cjs = require('../chunk-3EDD3V43.cjs');var _chunkVQ7MK5VBcjs = require('../chunk-VQ7MK5VB.cjs');require('../chunk-Y2ONHDRE.cjs');require('../chunk-YCSWULEN.cjs');var _chunkPFPGASVZcjs = require('../chunk-PFPGASVZ.cjs');var _react = require('react');function F(e){let{fieldState:s,setValue:n,setBlur:o,store:t}=_chunk3EDD3V43cjs.d.call(void 0, e),d=_react.useSyncExternalStore.call(void 0, u=>t.subscribe(u),()=>t.getMasksVersion(),()=>t.getMasksVersion()),a=_react.useMemo.call(void 0, ()=>t.resolveMask(e),[d,t.config.fields,e]),r=_react.useMemo.call(void 0, ()=>_chunkPFPGASVZcjs.b.call(void 0, s.value,_nullishCoalesce(a, () => (void 0))),[s.value,a]),i=_react.useCallback.call(void 0, u=>n(_chunkPFPGASVZcjs.c.call(void 0, u,_nullishCoalesce(a, () => (void 0)))),[a,n]),{isHidden:B,isRequired:f,value:l,error:p,touched:y,isDirty:h,isValidating:T}=s,E=!!(y&&p),I=y?p:void 0,x=_react.useCallback.call(void 0, u=>{let C=_chunkPFPGASVZcjs.a.call(void 0, u)?_optionalChain([u, 'access', _ => _.target, 'optionalAccess', _2 => _2.value]):u;i(C)},[i]),g=_react.useCallback.call(void 0, ()=>{o()},[o]);return{value:l,displayValue:r,setValue:i,setBlur:o,onChange:x,onBlur:g,props:{value:r,onChange:x,onBlur:g},meta:{error:I,touched:y,invalid:E,isDirty:h,isValidating:T,isHidden:B,isRequired:f,hasError:!!p}}}function G(){let e=_chunk3EDD3V43cjs.b.call(void 0, ),s=_react.useRef.call(void 0, null),n=_react.useCallback.call(void 0, ()=>{let r=e.getHistoryMetadata();if(s.current&&_chunkVQ7MK5VBcjs.a.call(void 0, s.current,r))return s.current;let i={canUndo:r.canUndo,canRedo:r.canRedo,historyIndex:r.historyIndex,historySize:r.historySize};return s.current=i,i},[e]),o=_react.useCallback.call(void 0, r=>e.subscribe(r),[e]),t=_react.useSyncExternalStore.call(void 0, o,n,n),d=_react.useCallback.call(void 0, ()=>{e.undo()},[e]),a=_react.useCallback.call(void 0, ()=>{e.redo()},[e]);return{...t,undo:d,redo:a}}function Q(e,s,n){let o=_chunk3EDD3V43cjs.b.call(void 0, ),t=F(e),d=_react.useRef.call(void 0, null),[a,r]=_react.useState.call(void 0, !1),i={setLoading:r,setError:(l,p)=>o.setError(l,p),setValue:l=>t.setValue(l),getUploadKey:()=>d.current,setUploadKey:l=>{d.current=l}},B=_react.useCallback.call(void 0, _chunkVQ7MK5VBcjs.b.call(void 0, e,s,i),[s,t,e,o]),f=_react.useCallback.call(void 0, _chunkVQ7MK5VBcjs.c.call(void 0, e,n,i),[n,t,e,o]);return{value:t.value,setValue:t.setValue,error:_optionalChain([t, 'access', _3 => _3.meta, 'optionalAccess', _4 => _4.error]),isValidating:!!_optionalChain([t, 'access', _5 => _5.meta, 'optionalAccess', _6 => _6.isValidating])||a,upload:B,remove:f}}exports.BitFormProvider = _chunk3EDD3V43cjs.a; exports.useBitArray = _chunk3EDD3V43cjs.e; exports.useBitField = F; exports.useBitForm = _chunk3EDD3V43cjs.c; exports.useBitHistory = G; exports.useBitPersist = _chunk3EDD3V43cjs.i; exports.useBitScope = _chunk3EDD3V43cjs.f; exports.useBitSteps = _chunk3EDD3V43cjs.g; exports.useBitStore = _chunk3EDD3V43cjs.b; exports.useBitUpload = Q; exports.useBitWatch = _chunk3EDD3V43cjs.h;
2
2
  //# sourceMappingURL=index.cjs.map