@lehnihon/bit-form 2.2.6 → 2.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -24
- package/dist/angular/index.cjs +1 -1
- package/dist/angular/index.cjs.map +1 -1
- package/dist/angular/index.d.cts +20 -20
- package/dist/angular/index.d.ts +20 -20
- package/dist/angular/index.js +1 -1
- package/dist/angular/index.js.map +1 -1
- package/dist/array-controller-B5bfXV1W.d.cts +23 -0
- package/dist/array-controller-Cx-DMH7Y.d.ts +23 -0
- package/dist/bus-B2VEKrPI.d.ts +19 -0
- package/dist/bus-ZLQeq4Vr.d.cts +19 -0
- package/dist/chunk-5NA2TFPG.js +1 -0
- package/dist/chunk-5NA2TFPG.js.map +1 -0
- package/dist/chunk-63OJBMKK.js +2 -0
- package/dist/chunk-63OJBMKK.js.map +1 -0
- package/dist/chunk-BSGJ3T5S.cjs +2 -0
- package/dist/chunk-BSGJ3T5S.cjs.map +1 -0
- package/dist/chunk-CPP7ELA5.js +2 -0
- package/dist/chunk-CPP7ELA5.js.map +1 -0
- package/dist/chunk-D7JQWF6V.cjs +2 -0
- package/dist/chunk-D7JQWF6V.cjs.map +1 -0
- package/dist/chunk-E2NZR44P.js +2 -0
- package/dist/chunk-E2NZR44P.js.map +1 -0
- package/dist/chunk-EQ55DKX2.js +2 -0
- package/dist/chunk-EQ55DKX2.js.map +1 -0
- package/dist/chunk-IV32WXCF.cjs +2 -0
- package/dist/chunk-IV32WXCF.cjs.map +1 -0
- package/dist/chunk-JC4R5WCC.js +2 -0
- package/dist/chunk-JC4R5WCC.js.map +1 -0
- package/dist/chunk-K5X37E3U.js +2 -0
- package/dist/chunk-K5X37E3U.js.map +1 -0
- package/dist/chunk-M6WBNHIT.cjs +2 -0
- package/dist/chunk-M6WBNHIT.cjs.map +1 -0
- package/dist/chunk-MFSQATNZ.cjs +2 -0
- package/dist/chunk-MFSQATNZ.cjs.map +1 -0
- package/dist/chunk-MFTWAFMG.cjs +2 -0
- package/dist/chunk-MFTWAFMG.cjs.map +1 -0
- package/dist/chunk-O5UPA33R.js +2 -0
- package/dist/chunk-O5UPA33R.js.map +1 -0
- package/dist/chunk-P2YWYBWG.cjs +2 -0
- package/dist/chunk-P2YWYBWG.cjs.map +1 -0
- package/dist/chunk-QKGTVKBU.cjs +2 -0
- package/dist/chunk-QKGTVKBU.cjs.map +1 -0
- package/dist/chunk-RD73EBSN.js +2 -0
- package/dist/chunk-RD73EBSN.js.map +1 -0
- package/dist/chunk-T2JRSWQU.cjs +2 -0
- package/dist/chunk-T2JRSWQU.cjs.map +1 -0
- package/dist/chunk-UQ3DSUWC.js +2 -0
- package/dist/chunk-UQ3DSUWC.js.map +1 -0
- package/dist/chunk-VZHG372Q.cjs +2 -0
- package/dist/chunk-VZHG372Q.cjs.map +1 -0
- package/dist/chunk-W2E5UIXT.js +2 -0
- package/dist/chunk-W2E5UIXT.js.map +1 -0
- package/dist/chunk-W5CLDRRE.cjs +1 -0
- package/dist/chunk-W5CLDRRE.cjs.map +1 -0
- package/dist/cli/index.cjs +22 -22
- package/dist/core/bindings.cjs +2 -0
- package/dist/core/bindings.cjs.map +1 -0
- package/dist/core/bindings.d.cts +81 -0
- package/dist/core/bindings.d.ts +81 -0
- package/dist/core/bindings.js +2 -0
- package/dist/core/bindings.js.map +1 -0
- package/dist/core/status.cjs +2 -0
- package/dist/core/status.cjs.map +1 -0
- package/dist/core/status.d.cts +44 -0
- package/dist/core/status.d.ts +44 -0
- package/dist/core/status.js +2 -0
- package/dist/core/status.js.map +1 -0
- package/dist/core/store.cjs +2 -0
- package/dist/core/store.cjs.map +1 -0
- package/dist/core/store.d.cts +84 -0
- package/dist/core/store.d.ts +84 -0
- package/dist/core/store.js +2 -0
- package/dist/core/store.js.map +1 -0
- package/dist/core/utils.cjs +2 -0
- package/dist/core/utils.cjs.map +1 -0
- package/dist/core/utils.d.cts +81 -0
- package/dist/core/utils.d.ts +81 -0
- package/dist/core/utils.js +2 -0
- package/dist/core/utils.js.map +1 -0
- package/dist/core.cjs +2 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.cts +14 -0
- package/dist/core.d.ts +14 -0
- package/dist/core.js +2 -0
- package/dist/core.js.map +1 -0
- package/dist/devtools/bridge.cjs +1 -1
- package/dist/devtools/bridge.cjs.map +1 -1
- package/dist/devtools/bridge.d.cts +5 -1
- package/dist/devtools/bridge.d.ts +5 -1
- package/dist/devtools/bridge.js +1 -1
- package/dist/devtools/bridge.js.map +1 -1
- package/dist/devtools/index.cjs +18 -18
- package/dist/devtools/index.cjs.map +1 -1
- package/dist/devtools/index.d.cts +27 -2
- package/dist/devtools/index.d.ts +27 -2
- package/dist/devtools/index.js +18 -18
- package/dist/devtools/index.js.map +1 -1
- package/dist/devtools/protocol.cjs +2 -0
- package/dist/devtools/protocol.cjs.map +1 -0
- package/dist/devtools/protocol.d.cts +54 -0
- package/dist/devtools/protocol.d.ts +54 -0
- package/dist/devtools/protocol.js +2 -0
- package/dist/devtools/protocol.js.map +1 -0
- package/dist/field-binding-B_OX3bjp.d.cts +25 -0
- package/dist/field-binding-MX6jVQbT.d.ts +25 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -193
- package/dist/index.d.ts +9 -193
- package/dist/index.js +1 -1
- package/dist/meta-types-Bzmm21TP.d.cts +18 -0
- package/dist/meta-types-Bzmm21TP.d.ts +18 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +10 -7
- package/dist/react/index.d.ts +10 -7
- package/dist/react/index.js +1 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react-native/index.cjs +1 -1
- package/dist/react-native/index.cjs.map +1 -1
- package/dist/react-native/index.d.cts +8 -5
- package/dist/react-native/index.d.ts +8 -5
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/resolvers/index.cjs +1 -1
- package/dist/resolvers/index.cjs.map +1 -1
- package/dist/resolvers/index.d.cts +2 -1
- package/dist/resolvers/index.d.ts +2 -1
- package/dist/resolvers/index.js +1 -1
- package/dist/resolvers/joi.d.cts +2 -1
- package/dist/resolvers/joi.d.ts +2 -1
- package/dist/resolvers/yup.d.cts +2 -1
- package/dist/resolvers/yup.d.ts +2 -1
- package/dist/resolvers/zod.d.cts +2 -1
- package/dist/resolvers/zod.d.ts +2 -1
- package/dist/store-api-types-D-ZHxzRy.d.cts +161 -0
- package/dist/store-api-types-DPi30jQF.d.ts +161 -0
- package/dist/{bus-B4zZmB9C.d.ts → types-CG5nYeRk.d.ts} +140 -41
- package/dist/{bus-BeAeZwWu.d.cts → types-D6LhF5GC.d.cts} +140 -41
- package/dist/{upload-EXnJLq8k.d.cts → upload-C2mpfhp1.d.cts} +1 -1
- package/dist/{upload-EXnJLq8k.d.ts → upload-C2mpfhp1.d.ts} +1 -1
- package/dist/{use-bit-persist-Dk3fUrds.d.ts → use-bit-persist-BTwy8kvA.d.ts} +14 -14
- package/dist/{use-bit-persist-D_gimC9A.d.cts → use-bit-persist-C2LHNTVv.d.cts} +14 -14
- package/dist/utils.cjs +2 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +6 -0
- package/dist/utils.d.ts +6 -0
- package/dist/utils.js +2 -0
- package/dist/utils.js.map +1 -0
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +17 -18
- package/dist/vue/index.d.ts +17 -18
- package/dist/vue/index.js +1 -1
- package/dist/vue/index.js.map +1 -1
- package/package.json +48 -17
- package/dist/chunk-2CVKNPWX.js +0 -2
- package/dist/chunk-2CVKNPWX.js.map +0 -1
- package/dist/chunk-3EDD3V43.cjs +0 -2
- package/dist/chunk-3EDD3V43.cjs.map +0 -1
- package/dist/chunk-PX6WKENM.js +0 -2
- package/dist/chunk-PX6WKENM.js.map +0 -1
- package/dist/chunk-QWH2NBVB.js +0 -2
- package/dist/chunk-QWH2NBVB.js.map +0 -1
- package/dist/chunk-T3FR7D5V.js +0 -2
- package/dist/chunk-T3FR7D5V.js.map +0 -1
- package/dist/chunk-VQ7MK5VB.cjs +0 -2
- package/dist/chunk-VQ7MK5VB.cjs.map +0 -1
- package/dist/chunk-Y2ONHDRE.cjs +0 -2
- package/dist/chunk-Y2ONHDRE.cjs.map +0 -1
- package/dist/chunk-YCSWULEN.cjs +0 -2
- package/dist/chunk-YCSWULEN.cjs.map +0 -1
- package/dist/field-binding-BXw0Ku2c.d.cts +0 -12
- package/dist/field-binding-BXw0Ku2c.d.ts +0 -12
- package/dist/public-types-Cd9ai20P.d.cts +0 -97
- package/dist/public-types-DdZxD6Op.d.ts +0 -97
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts","../src/react/use-bit-scope.ts","../src/react/use-bit-steps.ts","../src/react/use-bit-watch.ts","../src/react/use-bit-persist.ts","../src/react/use-bit-field-base.ts"],"sourcesContent":["import React, { createContext, useContext } from \"react\";\nimport type { BitStoreApi, BitStoreHooksApi } from \"../core\";\nimport { resolveBitStoreForHooks } from \"../core\";\n\nconst BitContext = createContext<BitStoreHooksApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStoreApi<any>;\n children: React.ReactNode;\n}) => (\n <BitContext.Provider value={resolveBitStoreForHooks(store)}>\n {children}\n </BitContext.Provider>\n);\n\nexport const useBitStore = <T extends object>() => {\n const store = useContext(BitContext);\n if (!store)\n throw new Error(\n \"BitForm hooks devem ser usados dentro de um BitFormProvider\",\n );\n return store as BitStoreHooksApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n createFormController,\n createStoreFormActions,\n} from \"../core/form-controller\";\nimport type { UseBitFormResult } from \"./types\";\n\nconst selectFormMeta = <T extends object>(state: {\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n}) => ({\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n});\n\nexport function useBitForm<T extends object>(): UseBitFormResult<T> {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const nextMeta = {\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n };\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const subscribeMeta = useCallback(\n (cb: () => void) =>\n store.subscribeSelector(selectFormMeta, () => cb(), {\n paths: [\"isValid\", \"isDirty\", \"isSubmitting\"],\n }),\n [store],\n );\n\n const metaState = useSyncExternalStore(\n subscribeMeta,\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const controller = useMemo(\n () =>\n createFormController(store, {\n clearSubmissionState: () => {\n setSubmitError(null);\n setLastResponse(null);\n },\n setSubmissionResult: (result) => {\n setLastResponse(result);\n },\n setSubmissionError: (error) => {\n setSubmitError(error);\n },\n }),\n [store],\n );\n\n const actions = useMemo(() => createStoreFormActions(store), [store]);\n\n const submit = useCallback(controller.submit, [controller]);\n const onSubmit = useCallback(controller.onSubmit, [controller]);\n const reset = useCallback(controller.reset, [controller]);\n\n const getValues = useCallback(controller.getValues, [controller]);\n const getErrors = useCallback(controller.getErrors, [controller]);\n const getTouched = useCallback(controller.getTouched, [controller]);\n const getDirtyValues = useCallback(controller.getDirtyValues, [controller]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n ...actions,\n };\n}\n","import { useCallback, useSyncExternalStore, useRef, useMemo } from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n const createId = useCallback(\n (index?: number) =>\n store.config.idFactory({\n scope: \"array\",\n path: path as string,\n index,\n }),\n [store, path],\n );\n const idsRef = useRef<string[]>([]);\n\n type Item = BitArrayItem<BitPathValue<TForm, P>>;\n\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const value = getDeepValue(state.values, path as string) as\n | BitPathValue<TForm, P>\n | undefined;\n const arrayValue = Array.isArray(value) ? (value as Item[]) : [];\n\n if (arrayValue.length !== idsRef.current.length) {\n if (arrayValue.length > idsRef.current.length) {\n const diff = arrayValue.length - idsRef.current.length;\n idsRef.current = [\n ...idsRef.current,\n ...Array(diff)\n .fill(null)\n .map((_, i) => createId(idsRef.current.length + i)),\n ];\n } else {\n idsRef.current = idsRef.current.slice(0, arrayValue.length);\n }\n }\n\n return arrayValue;\n }, [store, path, createId]);\n\n const subscribeArray = useCallback(\n (cb: () => void) => store.subscribePath(path, () => cb()),\n [store, path],\n );\n\n const data = useSyncExternalStore(subscribeArray, getSnapshot, getSnapshot);\n\n const methods = useMemo(\n () => ({\n append: (value: Item) => {\n idsRef.current = [...idsRef.current, createId(idsRef.current.length)];\n store.pushItem(path, value);\n },\n prepend: (value: Item) => {\n idsRef.current = [createId(0), ...idsRef.current];\n store.prependItem(path, value);\n },\n insert: (index: number, value: Item) => {\n const newIds = [...idsRef.current];\n newIds.splice(index, 0, createId(index));\n idsRef.current = newIds;\n store.insertItem(path, index, value);\n },\n remove: (index: number) => {\n idsRef.current = idsRef.current.filter((_, i) => i !== index);\n store.removeItem(path, index);\n },\n move: (from: number, to: number) => {\n const newIds = [...idsRef.current];\n const [item] = newIds.splice(from, 1);\n newIds.splice(to, 0, item);\n idsRef.current = newIds;\n store.moveItem(path, from, to);\n },\n swap: (indexA: number, indexB: number) => {\n const newIds = [...idsRef.current];\n [newIds[indexA], newIds[indexB]] = [newIds[indexB], newIds[indexA]];\n idsRef.current = newIds;\n store.swapItems(path, indexA, indexB);\n },\n replace: (items: Item[]) => {\n idsRef.current = items.map((_, index) => createId(index));\n store.setField(\n path as unknown as BitPath<TForm>,\n items as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n clear: () => {\n idsRef.current = [];\n store.setField(\n path as unknown as BitPath<TForm>,\n [] as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n }),\n [store, path, createId],\n );\n\n const fields = useMemo(\n () =>\n (data as Item[]).map((item: Item, index: number) => ({\n key: idsRef.current[index] || `temp-${index}`,\n value: item,\n index,\n })),\n [data],\n );\n\n return {\n fields,\n length: data.length,\n ...methods,\n };\n}\n","import { useCallback, useSyncExternalStore, useRef } from \"react\";\nimport type { ScopeStatus, ValidateScopeResult } from \"../core\";\nimport {\n getScopeSubscriptionPaths,\n isScopeStatusEqual,\n} from \"../core/scope-status\";\nimport { useBitStore } from \"./context\";\n\nexport type { ScopeStatus, ValidateScopeResult };\n\nexport function useBitScope(scopeName: string) {\n const store = useBitStore();\n const scopeFields = store.getScopeFields(scopeName);\n\n const lastStatus = useRef<ScopeStatus | null>(null);\n\n const getStatusSnapshot = useCallback(() => {\n const nextStatus = store.getStepStatus(scopeName);\n\n if (\n lastStatus.current &&\n isScopeStatusEqual(lastStatus.current, nextStatus)\n ) {\n return lastStatus.current;\n }\n\n lastStatus.current = nextStatus;\n return nextStatus;\n }, [store, scopeName]);\n\n // Assina apenas os slices de estado relevantes para o escopo (errors e\n // isDirty), evitando execuções desnecessárias do getStatusSnapshot em\n // mudanças não relacionadas (isSubmitting, isValidating de outros campos…)\n const subscribe = useCallback(\n (cb: () => void) =>\n store.subscribeSelector(\n (state) => ({ errors: state.errors, isDirty: state.isDirty }),\n () => cb(),\n { paths: getScopeSubscriptionPaths(scopeFields) },\n ),\n [store, scopeFields],\n );\n\n const status = useSyncExternalStore(\n subscribe,\n getStatusSnapshot,\n getStatusSnapshot,\n );\n\n const validate = useCallback(async (): Promise<ValidateScopeResult> => {\n const valid = await store.validate({ scope: scopeName });\n const errors = store.getStepErrors(scopeName);\n return { valid, errors };\n }, [store, scopeName]);\n\n const getErrors = useCallback(() => {\n return store.getStepErrors(scopeName);\n }, [store, scopeName]);\n\n return {\n scopeName,\n status,\n errors: status.errors,\n validate,\n getErrors,\n isValid: !status.hasErrors,\n isDirty: status.isDirty,\n };\n}\n","import { useCallback, useSyncExternalStore, useRef, useState } from \"react\";\nimport type { ScopeStatus, ValidateScopeResult } from \"../core\";\nimport {\n getScopeSubscriptionPaths,\n isScopeStatusEqual,\n} from \"../core/scope-status\";\nimport { useBitStore } from \"./context\";\nimport type { UseBitStepsResult } from \"./types\";\n\nexport function useBitSteps(scopeNames: string[]): UseBitStepsResult {\n const store = useBitStore();\n const [stepIndex, setStepIndex] = useState(0);\n\n const scope = scopeNames[stepIndex] ?? \"\";\n const scopeFields = store.getScopeFields(scope);\n const lastStatus = useRef<ScopeStatus | null>(null);\n\n const getStatusSnapshot = useCallback(() => {\n const nextStatus = store.getStepStatus(scope);\n\n if (\n lastStatus.current &&\n isScopeStatusEqual(lastStatus.current, nextStatus)\n ) {\n return lastStatus.current;\n }\n\n lastStatus.current = nextStatus;\n return nextStatus;\n }, [store, scope]);\n\n const status = useSyncExternalStore(\n useCallback(\n (cb: () => void) =>\n store.subscribeSelector(\n (state) => ({ errors: state.errors, isDirty: state.isDirty }),\n () => cb(),\n { paths: getScopeSubscriptionPaths(scopeFields) },\n ),\n [store, scopeFields],\n ),\n getStatusSnapshot,\n getStatusSnapshot,\n );\n\n const validate = useCallback(async (): Promise<ValidateScopeResult> => {\n const valid = await store.validate({ scope });\n const errors = store.getStepErrors(scope);\n return { valid, errors };\n }, [store, scope]);\n\n const getErrors = useCallback(() => {\n return store.getStepErrors(scope);\n }, [store, scope]);\n\n const next = useCallback(async (): Promise<boolean> => {\n const scopeFields = store.getScopeFields(scope);\n\n if (store.hasValidationsInProgress(scopeFields)) {\n return false;\n }\n\n const valid = await store.validate({ scope });\n if (valid) {\n setStepIndex((s) => Math.min(s + 1, scopeNames.length - 1));\n } else {\n const errors = store.getStepErrors(scope);\n const pathsWithErrors = Object.keys(errors);\n if (pathsWithErrors.length > 0) {\n store.markFieldsTouched(pathsWithErrors);\n }\n }\n return valid;\n }, [store, scope, scopeNames.length]);\n\n const prev = useCallback(() => {\n setStepIndex((s) => Math.max(s - 1, 0));\n }, []);\n\n const goTo = useCallback(\n (targetStep: number) => {\n setStepIndex(\n Math.max(0, Math.min(targetStep - 1, scopeNames.length - 1)),\n );\n },\n [scopeNames.length],\n );\n\n const isFirst = stepIndex === 0;\n const isLast = stepIndex >= scopeNames.length - 1;\n\n return {\n step: stepIndex + 1,\n stepIndex,\n scope,\n next,\n prev,\n goTo,\n isFirst,\n isLast,\n status,\n errors: status.errors,\n isValid: !status.hasErrors,\n isDirty: status.isDirty,\n validate,\n getErrors,\n };\n}\n","import { useCallback, useSyncExternalStore, useRef } from \"react\";\nimport { useBitStore } from \"./context\";\nimport { getDeepValue, valueEqual, BitPath, BitPathValue } from \"../core\";\n\nexport function useBitWatch<\n TForm extends object = any,\n P extends BitPath<TForm> = BitPath<TForm>,\n>(path: P): BitPathValue<TForm, P> {\n const store = useBitStore<TForm>();\n const lastValue = useRef<BitPathValue<TForm, P> | null>(null);\n\n const getSnapshot = useCallback(() => {\n const value = getDeepValue(\n store.getState().values,\n path as string,\n ) as BitPathValue<TForm, P>;\n\n if (lastValue.current !== null && valueEqual(lastValue.current, value)) {\n return lastValue.current;\n }\n\n lastValue.current = value;\n return value;\n }, [store, path]);\n\n // Assina apenas o path monitorado → evita executar getSnapshot em toda\n // mudança de estado do store (blur, validation, outros campos, etc.)\n const subscribe = useCallback(\n (cb: () => void) => store.subscribePath(path, () => cb()),\n [store, path],\n );\n\n return useSyncExternalStore(\n subscribe,\n getSnapshot,\n getSnapshot,\n ) as BitPathValue<TForm, P>;\n}\n","import { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { useBitStore } from \"./context\";\nimport type { UseBitPersistResult } from \"./types\";\n\nexport function useBitPersist(): UseBitPersistResult {\n const store = useBitStore<any>();\n\n const persistMeta = useSyncExternalStore(\n (cb) =>\n store.subscribeSelector(\n (state) => state.persist,\n () => cb(),\n { paths: [\"persist\"] },\n ),\n () => store.getPersistMetadata(),\n () => store.getPersistMetadata(),\n );\n\n const restore = useCallback(async () => {\n return store.restorePersisted();\n }, [store]);\n\n const save = useCallback(async () => {\n await store.forceSave();\n }, [store]);\n\n const clear = useCallback(async () => {\n await store.clearPersisted();\n }, [store]);\n\n const meta = useMemo(\n () => ({\n isSaving: persistMeta.isSaving,\n isRestoring: persistMeta.isRestoring,\n error: persistMeta.error,\n }),\n [persistMeta],\n );\n\n return {\n restore,\n save,\n clear,\n meta,\n };\n}\n","import { useCallback, useSyncExternalStore, useRef, useEffect } from \"react\";\nimport { useBitStore } from \"./context\";\nimport { BitPath, BitPathValue } from \"../core\";\nimport { subscribeFieldState } from \"../core/field-controller\";\n\nexport function useBitFieldBase<\n TValue = any,\n TForm extends object = any,\n P extends BitPath<TForm> = BitPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n const lastState = useRef<{\n value: BitPathValue<TForm, P>;\n error: any;\n touched: boolean;\n isHidden: boolean;\n isRequired: boolean;\n isDirty: boolean;\n isValidating: boolean;\n } | null>(null);\n\n useEffect(() => {\n return () => {\n if (store.unregisterField) {\n store.unregisterField(path);\n }\n };\n }, [store, path]);\n\n const getSnapshot = useCallback(() => {\n const nextState = store.getFieldState(path);\n\n if (\n lastState.current &&\n lastState.current.value === nextState.value &&\n lastState.current.error === nextState.error &&\n lastState.current.touched === nextState.touched &&\n lastState.current.isHidden === nextState.isHidden &&\n lastState.current.isRequired === nextState.isRequired &&\n lastState.current.isDirty === nextState.isDirty &&\n lastState.current.isValidating === nextState.isValidating\n ) {\n return lastState.current;\n }\n\n const newState = {\n value: nextState.value,\n error: nextState.error,\n touched: nextState.touched,\n isHidden: nextState.isHidden,\n isRequired: nextState.isRequired,\n isDirty: nextState.isDirty,\n isValidating: nextState.isValidating,\n };\n lastState.current = newState;\n return newState;\n }, [store, path]);\n\n const subscribe = useCallback(\n (cb: () => void) => subscribeFieldState(store, path, () => cb()),\n [store, path],\n );\n\n const fieldState = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n const setValue = useCallback(\n (val: BitPathValue<TForm, P>) => store.setField(path, val),\n [store, path],\n );\n\n const setBlur = useCallback(() => store.blurField(path), [store, path]);\n\n return { fieldState, setValue, setBlur, store };\n}\n"],"mappings":"0HAAA,OAAgB,iBAAAA,EAAe,cAAAC,MAAkB,QAa/C,cAAAC,MAAA,oBATF,IAAMC,EAAaC,EAA4C,IAAI,EAEtDC,GAAkB,CAAC,CAC9B,MAAAC,EACA,SAAAC,CACF,IAIEL,EAACC,EAAW,SAAX,CAAoB,MAAOK,EAAwBF,CAAK,EACtD,SAAAC,EACH,EAGWE,EAAc,IAAwB,CACjD,IAAMH,EAAQI,EAAWP,CAAU,EACnC,GAAI,CAACG,EACH,MAAM,IAAI,MACR,6DACF,EACF,OAAOA,CACT,ECzBA,OACE,eAAAK,EACA,wBAAAC,EACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QAQP,IAAMC,EAAoCC,IAInC,CACL,QAASA,EAAM,QACf,QAASA,EAAM,QACf,aAAcA,EAAM,YACtB,GAEO,SAASC,IAAoD,CAClE,IAAMC,EAAQC,EAAe,EAEvB,CAACC,EAAaC,CAAc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IAAMC,EAAYP,EAAM,cAAcD,CAAI,EAE1C,GACEG,EAAU,SACVA,EAAU,QAAQ,QAAUK,EAAU,OACtCL,EAAU,QAAQ,QAAUK,EAAU,OACtCL,EAAU,QAAQ,UAAYK,EAAU,SACxCL,EAAU,QAAQ,WAAaK,EAAU,UACzCL,EAAU,QAAQ,aAAeK,EAAU,YAC3CL,EAAU,QAAQ,UAAYK,EAAU,SACxCL,EAAU,QAAQ,eAAiBK,EAAU,aAE7C,OAAOL,EAAU,QAGnB,IAAMM,EAAW,CACf,MAAOD,EAAU,MACjB,MAAOA,EAAU,MACjB,QAASA,EAAU,QACnB,SAAUA,EAAU,SACpB,WAAYA,EAAU,WACtB,QAASA,EAAU,QACnB,aAAcA,EAAU,YAC1B,EACA,OAAAL,EAAU,QAAUM,EACbA,CACT,EAAG,CAACR,EAAOD,CAAI,CAAC,EAEVU,EAAYH,EACfI,GAAmBC,EAAoBX,EAAOD,EAAM,IAAMW,EAAG,CAAC,EAC/D,CAACV,EAAOD,CAAI,CACd,EAEMa,EAAaC,GAAqBJ,EAAWJ,EAAaA,CAAW,EAErES,EAAWR,EACdS,GAAgCf,EAAM,SAASD,EAAMgB,CAAG,EACzD,CAACf,EAAOD,CAAI,CACd,EAEMiB,EAAUV,EAAY,IAAMN,EAAM,UAAUD,CAAI,EAAG,CAACC,EAAOD,CAAI,CAAC,EAEtE,MAAO,CAAE,WAAAa,EAAY,SAAAE,EAAU,QAAAE,EAAS,MAAAhB,CAAM,CAChD","names":["createContext","useContext","jsx","BitContext","createContext","BitFormProvider","store","children","resolveBitStoreForHooks","useBitStore","useContext","useCallback","useSyncExternalStore","useMemo","useRef","useState","selectFormMeta","state","useBitForm","store","useBitStore","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","nextMeta","subscribeMeta","cb","metaState","useSyncExternalStore","controller","useMemo","createFormController","result","error","actions","createStoreFormActions","submit","onSubmit","reset","getValues","getErrors","getTouched","getDirtyValues","useCallback","useSyncExternalStore","useRef","useMemo","useBitArray","path","store","useBitStore","createId","useCallback","index","idsRef","useRef","getSnapshot","state","value","getDeepValue","arrayValue","diff","_","i","subscribeArray","cb","data","useSyncExternalStore","methods","useMemo","newIds","from","to","item","indexA","indexB","items","useCallback","useSyncExternalStore","useRef","useBitScope","scopeName","store","useBitStore","scopeFields","lastStatus","useRef","getStatusSnapshot","useCallback","nextStatus","isScopeStatusEqual","subscribe","cb","state","getScopeSubscriptionPaths","status","useSyncExternalStore","validate","valid","errors","getErrors","useCallback","useSyncExternalStore","useRef","useState","useBitSteps","scopeNames","store","useBitStore","stepIndex","setStepIndex","useState","scope","scopeFields","lastStatus","useRef","getStatusSnapshot","useCallback","nextStatus","isScopeStatusEqual","status","useSyncExternalStore","cb","state","getScopeSubscriptionPaths","validate","valid","errors","getErrors","next","s","pathsWithErrors","prev","goTo","targetStep","isFirst","isLast","useCallback","useSyncExternalStore","useRef","useBitWatch","path","store","useBitStore","lastValue","useRef","getSnapshot","useCallback","value","getDeepValue","valueEqual","subscribe","cb","useSyncExternalStore","useCallback","useMemo","useSyncExternalStore","useBitPersist","store","useBitStore","persistMeta","useSyncExternalStore","cb","state","restore","useCallback","save","clear","meta","useMemo","useCallback","useSyncExternalStore","useRef","useEffect","useBitFieldBase","path","store","useBitStore","lastState","useRef","useEffect","getSnapshot","useCallback","nextState","newState","subscribe","cb","subscribeFieldState","fieldState","useSyncExternalStore","setValue","val","setBlur"]}
|
package/dist/chunk-VQ7MK5VB.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});function d(r,t){return r.canUndo===t.canUndo&&r.canRedo===t.canRedo&&r.historyIndex===t.historyIndex&&r.historySize===t.historySize}function a(r,t,e){return async n=>{if(n){e.setLoading(!0),e.setError(r,void 0);try{let o=await t(n);e.setValue(o.url),e.setUploadKey(o.key),e.setError(r,void 0)}catch(o){let i=o instanceof Error?o.message:"Upload failed";e.setError(r,i)}finally{e.setLoading(!1)}}}}function s(r,t,e){return async()=>{let n=e.getUploadKey();if(n&&t)try{await t(n)}catch(o){let i=o instanceof Error?o.message:"Delete failed";e.setError(r,i);return}e.setValue(null),e.setUploadKey(null),e.setError(r,void 0)}}exports.a = d; exports.b = a; exports.c = s;
|
|
2
|
-
//# sourceMappingURL=chunk-VQ7MK5VB.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/history-status.ts","../src/core/adapters/upload-kernel.ts"],"names":["isHistoryMetaEqual","a","b","createUploadHandler","fieldPath","uploadFn","callbacks","file","result","error","message","createRemoveHandler","deleteFile","uploadKey"],"mappings":"AAgBO,kFAASA,CAAAA,CAAmBC,CAAAA,CAAgBC,CAAAA,CAAyB,CAC1E,OACED,CAAAA,CAAE,OAAA,GAAYC,CAAAA,CAAE,OAAA,EAChBD,CAAAA,CAAE,OAAA,GAAYC,CAAAA,CAAE,OAAA,EAChBD,CAAAA,CAAE,YAAA,GAAiBC,CAAAA,CAAE,YAAA,EACrBD,CAAAA,CAAE,WAAA,GAAgBC,CAAAA,CAAE,WAExB,CCcO,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACkD,CAClD,OAAO,MAAOC,CAAAA,EAAS,CACrB,EAAA,CAAKA,CAAAA,CAEL,CAAAD,CAAAA,CAAU,UAAA,CAAW,CAAA,CAAI,CAAA,CACzBA,CAAAA,CAAU,QAAA,CAASF,CAAAA,CAAW,KAAA,CAAS,CAAA,CAEvC,GAAI,CACF,IAAMI,CAAAA,CAAS,MAAMH,CAAAA,CAASE,CAAI,CAAA,CAElCD,CAAAA,CAAU,QAAA,CAASE,CAAAA,CAAO,GAAG,CAAA,CAC7BF,CAAAA,CAAU,YAAA,CAAaE,CAAAA,CAAO,GAAG,CAAA,CACjCF,CAAAA,CAAU,QAAA,CAASF,CAAAA,CAAW,KAAA,CAAS,CACzC,CAAA,KAAA,CAASK,CAAAA,CAAO,CACd,IAAMC,CAAAA,CAAUD,EAAAA,WAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,eAAA,CACzDH,CAAAA,CAAU,QAAA,CAASF,CAAAA,CAAWM,CAAO,CACvC,CAAA,OAAE,CACAJ,CAAAA,CAAU,UAAA,CAAW,CAAA,CAAK,CAC5B,CAAA,CACF,CACF,CAKO,SAASK,CAAAA,CACdP,CAAAA,CACAQ,CAAAA,CACAN,CAAAA,CACqB,CACrB,OAAO,KAAA,CAAA,CAAA,EAAY,CACjB,IAAMO,CAAAA,CAAYP,CAAAA,CAAU,YAAA,CAAa,CAAA,CAEzC,EAAA,CAAIO,CAAAA,EAAaD,CAAAA,CACf,GAAI,CACF,MAAMA,CAAAA,CAAWC,CAAS,CAC5B,CAAA,KAAA,CAASJ,CAAAA,CAAO,CACd,IAAMC,CAAAA,CACJD,EAAAA,WAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,eAAA,CAC3CH,CAAAA,CAAU,QAAA,CAASF,CAAAA,CAAWM,CAAO,CAAA,CACrC,MACF,CAGFJ,CAAAA,CAAU,QAAA,CAAS,IAAI,CAAA,CACvBA,CAAAA,CAAU,YAAA,CAAa,IAAI,CAAA,CAC3BA,CAAAA,CAAU,QAAA,CAASF,CAAAA,CAAW,KAAA,CAAS,CACzC,CACF,CAAA,4CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-VQ7MK5VB.cjs","sourcesContent":["import type { BitHistoryMetadata } from \"./store/contracts/public-types\";\n\n/**\n * Subconjunto relevante de BitHistoryMetadata para comparação de igualdade.\n * Evita re-renders/updates desnecessários quando o estado de histórico não muda.\n */\nexport type HistoryMeta = Pick<\n BitHistoryMetadata,\n \"canUndo\" | \"canRedo\" | \"historyIndex\" | \"historySize\"\n>;\n\n/**\n * Compara dois snapshots de metadata de histórico por valor.\n * Retorna `true` quando todos os campos relevantes são idênticos,\n * permitindo que os bindings de framework ignorem atualizações não relacionadas.\n */\nexport function isHistoryMetaEqual(a: HistoryMeta, b: HistoryMeta): boolean {\n return (\n a.canUndo === b.canUndo &&\n a.canRedo === b.canRedo &&\n a.historyIndex === b.historyIndex &&\n a.historySize === b.historySize\n );\n}\n","/**\n * Framework-agnostic upload kernel.\n *\n * Encapsulates the side-effect logic for uploading/removing files so that\n * React, Vue, and Angular adapters share a single implementation and only\n * differ in how they wire reactive state.\n */\n\nimport type { BitUploadFn, BitDeleteUploadFn } from \"../types/upload\";\n\nexport interface UploadKernelCallbacks {\n /** Called with `true` when upload starts and `false` when it finishes. */\n setLoading: (loading: boolean) => void;\n /** Set or clear a field-level error message. */\n setError: (path: string, message: string | undefined) => void;\n /** Set the stored file URL after a successful upload (or `null` on remove). */\n setValue: (value: string | null) => void;\n /** Return the key of the last uploaded file (used when deleting). */\n getUploadKey: () => string | null;\n /** Persist the upload key returned by the upload function. */\n setUploadKey: (key: string | null) => void;\n}\n\n/**\n * Creates a type-safe `upload` handler for a field.\n *\n * @example\n * ```ts\n * const upload = createUploadHandler(\"avatar\", myUploadFn, {\n * setLoading: (v) => (isUploading.value = v),\n * setError: (p, m) => store.setError(p, m),\n * setValue: (v) => field.setValue(v),\n * getUploadKey: () => uploadKey,\n * setUploadKey: (k) => (uploadKey = k),\n * });\n * ```\n */\nexport function createUploadHandler(\n fieldPath: string,\n uploadFn: BitUploadFn,\n callbacks: UploadKernelCallbacks,\n): (file: File | null | undefined) => Promise<void> {\n return async (file) => {\n if (!file) return;\n\n callbacks.setLoading(true);\n callbacks.setError(fieldPath, undefined);\n\n try {\n const result = await uploadFn(file);\n\n callbacks.setValue(result.url);\n callbacks.setUploadKey(result.key);\n callbacks.setError(fieldPath, undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Upload failed\";\n callbacks.setError(fieldPath, message);\n } finally {\n callbacks.setLoading(false);\n }\n };\n}\n\n/**\n * Creates a type-safe `remove` handler for a field.\n */\nexport function createRemoveHandler(\n fieldPath: string,\n deleteFile: BitDeleteUploadFn | undefined,\n callbacks: UploadKernelCallbacks,\n): () => Promise<void> {\n return async () => {\n const uploadKey = callbacks.getUploadKey();\n\n if (uploadKey && deleteFile) {\n try {\n await deleteFile(uploadKey);\n } catch (error) {\n const message =\n error instanceof Error ? error.message : \"Delete failed\";\n callbacks.setError(fieldPath, message);\n return;\n }\n }\n\n callbacks.setValue(null);\n callbacks.setUploadKey(null);\n callbacks.setError(fieldPath, undefined);\n };\n}\n"]}
|
package/dist/chunk-Y2ONHDRE.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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,MAAMJ,CAAAA,CAAQC,CAAAA,CAAQC,CAAW,CAAA,CAChDC,CAAAA,CAAS,SAAA,CAAUC,CAAM,CAC3B,CAAA,KAAA,CAASC,CAAAA,CAAO,CACd,EAAA,CAAIC,iCAAAA,CAA4B,CAAA,CAAG,CACjCH,CAAAA,CAAS,cAAA,CAAeI,iCAAAA,CAAyB,CAAC,CAAA,CAClD,MACF,CAEAJ,CAAAA,CAAS,gBAAA,CACPE,EAAAA,WAAiB,KAAA,CAAQA,CAAAA,CAAQ,IAAI,KAAA,CAAM,MAAA,CAAOA,CAAK,CAAC,CAC1D,CACF,CACF,CCTO,SAASG,CAAAA,CACdC,CAAAA,CACA,CACA,MAAO,CACL,QAAA,CAAU,CACRC,CAAAA,CACAC,CAAAA,CAAAA,EACGF,CAAAA,CAAM,QAAA,CAASC,CAAAA,CAAMC,CAAK,CAAA,CAC/B,SAAA,CACED,CAAAA,EACGD,CAAAA,CAAM,SAAA,CAAUC,CAAI,CAAA,CACzB,aAAA,CAAgBT,CAAAA,EAAcQ,CAAAA,CAAM,aAAA,CAAcR,CAAM,CAAA,CACxD,OAAA,CAAUA,CAAAA,EACRQ,CAAAA,CAAM,OAAA,CAAQR,CAAM,CAAA,CACtB,MAAA,CAASA,CAAAA,EAAcQ,CAAAA,CAAM,MAAA,CAAOR,CAAM,CAAA,CAC1C,QAAA,CAAU,CAACS,CAAAA,CAAcE,CAAAA,CAAAA,EACvBH,CAAAA,CAAM,QAAA,CAASC,CAAAA,CAAME,CAAO,CA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ACF,CAEO,SAASC,CAAAA,CAGdjB,CAAAA,CAAgCC,CAAAA,CAASiB,CAAAA,CAA2B,CAYpE,MAAO,CACL,QAAA,CAZgBhB,CAAAA,EAAmB,CACnCF,CAAAA,CAAM,QAAA,CACJC,CAAAA,CACAkB,iCAAAA,CAAiBjB,CAAOgB,CAAI,CAC9B,CACF,CAAA,CAQE,OAAA,CANc,CAAA,CAAA,EAAMlB,CAAAA,CAAM,SAAA,CAAUC,CAAI,CAAA,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"]}
|
package/dist/chunk-YCSWULEN.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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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AAA,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,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tipo de entrada aceito pelos handlers de campo.
|
|
3
|
-
* Cobre eventos nativos (`e.target.value`), eventos sintéticos e valores diretos.
|
|
4
|
-
* Definido aqui para ser compartilhado entre todos os frameworks.
|
|
5
|
-
*/
|
|
6
|
-
type BitFieldInputEvent = {
|
|
7
|
-
target?: {
|
|
8
|
-
value?: string | number | null;
|
|
9
|
-
};
|
|
10
|
-
} | string | number | null | undefined;
|
|
11
|
-
|
|
12
|
-
export type { BitFieldInputEvent as B };
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tipo de entrada aceito pelos handlers de campo.
|
|
3
|
-
* Cobre eventos nativos (`e.target.value`), eventos sintéticos e valores diretos.
|
|
4
|
-
* Definido aqui para ser compartilhado entre todos os frameworks.
|
|
5
|
-
*/
|
|
6
|
-
type BitFieldInputEvent = {
|
|
7
|
-
target?: {
|
|
8
|
-
value?: string | number | null;
|
|
9
|
-
};
|
|
10
|
-
} | string | number | null | undefined;
|
|
11
|
-
|
|
12
|
-
export type { BitFieldInputEvent as B };
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import { B as BitConfig, V as ValidatorFn, a as BitFieldDefinition, D as DevToolsOptions, b as BitPersistResolvedConfig, c as BitIdFactory, d as BitPlugin, e as BitState, f as BitPath, g as BitPathValue, h as DeepPartial, i as BitErrors, j as BitPersistMetadata, k as BitArrayPath, l as BitArrayItem, S as ScopeStatus, m as BitFieldState } from './bus-BeAeZwWu.cjs';
|
|
2
|
-
import { B as BitMask, a as BitMaskName } from './types-D8DgIUhJ.cjs';
|
|
3
|
-
|
|
4
|
-
type BitSelector<T extends object, TSlice> = (state: Readonly<BitState<T>>) => TSlice;
|
|
5
|
-
type BitEqualityFn<TValue> = (previous: TValue, next: TValue) => boolean;
|
|
6
|
-
interface BitSelectorSubscriptionOptions<TValue> {
|
|
7
|
-
equalityFn?: BitEqualityFn<TValue>;
|
|
8
|
-
emitImmediately?: boolean;
|
|
9
|
-
paths?: string[];
|
|
10
|
-
/**
|
|
11
|
-
* Quando `true`, o store tenta inferir paths acessados pelo selector via Proxy.
|
|
12
|
-
* Mantido como opt-in para reduzir custo de inscrição e complexidade implícita.
|
|
13
|
-
*/
|
|
14
|
-
autoTrackPaths?: boolean;
|
|
15
|
-
}
|
|
16
|
-
interface BitValidationOptions {
|
|
17
|
-
scope?: string;
|
|
18
|
-
scopeFields?: string[];
|
|
19
|
-
}
|
|
20
|
-
interface BitHistoryMetadata {
|
|
21
|
-
enabled: boolean;
|
|
22
|
-
canUndo: boolean;
|
|
23
|
-
canRedo: boolean;
|
|
24
|
-
historyIndex: number;
|
|
25
|
-
historySize: number;
|
|
26
|
-
}
|
|
27
|
-
interface BitFrameworkConfig<T extends object = any> extends BitConfig<T> {
|
|
28
|
-
initialValues: T;
|
|
29
|
-
resolver?: ValidatorFn<T>;
|
|
30
|
-
validationDelay: number;
|
|
31
|
-
enableHistory: boolean;
|
|
32
|
-
historyLimit: number;
|
|
33
|
-
masks?: Record<string, BitMask>;
|
|
34
|
-
fields?: Record<string, BitFieldDefinition<T>>;
|
|
35
|
-
devTools?: boolean | DevToolsOptions;
|
|
36
|
-
persist: BitPersistResolvedConfig<T>;
|
|
37
|
-
idFactory: BitIdFactory;
|
|
38
|
-
plugins: BitPlugin<T>[];
|
|
39
|
-
}
|
|
40
|
-
interface BitStoreApi<T extends object = any> {
|
|
41
|
-
readonly config: Readonly<BitFrameworkConfig<T>>;
|
|
42
|
-
getConfig(): Readonly<BitFrameworkConfig<T>>;
|
|
43
|
-
getState(): Readonly<BitState<T>>;
|
|
44
|
-
subscribe(listener: () => void): () => void;
|
|
45
|
-
setField<P extends BitPath<T>>(path: P, value: BitPathValue<T, P>): void;
|
|
46
|
-
blurField<P extends BitPath<T>>(path: P): void;
|
|
47
|
-
replaceValues(values: T): void;
|
|
48
|
-
hydrate(values: DeepPartial<T>): void;
|
|
49
|
-
rebase(values: T): void;
|
|
50
|
-
setError(path: string, message: string | undefined): void;
|
|
51
|
-
setErrors(errors: BitErrors<T>): void;
|
|
52
|
-
setServerErrors(serverErrors: Record<string, string[] | string>): void;
|
|
53
|
-
validate(options?: BitValidationOptions): Promise<boolean>;
|
|
54
|
-
reset(): void;
|
|
55
|
-
transaction<TResult>(callback: () => TResult): TResult;
|
|
56
|
-
submit(onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>): Promise<void>;
|
|
57
|
-
registerMask(name: BitMaskName, mask: BitMask): void;
|
|
58
|
-
getDirtyValues(): Partial<T>;
|
|
59
|
-
getPersistMetadata(): BitPersistMetadata;
|
|
60
|
-
restorePersisted(): Promise<boolean>;
|
|
61
|
-
forceSave(): Promise<void>;
|
|
62
|
-
clearPersisted(): Promise<void>;
|
|
63
|
-
cleanup(): void;
|
|
64
|
-
registerField(path: string, config: BitFieldDefinition<T>): void;
|
|
65
|
-
unregisterField(path: string): void;
|
|
66
|
-
isHidden<P extends BitPath<T>>(path: P): boolean;
|
|
67
|
-
isRequired<P extends BitPath<T>>(path: P): boolean;
|
|
68
|
-
isFieldDirty(path: string): boolean;
|
|
69
|
-
isFieldValidating(path: string): boolean;
|
|
70
|
-
watch<P extends BitPath<T>>(path: P, callback: (value: BitPathValue<T, P>) => void): () => void;
|
|
71
|
-
pushItem<P extends BitArrayPath<T>>(path: P, value: BitArrayItem<BitPathValue<T, P>>): void;
|
|
72
|
-
prependItem<P extends BitArrayPath<T>>(path: P, value: BitArrayItem<BitPathValue<T, P>>): void;
|
|
73
|
-
insertItem<P extends BitArrayPath<T>>(path: P, index: number, value: BitArrayItem<BitPathValue<T, P>>): void;
|
|
74
|
-
removeItem<P extends BitArrayPath<T>>(path: P, index: number): void;
|
|
75
|
-
moveItem<P extends BitArrayPath<T>>(path: P, from: number, to: number): void;
|
|
76
|
-
swapItems<P extends BitArrayPath<T>>(path: P, indexA: number, indexB: number): void;
|
|
77
|
-
getHistoryMetadata(): BitHistoryMetadata;
|
|
78
|
-
undo(): void;
|
|
79
|
-
redo(): void;
|
|
80
|
-
getStepStatus(scopeName: string): ScopeStatus;
|
|
81
|
-
getStepErrors(scopeName: string): Record<string, string>;
|
|
82
|
-
}
|
|
83
|
-
interface BitStoreHooksApi<T extends object = any> extends BitStoreApi<T> {
|
|
84
|
-
getFieldState<P extends BitPath<T>>(path: P): Readonly<BitFieldState<T, BitPathValue<T, P>>>;
|
|
85
|
-
subscribePath<P extends BitPath<T>>(path: P, listener: (value: BitPathValue<T, P>) => void, options?: BitSelectorSubscriptionOptions<BitPathValue<T, P>>): () => void;
|
|
86
|
-
subscribeSelector<TSlice>(selector: BitSelector<T, TSlice>, listener: (slice: TSlice) => void, options?: BitSelectorSubscriptionOptions<TSlice>): () => void;
|
|
87
|
-
unregisterPrefix?(prefix: string): void;
|
|
88
|
-
markFieldsTouched(paths: string[]): void;
|
|
89
|
-
hasValidationsInProgress(scopeFields?: string[]): boolean;
|
|
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;
|
|
94
|
-
getScopeFields(scopeName: string): string[];
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export type { BitFrameworkConfig as B, BitSelector as a, BitSelectorSubscriptionOptions as b, BitHistoryMetadata as c, BitValidationOptions as d, BitStoreApi as e, BitStoreHooksApi as f, BitEqualityFn as g };
|
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import { B as BitConfig, V as ValidatorFn, a as BitFieldDefinition, D as DevToolsOptions, b as BitPersistResolvedConfig, c as BitIdFactory, d as BitPlugin, e as BitState, f as BitPath, g as BitPathValue, h as DeepPartial, i as BitErrors, j as BitPersistMetadata, k as BitArrayPath, l as BitArrayItem, S as ScopeStatus, m as BitFieldState } from './bus-B4zZmB9C.js';
|
|
2
|
-
import { B as BitMask, a as BitMaskName } from './types-D8DgIUhJ.js';
|
|
3
|
-
|
|
4
|
-
type BitSelector<T extends object, TSlice> = (state: Readonly<BitState<T>>) => TSlice;
|
|
5
|
-
type BitEqualityFn<TValue> = (previous: TValue, next: TValue) => boolean;
|
|
6
|
-
interface BitSelectorSubscriptionOptions<TValue> {
|
|
7
|
-
equalityFn?: BitEqualityFn<TValue>;
|
|
8
|
-
emitImmediately?: boolean;
|
|
9
|
-
paths?: string[];
|
|
10
|
-
/**
|
|
11
|
-
* Quando `true`, o store tenta inferir paths acessados pelo selector via Proxy.
|
|
12
|
-
* Mantido como opt-in para reduzir custo de inscrição e complexidade implícita.
|
|
13
|
-
*/
|
|
14
|
-
autoTrackPaths?: boolean;
|
|
15
|
-
}
|
|
16
|
-
interface BitValidationOptions {
|
|
17
|
-
scope?: string;
|
|
18
|
-
scopeFields?: string[];
|
|
19
|
-
}
|
|
20
|
-
interface BitHistoryMetadata {
|
|
21
|
-
enabled: boolean;
|
|
22
|
-
canUndo: boolean;
|
|
23
|
-
canRedo: boolean;
|
|
24
|
-
historyIndex: number;
|
|
25
|
-
historySize: number;
|
|
26
|
-
}
|
|
27
|
-
interface BitFrameworkConfig<T extends object = any> extends BitConfig<T> {
|
|
28
|
-
initialValues: T;
|
|
29
|
-
resolver?: ValidatorFn<T>;
|
|
30
|
-
validationDelay: number;
|
|
31
|
-
enableHistory: boolean;
|
|
32
|
-
historyLimit: number;
|
|
33
|
-
masks?: Record<string, BitMask>;
|
|
34
|
-
fields?: Record<string, BitFieldDefinition<T>>;
|
|
35
|
-
devTools?: boolean | DevToolsOptions;
|
|
36
|
-
persist: BitPersistResolvedConfig<T>;
|
|
37
|
-
idFactory: BitIdFactory;
|
|
38
|
-
plugins: BitPlugin<T>[];
|
|
39
|
-
}
|
|
40
|
-
interface BitStoreApi<T extends object = any> {
|
|
41
|
-
readonly config: Readonly<BitFrameworkConfig<T>>;
|
|
42
|
-
getConfig(): Readonly<BitFrameworkConfig<T>>;
|
|
43
|
-
getState(): Readonly<BitState<T>>;
|
|
44
|
-
subscribe(listener: () => void): () => void;
|
|
45
|
-
setField<P extends BitPath<T>>(path: P, value: BitPathValue<T, P>): void;
|
|
46
|
-
blurField<P extends BitPath<T>>(path: P): void;
|
|
47
|
-
replaceValues(values: T): void;
|
|
48
|
-
hydrate(values: DeepPartial<T>): void;
|
|
49
|
-
rebase(values: T): void;
|
|
50
|
-
setError(path: string, message: string | undefined): void;
|
|
51
|
-
setErrors(errors: BitErrors<T>): void;
|
|
52
|
-
setServerErrors(serverErrors: Record<string, string[] | string>): void;
|
|
53
|
-
validate(options?: BitValidationOptions): Promise<boolean>;
|
|
54
|
-
reset(): void;
|
|
55
|
-
transaction<TResult>(callback: () => TResult): TResult;
|
|
56
|
-
submit(onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>): Promise<void>;
|
|
57
|
-
registerMask(name: BitMaskName, mask: BitMask): void;
|
|
58
|
-
getDirtyValues(): Partial<T>;
|
|
59
|
-
getPersistMetadata(): BitPersistMetadata;
|
|
60
|
-
restorePersisted(): Promise<boolean>;
|
|
61
|
-
forceSave(): Promise<void>;
|
|
62
|
-
clearPersisted(): Promise<void>;
|
|
63
|
-
cleanup(): void;
|
|
64
|
-
registerField(path: string, config: BitFieldDefinition<T>): void;
|
|
65
|
-
unregisterField(path: string): void;
|
|
66
|
-
isHidden<P extends BitPath<T>>(path: P): boolean;
|
|
67
|
-
isRequired<P extends BitPath<T>>(path: P): boolean;
|
|
68
|
-
isFieldDirty(path: string): boolean;
|
|
69
|
-
isFieldValidating(path: string): boolean;
|
|
70
|
-
watch<P extends BitPath<T>>(path: P, callback: (value: BitPathValue<T, P>) => void): () => void;
|
|
71
|
-
pushItem<P extends BitArrayPath<T>>(path: P, value: BitArrayItem<BitPathValue<T, P>>): void;
|
|
72
|
-
prependItem<P extends BitArrayPath<T>>(path: P, value: BitArrayItem<BitPathValue<T, P>>): void;
|
|
73
|
-
insertItem<P extends BitArrayPath<T>>(path: P, index: number, value: BitArrayItem<BitPathValue<T, P>>): void;
|
|
74
|
-
removeItem<P extends BitArrayPath<T>>(path: P, index: number): void;
|
|
75
|
-
moveItem<P extends BitArrayPath<T>>(path: P, from: number, to: number): void;
|
|
76
|
-
swapItems<P extends BitArrayPath<T>>(path: P, indexA: number, indexB: number): void;
|
|
77
|
-
getHistoryMetadata(): BitHistoryMetadata;
|
|
78
|
-
undo(): void;
|
|
79
|
-
redo(): void;
|
|
80
|
-
getStepStatus(scopeName: string): ScopeStatus;
|
|
81
|
-
getStepErrors(scopeName: string): Record<string, string>;
|
|
82
|
-
}
|
|
83
|
-
interface BitStoreHooksApi<T extends object = any> extends BitStoreApi<T> {
|
|
84
|
-
getFieldState<P extends BitPath<T>>(path: P): Readonly<BitFieldState<T, BitPathValue<T, P>>>;
|
|
85
|
-
subscribePath<P extends BitPath<T>>(path: P, listener: (value: BitPathValue<T, P>) => void, options?: BitSelectorSubscriptionOptions<BitPathValue<T, P>>): () => void;
|
|
86
|
-
subscribeSelector<TSlice>(selector: BitSelector<T, TSlice>, listener: (slice: TSlice) => void, options?: BitSelectorSubscriptionOptions<TSlice>): () => void;
|
|
87
|
-
unregisterPrefix?(prefix: string): void;
|
|
88
|
-
markFieldsTouched(paths: string[]): void;
|
|
89
|
-
hasValidationsInProgress(scopeFields?: string[]): boolean;
|
|
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;
|
|
94
|
-
getScopeFields(scopeName: string): string[];
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export type { BitFrameworkConfig as B, BitSelector as a, BitSelectorSubscriptionOptions as b, BitHistoryMetadata as c, BitValidationOptions as d, BitStoreApi as e, BitStoreHooksApi as f, BitEqualityFn as g };
|