@hot-updater/console 0.36.7 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/BundleIdDisplay-D4ErdU5_.js +1 -0
  3. package/.output/public/assets/InsightsCapabilityContext-B42VqvP6.js +1 -0
  4. package/.output/public/assets/api-keys-api-DGVTTvTJ.js +1 -0
  5. package/.output/public/assets/api-keys-z16OZIP4.js +1 -0
  6. package/.output/public/assets/badge-Br_KDO0J.js +1 -0
  7. package/.output/public/assets/card-DzuEXvyJ.js +1 -0
  8. package/.output/public/assets/chart-no-axes-combined-FaYMGmQS.js +1 -0
  9. package/.output/public/assets/createServerFn-gM2-LFBy.js +3 -0
  10. package/.output/public/assets/dialog-BeAENgez.js +1 -0
  11. package/.output/public/assets/dist-Bssh_cv0.js +1 -0
  12. package/.output/public/assets/field-Buq148-A.js +1 -0
  13. package/.output/public/assets/index-uOpQAIC4.js +10 -0
  14. package/.output/public/assets/input-group-B3p5UpyW.js +1 -0
  15. package/.output/public/assets/insights-DJTr7Ozn.js +1 -0
  16. package/.output/public/assets/insights-api-DVMOoRMS.js +1 -0
  17. package/.output/public/assets/installations-BY64iIAK.js +2 -0
  18. package/.output/public/assets/installations-D5v9i3AL.js +1 -0
  19. package/.output/public/assets/lazyRouteComponent-DKYu5cZJ.js +1 -0
  20. package/.output/public/assets/preload-helper-CQ36nxok.js +1 -0
  21. package/.output/public/assets/refresh-cw-BkbfZ62O.js +1 -0
  22. package/.output/public/assets/routes-BuoI5-Cr.js +2 -0
  23. package/.output/public/assets/routes-C8fvgETO.js +1 -0
  24. package/.output/public/assets/search-qsIDvS2I.js +1 -0
  25. package/.output/public/assets/shield-check-DE_hVuHu.js +1 -0
  26. package/.output/public/assets/signing-mJD88Y4C.js +1 -0
  27. package/.output/public/assets/styles-BZIG7t42.css +2 -0
  28. package/.output/public/assets/table-RamFEclP.js +1 -0
  29. package/.output/public/assets/useCompositeListItem-ChzDqdpc.js +42 -0
  30. package/.output/public/assets/useMutation-JsGVjQMY.js +1 -0
  31. package/.output/public/assets/useOpenInteractionType-Dwfy-SpA.js +1 -0
  32. package/.output/server/__23tanstack-start-server-fn-resolver-Dftxlm2E.mjs +146 -0
  33. package/.output/server/_libs/@base-ui/react+[...].mjs +16124 -0
  34. package/.output/server/_libs/@reduxjs/toolkit+[...].mjs +1554 -0
  35. package/.output/server/_libs/@tanstack/react-router+[...].mjs +41 -10
  36. package/.output/server/_libs/@tanstack/react-router-ssr-query+[...].mjs +132 -0
  37. package/.output/server/_libs/d3-array.mjs +231 -0
  38. package/.output/server/_libs/d3-color.mjs +330 -0
  39. package/.output/server/_libs/d3-format.mjs +252 -0
  40. package/.output/server/_libs/d3-interpolate.mjs +207 -0
  41. package/.output/server/_libs/d3-path.mjs +77 -0
  42. package/.output/server/_libs/d3-scale+[...].mjs +1907 -0
  43. package/.output/server/_libs/d3-shape.mjs +818 -0
  44. package/.output/server/_libs/decimal.js-light.mjs +884 -0
  45. package/.output/server/_libs/es-toolkit.mjs +1134 -0
  46. package/.output/server/_libs/eventemitter3.mjs +236 -0
  47. package/.output/server/_libs/immer.mjs +532 -0
  48. package/.output/server/_libs/lucide-react.mjs +141 -13
  49. package/.output/server/_libs/next-themes.mjs +2 -2
  50. package/.output/server/_libs/react-redux+[...].mjs +205 -0
  51. package/.output/server/_libs/recharts+[...].mjs +14117 -0
  52. package/.output/server/_libs/sonner.mjs +2 -2
  53. package/.output/server/_libs/tanstack__query-core.mjs +114 -1
  54. package/.output/server/_libs/tanstack__react-query.mjs +3 -4
  55. package/.output/server/_runtime.mjs +10 -1
  56. package/.output/server/_ssr/BundleActivityChart-CWcdPuUn.mjs +288 -0
  57. package/.output/server/_ssr/BundleIdDisplay-BEvB3MvA.mjs +13 -0
  58. package/.output/server/_ssr/InsightsCapabilityContext-Cx8fjm2s.mjs +15 -0
  59. package/.output/server/_ssr/api-keys-CpBqHpuC.mjs +300 -0
  60. package/.output/server/_ssr/api-keys-api-Czkp57UV.mjs +60 -0
  61. package/.output/server/_ssr/api-keys-rpc-BTtMDSoR.mjs +136 -0
  62. package/.output/server/_ssr/api-rpc-BEX8ISai.mjs +1468 -0
  63. package/.output/server/_ssr/auth-BF8mbAgF.mjs +21 -0
  64. package/.output/server/_ssr/auth-rpc-BFMEC-TT.mjs +24 -0
  65. package/.output/server/_ssr/auth.server-DW71WzsD.mjs +47 -0
  66. package/.output/server/_ssr/badge-CpWXQwyF.mjs +26 -0
  67. package/.output/server/_ssr/bundle-signing-rpc-BbCFUQSu.mjs +16 -0
  68. package/.output/server/_ssr/bundle-signing.server-C4NW5mWx.mjs +12 -0
  69. package/.output/server/_ssr/card-Bsc8mRis.mjs +86 -0
  70. package/.output/server/_ssr/config-Dv8qLDZ0.mjs +13 -0
  71. package/.output/server/_ssr/config.server-DQYEr_5X.mjs +361 -0
  72. package/.output/server/_ssr/{createServerFn-DzU0k62V.mjs → createServerFn-B2hcXoPM.mjs} +1 -1
  73. package/.output/server/_ssr/createServerRpc-DB29C_5p.mjs +12 -0
  74. package/.output/server/_ssr/{sidebar-Cv_H0_Jv.mjs → createSsrRpc-DhfrxEjg.mjs} +68 -50
  75. package/.output/server/_ssr/databaseRows-QlCYLi0H.mjs +166 -0
  76. package/.output/server/_ssr/deleteBundle-Cu_XOMt0.mjs +66 -0
  77. package/.output/server/_ssr/dialog-C0vKUp8R.mjs +170 -0
  78. package/.output/server/_ssr/dist-BVSLTpoP.mjs +250 -0
  79. package/.output/server/_ssr/downloadBundle-CNnYxYO2.mjs +24 -0
  80. package/.output/server/_ssr/{empty-plugin-adapters-B4HCzgmM.mjs → empty-plugin-adapters-B5QvGpEl.mjs} +1 -1
  81. package/.output/server/_ssr/field-DASCh-5d.mjs +74 -0
  82. package/.output/server/_ssr/{getBundleChildren-CVtSiH5t.mjs → getBundleChildren-BcRMFoDF.mjs} +10 -18
  83. package/.output/server/_ssr/input-group-etIsBUqv.mjs +288 -0
  84. package/.output/server/_ssr/insights-api-C1F7UreR.mjs +71 -0
  85. package/.output/server/_ssr/insights-input-9fEJF-ZG.mjs +96 -0
  86. package/.output/server/_ssr/insights-rpc-C-8R6kED.mjs +155 -0
  87. package/.output/server/_ssr/insights-ygT_aIfo.mjs +858 -0
  88. package/.output/server/_ssr/installations-DqRT1QTd.mjs +535 -0
  89. package/.output/server/_ssr/installations-K8TCYTYh.mjs +19 -0
  90. package/.output/server/_ssr/router-BxBEvtF1.mjs +513 -0
  91. package/.output/server/_ssr/routes-BC7rn-tf.mjs +37 -0
  92. package/.output/server/_ssr/routes-CM5KAwpB.mjs +2285 -0
  93. package/.output/server/_ssr/runtime.server-la7TRAH_.mjs +527 -0
  94. package/.output/server/_ssr/server-CpzW--lT.mjs +7468 -0
  95. package/.output/server/_ssr/signing-jk4HANnl.mjs +134 -0
  96. package/.output/server/_ssr/ssr.mjs +4 -5740
  97. package/.output/server/_ssr/start-DpViQGnt.mjs +4 -0
  98. package/.output/server/_ssr/table-CU58HeI7.mjs +53 -0
  99. package/.output/server/_ssr/uuidv7-CaKuKXrV.mjs +31 -0
  100. package/.output/server/_tanstack-start-manifest_v-Mz9MmSlD.mjs +103 -0
  101. package/.output/server/index.mjs +229 -47
  102. package/README.md +29 -8
  103. package/lib/index.d.mts +35 -0
  104. package/lib/index.mjs +4 -0
  105. package/lib/vite-internal.mjs +127 -0
  106. package/lib/vite.d.mts +10 -0
  107. package/lib/vite.mjs +5 -0
  108. package/package.json +51 -29
  109. package/public/apple-touch-icon.png +0 -0
  110. package/public/favicon-16x16.png +0 -0
  111. package/public/favicon-32x32.png +0 -0
  112. package/public/favicon.ico +0 -0
  113. package/public/logo.svg +1 -0
  114. package/public/manifest.json +30 -0
  115. package/public/robots.txt +3 -0
  116. package/src/components/AppSidebar.tsx +159 -0
  117. package/src/components/BundleIdDisplay.tsx +18 -0
  118. package/src/components/ChannelBadge.tsx +31 -0
  119. package/src/components/ConsoleAccessPage.tsx +122 -0
  120. package/src/components/EnabledStatusIcon.tsx +54 -0
  121. package/src/components/HashValueDisplay.tsx +85 -0
  122. package/src/components/HotUpdaterLogo.tsx +30 -0
  123. package/src/components/NotFoundPage.tsx +33 -0
  124. package/src/components/PlatformIcon.tsx +39 -0
  125. package/src/components/RolloutPercentageBadge.tsx +28 -0
  126. package/src/components/ThemeProvider.tsx +116 -0
  127. package/src/components/TimestampDisplay.tsx +41 -0
  128. package/src/components/features/api-keys/ApiKeysPage.tsx +377 -0
  129. package/src/components/features/bundles/BundleActivityChart.tsx +193 -0
  130. package/src/components/features/bundles/BundleChildrenPanel.tsx +201 -0
  131. package/src/components/features/bundles/BundleInsightsSummary.tsx +123 -0
  132. package/src/components/features/bundles/BundleMetadata.tsx +136 -0
  133. package/src/components/features/bundles/RolloutCohortsDialog.tsx +201 -0
  134. package/src/components/features/channels/ChannelManagementDialog.tsx +228 -0
  135. package/src/components/features/insights/ActivityChart.tsx +150 -0
  136. package/src/components/features/insights/BundleDistribution.tsx +133 -0
  137. package/src/components/features/insights/BundleSelector.tsx +114 -0
  138. package/src/components/features/insights/InsightsCapabilityContext.tsx +24 -0
  139. package/src/components/features/insights/InsightsControls.tsx +115 -0
  140. package/src/components/features/insights/InsightsErrorAlert.tsx +21 -0
  141. package/src/components/features/insights/InsightsOverview.tsx +208 -0
  142. package/src/components/features/insights/InstallationHistoryCard.tsx +248 -0
  143. package/src/components/features/insights/InstallationMatchesCard.tsx +132 -0
  144. package/src/components/features/insights/InstallationPageHeader.tsx +138 -0
  145. package/src/components/features/insights/InstallationPagination.tsx +48 -0
  146. package/src/components/features/insights/InstallationSearch.tsx +230 -0
  147. package/src/components/features/insights/UpdateOutcomes.tsx +147 -0
  148. package/src/components/features/releases/ReleaseEditorSheet.tsx +879 -0
  149. package/src/components/features/releases/ReleaseStateBadge.tsx +20 -0
  150. package/src/components/features/signing/BundleSigningPage.tsx +139 -0
  151. package/src/components/ui/alert-dialog.tsx +185 -0
  152. package/src/components/ui/alert.tsx +76 -0
  153. package/src/components/ui/badge.tsx +49 -0
  154. package/src/components/ui/button.tsx +58 -0
  155. package/src/components/ui/card.tsx +89 -0
  156. package/src/components/ui/chart.tsx +371 -0
  157. package/src/components/ui/combobox.tsx +303 -0
  158. package/src/components/ui/dialog.tsx +156 -0
  159. package/src/components/ui/dropdown-menu.tsx +270 -0
  160. package/src/components/ui/field.tsx +235 -0
  161. package/src/components/ui/input-group.tsx +147 -0
  162. package/src/components/ui/input.tsx +19 -0
  163. package/src/components/ui/label.tsx +25 -0
  164. package/src/components/ui/progress.tsx +84 -0
  165. package/src/components/ui/select.tsx +205 -0
  166. package/src/components/ui/separator.tsx +23 -0
  167. package/src/components/ui/sheet.tsx +132 -0
  168. package/src/components/ui/sidebar.tsx +779 -0
  169. package/src/components/ui/skeleton.tsx +13 -0
  170. package/src/components/ui/slider.tsx +56 -0
  171. package/src/components/ui/sonner.tsx +45 -0
  172. package/src/components/ui/switch.tsx +25 -0
  173. package/src/components/ui/table.tsx +114 -0
  174. package/src/components/ui/textarea.tsx +18 -0
  175. package/src/components/ui/toggle-group.tsx +89 -0
  176. package/src/components/ui/toggle.tsx +43 -0
  177. package/src/components/ui/tooltip.tsx +66 -0
  178. package/src/hooks/use-mobile.ts +30 -0
  179. package/src/index.ts +47 -0
  180. package/src/lib/api-keys-api.ts +69 -0
  181. package/src/lib/api-keys-rpc.ts +87 -0
  182. package/src/lib/api-rpc.ts +478 -0
  183. package/src/lib/api.ts +444 -0
  184. package/src/lib/auth-rpc.ts +16 -0
  185. package/src/lib/bundle-signing-api.ts +14 -0
  186. package/src/lib/bundle-signing-rpc.ts +16 -0
  187. package/src/lib/constants.ts +1 -0
  188. package/src/lib/git.ts +51 -0
  189. package/src/lib/insights-api.ts +144 -0
  190. package/src/lib/insights-error.ts +19 -0
  191. package/src/lib/insights-input.ts +187 -0
  192. package/src/lib/insights-overview.ts +170 -0
  193. package/src/lib/insights-rpc.ts +218 -0
  194. package/src/lib/server/auth.server.ts +43 -0
  195. package/src/lib/server/bundle-signing.server.ts +23 -0
  196. package/src/lib/server/config.server.ts +109 -0
  197. package/src/lib/server/console-runtime.server.ts +61 -0
  198. package/src/lib/server/deleteBundle.ts +145 -0
  199. package/src/lib/server/downloadBundle.ts +46 -0
  200. package/src/lib/server/getBundleChildren.ts +130 -0
  201. package/src/lib/server/listReleases.ts +61 -0
  202. package/src/lib/server/releaseActivity.ts +27 -0
  203. package/src/lib/server/releaseReachability.ts +95 -0
  204. package/src/lib/server/runtime.server.ts +172 -0
  205. package/src/lib/utils.ts +9 -0
  206. package/src/logo.svg +1 -0
  207. package/src/routeTree.gen.ts +199 -0
  208. package/src/router.tsx +21 -0
  209. package/src/routes/-installations-search.ts +19 -0
  210. package/src/routes/-releases-search.ts +74 -0
  211. package/src/routes/__root.tsx +174 -0
  212. package/src/routes/api/auth/$.ts +19 -0
  213. package/src/routes/api/bundles/$bundleId/download.ts +17 -0
  214. package/src/routes/api-keys.tsx +37 -0
  215. package/src/routes/index.tsx +982 -0
  216. package/src/routes/insights.tsx +139 -0
  217. package/src/routes/installations.tsx +194 -0
  218. package/src/routes/signing.tsx +37 -0
  219. package/src/styles.css +152 -0
  220. package/src/virtual-modules.d.ts +21 -0
  221. package/src/vite-env.d.ts +1 -0
  222. package/src/vite-internal.ts +195 -0
  223. package/src/vite.ts +12 -0
  224. package/.output/public/assets/dist-DJX53faP.js +0 -3
  225. package/.output/public/assets/index-Iylis5kY.js +0 -10
  226. package/.output/public/assets/routes-HT21hs0C.js +0 -54
  227. package/.output/public/assets/styles-C0Re4quB.css +0 -2
  228. package/.output/server/__23tanstack-start-server-fn-resolver-CgwgZ0-i.mjs +0 -66
  229. package/.output/server/_libs/@floating-ui/core+[...].mjs +0 -698
  230. package/.output/server/_libs/@floating-ui/dom+[...].mjs +0 -644
  231. package/.output/server/_libs/@floating-ui/react-dom+[...].mjs +0 -839
  232. package/.output/server/_libs/@radix-ui/react-alert-dialog+[...].mjs +0 -2138
  233. package/.output/server/_libs/@radix-ui/react-popper+[...].mjs +0 -308
  234. package/.output/server/_libs/@radix-ui/react-select+[...].mjs +0 -1038
  235. package/.output/server/_libs/@tanstack/devtools-event-client+[...].mjs +0 -196
  236. package/.output/server/_libs/@tanstack/form-core+[...].mjs +0 -3228
  237. package/.output/server/_libs/@tanstack/react-form+[...].mjs +0 -430
  238. package/.output/server/_libs/@tanstack/react-table+[...].mjs +0 -2382
  239. package/.output/server/_libs/radix-ui__number.mjs +0 -6
  240. package/.output/server/_libs/radix-ui__primitive.mjs +0 -9
  241. package/.output/server/_libs/radix-ui__react-arrow.mjs +0 -23
  242. package/.output/server/_libs/radix-ui__react-collection.mjs +0 -78
  243. package/.output/server/_libs/radix-ui__react-direction.mjs +0 -13
  244. package/.output/server/_libs/radix-ui__react-label.mjs +0 -22
  245. package/.output/server/_libs/radix-ui__react-separator.mjs +0 -30
  246. package/.output/server/_libs/radix-ui__react-slider.mjs +0 -510
  247. package/.output/server/_libs/radix-ui__react-switch.mjs +0 -157
  248. package/.output/server/_libs/radix-ui__react-tooltip.mjs +0 -493
  249. package/.output/server/_ssr/api-rpc-BIbDUKSz.mjs +0 -292
  250. package/.output/server/_ssr/config.server-BSS366KT.mjs +0 -41
  251. package/.output/server/_ssr/deleteBundle-BgbZTtpW.mjs +0 -141
  252. package/.output/server/_ssr/dist-KboydRVk.mjs +0 -120
  253. package/.output/server/_ssr/router-C3hqEy3k.mjs +0 -307
  254. package/.output/server/_ssr/routes-B0lQvvlC.mjs +0 -3048
  255. package/.output/server/_ssr/start-02sLteYG.mjs +0 -4
  256. package/.output/server/_ssr/storageProfile-FVkjPoGb.mjs +0 -9
  257. package/.output/server/_tanstack-start-manifest_v-Bpx52WOU.mjs +0 -20
  258. package/.output/server/node_modules/tslib/modules/index.js +0 -70
  259. package/.output/server/node_modules/tslib/modules/package.json +0 -3
  260. package/.output/server/node_modules/tslib/package.json +0 -47
  261. package/.output/server/node_modules/tslib/tslib.js +0 -484
  262. package/.output/server/package.json +0 -9
