@lehnihon/bit-form 1.0.6 → 1.0.7
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 +39 -0
- package/dist/angular/index.cjs +1 -1
- package/dist/angular/index.d.cts +2 -2
- package/dist/angular/index.d.ts +2 -2
- package/dist/angular/index.js +1 -1
- package/dist/{bus-DAwKIiMY.d.cts → bus-DkMkzOXE.d.cts} +4 -6
- package/dist/{bus-DAwKIiMY.d.ts → bus-DkMkzOXE.d.ts} +4 -6
- package/dist/{chunk-Z6ITPS2B.cjs → chunk-6ISGLRK2.cjs} +2 -2
- package/dist/{chunk-Z6ITPS2B.cjs.map → chunk-6ISGLRK2.cjs.map} +1 -1
- package/dist/{chunk-6VDQSKUN.cjs → chunk-J3EGU5ZH.cjs} +6 -6
- package/dist/{chunk-6VDQSKUN.cjs.map → chunk-J3EGU5ZH.cjs.map} +1 -1
- package/dist/{chunk-UFYHEI6S.js → chunk-OA4FCEV2.js} +2 -2
- package/dist/{chunk-KA4FAGIX.js → chunk-QU365SAC.js} +6 -6
- package/dist/chunk-QU365SAC.js.map +1 -0
- package/dist/devtools/bridge.cjs +1 -1
- package/dist/devtools/bridge.js +1 -1
- package/dist/devtools/index.cjs +1 -1
- package/dist/devtools/index.js +1 -1
- package/dist/{index-CPKnWBVv.d.ts → index-BXaNeJBk.d.ts} +1 -1
- package/dist/{index-BD_l3aH5.d.cts → index-mzR_3Kbx.d.cts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.cts +4 -4
- package/dist/react/index.d.ts +4 -4
- package/dist/react/index.js +1 -1
- package/dist/react-native/index.cjs +1 -1
- package/dist/react-native/index.d.cts +4 -4
- package/dist/react-native/index.d.ts +4 -4
- package/dist/react-native/index.js +1 -1
- package/dist/resolvers/joi.d.cts +1 -1
- package/dist/resolvers/joi.d.ts +1 -1
- package/dist/resolvers/yup.d.cts +1 -1
- package/dist/resolvers/yup.d.ts +1 -1
- package/dist/resolvers/zod.d.cts +1 -1
- package/dist/resolvers/zod.d.ts +1 -1
- package/dist/{use-bit-watch-CoCFwS-F.d.ts → use-bit-watch-DEYCmgNf.d.ts} +2 -2
- package/dist/{use-bit-watch-BSWy9rG7.d.cts → use-bit-watch-wjK9PF7w.d.cts} +2 -2
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.d.cts +2 -2
- package/dist/vue/index.d.ts +2 -2
- package/dist/vue/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-KA4FAGIX.js.map +0 -1
- /package/dist/{chunk-UFYHEI6S.js.map → chunk-OA4FCEV2.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/store/bus.ts","../src/core/utils.ts","../src/devtools/ui/styles.ts","../src/devtools/ui/index.ts","../src/devtools/init-dev-tools.ts"],"names":["rootGlobal","id","state","fn","bitBus","deepClone","obj","item","clone","key","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAaA,kwBAAMA,CAAAA,CACJ,OAAO,UAAA,CAAe,GAAA,CAClB,UAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAS,MAAA,CAE5CA,CAAAA,CAAW,YAAA,EAAA,CACdA,CAAAA,CAAW,YAAA,CAAe,CACxB,MAAA,CAAQ,CAAC,CAAA,CACT,SAAA,CAAW,IAAI,GAAA,CAEf,QAAA,CAASC,CAAAA,CAAYC,CAAAA,CAAY,CAC/B,IAAA,CAAK,SAAA,CAAU,OAAA,CAASC,CAAAA,EAAuBA,CAAAA,CAAGF,CAAAA,CAAIC,CAAK,CAAC,CAC9D,CAAA,CAEA,SAAA,CAAUC,CAAAA,CAAoB,CAC5B,OAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAE,CAAA,CACd,CA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACkES,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBG,MAAA;AAAA;AAAA;AAGyB,0CAAA;AAAA;AAE0C,uCAAA;AAC7B,kBAAA;AAAA;AAE6B,gBAAA;AACY,gBAAA;AAAA;AAAA;AAAA;AAIhB,yDAAA;AAAA;AAAA;AAG+B,4EAAA;AAAA;AAAA;AAGA,4EAAA;AAAA;AAAA;AAGpB,2FAAA;AAAA;AAAA;AAAA;AAOxE,QAAA;AAAA;AAEuD,uCAAA;AAIzD,UAAA;AAAA;AAEmD,iCAAA;AAAA;AAShD,QAAA;AAC8E,6DAAA;AACnE,QAAA;AAAA;AC5HA,IAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-6VDQSKUN.cjs","sourcesContent":["export type BitBusListener = (storeId: string, newState: any) => void;\n\ninterface BitFormGlobal {\n stores: Record<string, any>;\n listeners: Set<BitBusListener>;\n dispatch: (storeId: string, state: any) => void;\n subscribe: (fn: BitBusListener) => () => void;\n}\n\ndeclare global {\n var __BIT_FORM__: BitFormGlobal | undefined;\n}\n\nconst rootGlobal =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : ((typeof global !== \"undefined\" ? global : window) as any);\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state: any) {\n this.listeners.forEach((fn: BitBusListener) => fn(id, state));\n },\n\n subscribe(fn: BitBusListener) {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n },\n };\n}\n\nexport const bitBus = rootGlobal.__BIT_FORM__ as BitFormGlobal;\n","export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return 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\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([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\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 pathCache = new Map<string, string[]>();\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\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 = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\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 isNextNumeric = /^\\d+$/.test(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 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 const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\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)) 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","export function getDevToolsCSS(): string {\n return `\n .bit-devtools-container {\n position: fixed;\n bottom: 20px;\n right: 20px;\n z-index: 9999;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n .bit-devtools-trigger {\n background: #10b981;\n color: #fff;\n border: none;\n border-radius: 50%;\n width: 48px;\n height: 48px;\n cursor: pointer;\n box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);\n font-weight: bold;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 16px;\n margin-top: 16px;\n }\n .bit-devtools-trigger:hover { transform: scale(1.05); }\n\n .bit-devtools-panel {\n width: 450px;\n max-height: 80vh;\n background: #0f172a;\n color: #f8fafc;\n border-radius: 8px;\n padding: 16px;\n overflow-y: auto;\n box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);\n border: 1px solid #334155;\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .bit-devtools-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding-bottom: 12px;\n border-bottom: 1px solid #1e293b;\n }\n .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }\n\n .bit-store-block {\n background: #1e293b;\n border-radius: 6px;\n padding: 12px;\n border: 1px solid #334155;\n }\n\n .bit-store-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }\n\n .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }\n .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }\n .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }\n .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }\n .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }\n .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }\n\n .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }\n\n .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }\n .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }\n .bit-action-btn:hover:not(:disabled) { background: #475569; }\n .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }\n .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }\n\n pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }\n pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }\n `;\n}\n","import { getDevToolsCSS } from \"./styles\";\nimport type { DevToolsActions } from \"../types\";\n\nexport type { DevToolsActions };\n\nexport class BitFormDevToolsUI {\n private container: HTMLElement;\n private actions: DevToolsActions;\n private rootElement: HTMLDivElement;\n private currentStoresState: Record<string, any> = {};\n private isOpen: boolean = false;\n\n constructor(container: HTMLElement, actions: DevToolsActions) {\n this.container = container;\n this.actions = actions;\n\n if (!document.getElementById(\"bit-devtools-styles\")) {\n const style = document.createElement(\"style\");\n style.id = \"bit-devtools-styles\";\n style.textContent = getDevToolsCSS();\n document.head.appendChild(style);\n }\n\n this.rootElement = document.createElement(\"div\");\n this.rootElement.className = \"bit-devtools-container\";\n this.container.appendChild(this.rootElement);\n\n this.rootElement.addEventListener(\"click\", (e) => {\n const target = e.target as HTMLElement;\n\n // Evento do botão flutuante\n if (target.closest(\".bit-devtools-trigger\")) {\n this.isOpen = !this.isOpen;\n this.render();\n return;\n }\n\n // Eventos dos botões de ação\n const btn = target.closest(\".bit-action-btn\");\n if (btn && !btn.hasAttribute(\"disabled\")) {\n const action = btn.getAttribute(\"data-action\");\n const storeId = btn.getAttribute(\"data-store\");\n\n if (action && storeId) {\n if (action === \"undo\") this.actions.onUndo(storeId);\n if (action === \"redo\") this.actions.onRedo(storeId);\n if (action === \"reset\") this.actions.onReset(storeId);\n }\n }\n });\n }\n\n public updateState(storesState: Record<string, any>) {\n this.currentStoresState = storesState;\n this.render();\n }\n\n private render() {\n const storeEntries = Object.entries(this.currentStoresState);\n if (storeEntries.length === 0) {\n this.rootElement.innerHTML = \"\";\n return;\n }\n\n let panelHtml = \"\";\n\n if (this.isOpen) {\n panelHtml = `\n <div class=\"bit-devtools-panel\">\n <div class=\"bit-devtools-header\">\n <h2><span style=\"font-size: 20px;\">🛠</span> Bit-Form DevTools</h2>\n <span style=\"font-size: 11px; color: #64748b;\">v1.0.0</span>\n </div>\n `;\n\n for (const [id, state] of storeEntries) {\n const hasErrors = Object.keys(state.errors || {}).length > 0;\n\n // Lemos os metadados do histórico que o adaptador injetou\n const meta = state._meta || {\n totalSteps: 0,\n currentIndex: -1,\n canUndo: false,\n canRedo: false,\n };\n const currentStep = meta.currentIndex + 1;\n const totalSteps = meta.totalSteps;\n\n panelHtml += `\n <div class=\"bit-store-block\">\n <div class=\"bit-store-header\">\n <h3 class=\"bit-store-title\">${id}</h3>\n <div class=\"bit-badge-group\">\n <span class=\"bit-badge ${state.isValid ? \"badge-success\" : \"badge-error\"}\">\n ${state.isValid ? \"✓ Valid\" : \"✕ Invalid\"}\n </span>\n ${state.isDirty ? `<span class=\"bit-badge badge-warn\">Dirty</span>` : \"\"}\n ${state.isSubmitting ? `<span class=\"bit-badge badge-info\">⏳ Submitting</span>` : \"\"}\n </div>\n </div>\n\n <span class=\"bit-section-title\">Time Travel (${currentStep}/${totalSteps})</span>\n \n <div class=\"bit-controls\">\n <button class=\"bit-action-btn\" data-action=\"undo\" data-store=\"${id}\" ${meta.canUndo ? \"\" : \"disabled\"}>\n <span>↺</span> Undo\n </button>\n <button class=\"bit-action-btn\" data-action=\"redo\" data-store=\"${id}\" ${meta.canRedo ? \"\" : \"disabled\"}>\n <span>↻</span> Redo\n </button>\n <button class=\"bit-action-btn bit-btn-reset\" data-action=\"reset\" data-store=\"${id}\">\n <span>🗑</span> Reset\n </button>\n </div>\n `;\n\n if (hasErrors) {\n panelHtml += `\n <span class=\"bit-section-title\" style=\"color: #f87171;\">⚠️ Validations Failing</span>\n <pre class=\"bit-error-box\">${JSON.stringify(state.errors, null, 2)}</pre>\n `;\n }\n\n panelHtml += `\n <span class=\"bit-section-title\">Values</span>\n <pre class=\"bit-pre\">${JSON.stringify(state.values, null, 2)}</pre>\n </div>\n `;\n }\n\n panelHtml += `</div>`;\n }\n\n // Botão Flutuante (sempre renderizado)\n const triggerHtml = `\n <button class=\"bit-devtools-trigger\" style=\"transform: ${this.isOpen ? \"scale(0.9)\" : \"scale(1)\"};\" title=\"Abrir DevTools\">\n ${this.isOpen ? \"✖\" : \"Bit\"}\n </button>\n `;\n\n this.rootElement.innerHTML = panelHtml + triggerHtml;\n }\n}\n","import { setupLocalDevTools } from \"./adapters/local\";\nimport { setupRemoteDevTools } from \"./adapters/remote\";\nimport type { BitDevToolsOptions } from \"./types\";\n\nexport type { BitDevToolsOptions };\n\nexport function initDevTools(options: BitDevToolsOptions = {}) {\n const { mode = \"local\", url } = options;\n let containerEl: HTMLElement;\n\n let isAutoCreated = false;\n\n if (typeof options.container === \"string\") {\n const el = document.querySelector<HTMLElement>(options.container);\n if (!el)\n throw new Error(\n `[bit-form] Container '${options.container}' não encontrado na página.`,\n );\n containerEl = el;\n } else if (options.container instanceof HTMLElement) {\n containerEl = options.container;\n } else {\n containerEl = document.createElement(\"div\");\n containerEl.id = \"bit-form-devtools-root\";\n containerEl.style.position = \"fixed\";\n containerEl.style.bottom = \"20px\";\n containerEl.style.right = \"20px\";\n containerEl.style.zIndex = \"9999\";\n containerEl.style.maxHeight = \"80vh\";\n containerEl.style.overflowY = \"auto\";\n containerEl.style.boxShadow = \"0 10px 25px rgba(0,0,0,0.1)\";\n document.body.appendChild(containerEl);\n isAutoCreated = true;\n }\n\n let adapterInstance: any;\n\n if (mode === \"local\") {\n console.log(\"[bit-form] DevTools iniciado em modo Local.\");\n adapterInstance = setupLocalDevTools(containerEl);\n } else if (mode === \"remote\") {\n console.log(\"[bit-form] DevTools iniciado em modo Remote.\");\n adapterInstance = setupRemoteDevTools(containerEl, url);\n } else {\n throw new Error(`[bit-form] Modo DevTools inválido: ${mode}`);\n }\n\n return {\n ...adapterInstance,\n destroy: () => {\n if (adapterInstance && typeof adapterInstance.destroy === \"function\") {\n adapterInstance.destroy();\n }\n\n if (isAutoCreated && containerEl.parentNode) {\n containerEl.parentNode.removeChild(containerEl);\n } else {\n containerEl.innerHTML = \"\";\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/store/bus.ts","../src/core/utils.ts","../src/devtools/ui/styles.ts","../src/devtools/ui/index.ts","../src/devtools/init-dev-tools.ts"],"names":["rootGlobal","id","state","fn","bitBus","deepClone","obj","item","clone","key","valueEq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AA,CAAA,IAAWI,EAAAA,GAAKD,CAAAA,CAAS,CACvB,IAAME,CAAAA,CAAIJ,CAAAA,CAAS,CAAA,EAAA;ACtGd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACkES,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBG,MAAA;AAAA;AAAA;AAGyB,0CAAA;AAAA;AAE0C,uCAAA;AAC7B,kBAAA;AAAA;AAE6B,gBAAA;AACY,gBAAA;AAAA;AAAA;AAAA;AAIhB,yDAAA;AAAA;AAAA;AAG+B,4EAAA;AAAA;AAAA;AAGA,4EAAA;AAAA;AAAA;AAGpB,2FAAA;AAAA;AAAA;AAAA;AAOxE,QAAA;AAAA;AAEuD,uCAAA;AAIzD,UAAA;AAAA;AAEmD,iCAAA;AAAA;AAShD,QAAA;AAC8E,6DAAA;AACnE,QAAA;AAAA;AC5HA,IAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-J3EGU5ZH.cjs","sourcesContent":["export type BitBusListener = (storeId: string, newState: any) => void;\n\ninterface BitFormGlobal {\n stores: Record<string, any>;\n listeners: Set<BitBusListener>;\n dispatch: (storeId: string, state: any) => void;\n subscribe: (fn: BitBusListener) => () => void;\n}\n\ndeclare global {\n var __BIT_FORM__: BitFormGlobal | undefined;\n}\n\nconst rootGlobal =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : ((typeof global !== \"undefined\" ? global : window) as any);\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state: any) {\n this.listeners.forEach((fn: BitBusListener) => fn(id, state));\n },\n\n subscribe(fn: BitBusListener) {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n },\n };\n}\n\nexport const bitBus = rootGlobal.__BIT_FORM__ as BitFormGlobal;\n","export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return 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\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([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\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 pathCache = new Map<string, string[]>();\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\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 = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\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 isNextNumeric = /^\\d+$/.test(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 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 const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\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)) 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","export function getDevToolsCSS(): string {\n return `\n .bit-devtools-container {\n position: fixed;\n bottom: 20px;\n right: 20px;\n z-index: 9999;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n .bit-devtools-trigger {\n background: #10b981;\n color: #fff;\n border: none;\n border-radius: 50%;\n width: 48px;\n height: 48px;\n cursor: pointer;\n box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);\n font-weight: bold;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 16px;\n margin-top: 16px;\n }\n .bit-devtools-trigger:hover { transform: scale(1.05); }\n\n .bit-devtools-panel {\n width: 450px;\n max-height: 80vh;\n background: #0f172a;\n color: #f8fafc;\n border-radius: 8px;\n padding: 16px;\n overflow-y: auto;\n box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);\n border: 1px solid #334155;\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .bit-devtools-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding-bottom: 12px;\n border-bottom: 1px solid #1e293b;\n }\n .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }\n\n .bit-store-block {\n background: #1e293b;\n border-radius: 6px;\n padding: 12px;\n border: 1px solid #334155;\n }\n\n .bit-store-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }\n\n .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }\n .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }\n .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }\n .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }\n .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }\n .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }\n\n .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }\n\n .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }\n .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }\n .bit-action-btn:hover:not(:disabled) { background: #475569; }\n .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }\n .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }\n\n pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }\n pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }\n `;\n}\n","import { getDevToolsCSS } from \"./styles\";\nimport type { DevToolsActions } from \"../types\";\n\nexport type { DevToolsActions };\n\nexport class BitFormDevToolsUI {\n private container: HTMLElement;\n private actions: DevToolsActions;\n private rootElement: HTMLDivElement;\n private currentStoresState: Record<string, any> = {};\n private isOpen: boolean = false;\n\n constructor(container: HTMLElement, actions: DevToolsActions) {\n this.container = container;\n this.actions = actions;\n\n if (!document.getElementById(\"bit-devtools-styles\")) {\n const style = document.createElement(\"style\");\n style.id = \"bit-devtools-styles\";\n style.textContent = getDevToolsCSS();\n document.head.appendChild(style);\n }\n\n this.rootElement = document.createElement(\"div\");\n this.rootElement.className = \"bit-devtools-container\";\n this.container.appendChild(this.rootElement);\n\n this.rootElement.addEventListener(\"click\", (e) => {\n const target = e.target as HTMLElement;\n\n // Evento do botão flutuante\n if (target.closest(\".bit-devtools-trigger\")) {\n this.isOpen = !this.isOpen;\n this.render();\n return;\n }\n\n // Eventos dos botões de ação\n const btn = target.closest(\".bit-action-btn\");\n if (btn && !btn.hasAttribute(\"disabled\")) {\n const action = btn.getAttribute(\"data-action\");\n const storeId = btn.getAttribute(\"data-store\");\n\n if (action && storeId) {\n if (action === \"undo\") this.actions.onUndo(storeId);\n if (action === \"redo\") this.actions.onRedo(storeId);\n if (action === \"reset\") this.actions.onReset(storeId);\n }\n }\n });\n }\n\n public updateState(storesState: Record<string, any>) {\n this.currentStoresState = storesState;\n this.render();\n }\n\n private render() {\n const storeEntries = Object.entries(this.currentStoresState);\n if (storeEntries.length === 0) {\n this.rootElement.innerHTML = \"\";\n return;\n }\n\n let panelHtml = \"\";\n\n if (this.isOpen) {\n panelHtml = `\n <div class=\"bit-devtools-panel\">\n <div class=\"bit-devtools-header\">\n <h2><span style=\"font-size: 20px;\">🛠</span> Bit-Form DevTools</h2>\n <span style=\"font-size: 11px; color: #64748b;\">v1.0.0</span>\n </div>\n `;\n\n for (const [id, state] of storeEntries) {\n const hasErrors = Object.keys(state.errors || {}).length > 0;\n\n // Lemos os metadados do histórico que o adaptador injetou\n const meta = state._meta || {\n totalSteps: 0,\n currentIndex: -1,\n canUndo: false,\n canRedo: false,\n };\n const currentStep = meta.currentIndex + 1;\n const totalSteps = meta.totalSteps;\n\n panelHtml += `\n <div class=\"bit-store-block\">\n <div class=\"bit-store-header\">\n <h3 class=\"bit-store-title\">${id}</h3>\n <div class=\"bit-badge-group\">\n <span class=\"bit-badge ${state.isValid ? \"badge-success\" : \"badge-error\"}\">\n ${state.isValid ? \"✓ Valid\" : \"✕ Invalid\"}\n </span>\n ${state.isDirty ? `<span class=\"bit-badge badge-warn\">Dirty</span>` : \"\"}\n ${state.isSubmitting ? `<span class=\"bit-badge badge-info\">⏳ Submitting</span>` : \"\"}\n </div>\n </div>\n\n <span class=\"bit-section-title\">Time Travel (${currentStep}/${totalSteps})</span>\n \n <div class=\"bit-controls\">\n <button class=\"bit-action-btn\" data-action=\"undo\" data-store=\"${id}\" ${meta.canUndo ? \"\" : \"disabled\"}>\n <span>↺</span> Undo\n </button>\n <button class=\"bit-action-btn\" data-action=\"redo\" data-store=\"${id}\" ${meta.canRedo ? \"\" : \"disabled\"}>\n <span>↻</span> Redo\n </button>\n <button class=\"bit-action-btn bit-btn-reset\" data-action=\"reset\" data-store=\"${id}\">\n <span>🗑</span> Reset\n </button>\n </div>\n `;\n\n if (hasErrors) {\n panelHtml += `\n <span class=\"bit-section-title\" style=\"color: #f87171;\">⚠️ Validations Failing</span>\n <pre class=\"bit-error-box\">${JSON.stringify(state.errors, null, 2)}</pre>\n `;\n }\n\n panelHtml += `\n <span class=\"bit-section-title\">Values</span>\n <pre class=\"bit-pre\">${JSON.stringify(state.values, null, 2)}</pre>\n </div>\n `;\n }\n\n panelHtml += `</div>`;\n }\n\n // Botão Flutuante (sempre renderizado)\n const triggerHtml = `\n <button class=\"bit-devtools-trigger\" style=\"transform: ${this.isOpen ? \"scale(0.9)\" : \"scale(1)\"};\" title=\"Abrir DevTools\">\n ${this.isOpen ? \"✖\" : \"Bit\"}\n </button>\n `;\n\n this.rootElement.innerHTML = panelHtml + triggerHtml;\n }\n}\n","import { setupLocalDevTools } from \"./adapters/local\";\nimport { setupRemoteDevTools } from \"./adapters/remote\";\nimport type { BitDevToolsOptions } from \"./types\";\n\nexport type { BitDevToolsOptions };\n\nexport function initDevTools(options: BitDevToolsOptions = {}) {\n const { mode = \"local\", url } = options;\n let containerEl: HTMLElement;\n\n let isAutoCreated = false;\n\n if (typeof options.container === \"string\") {\n const el = document.querySelector<HTMLElement>(options.container);\n if (!el)\n throw new Error(\n `[bit-form] Container '${options.container}' não encontrado na página.`,\n );\n containerEl = el;\n } else if (options.container instanceof HTMLElement) {\n containerEl = options.container;\n } else {\n containerEl = document.createElement(\"div\");\n containerEl.id = \"bit-form-devtools-root\";\n containerEl.style.position = \"fixed\";\n containerEl.style.bottom = \"20px\";\n containerEl.style.right = \"20px\";\n containerEl.style.zIndex = \"9999\";\n containerEl.style.maxHeight = \"80vh\";\n containerEl.style.overflowY = \"auto\";\n containerEl.style.boxShadow = \"0 10px 25px rgba(0,0,0,0.1)\";\n document.body.appendChild(containerEl);\n isAutoCreated = true;\n }\n\n let adapterInstance: any;\n\n if (mode === \"local\") {\n console.log(\"[bit-form] DevTools iniciado em modo Local.\");\n adapterInstance = setupLocalDevTools(containerEl);\n } else if (mode === \"remote\") {\n console.log(\"[bit-form] DevTools iniciado em modo Remote.\");\n adapterInstance = setupRemoteDevTools(containerEl, url);\n } else {\n throw new Error(`[bit-form] Modo DevTools inválido: ${mode}`);\n }\n\n return {\n ...adapterInstance,\n destroy: () => {\n if (adapterInstance && typeof adapterInstance.destroy === \"function\") {\n adapterInstance.destroy();\n }\n\n if (isAutoCreated && containerEl.parentNode) {\n containerEl.parentNode.removeChild(containerEl);\n } else {\n containerEl.innerHTML = \"\";\n }\n },\n };\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{d as R,e as B,h as D,i as k}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{d as R,e as B,h as D,i as k}from"./chunk-QU365SAC.js";import{createContext as A,useContext as O}from"react";import{jsx as U}from"react/jsx-runtime";var w=A(null),nt=({store:t,children:e})=>U(w.Provider,{value:t,children:e}),S=()=>{let t=O(w);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};import{useCallback as y,useSyncExternalStore as q,useMemo as H,useRef as L,useState as M}from"react";function ct(){let t=S(),[e,r]=M(null),[i,a]=M(null),o=L(null),g=y(()=>{let u=t.getState(),{isValid:d,isDirty:b,isSubmitting:p}=u,T=t.canUndo,I=t.canRedo;if(o.current&&o.current.isValid===d&&o.current.isDirty===b&&o.current.isSubmitting===p&&o.current.canUndo===T&&o.current.canRedo===I)return o.current;let x={isValid:d,isDirty:b,isSubmitting:p,canUndo:T,canRedo:I};return o.current=x,x},[t]),c=q(t.subscribe.bind(t),g,g),s=y(u=>d=>(d?.preventDefault?.(),t.submit(u)),[t]),n=y(u=>d=>(d?.preventDefault?.(),r(null),t.submit(async b=>{try{let p=await u(b);a(p),r(null)}catch(p){D(p)?t.setServerErrors(k(p)):r(p instanceof Error?p:new Error(String(p)))}})),[t]),m=y(()=>{t.reset(),r(null),a(null)},[t]),l=y(()=>t.getState().values,[t]),f=y(()=>t.getState().errors,[t]),h=y(()=>t.getState().touched,[t]),v=H(()=>({setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),reset:m,validate:t.validate.bind(t),registerMask:t.registerMask.bind(t),pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t),undo:t.undo.bind(t),redo:t.redo.bind(t)}),[t,m]);return{...c,getValues:l,getErrors:f,getTouched:h,submit:s,onSubmit:n,submitError:e,lastResponse:i,...v,reset:m,store:t}}import{useCallback as W,useSyncExternalStore as _,useState as $,useMemo as j,useEffect as z}from"react";var P=()=>Math.random().toString(36).substring(2,9);function ht(t){let e=S(),r=W(()=>{let s=e.getState(),n=B(s.values,t);return Array.isArray(n)?n:[]},[e,t]),i=_(e.subscribe.bind(e),r,r),[a,o]=$(()=>i.map(P));z(()=>{i.length!==a.length&&o(s=>{if(i.length>s.length){let n=i.length-s.length;return[...s,...Array(n).fill(null).map(P)]}return s.slice(0,i.length)})},[i.length]);let g=j(()=>({append:s=>{o(n=>[...n,P()]),e.pushItem(t,s)},prepend:s=>{o(n=>[P(),...n]),e.prependItem(t,s)},insert:(s,n)=>{o(m=>{let l=[...m];return l.splice(s,0,P()),l}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((m,l)=>l!==s)),e.removeItem(t,s)},move:(s,n)=>{o(m=>{let l=[...m],[f]=l.splice(s,1);return l.splice(n,0,f),l}),e.moveItem(t,s,n)},swap:(s,n)=>{o(m=>{let l=[...m];return[l[s],l[n]]=[l[n],l[s]],l}),e.swapItems(t,s,n)},replace:s=>{o(s.map(P)),e.setField(t,s)},clear:()=>{o([]),e.setField(t,[])}}),[e,t]);return{fields:j(()=>i.map((s,n)=>({key:a[n]||`temp-${n}`,value:s,index:n})),[i,a]),length:i.length,...g}}import{useCallback as V,useSyncExternalStore as G,useRef as J}from"react";function Ft(t){let e=S(),r=J(null),i=V(()=>{let c=e.getStepStatus(t);return r.current&&r.current.hasErrors===c.hasErrors&&r.current.isDirty===c.isDirty&&Object.keys(r.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=c,c)},[e,t]),a=G(e.subscribe.bind(e),i,i),o=V(async()=>{let c=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:c,errors:s}},[e,t]),g=V(()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:a,errors:a.errors,validate:o,getErrors:g,isValid:!a.hasErrors,isDirty:a.isDirty}}import{useCallback as F,useSyncExternalStore as K,useRef as Q,useState as X}from"react";function It(t){let e=S(),[r,i]=X(0),a=t[r]??"",o=Q(null),g=F(()=>{let u=e.getStepStatus(a);return o.current&&o.current.hasErrors===u.hasErrors&&o.current.isDirty===u.isDirty&&Object.keys(o.current.errors).length===Object.keys(u.errors).length&&Object.entries(u.errors).every(([d,b])=>o.current.errors[d]===b)?o.current:(o.current=u,u)},[e,a]),c=K(e.subscribe.bind(e),g,g),s=F(async()=>{let u=await e.validate({scope:a}),d=e.getStepErrors(a);return{valid:u,errors:d}},[e,a]),n=F(()=>e.getStepErrors(a),[e,a]),m=F(async()=>{let u=await e.validate({scope:a});if(u)i(d=>Math.min(d+1,t.length-1));else{let d=e.getStepErrors(a),b=Object.keys(d);b.length>0&&e.markFieldsTouched(b)}return u},[e,a,t.length]),l=F(()=>{i(u=>Math.max(u-1,0))},[]),f=F(u=>{i(Math.max(0,Math.min(u-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:m,prev:l,goTo:f,isFirst:h,isLast:v,status:c,errors:c.errors,isValid:!c.hasErrors,isDirty:c.isDirty,validate:s,getErrors:n}}import{useCallback as C,useSyncExternalStore as Y,useRef as Z}from"react";function jt(t){let e=S(),r=Z(null),i=C(()=>{let o=B(e.getState().values,t);return r.current!==null&&R(r.current,o)?r.current:(r.current=o,o)},[e,t]),a=C(o=>e.subscribe(o),[e]);return Y(a,i,i)}import{useCallback as E,useSyncExternalStore as N,useRef as tt,useEffect as et}from"react";function Wt(t,e){let r=S(),i=tt(null);et(()=>(e&&r.registerField(t,e),()=>{r.unregisterField&&r.unregisterField(t)}),[r,t,e]);let a=E(()=>{let n=r.getState(),m=B(n.values,t),l=n.errors[t],f=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),u=r.isFieldDirty(t),d=r.isFieldValidating(t);if(i.current&&i.current.value===m&&i.current.error===l&&i.current.touched===f&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===u&&i.current.isValidating===d)return i.current;let b={value:m,error:l,touched:f,isHidden:h,isRequired:v,isDirty:u,isValidating:d};return i.current=b,b},[r,t]),o=E(n=>r.subscribe(n),[r]),g=N(o,a,a),c=E(n=>r.setField(t,n),[r,t]),s=E(()=>r.blurField(t),[r,t]);return{fieldState:g,setValue:c,setBlur:s,store:r}}export{nt as a,S as b,ct as c,Wt as d,ht as e,Ft as f,It as g,jt as h};
|
|
2
|
+
//# sourceMappingURL=chunk-OA4FCEV2.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_FORM__||(F.__BIT_FORM__={stores:{},listeners:new Set,dispatch(o,t){this.listeners.forEach(e=>e(o,t))},subscribe(o){return this.listeners.add(o),()=>{this.listeners.delete(o)}}});var m=F.__BIT_FORM__;function g(o){if(o===null||typeof o!="object")return o;if(o instanceof Date)return new Date(o.getTime());if(o instanceof RegExp)return new RegExp(o.source,o.flags);if(Array.isArray(o))return o.map(e=>g(e));let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=g(o[e]));return t}function S(o,t){return o===t?!0:o===null||typeof o!="object"||t===null||typeof t!="object"?!1:x(o,t)}function x(o,t){if(o===t)return!0;if(o===null||typeof o!="object"||t===null||typeof t!="object")return!1;if(o instanceof Date&&t instanceof Date)return o.getTime()===t.getTime();if(o instanceof RegExp&&t instanceof RegExp)return o.toString()===t.toString();let e=Object.keys(o),s=Object.keys(t);if(e.length!==s.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r)||!x(o[r],t[r]))return!1;return!0}function O(o,t,e="",s=new Set){if(S(o,t))return s;if(o===null||typeof o!="object"||t===null||typeof t!="object")return e&&s.add(e),s;if(Array.isArray(o)||Array.isArray(t))return!S(o,t)&&e&&s.add(e),s;let r=new Set([...Object.keys(o||{}),...Object.keys(t||{})]);for(let i of r){let n=e?`${e}.${i}`:i;O(o?.[i],t?.[i],n,s)}return s}var k=new Map;function p(o,t){if(!t)return o;let e=k.get(t)||t.split(".");k.has(t)||k.set(t,e);let s=o;for(let r of e){if(s==null)return;s=s[r]}return s}function y(o,t,e){if(!t)return e;let s=k.get(t)||t.split(".");k.has(t)||k.set(t,s);let r=Array.isArray(o)?[...o]:{...o},i=r;for(let n=0;n<s.length-1;n++){let l=s[n],a=s[n+1],c=/^\d+$/.test(a),d=i[l];d==null?i[l]=c?[]:{}:i[l]=Array.isArray(d)?[...d]:{...d},i=i[l]}return i[s[s.length-1]]=e,r}function kt(o,t){let e={},s=`${t}.`;for(let r in o)r!==t&&!r.startsWith(s)&&(e[r]=o[r]);return e}var $=(o,t,e)=>{let s={},r=`${t}.`;return Object.keys(o).forEach(i=>{if(!i.startsWith(r)){s[i]=o[i];return}let l=i.substring(r.length).split("."),a=parseInt(l[0],10),c=l.slice(1).join(".");if(a!==e)if(a>e){let d=a-1,f=c?`${r}${d}.${c}`:`${r}${d}`;s[f]=o[i]}else s[i]=o[i]}),s},U=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let a=n.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join(".");if(c===e){let f=d?`${i}${s}.${d}`:`${i}${s}`;r[f]=o[n]}else if(c===s){let f=d?`${i}${e}.${d}`:`${i}${e}`;r[f]=o[n]}else r[n]=o[n]}),r},L=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let a=n.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join("."),f=c;c===e?f=s:e<s&&c>e&&c<=s?f=c-1:e>s&&c>=s&&c<e&&(f=c+1);let h=d?`${i}${f}.${d}`:`${i}${f}`;r[h]=o[n]}),r};function gt(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;let t=o.errors??o;return typeof t!="object"||t===null||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string"||Array.isArray(e)&&e.every(s=>typeof s=="string"))}function Bt(o){return gt(o)?o.errors??o:{}}var ht={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},B=(o,t)=>{if(o==null||o==="")return"";let e=String(o),s=e.startsWith("-"),r=t?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",i=new RegExp(`[^a-zA-Z0-9${r}]`,"g"),n=e.replace(i,"");return s&&n&&!n.startsWith("-")?`-${n}`:n},mt=(o,t=2)=>{if(typeof o=="number")return o;if(!o)return 0;let e=String(o),s=e.includes("-"),r=e.replace(/\D/g,"");if(!r)return 0;let i=parseInt(r,10)/Math.pow(10,t);return s?-i:i},u=(o,t)=>{let e=s=>s.split("").filter(r=>ht[r]).length;return{format:s=>{let r=B(s,t?.allowChars);if(!r&&!t?.guide)return"";let n=[...Array.isArray(o)?o:[o]].sort((h,v)=>e(h)-e(v)),l=n[n.length-1];for(let h of n)if(r.length<=e(h)){l=h;break}let a="",c=0,d=t?.guide||!1,f=t?.placeholderChar||"_";for(let h=0;h<l.length;h++){let v=l[h],E=ht[v];if(c<r.length){let T=r[c];if(E)if(v==="U"&&(T=T.toUpperCase()),v==="L"&&(T=T.toLowerCase()),E.test(T))a+=T,c++;else if(d)a+=f;else break;else a+=v,T===v&&c++}else if(d)a+=E?f:v;else break}return a},parse:s=>{if(t?.customParse)return t.customParse(s);let i=u(o,t).format(s);if(t?.saveRaw){if(t?.guide){let l=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(l,"g");return i.replace(a,"")}return i}return B(i,t?.allowChars)}}},b=({prefix:o="",suffix:t="",thousand:e,decimal:s,precision:r=2,allowNegative:i=!0,saveRaw:n=!1})=>{let l=a=>{if(a==null||a==="")return"";let c="";if(typeof a=="number"?c=Math.abs(a).toFixed(r).replace(/\D/g,""):c=String(a).replace(/\D/g,""),!c&&String(a).includes("-")&&i)return"-";if(!c)return"";c=c.padStart(r+1,"0");let d=c.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",f=c.slice(-r),h=d.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${o}${h}${s}${f}${t}`};return{format:l,parse:a=>{let c=mt(a,r),d=i?c:Math.abs(c);return n?l(d):d}}},N=o=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=B(e,o?.allowChars),r=t(s);return u(r,o).format(e)},parse:e=>{let s=B(e,o?.allowChars),r=t(s);return u(r,o).parse(e)}}},P=o=>{let e=(o?.format||"DD/MM/YYYY")==="YYYY-MM-DD",s=u(e?"####-##-##":"##/##/####",o);return{format:r=>{let i=B(r);if(!i)return"";let n="",l="",a="";if(e?(a=i.substring(0,4),l=i.substring(4,6),n=i.substring(6,8)):(n=i.substring(0,2),l=i.substring(2,4),a=i.substring(4,8)),n.length===2){let d=parseInt(n,10);d>31&&(n="31"),d===0&&(n="01")}if(l.length===2){let d=parseInt(l,10);d>12&&(l="12"),d===0&&(l="01")}let c=e?`${a}${l}${n}`:`${n}${l}${a}`;return s.format(c)},parse:r=>s.parse(r)}};var _=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),j=b({prefix:"$",thousand:",",decimal:".",precision:2}),X=b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),q=b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),W=b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),z=b({suffix:"%",thousand:".",decimal:",",precision:1}),Y=b({thousand:".",decimal:",",precision:2}),J=b({thousand:".",decimal:",",precision:0}),K=u("###.###.###-##"),G=u("##.###.###/####-##"),Z=u(["(##) ####-####","(##) #####-####"]),Q=u("(##) ####-####"),tt=u("#####-###"),et=P({format:"DD/MM/YYYY",guide:!0,customParse:o=>{let t=o.replace(/_/g,""),e=t.split("/");return e.length===3&&e[2].length===4?`${e[2]}-${e[1]}-${e[0]}`:t.replace(/\D/g,"")}}),st=u("##:##"),rt=u("###########"),it=u("##.###.###-X"),Mt=u("(###) ###-####"),Et=u("#####-####"),Pt=u("##/##/####"),Ct=u("###-##-####"),ot=N(),nt=u("####"),Dt=P({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),at=u("HH:HH:HH:HH:HH:HH"),lt=u("#HHHHHH"),ct=u("###.###.###.###"),dt=u("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),wt=u("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var ut={brl:_,usd:j,eur:X,gbp:q,jpy:W,cpf:K,cnpj:G,rg:it,cep:tt,cnh:rt,phone:Z,landline:Q,date:et,time:st,ip:ct,ipv6:dt,mac:at,color:lt,cc:ot,cvv:nt,percent:z,decimal:Y,int:J};function Rt(o){let t={},e={},s={};if(!o)return{computed:t,transform:e,scopes:s};for(let[r,i]of Object.entries(o))i?.computed&&(t[r]=i.computed),i?.transform&&(e[r]=i.transform),i?.scope&&(s[i.scope]||(s[i.scope]=[]),s[i.scope].push(r));return{computed:Object.keys(t).length?t:void 0,transform:Object.keys(e).length?e:void 0,scopes:Object.keys(s).length?s:void 0}}function yt(o={}){let t=o.initialValues||{},e=o.validation,s=o.history,{computed:r,transform:i,scopes:n}=Rt(o.fields);return{name:o.name,initialValues:g(t),resolver:e?.resolver,validationDelay:e?.delay??300,defaultRequiredMessage:e?.defaultRequiredMessage,enableHistory:s?.enabled??!1,historyLimit:s?.limit??15,computed:r,transform:i,scopes:n,masks:ut,fields:o.fields,devTools:o.devTools}}var C=class{fieldConfigs=new Map;dependencies=new Map;hiddenFields=new Set;register(t,e,s){this.fieldConfigs.set(t,e);let r=e.conditional?.dependsOn;r&&r.forEach(i=>{this.dependencies.has(i)||this.dependencies.set(i,new Set),this.dependencies.get(i).add(t)}),this.evaluateFieldCondition(t,s)}isHidden(t){return this.hiddenFields.has(t)}isRequired(t,e){let s=this.fieldConfigs.get(t);return!s||this.isHidden(t)?!1:!!s.conditional?.requiredIf?.(e)}getRequiredErrors(t,e="Este campo \xE9 obrigat\xF3rio"){let s={};return this.fieldConfigs.forEach((r,i)=>{if(this.isRequired(i,t)){let n=p(t,i);this.isEmpty(n)&&(s[i]=r.validation?.requiredMessage??e)}}),s}evaluateAll(t){this.fieldConfigs.forEach((e,s)=>{this.evaluateFieldCondition(s,t)})}updateDependencies(t,e){let s=[],r=this.dependencies.get(t);return r&&r.forEach(i=>{let n=this.isHidden(i);this.evaluateFieldCondition(i,e);let l=this.isHidden(i);n!==l&&s.push(i)}),s}unregister(t){this.fieldConfigs.delete(t),this.hiddenFields.delete(t),this.dependencies.delete(t),this.dependencies.forEach(e=>{e.delete(t)})}unregisterPrefix(t){let e=[];this.fieldConfigs.forEach((s,r)=>{r.startsWith(t)&&e.push(r)}),e.forEach(s=>this.unregister(s))}evaluateFieldCondition(t,e){let r=this.fieldConfigs.get(t)?.conditional?.showIf;r&&(r(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t))}isEmpty(t){return t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0}};var D=class{constructor(t,e=15){this.enableHistory=t;this.maxHistory=e}history=[];historyIndex=-1;saveSnapshot(t){if(!this.enableHistory)return;let e=this.history[this.historyIndex];e&&x(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(g(t)),this.history.length>this.maxHistory?this.history.shift():this.historyIndex++)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.history.length-1:!1}undo(){return this.canUndo?(this.historyIndex--,g(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,g(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}};var w=class{constructor(t){this.store=t}pushItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[...s,e]),this.store.internalSaveSnapshot()}prependItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[e,...s]),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...p(this.store.getState().values,t)||[]];r.splice(e,0,s),this.store.setField(t,r),this.store.internalSaveSnapshot()}removeItem(t,e){let s=this.store.getState(),r=p(s.values,t);if(!Array.isArray(r))return;this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let i=r.filter((a,c)=>c!==e),n=y(s.values,t,i),l=this.store.updateDirtyForPath(t,n,this.store.getConfig().initialValues);this.store.internalUpdateState({values:n,errors:$(s.errors,t,e),touched:$(s.touched,t,e),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]];[i[e],i[s]]=[i[s],i[e]];let n=y(r.values,t,i),l=this.store.updateDirtyForPath(t,n,this.store.getConfig().initialValues);this.store.internalUpdateState({values:n,errors:U(r.errors,t,e,s),touched:U(r.touched,t,e,s),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]],[n]=i.splice(e,1);i.splice(s,0,n);let l=y(r.values,t,i),a=this.store.updateDirtyForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:L(r.errors,t,e,s),touched:L(r.touched,t,e,s),isDirty:a}),this.store.internalSaveSnapshot(),this.revalidate(t)}revalidate(t){let e=this.store;typeof e.triggerValidation=="function"?e.triggerValidation([t]):typeof this.store.validate=="function"&&this.store.validate()}};var I=class{constructor(t){this.config=t}apply(t){if(!this.config.computed)return t;let e=t,s=Object.entries(this.config.computed);for(let r=0;r<2;r++){let i=!1;for(let[n,l]of s){let a=l(e),c=p(e,n);x(c,a)||(e=y(e,n,a),i=!0)}if(!i)break}return e}};var R=class{constructor(t){this.store=t}validationTimeout;currentValidationId=0;asyncTimers={};asyncRequests={};asyncErrors={};handleAsync(t,e){let s=this.store.depsMg.fieldConfigs.get(t)||this.store.config.fields?.[t],r=s?.validation?.asyncValidate;if(!r)return;this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=s.validation?.asyncValidateDelay??500;this.asyncTimers[t]=setTimeout(async()=>{let n=(this.asyncRequests[t]||0)+1;this.asyncRequests[t]=n,this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!0}});try{let l=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==n)return;if(l)this.asyncErrors[t]=l,this.store.setError(t,l);else{delete this.asyncErrors[t];let a=this.store;if(a.validate)await a.validate({scopeFields:[t]});else{let c={...this.store.getState().errors};delete c[t],this.store.internalUpdateState({errors:c,isValid:Object.keys(c).length===0})}}}finally{this.asyncRequests[t]===n&&this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!1}})}},i)}trigger(t){this.validationTimeout&&clearTimeout(this.validationTimeout);let e=this.store.config.validationDelay??300;e>0?this.validationTimeout=setTimeout(()=>{this.validate({scopeFields:t})},e):this.validate({scopeFields:t})}async validate(t){let e=++this.currentValidationId,s=this.store.getState(),r=t?.scopeFields;t?.scope&&this.store.config.scopes?.[t.scope]&&(r=this.store.config.scopes[t.scope]);let i=this.store.config.resolver?await this.store.config.resolver(s.values,{scopeFields:r}):{},n=this.store.depsMg.getRequiredErrors(s.values,this.store.config.defaultRequiredMessage);if(i={...i,...n},this.store.depsMg.hiddenFields.forEach(a=>{delete i[a],delete this.asyncErrors[a]}),e!==this.currentValidationId)return s.isValid;if(r){let a={...s.errors};r.forEach(d=>{i[d]?a[d]=i[d]:this.asyncErrors[d]?a[d]=this.asyncErrors[d]:delete a[d]});let c=Object.keys(a).length===0;return this.store.internalUpdateState({errors:a,isValid:c}),r.every(d=>!i[d]&&!this.asyncErrors[d])}i={...this.asyncErrors,...i};let l=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:l}),l}clear(t){this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]),delete this.asyncErrors[t]}cancelAll(){this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(t=>clearTimeout(t))}};var V=class{constructor(t){this.store=t}updateField(t,e){let s=this.store.getState(),r=y(s.values,t,e),i={...s.errors};delete i[t],this.store.validatorMg.clear(t);let n=this.store.depsMg.updateDependencies(t,r);n.forEach(a=>{this.store.depsMg.isHidden(a)&&(delete i[a],this.store.validatorMg.clear(a))});let l=this.store.updateDirtyForPath(t,r,this.store.config.initialValues);return this.store.internalUpdateState({values:r,errors:i,isValid:Object.keys(i).length===0,isDirty:l}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:n.length>0}}updateAll(t){let e=g(t);this.store.config.initialValues=g(e),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(e),this.store.clearDirtyPaths(),this.store.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validatorMg.validate()}async submit(t){if(this.store.getState().isSubmitting)return;if(this.store.validatorMg.cancelAll(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validatorMg.validate())try{let r=g(this.store.getState().values);if(this.store.depsMg.hiddenFields.forEach(i=>{r=y(r,i,void 0)}),this.store.config.transform)for(let i in this.store.config.transform){let n=this.store.config.transform[i];if(n){let l=p(r,i);r=y(r,i,n(l,this.store.getState().values))}}await t(r)}catch(r){console.error(r)}else{let r=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(r).forEach(n=>{i[n]=!0}),this.store.internalUpdateState({touched:i})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.validatorMg.cancelAll();let t=g(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.clearDirtyPaths(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function bt(){return`
|
|
1
|
+
var F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_FORM__||(F.__BIT_FORM__={stores:{},listeners:new Set,dispatch(n,t){this.listeners.forEach(e=>e(n,t))},subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}});var m=F.__BIT_FORM__;function g(n){if(n===null||typeof n!="object")return 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(e=>g(e));let t={};for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=g(n[e]));return t}function S(n,t){return n===t?!0:n===null||typeof n!="object"||t===null||typeof t!="object"?!1:x(n,t)}function x(n,t){if(n===t)return!0;if(n===null||typeof n!="object"||t===null||typeof t!="object")return!1;if(n instanceof Date&&t instanceof Date)return n.getTime()===t.getTime();if(n instanceof RegExp&&t instanceof RegExp)return n.toString()===t.toString();let e=Object.keys(n),s=Object.keys(t);if(e.length!==s.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r)||!x(n[r],t[r]))return!1;return!0}function O(n,t,e="",s=new Set){if(S(n,t))return s;if(n===null||typeof n!="object"||t===null||typeof t!="object")return e&&s.add(e),s;if(Array.isArray(n)||Array.isArray(t))return!S(n,t)&&e&&s.add(e),s;let r=new Set([...Object.keys(n||{}),...Object.keys(t||{})]);for(let i of r){let o=e?`${e}.${i}`:i;O(n?.[i],t?.[i],o,s)}return s}var k=new Map;function p(n,t){if(!t)return n;let e=k.get(t)||t.split(".");k.has(t)||k.set(t,e);let s=n;for(let r of e){if(s==null)return;s=s[r]}return s}function y(n,t,e){if(!t)return e;let s=k.get(t)||t.split(".");k.has(t)||k.set(t,s);let r=Array.isArray(n)?[...n]:{...n},i=r;for(let o=0;o<s.length-1;o++){let l=s[o],a=s[o+1],c=/^\d+$/.test(a),d=i[l];d==null?i[l]=c?[]:{}:i[l]=Array.isArray(d)?[...d]:{...d},i=i[l]}return i[s[s.length-1]]=e,r}function kt(n,t){let e={},s=`${t}.`;for(let r in n)r!==t&&!r.startsWith(s)&&(e[r]=n[r]);return e}var $=(n,t,e)=>{let s={},r=`${t}.`;return Object.keys(n).forEach(i=>{if(!i.startsWith(r)){s[i]=n[i];return}let l=i.substring(r.length).split("."),a=parseInt(l[0],10),c=l.slice(1).join(".");if(a!==e)if(a>e){let d=a-1,f=c?`${r}${d}.${c}`:`${r}${d}`;s[f]=n[i]}else s[i]=n[i]}),s},U=(n,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(n).forEach(o=>{if(!o.startsWith(i)){r[o]=n[o];return}let a=o.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join(".");if(c===e){let f=d?`${i}${s}.${d}`:`${i}${s}`;r[f]=n[o]}else if(c===s){let f=d?`${i}${e}.${d}`:`${i}${e}`;r[f]=n[o]}else r[o]=n[o]}),r},L=(n,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(n).forEach(o=>{if(!o.startsWith(i)){r[o]=n[o];return}let a=o.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join("."),f=c;c===e?f=s:e<s&&c>e&&c<=s?f=c-1:e>s&&c>=s&&c<e&&(f=c+1);let h=d?`${i}${f}.${d}`:`${i}${f}`;r[h]=n[o]}),r};function gt(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let t=n.errors??n;return typeof t!="object"||t===null||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string"||Array.isArray(e)&&e.every(s=>typeof s=="string"))}function Bt(n){return gt(n)?n.errors??n:{}}var ht={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},B=(n,t)=>{if(n==null||n==="")return"";let e=String(n),s=e.startsWith("-"),r=t?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",i=new RegExp(`[^a-zA-Z0-9${r}]`,"g"),o=e.replace(i,"");return s&&o&&!o.startsWith("-")?`-${o}`:o},mt=(n,t=2)=>{if(typeof n=="number")return n;if(!n)return 0;let e=String(n),s=e.includes("-"),r=e.replace(/\D/g,"");if(!r)return 0;let i=parseInt(r,10)/Math.pow(10,t);return s?-i:i},u=(n,t)=>{let e=s=>s.split("").filter(r=>ht[r]).length;return{format:s=>{let r=B(s,t?.allowChars);if(!r&&!t?.guide)return"";let o=[...Array.isArray(n)?n:[n]].sort((h,v)=>e(h)-e(v)),l=o[o.length-1];for(let h of o)if(r.length<=e(h)){l=h;break}let a="",c=0,d=t?.guide||!1,f=t?.placeholderChar||"_";for(let h=0;h<l.length;h++){let v=l[h],E=ht[v];if(c<r.length){let T=r[c];if(E)if(v==="U"&&(T=T.toUpperCase()),v==="L"&&(T=T.toLowerCase()),E.test(T))a+=T,c++;else if(d)a+=f;else break;else a+=v,T===v&&c++}else if(d)a+=E?f:v;else break}return a},parse:s=>{if(t?.customParse)return t.customParse(s);let i=u(n,t).format(s);if(t?.saveRaw){if(t?.guide){let l=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(l,"g");return i.replace(a,"")}return i}return B(i,t?.allowChars)}}},b=({prefix:n="",suffix:t="",thousand:e,decimal:s,precision:r=2,allowNegative:i=!0,saveRaw:o=!1})=>{let l=a=>{if(a==null||a==="")return"";let c="";if(typeof a=="number"?c=Math.abs(a).toFixed(r).replace(/\D/g,""):c=String(a).replace(/\D/g,""),!c&&String(a).includes("-")&&i)return"-";if(!c)return"";c=c.padStart(r+1,"0");let d=c.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",f=c.slice(-r),h=d.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${n}${h}${s}${f}${t}`};return{format:l,parse:a=>{let c=mt(a,r),d=i?c:Math.abs(c);return o?l(d):d}}},N=n=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=B(e,n?.allowChars),r=t(s);return u(r,n).format(e)},parse:e=>{let s=B(e,n?.allowChars),r=t(s);return u(r,n).parse(e)}}},P=n=>{let e=(n?.format||"DD/MM/YYYY")==="YYYY-MM-DD",s=u(e?"####-##-##":"##/##/####",n);return{format:r=>{let i=B(r);if(!i)return"";let o="",l="",a="";if(e?(a=i.substring(0,4),l=i.substring(4,6),o=i.substring(6,8)):(o=i.substring(0,2),l=i.substring(2,4),a=i.substring(4,8)),o.length===2){let d=parseInt(o,10);d>31&&(o="31"),d===0&&(o="01")}if(l.length===2){let d=parseInt(l,10);d>12&&(l="12"),d===0&&(l="01")}let c=e?`${a}${l}${o}`:`${o}${l}${a}`;return s.format(c)},parse:r=>s.parse(r)}};var _=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),j=b({prefix:"$",thousand:",",decimal:".",precision:2}),X=b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),q=b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),W=b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),z=b({suffix:"%",thousand:".",decimal:",",precision:1}),Y=b({thousand:".",decimal:",",precision:2}),J=b({thousand:".",decimal:",",precision:0}),K=u("###.###.###-##"),G=u("##.###.###/####-##"),Z=u(["(##) ####-####","(##) #####-####"]),Q=u("(##) ####-####"),tt=u("#####-###"),et=P({format:"DD/MM/YYYY",guide:!0,customParse:n=>{let t=n.replace(/_/g,""),e=t.split("/");return e.length===3&&e[2].length===4?`${e[2]}-${e[1]}-${e[0]}`:t.replace(/\D/g,"")}}),st=u("##:##"),rt=u("###########"),it=u("##.###.###-X"),Mt=u("(###) ###-####"),Et=u("#####-####"),Pt=u("##/##/####"),Ct=u("###-##-####"),nt=N(),ot=u("####"),Dt=P({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),at=u("HH:HH:HH:HH:HH:HH"),lt=u("#HHHHHH"),ct=u("###.###.###.###"),dt=u("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),wt=u("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var ut={brl:_,usd:j,eur:X,gbp:q,jpy:W,cpf:K,cnpj:G,rg:it,cep:tt,cnh:rt,phone:Z,landline:Q,date:et,time:st,ip:ct,ipv6:dt,mac:at,color:lt,cc:nt,cvv:ot,percent:z,decimal:Y,int:J};function Vt(n){let t={},e={},s={};if(!n)return{computed:t,transform:e,scopes:s};for(let[r,i]of Object.entries(n))i?.computed&&(t[r]=i.computed),i?.transform&&(e[r]=i.transform),i?.scope&&(s[i.scope]||(s[i.scope]=[]),s[i.scope].push(r));return{computed:Object.keys(t).length?t:void 0,transform:Object.keys(e).length?e:void 0,scopes:Object.keys(s).length?s:void 0}}function yt(n={}){let t=n.initialValues||{},e=n.validation,s=n.history,{computed:r,transform:i,scopes:o}=Vt(n.fields);return{name:n.name,initialValues:g(t),resolver:e?.resolver,validationDelay:e?.delay??300,enableHistory:s?.enabled??!1,historyLimit:s?.limit??15,computed:r,transform:i,scopes:o,masks:ut,fields:n.fields,devTools:n.devTools}}var C=class{fieldConfigs=new Map;dependencies=new Map;hiddenFields=new Set;register(t,e,s){this.fieldConfigs.set(t,e);let r=e.conditional?.dependsOn;r&&r.forEach(i=>{this.dependencies.has(i)||this.dependencies.set(i,new Set),this.dependencies.get(i).add(t)}),this.evaluateFieldCondition(t,s)}isHidden(t){return this.hiddenFields.has(t)}isRequired(t,e){let s=this.fieldConfigs.get(t);return!s||this.isHidden(t)?!1:!!s.conditional?.requiredIf?.(e)}getRequiredErrors(t){let e={};return this.fieldConfigs.forEach((s,r)=>{if(this.isRequired(r,t)){let i=p(t,r);this.isEmpty(i)&&(e[r]=s.conditional?.requiredMessage??"required field")}}),e}evaluateAll(t){this.fieldConfigs.forEach((e,s)=>{this.evaluateFieldCondition(s,t)})}updateDependencies(t,e){let s=[],r=this.dependencies.get(t);return r&&r.forEach(i=>{let o=this.isHidden(i);this.evaluateFieldCondition(i,e);let l=this.isHidden(i);o!==l&&s.push(i)}),s}unregister(t){this.fieldConfigs.delete(t),this.hiddenFields.delete(t),this.dependencies.delete(t),this.dependencies.forEach(e=>{e.delete(t)})}unregisterPrefix(t){let e=[];this.fieldConfigs.forEach((s,r)=>{r.startsWith(t)&&e.push(r)}),e.forEach(s=>this.unregister(s))}evaluateFieldCondition(t,e){let r=this.fieldConfigs.get(t)?.conditional?.showIf;r&&(r(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t))}isEmpty(t){return t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0}};var D=class{constructor(t,e=15){this.enableHistory=t;this.maxHistory=e}history=[];historyIndex=-1;saveSnapshot(t){if(!this.enableHistory)return;let e=this.history[this.historyIndex];e&&x(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(g(t)),this.history.length>this.maxHistory?this.history.shift():this.historyIndex++)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.history.length-1:!1}undo(){return this.canUndo?(this.historyIndex--,g(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,g(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}};var w=class{constructor(t){this.store=t}pushItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[...s,e]),this.store.internalSaveSnapshot()}prependItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[e,...s]),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...p(this.store.getState().values,t)||[]];r.splice(e,0,s),this.store.setField(t,r),this.store.internalSaveSnapshot()}removeItem(t,e){let s=this.store.getState(),r=p(s.values,t);if(!Array.isArray(r))return;this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let i=r.filter((a,c)=>c!==e),o=y(s.values,t,i),l=this.store.updateDirtyForPath(t,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:$(s.errors,t,e),touched:$(s.touched,t,e),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]];[i[e],i[s]]=[i[s],i[e]];let o=y(r.values,t,i),l=this.store.updateDirtyForPath(t,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:U(r.errors,t,e,s),touched:U(r.touched,t,e,s),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]],[o]=i.splice(e,1);i.splice(s,0,o);let l=y(r.values,t,i),a=this.store.updateDirtyForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:L(r.errors,t,e,s),touched:L(r.touched,t,e,s),isDirty:a}),this.store.internalSaveSnapshot(),this.revalidate(t)}revalidate(t){let e=this.store;typeof e.triggerValidation=="function"?e.triggerValidation([t]):typeof this.store.validate=="function"&&this.store.validate()}};var I=class{constructor(t){this.config=t}apply(t){if(!this.config.computed)return t;let e=t,s=Object.entries(this.config.computed);for(let r=0;r<2;r++){let i=!1;for(let[o,l]of s){let a=l(e),c=p(e,o);x(c,a)||(e=y(e,o,a),i=!0)}if(!i)break}return e}};var V=class{constructor(t){this.store=t}validationTimeout;currentValidationId=0;asyncTimers={};asyncRequests={};asyncErrors={};handleAsync(t,e){let s=this.store.depsMg.fieldConfigs.get(t)||this.store.config.fields?.[t],r=s?.validation?.asyncValidate;if(!r)return;this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=s.validation?.asyncValidateDelay??500;this.asyncTimers[t]=setTimeout(async()=>{let o=(this.asyncRequests[t]||0)+1;this.asyncRequests[t]=o,this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!0}});try{let l=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==o)return;if(l)this.asyncErrors[t]=l,this.store.setError(t,l);else{delete this.asyncErrors[t];let a=this.store;if(a.validate)await a.validate({scopeFields:[t]});else{let c={...this.store.getState().errors};delete c[t],this.store.internalUpdateState({errors:c,isValid:Object.keys(c).length===0})}}}finally{this.asyncRequests[t]===o&&this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!1}})}},i)}trigger(t){this.validationTimeout&&clearTimeout(this.validationTimeout);let e=this.store.config.validationDelay??300;e>0?this.validationTimeout=setTimeout(()=>{this.validate({scopeFields:t})},e):this.validate({scopeFields:t})}async validate(t){let e=++this.currentValidationId,s=this.store.getState(),r=t?.scopeFields;t?.scope&&this.store.config.scopes?.[t.scope]&&(r=this.store.config.scopes[t.scope]);let i=this.store.config.resolver?await this.store.config.resolver(s.values,{scopeFields:r}):{},o=this.store.depsMg.getRequiredErrors(s.values);if(i={...i,...o},this.store.depsMg.hiddenFields.forEach(a=>{delete i[a],delete this.asyncErrors[a]}),e!==this.currentValidationId)return s.isValid;if(r){let a={...s.errors};r.forEach(d=>{i[d]?a[d]=i[d]:this.asyncErrors[d]?a[d]=this.asyncErrors[d]:delete a[d]});let c=Object.keys(a).length===0;return this.store.internalUpdateState({errors:a,isValid:c}),r.every(d=>!i[d]&&!this.asyncErrors[d])}i={...this.asyncErrors,...i};let l=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:l}),l}clear(t){this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]),delete this.asyncErrors[t]}cancelAll(){this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(t=>clearTimeout(t))}};var R=class{constructor(t){this.store=t}updateField(t,e){let s=this.store.getState(),r=y(s.values,t,e),i={...s.errors};delete i[t],this.store.validatorMg.clear(t);let o=this.store.depsMg.updateDependencies(t,r);o.forEach(a=>{this.store.depsMg.isHidden(a)&&(delete i[a],this.store.validatorMg.clear(a))});let l=this.store.updateDirtyForPath(t,r,this.store.config.initialValues);return this.store.internalUpdateState({values:r,errors:i,isValid:Object.keys(i).length===0,isDirty:l}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:o.length>0}}updateAll(t){let e=g(t);this.store.config.initialValues=g(e),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(e),this.store.clearDirtyPaths(),this.store.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validatorMg.validate()}async submit(t){if(this.store.getState().isSubmitting)return;if(this.store.validatorMg.cancelAll(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validatorMg.validate())try{let r=g(this.store.getState().values);if(this.store.depsMg.hiddenFields.forEach(i=>{r=y(r,i,void 0)}),this.store.config.transform)for(let i in this.store.config.transform){let o=this.store.config.transform[i];if(o){let l=p(r,i);r=y(r,i,o(l,this.store.getState().values))}}await t(r)}catch(r){console.error(r)}else{let r=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(r).forEach(o=>{i[o]=!0}),this.store.internalUpdateState({touched:i})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.validatorMg.cancelAll();let t=g(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.clearDirtyPaths(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function bt(){return`
|
|
2
2
|
.bit-devtools-container {
|
|
3
3
|
position: fixed;
|
|
4
4
|
bottom: 20px;
|
|
@@ -86,13 +86,13 @@ var F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_F
|
|
|
86
86
|
|
|
87
87
|
pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }
|
|
88
88
|
pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }
|
|
89
|
-
`}var M=class{container;actions;rootElement;currentStoresState={};isOpen=!1;constructor(t,e){if(this.container=t,this.actions=e,!document.getElementById("bit-devtools-styles")){let s=document.createElement("style");s.id="bit-devtools-styles",s.textContent=bt(),document.head.appendChild(s)}this.rootElement=document.createElement("div"),this.rootElement.className="bit-devtools-container",this.container.appendChild(this.rootElement),this.rootElement.addEventListener("click",s=>{let r=s.target;if(r.closest(".bit-devtools-trigger")){this.isOpen=!this.isOpen,this.render();return}let i=r.closest(".bit-action-btn");if(i&&!i.hasAttribute("disabled")){let
|
|
89
|
+
`}var M=class{container;actions;rootElement;currentStoresState={};isOpen=!1;constructor(t,e){if(this.container=t,this.actions=e,!document.getElementById("bit-devtools-styles")){let s=document.createElement("style");s.id="bit-devtools-styles",s.textContent=bt(),document.head.appendChild(s)}this.rootElement=document.createElement("div"),this.rootElement.className="bit-devtools-container",this.container.appendChild(this.rootElement),this.rootElement.addEventListener("click",s=>{let r=s.target;if(r.closest(".bit-devtools-trigger")){this.isOpen=!this.isOpen,this.render();return}let i=r.closest(".bit-action-btn");if(i&&!i.hasAttribute("disabled")){let o=i.getAttribute("data-action"),l=i.getAttribute("data-store");o&&l&&(o==="undo"&&this.actions.onUndo(l),o==="redo"&&this.actions.onRedo(l),o==="reset"&&this.actions.onReset(l))}})}updateState(t){this.currentStoresState=t,this.render()}render(){let t=Object.entries(this.currentStoresState);if(t.length===0){this.rootElement.innerHTML="";return}let e="";if(this.isOpen){e=`
|
|
90
90
|
<div class="bit-devtools-panel">
|
|
91
91
|
<div class="bit-devtools-header">
|
|
92
92
|
<h2><span style="font-size: 20px;">\u{1F6E0}</span> Bit-Form DevTools</h2>
|
|
93
93
|
<span style="font-size: 11px; color: #64748b;">v1.0.0</span>
|
|
94
94
|
</div>
|
|
95
|
-
`;for(let[r,i]of t){let
|
|
95
|
+
`;for(let[r,i]of t){let o=Object.keys(i.errors||{}).length>0,l=i._meta||{totalSteps:0,currentIndex:-1,canUndo:!1,canRedo:!1},a=l.currentIndex+1,c=l.totalSteps;e+=`
|
|
96
96
|
<div class="bit-store-block">
|
|
97
97
|
<div class="bit-store-header">
|
|
98
98
|
<h3 class="bit-store-title">${r}</h3>
|
|
@@ -118,7 +118,7 @@ var F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_F
|
|
|
118
118
|
<span>\u{1F5D1}</span> Reset
|
|
119
119
|
</button>
|
|
120
120
|
</div>
|
|
121
|
-
`,
|
|
121
|
+
`,o&&(e+=`
|
|
122
122
|
<span class="bit-section-title" style="color: #f87171;">\u26A0\uFE0F Validations Failing</span>
|
|
123
123
|
<pre class="bit-error-box">${JSON.stringify(i.errors,null,2)}</pre>
|
|
124
124
|
`),e+=`
|
|
@@ -129,5 +129,5 @@ var F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_F
|
|
|
129
129
|
<button class="bit-devtools-trigger" style="transform: ${this.isOpen?"scale(0.9)":"scale(1)"};" title="Abrir DevTools">
|
|
130
130
|
${this.isOpen?"\u2716":"Bit"}
|
|
131
131
|
</button>
|
|
132
|
-
`;this.rootElement.innerHTML=e+s}};function vt(
|
|
133
|
-
//# sourceMappingURL=chunk-
|
|
132
|
+
`;this.rootElement.innerHTML=e+s}};function vt(n){let t=new M(n,{onUndo:r=>m.stores[r]?.undo(),onRedo:r=>m.stores[r]?.redo(),onReset:r=>m.stores[r]?.reset()}),e=()=>{let r={};for(let[i,o]of Object.entries(m.stores)){let l=o,a=l.getState(),c=l?.historyMg,d=c?.history||[],f=c?.historyIndex??-1;r[i]={...a,_meta:{canUndo:l?.canUndo,canRedo:l?.canRedo,totalSteps:d.length,currentIndex:f}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),n.innerHTML=""}}}function xt(n,t="ws://localhost:3000"){let e=new WebSocket(t),s=new M(n,{onUndo:i=>r("ACTION",{storeId:i,action:"undo"}),onRedo:i=>r("ACTION",{storeId:i,action:"redo"}),onReset:i=>r("ACTION",{storeId:i,action:"reset"})}),r=(i,o)=>{e.readyState===WebSocket.OPEN?e.send(JSON.stringify({type:i,payload:o})):console.warn("[bit-form] Tentativa de envio falhou. WebSocket n\xE3o est\xE1 aberto.")};return e.addEventListener("open",()=>{console.log(`[bit-form] Conectado ao DevTools remoto em ${t}`)}),e.addEventListener("message",i=>{try{let o=JSON.parse(i.data);o.type==="STATE_UPDATE"&&s.updateState(o.payload)}catch(o){console.error("[bit-form] Erro ao processar mensagem do WebSocket:",o)}}),e.addEventListener("error",i=>{console.error("[bit-form] Erro na conex\xE3o do DevTools remoto:",i)}),s}function ft(n={}){let{mode:t="local",url:e}=n,s,r=!1;if(typeof n.container=="string"){let o=document.querySelector(n.container);if(!o)throw new Error(`[bit-form] Container '${n.container}' n\xE3o encontrado na p\xE1gina.`);s=o}else n.container instanceof HTMLElement?s=n.container:(s=document.createElement("div"),s.id="bit-form-devtools-root",s.style.position="fixed",s.style.bottom="20px",s.style.right="20px",s.style.zIndex="9999",s.style.maxHeight="80vh",s.style.overflowY="auto",s.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(s),r=!0);let i;if(t==="local")console.log("[bit-form] DevTools iniciado em modo Local."),i=vt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=xt(s,e);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${t}`);return{...i,destroy:()=>{i&&typeof i.destroy=="function"&&i.destroy(),r&&s.parentNode?s.parentNode.removeChild(s):s.innerHTML=""}}}var H=class{store;cleanupFn=null;constructor(t){this.store=t,this.setup()}setup(){let t=this.store.config.devTools;if(!t)return;let e=typeof t=="boolean"?{enabled:t,mode:"local"}:{enabled:!0,...t};if(e.enabled)if(e.mode==="remote"){let s=e.url||"ws://localhost:3000";this.cleanupFn=Tt(s)}else{let s=ft();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}};var pt=class{state;listeners=new Set;config;depsMg;historyMg;validatorMg;computedMg;lifecycleMg;arraysMg;devtoolsMg;storeId;dirtyPaths=new Set;configFields=new Set;constructor(t={}){this.config=yt(t),this.depsMg=new C,this.historyMg=new D(!!this.config.enableHistory,this.config.historyLimit??15),this.computedMg=new I(this.config),this.validatorMg=new V(this),this.arraysMg=new w(this),this.lifecycleMg=new R(this),this.devtoolsMg=new H(this);let e=g(this.config.initialValues),s=this.computedMg.apply(e);this.state={values:s,errors:{},touched:{},isValidating:{},isValid:!0,isSubmitting:!1,isDirty:!1},this.config.fields&&Object.entries(this.config.fields).forEach(([r,i])=>{this.configFields.add(r),this.depsMg.register(r,i,e)}),this.internalSaveSnapshot(),this.storeId=this.config.name||`bit-form-${Math.random().toString(36).substring(2,9)}`,m.stores[this.storeId]=this}getConfig(){return this.config}getState(){return this.state}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}unregisterField(t){if(this.configFields.has(t))return;this.depsMg.unregister(t);let e={...this.state.errors},s={...this.state.touched},r=!1;e[t]&&(delete e[t],r=!0),s[t]&&(delete s[t],r=!0),r&&this.internalUpdateState({errors:e,touched:s})}unregisterPrefix(t){this.depsMg.unregisterPrefix(t)}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.state.values)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}watch(t,e){let s=g(p(this.state.values,t));return this.subscribe(()=>{let r=p(this.state.values,t);x(r,s)||(s=g(r),e(r))})}setField(t,e){let{visibilitiesChanged:s}=this.lifecycleMg.updateField(t,e);(!this.config.resolver||s)&&this.notify()}blurField(t){this.internalSaveSnapshot(),this.state.touched[t]||this.internalUpdateState({touched:{...this.state.touched,[t]:!0}}),this.validatorMg.trigger([t])}markFieldsTouched(t){if(t.length===0)return;let e={...this.state.touched};t.forEach(s=>e[s]=!0),this.internalUpdateState({touched:e})}setValues(t){this.lifecycleMg.updateAll(t)}setError(t,e){let s={...this.state.errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.state.errors,...t}})}setServerErrors(t){let e={};for(let[s,r]of Object.entries(t))e[s]=Array.isArray(r)?r[0]:r;this.setErrors(e)}reset(){this.lifecycleMg.reset()}registerMask(t,e){this.config.masks[t]=e}pushItem(t,e){this.arraysMg.pushItem(t,e)}prependItem(t,e){this.arraysMg.prependItem(t,e)}insertItem(t,e,s){this.arraysMg.insertItem(t,e,s)}removeItem(t,e){this.arraysMg.removeItem(t,e)}swapItems(t,e,s){this.arraysMg.swapItems(t,e,s)}moveItem(t,e,s){this.arraysMg.moveItem(t,e,s)}get canUndo(){return this.historyMg.canUndo}get canRedo(){return this.historyMg.canRedo}undo(){let t=this.historyMg.undo();if(t){let e=this.rebuildDirtyPaths(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.rebuildDirtyPaths(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}validate(t){return this.validatorMg.validate(t)}getStepStatus(t){let e=this.config.scopes?.[t]||[],s=e.some(o=>!!this.state.errors[o]),r=e.some(o=>{let l=p(this.state.values,o),a=p(this.config.initialValues,o);return!S(l,a)}),i=this.getStepErrors(t);return{hasErrors:s,isDirty:r,errors:i}}getStepErrors(t){let e=this.config.scopes?.[t]||[],s={};for(let r of e){let i=this.state.errors[r];i&&(s[r]=i)}return s}isFieldDirty(t){let e=p(this.state.values,t),s=p(this.config.initialValues,t);return!S(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}async submit(t){return this.lifecycleMg.submit(t)}internalUpdateState(t){let e={...this.state,...t};t.values&&(e.values=this.computedMg.apply(t.values)),t.errors&&(e.isValid=Object.keys(e.errors).length===0),this.state=e,this.notify(),m.dispatch(this.storeId,this.state)}internalSaveSnapshot(){this.historyMg.saveSnapshot(this.state.values)}updateDirtyForPath(t,e,s){for(let o of this.dirtyPaths)o.startsWith(t+".")&&this.dirtyPaths.delete(o);let r=p(e,t),i=p(s,t);return S(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}clearDirtyPaths(){this.dirtyPaths.clear()}rebuildDirtyPaths(t,e){return this.dirtyPaths=O(t,e),this.dirtyPaths.size>0}cleanup(){this.listeners.clear(),this.validatorMg.cancelAll(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}};var St=n=>({...typeof n.getState=="function"?n.getState():n,_meta:{canUndo:n.canUndo,canRedo:n.canRedo,totalSteps:n.historyMg?.history?.length||0,currentIndex:n.historyMg?.historyIndex??-1}}),A=null;function Tt(n){A&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),A());let t=null,e=null,s,r=!1,i=()=>{r=!1,t=new WebSocket(n),t.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let l=Object.entries(m.stores);if(l.length>0){let a=l.reduce((c,[d,f])=>(c[d]=St(f),c),{});t?.send(JSON.stringify({type:"STATE_UPDATE",payload:a}))}e=m.subscribe((a,c)=>{if(t?.readyState===WebSocket.OPEN){let d=m.stores[a];d&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[a]:St(d)}}))}}),s=setInterval(()=>{t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=l=>{try{let{type:a,payload:c}=JSON.parse(l.data);if(a==="ACTION"){let{storeId:d,action:f}=c,h=m.stores[d];h&&typeof h[f]=="function"&&h[f]()}}catch(a){console.warn("[bit-form] Erro ao processar comando do CLI:",a)}},t.onclose=()=>{e&&e(),clearInterval(s),r?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(i,3e3))}};i();let o=()=>{r=!0,e&&e(),clearInterval(s),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),A=null};return A=o,o}export{m as a,g as b,S as c,x as d,p as e,y as f,kt as g,gt as h,Bt as i,B as j,mt as k,u as l,b as m,N as n,P as o,_ as p,j as q,X as r,q as s,W as t,z as u,Y as v,J as w,K as x,G as y,Z as z,Q as A,tt as B,et as C,st as D,rt as E,it as F,Mt as G,Et as H,Pt as I,Ct as J,nt as K,ot as L,Dt as M,at as N,lt as O,ct as P,dt as Q,wt as R,ut as S,Tt as T,ft as U,pt as V};
|
|
133
|
+
//# sourceMappingURL=chunk-QU365SAC.js.map
|