@@ -1,3228 +0,0 @@
1
- import { t as EventClient } from "./devtools-event-client+[...].mjs";
2
- //#region ../../node_modules/.pnpm/@tanstack+store@0.11.0/node_modules/@tanstack/store/dist/alien.js
3
- var ReactiveFlags = /* @__PURE__ */ function(ReactiveFlags) {
4
- ReactiveFlags[ReactiveFlags["None"] = 0] = "None";
5
- ReactiveFlags[ReactiveFlags["Mutable"] = 1] = "Mutable";
6
- ReactiveFlags[ReactiveFlags["Watching"] = 2] = "Watching";
7
- ReactiveFlags[ReactiveFlags["RecursedCheck"] = 4] = "RecursedCheck";
8
- ReactiveFlags[ReactiveFlags["Recursed"] = 8] = "Recursed";
9
- ReactiveFlags[ReactiveFlags["Dirty"] = 16] = "Dirty";
10
- ReactiveFlags[ReactiveFlags["Pending"] = 32] = "Pending";
11
- return ReactiveFlags;
12
- }({});
13
- /* @__NO_SIDE_EFFECTS__ */
14
- function createReactiveSystem({ update, notify, unwatched }) {
15
- return {
16
- link,
17
- unlink,
18
- propagate,
19
- checkDirty,
20
- shallowPropagate
21
- };
22
- function link(dep, sub, version) {
23
- const prevDep = sub.depsTail;
24
- if (prevDep !== void 0 && prevDep.dep === dep) return;
25
- const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
26
- if (nextDep !== void 0 && nextDep.dep === dep) {
27
- nextDep.version = version;
28
- sub.depsTail = nextDep;
29
- return;
30
- }
31
- const prevSub = dep.subsTail;
32
- if (prevSub !== void 0 && prevSub.version === version && prevSub.sub === sub) return;
33
- const newLink = sub.depsTail = dep.subsTail = {
34
- version,
35
- dep,
36
- sub,
37
- prevDep,
38
- nextDep,
39
- prevSub,
40
- nextSub: void 0
41
- };
42
- if (nextDep !== void 0) nextDep.prevDep = newLink;
43
- if (prevDep !== void 0) prevDep.nextDep = newLink;
44
- else sub.deps = newLink;
45
- if (prevSub !== void 0) prevSub.nextSub = newLink;
46
- else dep.subs = newLink;
47
- }
48
- function unlink(link, sub = link.sub) {
49
- const dep = link.dep;
50
- const prevDep = link.prevDep;
51
- const nextDep = link.nextDep;
52
- const nextSub = link.nextSub;
53
- const prevSub = link.prevSub;
54
- if (nextDep !== void 0) nextDep.prevDep = prevDep;
55
- else sub.depsTail = prevDep;
56
- if (prevDep !== void 0) prevDep.nextDep = nextDep;
57
- else sub.deps = nextDep;
58
- if (nextSub !== void 0) nextSub.prevSub = prevSub;
59
- else dep.subsTail = prevSub;
60
- if (prevSub !== void 0) prevSub.nextSub = nextSub;
61
- else if ((dep.subs = nextSub) === void 0) unwatched(dep);
62
- return nextDep;
63
- }
64
- function propagate(link) {
65
- let next = link.nextSub;
66
- let stack;
67
- top: do {
68
- const sub = link.sub;
69
- let flags = sub.flags;
70
- if (!(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed | ReactiveFlags.Dirty | ReactiveFlags.Pending))) sub.flags = flags | ReactiveFlags.Pending;
71
- else if (!(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed))) flags = ReactiveFlags.None;
72
- else if (!(flags & ReactiveFlags.RecursedCheck)) sub.flags = flags & ~ReactiveFlags.Recursed | ReactiveFlags.Pending;
73
- else if (!(flags & (ReactiveFlags.Dirty | ReactiveFlags.Pending)) && isValidLink(link, sub)) {
74
- sub.flags = flags | (ReactiveFlags.Recursed | ReactiveFlags.Pending);
75
- flags &= ReactiveFlags.Mutable;
76
- } else flags = ReactiveFlags.None;
77
- if (flags & ReactiveFlags.Watching) notify(sub);
78
- if (flags & ReactiveFlags.Mutable) {
79
- const subSubs = sub.subs;
80
- if (subSubs !== void 0) {
81
- const nextSub = (link = subSubs).nextSub;
82
- if (nextSub !== void 0) {
83
- stack = {
84
- value: next,
85
- prev: stack
86
- };
87
- next = nextSub;
88
- }
89
- continue;
90
- }
91
- }
92
- if ((link = next) !== void 0) {
93
- next = link.nextSub;
94
- continue;
95
- }
96
- while (stack !== void 0) {
97
- link = stack.value;
98
- stack = stack.prev;
99
- if (link !== void 0) {
100
- next = link.nextSub;
101
- continue top;
102
- }
103
- }
104
- break;
105
- } while (true);
106
- }
107
- function checkDirty(link, sub) {
108
- let stack;
109
- let checkDepth = 0;
110
- let dirty = false;
111
- top: do {
112
- const dep = link.dep;
113
- const flags = dep.flags;
114
- if (sub.flags & ReactiveFlags.Dirty) dirty = true;
115
- else if ((flags & (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) === (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) {
116
- if (update(dep)) {
117
- const subs = dep.subs;
118
- if (subs.nextSub !== void 0) shallowPropagate(subs);
119
- dirty = true;
120
- }
121
- } else if ((flags & (ReactiveFlags.Mutable | ReactiveFlags.Pending)) === (ReactiveFlags.Mutable | ReactiveFlags.Pending)) {
122
- if (link.nextSub !== void 0 || link.prevSub !== void 0) stack = {
123
- value: link,
124
- prev: stack
125
- };
126
- link = dep.deps;
127
- sub = dep;
128
- ++checkDepth;
129
- continue;
130
- }
131
- if (!dirty) {
132
- const nextDep = link.nextDep;
133
- if (nextDep !== void 0) {
134
- link = nextDep;
135
- continue;
136
- }
137
- }
138
- while (checkDepth--) {
139
- const firstSub = sub.subs;
140
- const hasMultipleSubs = firstSub.nextSub !== void 0;
141
- if (hasMultipleSubs) {
142
- link = stack.value;
143
- stack = stack.prev;
144
- } else link = firstSub;
145
- if (dirty) {
146
- if (update(sub)) {
147
- if (hasMultipleSubs) shallowPropagate(firstSub);
148
- sub = link.sub;
149
- continue;
150
- }
151
- dirty = false;
152
- } else sub.flags &= ~ReactiveFlags.Pending;
153
- sub = link.sub;
154
- const nextDep = link.nextDep;
155
- if (nextDep !== void 0) {
156
- link = nextDep;
157
- continue top;
158
- }
159
- }
160
- return dirty;
161
- } while (true);
162
- }
163
- function shallowPropagate(link) {
164
- do {
165
- const sub = link.sub;
166
- const flags = sub.flags;
167
- if ((flags & (ReactiveFlags.Pending | ReactiveFlags.Dirty)) === ReactiveFlags.Pending) {
168
- sub.flags = flags | ReactiveFlags.Dirty;
169
- if ((flags & (ReactiveFlags.Watching | ReactiveFlags.RecursedCheck)) === ReactiveFlags.Watching) notify(sub);
170
- }
171
- } while ((link = link.nextSub) !== void 0);
172
- }
173
- function isValidLink(checkLink, sub) {
174
- let link = sub.depsTail;
175
- while (link !== void 0) {
176
- if (link === checkLink) return true;
177
- link = link.prevDep;
178
- }
179
- return false;
180
- }
181
- }
182
- //#endregion
183
- //#region ../../node_modules/.pnpm/@tanstack+store@0.11.0/node_modules/@tanstack/store/dist/atom.js
184
- function toObserver(nextHandler, errorHandler, completionHandler) {
185
- const isObserver = typeof nextHandler === "object";
186
- const self = isObserver ? nextHandler : void 0;
187
- return {
188
- next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
189
- error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
190
- complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
191
- };
192
- }
193
- var queuedEffects = [];
194
- var cycle = 0;
195
- var { link, unlink, propagate, checkDirty, shallowPropagate } = /* @__PURE__ */ createReactiveSystem({
196
- update(atom) {
197
- return atom._update();
198
- },
199
- notify(effect) {
200
- queuedEffects[queuedEffectsLength++] = effect;
201
- effect.flags &= ~ReactiveFlags.Watching;
202
- },
203
- unwatched(atom) {
204
- if (atom.depsTail !== void 0) {
205
- atom.depsTail = void 0;
206
- atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
207
- purgeDeps(atom);
208
- }
209
- }
210
- });
211
- var notifyIndex = 0;
212
- var queuedEffectsLength = 0;
213
- var activeSub;
214
- var batchDepth = 0;
215
- function batch(fn) {
216
- try {
217
- ++batchDepth;
218
- fn();
219
- } finally {
220
- if (!--batchDepth) flush();
221
- }
222
- }
223
- function purgeDeps(sub) {
224
- const depsTail = sub.depsTail;
225
- let dep = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
226
- while (dep !== void 0) dep = unlink(dep, sub);
227
- }
228
- function flush() {
229
- if (batchDepth > 0) return;
230
- while (notifyIndex < queuedEffectsLength) {
231
- const effect = queuedEffects[notifyIndex];
232
- queuedEffects[notifyIndex++] = void 0;
233
- effect.notify();
234
- }
235
- notifyIndex = 0;
236
- queuedEffectsLength = 0;
237
- }
238
- function createAtom(valueOrFn, options) {
239
- const isComputed = typeof valueOrFn === "function";
240
- const getter = valueOrFn;
241
- const atom = {
242
- _snapshot: isComputed ? void 0 : valueOrFn,
243
- subs: void 0,
244
- subsTail: void 0,
245
- deps: void 0,
246
- depsTail: void 0,
247
- flags: isComputed ? ReactiveFlags.None : ReactiveFlags.Mutable,
248
- get() {
249
- if (activeSub !== void 0) link(atom, activeSub, cycle);
250
- return atom._snapshot;
251
- },
252
- subscribe(observerOrFn) {
253
- const obs = toObserver(observerOrFn);
254
- const observed = { current: false };
255
- const e = effect(() => {
256
- atom.get();
257
- if (!observed.current) observed.current = true;
258
- else obs.next?.(atom._snapshot);
259
- });
260
- return { unsubscribe: () => {
261
- e.stop();
262
- } };
263
- },
264
- _update(getValue) {
265
- const prevSub = activeSub;
266
- const compare = options?.compare ?? Object.is;
267
- if (isComputed) {
268
- activeSub = atom;
269
- ++cycle;
270
- atom.depsTail = void 0;
271
- } else if (getValue === void 0) return false;
272
- if (isComputed) atom.flags = ReactiveFlags.Mutable | ReactiveFlags.RecursedCheck;
273
- try {
274
- const oldValue = atom._snapshot;
275
- const newValue = typeof getValue === "function" ? getValue(oldValue) : getValue === void 0 && isComputed ? getter(oldValue) : getValue;
276
- if (oldValue === void 0 || !compare(oldValue, newValue)) {
277
- atom._snapshot = newValue;
278
- return true;
279
- }
280
- return false;
281
- } finally {
282
- activeSub = prevSub;
283
- if (isComputed) atom.flags &= ~ReactiveFlags.RecursedCheck;
284
- purgeDeps(atom);
285
- }
286
- }
287
- };
288
- if (isComputed) {
289
- atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty;
290
- atom.get = function() {
291
- const flags = atom.flags;
292
- if (flags & ReactiveFlags.Dirty || flags & ReactiveFlags.Pending && checkDirty(atom.deps, atom)) {
293
- if (atom._update()) {
294
- const subs = atom.subs;
295
- if (subs !== void 0) shallowPropagate(subs);
296
- }
297
- } else if (flags & ReactiveFlags.Pending) atom.flags = flags & ~ReactiveFlags.Pending;
298
- if (activeSub !== void 0) link(atom, activeSub, cycle);
299
- return atom._snapshot;
300
- };
301
- } else atom.set = function(valueOrFn) {
302
- if (atom._update(valueOrFn)) {
303
- const subs = atom.subs;
304
- if (subs !== void 0) {
305
- propagate(subs);
306
- shallowPropagate(subs);
307
- flush();
308
- }
309
- }
310
- };
311
- return atom;
312
- }
313
- function effect(fn) {
314
- const run = () => {
315
- const prevSub = activeSub;
316
- activeSub = effectObj;
317
- ++cycle;
318
- effectObj.depsTail = void 0;
319
- effectObj.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck;
320
- try {
321
- return fn();
322
- } finally {
323
- activeSub = prevSub;
324
- effectObj.flags &= ~ReactiveFlags.RecursedCheck;
325
- purgeDeps(effectObj);
326
- }
327
- };
328
- const effectObj = {
329
- deps: void 0,
330
- depsTail: void 0,
331
- subs: void 0,
332
- subsTail: void 0,
333
- flags: ReactiveFlags.Watching | ReactiveFlags.RecursedCheck,
334
- notify() {
335
- const flags = this.flags;
336
- if (flags & ReactiveFlags.Dirty || flags & ReactiveFlags.Pending && checkDirty(this.deps, this)) run();
337
- else this.flags = ReactiveFlags.Watching;
338
- },
339
- stop() {
340
- this.flags = ReactiveFlags.None;
341
- this.depsTail = void 0;
342
- purgeDeps(this);
343
- }
344
- };
345
- run();
346
- return effectObj;
347
- }
348
- //#endregion
349
- //#region ../../node_modules/.pnpm/@tanstack+store@0.11.0/node_modules/@tanstack/store/dist/store.js
350
- var Store = class {
351
- constructor(valueOrFn, actionsFactory) {
352
- this.atom = createAtom(valueOrFn);
353
- this.get = this.get.bind(this);
354
- this.setState = this.setState.bind(this);
355
- this.subscribe = this.subscribe.bind(this);
356
- if (actionsFactory) this.actions = actionsFactory(this);
357
- }
358
- setState(updater) {
359
- this.atom.set(updater);
360
- }
361
- get state() {
362
- return this.atom.get();
363
- }
364
- get() {
365
- return this.state;
366
- }
367
- subscribe(observerOrFn) {
368
- return this.atom.subscribe(toObserver(observerOrFn));
369
- }
370
- };
371
- var ReadonlyStore = class {
372
- constructor(valueOrFn) {
373
- this.atom = createAtom(valueOrFn);
374
- }
375
- get state() {
376
- return this.atom.get();
377
- }
378
- get() {
379
- return this.state;
380
- }
381
- subscribe(observerOrFn) {
382
- return this.atom.subscribe(toObserver(observerOrFn));
383
- }
384
- };
385
- function createStore(valueOrFn, actions) {
386
- if (typeof valueOrFn === "function") return new ReadonlyStore(valueOrFn);
387
- if (actions) return new Store(valueOrFn, actions);
388
- return new Store(valueOrFn);
389
- }
390
- //#endregion
391
- //#region ../../node_modules/.pnpm/@tanstack+pacer-lite@0.1.1/node_modules/@tanstack/pacer-lite/dist/lite-throttler.js
392
- /**
393
- * A lightweight class that creates a throttled function.
394
- *
395
- * This is an alternative to the Throttler in the core @tanstack/pacer package, but is more
396
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core Throttler,
397
- * this version does not use TanStack Store for state management, has no devtools integration,
398
- * and provides only essential throttling functionality.
399
- *
400
- * Throttling ensures a function is called at most once within a specified time window.
401
- * Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
402
- * execution timing regardless of call frequency.
403
- *
404
- * Supports both leading and trailing edge execution:
405
- * - Leading: Execute immediately on first call (default: true)
406
- * - Trailing: Execute after wait period if called during throttle (default: true)
407
- *
408
- * Features:
409
- * - Zero dependencies - no external libraries required
410
- * - Minimal API surface - only essential methods (maybeExecute, flush, cancel)
411
- * - Simple state management - uses basic private properties instead of reactive stores
412
- * - Callback support for monitoring execution events
413
- * - Lightweight - designed for use in npm packages where bundle size matters
414
- *
415
- * @example
416
- * ```ts
417
- * const throttler = new LiteThrottler((scrollY: number) => {
418
- * updateScrollPosition(scrollY);
419
- * }, {
420
- * wait: 100,
421
- * onExecute: (args, throttler) => {
422
- * console.log('Updated scroll position:', args[0]);
423
- * }
424
- * });
425
- *
426
- * // Will execute at most once per 100ms
427
- * window.addEventListener('scroll', () => {
428
- * throttler.maybeExecute(window.scrollY);
429
- * });
430
- * ```
431
- */
432
- var LiteThrottler = class {
433
- constructor(fn, options) {
434
- this.fn = fn;
435
- this.options = options;
436
- this.lastExecutionTime = 0;
437
- this.isPending = false;
438
- this.maybeExecute = (...args) => {
439
- const timeSinceLastExecution = Date.now() - this.lastExecutionTime;
440
- if (this.options.leading && timeSinceLastExecution >= this.options.wait) this.execute(...args);
441
- else {
442
- this.lastArgs = args;
443
- if (!this.timeoutId && this.options.trailing) {
444
- const timeoutDuration = this.options.wait - timeSinceLastExecution;
445
- this.isPending = true;
446
- this.timeoutId = setTimeout(() => {
447
- if (this.lastArgs !== void 0) this.execute(...this.lastArgs);
448
- }, timeoutDuration);
449
- }
450
- }
451
- };
452
- this.execute = (...args) => {
453
- this.fn(...args);
454
- this.options.onExecute?.(args, this);
455
- this.lastExecutionTime = Date.now();
456
- this.clearTimeout();
457
- this.lastArgs = void 0;
458
- this.isPending = false;
459
- };
460
- this.flush = () => {
461
- if (this.isPending && this.lastArgs) this.execute(...this.lastArgs);
462
- };
463
- this.cancel = () => {
464
- this.clearTimeout();
465
- this.lastArgs = void 0;
466
- this.isPending = false;
467
- };
468
- this.clearTimeout = () => {
469
- if (this.timeoutId) {
470
- clearTimeout(this.timeoutId);
471
- this.timeoutId = void 0;
472
- }
473
- };
474
- if (this.options.leading === void 0 && this.options.trailing === void 0) {
475
- this.options.leading = true;
476
- this.options.trailing = true;
477
- }
478
- }
479
- };
480
- /**
481
- * Creates a lightweight throttled function that limits how often the provided function can execute.
482
- *
483
- * This is an alternative to the throttle function in the core @tanstack/pacer package, but is more
484
- * suitable for libraries and npm packages that need minimal overhead. Unlike the core version,
485
- * this function creates a throttler with no external dependencies, devtools integration, or reactive state.
486
- *
487
- * Throttling ensures a function executes at most once within a specified time window,
488
- * regardless of how many times it is called. This is useful for rate-limiting
489
- * expensive operations or UI updates.
490
- *
491
- * @example
492
- * ```ts
493
- * const throttledScroll = liteThrottle(() => {
494
- * updateScrollIndicator();
495
- * }, { wait: 100 });
496
- *
497
- * // Will execute at most once per 100ms
498
- * window.addEventListener('scroll', throttledScroll);
499
- * ```
500
- *
501
- * @example
502
- * ```ts
503
- * // Leading edge execution - fires immediately then throttles
504
- * const throttledResize = liteThrottle(() => {
505
- * recalculateLayout();
506
- * }, { wait: 250, leading: true, trailing: false });
507
- * ```
508
- */
509
- function liteThrottle(fn, options) {
510
- return new LiteThrottler(fn, options).maybeExecute;
511
- }
512
- //#endregion
513
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/EventClient.js
514
- var FormEventClient = class extends EventClient {
515
- constructor() {
516
- super({
517
- pluginId: "form-devtools",
518
- reconnectEveryMs: 1e3
519
- });
520
- }
521
- };
522
- var formEventClient = new FormEventClient();
523
- //#endregion
524
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/utils.js
525
- function functionalUpdate(updater, input) {
526
- return typeof updater === "function" ? updater(input) : updater;
527
- }
528
- function getBy(obj, path) {
529
- return makePathArray(path).reduce((current, pathPart) => {
530
- if (current === null) return null;
531
- if (typeof current !== "undefined") return current[pathPart];
532
- }, obj);
533
- }
534
- function setBy(obj, _path, updater) {
535
- const path = makePathArray(_path);
536
- function doSet(parent) {
537
- if (!path.length) return functionalUpdate(updater, parent);
538
- const key = path.shift();
539
- if (typeof key === "string" || typeof key === "number" && !Array.isArray(parent)) {
540
- if (typeof parent === "object") {
541
- if (parent === null) parent = {};
542
- return {
543
- ...parent,
544
- [key]: doSet(parent[key])
545
- };
546
- }
547
- return { [key]: doSet() };
548
- }
549
- if (Array.isArray(parent) && typeof key === "number") {
550
- const prefix = parent.slice(0, key);
551
- return [
552
- ...prefix.length ? prefix : new Array(key),
553
- doSet(parent[key]),
554
- ...parent.slice(key + 1)
555
- ];
556
- }
557
- return [...new Array(key), doSet()];
558
- }
559
- return doSet(obj);
560
- }
561
- function deleteBy(obj, _path) {
562
- const path = makePathArray(_path);
563
- function doDelete(parent) {
564
- if (!parent) return;
565
- if (path.length === 1) {
566
- const finalPath = path[0];
567
- if (Array.isArray(parent) && typeof finalPath === "number") return parent.filter((_, i) => i !== finalPath);
568
- const { [finalPath]: remove, ...rest } = parent;
569
- return rest;
570
- }
571
- const key = path.shift();
572
- if (typeof key === "string" || typeof key === "number" && !Array.isArray(parent)) {
573
- if (typeof parent === "object") return {
574
- ...parent,
575
- [key]: doDelete(parent[key])
576
- };
577
- }
578
- if (typeof key === "number") {
579
- if (Array.isArray(parent)) {
580
- if (key >= parent.length) return parent;
581
- const prefix = parent.slice(0, key);
582
- return [
583
- ...prefix.length ? prefix : new Array(key),
584
- doDelete(parent[key]),
585
- ...parent.slice(key + 1)
586
- ];
587
- }
588
- }
589
- throw new Error("It seems we have created an infinite loop in deleteBy. ");
590
- }
591
- return doDelete(obj);
592
- }
593
- var CC_DOT = 46;
594
- var CC_OPEN = 91;
595
- var CC_CLOSE = 93;
596
- var CC_ZERO = 48;
597
- var CC_NINE = 57;
598
- function makePathArray(str) {
599
- if (Array.isArray(str)) return [...str];
600
- if (typeof str !== "string") throw new Error("Path must be a string.");
601
- const len = str.length;
602
- const result = [];
603
- let segStart = len > 0 && str.charCodeAt(0) === CC_OPEN ? 1 : 0;
604
- let allDigits = true;
605
- let prev = -1;
606
- for (let i = segStart; i <= len; i++) {
607
- const char = i < len ? str.charCodeAt(i) : -1;
608
- if (i === len || char === CC_DOT || char === CC_OPEN || char === CC_CLOSE) {
609
- const segLen = i - segStart;
610
- if (segLen > 0) {
611
- const treatAsNumber = allDigits && (segLen === 1 || str.charCodeAt(segStart) !== CC_ZERO);
612
- const seg = str.slice(segStart, i);
613
- if (treatAsNumber) {
614
- const num = parseInt(seg, 10);
615
- if (segLen <= 15 || String(num) === seg) result.push(num);
616
- else result.push(seg);
617
- } else result.push(seg);
618
- } else if (prev !== CC_CLOSE && !(prev === -1 && char === CC_CLOSE) && !(prev === char && (char === CC_DOT || char === CC_OPEN))) result.push("");
619
- segStart = i + 1;
620
- allDigits = true;
621
- } else if (char < CC_ZERO || char > CC_NINE) allDigits = false;
622
- prev = char;
623
- }
624
- if (!result.length) result.push("");
625
- return result;
626
- }
627
- function isNonEmptyArray(obj) {
628
- return !(Array.isArray(obj) && obj.length === 0);
629
- }
630
- function getSyncValidatorArray(cause, options) {
631
- const runValidation = (props) => {
632
- return props.validators.filter(Boolean).map((validator) => {
633
- return {
634
- cause: validator.cause,
635
- validate: validator.fn
636
- };
637
- });
638
- };
639
- return options.validationLogic({
640
- form: options.form,
641
- group: options.group,
642
- validators: options.validators,
643
- event: {
644
- type: cause,
645
- fieldName: options.fieldName,
646
- async: false
647
- },
648
- runValidation
649
- });
650
- }
651
- function getAsyncValidatorArray(cause, options) {
652
- const { asyncDebounceMs } = options;
653
- const { onBlurAsyncDebounceMs, onChangeAsyncDebounceMs, onDynamicAsyncDebounceMs } = options.validators || {};
654
- const defaultDebounceMs = asyncDebounceMs ?? 0;
655
- const runValidation = (props) => {
656
- return props.validators.filter(Boolean).map((validator) => {
657
- const validatorCause = validator?.cause || cause;
658
- let debounceMs = defaultDebounceMs;
659
- switch (validatorCause) {
660
- case "change":
661
- debounceMs = onChangeAsyncDebounceMs ?? defaultDebounceMs;
662
- break;
663
- case "blur":
664
- debounceMs = onBlurAsyncDebounceMs ?? defaultDebounceMs;
665
- break;
666
- case "dynamic":
667
- debounceMs = onDynamicAsyncDebounceMs ?? defaultDebounceMs;
668
- break;
669
- case "submit":
670
- debounceMs = 0;
671
- break;
672
- }
673
- if (cause === "submit") debounceMs = 0;
674
- return {
675
- cause: validatorCause,
676
- validate: validator.fn,
677
- debounceMs
678
- };
679
- });
680
- };
681
- return options.validationLogic({
682
- form: options.form,
683
- group: options.group,
684
- validators: options.validators,
685
- event: {
686
- type: cause,
687
- fieldName: options.fieldName,
688
- async: true
689
- },
690
- runValidation
691
- });
692
- }
693
- var isGlobalFormValidationError = (error) => {
694
- return !!error && typeof error === "object" && "fields" in error;
695
- };
696
- function evaluate(objA, objB) {
697
- if (Object.is(objA, objB)) return true;
698
- if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) return false;
699
- if (objA instanceof Date && objB instanceof Date) return objA.getTime() === objB.getTime();
700
- if (objA instanceof Map && objB instanceof Map) {
701
- if (objA.size !== objB.size) return false;
702
- for (const [k, v] of objA) if (!objB.has(k) || !Object.is(v, objB.get(k))) return false;
703
- return true;
704
- }
705
- if (objA instanceof Set && objB instanceof Set) {
706
- if (objA.size !== objB.size) return false;
707
- for (const v of objA) if (!objB.has(v)) return false;
708
- return true;
709
- }
710
- const keysA = Object.keys(objA);
711
- const keysB = Object.keys(objB);
712
- if (keysA.length !== keysB.length) return false;
713
- if (keysA.length === 0 && !Array.isArray(objA) && !Array.isArray(objB) && (Object.getPrototypeOf(objA) !== Object.prototype || Object.getPrototypeOf(objB) !== Object.prototype)) return false;
714
- for (const key of keysA) if (!keysB.includes(key) || !evaluate(objA[key], objB[key])) return false;
715
- return true;
716
- }
717
- var determineFormLevelErrorSourceAndValue = ({ newFormValidatorError, isPreviousErrorFromFormValidator, previousErrorValue }) => {
718
- if (newFormValidatorError) return {
719
- newErrorValue: newFormValidatorError,
720
- newSource: "form"
721
- };
722
- if (isPreviousErrorFromFormValidator) return {
723
- newErrorValue: void 0,
724
- newSource: void 0
725
- };
726
- if (previousErrorValue) return {
727
- newErrorValue: previousErrorValue,
728
- newSource: "field"
729
- };
730
- return {
731
- newErrorValue: void 0,
732
- newSource: void 0
733
- };
734
- };
735
- var determineFieldLevelErrorSourceAndValue = ({ formLevelError, fieldLevelError }) => {
736
- if (fieldLevelError) return {
737
- newErrorValue: fieldLevelError,
738
- newSource: "field"
739
- };
740
- if (formLevelError) return {
741
- newErrorValue: formLevelError,
742
- newSource: "form"
743
- };
744
- return {
745
- newErrorValue: void 0,
746
- newSource: void 0
747
- };
748
- };
749
- function mergeOpts(originalOpts, overrides) {
750
- if (originalOpts === void 0 || originalOpts === null) return overrides;
751
- return {
752
- ...originalOpts,
753
- ...overrides
754
- };
755
- }
756
- var IDX = 256;
757
- var HEX = [];
758
- var BUFFER;
759
- while (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1);
760
- function uuid() {
761
- let i = 0;
762
- let num;
763
- let out = "";
764
- if (!BUFFER || IDX + 16 > 256) {
765
- BUFFER = new Array(256);
766
- i = 256;
767
- while (i--) BUFFER[i] = 256 * Math.random() | 0;
768
- i = 0;
769
- IDX = 0;
770
- }
771
- for (; i < 16; i++) {
772
- num = BUFFER[IDX + i];
773
- if (i === 6) out += HEX[num & 15 | 64];
774
- else if (i === 8) out += HEX[num & 63 | 128];
775
- else out += HEX[num];
776
- if (i & 1 && i > 1 && i < 11) out += "-";
777
- }
778
- IDX++;
779
- return out;
780
- }
781
- var throttleFormState = liteThrottle((form) => formEventClient.emit("form-state", {
782
- id: form.formId,
783
- state: form.store.state
784
- }), { wait: 300 });
785
- function deepCopy(obj) {
786
- if (obj === null || typeof obj !== "object") return obj;
787
- if (obj instanceof Date) return new Date(obj.getTime());
788
- if (Array.isArray(obj)) {
789
- const arrCopy = [];
790
- for (let i = 0; i < obj.length; i++) arrCopy[i] = deepCopy(obj[i]);
791
- return arrCopy;
792
- }
793
- if (obj instanceof Map) {
794
- const mapCopy = /* @__PURE__ */ new Map();
795
- obj.forEach((value, key) => {
796
- mapCopy.set(key, deepCopy(value));
797
- });
798
- return mapCopy;
799
- }
800
- if (obj instanceof Set) {
801
- const setCopy = /* @__PURE__ */ new Set();
802
- obj.forEach((value) => {
803
- setCopy.add(deepCopy(value));
804
- });
805
- return setCopy;
806
- }
807
- const copy = {};
808
- for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) copy[key] = deepCopy(obj[key]);
809
- return copy;
810
- }
811
- function isFieldInGroup(groupName, fieldName) {
812
- return fieldName === groupName || fieldName.startsWith(`${groupName}.`) || fieldName.startsWith(`${groupName}[`);
813
- }
814
- //#endregion
815
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/ValidationLogic.js
816
- var defaultValidationLogic = (props) => {
817
- if (!props.validators) return props.runValidation({
818
- validators: [],
819
- form: props.form
820
- });
821
- const isAsync = props.event.async;
822
- const onMountValidator = isAsync ? void 0 : {
823
- fn: props.validators.onMount,
824
- cause: "mount"
825
- };
826
- const onChangeValidator = {
827
- fn: isAsync ? props.validators.onChangeAsync : props.validators.onChange,
828
- cause: "change"
829
- };
830
- const onBlurValidator = {
831
- fn: isAsync ? props.validators.onBlurAsync : props.validators.onBlur,
832
- cause: "blur"
833
- };
834
- const onSubmitValidator = {
835
- fn: isAsync ? props.validators.onSubmitAsync : props.validators.onSubmit,
836
- cause: "submit"
837
- };
838
- const onServerValidator = isAsync ? void 0 : {
839
- fn: () => void 0,
840
- cause: "server"
841
- };
842
- switch (props.event.type) {
843
- case "mount": return props.runValidation({
844
- validators: [onMountValidator],
845
- form: props.form
846
- });
847
- case "submit": return props.runValidation({
848
- validators: [
849
- onChangeValidator,
850
- onBlurValidator,
851
- onSubmitValidator,
852
- onServerValidator
853
- ],
854
- form: props.form
855
- });
856
- case "server": return props.runValidation({
857
- validators: [],
858
- form: props.form
859
- });
860
- case "blur": return props.runValidation({
861
- validators: [onBlurValidator, onServerValidator],
862
- form: props.form
863
- });
864
- case "change": return props.runValidation({
865
- validators: [onChangeValidator, onServerValidator],
866
- form: props.form
867
- });
868
- default: throw new Error(`Unknown validation event type: ${props.event.type}`);
869
- }
870
- };
871
- //#endregion
872
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/standardSchemaValidator.js
873
- function prefixSchemaToErrors(issues, formValue) {
874
- const schema = /* @__PURE__ */ new Map();
875
- for (const issue of issues) {
876
- const issuePath = issue.path ?? [];
877
- let currentFormValue = formValue;
878
- let path = "";
879
- for (let i = 0; i < issuePath.length; i++) {
880
- const pathSegment = issuePath[i];
881
- if (pathSegment === void 0) continue;
882
- const segment = typeof pathSegment === "object" ? pathSegment.key : pathSegment;
883
- const segmentAsNumber = Number(segment);
884
- if (Array.isArray(currentFormValue) && !Number.isNaN(segmentAsNumber)) path += `[${segmentAsNumber}]`;
885
- else path += (i > 0 ? "." : "") + String(segment);
886
- if (typeof currentFormValue === "object" && currentFormValue !== null) currentFormValue = currentFormValue[segment];
887
- else currentFormValue = void 0;
888
- }
889
- schema.set(path, (schema.get(path) ?? []).concat(issue));
890
- }
891
- return Object.fromEntries(schema);
892
- }
893
- var transformFormIssues = (issues, formValue) => {
894
- const schemaErrors = prefixSchemaToErrors(issues, formValue);
895
- return {
896
- form: schemaErrors,
897
- fields: schemaErrors
898
- };
899
- };
900
- var standardSchemaValidators = {
901
- validate({ value, validationSource }, schema) {
902
- const result = schema["~standard"].validate(value);
903
- if (result instanceof Promise) throw new Error("async function passed to sync validator");
904
- if (!result.issues) return;
905
- if (validationSource === "field") return result.issues;
906
- return transformFormIssues(result.issues, value);
907
- },
908
- async validateAsync({ value, validationSource }, schema) {
909
- const result = await schema["~standard"].validate(value);
910
- if (!result.issues) return;
911
- if (validationSource === "field") return result.issues;
912
- return transformFormIssues(result.issues, value);
913
- }
914
- };
915
- var isStandardSchemaValidator = (validator) => !!validator && "~standard" in validator;
916
- //#endregion
917
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/metaHelper.js
918
- var defaultFieldMeta = {
919
- isValidating: false,
920
- isTouched: false,
921
- isBlurred: false,
922
- isDirty: false,
923
- isPristine: true,
924
- isValid: true,
925
- isDefaultValue: true,
926
- errors: [],
927
- errorMap: {},
928
- errorSourceMap: {},
929
- _arrayVersion: 0
930
- };
931
- function metaHelper(formApi) {
932
- function bumpArrayVersion(field) {
933
- const currentMeta = formApi.getFieldMeta(field) ?? defaultFieldMeta;
934
- formApi.setFieldMeta(field, {
935
- ...currentMeta,
936
- _arrayVersion: (currentMeta._arrayVersion || 0) + 1
937
- });
938
- }
939
- function handleArrayMove(field, fromIndex, toIndex) {
940
- bumpArrayVersion(field);
941
- const affectedFields = getAffectedFields(field, fromIndex, "move", toIndex);
942
- const startIndex = Math.min(fromIndex, toIndex);
943
- const endIndex = Math.max(fromIndex, toIndex);
944
- for (let i = startIndex; i <= endIndex; i++) affectedFields.push(getFieldPath(field, i));
945
- const fromFields = Object.keys(formApi.fieldInfo).reduce((fieldMap, fieldKey) => {
946
- if (fieldKey.startsWith(getFieldPath(field, fromIndex))) fieldMap.set(fieldKey, formApi.getFieldMeta(fieldKey));
947
- return fieldMap;
948
- }, /* @__PURE__ */ new Map());
949
- shiftMeta(affectedFields, fromIndex < toIndex ? "up" : "down");
950
- Object.keys(formApi.fieldInfo).filter((fieldKey) => fieldKey.startsWith(getFieldPath(field, toIndex))).forEach((fieldKey) => {
951
- const fromKey = fieldKey.replace(getFieldPath(field, toIndex), getFieldPath(field, fromIndex));
952
- const fromMeta = fromFields.get(fromKey);
953
- if (fromMeta) formApi.setFieldMeta(fieldKey, fromMeta);
954
- });
955
- }
956
- function handleArrayRemove(field, index) {
957
- bumpArrayVersion(field);
958
- shiftMeta(getAffectedFields(field, index, "remove"), "up");
959
- }
960
- function handleArraySwap(field, index, secondIndex) {
961
- bumpArrayVersion(field);
962
- getAffectedFields(field, index, "swap", secondIndex).forEach((fieldKey) => {
963
- if (!fieldKey.toString().startsWith(getFieldPath(field, index))) return;
964
- const swappedKey = fieldKey.toString().replace(getFieldPath(field, index), getFieldPath(field, secondIndex));
965
- const [meta1, meta2] = [formApi.getFieldMeta(fieldKey), formApi.getFieldMeta(swappedKey)];
966
- if (meta1) formApi.setFieldMeta(swappedKey, meta1);
967
- if (meta2) formApi.setFieldMeta(fieldKey, meta2);
968
- });
969
- }
970
- function handleArrayInsert(field, insertIndex) {
971
- bumpArrayVersion(field);
972
- const affectedFields = getAffectedFields(field, insertIndex, "insert");
973
- shiftMeta(affectedFields, "down");
974
- affectedFields.forEach((fieldKey) => {
975
- if (fieldKey.toString().startsWith(getFieldPath(field, insertIndex))) formApi.setFieldMeta(fieldKey, getEmptyFieldMeta());
976
- });
977
- }
978
- function getFieldPath(field, index) {
979
- return `${field}[${index}]`;
980
- }
981
- function getAffectedFields(field, index, mode, secondIndex) {
982
- const affectedFieldKeys = [getFieldPath(field, index)];
983
- switch (mode) {
984
- case "swap":
985
- affectedFieldKeys.push(getFieldPath(field, secondIndex));
986
- break;
987
- case "move": {
988
- const [startIndex, endIndex] = [Math.min(index, secondIndex), Math.max(index, secondIndex)];
989
- for (let i = startIndex; i <= endIndex; i++) affectedFieldKeys.push(getFieldPath(field, i));
990
- break;
991
- }
992
- default: {
993
- const currentValue = formApi.getFieldValue(field);
994
- const fieldItems = Array.isArray(currentValue) ? currentValue.length : 0;
995
- for (let i = index + 1; i < fieldItems; i++) affectedFieldKeys.push(getFieldPath(field, i));
996
- break;
997
- }
998
- }
999
- return Object.keys(formApi.fieldInfo).filter((fieldKey) => affectedFieldKeys.some((key) => fieldKey.startsWith(key)));
1000
- }
1001
- function updateIndex(fieldKey, direction) {
1002
- return fieldKey.replace(/\[(\d+)\]/, (_, num) => {
1003
- const currIndex = parseInt(num, 10);
1004
- return `[${direction === "up" ? currIndex + 1 : Math.max(0, currIndex - 1)}]`;
1005
- });
1006
- }
1007
- function shiftMeta(fields, direction) {
1008
- (direction === "up" ? fields : [...fields].reverse()).forEach((fieldKey) => {
1009
- const nextFieldKey = updateIndex(fieldKey.toString(), direction);
1010
- const nextFieldMeta = formApi.getFieldMeta(nextFieldKey);
1011
- if (nextFieldMeta) formApi.setFieldMeta(fieldKey, nextFieldMeta);
1012
- else formApi.setFieldMeta(fieldKey, getEmptyFieldMeta());
1013
- });
1014
- }
1015
- const getEmptyFieldMeta = () => defaultFieldMeta;
1016
- return {
1017
- bumpArrayVersion,
1018
- handleArrayMove,
1019
- handleArrayRemove,
1020
- handleArraySwap,
1021
- handleArrayInsert
1022
- };
1023
- }
1024
- //#endregion
1025
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FormApi.js
1026
- function getDefaultFormState(defaultState) {
1027
- return {
1028
- values: defaultState.values ?? {},
1029
- errorMap: defaultState.errorMap ?? {},
1030
- fieldMetaBase: defaultState.fieldMetaBase ?? {},
1031
- formGroupStateBase: defaultState.formGroupStateBase ?? {},
1032
- isSubmitted: defaultState.isSubmitted ?? false,
1033
- isSubmitting: defaultState.isSubmitting ?? false,
1034
- isValidating: defaultState.isValidating ?? false,
1035
- submissionAttempts: defaultState.submissionAttempts ?? 0,
1036
- isSubmitSuccessful: defaultState.isSubmitSuccessful ?? false,
1037
- validationMetaMap: defaultState.validationMetaMap ?? {
1038
- onChange: void 0,
1039
- onBlur: void 0,
1040
- onSubmit: void 0,
1041
- onMount: void 0,
1042
- onServer: void 0,
1043
- onDynamic: void 0
1044
- }
1045
- };
1046
- }
1047
- var FormApi = class {
1048
- /**
1049
- * Constructs a new `FormApi` instance with the given form options.
1050
- */
1051
- constructor(opts) {
1052
- this.options = {};
1053
- this.fieldInfo = {};
1054
- this.formGroupApis = /* @__PURE__ */ new Set();
1055
- this.mount = () => {
1056
- const cleanupDevtoolBroadcast = this.store.subscribe(() => {
1057
- throttleFormState(this);
1058
- });
1059
- const cleanupFormStateListener = formEventClient.on("request-form-state", (e) => {
1060
- if (e.payload.id === this._formId) formEventClient.emit("form-api", {
1061
- id: this._formId,
1062
- state: this.store.state,
1063
- options: this.options
1064
- });
1065
- });
1066
- const cleanupFormResetListener = formEventClient.on("request-form-reset", (e) => {
1067
- if (e.payload.id === this._formId) this.reset();
1068
- });
1069
- const cleanupFormForceSubmitListener = formEventClient.on("request-form-force-submit", (e) => {
1070
- if (e.payload.id === this._formId) {
1071
- this._devtoolsSubmissionOverride = true;
1072
- this.handleSubmit();
1073
- this._devtoolsSubmissionOverride = false;
1074
- }
1075
- });
1076
- const cleanup = () => {
1077
- cleanupFormForceSubmitListener();
1078
- cleanupFormResetListener();
1079
- cleanupFormStateListener();
1080
- cleanupDevtoolBroadcast.unsubscribe();
1081
- formEventClient.emit("form-unmounted", { id: this._formId });
1082
- };
1083
- this.options.listeners?.onMount?.({ formApi: this });
1084
- const { onMount } = this.options.validators || {};
1085
- formEventClient.emit("form-api", {
1086
- id: this._formId,
1087
- state: this.store.state,
1088
- options: this.options
1089
- });
1090
- if (!onMount) return cleanup;
1091
- this.validateSync("mount");
1092
- return cleanup;
1093
- };
1094
- this.update = (options) => {
1095
- if (!options) return;
1096
- const oldOptions = this.options;
1097
- this.options = options;
1098
- const shouldUpdateValues = options.defaultValues && !evaluate(options.defaultValues, oldOptions.defaultValues) && !this.state.isTouched;
1099
- const shouldUpdateState = !evaluate(options.defaultState, oldOptions.defaultState) && !this.state.isTouched;
1100
- if (!shouldUpdateValues && !shouldUpdateState) return;
1101
- batch(() => {
1102
- this.baseStore.setState(() => getDefaultFormState(Object.assign({}, this.state, shouldUpdateState ? options.defaultState : {}, shouldUpdateValues ? { values: options.defaultValues } : {})));
1103
- });
1104
- if (shouldUpdateValues) {
1105
- const helper = metaHelper(this);
1106
- for (const fieldKey of Object.keys(this.fieldInfo)) if (Array.isArray(this.getFieldValue(fieldKey))) helper.bumpArrayVersion(fieldKey);
1107
- }
1108
- formEventClient.emit("form-api", {
1109
- id: this._formId,
1110
- state: this.store.state,
1111
- options: this.options
1112
- });
1113
- };
1114
- this.reset = (values, opts2) => {
1115
- const { fieldMeta: currentFieldMeta } = this.state;
1116
- const fieldMetaBase = this.resetFieldMeta(currentFieldMeta);
1117
- if (values && !opts2?.keepDefaultValues) this.options = {
1118
- ...this.options,
1119
- defaultValues: values
1120
- };
1121
- this.baseStore.setState(() => {
1122
- let nextValues = values ?? this.options.defaultValues ?? this.options.defaultState?.values;
1123
- if (!values) Object.values(this.fieldInfo).forEach((fieldInfo) => {
1124
- if (fieldInfo.instance && fieldInfo.instance.options.defaultValue !== void 0) nextValues = setBy(nextValues, fieldInfo.instance.name, fieldInfo.instance.options.defaultValue);
1125
- });
1126
- return getDefaultFormState({
1127
- ...this.options.defaultState,
1128
- values: nextValues,
1129
- fieldMetaBase
1130
- });
1131
- });
1132
- };
1133
- this.validateAllFields = async (cause) => {
1134
- const fieldValidationPromises = [];
1135
- batch(() => {
1136
- Object.values(this.fieldInfo).forEach((field) => {
1137
- if (!field.instance) return;
1138
- const fieldInstance = field.instance;
1139
- fieldValidationPromises.push(Promise.resolve().then(() => fieldInstance.validate(cause, {
1140
- skipFormValidation: true,
1141
- skipGroupValidation: true
1142
- })));
1143
- if (!field.instance.store.state.meta.isTouched) field.instance.setMeta((prev) => ({
1144
- ...prev,
1145
- isTouched: true
1146
- }));
1147
- });
1148
- });
1149
- return (await Promise.all(fieldValidationPromises)).flat();
1150
- };
1151
- this.validateArrayFieldsStartingFrom = async (field, index, cause) => {
1152
- const currentValue = this.getFieldValue(field);
1153
- const lastIndex = Array.isArray(currentValue) ? Math.max(currentValue.length - 1, 0) : null;
1154
- const fieldKeysToValidate = [`${field}[${index}]`];
1155
- for (let i = index + 1; i <= (lastIndex ?? 0); i++) fieldKeysToValidate.push(`${field}[${i}]`);
1156
- const fieldsToValidate = Object.keys(this.fieldInfo).filter((fieldKey) => fieldKeysToValidate.some((key) => fieldKey.startsWith(key)));
1157
- const fieldValidationPromises = [];
1158
- batch(() => {
1159
- fieldsToValidate.forEach((nestedField) => {
1160
- fieldValidationPromises.push(Promise.resolve().then(() => this.validateField(nestedField, cause)));
1161
- });
1162
- });
1163
- return (await Promise.all(fieldValidationPromises)).flat();
1164
- };
1165
- this.validateField = (field, cause) => {
1166
- const fieldInstance = this.fieldInfo[field]?.instance;
1167
- if (!fieldInstance) {
1168
- const { hasErrored } = this.validateSync(cause);
1169
- if (hasErrored && !this.options.asyncAlways) return this.getFieldMeta(field)?.errors ?? [];
1170
- return this.validateAsync(cause).then(() => {
1171
- return this.getFieldMeta(field)?.errors ?? [];
1172
- });
1173
- }
1174
- if (!fieldInstance.store.state.meta.isTouched) fieldInstance.setMeta((prev) => ({
1175
- ...prev,
1176
- isTouched: true
1177
- }));
1178
- return fieldInstance.validate(cause);
1179
- };
1180
- this.validateSync = (cause, validateOpts) => {
1181
- const validates = getSyncValidatorArray(cause, {
1182
- ...this.options,
1183
- form: this,
1184
- group: validateOpts?.group,
1185
- validationLogic: this.options.validationLogic || defaultValidationLogic
1186
- });
1187
- let hasErrored = false;
1188
- const currentValidationErrorMap = {};
1189
- batch(() => {
1190
- for (const validateObj of validates) {
1191
- if (!validateObj.validate) continue;
1192
- const { formError, fieldErrors } = normalizeError$2(this.runValidator({
1193
- validate: validateObj.validate,
1194
- value: {
1195
- value: this.state.values,
1196
- formApi: this,
1197
- validationSource: "form"
1198
- },
1199
- type: "validate"
1200
- }));
1201
- const errorMapKey = getErrorMapKey$2(validateObj.cause);
1202
- let allFieldsToProcess = /* @__PURE__ */ new Set([...Object.keys(this.state.fieldMeta), ...Object.keys(fieldErrors || {})]);
1203
- if (validateOpts?.filterFieldNames) allFieldsToProcess = new Set([...allFieldsToProcess].filter(validateOpts.filterFieldNames));
1204
- for (const field of allFieldsToProcess) {
1205
- if (this.baseStore.state.fieldMetaBase[field] === void 0 && !fieldErrors?.[field]) continue;
1206
- const { errorMap: currentErrorMap, errorSourceMap: currentErrorMapSource } = this.getFieldMeta(field) ?? defaultFieldMeta;
1207
- const newFormValidatorError = fieldErrors?.[field];
1208
- const { newErrorValue, newSource } = determineFormLevelErrorSourceAndValue({
1209
- newFormValidatorError,
1210
- isPreviousErrorFromFormValidator: currentErrorMapSource?.[errorMapKey] === "form",
1211
- previousErrorValue: currentErrorMap?.[errorMapKey]
1212
- });
1213
- if (newSource === "form") currentValidationErrorMap[field] = {
1214
- ...currentValidationErrorMap[field],
1215
- [errorMapKey]: newFormValidatorError
1216
- };
1217
- if (currentErrorMap?.[errorMapKey] !== newErrorValue) this.setFieldMeta(field, (prev = defaultFieldMeta) => ({
1218
- ...prev,
1219
- errorMap: {
1220
- ...prev.errorMap,
1221
- [errorMapKey]: newErrorValue
1222
- },
1223
- errorSourceMap: {
1224
- ...prev.errorSourceMap,
1225
- [errorMapKey]: newSource
1226
- }
1227
- }));
1228
- }
1229
- if (!validateOpts?.dontUpdateFormErrorMap) {
1230
- if (this.state.errorMap?.[errorMapKey] !== formError) this.baseStore.setState((prev) => ({
1231
- ...prev,
1232
- errorMap: {
1233
- ...prev.errorMap,
1234
- [errorMapKey]: formError
1235
- }
1236
- }));
1237
- }
1238
- if (formError || fieldErrors) hasErrored = true;
1239
- }
1240
- if (validateOpts?.dontUpdateFormErrorMap) return;
1241
- const submitErrKey = getErrorMapKey$2("submit");
1242
- if (this.state.errorMap?.[submitErrKey] && cause !== "submit" && !hasErrored) this.baseStore.setState((prev) => ({
1243
- ...prev,
1244
- errorMap: {
1245
- ...prev.errorMap,
1246
- [submitErrKey]: void 0
1247
- }
1248
- }));
1249
- const serverErrKey = getErrorMapKey$2("server");
1250
- if (this.state.errorMap?.[serverErrKey] && cause !== "server" && !hasErrored) this.baseStore.setState((prev) => ({
1251
- ...prev,
1252
- errorMap: {
1253
- ...prev.errorMap,
1254
- [serverErrKey]: void 0
1255
- }
1256
- }));
1257
- });
1258
- return {
1259
- hasErrored,
1260
- fieldsErrorMap: currentValidationErrorMap
1261
- };
1262
- };
1263
- this.validateAsync = async (cause, validateOpts) => {
1264
- const validates = getAsyncValidatorArray(cause, {
1265
- ...this.options,
1266
- form: this,
1267
- group: validateOpts?.group,
1268
- validationLogic: this.options.validationLogic || defaultValidationLogic
1269
- });
1270
- if (!this.state.isFormValidating) this.baseStore.setState((prev) => ({
1271
- ...prev,
1272
- isFormValidating: true
1273
- }));
1274
- const promises = [];
1275
- let fieldErrorsFromFormValidators;
1276
- for (const validateObj of validates) {
1277
- if (!validateObj.validate) continue;
1278
- const key = getErrorMapKey$2(validateObj.cause);
1279
- this.state.validationMetaMap[key]?.lastAbortController.abort();
1280
- const controller = new AbortController();
1281
- this.state.validationMetaMap[key] = { lastAbortController: controller };
1282
- promises.push(new Promise(async (resolve) => {
1283
- let rawError;
1284
- try {
1285
- rawError = await new Promise((rawResolve, rawReject) => {
1286
- setTimeout(async () => {
1287
- if (controller.signal.aborted) return rawResolve(void 0);
1288
- try {
1289
- rawResolve(await this.runValidator({
1290
- validate: validateObj.validate,
1291
- value: {
1292
- value: this.state.values,
1293
- formApi: this,
1294
- validationSource: "form",
1295
- signal: controller.signal
1296
- },
1297
- type: "validateAsync"
1298
- }));
1299
- } catch (e) {
1300
- rawReject(e);
1301
- }
1302
- }, validateObj.debounceMs);
1303
- });
1304
- } catch (e) {
1305
- rawError = e;
1306
- }
1307
- const { formError, fieldErrors: fieldErrorsFromNormalizeError } = normalizeError$2(rawError);
1308
- if (fieldErrorsFromNormalizeError) fieldErrorsFromFormValidators = fieldErrorsFromFormValidators ? {
1309
- ...fieldErrorsFromFormValidators,
1310
- ...fieldErrorsFromNormalizeError
1311
- } : fieldErrorsFromNormalizeError;
1312
- const errorMapKey = getErrorMapKey$2(validateObj.cause);
1313
- let fields = Object.keys(this.state.fieldMeta);
1314
- if (validateOpts?.filterFieldNames) fields = fields.filter(validateOpts.filterFieldNames);
1315
- for (const field of fields) {
1316
- if (this.baseStore.state.fieldMetaBase[field] === void 0) continue;
1317
- const fieldMeta = this.getFieldMeta(field);
1318
- if (!fieldMeta) continue;
1319
- const { errorMap: currentErrorMap, errorSourceMap: currentErrorMapSource } = fieldMeta;
1320
- const newFormValidatorError = fieldErrorsFromFormValidators?.[field];
1321
- const { newErrorValue, newSource } = determineFormLevelErrorSourceAndValue({
1322
- newFormValidatorError,
1323
- isPreviousErrorFromFormValidator: currentErrorMapSource?.[errorMapKey] === "form",
1324
- previousErrorValue: currentErrorMap?.[errorMapKey]
1325
- });
1326
- if (currentErrorMap?.[errorMapKey] !== newErrorValue) this.setFieldMeta(field, (prev) => ({
1327
- ...prev,
1328
- errorMap: {
1329
- ...prev.errorMap,
1330
- [errorMapKey]: newErrorValue
1331
- },
1332
- errorSourceMap: {
1333
- ...prev.errorSourceMap,
1334
- [errorMapKey]: newSource
1335
- }
1336
- }));
1337
- }
1338
- if (!validateOpts?.dontUpdateFormErrorMap) this.baseStore.setState((prev) => ({
1339
- ...prev,
1340
- errorMap: {
1341
- ...prev.errorMap,
1342
- [errorMapKey]: formError
1343
- }
1344
- }));
1345
- resolve(fieldErrorsFromFormValidators ? {
1346
- fieldErrors: fieldErrorsFromFormValidators,
1347
- errorMapKey
1348
- } : void 0);
1349
- }));
1350
- }
1351
- let results = [];
1352
- const fieldsErrorMap = {};
1353
- if (promises.length) {
1354
- results = await Promise.all(promises);
1355
- for (const fieldValidationResult of results) if (fieldValidationResult?.fieldErrors) {
1356
- const { errorMapKey } = fieldValidationResult;
1357
- for (const [field, fieldError] of Object.entries(fieldValidationResult.fieldErrors)) fieldsErrorMap[field] = {
1358
- ...fieldsErrorMap[field] || {},
1359
- [errorMapKey]: fieldError
1360
- };
1361
- }
1362
- }
1363
- this.baseStore.setState((prev) => ({
1364
- ...prev,
1365
- isFormValidating: false
1366
- }));
1367
- return fieldsErrorMap;
1368
- };
1369
- this.validate = (cause, validateOpts) => {
1370
- const { hasErrored, fieldsErrorMap } = this.validateSync(cause, validateOpts);
1371
- if (hasErrored && !this.options.asyncAlways) return fieldsErrorMap;
1372
- return this.validateAsync(cause, validateOpts);
1373
- };
1374
- this._handleSubmit = async (submitMeta) => {
1375
- this.baseStore.setState((old) => ({
1376
- ...old,
1377
- isSubmitted: false,
1378
- submissionAttempts: old.submissionAttempts + 1,
1379
- isSubmitSuccessful: false
1380
- }));
1381
- batch(() => {
1382
- Object.values(this.fieldInfo).forEach((field) => {
1383
- if (!field.instance) return;
1384
- if (!field.instance.store.state.meta.isTouched) field.instance.setMeta((prev) => ({
1385
- ...prev,
1386
- isTouched: true
1387
- }));
1388
- });
1389
- });
1390
- const submitMetaArg = submitMeta ?? this.options.onSubmitMeta;
1391
- if (!this.state.canSubmit && !this._devtoolsSubmissionOverride) {
1392
- this.options.onSubmitInvalid?.({
1393
- value: this.state.values,
1394
- formApi: this,
1395
- meta: submitMetaArg
1396
- });
1397
- return;
1398
- }
1399
- this.baseStore.setState((d) => ({
1400
- ...d,
1401
- isSubmitting: true
1402
- }));
1403
- const done = () => {
1404
- this.baseStore.setState((prev) => ({
1405
- ...prev,
1406
- isSubmitting: false
1407
- }));
1408
- };
1409
- await this.validateAllFields("submit");
1410
- if (!this.state.isFieldsValid) {
1411
- done();
1412
- this.options.onSubmitInvalid?.({
1413
- value: this.state.values,
1414
- formApi: this,
1415
- meta: submitMetaArg
1416
- });
1417
- formEventClient.emit("form-submission", {
1418
- id: this._formId,
1419
- submissionAttempt: this.state.submissionAttempts,
1420
- successful: false,
1421
- stage: "validateAllFields",
1422
- errors: Object.values(this.state.fieldMeta).map((meta) => meta.errors).flat()
1423
- });
1424
- return;
1425
- }
1426
- await this.validate("submit");
1427
- if (!this.state.isValid) {
1428
- done();
1429
- this.options.onSubmitInvalid?.({
1430
- value: this.state.values,
1431
- formApi: this,
1432
- meta: submitMetaArg
1433
- });
1434
- formEventClient.emit("form-submission", {
1435
- id: this._formId,
1436
- submissionAttempt: this.state.submissionAttempts,
1437
- successful: false,
1438
- stage: "validate",
1439
- errors: this.state.errors
1440
- });
1441
- return;
1442
- }
1443
- batch(() => {
1444
- Object.values(this.fieldInfo).forEach((field) => {
1445
- field.instance?.triggerOnSubmitListener();
1446
- });
1447
- });
1448
- this.options.listeners?.onSubmit?.({
1449
- formApi: this,
1450
- meta: submitMetaArg
1451
- });
1452
- try {
1453
- await this.options.onSubmit?.({
1454
- value: this.state.values,
1455
- formApi: this,
1456
- meta: submitMetaArg
1457
- });
1458
- batch(() => {
1459
- this.baseStore.setState((prev) => ({
1460
- ...prev,
1461
- isSubmitted: true,
1462
- isSubmitSuccessful: true
1463
- }));
1464
- formEventClient.emit("form-submission", {
1465
- id: this._formId,
1466
- submissionAttempt: this.state.submissionAttempts,
1467
- successful: true
1468
- });
1469
- done();
1470
- });
1471
- } catch (err) {
1472
- this.baseStore.setState((prev) => ({
1473
- ...prev,
1474
- isSubmitSuccessful: false
1475
- }));
1476
- formEventClient.emit("form-submission", {
1477
- id: this._formId,
1478
- submissionAttempt: this.state.submissionAttempts,
1479
- successful: false,
1480
- stage: "inflight",
1481
- onError: err
1482
- });
1483
- done();
1484
- throw err;
1485
- }
1486
- };
1487
- this.getFieldValue = (field) => getBy(this.state.values, field);
1488
- this.getFieldMeta = (field) => {
1489
- return this.state.fieldMeta[field];
1490
- };
1491
- this.getFormGroupMeta = (name) => {
1492
- return this.formGroupMetaDerived.state[name];
1493
- };
1494
- this.getFieldInfo = (field) => {
1495
- return this.fieldInfo[field] ||= {
1496
- instance: null,
1497
- validationMetaMap: {
1498
- onChange: void 0,
1499
- onBlur: void 0,
1500
- onSubmit: void 0,
1501
- onMount: void 0,
1502
- onServer: void 0,
1503
- onDynamic: void 0
1504
- }
1505
- };
1506
- };
1507
- this.setFieldMeta = (field, updater) => {
1508
- this.baseStore.setState((prev) => {
1509
- return {
1510
- ...prev,
1511
- fieldMetaBase: {
1512
- ...prev.fieldMetaBase,
1513
- [field]: functionalUpdate(updater, prev.fieldMetaBase[field])
1514
- }
1515
- };
1516
- });
1517
- };
1518
- this.resetFieldMeta = (fieldMeta) => {
1519
- return Object.keys(fieldMeta).reduce((acc, key) => {
1520
- const fieldKey = key;
1521
- acc[fieldKey] = defaultFieldMeta;
1522
- return acc;
1523
- }, {});
1524
- };
1525
- this.setFieldValue = (field, updater, opts2) => {
1526
- const dontUpdateMeta = opts2?.dontUpdateMeta ?? false;
1527
- const dontRunListeners = opts2?.dontRunListeners ?? false;
1528
- const dontValidate = opts2?.dontValidate ?? false;
1529
- batch(() => {
1530
- if (!dontUpdateMeta) this.setFieldMeta(field, (prev) => ({
1531
- ...prev,
1532
- isTouched: true,
1533
- isDirty: true,
1534
- errorMap: {
1535
- ...prev?.errorMap,
1536
- onMount: void 0
1537
- }
1538
- }));
1539
- this.baseStore.setState((prev) => {
1540
- return {
1541
- ...prev,
1542
- values: setBy(prev.values, field, updater)
1543
- };
1544
- });
1545
- });
1546
- if (!dontRunListeners) this.getFieldInfo(field).instance?.triggerOnChangeListener();
1547
- if (!dontValidate) this.validateField(field, "change");
1548
- };
1549
- this.deleteField = (field) => {
1550
- const fieldsToDelete = [...Object.keys(this.fieldInfo).filter((f) => {
1551
- const fieldStr = field.toString();
1552
- return f !== fieldStr && f.startsWith(fieldStr);
1553
- }), field];
1554
- this.baseStore.setState((prev) => {
1555
- const newState = { ...prev };
1556
- fieldsToDelete.forEach((f) => {
1557
- newState.values = deleteBy(newState.values, f);
1558
- delete this.fieldInfo[f];
1559
- delete newState.fieldMetaBase[f];
1560
- });
1561
- return newState;
1562
- });
1563
- };
1564
- this.pushFieldValue = (field, value, options) => {
1565
- this.setFieldValue(field, (prev) => [...Array.isArray(prev) ? prev : [], value], options);
1566
- metaHelper(this).bumpArrayVersion(field);
1567
- };
1568
- this.insertFieldValue = async (field, index, value, options) => {
1569
- this.setFieldValue(field, (prev) => {
1570
- return [
1571
- ...prev.slice(0, index),
1572
- value,
1573
- ...prev.slice(index)
1574
- ];
1575
- }, mergeOpts(options, { dontValidate: true }));
1576
- const dontValidate = options?.dontValidate ?? false;
1577
- if (!dontValidate) await this.validateField(field, "change");
1578
- metaHelper(this).handleArrayInsert(field, index);
1579
- if (!dontValidate) await this.validateArrayFieldsStartingFrom(field, index, "change");
1580
- };
1581
- this.replaceFieldValue = async (field, index, value, options) => {
1582
- this.setFieldValue(field, (prev) => {
1583
- return prev.map((d, i) => i === index ? value : d);
1584
- }, mergeOpts(options, { dontValidate: true }));
1585
- metaHelper(this).bumpArrayVersion(field);
1586
- if (!(options?.dontValidate ?? false)) {
1587
- await this.validateField(field, "change");
1588
- await this.validateArrayFieldsStartingFrom(field, index, "change");
1589
- }
1590
- };
1591
- this.removeFieldValue = async (field, index, options) => {
1592
- const fieldValue = this.getFieldValue(field);
1593
- const lastIndex = Array.isArray(fieldValue) ? Math.max(fieldValue.length - 1, 0) : null;
1594
- this.setFieldValue(field, (prev) => {
1595
- return prev.filter((_d, i) => i !== index);
1596
- }, mergeOpts(options, { dontValidate: true }));
1597
- metaHelper(this).handleArrayRemove(field, index);
1598
- if (lastIndex !== null) {
1599
- const start = `${field}[${lastIndex}]`;
1600
- this.deleteField(start);
1601
- }
1602
- if (!(options?.dontValidate ?? false)) {
1603
- await this.validateField(field, "change");
1604
- await this.validateArrayFieldsStartingFrom(field, index, "change");
1605
- }
1606
- };
1607
- this.swapFieldValues = (field, index1, index2, options) => {
1608
- this.setFieldValue(field, (prev) => {
1609
- const prev1 = prev[index1];
1610
- const prev2 = prev[index2];
1611
- return setBy(setBy(prev, `${index1}`, prev2), `${index2}`, prev1);
1612
- }, mergeOpts(options, { dontValidate: true }));
1613
- metaHelper(this).handleArraySwap(field, index1, index2);
1614
- if (!(options?.dontValidate ?? false)) {
1615
- this.validateField(field, "change");
1616
- this.validateField(`${field}[${index1}]`, "change");
1617
- this.validateField(`${field}[${index2}]`, "change");
1618
- }
1619
- };
1620
- this.moveFieldValues = (field, index1, index2, options) => {
1621
- this.setFieldValue(field, (prev) => {
1622
- const next = [...prev];
1623
- next.splice(index2, 0, next.splice(index1, 1)[0]);
1624
- return next;
1625
- }, mergeOpts(options, { dontValidate: true }));
1626
- metaHelper(this).handleArrayMove(field, index1, index2);
1627
- if (!(options?.dontValidate ?? false)) {
1628
- this.validateField(field, "change");
1629
- this.validateField(`${field}[${index1}]`, "change");
1630
- this.validateField(`${field}[${index2}]`, "change");
1631
- }
1632
- };
1633
- this.clearFieldValues = (field, options) => {
1634
- const fieldValue = this.getFieldValue(field);
1635
- const lastIndex = Array.isArray(fieldValue) ? Math.max(fieldValue.length - 1, 0) : null;
1636
- this.setFieldValue(field, [], mergeOpts(options, { dontValidate: true }));
1637
- metaHelper(this).bumpArrayVersion(field);
1638
- if (lastIndex !== null) for (let i = 0; i <= lastIndex; i++) {
1639
- const fieldKey = `${field}[${i}]`;
1640
- this.deleteField(fieldKey);
1641
- }
1642
- if (!(options?.dontValidate ?? false)) this.validateField(field, "change");
1643
- };
1644
- this.resetField = (field) => {
1645
- this.baseStore.setState((prev) => {
1646
- const fieldDefault = this.getFieldInfo(field).instance?.options.defaultValue;
1647
- const formDefault = getBy(this.options.defaultValues, field);
1648
- const targetValue = fieldDefault ?? formDefault;
1649
- return {
1650
- ...prev,
1651
- fieldMetaBase: {
1652
- ...prev.fieldMetaBase,
1653
- [field]: defaultFieldMeta
1654
- },
1655
- values: targetValue !== void 0 ? setBy(prev.values, field, targetValue) : prev.values
1656
- };
1657
- });
1658
- };
1659
- this.setErrorMap = (errorMap) => {
1660
- batch(() => {
1661
- Object.entries(errorMap).forEach(([key, value]) => {
1662
- const errorMapKey = key;
1663
- if (isGlobalFormValidationError(value)) {
1664
- const { formError, fieldErrors } = normalizeError$2(value);
1665
- for (const fieldName of Object.keys(this.fieldInfo)) {
1666
- if (!this.getFieldMeta(fieldName)) continue;
1667
- this.setFieldMeta(fieldName, (prev) => ({
1668
- ...prev,
1669
- errorMap: {
1670
- ...prev.errorMap,
1671
- [errorMapKey]: fieldErrors?.[fieldName]
1672
- },
1673
- errorSourceMap: {
1674
- ...prev.errorSourceMap,
1675
- [errorMapKey]: "form"
1676
- }
1677
- }));
1678
- }
1679
- this.baseStore.setState((prev) => ({
1680
- ...prev,
1681
- errorMap: {
1682
- ...prev.errorMap,
1683
- [errorMapKey]: formError
1684
- }
1685
- }));
1686
- } else this.baseStore.setState((prev) => ({
1687
- ...prev,
1688
- errorMap: {
1689
- ...prev.errorMap,
1690
- [errorMapKey]: value
1691
- }
1692
- }));
1693
- });
1694
- });
1695
- };
1696
- this.getAllErrors = () => {
1697
- return {
1698
- form: {
1699
- errors: this.state.errors,
1700
- errorMap: this.state.errorMap
1701
- },
1702
- fields: Object.entries(this.state.fieldMeta).reduce((acc, [fieldName, fieldMeta]) => {
1703
- if (Object.keys(fieldMeta).length && fieldMeta.errors.length) acc[fieldName] = {
1704
- errors: fieldMeta.errors,
1705
- errorMap: fieldMeta.errorMap
1706
- };
1707
- return acc;
1708
- }, {})
1709
- };
1710
- };
1711
- this.parseValuesWithSchema = (schema) => {
1712
- return standardSchemaValidators.validate({
1713
- value: this.state.values,
1714
- validationSource: "form"
1715
- }, schema);
1716
- };
1717
- this.parseValuesWithSchemaAsync = (schema) => {
1718
- return standardSchemaValidators.validateAsync({
1719
- value: this.state.values,
1720
- validationSource: "form"
1721
- }, schema);
1722
- };
1723
- this.timeoutIds = {
1724
- validations: {},
1725
- listeners: {},
1726
- formListeners: {}
1727
- };
1728
- this._formId = opts?.formId ?? uuid();
1729
- this._devtoolsSubmissionOverride = false;
1730
- let baseStoreVal = getDefaultFormState({
1731
- ...opts?.defaultState,
1732
- values: opts?.defaultValues ?? opts?.defaultState?.values
1733
- });
1734
- if (opts?.transform) {
1735
- baseStoreVal = opts.transform({ state: baseStoreVal }).state;
1736
- for (const errKey of Object.keys(baseStoreVal.errorMap)) {
1737
- const errKeyMap = baseStoreVal.errorMap[errKey];
1738
- if (errKeyMap === void 0 || !isGlobalFormValidationError(errKeyMap)) continue;
1739
- for (const fieldName of Object.keys(errKeyMap.fields)) {
1740
- const fieldErr = errKeyMap.fields[fieldName];
1741
- if (fieldErr === void 0) continue;
1742
- const existingFieldMeta = baseStoreVal.fieldMetaBase[fieldName];
1743
- baseStoreVal.fieldMetaBase[fieldName] = {
1744
- isTouched: false,
1745
- isValidating: false,
1746
- isBlurred: false,
1747
- isDirty: false,
1748
- _arrayVersion: 0,
1749
- ...existingFieldMeta ?? {},
1750
- errorSourceMap: {
1751
- ...existingFieldMeta?.["errorSourceMap"] ?? {},
1752
- onChange: "form"
1753
- },
1754
- errorMap: {
1755
- ...existingFieldMeta?.["errorMap"] ?? {},
1756
- [errKey]: fieldErr
1757
- }
1758
- };
1759
- }
1760
- }
1761
- }
1762
- this.baseStore = createStore(baseStoreVal);
1763
- let prevBaseStore = void 0;
1764
- this.fieldMetaDerived = createStore((prevVal) => {
1765
- const currBaseStore = this.baseStore.get();
1766
- let originalMetaCount = 0;
1767
- const fieldMeta = {};
1768
- for (const fieldName of Object.keys(currBaseStore.fieldMetaBase)) {
1769
- const currBaseMeta = currBaseStore.fieldMetaBase[fieldName];
1770
- const prevBaseMeta = prevBaseStore?.fieldMetaBase[fieldName];
1771
- const prevFieldInfo = prevVal?.[fieldName];
1772
- const curFieldVal = getBy(currBaseStore.values, fieldName);
1773
- let fieldErrors = prevFieldInfo?.errors;
1774
- if (!prevBaseMeta || currBaseMeta.errorMap !== prevBaseMeta.errorMap) {
1775
- fieldErrors = Object.values(currBaseMeta.errorMap ?? {}).filter((val) => val !== void 0);
1776
- const fieldInstance = this.getFieldInfo(fieldName)?.instance;
1777
- if (!fieldInstance || !fieldInstance.options.disableErrorFlat) fieldErrors = fieldErrors.flat(1);
1778
- }
1779
- const isFieldValid = !isNonEmptyArray(fieldErrors);
1780
- const isFieldPristine = !currBaseMeta.isDirty;
1781
- const isDefaultValue = evaluate(curFieldVal, this.getFieldInfo(fieldName)?.instance?.options.defaultValue ?? getBy(this.options.defaultValues, fieldName));
1782
- if (prevFieldInfo && prevFieldInfo.isPristine === isFieldPristine && prevFieldInfo.isValid === isFieldValid && prevFieldInfo.isDefaultValue === isDefaultValue && prevFieldInfo.errors === fieldErrors && currBaseMeta === prevBaseMeta) {
1783
- fieldMeta[fieldName] = prevFieldInfo;
1784
- originalMetaCount++;
1785
- continue;
1786
- }
1787
- fieldMeta[fieldName] = {
1788
- ...currBaseMeta,
1789
- errors: fieldErrors ?? [],
1790
- isPristine: isFieldPristine,
1791
- isValid: isFieldValid,
1792
- isDefaultValue
1793
- };
1794
- }
1795
- if (!Object.keys(currBaseStore.fieldMetaBase).length) return fieldMeta;
1796
- if (prevVal && originalMetaCount === Object.keys(currBaseStore.fieldMetaBase).length) return prevVal;
1797
- prevBaseStore = this.baseStore.get();
1798
- return fieldMeta;
1799
- });
1800
- this.formGroupMetaDerived = createStore((prevVal) => {
1801
- const currBaseStore = this.baseStore.get();
1802
- const currFieldMeta = this.fieldMetaDerived.get();
1803
- const result = {};
1804
- for (const group of this.formGroupApis) {
1805
- const groupName = group.name;
1806
- const lifecycle = currBaseStore.formGroupStateBase[groupName] ?? {
1807
- isSubmitted: false,
1808
- isSubmitting: false,
1809
- isValidating: false,
1810
- submissionAttempts: 0,
1811
- isSubmitSuccessful: false
1812
- };
1813
- const ownFieldMeta = currFieldMeta[groupName];
1814
- let isFieldsValidating = false;
1815
- let isFieldsValid = true;
1816
- let aggIsTouched = false;
1817
- let aggIsBlurred = false;
1818
- let aggIsDefaultValue = true;
1819
- let aggIsDirty = false;
1820
- for (const fieldName in currFieldMeta) {
1821
- if (fieldName === groupName) continue;
1822
- if (!isFieldInGroup(groupName, fieldName)) continue;
1823
- const m = currFieldMeta[fieldName];
1824
- if (!m) continue;
1825
- if (m.isValidating) isFieldsValidating = true;
1826
- if (!m.isValid) isFieldsValid = false;
1827
- if (m.isTouched) aggIsTouched = true;
1828
- if (m.isBlurred) aggIsBlurred = true;
1829
- if (!m.isDefaultValue) aggIsDefaultValue = false;
1830
- if (m.isDirty) aggIsDirty = true;
1831
- }
1832
- const isPristine = !aggIsDirty;
1833
- const isValidating = !!isFieldsValidating || lifecycle.isValidating;
1834
- const errorMap = ownFieldMeta?.errorMap ?? {};
1835
- const errorSourceMap = ownFieldMeta?.errorSourceMap ?? {};
1836
- const hasOnMountError = Boolean(errorMap.onMount || Object.entries(currFieldMeta).some(([fieldName, field]) => field && fieldName !== groupName && isFieldInGroup(groupName, fieldName) && field.errorMap.onMount));
1837
- const prevGroupMeta = prevVal?.[groupName];
1838
- let errors = prevGroupMeta?.errors ?? [];
1839
- if (!prevGroupMeta || prevGroupMeta.__srcErrorMap !== errorMap) errors = Object.values(errorMap).reduce((acc, curr) => {
1840
- if (curr === void 0) return acc;
1841
- if (curr && typeof curr === "object" && "fields" in curr) {
1842
- const groupErr = curr.group;
1843
- if (groupErr !== void 0) acc.push(groupErr);
1844
- return acc;
1845
- }
1846
- acc.push(curr);
1847
- return acc;
1848
- }, []);
1849
- const isGroupValid = errors.length === 0;
1850
- const isValid = isFieldsValid && isGroupValid;
1851
- const submitInvalid = group.options.canSubmitWhenInvalid ?? false;
1852
- const canSubmit = lifecycle.submissionAttempts === 0 && !aggIsTouched && !hasOnMountError || !isValidating && !lifecycle.isSubmitting && isValid || submitInvalid;
1853
- if (prevGroupMeta && prevGroupMeta.errorMap === errorMap && prevGroupMeta.errorSourceMap === errorSourceMap && prevGroupMeta.errors === errors && prevGroupMeta.isFieldsValidating === isFieldsValidating && prevGroupMeta.isFieldsValid === isFieldsValid && prevGroupMeta.isGroupValid === isGroupValid && prevGroupMeta.isValid === isValid && prevGroupMeta.canSubmit === canSubmit && prevGroupMeta.isTouched === aggIsTouched && prevGroupMeta.isBlurred === aggIsBlurred && prevGroupMeta.isPristine === isPristine && prevGroupMeta.isDefaultValue === aggIsDefaultValue && prevGroupMeta.isDirty === aggIsDirty && prevGroupMeta.isValidating === isValidating && prevGroupMeta.isSubmitting === lifecycle.isSubmitting && prevGroupMeta.isSubmitted === lifecycle.isSubmitted && prevGroupMeta.submissionAttempts === lifecycle.submissionAttempts && prevGroupMeta.isSubmitSuccessful === lifecycle.isSubmitSuccessful) {
1854
- result[groupName] = prevGroupMeta;
1855
- continue;
1856
- }
1857
- const meta = {
1858
- ...lifecycle,
1859
- errorMap,
1860
- errorSourceMap,
1861
- _arrayVersion: ownFieldMeta?._arrayVersion ?? 0,
1862
- isTouched: aggIsTouched,
1863
- isBlurred: aggIsBlurred,
1864
- isDirty: aggIsDirty,
1865
- isPristine,
1866
- isDefaultValue: aggIsDefaultValue,
1867
- isValid,
1868
- errors,
1869
- isValidating,
1870
- isFieldsValidating,
1871
- isFieldsValid,
1872
- isGroupValid,
1873
- canSubmit
1874
- };
1875
- Object.defineProperty(meta, "__srcErrorMap", {
1876
- value: errorMap,
1877
- enumerable: false,
1878
- configurable: true
1879
- });
1880
- result[groupName] = meta;
1881
- }
1882
- return result;
1883
- });
1884
- let prevBaseStoreForStore = void 0;
1885
- this.store = createStore((prevVal) => {
1886
- const currBaseStore = this.baseStore.get();
1887
- const currFieldMeta = this.fieldMetaDerived.get();
1888
- const fieldMetaValues = Object.values(currFieldMeta).filter(Boolean);
1889
- const isFieldsValidating = fieldMetaValues.some((field) => field.isValidating);
1890
- const isFieldsValid = fieldMetaValues.every((field) => field.isValid);
1891
- const isTouched = fieldMetaValues.some((field) => field.isTouched);
1892
- const isBlurred = fieldMetaValues.some((field) => field.isBlurred);
1893
- const isDefaultValue = fieldMetaValues.every((field) => field.isDefaultValue);
1894
- const shouldInvalidateOnMount = isTouched && currBaseStore.errorMap?.onMount;
1895
- const isDirty = fieldMetaValues.some((field) => field.isDirty);
1896
- const isPristine = !isDirty;
1897
- const hasOnMountError = Boolean(currBaseStore.errorMap?.onMount || fieldMetaValues.some((f) => f?.errorMap?.onMount));
1898
- const isValidating = !!isFieldsValidating;
1899
- let errors = prevVal?.errors ?? [];
1900
- if (!prevBaseStoreForStore || currBaseStore.errorMap !== prevBaseStoreForStore.errorMap) errors = Object.values(currBaseStore.errorMap).reduce((prev, curr) => {
1901
- if (curr === void 0) return prev;
1902
- if (curr && isGlobalFormValidationError(curr)) {
1903
- prev.push(curr.form);
1904
- return prev;
1905
- }
1906
- prev.push(curr);
1907
- return prev;
1908
- }, []);
1909
- const isFormValid = errors.length === 0;
1910
- const isValid = isFieldsValid && isFormValid;
1911
- const submitInvalid = this.options.canSubmitWhenInvalid ?? false;
1912
- const canSubmit = currBaseStore.submissionAttempts === 0 && !isTouched && !hasOnMountError || !isValidating && !currBaseStore.isSubmitting && isValid || submitInvalid;
1913
- let errorMap = currBaseStore.errorMap;
1914
- if (shouldInvalidateOnMount) {
1915
- errors = errors.filter((err) => err !== currBaseStore.errorMap.onMount);
1916
- errorMap = Object.assign(errorMap, { onMount: void 0 });
1917
- }
1918
- if (prevVal && prevBaseStoreForStore && prevVal.errorMap === errorMap && prevVal.fieldMeta === this.fieldMetaDerived.state && prevVal.errors === errors && prevVal.isFieldsValidating === isFieldsValidating && prevVal.isFieldsValid === isFieldsValid && prevVal.isFormValid === isFormValid && prevVal.isValid === isValid && prevVal.canSubmit === canSubmit && prevVal.isTouched === isTouched && prevVal.isBlurred === isBlurred && prevVal.isPristine === isPristine && prevVal.isDefaultValue === isDefaultValue && prevVal.isDirty === isDirty && evaluate(prevBaseStoreForStore, currBaseStore)) return prevVal;
1919
- const state = {
1920
- ...currBaseStore,
1921
- errorMap,
1922
- fieldMeta: this.fieldMetaDerived.state,
1923
- errors,
1924
- isFieldsValidating,
1925
- isFieldsValid,
1926
- isFormValid,
1927
- isValid,
1928
- canSubmit,
1929
- isTouched,
1930
- isBlurred,
1931
- isPristine,
1932
- isDefaultValue,
1933
- isDirty
1934
- };
1935
- prevBaseStoreForStore = this.baseStore.get();
1936
- return state;
1937
- });
1938
- this.handleSubmit = this.handleSubmit.bind(this);
1939
- this.update(opts || {});
1940
- }
1941
- get state() {
1942
- return this.store.state;
1943
- }
1944
- get formId() {
1945
- return this._formId;
1946
- }
1947
- /**
1948
- * @private
1949
- */
1950
- runValidator(props) {
1951
- if (isStandardSchemaValidator(props.validate)) return standardSchemaValidators[props.type](props.value, props.validate);
1952
- return props.validate(props.value);
1953
- }
1954
- handleSubmit(submitMeta) {
1955
- return this._handleSubmit(submitMeta);
1956
- }
1957
- };
1958
- function normalizeError$2(rawError) {
1959
- if (rawError) {
1960
- if (isGlobalFormValidationError(rawError)) return {
1961
- formError: normalizeError$2(rawError.form).formError,
1962
- fieldErrors: rawError.fields
1963
- };
1964
- return { formError: rawError };
1965
- }
1966
- return { formError: void 0 };
1967
- }
1968
- function getErrorMapKey$2(cause) {
1969
- switch (cause) {
1970
- case "submit": return "onSubmit";
1971
- case "blur": return "onBlur";
1972
- case "mount": return "onMount";
1973
- case "server": return "onServer";
1974
- case "dynamic": return "onDynamic";
1975
- default: return "onChange";
1976
- }
1977
- }
1978
- //#endregion
1979
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FieldApi.js
1980
- var FieldApi = class FieldApi {
1981
- /**
1982
- * Initializes a new `FieldApi` instance.
1983
- */
1984
- constructor(opts) {
1985
- this.options = {};
1986
- this.mount = () => {
1987
- if (this.options.defaultValue !== void 0 && !this.getMeta().isTouched) this.form.setFieldValue(this.name, this.options.defaultValue, { dontUpdateMeta: true });
1988
- const info = this.getInfo();
1989
- info.instance = this;
1990
- this.update(this.options);
1991
- const { onMount } = this.options.validators || {};
1992
- if (onMount) {
1993
- const error = this.runValidator({
1994
- validate: onMount,
1995
- value: {
1996
- value: this.state.value,
1997
- fieldApi: this,
1998
- validationSource: "field"
1999
- },
2000
- type: "validate"
2001
- });
2002
- if (error) this.setMeta((prev) => ({
2003
- ...prev,
2004
- errorMap: {
2005
- ...prev?.errorMap,
2006
- onMount: error
2007
- },
2008
- errorSourceMap: {
2009
- ...prev?.errorSourceMap,
2010
- onMount: "field"
2011
- }
2012
- }));
2013
- }
2014
- this.options.listeners?.onMount?.({
2015
- value: this.state.value,
2016
- fieldApi: this
2017
- });
2018
- return () => {
2019
- for (const [key, timeout] of Object.entries(this.timeoutIds.validations)) if (timeout) {
2020
- clearTimeout(timeout);
2021
- this.timeoutIds.validations[key] = null;
2022
- }
2023
- for (const [key, timeout] of Object.entries(this.timeoutIds.listeners)) if (timeout) {
2024
- clearTimeout(timeout);
2025
- this.timeoutIds.listeners[key] = null;
2026
- }
2027
- for (const [key, timeout] of Object.entries(this.timeoutIds.formListeners)) if (timeout) {
2028
- clearTimeout(timeout);
2029
- this.timeoutIds.formListeners[key] = null;
2030
- }
2031
- const fieldInfo = this.form.fieldInfo[this.name];
2032
- if (!fieldInfo) return;
2033
- if (fieldInfo.instance !== this) return;
2034
- for (const [key, validationMeta] of Object.entries(fieldInfo.validationMetaMap)) {
2035
- validationMeta?.lastAbortController.abort();
2036
- fieldInfo.validationMetaMap[key] = void 0;
2037
- }
2038
- this.form.baseStore.setState((prev) => ({
2039
- ...prev,
2040
- fieldMetaBase: {
2041
- ...prev.fieldMetaBase,
2042
- [this.name]: {
2043
- ...defaultFieldMeta,
2044
- isTouched: prev.fieldMetaBase[this.name]?.isTouched ?? defaultFieldMeta.isTouched,
2045
- isBlurred: prev.fieldMetaBase[this.name]?.isBlurred ?? defaultFieldMeta.isBlurred,
2046
- isDirty: prev.fieldMetaBase[this.name]?.isDirty ?? defaultFieldMeta.isDirty
2047
- }
2048
- }
2049
- }));
2050
- fieldInfo.instance = null;
2051
- this.options.listeners?.onUnmount?.({
2052
- value: this.state.value,
2053
- fieldApi: this
2054
- });
2055
- this.form.options.listeners?.onFieldUnmount?.({
2056
- formApi: this.form,
2057
- fieldApi: this
2058
- });
2059
- };
2060
- };
2061
- this.update = (opts2) => {
2062
- this.options = opts2;
2063
- this.name = opts2.name;
2064
- if (!this.state.meta.isTouched && this.options.defaultValue !== void 0) {
2065
- if (!evaluate(this.form.getFieldValue(this.name), opts2.defaultValue)) this.form.setFieldValue(this.name, opts2.defaultValue, {
2066
- dontUpdateMeta: true,
2067
- dontValidate: true,
2068
- dontRunListeners: true
2069
- });
2070
- }
2071
- if (!this.form.getFieldMeta(this.name)) this.form.setFieldMeta(this.name, this.state.meta);
2072
- };
2073
- this.getValue = () => {
2074
- return this.form.getFieldValue(this.name);
2075
- };
2076
- this.setValue = (updater, options) => {
2077
- this.form.setFieldValue(this.name, updater, mergeOpts(options, {
2078
- dontRunListeners: true,
2079
- dontValidate: true
2080
- }));
2081
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2082
- if (!options?.dontValidate) this.validate("change");
2083
- };
2084
- this.getMeta = () => this.store.state.meta;
2085
- this.setMeta = (updater) => this.form.setFieldMeta(this.name, updater);
2086
- this.getInfo = () => this.form.getFieldInfo(this.name);
2087
- this.pushValue = (value, options) => {
2088
- this.form.pushFieldValue(this.name, value, mergeOpts(options, { dontRunListeners: true }));
2089
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2090
- };
2091
- this.insertValue = (index, value, options) => {
2092
- this.form.insertFieldValue(this.name, index, value, mergeOpts(options, { dontRunListeners: true }));
2093
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2094
- };
2095
- this.replaceValue = (index, value, options) => {
2096
- this.form.replaceFieldValue(this.name, index, value, mergeOpts(options, { dontRunListeners: true }));
2097
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2098
- };
2099
- this.removeValue = (index, options) => {
2100
- this.form.removeFieldValue(this.name, index, mergeOpts(options, { dontRunListeners: true }));
2101
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2102
- };
2103
- this.swapValues = (aIndex, bIndex, options) => {
2104
- this.form.swapFieldValues(this.name, aIndex, bIndex, mergeOpts(options, { dontRunListeners: true }));
2105
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2106
- };
2107
- this.moveValue = (aIndex, bIndex, options) => {
2108
- this.form.moveFieldValues(this.name, aIndex, bIndex, mergeOpts(options, { dontRunListeners: true }));
2109
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2110
- };
2111
- this.clearValues = (options) => {
2112
- this.form.clearFieldValues(this.name, mergeOpts(options, { dontRunListeners: true }));
2113
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2114
- };
2115
- this.getLinkedFields = (cause) => {
2116
- const fields = Object.values(this.form.fieldInfo);
2117
- const linkedFields = [];
2118
- for (const field of fields) {
2119
- if (!field.instance) continue;
2120
- if (!(field.instance instanceof FieldApi)) continue;
2121
- const { onChangeListenTo, onBlurListenTo } = field.instance.options.validators || {};
2122
- if (cause === "change" && onChangeListenTo?.includes(this.name)) linkedFields.push(field.instance);
2123
- if (cause === "blur" && onBlurListenTo?.includes(this.name)) linkedFields.push(field.instance);
2124
- }
2125
- return linkedFields;
2126
- };
2127
- this.validateSync = (cause, errorFromForm) => {
2128
- const validates = getSyncValidatorArray(cause, {
2129
- ...this.options,
2130
- form: this.form,
2131
- fieldName: this.name,
2132
- validationLogic: this.form.options.validationLogic || defaultValidationLogic
2133
- });
2134
- const linkedFieldValidates = this.getLinkedFields(cause).reduce((acc, field) => {
2135
- const fieldValidates = getSyncValidatorArray(cause, {
2136
- ...field.options,
2137
- form: field.form,
2138
- fieldName: field.name,
2139
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
2140
- });
2141
- fieldValidates.forEach((validate) => {
2142
- validate.field = field;
2143
- });
2144
- return acc.concat(fieldValidates);
2145
- }, []);
2146
- let hasErrored = false;
2147
- batch(() => {
2148
- const validateFieldFn = (field, validateObj) => {
2149
- const errorMapKey = getErrorMapKey$1(validateObj.cause);
2150
- const fieldLevelError = validateObj.validate ? normalizeError$1(field.runValidator({
2151
- validate: validateObj.validate,
2152
- value: {
2153
- value: field.store.state.value,
2154
- validationSource: "field",
2155
- fieldApi: field
2156
- },
2157
- type: "validate"
2158
- })) : void 0;
2159
- const formLevelError = errorFromForm[errorMapKey];
2160
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
2161
- formLevelError,
2162
- fieldLevelError
2163
- });
2164
- if (field.state.meta.errorMap?.[errorMapKey] !== newErrorValue) field.setMeta((prev) => ({
2165
- ...prev,
2166
- errorMap: {
2167
- ...prev.errorMap,
2168
- [errorMapKey]: newErrorValue
2169
- },
2170
- errorSourceMap: {
2171
- ...prev.errorSourceMap,
2172
- [errorMapKey]: newSource
2173
- }
2174
- }));
2175
- if (newErrorValue) hasErrored = true;
2176
- };
2177
- for (const validateObj of validates) validateFieldFn(this, validateObj);
2178
- for (const fieldValitateObj of linkedFieldValidates) {
2179
- if (!fieldValitateObj.validate) continue;
2180
- validateFieldFn(fieldValitateObj.field, fieldValitateObj);
2181
- }
2182
- });
2183
- const submitErrKey = getErrorMapKey$1("submit");
2184
- if (this.state.meta.errorMap?.[submitErrKey] && cause !== "submit" && !hasErrored) this.setMeta((prev) => ({
2185
- ...prev,
2186
- errorMap: {
2187
- ...prev.errorMap,
2188
- [submitErrKey]: void 0
2189
- },
2190
- errorSourceMap: {
2191
- ...prev.errorSourceMap,
2192
- [submitErrKey]: void 0
2193
- }
2194
- }));
2195
- return { hasErrored };
2196
- };
2197
- this.validateAsync = async (cause, formValidationResultPromise) => {
2198
- const validates = getAsyncValidatorArray(cause, {
2199
- ...this.options,
2200
- form: this.form,
2201
- fieldName: this.name,
2202
- validationLogic: this.form.options.validationLogic || defaultValidationLogic
2203
- });
2204
- const asyncFormValidationResults = await formValidationResultPromise;
2205
- const linkedFields = this.getLinkedFields(cause);
2206
- const linkedFieldValidates = linkedFields.reduce((acc, field) => {
2207
- const fieldValidates = getAsyncValidatorArray(cause, {
2208
- ...field.options,
2209
- form: field.form,
2210
- fieldName: field.name,
2211
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
2212
- });
2213
- fieldValidates.forEach((validate) => {
2214
- validate.field = field;
2215
- });
2216
- return acc.concat(fieldValidates);
2217
- }, []);
2218
- const validatesPromises = [];
2219
- const linkedPromises = [];
2220
- const hasAsyncValidators = validates.some((v) => v.validate) || linkedFieldValidates.some((v) => v.validate);
2221
- if (hasAsyncValidators) {
2222
- if (!this.state.meta.isValidating) this.setMeta((prev) => ({
2223
- ...prev,
2224
- isValidating: true
2225
- }));
2226
- for (const linkedField of linkedFields) linkedField.setMeta((prev) => ({
2227
- ...prev,
2228
- isValidating: true
2229
- }));
2230
- }
2231
- const validateFieldAsyncFn = (field, validateObj, promises) => {
2232
- const errorMapKey = getErrorMapKey$1(validateObj.cause);
2233
- const fieldInfo = field.getInfo();
2234
- fieldInfo.validationMetaMap[errorMapKey]?.lastAbortController.abort();
2235
- const controller = new AbortController();
2236
- fieldInfo.validationMetaMap[errorMapKey] = { lastAbortController: controller };
2237
- promises.push(new Promise(async (resolve) => {
2238
- let rawError;
2239
- try {
2240
- rawError = await new Promise((rawResolve, rawReject) => {
2241
- if (field.timeoutIds.validations[validateObj.cause]) clearTimeout(field.timeoutIds.validations[validateObj.cause]);
2242
- field.timeoutIds.validations[validateObj.cause] = setTimeout(async () => {
2243
- if (controller.signal.aborted) return rawResolve(void 0);
2244
- try {
2245
- rawResolve(await this.runValidator({
2246
- validate: validateObj.validate,
2247
- value: {
2248
- value: field.store.state.value,
2249
- fieldApi: field,
2250
- signal: controller.signal,
2251
- validationSource: "field"
2252
- },
2253
- type: "validateAsync"
2254
- }));
2255
- } catch (e) {
2256
- rawReject(e);
2257
- }
2258
- }, validateObj.debounceMs);
2259
- });
2260
- } catch (e) {
2261
- rawError = e;
2262
- }
2263
- if (controller.signal.aborted) return resolve(void 0);
2264
- const fieldLevelError = normalizeError$1(rawError);
2265
- const formLevelError = asyncFormValidationResults[field.name]?.[errorMapKey];
2266
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
2267
- formLevelError,
2268
- fieldLevelError
2269
- });
2270
- if (field.getInfo().instance !== field) return resolve(void 0);
2271
- field.setMeta((prev) => {
2272
- return {
2273
- ...prev,
2274
- errorMap: {
2275
- ...prev?.errorMap,
2276
- [errorMapKey]: newErrorValue
2277
- },
2278
- errorSourceMap: {
2279
- ...prev.errorSourceMap,
2280
- [errorMapKey]: newSource
2281
- }
2282
- };
2283
- });
2284
- resolve(newErrorValue);
2285
- }));
2286
- };
2287
- for (const validateObj of validates) {
2288
- if (!validateObj.validate) continue;
2289
- validateFieldAsyncFn(this, validateObj, validatesPromises);
2290
- }
2291
- for (const fieldValitateObj of linkedFieldValidates) {
2292
- if (!fieldValitateObj.validate) continue;
2293
- validateFieldAsyncFn(fieldValitateObj.field, fieldValitateObj, linkedPromises);
2294
- }
2295
- let results = [];
2296
- if (validatesPromises.length || linkedPromises.length) {
2297
- results = await Promise.all(validatesPromises);
2298
- await Promise.all(linkedPromises);
2299
- }
2300
- if (hasAsyncValidators) {
2301
- this.setMeta((prev) => ({
2302
- ...prev,
2303
- isValidating: false
2304
- }));
2305
- for (const linkedField of linkedFields) linkedField.setMeta((prev) => ({
2306
- ...prev,
2307
- isValidating: false
2308
- }));
2309
- }
2310
- return results.filter(Boolean);
2311
- };
2312
- this.validate = (cause, opts2) => {
2313
- if (!this.state.meta.isTouched) return [];
2314
- const encompassingGroups = opts2?.skipGroupValidation ? [] : Array.from(this.form.formGroupApis).filter((group) => this.name.startsWith(group.name));
2315
- let fieldsErrorMap = (opts2?.skipFormValidation ? { fieldsErrorMap: {} } : this.form.validateSync(cause)).fieldsErrorMap[this.name] ?? {};
2316
- if (!opts2?.skipFormValidation) for (const group of encompassingGroups) {
2317
- if (group.state.meta.submissionAttempts === 0) continue;
2318
- const { fieldsErrorMap: groupFormErrors } = this.form.validateSync(cause, {
2319
- group,
2320
- dontUpdateFormErrorMap: true,
2321
- filterFieldNames: (fieldName) => isFieldInGroup(group.name, fieldName)
2322
- });
2323
- fieldsErrorMap = {
2324
- ...fieldsErrorMap,
2325
- ...groupFormErrors[this.name] ?? {}
2326
- };
2327
- }
2328
- const { hasErrored } = this.validateSync(cause, fieldsErrorMap);
2329
- const groupHasErroredWeakMap = /* @__PURE__ */ new WeakMap();
2330
- for (const group of encompassingGroups) {
2331
- const { hasErrored: groupHasErrored } = group.validateSync(cause, {}, { skipRelatedFieldValidation: true });
2332
- groupHasErroredWeakMap.set(group, groupHasErrored);
2333
- }
2334
- if (hasErrored && !this.options.asyncAlways) {
2335
- this.getInfo().validationMetaMap[getErrorMapKey$1(cause)]?.lastAbortController.abort();
2336
- const groupErrors = [];
2337
- for (const group of encompassingGroups) {
2338
- group.getInfo().validationMetaMap[getErrorMapKey$1(cause)]?.lastAbortController.abort();
2339
- groupErrors.push(group.state.meta.errors);
2340
- }
2341
- return [...this.state.meta.errors, ...groupErrors.flat()];
2342
- }
2343
- const formValidationResultPromise = opts2?.skipFormValidation ? Promise.resolve({}) : this.form.validateAsync(cause);
2344
- const fieldAsyncResults = this.validateAsync(cause, formValidationResultPromise);
2345
- const groupAsyncResults = [];
2346
- for (const group of encompassingGroups) {
2347
- if (groupHasErroredWeakMap.get(group) && !group.options.asyncAlways) continue;
2348
- groupAsyncResults.push(group.validateAsync(cause, formValidationResultPromise, { skipRelatedFieldValidation: true }));
2349
- }
2350
- if (groupAsyncResults.length === 0) return fieldAsyncResults;
2351
- return Promise.all([fieldAsyncResults, ...groupAsyncResults]).then((results) => results.flat());
2352
- };
2353
- this.handleChange = (updater) => {
2354
- this.setValue(updater);
2355
- };
2356
- this.handleBlur = () => {
2357
- if (!this.state.meta.isTouched) this.setMeta((prev) => ({
2358
- ...prev,
2359
- isTouched: true
2360
- }));
2361
- if (!this.state.meta.isBlurred) this.setMeta((prev) => ({
2362
- ...prev,
2363
- isBlurred: true
2364
- }));
2365
- this.validate("blur");
2366
- this.triggerOnBlurListener();
2367
- };
2368
- this.setErrorMap = (errorMap) => {
2369
- this.setMeta((prev) => ({
2370
- ...prev,
2371
- errorMap: {
2372
- ...prev.errorMap,
2373
- ...errorMap
2374
- }
2375
- }));
2376
- };
2377
- this.parseValueWithSchema = (schema) => {
2378
- return standardSchemaValidators.validate({
2379
- value: this.state.value,
2380
- validationSource: "field"
2381
- }, schema);
2382
- };
2383
- this.parseValueWithSchemaAsync = (schema) => {
2384
- return standardSchemaValidators.validateAsync({
2385
- value: this.state.value,
2386
- validationSource: "field"
2387
- }, schema);
2388
- };
2389
- this.triggerOnBlurListener = () => {
2390
- const formDebounceMs = this.form.options.listeners?.onBlurDebounceMs;
2391
- if (formDebounceMs && formDebounceMs > 0) {
2392
- if (this.timeoutIds.formListeners.blur) clearTimeout(this.timeoutIds.formListeners.blur);
2393
- this.timeoutIds.formListeners.blur = setTimeout(() => {
2394
- this.form.options.listeners?.onBlur?.({
2395
- formApi: this.form,
2396
- fieldApi: this
2397
- });
2398
- }, formDebounceMs);
2399
- } else this.form.options.listeners?.onBlur?.({
2400
- formApi: this.form,
2401
- fieldApi: this
2402
- });
2403
- const fieldDebounceMs = this.options.listeners?.onBlurDebounceMs;
2404
- if (fieldDebounceMs && fieldDebounceMs > 0) {
2405
- if (this.timeoutIds.listeners.blur) clearTimeout(this.timeoutIds.listeners.blur);
2406
- this.timeoutIds.listeners.blur = setTimeout(() => {
2407
- this.options.listeners?.onBlur?.({
2408
- value: this.state.value,
2409
- fieldApi: this
2410
- });
2411
- }, fieldDebounceMs);
2412
- } else this.options.listeners?.onBlur?.({
2413
- value: this.state.value,
2414
- fieldApi: this
2415
- });
2416
- };
2417
- this.triggerOnChangeListener = () => {
2418
- const formDebounceMs = this.form.options.listeners?.onChangeDebounceMs;
2419
- if (formDebounceMs && formDebounceMs > 0) {
2420
- if (this.timeoutIds.formListeners.change) clearTimeout(this.timeoutIds.formListeners.change);
2421
- this.timeoutIds.formListeners.change = setTimeout(() => {
2422
- this.form.options.listeners?.onChange?.({
2423
- formApi: this.form,
2424
- fieldApi: this
2425
- });
2426
- }, formDebounceMs);
2427
- } else this.form.options.listeners?.onChange?.({
2428
- formApi: this.form,
2429
- fieldApi: this
2430
- });
2431
- const fieldDebounceMs = this.options.listeners?.onChangeDebounceMs;
2432
- if (fieldDebounceMs && fieldDebounceMs > 0) {
2433
- if (this.timeoutIds.listeners.change) clearTimeout(this.timeoutIds.listeners.change);
2434
- this.timeoutIds.listeners.change = setTimeout(() => {
2435
- this.options.listeners?.onChange?.({
2436
- value: this.state.value,
2437
- fieldApi: this
2438
- });
2439
- }, fieldDebounceMs);
2440
- } else this.options.listeners?.onChange?.({
2441
- value: this.state.value,
2442
- fieldApi: this
2443
- });
2444
- for (const group of this.form.formGroupApis) if (isFieldInGroup(group.name, this.name)) group.triggerOnChangeListener();
2445
- };
2446
- this.triggerOnSubmitListener = () => {
2447
- this.options.listeners?.onSubmit?.({
2448
- value: this.state.value,
2449
- fieldApi: this
2450
- });
2451
- };
2452
- this.form = opts.form;
2453
- this.name = opts.name;
2454
- this.options = opts;
2455
- this.timeoutIds = {
2456
- validations: {},
2457
- listeners: {},
2458
- formListeners: {}
2459
- };
2460
- this.store = createStore((prevVal) => {
2461
- this.form.store.get();
2462
- const meta = this.form.getFieldMeta(this.name) ?? {
2463
- ...defaultFieldMeta,
2464
- ...opts.defaultMeta
2465
- };
2466
- let value = this.form.getFieldValue(this.name);
2467
- if (!meta.isTouched && value === void 0 && this.options.defaultValue !== void 0 && !evaluate(value, this.options.defaultValue)) value = this.options.defaultValue;
2468
- if (prevVal && prevVal.value === value && prevVal.meta === meta) return prevVal;
2469
- return {
2470
- value,
2471
- meta
2472
- };
2473
- });
2474
- }
2475
- /**
2476
- * The current field state.
2477
- */
2478
- get state() {
2479
- return this.store.state;
2480
- }
2481
- /**
2482
- * @private
2483
- */
2484
- runValidator(props) {
2485
- if (isStandardSchemaValidator(props.validate)) return standardSchemaValidators[props.type](props.value, props.validate);
2486
- return props.validate(props.value);
2487
- }
2488
- };
2489
- function normalizeError$1(rawError) {
2490
- if (rawError) return rawError;
2491
- }
2492
- function getErrorMapKey$1(cause) {
2493
- switch (cause) {
2494
- case "submit": return "onSubmit";
2495
- case "blur": return "onBlur";
2496
- case "mount": return "onMount";
2497
- case "server": return "onServer";
2498
- case "dynamic": return "onDynamic";
2499
- default: return "onChange";
2500
- }
2501
- }
2502
- //#endregion
2503
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/FormGroupApi.js
2504
- function getDefaultFormGroupState(defaultState) {
2505
- return {
2506
- isSubmitted: defaultState.isSubmitted ?? false,
2507
- isSubmitting: defaultState.isSubmitting ?? false,
2508
- isValidating: defaultState.isValidating ?? false,
2509
- submissionAttempts: defaultState.submissionAttempts ?? 0,
2510
- isSubmitSuccessful: defaultState.isSubmitSuccessful ?? false
2511
- };
2512
- }
2513
- function getDefaultFormGroupMeta(defaultMeta) {
2514
- return {
2515
- ...defaultFieldMeta,
2516
- ...defaultMeta,
2517
- errors: [],
2518
- isPristine: true,
2519
- isValid: true,
2520
- isDefaultValue: true,
2521
- isFieldsValidating: false,
2522
- isFieldsValid: true,
2523
- isGroupValid: true,
2524
- canSubmit: true,
2525
- isSubmitting: false,
2526
- isSubmitted: false,
2527
- isValidating: false,
2528
- submissionAttempts: 0,
2529
- isSubmitSuccessful: false
2530
- };
2531
- }
2532
- var FormGroupApi = class FormGroupApi {
2533
- constructor(opts) {
2534
- this.options = {};
2535
- this.setFormGroupState = (updater) => {
2536
- this.form.baseStore.setState((prev) => {
2537
- const prevGroupState = prev.formGroupStateBase[this.name] ?? getDefaultFormGroupState({});
2538
- return {
2539
- ...prev,
2540
- formGroupStateBase: {
2541
- ...prev.formGroupStateBase,
2542
- [this.name]: updater(prevGroupState)
2543
- }
2544
- };
2545
- });
2546
- };
2547
- this._lastDistributedFieldNames = {};
2548
- this.update = (opts2) => {
2549
- this.options = opts2;
2550
- this.name = opts2.name;
2551
- if (!this.state.meta.isTouched && this.options.defaultValue !== void 0) {
2552
- if (!evaluate(this.form.getFieldValue(this.name), opts2.defaultValue)) this.form.setFieldValue(this.name, opts2.defaultValue, {
2553
- dontUpdateMeta: true,
2554
- dontValidate: true,
2555
- dontRunListeners: true
2556
- });
2557
- }
2558
- if (!this.form.getFieldMeta(this.name)) this.form.setFieldMeta(this.name, {
2559
- ...defaultFieldMeta,
2560
- ...this.options.defaultMeta
2561
- });
2562
- };
2563
- this.mount = () => {
2564
- this.update(this.options);
2565
- this.form.formGroupApis.add(this);
2566
- this.fieldInfo.instance = this;
2567
- this.form.baseStore.setState((prev) => ({
2568
- ...prev,
2569
- formGroupStateBase: {
2570
- ...prev.formGroupStateBase,
2571
- [this.name]: prev.formGroupStateBase[this.name] ?? getDefaultFormGroupState({ ...this.options.defaultState })
2572
- }
2573
- }));
2574
- const { onMount } = this.options.validators || {};
2575
- if (onMount) {
2576
- const rawError = this.runValidator({
2577
- validate: onMount,
2578
- value: {
2579
- value: this.state.value,
2580
- groupApi: this,
2581
- validationSource: "form"
2582
- },
2583
- type: "validate"
2584
- });
2585
- let groupOwnRawError = rawError;
2586
- let groupFieldErrors = void 0;
2587
- if (isGlobalGroupValidationError(rawError)) {
2588
- groupOwnRawError = rawError.group;
2589
- groupFieldErrors = rawError.fields;
2590
- }
2591
- const error = normalizeError(groupOwnRawError);
2592
- if (error) this.setMeta((prev) => ({
2593
- ...prev,
2594
- errorMap: {
2595
- ...prev.errorMap,
2596
- onMount: error
2597
- },
2598
- errorSourceMap: {
2599
- ...prev.errorSourceMap,
2600
- onMount: "field"
2601
- }
2602
- }));
2603
- this.distributeFieldErrors("onMount", groupFieldErrors);
2604
- }
2605
- this.options.listeners?.onMount?.({
2606
- value: this.state.value,
2607
- groupApi: this
2608
- });
2609
- return () => {
2610
- for (const [key, timeout] of Object.entries(this.timeoutIds.validations)) if (timeout) {
2611
- clearTimeout(timeout);
2612
- this.timeoutIds.validations[key] = null;
2613
- }
2614
- for (const [key, timeout] of Object.entries(this.timeoutIds.listeners)) if (timeout) {
2615
- clearTimeout(timeout);
2616
- this.timeoutIds.listeners[key] = null;
2617
- }
2618
- for (const [key, timeout] of Object.entries(this.timeoutIds.formListeners)) if (timeout) {
2619
- clearTimeout(timeout);
2620
- this.timeoutIds.formListeners[key] = null;
2621
- }
2622
- if (this.fieldInfo.instance !== this) return;
2623
- for (const [key, validationMeta] of Object.entries(this.fieldInfo.validationMetaMap)) {
2624
- validationMeta?.lastAbortController.abort();
2625
- this.fieldInfo.validationMetaMap[key] = void 0;
2626
- }
2627
- this.form.formGroupApis.delete(this);
2628
- this.form.baseStore.setState((prev) => ({
2629
- ...prev,
2630
- formGroupStateBase: {
2631
- ...prev.formGroupStateBase,
2632
- [this.name]: getDefaultFormGroupState({})
2633
- }
2634
- }));
2635
- this.fieldInfo.instance = null;
2636
- this.options.listeners?.onUnmount?.({
2637
- value: this.state.value,
2638
- groupApi: this
2639
- });
2640
- };
2641
- };
2642
- this.setValue = (updater, options) => {
2643
- this.form.setFieldValue(this.name, updater, mergeOpts(options, {
2644
- dontRunListeners: true,
2645
- dontValidate: true
2646
- }));
2647
- if (!options?.dontRunListeners) this.triggerOnChangeListener();
2648
- if (!options?.dontValidate) this.validate("change");
2649
- };
2650
- this.getMeta = () => this.store.state.meta;
2651
- this.setMeta = (updater) => this.form.setFieldMeta(this.name, updater);
2652
- this.getInfo = () => this.fieldInfo;
2653
- this.getRelatedFields = () => {
2654
- const fields = Object.values(this.form.fieldInfo);
2655
- const relatedFields = [];
2656
- for (const field of fields) {
2657
- if (!field.instance) continue;
2658
- if (!(field.instance instanceof FieldApi)) continue;
2659
- if (field.instance.name.startsWith(this.name)) relatedFields.push(field.instance);
2660
- }
2661
- return relatedFields;
2662
- };
2663
- this.getRelatedFieldMetasDerived = () => {
2664
- const fields = Object.entries(this.form.fieldMetaDerived.state);
2665
- const relatedFieldMetas = [];
2666
- for (const [fieldName, fieldMeta] of fields) {
2667
- if (fieldName === this.name) continue;
2668
- if (isFieldInGroup(this.name, fieldName)) relatedFieldMetas.push({
2669
- ...fieldMeta,
2670
- name: fieldName
2671
- });
2672
- }
2673
- return relatedFieldMetas;
2674
- };
2675
- this.buildChildFieldName = (relativeName) => {
2676
- if (relativeName === "") return this.name;
2677
- if (relativeName.startsWith("[")) return `${this.name}${relativeName}`;
2678
- return `${this.name}.${relativeName}`;
2679
- };
2680
- this.distributeFieldErrors = (errorMapKey, fieldErrors) => {
2681
- const previousNames = this._lastDistributedFieldNames[errorMapKey] ?? /* @__PURE__ */ new Set();
2682
- const currentNames = /* @__PURE__ */ new Set();
2683
- if (fieldErrors) for (const [relativeName, err] of Object.entries(fieldErrors)) {
2684
- if (err === void 0 || err === null || err === false) continue;
2685
- currentNames.add(this.buildChildFieldName(relativeName));
2686
- }
2687
- const allNames = /* @__PURE__ */ new Set([...previousNames, ...currentNames]);
2688
- let hasErrored = false;
2689
- for (const fullName of allNames) {
2690
- const relativeName = fullName.startsWith(this.name + "[") ? fullName.slice(this.name.length) : fullName.slice(this.name.length + 1);
2691
- const newFormValidatorError = fieldErrors?.[relativeName];
2692
- const fieldMeta = this.form.getFieldMeta(fullName);
2693
- if (!fieldMeta && !newFormValidatorError) continue;
2694
- const previousErrorValue = fieldMeta?.errorMap[errorMapKey];
2695
- const { newErrorValue, newSource } = determineFormLevelErrorSourceAndValue({
2696
- newFormValidatorError,
2697
- isPreviousErrorFromFormValidator: fieldMeta?.errorSourceMap[errorMapKey] === "form",
2698
- previousErrorValue
2699
- });
2700
- if (newErrorValue) hasErrored = true;
2701
- if (previousErrorValue === newErrorValue && fieldMeta?.errorSourceMap[errorMapKey] === newSource) continue;
2702
- this.form.setFieldMeta(fullName, (prev) => ({
2703
- ...prev,
2704
- errorMap: {
2705
- ...prev.errorMap,
2706
- [errorMapKey]: newErrorValue
2707
- },
2708
- errorSourceMap: {
2709
- ...prev.errorSourceMap,
2710
- [errorMapKey]: newSource
2711
- }
2712
- }));
2713
- }
2714
- this._lastDistributedFieldNames[errorMapKey] = currentNames;
2715
- return hasErrored;
2716
- };
2717
- this.validateSync = (cause, errorFromForm, opts2 = {}) => {
2718
- const validates = getSyncValidatorArray(cause, {
2719
- ...this.options,
2720
- form: this.form,
2721
- group: this,
2722
- validationLogic: this.options.validationLogic || this.form.options.validationLogic || defaultValidationLogic
2723
- });
2724
- const relatedFieldValidates = (opts2.skipRelatedFieldValidation ? [] : this.getRelatedFields()).reduce((acc, field) => {
2725
- const fieldValidates = getSyncValidatorArray(cause, {
2726
- ...field.options,
2727
- form: field.form,
2728
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
2729
- });
2730
- fieldValidates.forEach((validate) => {
2731
- validate.field = field;
2732
- });
2733
- return acc.concat(fieldValidates);
2734
- }, []);
2735
- let hasErrored = false;
2736
- batch(() => {
2737
- const validateFieldOrGroupFn = (fieldOrGroup, validateObj) => {
2738
- const errorMapKey = getErrorMapKey(validateObj.cause);
2739
- const isGroup = fieldOrGroup === this;
2740
- let rawError = void 0;
2741
- if (validateObj.validate) rawError = fieldOrGroup.runValidator({
2742
- validate: validateObj.validate,
2743
- value: {
2744
- value: fieldOrGroup.store.state.value,
2745
- validationSource: isGroup ? "form" : "field",
2746
- ...fieldOrGroup instanceof FormGroupApi ? { groupApi: fieldOrGroup } : { fieldApi: fieldOrGroup }
2747
- },
2748
- type: "validate"
2749
- });
2750
- let groupOwnRawError = rawError;
2751
- let groupFieldErrors = void 0;
2752
- if (isGroup && isGlobalGroupValidationError(rawError)) {
2753
- groupOwnRawError = rawError.group;
2754
- groupFieldErrors = rawError.fields;
2755
- }
2756
- const fieldLevelError = normalizeError(groupOwnRawError);
2757
- const formLevelError = errorFromForm[errorMapKey];
2758
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
2759
- formLevelError,
2760
- fieldLevelError
2761
- });
2762
- if (fieldOrGroup.state.meta.errorMap?.[errorMapKey] !== newErrorValue) fieldOrGroup.setMeta((prev) => ({
2763
- ...prev,
2764
- errorMap: {
2765
- ...prev.errorMap,
2766
- [errorMapKey]: newErrorValue
2767
- },
2768
- errorSourceMap: {
2769
- ...prev.errorSourceMap,
2770
- [errorMapKey]: newSource
2771
- }
2772
- }));
2773
- if (newErrorValue) hasErrored = true;
2774
- if (isGroup) {
2775
- if (this.distributeFieldErrors(errorMapKey, groupFieldErrors)) hasErrored = true;
2776
- }
2777
- };
2778
- for (const validateObj of validates) validateFieldOrGroupFn(this, validateObj);
2779
- for (const fieldValidateObj of relatedFieldValidates) {
2780
- if (!fieldValidateObj.validate) continue;
2781
- validateFieldOrGroupFn(fieldValidateObj.field, fieldValidateObj);
2782
- }
2783
- });
2784
- const submitErrKey = getErrorMapKey("submit");
2785
- if (this.state.meta.errorMap?.[submitErrKey] && cause !== "submit" && !hasErrored) this.setMeta((prev) => ({
2786
- ...prev,
2787
- errorMap: {
2788
- ...prev.errorMap,
2789
- [submitErrKey]: void 0
2790
- },
2791
- errorSourceMap: {
2792
- ...prev.errorSourceMap,
2793
- [submitErrKey]: void 0
2794
- }
2795
- }));
2796
- return { hasErrored };
2797
- };
2798
- this.validateAsync = async (cause, formValidationResultPromise, opts2 = {}) => {
2799
- const validates = getAsyncValidatorArray(cause, {
2800
- ...this.options,
2801
- form: this.form,
2802
- group: this,
2803
- validationLogic: this.options.validationLogic || this.form.options.validationLogic || defaultValidationLogic
2804
- });
2805
- const asyncFormValidationResults = await formValidationResultPromise;
2806
- const relatedFields = opts2.skipRelatedFieldValidation ? [] : this.getRelatedFields();
2807
- const relatedFieldValidates = relatedFields.reduce((acc, field) => {
2808
- const fieldValidates = getAsyncValidatorArray(cause, {
2809
- ...field.options,
2810
- form: field.form,
2811
- validationLogic: field.form.options.validationLogic || defaultValidationLogic
2812
- });
2813
- fieldValidates.forEach((validate) => {
2814
- validate.field = field;
2815
- });
2816
- return acc.concat(fieldValidates);
2817
- }, []);
2818
- const validatesPromises = [];
2819
- const linkedPromises = [];
2820
- const hasAsyncValidators = validates.some((v) => v.validate) || relatedFieldValidates.some((v) => v.validate);
2821
- if (hasAsyncValidators) {
2822
- if (!this.state.meta.isValidating) this.setMeta((prev) => ({
2823
- ...prev,
2824
- isValidating: true
2825
- }));
2826
- for (const linkedField of relatedFields) linkedField.setMeta((prev) => ({
2827
- ...prev,
2828
- isValidating: true
2829
- }));
2830
- }
2831
- const validateFieldOrGroupAsyncFn = (fieldOrGroup, validateObj, promises) => {
2832
- const errorMapKey = getErrorMapKey(validateObj.cause);
2833
- const fieldInfo = fieldOrGroup.getInfo();
2834
- fieldInfo.validationMetaMap[errorMapKey]?.lastAbortController.abort();
2835
- const controller = new AbortController();
2836
- fieldInfo.validationMetaMap[errorMapKey] = { lastAbortController: controller };
2837
- const isGroup = fieldOrGroup === this;
2838
- promises.push(new Promise(async (resolve) => {
2839
- let rawError;
2840
- try {
2841
- rawError = await new Promise((rawResolve, rawReject) => {
2842
- if (fieldOrGroup.timeoutIds.validations[validateObj.cause]) clearTimeout(fieldOrGroup.timeoutIds.validations[validateObj.cause]);
2843
- fieldOrGroup.timeoutIds.validations[validateObj.cause] = setTimeout(async () => {
2844
- if (controller.signal.aborted) return rawResolve(void 0);
2845
- try {
2846
- rawResolve(await this.runValidator({
2847
- validate: validateObj.validate,
2848
- value: {
2849
- value: fieldOrGroup.store.state.value,
2850
- signal: controller.signal,
2851
- validationSource: isGroup ? "form" : "field",
2852
- ...fieldOrGroup instanceof FormGroupApi ? { groupApi: fieldOrGroup } : { fieldApi: fieldOrGroup }
2853
- },
2854
- type: "validateAsync"
2855
- }));
2856
- } catch (e) {
2857
- rawReject(e);
2858
- }
2859
- }, validateObj.debounceMs);
2860
- });
2861
- } catch (e) {
2862
- rawError = e;
2863
- }
2864
- if (controller.signal.aborted) return resolve(void 0);
2865
- let groupOwnRawError = rawError;
2866
- let groupFieldErrors = void 0;
2867
- if (isGroup && isGlobalGroupValidationError(rawError)) {
2868
- groupOwnRawError = rawError.group;
2869
- groupFieldErrors = rawError.fields;
2870
- }
2871
- const fieldLevelError = normalizeError(groupOwnRawError);
2872
- const formLevelError = asyncFormValidationResults[fieldOrGroup.name]?.[errorMapKey];
2873
- const { newErrorValue, newSource } = determineFieldLevelErrorSourceAndValue({
2874
- formLevelError,
2875
- fieldLevelError
2876
- });
2877
- if (fieldOrGroup.getInfo().instance !== fieldOrGroup) return resolve(void 0);
2878
- fieldOrGroup.setMeta((prev) => {
2879
- return {
2880
- ...prev,
2881
- errorMap: {
2882
- ...prev?.errorMap,
2883
- [errorMapKey]: newErrorValue
2884
- },
2885
- errorSourceMap: {
2886
- ...prev.errorSourceMap,
2887
- [errorMapKey]: newSource
2888
- }
2889
- };
2890
- });
2891
- if (isGroup) this.distributeFieldErrors(errorMapKey, groupFieldErrors);
2892
- resolve(newErrorValue);
2893
- }));
2894
- };
2895
- for (const validateObj of validates) {
2896
- if (!validateObj.validate) continue;
2897
- validateFieldOrGroupAsyncFn(this, validateObj, validatesPromises);
2898
- }
2899
- for (const fieldValitateObj of relatedFieldValidates) {
2900
- if (!fieldValitateObj.validate) continue;
2901
- validateFieldOrGroupAsyncFn(fieldValitateObj.field, fieldValitateObj, linkedPromises);
2902
- }
2903
- let results = [];
2904
- if (validatesPromises.length || linkedPromises.length) {
2905
- results = await Promise.all(validatesPromises);
2906
- await Promise.all(linkedPromises);
2907
- }
2908
- if (hasAsyncValidators) {
2909
- this.setMeta((prev) => ({
2910
- ...prev,
2911
- isValidating: false
2912
- }));
2913
- for (const linkedField of relatedFields) linkedField.setMeta((prev) => ({
2914
- ...prev,
2915
- isValidating: false
2916
- }));
2917
- }
2918
- return results.filter(Boolean);
2919
- };
2920
- this.validateAllFields = async (cause) => {
2921
- const fieldValidationPromises = [];
2922
- batch(() => {
2923
- Object.values(this.getRelatedFields()).forEach((fieldInstance) => {
2924
- fieldValidationPromises.push(Promise.resolve().then(() => fieldInstance.validate(cause, {
2925
- skipFormValidation: true,
2926
- skipGroupValidation: true
2927
- })));
2928
- if (!fieldInstance.store.state.meta.isTouched) fieldInstance.setMeta((prev) => ({
2929
- ...prev,
2930
- isTouched: true
2931
- }));
2932
- });
2933
- });
2934
- return (await Promise.all(fieldValidationPromises)).flat();
2935
- };
2936
- this.validateArrayFieldsStartingFrom = (field, index, cause) => {
2937
- return this.form.validateArrayFieldsStartingFrom(field, index, cause);
2938
- };
2939
- this.validateField = (field, cause) => {
2940
- return this.form.validateField(field, cause);
2941
- };
2942
- this.getFieldValue = (field) => {
2943
- return this.form.getFieldValue(field);
2944
- };
2945
- this.getFieldMeta = (field) => {
2946
- return this.form.getFieldMeta(field);
2947
- };
2948
- this.setFieldMeta = (field, updater) => {
2949
- return this.form.setFieldMeta(field, updater);
2950
- };
2951
- this.setFieldValue = (field, value) => {
2952
- return this.form.setFieldValue(field, value);
2953
- };
2954
- this.deleteField = (field) => {
2955
- return this.form.deleteField(field);
2956
- };
2957
- this.pushFieldValue = (field, value) => {
2958
- return this.form.pushFieldValue(field, value);
2959
- };
2960
- this.insertFieldValue = (field, index, value) => {
2961
- return this.form.insertFieldValue(field, index, value);
2962
- };
2963
- this.replaceFieldValue = (field, index, value) => {
2964
- return this.form.replaceFieldValue(field, index, value);
2965
- };
2966
- this.swapFieldValues = (field, index1, index2) => {
2967
- return this.form.swapFieldValues(field, index1, index2);
2968
- };
2969
- this.moveFieldValues = (field, fromIndex, toIndex) => {
2970
- return this.form.moveFieldValues(field, fromIndex, toIndex);
2971
- };
2972
- this.clearFieldValues = (field) => {
2973
- return this.form.clearFieldValues(field);
2974
- };
2975
- this.resetField = (field) => {
2976
- return this.form.resetField(field);
2977
- };
2978
- this.removeFieldValue = (field, index) => {
2979
- return this.form.removeFieldValue(field, index);
2980
- };
2981
- this.areRelatedFieldsValid = () => {
2982
- return Object.values(this.getRelatedFields()).every((field) => field.state.meta.isValid);
2983
- };
2984
- this.validate = (cause, opts2) => {
2985
- const { fieldsErrorMap } = opts2?.skipFormValidation ? { fieldsErrorMap: {} } : this.form.validateSync(cause, {
2986
- dontUpdateFormErrorMap: true,
2987
- filterFieldNames: (fieldName) => isFieldInGroup(this.name, fieldName)
2988
- });
2989
- const { hasErrored } = this.validateSync(cause, fieldsErrorMap[this.name] ?? {}, { skipRelatedFieldValidation: opts2?.skipRelatedFieldValidation });
2990
- if (hasErrored && !this.options.asyncAlways) {
2991
- this.getInfo().validationMetaMap[getErrorMapKey(cause)]?.lastAbortController.abort();
2992
- return this.state.meta.errors;
2993
- }
2994
- const formValidationResultPromise = opts2?.skipFormValidation ? Promise.resolve({}) : this.form.validateAsync(cause, {
2995
- dontUpdateFormErrorMap: true,
2996
- filterFieldNames: (fieldName) => isFieldInGroup(this.name, fieldName)
2997
- });
2998
- return this.validateAsync(cause, formValidationResultPromise, { skipRelatedFieldValidation: opts2?.skipRelatedFieldValidation });
2999
- };
3000
- this.triggerOnChangeListener = () => {
3001
- const formDebounceMs = this.form.options.listeners?.onChangeGroupDebounceMs;
3002
- if (formDebounceMs && formDebounceMs > 0) {
3003
- if (this.timeoutIds.formListeners.change) clearTimeout(this.timeoutIds.formListeners.change);
3004
- this.timeoutIds.formListeners.change = setTimeout(() => {
3005
- this.form.options.listeners?.onChangeGroup?.({
3006
- formApi: this.form,
3007
- groupApi: this
3008
- });
3009
- }, formDebounceMs);
3010
- } else this.form.options.listeners?.onChangeGroup?.({
3011
- formApi: this.form,
3012
- groupApi: this
3013
- });
3014
- const fieldDebounceMs = this.options.listeners?.onChangeDebounceMs;
3015
- if (fieldDebounceMs && fieldDebounceMs > 0) {
3016
- if (this.timeoutIds.listeners.change) clearTimeout(this.timeoutIds.listeners.change);
3017
- this.timeoutIds.listeners.change = setTimeout(() => {
3018
- this.options.listeners?.onChange?.({
3019
- value: this.state.value,
3020
- groupApi: this
3021
- });
3022
- }, fieldDebounceMs);
3023
- } else this.options.listeners?.onChange?.({
3024
- value: this.state.value,
3025
- groupApi: this
3026
- });
3027
- };
3028
- this.triggerOnSubmitListener = () => {
3029
- this.options.listeners?.onSubmit?.({
3030
- value: this.state.value,
3031
- groupApi: this
3032
- });
3033
- };
3034
- this._handleSubmit = async (submitMeta) => {
3035
- this.setFormGroupState((old) => ({
3036
- ...old,
3037
- isSubmitted: false,
3038
- submissionAttempts: old.submissionAttempts + 1,
3039
- isSubmitSuccessful: false
3040
- }));
3041
- batch(() => {
3042
- Object.values(this.getRelatedFields()).forEach((field) => {
3043
- if (!field.state.meta.isTouched) field.setMeta((prev) => ({
3044
- ...prev,
3045
- isTouched: true
3046
- }));
3047
- });
3048
- });
3049
- const submitMetaArg = submitMeta ?? this.options.onSubmitMeta;
3050
- this.setFormGroupState((d) => ({
3051
- ...d,
3052
- isSubmitting: true
3053
- }));
3054
- const done = () => {
3055
- this.setFormGroupState((prev) => ({
3056
- ...prev,
3057
- isSubmitting: false
3058
- }));
3059
- };
3060
- await this.validateAllFields("submit");
3061
- if (!this.areRelatedFieldsValid()) {
3062
- done();
3063
- this.options.onGroupSubmitInvalid?.({
3064
- value: this.state.value,
3065
- groupApi: this,
3066
- meta: submitMetaArg
3067
- });
3068
- return;
3069
- }
3070
- await this.validate("submit", { skipRelatedFieldValidation: true });
3071
- if (!this.areRelatedFieldsValid() || !this.state.meta.isValid) {
3072
- done();
3073
- this.options.onGroupSubmitInvalid?.({
3074
- value: this.state.value,
3075
- groupApi: this,
3076
- meta: submitMetaArg
3077
- });
3078
- return;
3079
- }
3080
- batch(() => {
3081
- Object.values(this.getRelatedFields()).forEach((field) => {
3082
- field.options.listeners?.onGroupSubmit?.({
3083
- value: field.state.value,
3084
- fieldApi: field
3085
- });
3086
- });
3087
- });
3088
- this.options.listeners?.onSubmit?.({
3089
- groupApi: this,
3090
- value: this.state.value
3091
- });
3092
- try {
3093
- await this.options.onGroupSubmit?.({
3094
- value: this.state.value,
3095
- groupApi: this,
3096
- meta: submitMetaArg
3097
- });
3098
- batch(() => {
3099
- this.setFormGroupState((prev) => ({
3100
- ...prev,
3101
- isSubmitted: true,
3102
- isSubmitSuccessful: true
3103
- }));
3104
- done();
3105
- });
3106
- } catch (err) {
3107
- this.setFormGroupState((prev) => ({
3108
- ...prev,
3109
- isSubmitSuccessful: false
3110
- }));
3111
- done();
3112
- throw err;
3113
- }
3114
- };
3115
- this.form = opts.form;
3116
- this.name = opts.name;
3117
- this.options = opts;
3118
- this.timeoutIds = {
3119
- validations: {},
3120
- listeners: {},
3121
- formListeners: {}
3122
- };
3123
- this.fieldInfo = {
3124
- instance: null,
3125
- validationMetaMap: {
3126
- onChange: void 0,
3127
- onBlur: void 0,
3128
- onSubmit: void 0,
3129
- onMount: void 0,
3130
- onServer: void 0,
3131
- onDynamic: void 0
3132
- }
3133
- };
3134
- this.store = createStore((prevVal) => {
3135
- this.form.formGroupMetaDerived.get();
3136
- this.form.baseStore.get();
3137
- const meta = this.form.getFormGroupMeta(this.name) ?? getDefaultFormGroupMeta(opts.defaultMeta);
3138
- let value = this.form.getFieldValue(this.name);
3139
- if (!meta.isTouched && value === void 0 && this.options.defaultValue !== void 0 && !evaluate(value, this.options.defaultValue)) value = this.options.defaultValue;
3140
- if (prevVal && prevVal.value === value && prevVal.meta === meta) return prevVal;
3141
- return {
3142
- value,
3143
- meta
3144
- };
3145
- });
3146
- this.handleSubmit = this.handleSubmit.bind(this);
3147
- }
3148
- /**
3149
- * The current field state.
3150
- */
3151
- get state() {
3152
- return this.store.state;
3153
- }
3154
- /**
3155
- * @private
3156
- */
3157
- runValidator(props) {
3158
- if (isStandardSchemaValidator(props.validate)) {
3159
- const result = standardSchemaValidators[props.type](props.value, props.validate);
3160
- if (props.type === "validate") return remapStandardSchemaResultForGroup(result);
3161
- return result.then(remapStandardSchemaResultForGroup);
3162
- }
3163
- return props.validate(props.value);
3164
- }
3165
- handleSubmit(submitMeta) {
3166
- return this._handleSubmit(submitMeta);
3167
- }
3168
- };
3169
- function normalizeError(rawError) {
3170
- if (rawError) return rawError;
3171
- }
3172
- function isGlobalGroupValidationError(error) {
3173
- return !!error && typeof error === "object" && "fields" in error;
3174
- }
3175
- function remapStandardSchemaResultForGroup(result) {
3176
- if (!result || typeof result !== "object") return result;
3177
- if (!("form" in result) && !("fields" in result)) return result;
3178
- const { form, fields, ...rest } = result;
3179
- return {
3180
- ...rest,
3181
- group: form,
3182
- fields
3183
- };
3184
- }
3185
- function getErrorMapKey(cause) {
3186
- switch (cause) {
3187
- case "submit": return "onSubmit";
3188
- case "blur": return "onBlur";
3189
- case "mount": return "onMount";
3190
- case "server": return "onServer";
3191
- case "dynamic": return "onDynamic";
3192
- default: return "onChange";
3193
- }
3194
- }
3195
- //#endregion
3196
- //#region ../../node_modules/.pnpm/@tanstack+form-core@1.33.0/node_modules/@tanstack/form-core/dist/esm/transform.js
3197
- function mergeAndUpdate(form, fn) {
3198
- if (!fn) return;
3199
- const newObj = Object.assign({}, form, { state: deepCopy(form.state) });
3200
- fn(newObj);
3201
- if (newObj.fieldInfo !== form.fieldInfo) form.fieldInfo = newObj.fieldInfo;
3202
- if (newObj.options !== form.options) form.options = newObj.options;
3203
- const diffedObject = Object.keys({
3204
- values: null,
3205
- validationMetaMap: null,
3206
- fieldMetaBase: null,
3207
- formGroupStateBase: null,
3208
- isSubmitting: null,
3209
- isSubmitted: null,
3210
- isValidating: null,
3211
- submissionAttempts: null,
3212
- isSubmitSuccessful: null,
3213
- _force_re_eval: null
3214
- }).reduce((prev, key) => {
3215
- if (form.state[key] !== newObj.state[key]) prev[key] = newObj.state[key];
3216
- return prev;
3217
- }, {});
3218
- batch(() => {
3219
- if (Object.keys(diffedObject).length) form.baseStore.setState((prev) => ({
3220
- ...prev,
3221
- ...diffedObject
3222
- }));
3223
- if (newObj.state.errorMap !== form.state.errorMap) form.setErrorMap(newObj.state.errorMap);
3224
- });
3225
- return newObj;
3226
- }
3227
- //#endregion
3228
- export { functionalUpdate as a, FormApi as i, FormGroupApi as n, uuid as o, FieldApi as r, mergeAndUpdate as t };