tenjin-cli 0.1.0-alpha.15 → 0.1.0-alpha.16

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 (267) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +41 -310
  3. package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-25TJPVBF.js +353 -0
  7. package/dist/chunk-25TJPVBF.js.map +1 -0
  8. package/dist/chunk-2BKS2FVE.js +93 -0
  9. package/dist/chunk-2BKS2FVE.js.map +1 -0
  10. package/dist/chunk-2QYORQBF.js +55 -0
  11. package/dist/chunk-2QYORQBF.js.map +1 -0
  12. package/dist/{chunk-NIKXHWOL.js → chunk-2U5ZVEV3.js} +16 -16
  13. package/dist/chunk-2U5ZVEV3.js.map +1 -0
  14. package/dist/{chunk-HPJGOLTN.js → chunk-3AJS6LLN.js} +13 -8
  15. package/dist/chunk-3AJS6LLN.js.map +1 -0
  16. package/dist/{chunk-KINZ23CV.js → chunk-3AUDA53C.js} +4740 -23
  17. package/dist/chunk-3AUDA53C.js.map +1 -0
  18. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  19. package/dist/chunk-56MOAIP5.js.map +1 -0
  20. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  21. package/dist/chunk-5X4SZ5BF.js +227 -0
  22. package/dist/chunk-5X4SZ5BF.js.map +1 -0
  23. package/dist/chunk-7WEQQJLG.js +68 -0
  24. package/dist/chunk-7WEQQJLG.js.map +1 -0
  25. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  26. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  27. package/dist/{chunk-ZFJJ3EXC.js → chunk-BBVUVBUO.js} +516 -185
  28. package/dist/chunk-BBVUVBUO.js.map +1 -0
  29. package/dist/{chunk-JBIKAAT3.js → chunk-BFFM2WFK.js} +8 -8
  30. package/dist/chunk-BFFM2WFK.js.map +1 -0
  31. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  32. package/dist/chunk-DMZZLPZN.js +205 -0
  33. package/dist/chunk-DMZZLPZN.js.map +1 -0
  34. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  35. package/dist/chunk-EGELTSPU.js.map +1 -0
  36. package/dist/chunk-GULLJQXA.js +698 -0
  37. package/dist/chunk-GULLJQXA.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-HVRC33OL.js +174 -0
  40. package/dist/chunk-HVRC33OL.js.map +1 -0
  41. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  42. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  43. package/dist/chunk-L3PVMIYQ.js +10328 -0
  44. package/dist/chunk-L3PVMIYQ.js.map +1 -0
  45. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  46. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  47. package/dist/chunk-MEFB5KHA.js.map +1 -0
  48. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  49. package/dist/chunk-N35E6CM2.js.map +1 -0
  50. package/dist/chunk-OCBHUHWB.js +69 -0
  51. package/dist/chunk-OCBHUHWB.js.map +1 -0
  52. package/dist/chunk-OIM4HLN6.js +1405 -0
  53. package/dist/chunk-OIM4HLN6.js.map +1 -0
  54. package/dist/{chunk-VYOJOX4Z.js → chunk-OJLYNM4Z.js} +54 -33
  55. package/dist/chunk-OJLYNM4Z.js.map +1 -0
  56. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  57. package/dist/chunk-PZEN5PHN.js +285 -0
  58. package/dist/chunk-PZEN5PHN.js.map +1 -0
  59. package/dist/chunk-SKAHDQH7.js +1785 -0
  60. package/dist/chunk-SKAHDQH7.js.map +1 -0
  61. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  62. package/dist/chunk-U5DXNFJC.js +137 -0
  63. package/dist/chunk-U5DXNFJC.js.map +1 -0
  64. package/dist/chunk-USS336NF.js +165 -0
  65. package/dist/chunk-USS336NF.js.map +1 -0
  66. package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
  67. package/dist/chunk-WH7OWT6G.js.map +1 -0
  68. package/dist/chunk-WXC57XGG.js +29 -0
  69. package/dist/chunk-WXC57XGG.js.map +1 -0
  70. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  71. package/dist/{chunk-CPCX67TI.js → chunk-YEETV6IW.js} +1079 -1039
  72. package/dist/chunk-YEETV6IW.js.map +1 -0
  73. package/dist/{chunk-OLWTRUTS.js → chunk-YJHHCWM3.js} +35 -16
  74. package/dist/chunk-YJHHCWM3.js.map +1 -0
  75. package/dist/{cli-KKRKBU5T.js → cli-M3XCSOU6.js} +289 -374
  76. package/dist/cli-M3XCSOU6.js.map +1 -0
  77. package/dist/config-MXOX7XDR.js +41 -0
  78. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  79. package/dist/doctor-LU4YIZWM.js +349 -0
  80. package/dist/doctor-LU4YIZWM.js.map +1 -0
  81. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  82. package/dist/{chunk-KAJZHIQ4.js → fund-A54P2QFK.js} +80 -24
  83. package/dist/fund-A54P2QFK.js.map +1 -0
  84. package/dist/hook-command-U6KWPEDQ.js +377 -0
  85. package/dist/hook-command-U6KWPEDQ.js.map +1 -0
  86. package/dist/index.js +8 -3
  87. package/dist/index.js.map +1 -1
  88. package/dist/install-XUM2XSHW.js +53 -0
  89. package/dist/install-wallet-QIOFORTX.js +105 -0
  90. package/dist/install-wallet-QIOFORTX.js.map +1 -0
  91. package/dist/{run-XYTQ5TWQ.js → mcp-HJC2PLRV.js} +3727 -10670
  92. package/dist/mcp-HJC2PLRV.js.map +1 -0
  93. package/dist/paths-P2N4JTDZ.js +49 -0
  94. package/dist/pay-SBXZEPEP.js +37 -0
  95. package/dist/redact-46ZHF2NH.js +17 -0
  96. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  97. package/dist/{send-G746D7PQ.js → send-ASD2ZXJD.js} +28 -29
  98. package/dist/send-ASD2ZXJD.js.map +1 -0
  99. package/dist/{chunk-QZ6ROAJU.js → skill-placement-NFVHY6A3.js} +157 -11
  100. package/dist/skill-placement-NFVHY6A3.js.map +1 -0
  101. package/dist/status-T2SDB57A.js +63 -0
  102. package/dist/status-T2SDB57A.js.map +1 -0
  103. package/dist/status-line-CGPUSDMC.js +71 -0
  104. package/dist/status-line-CGPUSDMC.js.map +1 -0
  105. package/dist/status-line-wiring-BYPHTYZE.js +30 -0
  106. package/dist/tenjin-daemon.mjs +20060 -0
  107. package/dist/tenjin-shim.mjs +251 -0
  108. package/dist/tenjin-vitest-reporter.mjs +49 -0
  109. package/dist/uninstall-FKYZHAM3.js +144 -0
  110. package/dist/uninstall-FKYZHAM3.js.map +1 -0
  111. package/dist/{update-R76LHOZW.js → update-ANJ2AOTN.js} +133 -16
  112. package/dist/update-ANJ2AOTN.js.map +1 -0
  113. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  114. package/dist/wallet-PWAHVKWW.js +31 -0
  115. package/dist/wallet-kdf-worker.mjs +980 -0
  116. package/docs/agent-permissions.md +65 -354
  117. package/docs/safety-model.md +16 -6
  118. package/package.json +8 -7
  119. package/LICENSE +0 -21
  120. package/dist/buy-VIRNSYGN.js +0 -47
  121. package/dist/chunk-2MYQN7HM.js +0 -247
  122. package/dist/chunk-2MYQN7HM.js.map +0 -1
  123. package/dist/chunk-2RF2GIJQ.js +0 -1188
  124. package/dist/chunk-2RF2GIJQ.js.map +0 -1
  125. package/dist/chunk-3GL2Z5QK.js +0 -57
  126. package/dist/chunk-3GL2Z5QK.js.map +0 -1
  127. package/dist/chunk-47PP7TAG.js.map +0 -1
  128. package/dist/chunk-4CQIDQOT.js +0 -167
  129. package/dist/chunk-4CQIDQOT.js.map +0 -1
  130. package/dist/chunk-4KG27W2S.js +0 -614
  131. package/dist/chunk-4KG27W2S.js.map +0 -1
  132. package/dist/chunk-5QQTYWEU.js +0 -199
  133. package/dist/chunk-5QQTYWEU.js.map +0 -1
  134. package/dist/chunk-65DTCCJ7.js +0 -21
  135. package/dist/chunk-65DTCCJ7.js.map +0 -1
  136. package/dist/chunk-A5DKHMUN.js +0 -173
  137. package/dist/chunk-A5DKHMUN.js.map +0 -1
  138. package/dist/chunk-B63XPWQ4.js +0 -246
  139. package/dist/chunk-B63XPWQ4.js.map +0 -1
  140. package/dist/chunk-CAR6FHK6.js +0 -105
  141. package/dist/chunk-CAR6FHK6.js.map +0 -1
  142. package/dist/chunk-CPCX67TI.js.map +0 -1
  143. package/dist/chunk-CQBVCYI2.js +0 -162
  144. package/dist/chunk-CQBVCYI2.js.map +0 -1
  145. package/dist/chunk-DBU5CXBV.js +0 -4731
  146. package/dist/chunk-DBU5CXBV.js.map +0 -1
  147. package/dist/chunk-DHJD77OW.js +0 -81
  148. package/dist/chunk-DHJD77OW.js.map +0 -1
  149. package/dist/chunk-EDZSNPE5.js +0 -35
  150. package/dist/chunk-EDZSNPE5.js.map +0 -1
  151. package/dist/chunk-EFWZPUTC.js +0 -65
  152. package/dist/chunk-EFWZPUTC.js.map +0 -1
  153. package/dist/chunk-EPFL6CTE.js +0 -448
  154. package/dist/chunk-EPFL6CTE.js.map +0 -1
  155. package/dist/chunk-GHLVXVZD.js +0 -142
  156. package/dist/chunk-GHLVXVZD.js.map +0 -1
  157. package/dist/chunk-H3SOOJ2I.js +0 -580
  158. package/dist/chunk-H3SOOJ2I.js.map +0 -1
  159. package/dist/chunk-HPJGOLTN.js.map +0 -1
  160. package/dist/chunk-HRGBS2PA.js +0 -203
  161. package/dist/chunk-HRGBS2PA.js.map +0 -1
  162. package/dist/chunk-ITUXPJIS.js +0 -314
  163. package/dist/chunk-ITUXPJIS.js.map +0 -1
  164. package/dist/chunk-JBIKAAT3.js.map +0 -1
  165. package/dist/chunk-KAJZHIQ4.js.map +0 -1
  166. package/dist/chunk-KINZ23CV.js.map +0 -1
  167. package/dist/chunk-LRYV3SK7.js +0 -235
  168. package/dist/chunk-LRYV3SK7.js.map +0 -1
  169. package/dist/chunk-M2O56UK7.js.map +0 -1
  170. package/dist/chunk-MJZZTKCC.js.map +0 -1
  171. package/dist/chunk-NIKXHWOL.js.map +0 -1
  172. package/dist/chunk-OKDRDT74.js +0 -209
  173. package/dist/chunk-OKDRDT74.js.map +0 -1
  174. package/dist/chunk-OKYSNAS3.js +0 -2144
  175. package/dist/chunk-OKYSNAS3.js.map +0 -1
  176. package/dist/chunk-OLWTRUTS.js.map +0 -1
  177. package/dist/chunk-QQ6ELLSA.js +0 -143
  178. package/dist/chunk-QQ6ELLSA.js.map +0 -1
  179. package/dist/chunk-QZ6ROAJU.js.map +0 -1
  180. package/dist/chunk-R7RSCBI7.js +0 -794
  181. package/dist/chunk-R7RSCBI7.js.map +0 -1
  182. package/dist/chunk-SGK2B724.js +0 -67
  183. package/dist/chunk-SGK2B724.js.map +0 -1
  184. package/dist/chunk-U6VPKMGC.js +0 -390
  185. package/dist/chunk-U6VPKMGC.js.map +0 -1
  186. package/dist/chunk-UHTVXQ2O.js +0 -140
  187. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  188. package/dist/chunk-UO22YNY4.js.map +0 -1
  189. package/dist/chunk-US456VUI.js +0 -149
  190. package/dist/chunk-US456VUI.js.map +0 -1
  191. package/dist/chunk-V44J2MXV.js +0 -400
  192. package/dist/chunk-V44J2MXV.js.map +0 -1
  193. package/dist/chunk-VJQKL3YH.js +0 -216
  194. package/dist/chunk-VJQKL3YH.js.map +0 -1
  195. package/dist/chunk-VJSQSLBM.js +0 -1442
  196. package/dist/chunk-VJSQSLBM.js.map +0 -1
  197. package/dist/chunk-VYOJOX4Z.js.map +0 -1
  198. package/dist/chunk-WY2K35OL.js +0 -269
  199. package/dist/chunk-WY2K35OL.js.map +0 -1
  200. package/dist/chunk-ZFJJ3EXC.js.map +0 -1
  201. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  202. package/dist/cli-KKRKBU5T.js.map +0 -1
  203. package/dist/config-JMRUNYE6.js +0 -37
  204. package/dist/discover-B5HF6SHM.js +0 -102
  205. package/dist/discover-B5HF6SHM.js.map +0 -1
  206. package/dist/doctor-ZBG7X66D.js +0 -32
  207. package/dist/edit-PZJIILQE.js +0 -40
  208. package/dist/fund-EUDH5KPA.js +0 -40
  209. package/dist/inspect-QC6WEQPN.js +0 -37
  210. package/dist/install-GNK2W3PI.js +0 -972
  211. package/dist/install-GNK2W3PI.js.map +0 -1
  212. package/dist/outcome-KSGWZHUS.js +0 -24
  213. package/dist/pay-BC4UICPA.js +0 -361
  214. package/dist/pay-BC4UICPA.js.map +0 -1
  215. package/dist/publish-LXWFDIKF.js +0 -42
  216. package/dist/read-JMNUQ56P.js +0 -160
  217. package/dist/read-JMNUQ56P.js.map +0 -1
  218. package/dist/run-XYTQ5TWQ.js.map +0 -1
  219. package/dist/search-TSQAB45E.js +0 -25
  220. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  221. package/dist/send-G746D7PQ.js.map +0 -1
  222. package/dist/session-JBKWMJ24.js +0 -89
  223. package/dist/session-JBKWMJ24.js.map +0 -1
  224. package/dist/skill-heal-WKD67SLJ.js +0 -92
  225. package/dist/skill-heal-WKD67SLJ.js.map +0 -1
  226. package/dist/skill-placement-RIU4AMC2.js +0 -20
  227. package/dist/skill-placement-RIU4AMC2.js.map +0 -1
  228. package/dist/uninstall-5E263VTS.js +0 -73
  229. package/dist/uninstall-5E263VTS.js.map +0 -1
  230. package/dist/update-R76LHOZW.js.map +0 -1
  231. package/dist/usdc-4VCDHFWX.js +0 -38
  232. package/dist/usdc-4VCDHFWX.js.map +0 -1
  233. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  234. package/dist/wallet-TQ7D5EQ7.js +0 -41
  235. package/dist/wallet-TQ7D5EQ7.js.map +0 -1
  236. package/dist/wallet-ZAVXWLWP.js +0 -32
  237. package/dist/wallet-ZAVXWLWP.js.map +0 -1
  238. package/docs/command-reference.md +0 -303
  239. package/skills/tenjin/SKILL.md +0 -373
  240. package/skills/tenjin-pay/SKILL.md +0 -76
  241. package/skills/tenjin-publish/SKILL.md +0 -227
  242. package/skills/tenjin-publish/references/maintain.md +0 -39
  243. package/skills/tenjin-search/SKILL.md +0 -154
  244. package/skills/tenjin-search/references/permissions.md +0 -112
  245. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  246. /package/dist/{buy-VIRNSYGN.js.map → ccip-7RMRLAGV.js.map} +0 -0
  247. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  248. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  249. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  250. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  251. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  252. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  253. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  254. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  255. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  256. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  257. /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
  258. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  259. /package/dist/{config-JMRUNYE6.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  260. /package/dist/{doctor-ZBG7X66D.js.map → install-XUM2XSHW.js.map} +0 -0
  261. /package/dist/{edit-PZJIILQE.js.map → paths-P2N4JTDZ.js.map} +0 -0
  262. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
  263. /package/dist/{fund-EUDH5KPA.js.map → redact-46ZHF2NH.js.map} +0 -0
  264. /package/dist/{inspect-QC6WEQPN.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  265. /package/dist/{outcome-KSGWZHUS.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
  266. /package/dist/{publish-LXWFDIKF.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  267. /package/dist/{search-TSQAB45E.js.map → wallet-PWAHVKWW.js.map} +0 -0
@@ -1,4731 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- __export
4
- } from "./chunk-ZXTAQYNA.js";
5
-
6
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
7
- var external_exports = {};
8
- __export(external_exports, {
9
- BRAND: () => BRAND,
10
- DIRTY: () => DIRTY,
11
- EMPTY_PATH: () => EMPTY_PATH,
12
- INVALID: () => INVALID,
13
- NEVER: () => NEVER,
14
- OK: () => OK,
15
- ParseStatus: () => ParseStatus,
16
- Schema: () => ZodType,
17
- ZodAny: () => ZodAny,
18
- ZodArray: () => ZodArray,
19
- ZodBigInt: () => ZodBigInt,
20
- ZodBoolean: () => ZodBoolean,
21
- ZodBranded: () => ZodBranded,
22
- ZodCatch: () => ZodCatch,
23
- ZodDate: () => ZodDate,
24
- ZodDefault: () => ZodDefault,
25
- ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
26
- ZodEffects: () => ZodEffects,
27
- ZodEnum: () => ZodEnum,
28
- ZodError: () => ZodError,
29
- ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
30
- ZodFunction: () => ZodFunction,
31
- ZodIntersection: () => ZodIntersection,
32
- ZodIssueCode: () => ZodIssueCode,
33
- ZodLazy: () => ZodLazy,
34
- ZodLiteral: () => ZodLiteral,
35
- ZodMap: () => ZodMap,
36
- ZodNaN: () => ZodNaN,
37
- ZodNativeEnum: () => ZodNativeEnum,
38
- ZodNever: () => ZodNever,
39
- ZodNull: () => ZodNull,
40
- ZodNullable: () => ZodNullable,
41
- ZodNumber: () => ZodNumber,
42
- ZodObject: () => ZodObject,
43
- ZodOptional: () => ZodOptional,
44
- ZodParsedType: () => ZodParsedType,
45
- ZodPipeline: () => ZodPipeline,
46
- ZodPromise: () => ZodPromise,
47
- ZodReadonly: () => ZodReadonly,
48
- ZodRecord: () => ZodRecord,
49
- ZodSchema: () => ZodType,
50
- ZodSet: () => ZodSet,
51
- ZodString: () => ZodString,
52
- ZodSymbol: () => ZodSymbol,
53
- ZodTransformer: () => ZodEffects,
54
- ZodTuple: () => ZodTuple,
55
- ZodType: () => ZodType,
56
- ZodUndefined: () => ZodUndefined,
57
- ZodUnion: () => ZodUnion,
58
- ZodUnknown: () => ZodUnknown,
59
- ZodVoid: () => ZodVoid,
60
- addIssueToContext: () => addIssueToContext,
61
- any: () => anyType,
62
- array: () => arrayType,
63
- bigint: () => bigIntType,
64
- boolean: () => booleanType,
65
- coerce: () => coerce,
66
- custom: () => custom,
67
- date: () => dateType,
68
- datetimeRegex: () => datetimeRegex,
69
- defaultErrorMap: () => en_default,
70
- discriminatedUnion: () => discriminatedUnionType,
71
- effect: () => effectsType,
72
- enum: () => enumType,
73
- function: () => functionType,
74
- getErrorMap: () => getErrorMap,
75
- getParsedType: () => getParsedType,
76
- instanceof: () => instanceOfType,
77
- intersection: () => intersectionType,
78
- isAborted: () => isAborted,
79
- isAsync: () => isAsync,
80
- isDirty: () => isDirty,
81
- isValid: () => isValid,
82
- late: () => late,
83
- lazy: () => lazyType,
84
- literal: () => literalType,
85
- makeIssue: () => makeIssue,
86
- map: () => mapType,
87
- nan: () => nanType,
88
- nativeEnum: () => nativeEnumType,
89
- never: () => neverType,
90
- null: () => nullType,
91
- nullable: () => nullableType,
92
- number: () => numberType,
93
- object: () => objectType,
94
- objectUtil: () => objectUtil,
95
- oboolean: () => oboolean,
96
- onumber: () => onumber,
97
- optional: () => optionalType,
98
- ostring: () => ostring,
99
- pipeline: () => pipelineType,
100
- preprocess: () => preprocessType,
101
- promise: () => promiseType,
102
- quotelessJson: () => quotelessJson,
103
- record: () => recordType,
104
- set: () => setType,
105
- setErrorMap: () => setErrorMap,
106
- strictObject: () => strictObjectType,
107
- string: () => stringType,
108
- symbol: () => symbolType,
109
- transformer: () => effectsType,
110
- tuple: () => tupleType,
111
- undefined: () => undefinedType,
112
- union: () => unionType,
113
- unknown: () => unknownType,
114
- util: () => util,
115
- void: () => voidType
116
- });
117
-
118
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
119
- var util;
120
- (function(util2) {
121
- util2.assertEqual = (_) => {
122
- };
123
- function assertIs(_arg) {
124
- }
125
- util2.assertIs = assertIs;
126
- function assertNever(_x) {
127
- throw new Error();
128
- }
129
- util2.assertNever = assertNever;
130
- util2.arrayToEnum = (items) => {
131
- const obj = {};
132
- for (const item of items) {
133
- obj[item] = item;
134
- }
135
- return obj;
136
- };
137
- util2.getValidEnumValues = (obj) => {
138
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
139
- const filtered = {};
140
- for (const k of validKeys) {
141
- filtered[k] = obj[k];
142
- }
143
- return util2.objectValues(filtered);
144
- };
145
- util2.objectValues = (obj) => {
146
- return util2.objectKeys(obj).map(function(e) {
147
- return obj[e];
148
- });
149
- };
150
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
151
- const keys = [];
152
- for (const key in object) {
153
- if (Object.prototype.hasOwnProperty.call(object, key)) {
154
- keys.push(key);
155
- }
156
- }
157
- return keys;
158
- };
159
- util2.find = (arr, checker) => {
160
- for (const item of arr) {
161
- if (checker(item))
162
- return item;
163
- }
164
- return void 0;
165
- };
166
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
167
- function joinValues(array, separator = " | ") {
168
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
169
- }
170
- util2.joinValues = joinValues;
171
- util2.jsonStringifyReplacer = (_, value) => {
172
- if (typeof value === "bigint") {
173
- return value.toString();
174
- }
175
- return value;
176
- };
177
- })(util || (util = {}));
178
- var objectUtil;
179
- (function(objectUtil2) {
180
- objectUtil2.mergeShapes = (first, second) => {
181
- return {
182
- ...first,
183
- ...second
184
- // second overwrites first
185
- };
186
- };
187
- })(objectUtil || (objectUtil = {}));
188
- var ZodParsedType = util.arrayToEnum([
189
- "string",
190
- "nan",
191
- "number",
192
- "integer",
193
- "float",
194
- "boolean",
195
- "date",
196
- "bigint",
197
- "symbol",
198
- "function",
199
- "undefined",
200
- "null",
201
- "array",
202
- "object",
203
- "unknown",
204
- "promise",
205
- "void",
206
- "never",
207
- "map",
208
- "set"
209
- ]);
210
- var getParsedType = (data) => {
211
- const t = typeof data;
212
- switch (t) {
213
- case "undefined":
214
- return ZodParsedType.undefined;
215
- case "string":
216
- return ZodParsedType.string;
217
- case "number":
218
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
219
- case "boolean":
220
- return ZodParsedType.boolean;
221
- case "function":
222
- return ZodParsedType.function;
223
- case "bigint":
224
- return ZodParsedType.bigint;
225
- case "symbol":
226
- return ZodParsedType.symbol;
227
- case "object":
228
- if (Array.isArray(data)) {
229
- return ZodParsedType.array;
230
- }
231
- if (data === null) {
232
- return ZodParsedType.null;
233
- }
234
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
235
- return ZodParsedType.promise;
236
- }
237
- if (typeof Map !== "undefined" && data instanceof Map) {
238
- return ZodParsedType.map;
239
- }
240
- if (typeof Set !== "undefined" && data instanceof Set) {
241
- return ZodParsedType.set;
242
- }
243
- if (typeof Date !== "undefined" && data instanceof Date) {
244
- return ZodParsedType.date;
245
- }
246
- return ZodParsedType.object;
247
- default:
248
- return ZodParsedType.unknown;
249
- }
250
- };
251
-
252
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
253
- var ZodIssueCode = util.arrayToEnum([
254
- "invalid_type",
255
- "invalid_literal",
256
- "custom",
257
- "invalid_union",
258
- "invalid_union_discriminator",
259
- "invalid_enum_value",
260
- "unrecognized_keys",
261
- "invalid_arguments",
262
- "invalid_return_type",
263
- "invalid_date",
264
- "invalid_string",
265
- "too_small",
266
- "too_big",
267
- "invalid_intersection_types",
268
- "not_multiple_of",
269
- "not_finite"
270
- ]);
271
- var quotelessJson = (obj) => {
272
- const json = JSON.stringify(obj, null, 2);
273
- return json.replace(/"([^"]+)":/g, "$1:");
274
- };
275
- var ZodError = class _ZodError extends Error {
276
- get errors() {
277
- return this.issues;
278
- }
279
- constructor(issues) {
280
- super();
281
- this.issues = [];
282
- this.addIssue = (sub) => {
283
- this.issues = [...this.issues, sub];
284
- };
285
- this.addIssues = (subs = []) => {
286
- this.issues = [...this.issues, ...subs];
287
- };
288
- const actualProto = new.target.prototype;
289
- if (Object.setPrototypeOf) {
290
- Object.setPrototypeOf(this, actualProto);
291
- } else {
292
- this.__proto__ = actualProto;
293
- }
294
- this.name = "ZodError";
295
- this.issues = issues;
296
- }
297
- format(_mapper) {
298
- const mapper = _mapper || function(issue) {
299
- return issue.message;
300
- };
301
- const fieldErrors = { _errors: [] };
302
- const processError = (error) => {
303
- for (const issue of error.issues) {
304
- if (issue.code === "invalid_union") {
305
- issue.unionErrors.map(processError);
306
- } else if (issue.code === "invalid_return_type") {
307
- processError(issue.returnTypeError);
308
- } else if (issue.code === "invalid_arguments") {
309
- processError(issue.argumentsError);
310
- } else if (issue.path.length === 0) {
311
- fieldErrors._errors.push(mapper(issue));
312
- } else {
313
- let curr = fieldErrors;
314
- let i = 0;
315
- while (i < issue.path.length) {
316
- const el = issue.path[i];
317
- const terminal = i === issue.path.length - 1;
318
- if (!terminal) {
319
- curr[el] = curr[el] || { _errors: [] };
320
- } else {
321
- curr[el] = curr[el] || { _errors: [] };
322
- curr[el]._errors.push(mapper(issue));
323
- }
324
- curr = curr[el];
325
- i++;
326
- }
327
- }
328
- }
329
- };
330
- processError(this);
331
- return fieldErrors;
332
- }
333
- static assert(value) {
334
- if (!(value instanceof _ZodError)) {
335
- throw new Error(`Not a ZodError: ${value}`);
336
- }
337
- }
338
- toString() {
339
- return this.message;
340
- }
341
- get message() {
342
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
343
- }
344
- get isEmpty() {
345
- return this.issues.length === 0;
346
- }
347
- flatten(mapper = (issue) => issue.message) {
348
- const fieldErrors = {};
349
- const formErrors = [];
350
- for (const sub of this.issues) {
351
- if (sub.path.length > 0) {
352
- const firstEl = sub.path[0];
353
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
354
- fieldErrors[firstEl].push(mapper(sub));
355
- } else {
356
- formErrors.push(mapper(sub));
357
- }
358
- }
359
- return { formErrors, fieldErrors };
360
- }
361
- get formErrors() {
362
- return this.flatten();
363
- }
364
- };
365
- ZodError.create = (issues) => {
366
- const error = new ZodError(issues);
367
- return error;
368
- };
369
-
370
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
371
- var errorMap = (issue, _ctx) => {
372
- let message;
373
- switch (issue.code) {
374
- case ZodIssueCode.invalid_type:
375
- if (issue.received === ZodParsedType.undefined) {
376
- message = "Required";
377
- } else {
378
- message = `Expected ${issue.expected}, received ${issue.received}`;
379
- }
380
- break;
381
- case ZodIssueCode.invalid_literal:
382
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
383
- break;
384
- case ZodIssueCode.unrecognized_keys:
385
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
386
- break;
387
- case ZodIssueCode.invalid_union:
388
- message = `Invalid input`;
389
- break;
390
- case ZodIssueCode.invalid_union_discriminator:
391
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
392
- break;
393
- case ZodIssueCode.invalid_enum_value:
394
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
395
- break;
396
- case ZodIssueCode.invalid_arguments:
397
- message = `Invalid function arguments`;
398
- break;
399
- case ZodIssueCode.invalid_return_type:
400
- message = `Invalid function return type`;
401
- break;
402
- case ZodIssueCode.invalid_date:
403
- message = `Invalid date`;
404
- break;
405
- case ZodIssueCode.invalid_string:
406
- if (typeof issue.validation === "object") {
407
- if ("includes" in issue.validation) {
408
- message = `Invalid input: must include "${issue.validation.includes}"`;
409
- if (typeof issue.validation.position === "number") {
410
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
411
- }
412
- } else if ("startsWith" in issue.validation) {
413
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
414
- } else if ("endsWith" in issue.validation) {
415
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
416
- } else {
417
- util.assertNever(issue.validation);
418
- }
419
- } else if (issue.validation !== "regex") {
420
- message = `Invalid ${issue.validation}`;
421
- } else {
422
- message = "Invalid";
423
- }
424
- break;
425
- case ZodIssueCode.too_small:
426
- if (issue.type === "array")
427
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
428
- else if (issue.type === "string")
429
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
430
- else if (issue.type === "number")
431
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
432
- else if (issue.type === "bigint")
433
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
434
- else if (issue.type === "date")
435
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
436
- else
437
- message = "Invalid input";
438
- break;
439
- case ZodIssueCode.too_big:
440
- if (issue.type === "array")
441
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
442
- else if (issue.type === "string")
443
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
444
- else if (issue.type === "number")
445
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
446
- else if (issue.type === "bigint")
447
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
448
- else if (issue.type === "date")
449
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
450
- else
451
- message = "Invalid input";
452
- break;
453
- case ZodIssueCode.custom:
454
- message = `Invalid input`;
455
- break;
456
- case ZodIssueCode.invalid_intersection_types:
457
- message = `Intersection results could not be merged`;
458
- break;
459
- case ZodIssueCode.not_multiple_of:
460
- message = `Number must be a multiple of ${issue.multipleOf}`;
461
- break;
462
- case ZodIssueCode.not_finite:
463
- message = "Number must be finite";
464
- break;
465
- default:
466
- message = _ctx.defaultError;
467
- util.assertNever(issue);
468
- }
469
- return { message };
470
- };
471
- var en_default = errorMap;
472
-
473
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
474
- var overrideErrorMap = en_default;
475
- function setErrorMap(map) {
476
- overrideErrorMap = map;
477
- }
478
- function getErrorMap() {
479
- return overrideErrorMap;
480
- }
481
-
482
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
483
- var makeIssue = (params) => {
484
- const { data, path, errorMaps, issueData } = params;
485
- const fullPath = [...path, ...issueData.path || []];
486
- const fullIssue = {
487
- ...issueData,
488
- path: fullPath
489
- };
490
- if (issueData.message !== void 0) {
491
- return {
492
- ...issueData,
493
- path: fullPath,
494
- message: issueData.message
495
- };
496
- }
497
- let errorMessage = "";
498
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
499
- for (const map of maps) {
500
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
501
- }
502
- return {
503
- ...issueData,
504
- path: fullPath,
505
- message: errorMessage
506
- };
507
- };
508
- var EMPTY_PATH = [];
509
- function addIssueToContext(ctx, issueData) {
510
- const overrideMap = getErrorMap();
511
- const issue = makeIssue({
512
- issueData,
513
- data: ctx.data,
514
- path: ctx.path,
515
- errorMaps: [
516
- ctx.common.contextualErrorMap,
517
- // contextual error map is first priority
518
- ctx.schemaErrorMap,
519
- // then schema-bound map if available
520
- overrideMap,
521
- // then global override map
522
- overrideMap === en_default ? void 0 : en_default
523
- // then global default map
524
- ].filter((x) => !!x)
525
- });
526
- ctx.common.issues.push(issue);
527
- }
528
- var ParseStatus = class _ParseStatus {
529
- constructor() {
530
- this.value = "valid";
531
- }
532
- dirty() {
533
- if (this.value === "valid")
534
- this.value = "dirty";
535
- }
536
- abort() {
537
- if (this.value !== "aborted")
538
- this.value = "aborted";
539
- }
540
- static mergeArray(status, results) {
541
- const arrayValue = [];
542
- for (const s of results) {
543
- if (s.status === "aborted")
544
- return INVALID;
545
- if (s.status === "dirty")
546
- status.dirty();
547
- arrayValue.push(s.value);
548
- }
549
- return { status: status.value, value: arrayValue };
550
- }
551
- static async mergeObjectAsync(status, pairs) {
552
- const syncPairs = [];
553
- for (const pair of pairs) {
554
- const key = await pair.key;
555
- const value = await pair.value;
556
- syncPairs.push({
557
- key,
558
- value
559
- });
560
- }
561
- return _ParseStatus.mergeObjectSync(status, syncPairs);
562
- }
563
- static mergeObjectSync(status, pairs) {
564
- const finalObject = {};
565
- for (const pair of pairs) {
566
- const { key, value } = pair;
567
- if (key.status === "aborted")
568
- return INVALID;
569
- if (value.status === "aborted")
570
- return INVALID;
571
- if (key.status === "dirty")
572
- status.dirty();
573
- if (value.status === "dirty")
574
- status.dirty();
575
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
576
- finalObject[key.value] = value.value;
577
- }
578
- }
579
- return { status: status.value, value: finalObject };
580
- }
581
- };
582
- var INVALID = Object.freeze({
583
- status: "aborted"
584
- });
585
- var DIRTY = (value) => ({ status: "dirty", value });
586
- var OK = (value) => ({ status: "valid", value });
587
- var isAborted = (x) => x.status === "aborted";
588
- var isDirty = (x) => x.status === "dirty";
589
- var isValid = (x) => x.status === "valid";
590
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
591
-
592
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
593
- var errorUtil;
594
- (function(errorUtil2) {
595
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
596
- errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
597
- })(errorUtil || (errorUtil = {}));
598
-
599
- // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
600
- var ParseInputLazyPath = class {
601
- constructor(parent, value, path, key) {
602
- this._cachedPath = [];
603
- this.parent = parent;
604
- this.data = value;
605
- this._path = path;
606
- this._key = key;
607
- }
608
- get path() {
609
- if (!this._cachedPath.length) {
610
- if (Array.isArray(this._key)) {
611
- this._cachedPath.push(...this._path, ...this._key);
612
- } else {
613
- this._cachedPath.push(...this._path, this._key);
614
- }
615
- }
616
- return this._cachedPath;
617
- }
618
- };
619
- var handleResult = (ctx, result) => {
620
- if (isValid(result)) {
621
- return { success: true, data: result.value };
622
- } else {
623
- if (!ctx.common.issues.length) {
624
- throw new Error("Validation failed but no issues detected.");
625
- }
626
- return {
627
- success: false,
628
- get error() {
629
- if (this._error)
630
- return this._error;
631
- const error = new ZodError(ctx.common.issues);
632
- this._error = error;
633
- return this._error;
634
- }
635
- };
636
- }
637
- };
638
- function processCreateParams(params) {
639
- if (!params)
640
- return {};
641
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
642
- if (errorMap2 && (invalid_type_error || required_error)) {
643
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
644
- }
645
- if (errorMap2)
646
- return { errorMap: errorMap2, description };
647
- const customMap = (iss, ctx) => {
648
- const { message } = params;
649
- if (iss.code === "invalid_enum_value") {
650
- return { message: message ?? ctx.defaultError };
651
- }
652
- if (typeof ctx.data === "undefined") {
653
- return { message: message ?? required_error ?? ctx.defaultError };
654
- }
655
- if (iss.code !== "invalid_type")
656
- return { message: ctx.defaultError };
657
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
658
- };
659
- return { errorMap: customMap, description };
660
- }
661
- var ZodType = class {
662
- get description() {
663
- return this._def.description;
664
- }
665
- _getType(input) {
666
- return getParsedType(input.data);
667
- }
668
- _getOrReturnCtx(input, ctx) {
669
- return ctx || {
670
- common: input.parent.common,
671
- data: input.data,
672
- parsedType: getParsedType(input.data),
673
- schemaErrorMap: this._def.errorMap,
674
- path: input.path,
675
- parent: input.parent
676
- };
677
- }
678
- _processInputParams(input) {
679
- return {
680
- status: new ParseStatus(),
681
- ctx: {
682
- common: input.parent.common,
683
- data: input.data,
684
- parsedType: getParsedType(input.data),
685
- schemaErrorMap: this._def.errorMap,
686
- path: input.path,
687
- parent: input.parent
688
- }
689
- };
690
- }
691
- _parseSync(input) {
692
- const result = this._parse(input);
693
- if (isAsync(result)) {
694
- throw new Error("Synchronous parse encountered promise.");
695
- }
696
- return result;
697
- }
698
- _parseAsync(input) {
699
- const result = this._parse(input);
700
- return Promise.resolve(result);
701
- }
702
- parse(data, params) {
703
- const result = this.safeParse(data, params);
704
- if (result.success)
705
- return result.data;
706
- throw result.error;
707
- }
708
- safeParse(data, params) {
709
- const ctx = {
710
- common: {
711
- issues: [],
712
- async: params?.async ?? false,
713
- contextualErrorMap: params?.errorMap
714
- },
715
- path: params?.path || [],
716
- schemaErrorMap: this._def.errorMap,
717
- parent: null,
718
- data,
719
- parsedType: getParsedType(data)
720
- };
721
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
722
- return handleResult(ctx, result);
723
- }
724
- "~validate"(data) {
725
- const ctx = {
726
- common: {
727
- issues: [],
728
- async: !!this["~standard"].async
729
- },
730
- path: [],
731
- schemaErrorMap: this._def.errorMap,
732
- parent: null,
733
- data,
734
- parsedType: getParsedType(data)
735
- };
736
- if (!this["~standard"].async) {
737
- try {
738
- const result = this._parseSync({ data, path: [], parent: ctx });
739
- return isValid(result) ? {
740
- value: result.value
741
- } : {
742
- issues: ctx.common.issues
743
- };
744
- } catch (err) {
745
- if (err?.message?.toLowerCase()?.includes("encountered")) {
746
- this["~standard"].async = true;
747
- }
748
- ctx.common = {
749
- issues: [],
750
- async: true
751
- };
752
- }
753
- }
754
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
755
- value: result.value
756
- } : {
757
- issues: ctx.common.issues
758
- });
759
- }
760
- async parseAsync(data, params) {
761
- const result = await this.safeParseAsync(data, params);
762
- if (result.success)
763
- return result.data;
764
- throw result.error;
765
- }
766
- async safeParseAsync(data, params) {
767
- const ctx = {
768
- common: {
769
- issues: [],
770
- contextualErrorMap: params?.errorMap,
771
- async: true
772
- },
773
- path: params?.path || [],
774
- schemaErrorMap: this._def.errorMap,
775
- parent: null,
776
- data,
777
- parsedType: getParsedType(data)
778
- };
779
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
780
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
781
- return handleResult(ctx, result);
782
- }
783
- refine(check, message) {
784
- const getIssueProperties = (val) => {
785
- if (typeof message === "string" || typeof message === "undefined") {
786
- return { message };
787
- } else if (typeof message === "function") {
788
- return message(val);
789
- } else {
790
- return message;
791
- }
792
- };
793
- return this._refinement((val, ctx) => {
794
- const result = check(val);
795
- const setError = () => ctx.addIssue({
796
- code: ZodIssueCode.custom,
797
- ...getIssueProperties(val)
798
- });
799
- if (typeof Promise !== "undefined" && result instanceof Promise) {
800
- return result.then((data) => {
801
- if (!data) {
802
- setError();
803
- return false;
804
- } else {
805
- return true;
806
- }
807
- });
808
- }
809
- if (!result) {
810
- setError();
811
- return false;
812
- } else {
813
- return true;
814
- }
815
- });
816
- }
817
- refinement(check, refinementData) {
818
- return this._refinement((val, ctx) => {
819
- if (!check(val)) {
820
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
821
- return false;
822
- } else {
823
- return true;
824
- }
825
- });
826
- }
827
- _refinement(refinement) {
828
- return new ZodEffects({
829
- schema: this,
830
- typeName: ZodFirstPartyTypeKind.ZodEffects,
831
- effect: { type: "refinement", refinement }
832
- });
833
- }
834
- superRefine(refinement) {
835
- return this._refinement(refinement);
836
- }
837
- constructor(def) {
838
- this.spa = this.safeParseAsync;
839
- this._def = def;
840
- this.parse = this.parse.bind(this);
841
- this.safeParse = this.safeParse.bind(this);
842
- this.parseAsync = this.parseAsync.bind(this);
843
- this.safeParseAsync = this.safeParseAsync.bind(this);
844
- this.spa = this.spa.bind(this);
845
- this.refine = this.refine.bind(this);
846
- this.refinement = this.refinement.bind(this);
847
- this.superRefine = this.superRefine.bind(this);
848
- this.optional = this.optional.bind(this);
849
- this.nullable = this.nullable.bind(this);
850
- this.nullish = this.nullish.bind(this);
851
- this.array = this.array.bind(this);
852
- this.promise = this.promise.bind(this);
853
- this.or = this.or.bind(this);
854
- this.and = this.and.bind(this);
855
- this.transform = this.transform.bind(this);
856
- this.brand = this.brand.bind(this);
857
- this.default = this.default.bind(this);
858
- this.catch = this.catch.bind(this);
859
- this.describe = this.describe.bind(this);
860
- this.pipe = this.pipe.bind(this);
861
- this.readonly = this.readonly.bind(this);
862
- this.isNullable = this.isNullable.bind(this);
863
- this.isOptional = this.isOptional.bind(this);
864
- this["~standard"] = {
865
- version: 1,
866
- vendor: "zod",
867
- validate: (data) => this["~validate"](data)
868
- };
869
- }
870
- optional() {
871
- return ZodOptional.create(this, this._def);
872
- }
873
- nullable() {
874
- return ZodNullable.create(this, this._def);
875
- }
876
- nullish() {
877
- return this.nullable().optional();
878
- }
879
- array() {
880
- return ZodArray.create(this);
881
- }
882
- promise() {
883
- return ZodPromise.create(this, this._def);
884
- }
885
- or(option) {
886
- return ZodUnion.create([this, option], this._def);
887
- }
888
- and(incoming) {
889
- return ZodIntersection.create(this, incoming, this._def);
890
- }
891
- transform(transform) {
892
- return new ZodEffects({
893
- ...processCreateParams(this._def),
894
- schema: this,
895
- typeName: ZodFirstPartyTypeKind.ZodEffects,
896
- effect: { type: "transform", transform }
897
- });
898
- }
899
- default(def) {
900
- const defaultValueFunc = typeof def === "function" ? def : () => def;
901
- return new ZodDefault({
902
- ...processCreateParams(this._def),
903
- innerType: this,
904
- defaultValue: defaultValueFunc,
905
- typeName: ZodFirstPartyTypeKind.ZodDefault
906
- });
907
- }
908
- brand() {
909
- return new ZodBranded({
910
- typeName: ZodFirstPartyTypeKind.ZodBranded,
911
- type: this,
912
- ...processCreateParams(this._def)
913
- });
914
- }
915
- catch(def) {
916
- const catchValueFunc = typeof def === "function" ? def : () => def;
917
- return new ZodCatch({
918
- ...processCreateParams(this._def),
919
- innerType: this,
920
- catchValue: catchValueFunc,
921
- typeName: ZodFirstPartyTypeKind.ZodCatch
922
- });
923
- }
924
- describe(description) {
925
- const This = this.constructor;
926
- return new This({
927
- ...this._def,
928
- description
929
- });
930
- }
931
- pipe(target) {
932
- return ZodPipeline.create(this, target);
933
- }
934
- readonly() {
935
- return ZodReadonly.create(this);
936
- }
937
- isOptional() {
938
- return this.safeParse(void 0).success;
939
- }
940
- isNullable() {
941
- return this.safeParse(null).success;
942
- }
943
- };
944
- var cuidRegex = /^c[^\s-]{8,}$/i;
945
- var cuid2Regex = /^[0-9a-z]+$/;
946
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
947
- var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
948
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
949
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
950
- var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
951
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
952
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
953
- var emojiRegex;
954
- var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
955
- var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
956
- var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
957
- var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
958
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
959
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
960
- var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
961
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
962
- function timeRegexSource(args) {
963
- let secondsRegexSource = `[0-5]\\d`;
964
- if (args.precision) {
965
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
966
- } else if (args.precision == null) {
967
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
968
- }
969
- const secondsQuantifier = args.precision ? "+" : "?";
970
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
971
- }
972
- function timeRegex(args) {
973
- return new RegExp(`^${timeRegexSource(args)}$`);
974
- }
975
- function datetimeRegex(args) {
976
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
977
- const opts = [];
978
- opts.push(args.local ? `Z?` : `Z`);
979
- if (args.offset)
980
- opts.push(`([+-]\\d{2}:?\\d{2})`);
981
- regex = `${regex}(${opts.join("|")})`;
982
- return new RegExp(`^${regex}$`);
983
- }
984
- function isValidIP(ip, version) {
985
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
986
- return true;
987
- }
988
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
989
- return true;
990
- }
991
- return false;
992
- }
993
- function isValidJWT(jwt, alg) {
994
- if (!jwtRegex.test(jwt))
995
- return false;
996
- try {
997
- const [header] = jwt.split(".");
998
- if (!header)
999
- return false;
1000
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1001
- const decoded = JSON.parse(atob(base64));
1002
- if (typeof decoded !== "object" || decoded === null)
1003
- return false;
1004
- if ("typ" in decoded && decoded?.typ !== "JWT")
1005
- return false;
1006
- if (!decoded.alg)
1007
- return false;
1008
- if (alg && decoded.alg !== alg)
1009
- return false;
1010
- return true;
1011
- } catch {
1012
- return false;
1013
- }
1014
- }
1015
- function isValidCidr(ip, version) {
1016
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1017
- return true;
1018
- }
1019
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1020
- return true;
1021
- }
1022
- return false;
1023
- }
1024
- var ZodString = class _ZodString extends ZodType {
1025
- _parse(input) {
1026
- if (this._def.coerce) {
1027
- input.data = String(input.data);
1028
- }
1029
- const parsedType = this._getType(input);
1030
- if (parsedType !== ZodParsedType.string) {
1031
- const ctx2 = this._getOrReturnCtx(input);
1032
- addIssueToContext(ctx2, {
1033
- code: ZodIssueCode.invalid_type,
1034
- expected: ZodParsedType.string,
1035
- received: ctx2.parsedType
1036
- });
1037
- return INVALID;
1038
- }
1039
- const status = new ParseStatus();
1040
- let ctx = void 0;
1041
- for (const check of this._def.checks) {
1042
- if (check.kind === "min") {
1043
- if (input.data.length < check.value) {
1044
- ctx = this._getOrReturnCtx(input, ctx);
1045
- addIssueToContext(ctx, {
1046
- code: ZodIssueCode.too_small,
1047
- minimum: check.value,
1048
- type: "string",
1049
- inclusive: true,
1050
- exact: false,
1051
- message: check.message
1052
- });
1053
- status.dirty();
1054
- }
1055
- } else if (check.kind === "max") {
1056
- if (input.data.length > check.value) {
1057
- ctx = this._getOrReturnCtx(input, ctx);
1058
- addIssueToContext(ctx, {
1059
- code: ZodIssueCode.too_big,
1060
- maximum: check.value,
1061
- type: "string",
1062
- inclusive: true,
1063
- exact: false,
1064
- message: check.message
1065
- });
1066
- status.dirty();
1067
- }
1068
- } else if (check.kind === "length") {
1069
- const tooBig = input.data.length > check.value;
1070
- const tooSmall = input.data.length < check.value;
1071
- if (tooBig || tooSmall) {
1072
- ctx = this._getOrReturnCtx(input, ctx);
1073
- if (tooBig) {
1074
- addIssueToContext(ctx, {
1075
- code: ZodIssueCode.too_big,
1076
- maximum: check.value,
1077
- type: "string",
1078
- inclusive: true,
1079
- exact: true,
1080
- message: check.message
1081
- });
1082
- } else if (tooSmall) {
1083
- addIssueToContext(ctx, {
1084
- code: ZodIssueCode.too_small,
1085
- minimum: check.value,
1086
- type: "string",
1087
- inclusive: true,
1088
- exact: true,
1089
- message: check.message
1090
- });
1091
- }
1092
- status.dirty();
1093
- }
1094
- } else if (check.kind === "email") {
1095
- if (!emailRegex.test(input.data)) {
1096
- ctx = this._getOrReturnCtx(input, ctx);
1097
- addIssueToContext(ctx, {
1098
- validation: "email",
1099
- code: ZodIssueCode.invalid_string,
1100
- message: check.message
1101
- });
1102
- status.dirty();
1103
- }
1104
- } else if (check.kind === "emoji") {
1105
- if (!emojiRegex) {
1106
- emojiRegex = new RegExp(_emojiRegex, "u");
1107
- }
1108
- if (!emojiRegex.test(input.data)) {
1109
- ctx = this._getOrReturnCtx(input, ctx);
1110
- addIssueToContext(ctx, {
1111
- validation: "emoji",
1112
- code: ZodIssueCode.invalid_string,
1113
- message: check.message
1114
- });
1115
- status.dirty();
1116
- }
1117
- } else if (check.kind === "uuid") {
1118
- if (!uuidRegex.test(input.data)) {
1119
- ctx = this._getOrReturnCtx(input, ctx);
1120
- addIssueToContext(ctx, {
1121
- validation: "uuid",
1122
- code: ZodIssueCode.invalid_string,
1123
- message: check.message
1124
- });
1125
- status.dirty();
1126
- }
1127
- } else if (check.kind === "nanoid") {
1128
- if (!nanoidRegex.test(input.data)) {
1129
- ctx = this._getOrReturnCtx(input, ctx);
1130
- addIssueToContext(ctx, {
1131
- validation: "nanoid",
1132
- code: ZodIssueCode.invalid_string,
1133
- message: check.message
1134
- });
1135
- status.dirty();
1136
- }
1137
- } else if (check.kind === "cuid") {
1138
- if (!cuidRegex.test(input.data)) {
1139
- ctx = this._getOrReturnCtx(input, ctx);
1140
- addIssueToContext(ctx, {
1141
- validation: "cuid",
1142
- code: ZodIssueCode.invalid_string,
1143
- message: check.message
1144
- });
1145
- status.dirty();
1146
- }
1147
- } else if (check.kind === "cuid2") {
1148
- if (!cuid2Regex.test(input.data)) {
1149
- ctx = this._getOrReturnCtx(input, ctx);
1150
- addIssueToContext(ctx, {
1151
- validation: "cuid2",
1152
- code: ZodIssueCode.invalid_string,
1153
- message: check.message
1154
- });
1155
- status.dirty();
1156
- }
1157
- } else if (check.kind === "ulid") {
1158
- if (!ulidRegex.test(input.data)) {
1159
- ctx = this._getOrReturnCtx(input, ctx);
1160
- addIssueToContext(ctx, {
1161
- validation: "ulid",
1162
- code: ZodIssueCode.invalid_string,
1163
- message: check.message
1164
- });
1165
- status.dirty();
1166
- }
1167
- } else if (check.kind === "url") {
1168
- try {
1169
- new URL(input.data);
1170
- } catch {
1171
- ctx = this._getOrReturnCtx(input, ctx);
1172
- addIssueToContext(ctx, {
1173
- validation: "url",
1174
- code: ZodIssueCode.invalid_string,
1175
- message: check.message
1176
- });
1177
- status.dirty();
1178
- }
1179
- } else if (check.kind === "regex") {
1180
- check.regex.lastIndex = 0;
1181
- const testResult = check.regex.test(input.data);
1182
- if (!testResult) {
1183
- ctx = this._getOrReturnCtx(input, ctx);
1184
- addIssueToContext(ctx, {
1185
- validation: "regex",
1186
- code: ZodIssueCode.invalid_string,
1187
- message: check.message
1188
- });
1189
- status.dirty();
1190
- }
1191
- } else if (check.kind === "trim") {
1192
- input.data = input.data.trim();
1193
- } else if (check.kind === "includes") {
1194
- if (!input.data.includes(check.value, check.position)) {
1195
- ctx = this._getOrReturnCtx(input, ctx);
1196
- addIssueToContext(ctx, {
1197
- code: ZodIssueCode.invalid_string,
1198
- validation: { includes: check.value, position: check.position },
1199
- message: check.message
1200
- });
1201
- status.dirty();
1202
- }
1203
- } else if (check.kind === "toLowerCase") {
1204
- input.data = input.data.toLowerCase();
1205
- } else if (check.kind === "toUpperCase") {
1206
- input.data = input.data.toUpperCase();
1207
- } else if (check.kind === "startsWith") {
1208
- if (!input.data.startsWith(check.value)) {
1209
- ctx = this._getOrReturnCtx(input, ctx);
1210
- addIssueToContext(ctx, {
1211
- code: ZodIssueCode.invalid_string,
1212
- validation: { startsWith: check.value },
1213
- message: check.message
1214
- });
1215
- status.dirty();
1216
- }
1217
- } else if (check.kind === "endsWith") {
1218
- if (!input.data.endsWith(check.value)) {
1219
- ctx = this._getOrReturnCtx(input, ctx);
1220
- addIssueToContext(ctx, {
1221
- code: ZodIssueCode.invalid_string,
1222
- validation: { endsWith: check.value },
1223
- message: check.message
1224
- });
1225
- status.dirty();
1226
- }
1227
- } else if (check.kind === "datetime") {
1228
- const regex = datetimeRegex(check);
1229
- if (!regex.test(input.data)) {
1230
- ctx = this._getOrReturnCtx(input, ctx);
1231
- addIssueToContext(ctx, {
1232
- code: ZodIssueCode.invalid_string,
1233
- validation: "datetime",
1234
- message: check.message
1235
- });
1236
- status.dirty();
1237
- }
1238
- } else if (check.kind === "date") {
1239
- const regex = dateRegex;
1240
- if (!regex.test(input.data)) {
1241
- ctx = this._getOrReturnCtx(input, ctx);
1242
- addIssueToContext(ctx, {
1243
- code: ZodIssueCode.invalid_string,
1244
- validation: "date",
1245
- message: check.message
1246
- });
1247
- status.dirty();
1248
- }
1249
- } else if (check.kind === "time") {
1250
- const regex = timeRegex(check);
1251
- if (!regex.test(input.data)) {
1252
- ctx = this._getOrReturnCtx(input, ctx);
1253
- addIssueToContext(ctx, {
1254
- code: ZodIssueCode.invalid_string,
1255
- validation: "time",
1256
- message: check.message
1257
- });
1258
- status.dirty();
1259
- }
1260
- } else if (check.kind === "duration") {
1261
- if (!durationRegex.test(input.data)) {
1262
- ctx = this._getOrReturnCtx(input, ctx);
1263
- addIssueToContext(ctx, {
1264
- validation: "duration",
1265
- code: ZodIssueCode.invalid_string,
1266
- message: check.message
1267
- });
1268
- status.dirty();
1269
- }
1270
- } else if (check.kind === "ip") {
1271
- if (!isValidIP(input.data, check.version)) {
1272
- ctx = this._getOrReturnCtx(input, ctx);
1273
- addIssueToContext(ctx, {
1274
- validation: "ip",
1275
- code: ZodIssueCode.invalid_string,
1276
- message: check.message
1277
- });
1278
- status.dirty();
1279
- }
1280
- } else if (check.kind === "jwt") {
1281
- if (!isValidJWT(input.data, check.alg)) {
1282
- ctx = this._getOrReturnCtx(input, ctx);
1283
- addIssueToContext(ctx, {
1284
- validation: "jwt",
1285
- code: ZodIssueCode.invalid_string,
1286
- message: check.message
1287
- });
1288
- status.dirty();
1289
- }
1290
- } else if (check.kind === "cidr") {
1291
- if (!isValidCidr(input.data, check.version)) {
1292
- ctx = this._getOrReturnCtx(input, ctx);
1293
- addIssueToContext(ctx, {
1294
- validation: "cidr",
1295
- code: ZodIssueCode.invalid_string,
1296
- message: check.message
1297
- });
1298
- status.dirty();
1299
- }
1300
- } else if (check.kind === "base64") {
1301
- if (!base64Regex.test(input.data)) {
1302
- ctx = this._getOrReturnCtx(input, ctx);
1303
- addIssueToContext(ctx, {
1304
- validation: "base64",
1305
- code: ZodIssueCode.invalid_string,
1306
- message: check.message
1307
- });
1308
- status.dirty();
1309
- }
1310
- } else if (check.kind === "base64url") {
1311
- if (!base64urlRegex.test(input.data)) {
1312
- ctx = this._getOrReturnCtx(input, ctx);
1313
- addIssueToContext(ctx, {
1314
- validation: "base64url",
1315
- code: ZodIssueCode.invalid_string,
1316
- message: check.message
1317
- });
1318
- status.dirty();
1319
- }
1320
- } else {
1321
- util.assertNever(check);
1322
- }
1323
- }
1324
- return { status: status.value, value: input.data };
1325
- }
1326
- _regex(regex, validation, message) {
1327
- return this.refinement((data) => regex.test(data), {
1328
- validation,
1329
- code: ZodIssueCode.invalid_string,
1330
- ...errorUtil.errToObj(message)
1331
- });
1332
- }
1333
- _addCheck(check) {
1334
- return new _ZodString({
1335
- ...this._def,
1336
- checks: [...this._def.checks, check]
1337
- });
1338
- }
1339
- email(message) {
1340
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1341
- }
1342
- url(message) {
1343
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1344
- }
1345
- emoji(message) {
1346
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1347
- }
1348
- uuid(message) {
1349
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1350
- }
1351
- nanoid(message) {
1352
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1353
- }
1354
- cuid(message) {
1355
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1356
- }
1357
- cuid2(message) {
1358
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1359
- }
1360
- ulid(message) {
1361
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1362
- }
1363
- base64(message) {
1364
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1365
- }
1366
- base64url(message) {
1367
- return this._addCheck({
1368
- kind: "base64url",
1369
- ...errorUtil.errToObj(message)
1370
- });
1371
- }
1372
- jwt(options) {
1373
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1374
- }
1375
- ip(options) {
1376
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1377
- }
1378
- cidr(options) {
1379
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1380
- }
1381
- datetime(options) {
1382
- if (typeof options === "string") {
1383
- return this._addCheck({
1384
- kind: "datetime",
1385
- precision: null,
1386
- offset: false,
1387
- local: false,
1388
- message: options
1389
- });
1390
- }
1391
- return this._addCheck({
1392
- kind: "datetime",
1393
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1394
- offset: options?.offset ?? false,
1395
- local: options?.local ?? false,
1396
- ...errorUtil.errToObj(options?.message)
1397
- });
1398
- }
1399
- date(message) {
1400
- return this._addCheck({ kind: "date", message });
1401
- }
1402
- time(options) {
1403
- if (typeof options === "string") {
1404
- return this._addCheck({
1405
- kind: "time",
1406
- precision: null,
1407
- message: options
1408
- });
1409
- }
1410
- return this._addCheck({
1411
- kind: "time",
1412
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1413
- ...errorUtil.errToObj(options?.message)
1414
- });
1415
- }
1416
- duration(message) {
1417
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1418
- }
1419
- regex(regex, message) {
1420
- return this._addCheck({
1421
- kind: "regex",
1422
- regex,
1423
- ...errorUtil.errToObj(message)
1424
- });
1425
- }
1426
- includes(value, options) {
1427
- return this._addCheck({
1428
- kind: "includes",
1429
- value,
1430
- position: options?.position,
1431
- ...errorUtil.errToObj(options?.message)
1432
- });
1433
- }
1434
- startsWith(value, message) {
1435
- return this._addCheck({
1436
- kind: "startsWith",
1437
- value,
1438
- ...errorUtil.errToObj(message)
1439
- });
1440
- }
1441
- endsWith(value, message) {
1442
- return this._addCheck({
1443
- kind: "endsWith",
1444
- value,
1445
- ...errorUtil.errToObj(message)
1446
- });
1447
- }
1448
- min(minLength, message) {
1449
- return this._addCheck({
1450
- kind: "min",
1451
- value: minLength,
1452
- ...errorUtil.errToObj(message)
1453
- });
1454
- }
1455
- max(maxLength, message) {
1456
- return this._addCheck({
1457
- kind: "max",
1458
- value: maxLength,
1459
- ...errorUtil.errToObj(message)
1460
- });
1461
- }
1462
- length(len, message) {
1463
- return this._addCheck({
1464
- kind: "length",
1465
- value: len,
1466
- ...errorUtil.errToObj(message)
1467
- });
1468
- }
1469
- /**
1470
- * Equivalent to `.min(1)`
1471
- */
1472
- nonempty(message) {
1473
- return this.min(1, errorUtil.errToObj(message));
1474
- }
1475
- trim() {
1476
- return new _ZodString({
1477
- ...this._def,
1478
- checks: [...this._def.checks, { kind: "trim" }]
1479
- });
1480
- }
1481
- toLowerCase() {
1482
- return new _ZodString({
1483
- ...this._def,
1484
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1485
- });
1486
- }
1487
- toUpperCase() {
1488
- return new _ZodString({
1489
- ...this._def,
1490
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1491
- });
1492
- }
1493
- get isDatetime() {
1494
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1495
- }
1496
- get isDate() {
1497
- return !!this._def.checks.find((ch) => ch.kind === "date");
1498
- }
1499
- get isTime() {
1500
- return !!this._def.checks.find((ch) => ch.kind === "time");
1501
- }
1502
- get isDuration() {
1503
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1504
- }
1505
- get isEmail() {
1506
- return !!this._def.checks.find((ch) => ch.kind === "email");
1507
- }
1508
- get isURL() {
1509
- return !!this._def.checks.find((ch) => ch.kind === "url");
1510
- }
1511
- get isEmoji() {
1512
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1513
- }
1514
- get isUUID() {
1515
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1516
- }
1517
- get isNANOID() {
1518
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1519
- }
1520
- get isCUID() {
1521
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1522
- }
1523
- get isCUID2() {
1524
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1525
- }
1526
- get isULID() {
1527
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1528
- }
1529
- get isIP() {
1530
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1531
- }
1532
- get isCIDR() {
1533
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1534
- }
1535
- get isBase64() {
1536
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1537
- }
1538
- get isBase64url() {
1539
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1540
- }
1541
- get minLength() {
1542
- let min = null;
1543
- for (const ch of this._def.checks) {
1544
- if (ch.kind === "min") {
1545
- if (min === null || ch.value > min)
1546
- min = ch.value;
1547
- }
1548
- }
1549
- return min;
1550
- }
1551
- get maxLength() {
1552
- let max = null;
1553
- for (const ch of this._def.checks) {
1554
- if (ch.kind === "max") {
1555
- if (max === null || ch.value < max)
1556
- max = ch.value;
1557
- }
1558
- }
1559
- return max;
1560
- }
1561
- };
1562
- ZodString.create = (params) => {
1563
- return new ZodString({
1564
- checks: [],
1565
- typeName: ZodFirstPartyTypeKind.ZodString,
1566
- coerce: params?.coerce ?? false,
1567
- ...processCreateParams(params)
1568
- });
1569
- };
1570
- function floatSafeRemainder(val, step) {
1571
- const valDecCount = (val.toString().split(".")[1] || "").length;
1572
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1573
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1574
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1575
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1576
- return valInt % stepInt / 10 ** decCount;
1577
- }
1578
- var ZodNumber = class _ZodNumber extends ZodType {
1579
- constructor() {
1580
- super(...arguments);
1581
- this.min = this.gte;
1582
- this.max = this.lte;
1583
- this.step = this.multipleOf;
1584
- }
1585
- _parse(input) {
1586
- if (this._def.coerce) {
1587
- input.data = Number(input.data);
1588
- }
1589
- const parsedType = this._getType(input);
1590
- if (parsedType !== ZodParsedType.number) {
1591
- const ctx2 = this._getOrReturnCtx(input);
1592
- addIssueToContext(ctx2, {
1593
- code: ZodIssueCode.invalid_type,
1594
- expected: ZodParsedType.number,
1595
- received: ctx2.parsedType
1596
- });
1597
- return INVALID;
1598
- }
1599
- let ctx = void 0;
1600
- const status = new ParseStatus();
1601
- for (const check of this._def.checks) {
1602
- if (check.kind === "int") {
1603
- if (!util.isInteger(input.data)) {
1604
- ctx = this._getOrReturnCtx(input, ctx);
1605
- addIssueToContext(ctx, {
1606
- code: ZodIssueCode.invalid_type,
1607
- expected: "integer",
1608
- received: "float",
1609
- message: check.message
1610
- });
1611
- status.dirty();
1612
- }
1613
- } else if (check.kind === "min") {
1614
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1615
- if (tooSmall) {
1616
- ctx = this._getOrReturnCtx(input, ctx);
1617
- addIssueToContext(ctx, {
1618
- code: ZodIssueCode.too_small,
1619
- minimum: check.value,
1620
- type: "number",
1621
- inclusive: check.inclusive,
1622
- exact: false,
1623
- message: check.message
1624
- });
1625
- status.dirty();
1626
- }
1627
- } else if (check.kind === "max") {
1628
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1629
- if (tooBig) {
1630
- ctx = this._getOrReturnCtx(input, ctx);
1631
- addIssueToContext(ctx, {
1632
- code: ZodIssueCode.too_big,
1633
- maximum: check.value,
1634
- type: "number",
1635
- inclusive: check.inclusive,
1636
- exact: false,
1637
- message: check.message
1638
- });
1639
- status.dirty();
1640
- }
1641
- } else if (check.kind === "multipleOf") {
1642
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1643
- ctx = this._getOrReturnCtx(input, ctx);
1644
- addIssueToContext(ctx, {
1645
- code: ZodIssueCode.not_multiple_of,
1646
- multipleOf: check.value,
1647
- message: check.message
1648
- });
1649
- status.dirty();
1650
- }
1651
- } else if (check.kind === "finite") {
1652
- if (!Number.isFinite(input.data)) {
1653
- ctx = this._getOrReturnCtx(input, ctx);
1654
- addIssueToContext(ctx, {
1655
- code: ZodIssueCode.not_finite,
1656
- message: check.message
1657
- });
1658
- status.dirty();
1659
- }
1660
- } else {
1661
- util.assertNever(check);
1662
- }
1663
- }
1664
- return { status: status.value, value: input.data };
1665
- }
1666
- gte(value, message) {
1667
- return this.setLimit("min", value, true, errorUtil.toString(message));
1668
- }
1669
- gt(value, message) {
1670
- return this.setLimit("min", value, false, errorUtil.toString(message));
1671
- }
1672
- lte(value, message) {
1673
- return this.setLimit("max", value, true, errorUtil.toString(message));
1674
- }
1675
- lt(value, message) {
1676
- return this.setLimit("max", value, false, errorUtil.toString(message));
1677
- }
1678
- setLimit(kind, value, inclusive, message) {
1679
- return new _ZodNumber({
1680
- ...this._def,
1681
- checks: [
1682
- ...this._def.checks,
1683
- {
1684
- kind,
1685
- value,
1686
- inclusive,
1687
- message: errorUtil.toString(message)
1688
- }
1689
- ]
1690
- });
1691
- }
1692
- _addCheck(check) {
1693
- return new _ZodNumber({
1694
- ...this._def,
1695
- checks: [...this._def.checks, check]
1696
- });
1697
- }
1698
- int(message) {
1699
- return this._addCheck({
1700
- kind: "int",
1701
- message: errorUtil.toString(message)
1702
- });
1703
- }
1704
- positive(message) {
1705
- return this._addCheck({
1706
- kind: "min",
1707
- value: 0,
1708
- inclusive: false,
1709
- message: errorUtil.toString(message)
1710
- });
1711
- }
1712
- negative(message) {
1713
- return this._addCheck({
1714
- kind: "max",
1715
- value: 0,
1716
- inclusive: false,
1717
- message: errorUtil.toString(message)
1718
- });
1719
- }
1720
- nonpositive(message) {
1721
- return this._addCheck({
1722
- kind: "max",
1723
- value: 0,
1724
- inclusive: true,
1725
- message: errorUtil.toString(message)
1726
- });
1727
- }
1728
- nonnegative(message) {
1729
- return this._addCheck({
1730
- kind: "min",
1731
- value: 0,
1732
- inclusive: true,
1733
- message: errorUtil.toString(message)
1734
- });
1735
- }
1736
- multipleOf(value, message) {
1737
- return this._addCheck({
1738
- kind: "multipleOf",
1739
- value,
1740
- message: errorUtil.toString(message)
1741
- });
1742
- }
1743
- finite(message) {
1744
- return this._addCheck({
1745
- kind: "finite",
1746
- message: errorUtil.toString(message)
1747
- });
1748
- }
1749
- safe(message) {
1750
- return this._addCheck({
1751
- kind: "min",
1752
- inclusive: true,
1753
- value: Number.MIN_SAFE_INTEGER,
1754
- message: errorUtil.toString(message)
1755
- })._addCheck({
1756
- kind: "max",
1757
- inclusive: true,
1758
- value: Number.MAX_SAFE_INTEGER,
1759
- message: errorUtil.toString(message)
1760
- });
1761
- }
1762
- get minValue() {
1763
- let min = null;
1764
- for (const ch of this._def.checks) {
1765
- if (ch.kind === "min") {
1766
- if (min === null || ch.value > min)
1767
- min = ch.value;
1768
- }
1769
- }
1770
- return min;
1771
- }
1772
- get maxValue() {
1773
- let max = null;
1774
- for (const ch of this._def.checks) {
1775
- if (ch.kind === "max") {
1776
- if (max === null || ch.value < max)
1777
- max = ch.value;
1778
- }
1779
- }
1780
- return max;
1781
- }
1782
- get isInt() {
1783
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1784
- }
1785
- get isFinite() {
1786
- let max = null;
1787
- let min = null;
1788
- for (const ch of this._def.checks) {
1789
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1790
- return true;
1791
- } else if (ch.kind === "min") {
1792
- if (min === null || ch.value > min)
1793
- min = ch.value;
1794
- } else if (ch.kind === "max") {
1795
- if (max === null || ch.value < max)
1796
- max = ch.value;
1797
- }
1798
- }
1799
- return Number.isFinite(min) && Number.isFinite(max);
1800
- }
1801
- };
1802
- ZodNumber.create = (params) => {
1803
- return new ZodNumber({
1804
- checks: [],
1805
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1806
- coerce: params?.coerce || false,
1807
- ...processCreateParams(params)
1808
- });
1809
- };
1810
- var ZodBigInt = class _ZodBigInt extends ZodType {
1811
- constructor() {
1812
- super(...arguments);
1813
- this.min = this.gte;
1814
- this.max = this.lte;
1815
- }
1816
- _parse(input) {
1817
- if (this._def.coerce) {
1818
- try {
1819
- input.data = BigInt(input.data);
1820
- } catch {
1821
- return this._getInvalidInput(input);
1822
- }
1823
- }
1824
- const parsedType = this._getType(input);
1825
- if (parsedType !== ZodParsedType.bigint) {
1826
- return this._getInvalidInput(input);
1827
- }
1828
- let ctx = void 0;
1829
- const status = new ParseStatus();
1830
- for (const check of this._def.checks) {
1831
- if (check.kind === "min") {
1832
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1833
- if (tooSmall) {
1834
- ctx = this._getOrReturnCtx(input, ctx);
1835
- addIssueToContext(ctx, {
1836
- code: ZodIssueCode.too_small,
1837
- type: "bigint",
1838
- minimum: check.value,
1839
- inclusive: check.inclusive,
1840
- message: check.message
1841
- });
1842
- status.dirty();
1843
- }
1844
- } else if (check.kind === "max") {
1845
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1846
- if (tooBig) {
1847
- ctx = this._getOrReturnCtx(input, ctx);
1848
- addIssueToContext(ctx, {
1849
- code: ZodIssueCode.too_big,
1850
- type: "bigint",
1851
- maximum: check.value,
1852
- inclusive: check.inclusive,
1853
- message: check.message
1854
- });
1855
- status.dirty();
1856
- }
1857
- } else if (check.kind === "multipleOf") {
1858
- if (input.data % check.value !== BigInt(0)) {
1859
- ctx = this._getOrReturnCtx(input, ctx);
1860
- addIssueToContext(ctx, {
1861
- code: ZodIssueCode.not_multiple_of,
1862
- multipleOf: check.value,
1863
- message: check.message
1864
- });
1865
- status.dirty();
1866
- }
1867
- } else {
1868
- util.assertNever(check);
1869
- }
1870
- }
1871
- return { status: status.value, value: input.data };
1872
- }
1873
- _getInvalidInput(input) {
1874
- const ctx = this._getOrReturnCtx(input);
1875
- addIssueToContext(ctx, {
1876
- code: ZodIssueCode.invalid_type,
1877
- expected: ZodParsedType.bigint,
1878
- received: ctx.parsedType
1879
- });
1880
- return INVALID;
1881
- }
1882
- gte(value, message) {
1883
- return this.setLimit("min", value, true, errorUtil.toString(message));
1884
- }
1885
- gt(value, message) {
1886
- return this.setLimit("min", value, false, errorUtil.toString(message));
1887
- }
1888
- lte(value, message) {
1889
- return this.setLimit("max", value, true, errorUtil.toString(message));
1890
- }
1891
- lt(value, message) {
1892
- return this.setLimit("max", value, false, errorUtil.toString(message));
1893
- }
1894
- setLimit(kind, value, inclusive, message) {
1895
- return new _ZodBigInt({
1896
- ...this._def,
1897
- checks: [
1898
- ...this._def.checks,
1899
- {
1900
- kind,
1901
- value,
1902
- inclusive,
1903
- message: errorUtil.toString(message)
1904
- }
1905
- ]
1906
- });
1907
- }
1908
- _addCheck(check) {
1909
- return new _ZodBigInt({
1910
- ...this._def,
1911
- checks: [...this._def.checks, check]
1912
- });
1913
- }
1914
- positive(message) {
1915
- return this._addCheck({
1916
- kind: "min",
1917
- value: BigInt(0),
1918
- inclusive: false,
1919
- message: errorUtil.toString(message)
1920
- });
1921
- }
1922
- negative(message) {
1923
- return this._addCheck({
1924
- kind: "max",
1925
- value: BigInt(0),
1926
- inclusive: false,
1927
- message: errorUtil.toString(message)
1928
- });
1929
- }
1930
- nonpositive(message) {
1931
- return this._addCheck({
1932
- kind: "max",
1933
- value: BigInt(0),
1934
- inclusive: true,
1935
- message: errorUtil.toString(message)
1936
- });
1937
- }
1938
- nonnegative(message) {
1939
- return this._addCheck({
1940
- kind: "min",
1941
- value: BigInt(0),
1942
- inclusive: true,
1943
- message: errorUtil.toString(message)
1944
- });
1945
- }
1946
- multipleOf(value, message) {
1947
- return this._addCheck({
1948
- kind: "multipleOf",
1949
- value,
1950
- message: errorUtil.toString(message)
1951
- });
1952
- }
1953
- get minValue() {
1954
- let min = null;
1955
- for (const ch of this._def.checks) {
1956
- if (ch.kind === "min") {
1957
- if (min === null || ch.value > min)
1958
- min = ch.value;
1959
- }
1960
- }
1961
- return min;
1962
- }
1963
- get maxValue() {
1964
- let max = null;
1965
- for (const ch of this._def.checks) {
1966
- if (ch.kind === "max") {
1967
- if (max === null || ch.value < max)
1968
- max = ch.value;
1969
- }
1970
- }
1971
- return max;
1972
- }
1973
- };
1974
- ZodBigInt.create = (params) => {
1975
- return new ZodBigInt({
1976
- checks: [],
1977
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1978
- coerce: params?.coerce ?? false,
1979
- ...processCreateParams(params)
1980
- });
1981
- };
1982
- var ZodBoolean = class extends ZodType {
1983
- _parse(input) {
1984
- if (this._def.coerce) {
1985
- input.data = Boolean(input.data);
1986
- }
1987
- const parsedType = this._getType(input);
1988
- if (parsedType !== ZodParsedType.boolean) {
1989
- const ctx = this._getOrReturnCtx(input);
1990
- addIssueToContext(ctx, {
1991
- code: ZodIssueCode.invalid_type,
1992
- expected: ZodParsedType.boolean,
1993
- received: ctx.parsedType
1994
- });
1995
- return INVALID;
1996
- }
1997
- return OK(input.data);
1998
- }
1999
- };
2000
- ZodBoolean.create = (params) => {
2001
- return new ZodBoolean({
2002
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2003
- coerce: params?.coerce || false,
2004
- ...processCreateParams(params)
2005
- });
2006
- };
2007
- var ZodDate = class _ZodDate extends ZodType {
2008
- _parse(input) {
2009
- if (this._def.coerce) {
2010
- input.data = new Date(input.data);
2011
- }
2012
- const parsedType = this._getType(input);
2013
- if (parsedType !== ZodParsedType.date) {
2014
- const ctx2 = this._getOrReturnCtx(input);
2015
- addIssueToContext(ctx2, {
2016
- code: ZodIssueCode.invalid_type,
2017
- expected: ZodParsedType.date,
2018
- received: ctx2.parsedType
2019
- });
2020
- return INVALID;
2021
- }
2022
- if (Number.isNaN(input.data.getTime())) {
2023
- const ctx2 = this._getOrReturnCtx(input);
2024
- addIssueToContext(ctx2, {
2025
- code: ZodIssueCode.invalid_date
2026
- });
2027
- return INVALID;
2028
- }
2029
- const status = new ParseStatus();
2030
- let ctx = void 0;
2031
- for (const check of this._def.checks) {
2032
- if (check.kind === "min") {
2033
- if (input.data.getTime() < check.value) {
2034
- ctx = this._getOrReturnCtx(input, ctx);
2035
- addIssueToContext(ctx, {
2036
- code: ZodIssueCode.too_small,
2037
- message: check.message,
2038
- inclusive: true,
2039
- exact: false,
2040
- minimum: check.value,
2041
- type: "date"
2042
- });
2043
- status.dirty();
2044
- }
2045
- } else if (check.kind === "max") {
2046
- if (input.data.getTime() > check.value) {
2047
- ctx = this._getOrReturnCtx(input, ctx);
2048
- addIssueToContext(ctx, {
2049
- code: ZodIssueCode.too_big,
2050
- message: check.message,
2051
- inclusive: true,
2052
- exact: false,
2053
- maximum: check.value,
2054
- type: "date"
2055
- });
2056
- status.dirty();
2057
- }
2058
- } else {
2059
- util.assertNever(check);
2060
- }
2061
- }
2062
- return {
2063
- status: status.value,
2064
- value: new Date(input.data.getTime())
2065
- };
2066
- }
2067
- _addCheck(check) {
2068
- return new _ZodDate({
2069
- ...this._def,
2070
- checks: [...this._def.checks, check]
2071
- });
2072
- }
2073
- min(minDate, message) {
2074
- return this._addCheck({
2075
- kind: "min",
2076
- value: minDate.getTime(),
2077
- message: errorUtil.toString(message)
2078
- });
2079
- }
2080
- max(maxDate, message) {
2081
- return this._addCheck({
2082
- kind: "max",
2083
- value: maxDate.getTime(),
2084
- message: errorUtil.toString(message)
2085
- });
2086
- }
2087
- get minDate() {
2088
- let min = null;
2089
- for (const ch of this._def.checks) {
2090
- if (ch.kind === "min") {
2091
- if (min === null || ch.value > min)
2092
- min = ch.value;
2093
- }
2094
- }
2095
- return min != null ? new Date(min) : null;
2096
- }
2097
- get maxDate() {
2098
- let max = null;
2099
- for (const ch of this._def.checks) {
2100
- if (ch.kind === "max") {
2101
- if (max === null || ch.value < max)
2102
- max = ch.value;
2103
- }
2104
- }
2105
- return max != null ? new Date(max) : null;
2106
- }
2107
- };
2108
- ZodDate.create = (params) => {
2109
- return new ZodDate({
2110
- checks: [],
2111
- coerce: params?.coerce || false,
2112
- typeName: ZodFirstPartyTypeKind.ZodDate,
2113
- ...processCreateParams(params)
2114
- });
2115
- };
2116
- var ZodSymbol = class extends ZodType {
2117
- _parse(input) {
2118
- const parsedType = this._getType(input);
2119
- if (parsedType !== ZodParsedType.symbol) {
2120
- const ctx = this._getOrReturnCtx(input);
2121
- addIssueToContext(ctx, {
2122
- code: ZodIssueCode.invalid_type,
2123
- expected: ZodParsedType.symbol,
2124
- received: ctx.parsedType
2125
- });
2126
- return INVALID;
2127
- }
2128
- return OK(input.data);
2129
- }
2130
- };
2131
- ZodSymbol.create = (params) => {
2132
- return new ZodSymbol({
2133
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2134
- ...processCreateParams(params)
2135
- });
2136
- };
2137
- var ZodUndefined = class extends ZodType {
2138
- _parse(input) {
2139
- const parsedType = this._getType(input);
2140
- if (parsedType !== ZodParsedType.undefined) {
2141
- const ctx = this._getOrReturnCtx(input);
2142
- addIssueToContext(ctx, {
2143
- code: ZodIssueCode.invalid_type,
2144
- expected: ZodParsedType.undefined,
2145
- received: ctx.parsedType
2146
- });
2147
- return INVALID;
2148
- }
2149
- return OK(input.data);
2150
- }
2151
- };
2152
- ZodUndefined.create = (params) => {
2153
- return new ZodUndefined({
2154
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2155
- ...processCreateParams(params)
2156
- });
2157
- };
2158
- var ZodNull = class extends ZodType {
2159
- _parse(input) {
2160
- const parsedType = this._getType(input);
2161
- if (parsedType !== ZodParsedType.null) {
2162
- const ctx = this._getOrReturnCtx(input);
2163
- addIssueToContext(ctx, {
2164
- code: ZodIssueCode.invalid_type,
2165
- expected: ZodParsedType.null,
2166
- received: ctx.parsedType
2167
- });
2168
- return INVALID;
2169
- }
2170
- return OK(input.data);
2171
- }
2172
- };
2173
- ZodNull.create = (params) => {
2174
- return new ZodNull({
2175
- typeName: ZodFirstPartyTypeKind.ZodNull,
2176
- ...processCreateParams(params)
2177
- });
2178
- };
2179
- var ZodAny = class extends ZodType {
2180
- constructor() {
2181
- super(...arguments);
2182
- this._any = true;
2183
- }
2184
- _parse(input) {
2185
- return OK(input.data);
2186
- }
2187
- };
2188
- ZodAny.create = (params) => {
2189
- return new ZodAny({
2190
- typeName: ZodFirstPartyTypeKind.ZodAny,
2191
- ...processCreateParams(params)
2192
- });
2193
- };
2194
- var ZodUnknown = class extends ZodType {
2195
- constructor() {
2196
- super(...arguments);
2197
- this._unknown = true;
2198
- }
2199
- _parse(input) {
2200
- return OK(input.data);
2201
- }
2202
- };
2203
- ZodUnknown.create = (params) => {
2204
- return new ZodUnknown({
2205
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2206
- ...processCreateParams(params)
2207
- });
2208
- };
2209
- var ZodNever = class extends ZodType {
2210
- _parse(input) {
2211
- const ctx = this._getOrReturnCtx(input);
2212
- addIssueToContext(ctx, {
2213
- code: ZodIssueCode.invalid_type,
2214
- expected: ZodParsedType.never,
2215
- received: ctx.parsedType
2216
- });
2217
- return INVALID;
2218
- }
2219
- };
2220
- ZodNever.create = (params) => {
2221
- return new ZodNever({
2222
- typeName: ZodFirstPartyTypeKind.ZodNever,
2223
- ...processCreateParams(params)
2224
- });
2225
- };
2226
- var ZodVoid = class extends ZodType {
2227
- _parse(input) {
2228
- const parsedType = this._getType(input);
2229
- if (parsedType !== ZodParsedType.undefined) {
2230
- const ctx = this._getOrReturnCtx(input);
2231
- addIssueToContext(ctx, {
2232
- code: ZodIssueCode.invalid_type,
2233
- expected: ZodParsedType.void,
2234
- received: ctx.parsedType
2235
- });
2236
- return INVALID;
2237
- }
2238
- return OK(input.data);
2239
- }
2240
- };
2241
- ZodVoid.create = (params) => {
2242
- return new ZodVoid({
2243
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2244
- ...processCreateParams(params)
2245
- });
2246
- };
2247
- var ZodArray = class _ZodArray extends ZodType {
2248
- _parse(input) {
2249
- const { ctx, status } = this._processInputParams(input);
2250
- const def = this._def;
2251
- if (ctx.parsedType !== ZodParsedType.array) {
2252
- addIssueToContext(ctx, {
2253
- code: ZodIssueCode.invalid_type,
2254
- expected: ZodParsedType.array,
2255
- received: ctx.parsedType
2256
- });
2257
- return INVALID;
2258
- }
2259
- if (def.exactLength !== null) {
2260
- const tooBig = ctx.data.length > def.exactLength.value;
2261
- const tooSmall = ctx.data.length < def.exactLength.value;
2262
- if (tooBig || tooSmall) {
2263
- addIssueToContext(ctx, {
2264
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2265
- minimum: tooSmall ? def.exactLength.value : void 0,
2266
- maximum: tooBig ? def.exactLength.value : void 0,
2267
- type: "array",
2268
- inclusive: true,
2269
- exact: true,
2270
- message: def.exactLength.message
2271
- });
2272
- status.dirty();
2273
- }
2274
- }
2275
- if (def.minLength !== null) {
2276
- if (ctx.data.length < def.minLength.value) {
2277
- addIssueToContext(ctx, {
2278
- code: ZodIssueCode.too_small,
2279
- minimum: def.minLength.value,
2280
- type: "array",
2281
- inclusive: true,
2282
- exact: false,
2283
- message: def.minLength.message
2284
- });
2285
- status.dirty();
2286
- }
2287
- }
2288
- if (def.maxLength !== null) {
2289
- if (ctx.data.length > def.maxLength.value) {
2290
- addIssueToContext(ctx, {
2291
- code: ZodIssueCode.too_big,
2292
- maximum: def.maxLength.value,
2293
- type: "array",
2294
- inclusive: true,
2295
- exact: false,
2296
- message: def.maxLength.message
2297
- });
2298
- status.dirty();
2299
- }
2300
- }
2301
- if (ctx.common.async) {
2302
- return Promise.all([...ctx.data].map((item, i) => {
2303
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2304
- })).then((result2) => {
2305
- return ParseStatus.mergeArray(status, result2);
2306
- });
2307
- }
2308
- const result = [...ctx.data].map((item, i) => {
2309
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2310
- });
2311
- return ParseStatus.mergeArray(status, result);
2312
- }
2313
- get element() {
2314
- return this._def.type;
2315
- }
2316
- min(minLength, message) {
2317
- return new _ZodArray({
2318
- ...this._def,
2319
- minLength: { value: minLength, message: errorUtil.toString(message) }
2320
- });
2321
- }
2322
- max(maxLength, message) {
2323
- return new _ZodArray({
2324
- ...this._def,
2325
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
2326
- });
2327
- }
2328
- length(len, message) {
2329
- return new _ZodArray({
2330
- ...this._def,
2331
- exactLength: { value: len, message: errorUtil.toString(message) }
2332
- });
2333
- }
2334
- nonempty(message) {
2335
- return this.min(1, message);
2336
- }
2337
- };
2338
- ZodArray.create = (schema, params) => {
2339
- return new ZodArray({
2340
- type: schema,
2341
- minLength: null,
2342
- maxLength: null,
2343
- exactLength: null,
2344
- typeName: ZodFirstPartyTypeKind.ZodArray,
2345
- ...processCreateParams(params)
2346
- });
2347
- };
2348
- function deepPartialify(schema) {
2349
- if (schema instanceof ZodObject) {
2350
- const newShape = {};
2351
- for (const key in schema.shape) {
2352
- const fieldSchema = schema.shape[key];
2353
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2354
- }
2355
- return new ZodObject({
2356
- ...schema._def,
2357
- shape: () => newShape
2358
- });
2359
- } else if (schema instanceof ZodArray) {
2360
- return new ZodArray({
2361
- ...schema._def,
2362
- type: deepPartialify(schema.element)
2363
- });
2364
- } else if (schema instanceof ZodOptional) {
2365
- return ZodOptional.create(deepPartialify(schema.unwrap()));
2366
- } else if (schema instanceof ZodNullable) {
2367
- return ZodNullable.create(deepPartialify(schema.unwrap()));
2368
- } else if (schema instanceof ZodTuple) {
2369
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2370
- } else {
2371
- return schema;
2372
- }
2373
- }
2374
- var ZodObject = class _ZodObject extends ZodType {
2375
- constructor() {
2376
- super(...arguments);
2377
- this._cached = null;
2378
- this.nonstrict = this.passthrough;
2379
- this.augment = this.extend;
2380
- }
2381
- _getCached() {
2382
- if (this._cached !== null)
2383
- return this._cached;
2384
- const shape = this._def.shape();
2385
- const keys = util.objectKeys(shape);
2386
- this._cached = { shape, keys };
2387
- return this._cached;
2388
- }
2389
- _parse(input) {
2390
- const parsedType = this._getType(input);
2391
- if (parsedType !== ZodParsedType.object) {
2392
- const ctx2 = this._getOrReturnCtx(input);
2393
- addIssueToContext(ctx2, {
2394
- code: ZodIssueCode.invalid_type,
2395
- expected: ZodParsedType.object,
2396
- received: ctx2.parsedType
2397
- });
2398
- return INVALID;
2399
- }
2400
- const { status, ctx } = this._processInputParams(input);
2401
- const { shape, keys: shapeKeys } = this._getCached();
2402
- const extraKeys = [];
2403
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2404
- for (const key in ctx.data) {
2405
- if (!shapeKeys.includes(key)) {
2406
- extraKeys.push(key);
2407
- }
2408
- }
2409
- }
2410
- const pairs = [];
2411
- for (const key of shapeKeys) {
2412
- const keyValidator = shape[key];
2413
- const value = ctx.data[key];
2414
- pairs.push({
2415
- key: { status: "valid", value: key },
2416
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2417
- alwaysSet: key in ctx.data
2418
- });
2419
- }
2420
- if (this._def.catchall instanceof ZodNever) {
2421
- const unknownKeys = this._def.unknownKeys;
2422
- if (unknownKeys === "passthrough") {
2423
- for (const key of extraKeys) {
2424
- pairs.push({
2425
- key: { status: "valid", value: key },
2426
- value: { status: "valid", value: ctx.data[key] }
2427
- });
2428
- }
2429
- } else if (unknownKeys === "strict") {
2430
- if (extraKeys.length > 0) {
2431
- addIssueToContext(ctx, {
2432
- code: ZodIssueCode.unrecognized_keys,
2433
- keys: extraKeys
2434
- });
2435
- status.dirty();
2436
- }
2437
- } else if (unknownKeys === "strip") {
2438
- } else {
2439
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2440
- }
2441
- } else {
2442
- const catchall = this._def.catchall;
2443
- for (const key of extraKeys) {
2444
- const value = ctx.data[key];
2445
- pairs.push({
2446
- key: { status: "valid", value: key },
2447
- value: catchall._parse(
2448
- new ParseInputLazyPath(ctx, value, ctx.path, key)
2449
- //, ctx.child(key), value, getParsedType(value)
2450
- ),
2451
- alwaysSet: key in ctx.data
2452
- });
2453
- }
2454
- }
2455
- if (ctx.common.async) {
2456
- return Promise.resolve().then(async () => {
2457
- const syncPairs = [];
2458
- for (const pair of pairs) {
2459
- const key = await pair.key;
2460
- const value = await pair.value;
2461
- syncPairs.push({
2462
- key,
2463
- value,
2464
- alwaysSet: pair.alwaysSet
2465
- });
2466
- }
2467
- return syncPairs;
2468
- }).then((syncPairs) => {
2469
- return ParseStatus.mergeObjectSync(status, syncPairs);
2470
- });
2471
- } else {
2472
- return ParseStatus.mergeObjectSync(status, pairs);
2473
- }
2474
- }
2475
- get shape() {
2476
- return this._def.shape();
2477
- }
2478
- strict(message) {
2479
- errorUtil.errToObj;
2480
- return new _ZodObject({
2481
- ...this._def,
2482
- unknownKeys: "strict",
2483
- ...message !== void 0 ? {
2484
- errorMap: (issue, ctx) => {
2485
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2486
- if (issue.code === "unrecognized_keys")
2487
- return {
2488
- message: errorUtil.errToObj(message).message ?? defaultError
2489
- };
2490
- return {
2491
- message: defaultError
2492
- };
2493
- }
2494
- } : {}
2495
- });
2496
- }
2497
- strip() {
2498
- return new _ZodObject({
2499
- ...this._def,
2500
- unknownKeys: "strip"
2501
- });
2502
- }
2503
- passthrough() {
2504
- return new _ZodObject({
2505
- ...this._def,
2506
- unknownKeys: "passthrough"
2507
- });
2508
- }
2509
- // const AugmentFactory =
2510
- // <Def extends ZodObjectDef>(def: Def) =>
2511
- // <Augmentation extends ZodRawShape>(
2512
- // augmentation: Augmentation
2513
- // ): ZodObject<
2514
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2515
- // Def["unknownKeys"],
2516
- // Def["catchall"]
2517
- // > => {
2518
- // return new ZodObject({
2519
- // ...def,
2520
- // shape: () => ({
2521
- // ...def.shape(),
2522
- // ...augmentation,
2523
- // }),
2524
- // }) as any;
2525
- // };
2526
- extend(augmentation) {
2527
- return new _ZodObject({
2528
- ...this._def,
2529
- shape: () => ({
2530
- ...this._def.shape(),
2531
- ...augmentation
2532
- })
2533
- });
2534
- }
2535
- /**
2536
- * Prior to zod@1.0.12 there was a bug in the
2537
- * inferred type of merged objects. Please
2538
- * upgrade if you are experiencing issues.
2539
- */
2540
- merge(merging) {
2541
- const merged = new _ZodObject({
2542
- unknownKeys: merging._def.unknownKeys,
2543
- catchall: merging._def.catchall,
2544
- shape: () => ({
2545
- ...this._def.shape(),
2546
- ...merging._def.shape()
2547
- }),
2548
- typeName: ZodFirstPartyTypeKind.ZodObject
2549
- });
2550
- return merged;
2551
- }
2552
- // merge<
2553
- // Incoming extends AnyZodObject,
2554
- // Augmentation extends Incoming["shape"],
2555
- // NewOutput extends {
2556
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2557
- // ? Augmentation[k]["_output"]
2558
- // : k extends keyof Output
2559
- // ? Output[k]
2560
- // : never;
2561
- // },
2562
- // NewInput extends {
2563
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2564
- // ? Augmentation[k]["_input"]
2565
- // : k extends keyof Input
2566
- // ? Input[k]
2567
- // : never;
2568
- // }
2569
- // >(
2570
- // merging: Incoming
2571
- // ): ZodObject<
2572
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2573
- // Incoming["_def"]["unknownKeys"],
2574
- // Incoming["_def"]["catchall"],
2575
- // NewOutput,
2576
- // NewInput
2577
- // > {
2578
- // const merged: any = new ZodObject({
2579
- // unknownKeys: merging._def.unknownKeys,
2580
- // catchall: merging._def.catchall,
2581
- // shape: () =>
2582
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2583
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2584
- // }) as any;
2585
- // return merged;
2586
- // }
2587
- setKey(key, schema) {
2588
- return this.augment({ [key]: schema });
2589
- }
2590
- // merge<Incoming extends AnyZodObject>(
2591
- // merging: Incoming
2592
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2593
- // ZodObject<
2594
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2595
- // Incoming["_def"]["unknownKeys"],
2596
- // Incoming["_def"]["catchall"]
2597
- // > {
2598
- // // const mergedShape = objectUtil.mergeShapes(
2599
- // // this._def.shape(),
2600
- // // merging._def.shape()
2601
- // // );
2602
- // const merged: any = new ZodObject({
2603
- // unknownKeys: merging._def.unknownKeys,
2604
- // catchall: merging._def.catchall,
2605
- // shape: () =>
2606
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2607
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2608
- // }) as any;
2609
- // return merged;
2610
- // }
2611
- catchall(index) {
2612
- return new _ZodObject({
2613
- ...this._def,
2614
- catchall: index
2615
- });
2616
- }
2617
- pick(mask) {
2618
- const shape = {};
2619
- for (const key of util.objectKeys(mask)) {
2620
- if (mask[key] && this.shape[key]) {
2621
- shape[key] = this.shape[key];
2622
- }
2623
- }
2624
- return new _ZodObject({
2625
- ...this._def,
2626
- shape: () => shape
2627
- });
2628
- }
2629
- omit(mask) {
2630
- const shape = {};
2631
- for (const key of util.objectKeys(this.shape)) {
2632
- if (!mask[key]) {
2633
- shape[key] = this.shape[key];
2634
- }
2635
- }
2636
- return new _ZodObject({
2637
- ...this._def,
2638
- shape: () => shape
2639
- });
2640
- }
2641
- /**
2642
- * @deprecated
2643
- */
2644
- deepPartial() {
2645
- return deepPartialify(this);
2646
- }
2647
- partial(mask) {
2648
- const newShape = {};
2649
- for (const key of util.objectKeys(this.shape)) {
2650
- const fieldSchema = this.shape[key];
2651
- if (mask && !mask[key]) {
2652
- newShape[key] = fieldSchema;
2653
- } else {
2654
- newShape[key] = fieldSchema.optional();
2655
- }
2656
- }
2657
- return new _ZodObject({
2658
- ...this._def,
2659
- shape: () => newShape
2660
- });
2661
- }
2662
- required(mask) {
2663
- const newShape = {};
2664
- for (const key of util.objectKeys(this.shape)) {
2665
- if (mask && !mask[key]) {
2666
- newShape[key] = this.shape[key];
2667
- } else {
2668
- const fieldSchema = this.shape[key];
2669
- let newField = fieldSchema;
2670
- while (newField instanceof ZodOptional) {
2671
- newField = newField._def.innerType;
2672
- }
2673
- newShape[key] = newField;
2674
- }
2675
- }
2676
- return new _ZodObject({
2677
- ...this._def,
2678
- shape: () => newShape
2679
- });
2680
- }
2681
- keyof() {
2682
- return createZodEnum(util.objectKeys(this.shape));
2683
- }
2684
- };
2685
- ZodObject.create = (shape, params) => {
2686
- return new ZodObject({
2687
- shape: () => shape,
2688
- unknownKeys: "strip",
2689
- catchall: ZodNever.create(),
2690
- typeName: ZodFirstPartyTypeKind.ZodObject,
2691
- ...processCreateParams(params)
2692
- });
2693
- };
2694
- ZodObject.strictCreate = (shape, params) => {
2695
- return new ZodObject({
2696
- shape: () => shape,
2697
- unknownKeys: "strict",
2698
- catchall: ZodNever.create(),
2699
- typeName: ZodFirstPartyTypeKind.ZodObject,
2700
- ...processCreateParams(params)
2701
- });
2702
- };
2703
- ZodObject.lazycreate = (shape, params) => {
2704
- return new ZodObject({
2705
- shape,
2706
- unknownKeys: "strip",
2707
- catchall: ZodNever.create(),
2708
- typeName: ZodFirstPartyTypeKind.ZodObject,
2709
- ...processCreateParams(params)
2710
- });
2711
- };
2712
- var ZodUnion = class extends ZodType {
2713
- _parse(input) {
2714
- const { ctx } = this._processInputParams(input);
2715
- const options = this._def.options;
2716
- function handleResults(results) {
2717
- for (const result of results) {
2718
- if (result.result.status === "valid") {
2719
- return result.result;
2720
- }
2721
- }
2722
- for (const result of results) {
2723
- if (result.result.status === "dirty") {
2724
- ctx.common.issues.push(...result.ctx.common.issues);
2725
- return result.result;
2726
- }
2727
- }
2728
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2729
- addIssueToContext(ctx, {
2730
- code: ZodIssueCode.invalid_union,
2731
- unionErrors
2732
- });
2733
- return INVALID;
2734
- }
2735
- if (ctx.common.async) {
2736
- return Promise.all(options.map(async (option) => {
2737
- const childCtx = {
2738
- ...ctx,
2739
- common: {
2740
- ...ctx.common,
2741
- issues: []
2742
- },
2743
- parent: null
2744
- };
2745
- return {
2746
- result: await option._parseAsync({
2747
- data: ctx.data,
2748
- path: ctx.path,
2749
- parent: childCtx
2750
- }),
2751
- ctx: childCtx
2752
- };
2753
- })).then(handleResults);
2754
- } else {
2755
- let dirty = void 0;
2756
- const issues = [];
2757
- for (const option of options) {
2758
- const childCtx = {
2759
- ...ctx,
2760
- common: {
2761
- ...ctx.common,
2762
- issues: []
2763
- },
2764
- parent: null
2765
- };
2766
- const result = option._parseSync({
2767
- data: ctx.data,
2768
- path: ctx.path,
2769
- parent: childCtx
2770
- });
2771
- if (result.status === "valid") {
2772
- return result;
2773
- } else if (result.status === "dirty" && !dirty) {
2774
- dirty = { result, ctx: childCtx };
2775
- }
2776
- if (childCtx.common.issues.length) {
2777
- issues.push(childCtx.common.issues);
2778
- }
2779
- }
2780
- if (dirty) {
2781
- ctx.common.issues.push(...dirty.ctx.common.issues);
2782
- return dirty.result;
2783
- }
2784
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
2785
- addIssueToContext(ctx, {
2786
- code: ZodIssueCode.invalid_union,
2787
- unionErrors
2788
- });
2789
- return INVALID;
2790
- }
2791
- }
2792
- get options() {
2793
- return this._def.options;
2794
- }
2795
- };
2796
- ZodUnion.create = (types, params) => {
2797
- return new ZodUnion({
2798
- options: types,
2799
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2800
- ...processCreateParams(params)
2801
- });
2802
- };
2803
- var getDiscriminator = (type) => {
2804
- if (type instanceof ZodLazy) {
2805
- return getDiscriminator(type.schema);
2806
- } else if (type instanceof ZodEffects) {
2807
- return getDiscriminator(type.innerType());
2808
- } else if (type instanceof ZodLiteral) {
2809
- return [type.value];
2810
- } else if (type instanceof ZodEnum) {
2811
- return type.options;
2812
- } else if (type instanceof ZodNativeEnum) {
2813
- return util.objectValues(type.enum);
2814
- } else if (type instanceof ZodDefault) {
2815
- return getDiscriminator(type._def.innerType);
2816
- } else if (type instanceof ZodUndefined) {
2817
- return [void 0];
2818
- } else if (type instanceof ZodNull) {
2819
- return [null];
2820
- } else if (type instanceof ZodOptional) {
2821
- return [void 0, ...getDiscriminator(type.unwrap())];
2822
- } else if (type instanceof ZodNullable) {
2823
- return [null, ...getDiscriminator(type.unwrap())];
2824
- } else if (type instanceof ZodBranded) {
2825
- return getDiscriminator(type.unwrap());
2826
- } else if (type instanceof ZodReadonly) {
2827
- return getDiscriminator(type.unwrap());
2828
- } else if (type instanceof ZodCatch) {
2829
- return getDiscriminator(type._def.innerType);
2830
- } else {
2831
- return [];
2832
- }
2833
- };
2834
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
2835
- _parse(input) {
2836
- const { ctx } = this._processInputParams(input);
2837
- if (ctx.parsedType !== ZodParsedType.object) {
2838
- addIssueToContext(ctx, {
2839
- code: ZodIssueCode.invalid_type,
2840
- expected: ZodParsedType.object,
2841
- received: ctx.parsedType
2842
- });
2843
- return INVALID;
2844
- }
2845
- const discriminator = this.discriminator;
2846
- const discriminatorValue = ctx.data[discriminator];
2847
- const option = this.optionsMap.get(discriminatorValue);
2848
- if (!option) {
2849
- addIssueToContext(ctx, {
2850
- code: ZodIssueCode.invalid_union_discriminator,
2851
- options: Array.from(this.optionsMap.keys()),
2852
- path: [discriminator]
2853
- });
2854
- return INVALID;
2855
- }
2856
- if (ctx.common.async) {
2857
- return option._parseAsync({
2858
- data: ctx.data,
2859
- path: ctx.path,
2860
- parent: ctx
2861
- });
2862
- } else {
2863
- return option._parseSync({
2864
- data: ctx.data,
2865
- path: ctx.path,
2866
- parent: ctx
2867
- });
2868
- }
2869
- }
2870
- get discriminator() {
2871
- return this._def.discriminator;
2872
- }
2873
- get options() {
2874
- return this._def.options;
2875
- }
2876
- get optionsMap() {
2877
- return this._def.optionsMap;
2878
- }
2879
- /**
2880
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2881
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2882
- * have a different value for each object in the union.
2883
- * @param discriminator the name of the discriminator property
2884
- * @param types an array of object schemas
2885
- * @param params
2886
- */
2887
- static create(discriminator, options, params) {
2888
- const optionsMap = /* @__PURE__ */ new Map();
2889
- for (const type of options) {
2890
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2891
- if (!discriminatorValues.length) {
2892
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2893
- }
2894
- for (const value of discriminatorValues) {
2895
- if (optionsMap.has(value)) {
2896
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2897
- }
2898
- optionsMap.set(value, type);
2899
- }
2900
- }
2901
- return new _ZodDiscriminatedUnion({
2902
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2903
- discriminator,
2904
- options,
2905
- optionsMap,
2906
- ...processCreateParams(params)
2907
- });
2908
- }
2909
- };
2910
- function mergeValues(a, b) {
2911
- const aType = getParsedType(a);
2912
- const bType = getParsedType(b);
2913
- if (a === b) {
2914
- return { valid: true, data: a };
2915
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2916
- const bKeys = util.objectKeys(b);
2917
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2918
- const newObj = { ...a, ...b };
2919
- for (const key of sharedKeys) {
2920
- const sharedValue = mergeValues(a[key], b[key]);
2921
- if (!sharedValue.valid) {
2922
- return { valid: false };
2923
- }
2924
- newObj[key] = sharedValue.data;
2925
- }
2926
- return { valid: true, data: newObj };
2927
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2928
- if (a.length !== b.length) {
2929
- return { valid: false };
2930
- }
2931
- const newArray = [];
2932
- for (let index = 0; index < a.length; index++) {
2933
- const itemA = a[index];
2934
- const itemB = b[index];
2935
- const sharedValue = mergeValues(itemA, itemB);
2936
- if (!sharedValue.valid) {
2937
- return { valid: false };
2938
- }
2939
- newArray.push(sharedValue.data);
2940
- }
2941
- return { valid: true, data: newArray };
2942
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2943
- return { valid: true, data: a };
2944
- } else {
2945
- return { valid: false };
2946
- }
2947
- }
2948
- var ZodIntersection = class extends ZodType {
2949
- _parse(input) {
2950
- const { status, ctx } = this._processInputParams(input);
2951
- const handleParsed = (parsedLeft, parsedRight) => {
2952
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2953
- return INVALID;
2954
- }
2955
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2956
- if (!merged.valid) {
2957
- addIssueToContext(ctx, {
2958
- code: ZodIssueCode.invalid_intersection_types
2959
- });
2960
- return INVALID;
2961
- }
2962
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2963
- status.dirty();
2964
- }
2965
- return { status: status.value, value: merged.data };
2966
- };
2967
- if (ctx.common.async) {
2968
- return Promise.all([
2969
- this._def.left._parseAsync({
2970
- data: ctx.data,
2971
- path: ctx.path,
2972
- parent: ctx
2973
- }),
2974
- this._def.right._parseAsync({
2975
- data: ctx.data,
2976
- path: ctx.path,
2977
- parent: ctx
2978
- })
2979
- ]).then(([left, right]) => handleParsed(left, right));
2980
- } else {
2981
- return handleParsed(this._def.left._parseSync({
2982
- data: ctx.data,
2983
- path: ctx.path,
2984
- parent: ctx
2985
- }), this._def.right._parseSync({
2986
- data: ctx.data,
2987
- path: ctx.path,
2988
- parent: ctx
2989
- }));
2990
- }
2991
- }
2992
- };
2993
- ZodIntersection.create = (left, right, params) => {
2994
- return new ZodIntersection({
2995
- left,
2996
- right,
2997
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
2998
- ...processCreateParams(params)
2999
- });
3000
- };
3001
- var ZodTuple = class _ZodTuple extends ZodType {
3002
- _parse(input) {
3003
- const { status, ctx } = this._processInputParams(input);
3004
- if (ctx.parsedType !== ZodParsedType.array) {
3005
- addIssueToContext(ctx, {
3006
- code: ZodIssueCode.invalid_type,
3007
- expected: ZodParsedType.array,
3008
- received: ctx.parsedType
3009
- });
3010
- return INVALID;
3011
- }
3012
- if (ctx.data.length < this._def.items.length) {
3013
- addIssueToContext(ctx, {
3014
- code: ZodIssueCode.too_small,
3015
- minimum: this._def.items.length,
3016
- inclusive: true,
3017
- exact: false,
3018
- type: "array"
3019
- });
3020
- return INVALID;
3021
- }
3022
- const rest = this._def.rest;
3023
- if (!rest && ctx.data.length > this._def.items.length) {
3024
- addIssueToContext(ctx, {
3025
- code: ZodIssueCode.too_big,
3026
- maximum: this._def.items.length,
3027
- inclusive: true,
3028
- exact: false,
3029
- type: "array"
3030
- });
3031
- status.dirty();
3032
- }
3033
- const items = [...ctx.data].map((item, itemIndex) => {
3034
- const schema = this._def.items[itemIndex] || this._def.rest;
3035
- if (!schema)
3036
- return null;
3037
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3038
- }).filter((x) => !!x);
3039
- if (ctx.common.async) {
3040
- return Promise.all(items).then((results) => {
3041
- return ParseStatus.mergeArray(status, results);
3042
- });
3043
- } else {
3044
- return ParseStatus.mergeArray(status, items);
3045
- }
3046
- }
3047
- get items() {
3048
- return this._def.items;
3049
- }
3050
- rest(rest) {
3051
- return new _ZodTuple({
3052
- ...this._def,
3053
- rest
3054
- });
3055
- }
3056
- };
3057
- ZodTuple.create = (schemas, params) => {
3058
- if (!Array.isArray(schemas)) {
3059
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3060
- }
3061
- return new ZodTuple({
3062
- items: schemas,
3063
- typeName: ZodFirstPartyTypeKind.ZodTuple,
3064
- rest: null,
3065
- ...processCreateParams(params)
3066
- });
3067
- };
3068
- var ZodRecord = class _ZodRecord extends ZodType {
3069
- get keySchema() {
3070
- return this._def.keyType;
3071
- }
3072
- get valueSchema() {
3073
- return this._def.valueType;
3074
- }
3075
- _parse(input) {
3076
- const { status, ctx } = this._processInputParams(input);
3077
- if (ctx.parsedType !== ZodParsedType.object) {
3078
- addIssueToContext(ctx, {
3079
- code: ZodIssueCode.invalid_type,
3080
- expected: ZodParsedType.object,
3081
- received: ctx.parsedType
3082
- });
3083
- return INVALID;
3084
- }
3085
- const pairs = [];
3086
- const keyType = this._def.keyType;
3087
- const valueType = this._def.valueType;
3088
- for (const key in ctx.data) {
3089
- pairs.push({
3090
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3091
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3092
- alwaysSet: key in ctx.data
3093
- });
3094
- }
3095
- if (ctx.common.async) {
3096
- return ParseStatus.mergeObjectAsync(status, pairs);
3097
- } else {
3098
- return ParseStatus.mergeObjectSync(status, pairs);
3099
- }
3100
- }
3101
- get element() {
3102
- return this._def.valueType;
3103
- }
3104
- static create(first, second, third) {
3105
- if (second instanceof ZodType) {
3106
- return new _ZodRecord({
3107
- keyType: first,
3108
- valueType: second,
3109
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3110
- ...processCreateParams(third)
3111
- });
3112
- }
3113
- return new _ZodRecord({
3114
- keyType: ZodString.create(),
3115
- valueType: first,
3116
- typeName: ZodFirstPartyTypeKind.ZodRecord,
3117
- ...processCreateParams(second)
3118
- });
3119
- }
3120
- };
3121
- var ZodMap = class extends ZodType {
3122
- get keySchema() {
3123
- return this._def.keyType;
3124
- }
3125
- get valueSchema() {
3126
- return this._def.valueType;
3127
- }
3128
- _parse(input) {
3129
- const { status, ctx } = this._processInputParams(input);
3130
- if (ctx.parsedType !== ZodParsedType.map) {
3131
- addIssueToContext(ctx, {
3132
- code: ZodIssueCode.invalid_type,
3133
- expected: ZodParsedType.map,
3134
- received: ctx.parsedType
3135
- });
3136
- return INVALID;
3137
- }
3138
- const keyType = this._def.keyType;
3139
- const valueType = this._def.valueType;
3140
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3141
- return {
3142
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3143
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3144
- };
3145
- });
3146
- if (ctx.common.async) {
3147
- const finalMap = /* @__PURE__ */ new Map();
3148
- return Promise.resolve().then(async () => {
3149
- for (const pair of pairs) {
3150
- const key = await pair.key;
3151
- const value = await pair.value;
3152
- if (key.status === "aborted" || value.status === "aborted") {
3153
- return INVALID;
3154
- }
3155
- if (key.status === "dirty" || value.status === "dirty") {
3156
- status.dirty();
3157
- }
3158
- finalMap.set(key.value, value.value);
3159
- }
3160
- return { status: status.value, value: finalMap };
3161
- });
3162
- } else {
3163
- const finalMap = /* @__PURE__ */ new Map();
3164
- for (const pair of pairs) {
3165
- const key = pair.key;
3166
- const value = pair.value;
3167
- if (key.status === "aborted" || value.status === "aborted") {
3168
- return INVALID;
3169
- }
3170
- if (key.status === "dirty" || value.status === "dirty") {
3171
- status.dirty();
3172
- }
3173
- finalMap.set(key.value, value.value);
3174
- }
3175
- return { status: status.value, value: finalMap };
3176
- }
3177
- }
3178
- };
3179
- ZodMap.create = (keyType, valueType, params) => {
3180
- return new ZodMap({
3181
- valueType,
3182
- keyType,
3183
- typeName: ZodFirstPartyTypeKind.ZodMap,
3184
- ...processCreateParams(params)
3185
- });
3186
- };
3187
- var ZodSet = class _ZodSet extends ZodType {
3188
- _parse(input) {
3189
- const { status, ctx } = this._processInputParams(input);
3190
- if (ctx.parsedType !== ZodParsedType.set) {
3191
- addIssueToContext(ctx, {
3192
- code: ZodIssueCode.invalid_type,
3193
- expected: ZodParsedType.set,
3194
- received: ctx.parsedType
3195
- });
3196
- return INVALID;
3197
- }
3198
- const def = this._def;
3199
- if (def.minSize !== null) {
3200
- if (ctx.data.size < def.minSize.value) {
3201
- addIssueToContext(ctx, {
3202
- code: ZodIssueCode.too_small,
3203
- minimum: def.minSize.value,
3204
- type: "set",
3205
- inclusive: true,
3206
- exact: false,
3207
- message: def.minSize.message
3208
- });
3209
- status.dirty();
3210
- }
3211
- }
3212
- if (def.maxSize !== null) {
3213
- if (ctx.data.size > def.maxSize.value) {
3214
- addIssueToContext(ctx, {
3215
- code: ZodIssueCode.too_big,
3216
- maximum: def.maxSize.value,
3217
- type: "set",
3218
- inclusive: true,
3219
- exact: false,
3220
- message: def.maxSize.message
3221
- });
3222
- status.dirty();
3223
- }
3224
- }
3225
- const valueType = this._def.valueType;
3226
- function finalizeSet(elements2) {
3227
- const parsedSet = /* @__PURE__ */ new Set();
3228
- for (const element of elements2) {
3229
- if (element.status === "aborted")
3230
- return INVALID;
3231
- if (element.status === "dirty")
3232
- status.dirty();
3233
- parsedSet.add(element.value);
3234
- }
3235
- return { status: status.value, value: parsedSet };
3236
- }
3237
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3238
- if (ctx.common.async) {
3239
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3240
- } else {
3241
- return finalizeSet(elements);
3242
- }
3243
- }
3244
- min(minSize, message) {
3245
- return new _ZodSet({
3246
- ...this._def,
3247
- minSize: { value: minSize, message: errorUtil.toString(message) }
3248
- });
3249
- }
3250
- max(maxSize, message) {
3251
- return new _ZodSet({
3252
- ...this._def,
3253
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
3254
- });
3255
- }
3256
- size(size, message) {
3257
- return this.min(size, message).max(size, message);
3258
- }
3259
- nonempty(message) {
3260
- return this.min(1, message);
3261
- }
3262
- };
3263
- ZodSet.create = (valueType, params) => {
3264
- return new ZodSet({
3265
- valueType,
3266
- minSize: null,
3267
- maxSize: null,
3268
- typeName: ZodFirstPartyTypeKind.ZodSet,
3269
- ...processCreateParams(params)
3270
- });
3271
- };
3272
- var ZodFunction = class _ZodFunction extends ZodType {
3273
- constructor() {
3274
- super(...arguments);
3275
- this.validate = this.implement;
3276
- }
3277
- _parse(input) {
3278
- const { ctx } = this._processInputParams(input);
3279
- if (ctx.parsedType !== ZodParsedType.function) {
3280
- addIssueToContext(ctx, {
3281
- code: ZodIssueCode.invalid_type,
3282
- expected: ZodParsedType.function,
3283
- received: ctx.parsedType
3284
- });
3285
- return INVALID;
3286
- }
3287
- function makeArgsIssue(args, error) {
3288
- return makeIssue({
3289
- data: args,
3290
- path: ctx.path,
3291
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3292
- issueData: {
3293
- code: ZodIssueCode.invalid_arguments,
3294
- argumentsError: error
3295
- }
3296
- });
3297
- }
3298
- function makeReturnsIssue(returns, error) {
3299
- return makeIssue({
3300
- data: returns,
3301
- path: ctx.path,
3302
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3303
- issueData: {
3304
- code: ZodIssueCode.invalid_return_type,
3305
- returnTypeError: error
3306
- }
3307
- });
3308
- }
3309
- const params = { errorMap: ctx.common.contextualErrorMap };
3310
- const fn = ctx.data;
3311
- if (this._def.returns instanceof ZodPromise) {
3312
- const me = this;
3313
- return OK(async function(...args) {
3314
- const error = new ZodError([]);
3315
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3316
- error.addIssue(makeArgsIssue(args, e));
3317
- throw error;
3318
- });
3319
- const result = await Reflect.apply(fn, this, parsedArgs);
3320
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3321
- error.addIssue(makeReturnsIssue(result, e));
3322
- throw error;
3323
- });
3324
- return parsedReturns;
3325
- });
3326
- } else {
3327
- const me = this;
3328
- return OK(function(...args) {
3329
- const parsedArgs = me._def.args.safeParse(args, params);
3330
- if (!parsedArgs.success) {
3331
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3332
- }
3333
- const result = Reflect.apply(fn, this, parsedArgs.data);
3334
- const parsedReturns = me._def.returns.safeParse(result, params);
3335
- if (!parsedReturns.success) {
3336
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3337
- }
3338
- return parsedReturns.data;
3339
- });
3340
- }
3341
- }
3342
- parameters() {
3343
- return this._def.args;
3344
- }
3345
- returnType() {
3346
- return this._def.returns;
3347
- }
3348
- args(...items) {
3349
- return new _ZodFunction({
3350
- ...this._def,
3351
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3352
- });
3353
- }
3354
- returns(returnType) {
3355
- return new _ZodFunction({
3356
- ...this._def,
3357
- returns: returnType
3358
- });
3359
- }
3360
- implement(func) {
3361
- const validatedFunc = this.parse(func);
3362
- return validatedFunc;
3363
- }
3364
- strictImplement(func) {
3365
- const validatedFunc = this.parse(func);
3366
- return validatedFunc;
3367
- }
3368
- static create(args, returns, params) {
3369
- return new _ZodFunction({
3370
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3371
- returns: returns || ZodUnknown.create(),
3372
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3373
- ...processCreateParams(params)
3374
- });
3375
- }
3376
- };
3377
- var ZodLazy = class extends ZodType {
3378
- get schema() {
3379
- return this._def.getter();
3380
- }
3381
- _parse(input) {
3382
- const { ctx } = this._processInputParams(input);
3383
- const lazySchema = this._def.getter();
3384
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3385
- }
3386
- };
3387
- ZodLazy.create = (getter, params) => {
3388
- return new ZodLazy({
3389
- getter,
3390
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3391
- ...processCreateParams(params)
3392
- });
3393
- };
3394
- var ZodLiteral = class extends ZodType {
3395
- _parse(input) {
3396
- if (input.data !== this._def.value) {
3397
- const ctx = this._getOrReturnCtx(input);
3398
- addIssueToContext(ctx, {
3399
- received: ctx.data,
3400
- code: ZodIssueCode.invalid_literal,
3401
- expected: this._def.value
3402
- });
3403
- return INVALID;
3404
- }
3405
- return { status: "valid", value: input.data };
3406
- }
3407
- get value() {
3408
- return this._def.value;
3409
- }
3410
- };
3411
- ZodLiteral.create = (value, params) => {
3412
- return new ZodLiteral({
3413
- value,
3414
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3415
- ...processCreateParams(params)
3416
- });
3417
- };
3418
- function createZodEnum(values, params) {
3419
- return new ZodEnum({
3420
- values,
3421
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3422
- ...processCreateParams(params)
3423
- });
3424
- }
3425
- var ZodEnum = class _ZodEnum extends ZodType {
3426
- _parse(input) {
3427
- if (typeof input.data !== "string") {
3428
- const ctx = this._getOrReturnCtx(input);
3429
- const expectedValues = this._def.values;
3430
- addIssueToContext(ctx, {
3431
- expected: util.joinValues(expectedValues),
3432
- received: ctx.parsedType,
3433
- code: ZodIssueCode.invalid_type
3434
- });
3435
- return INVALID;
3436
- }
3437
- if (!this._cache) {
3438
- this._cache = new Set(this._def.values);
3439
- }
3440
- if (!this._cache.has(input.data)) {
3441
- const ctx = this._getOrReturnCtx(input);
3442
- const expectedValues = this._def.values;
3443
- addIssueToContext(ctx, {
3444
- received: ctx.data,
3445
- code: ZodIssueCode.invalid_enum_value,
3446
- options: expectedValues
3447
- });
3448
- return INVALID;
3449
- }
3450
- return OK(input.data);
3451
- }
3452
- get options() {
3453
- return this._def.values;
3454
- }
3455
- get enum() {
3456
- const enumValues = {};
3457
- for (const val of this._def.values) {
3458
- enumValues[val] = val;
3459
- }
3460
- return enumValues;
3461
- }
3462
- get Values() {
3463
- const enumValues = {};
3464
- for (const val of this._def.values) {
3465
- enumValues[val] = val;
3466
- }
3467
- return enumValues;
3468
- }
3469
- get Enum() {
3470
- const enumValues = {};
3471
- for (const val of this._def.values) {
3472
- enumValues[val] = val;
3473
- }
3474
- return enumValues;
3475
- }
3476
- extract(values, newDef = this._def) {
3477
- return _ZodEnum.create(values, {
3478
- ...this._def,
3479
- ...newDef
3480
- });
3481
- }
3482
- exclude(values, newDef = this._def) {
3483
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3484
- ...this._def,
3485
- ...newDef
3486
- });
3487
- }
3488
- };
3489
- ZodEnum.create = createZodEnum;
3490
- var ZodNativeEnum = class extends ZodType {
3491
- _parse(input) {
3492
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3493
- const ctx = this._getOrReturnCtx(input);
3494
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3495
- const expectedValues = util.objectValues(nativeEnumValues);
3496
- addIssueToContext(ctx, {
3497
- expected: util.joinValues(expectedValues),
3498
- received: ctx.parsedType,
3499
- code: ZodIssueCode.invalid_type
3500
- });
3501
- return INVALID;
3502
- }
3503
- if (!this._cache) {
3504
- this._cache = new Set(util.getValidEnumValues(this._def.values));
3505
- }
3506
- if (!this._cache.has(input.data)) {
3507
- const expectedValues = util.objectValues(nativeEnumValues);
3508
- addIssueToContext(ctx, {
3509
- received: ctx.data,
3510
- code: ZodIssueCode.invalid_enum_value,
3511
- options: expectedValues
3512
- });
3513
- return INVALID;
3514
- }
3515
- return OK(input.data);
3516
- }
3517
- get enum() {
3518
- return this._def.values;
3519
- }
3520
- };
3521
- ZodNativeEnum.create = (values, params) => {
3522
- return new ZodNativeEnum({
3523
- values,
3524
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3525
- ...processCreateParams(params)
3526
- });
3527
- };
3528
- var ZodPromise = class extends ZodType {
3529
- unwrap() {
3530
- return this._def.type;
3531
- }
3532
- _parse(input) {
3533
- const { ctx } = this._processInputParams(input);
3534
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3535
- addIssueToContext(ctx, {
3536
- code: ZodIssueCode.invalid_type,
3537
- expected: ZodParsedType.promise,
3538
- received: ctx.parsedType
3539
- });
3540
- return INVALID;
3541
- }
3542
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3543
- return OK(promisified.then((data) => {
3544
- return this._def.type.parseAsync(data, {
3545
- path: ctx.path,
3546
- errorMap: ctx.common.contextualErrorMap
3547
- });
3548
- }));
3549
- }
3550
- };
3551
- ZodPromise.create = (schema, params) => {
3552
- return new ZodPromise({
3553
- type: schema,
3554
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3555
- ...processCreateParams(params)
3556
- });
3557
- };
3558
- var ZodEffects = class extends ZodType {
3559
- innerType() {
3560
- return this._def.schema;
3561
- }
3562
- sourceType() {
3563
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3564
- }
3565
- _parse(input) {
3566
- const { status, ctx } = this._processInputParams(input);
3567
- const effect = this._def.effect || null;
3568
- const checkCtx = {
3569
- addIssue: (arg) => {
3570
- addIssueToContext(ctx, arg);
3571
- if (arg.fatal) {
3572
- status.abort();
3573
- } else {
3574
- status.dirty();
3575
- }
3576
- },
3577
- get path() {
3578
- return ctx.path;
3579
- }
3580
- };
3581
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3582
- if (effect.type === "preprocess") {
3583
- const processed = effect.transform(ctx.data, checkCtx);
3584
- if (ctx.common.async) {
3585
- return Promise.resolve(processed).then(async (processed2) => {
3586
- if (status.value === "aborted")
3587
- return INVALID;
3588
- const result = await this._def.schema._parseAsync({
3589
- data: processed2,
3590
- path: ctx.path,
3591
- parent: ctx
3592
- });
3593
- if (result.status === "aborted")
3594
- return INVALID;
3595
- if (result.status === "dirty")
3596
- return DIRTY(result.value);
3597
- if (status.value === "dirty")
3598
- return DIRTY(result.value);
3599
- return result;
3600
- });
3601
- } else {
3602
- if (status.value === "aborted")
3603
- return INVALID;
3604
- const result = this._def.schema._parseSync({
3605
- data: processed,
3606
- path: ctx.path,
3607
- parent: ctx
3608
- });
3609
- if (result.status === "aborted")
3610
- return INVALID;
3611
- if (result.status === "dirty")
3612
- return DIRTY(result.value);
3613
- if (status.value === "dirty")
3614
- return DIRTY(result.value);
3615
- return result;
3616
- }
3617
- }
3618
- if (effect.type === "refinement") {
3619
- const executeRefinement = (acc) => {
3620
- const result = effect.refinement(acc, checkCtx);
3621
- if (ctx.common.async) {
3622
- return Promise.resolve(result);
3623
- }
3624
- if (result instanceof Promise) {
3625
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3626
- }
3627
- return acc;
3628
- };
3629
- if (ctx.common.async === false) {
3630
- const inner = this._def.schema._parseSync({
3631
- data: ctx.data,
3632
- path: ctx.path,
3633
- parent: ctx
3634
- });
3635
- if (inner.status === "aborted")
3636
- return INVALID;
3637
- if (inner.status === "dirty")
3638
- status.dirty();
3639
- executeRefinement(inner.value);
3640
- return { status: status.value, value: inner.value };
3641
- } else {
3642
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3643
- if (inner.status === "aborted")
3644
- return INVALID;
3645
- if (inner.status === "dirty")
3646
- status.dirty();
3647
- return executeRefinement(inner.value).then(() => {
3648
- return { status: status.value, value: inner.value };
3649
- });
3650
- });
3651
- }
3652
- }
3653
- if (effect.type === "transform") {
3654
- if (ctx.common.async === false) {
3655
- const base = this._def.schema._parseSync({
3656
- data: ctx.data,
3657
- path: ctx.path,
3658
- parent: ctx
3659
- });
3660
- if (!isValid(base))
3661
- return INVALID;
3662
- const result = effect.transform(base.value, checkCtx);
3663
- if (result instanceof Promise) {
3664
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3665
- }
3666
- return { status: status.value, value: result };
3667
- } else {
3668
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3669
- if (!isValid(base))
3670
- return INVALID;
3671
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3672
- status: status.value,
3673
- value: result
3674
- }));
3675
- });
3676
- }
3677
- }
3678
- util.assertNever(effect);
3679
- }
3680
- };
3681
- ZodEffects.create = (schema, effect, params) => {
3682
- return new ZodEffects({
3683
- schema,
3684
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3685
- effect,
3686
- ...processCreateParams(params)
3687
- });
3688
- };
3689
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3690
- return new ZodEffects({
3691
- schema,
3692
- effect: { type: "preprocess", transform: preprocess },
3693
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3694
- ...processCreateParams(params)
3695
- });
3696
- };
3697
- var ZodOptional = class extends ZodType {
3698
- _parse(input) {
3699
- const parsedType = this._getType(input);
3700
- if (parsedType === ZodParsedType.undefined) {
3701
- return OK(void 0);
3702
- }
3703
- return this._def.innerType._parse(input);
3704
- }
3705
- unwrap() {
3706
- return this._def.innerType;
3707
- }
3708
- };
3709
- ZodOptional.create = (type, params) => {
3710
- return new ZodOptional({
3711
- innerType: type,
3712
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3713
- ...processCreateParams(params)
3714
- });
3715
- };
3716
- var ZodNullable = class extends ZodType {
3717
- _parse(input) {
3718
- const parsedType = this._getType(input);
3719
- if (parsedType === ZodParsedType.null) {
3720
- return OK(null);
3721
- }
3722
- return this._def.innerType._parse(input);
3723
- }
3724
- unwrap() {
3725
- return this._def.innerType;
3726
- }
3727
- };
3728
- ZodNullable.create = (type, params) => {
3729
- return new ZodNullable({
3730
- innerType: type,
3731
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3732
- ...processCreateParams(params)
3733
- });
3734
- };
3735
- var ZodDefault = class extends ZodType {
3736
- _parse(input) {
3737
- const { ctx } = this._processInputParams(input);
3738
- let data = ctx.data;
3739
- if (ctx.parsedType === ZodParsedType.undefined) {
3740
- data = this._def.defaultValue();
3741
- }
3742
- return this._def.innerType._parse({
3743
- data,
3744
- path: ctx.path,
3745
- parent: ctx
3746
- });
3747
- }
3748
- removeDefault() {
3749
- return this._def.innerType;
3750
- }
3751
- };
3752
- ZodDefault.create = (type, params) => {
3753
- return new ZodDefault({
3754
- innerType: type,
3755
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3756
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3757
- ...processCreateParams(params)
3758
- });
3759
- };
3760
- var ZodCatch = class extends ZodType {
3761
- _parse(input) {
3762
- const { ctx } = this._processInputParams(input);
3763
- const newCtx = {
3764
- ...ctx,
3765
- common: {
3766
- ...ctx.common,
3767
- issues: []
3768
- }
3769
- };
3770
- const result = this._def.innerType._parse({
3771
- data: newCtx.data,
3772
- path: newCtx.path,
3773
- parent: {
3774
- ...newCtx
3775
- }
3776
- });
3777
- if (isAsync(result)) {
3778
- return result.then((result2) => {
3779
- return {
3780
- status: "valid",
3781
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
3782
- get error() {
3783
- return new ZodError(newCtx.common.issues);
3784
- },
3785
- input: newCtx.data
3786
- })
3787
- };
3788
- });
3789
- } else {
3790
- return {
3791
- status: "valid",
3792
- value: result.status === "valid" ? result.value : this._def.catchValue({
3793
- get error() {
3794
- return new ZodError(newCtx.common.issues);
3795
- },
3796
- input: newCtx.data
3797
- })
3798
- };
3799
- }
3800
- }
3801
- removeCatch() {
3802
- return this._def.innerType;
3803
- }
3804
- };
3805
- ZodCatch.create = (type, params) => {
3806
- return new ZodCatch({
3807
- innerType: type,
3808
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3809
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3810
- ...processCreateParams(params)
3811
- });
3812
- };
3813
- var ZodNaN = class extends ZodType {
3814
- _parse(input) {
3815
- const parsedType = this._getType(input);
3816
- if (parsedType !== ZodParsedType.nan) {
3817
- const ctx = this._getOrReturnCtx(input);
3818
- addIssueToContext(ctx, {
3819
- code: ZodIssueCode.invalid_type,
3820
- expected: ZodParsedType.nan,
3821
- received: ctx.parsedType
3822
- });
3823
- return INVALID;
3824
- }
3825
- return { status: "valid", value: input.data };
3826
- }
3827
- };
3828
- ZodNaN.create = (params) => {
3829
- return new ZodNaN({
3830
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3831
- ...processCreateParams(params)
3832
- });
3833
- };
3834
- var BRAND = /* @__PURE__ */ Symbol("zod_brand");
3835
- var ZodBranded = class extends ZodType {
3836
- _parse(input) {
3837
- const { ctx } = this._processInputParams(input);
3838
- const data = ctx.data;
3839
- return this._def.type._parse({
3840
- data,
3841
- path: ctx.path,
3842
- parent: ctx
3843
- });
3844
- }
3845
- unwrap() {
3846
- return this._def.type;
3847
- }
3848
- };
3849
- var ZodPipeline = class _ZodPipeline extends ZodType {
3850
- _parse(input) {
3851
- const { status, ctx } = this._processInputParams(input);
3852
- if (ctx.common.async) {
3853
- const handleAsync = async () => {
3854
- const inResult = await this._def.in._parseAsync({
3855
- data: ctx.data,
3856
- path: ctx.path,
3857
- parent: ctx
3858
- });
3859
- if (inResult.status === "aborted")
3860
- return INVALID;
3861
- if (inResult.status === "dirty") {
3862
- status.dirty();
3863
- return DIRTY(inResult.value);
3864
- } else {
3865
- return this._def.out._parseAsync({
3866
- data: inResult.value,
3867
- path: ctx.path,
3868
- parent: ctx
3869
- });
3870
- }
3871
- };
3872
- return handleAsync();
3873
- } else {
3874
- const inResult = this._def.in._parseSync({
3875
- data: ctx.data,
3876
- path: ctx.path,
3877
- parent: ctx
3878
- });
3879
- if (inResult.status === "aborted")
3880
- return INVALID;
3881
- if (inResult.status === "dirty") {
3882
- status.dirty();
3883
- return {
3884
- status: "dirty",
3885
- value: inResult.value
3886
- };
3887
- } else {
3888
- return this._def.out._parseSync({
3889
- data: inResult.value,
3890
- path: ctx.path,
3891
- parent: ctx
3892
- });
3893
- }
3894
- }
3895
- }
3896
- static create(a, b) {
3897
- return new _ZodPipeline({
3898
- in: a,
3899
- out: b,
3900
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3901
- });
3902
- }
3903
- };
3904
- var ZodReadonly = class extends ZodType {
3905
- _parse(input) {
3906
- const result = this._def.innerType._parse(input);
3907
- const freeze = (data) => {
3908
- if (isValid(data)) {
3909
- data.value = Object.freeze(data.value);
3910
- }
3911
- return data;
3912
- };
3913
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3914
- }
3915
- unwrap() {
3916
- return this._def.innerType;
3917
- }
3918
- };
3919
- ZodReadonly.create = (type, params) => {
3920
- return new ZodReadonly({
3921
- innerType: type,
3922
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3923
- ...processCreateParams(params)
3924
- });
3925
- };
3926
- function cleanParams(params, data) {
3927
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3928
- const p2 = typeof p === "string" ? { message: p } : p;
3929
- return p2;
3930
- }
3931
- function custom(check, _params = {}, fatal) {
3932
- if (check)
3933
- return ZodAny.create().superRefine((data, ctx) => {
3934
- const r = check(data);
3935
- if (r instanceof Promise) {
3936
- return r.then((r2) => {
3937
- if (!r2) {
3938
- const params = cleanParams(_params, data);
3939
- const _fatal = params.fatal ?? fatal ?? true;
3940
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3941
- }
3942
- });
3943
- }
3944
- if (!r) {
3945
- const params = cleanParams(_params, data);
3946
- const _fatal = params.fatal ?? fatal ?? true;
3947
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3948
- }
3949
- return;
3950
- });
3951
- return ZodAny.create();
3952
- }
3953
- var late = {
3954
- object: ZodObject.lazycreate
3955
- };
3956
- var ZodFirstPartyTypeKind;
3957
- (function(ZodFirstPartyTypeKind2) {
3958
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
3959
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
3960
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
3961
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
3962
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
3963
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
3964
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
3965
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
3966
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
3967
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
3968
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
3969
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
3970
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
3971
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
3972
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
3973
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
3974
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3975
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
3976
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
3977
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
3978
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
3979
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
3980
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
3981
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
3982
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
3983
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
3984
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
3985
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
3986
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
3987
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
3988
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
3989
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
3990
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
3991
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
3992
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
3993
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
3994
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3995
- var instanceOfType = (cls, params = {
3996
- message: `Input not instance of ${cls.name}`
3997
- }) => custom((data) => data instanceof cls, params);
3998
- var stringType = ZodString.create;
3999
- var numberType = ZodNumber.create;
4000
- var nanType = ZodNaN.create;
4001
- var bigIntType = ZodBigInt.create;
4002
- var booleanType = ZodBoolean.create;
4003
- var dateType = ZodDate.create;
4004
- var symbolType = ZodSymbol.create;
4005
- var undefinedType = ZodUndefined.create;
4006
- var nullType = ZodNull.create;
4007
- var anyType = ZodAny.create;
4008
- var unknownType = ZodUnknown.create;
4009
- var neverType = ZodNever.create;
4010
- var voidType = ZodVoid.create;
4011
- var arrayType = ZodArray.create;
4012
- var objectType = ZodObject.create;
4013
- var strictObjectType = ZodObject.strictCreate;
4014
- var unionType = ZodUnion.create;
4015
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
4016
- var intersectionType = ZodIntersection.create;
4017
- var tupleType = ZodTuple.create;
4018
- var recordType = ZodRecord.create;
4019
- var mapType = ZodMap.create;
4020
- var setType = ZodSet.create;
4021
- var functionType = ZodFunction.create;
4022
- var lazyType = ZodLazy.create;
4023
- var literalType = ZodLiteral.create;
4024
- var enumType = ZodEnum.create;
4025
- var nativeEnumType = ZodNativeEnum.create;
4026
- var promiseType = ZodPromise.create;
4027
- var effectsType = ZodEffects.create;
4028
- var optionalType = ZodOptional.create;
4029
- var nullableType = ZodNullable.create;
4030
- var preprocessType = ZodEffects.createWithPreprocess;
4031
- var pipelineType = ZodPipeline.create;
4032
- var ostring = () => stringType().optional();
4033
- var onumber = () => numberType().optional();
4034
- var oboolean = () => booleanType().optional();
4035
- var coerce = {
4036
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4037
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4038
- boolean: ((arg) => ZodBoolean.create({
4039
- ...arg,
4040
- coerce: true
4041
- })),
4042
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4043
- date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
4044
- };
4045
- var NEVER = INVALID;
4046
-
4047
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/chunk-FPXAE3OS.mjs
4048
- var NonEmptyString = external_exports.string().min(1);
4049
- var Any = external_exports.record(external_exports.unknown());
4050
- var OptionalAny = external_exports.record(external_exports.unknown()).optional().nullable();
4051
- var NetworkSchemaV1 = NonEmptyString;
4052
- var NetworkSchemaV2 = external_exports.string().min(3).refine((val) => val.includes(":"), {
4053
- message: "Network must be in CAIP-2 format (e.g., 'eip155:84532')"
4054
- });
4055
- var NetworkSchema = external_exports.union([NetworkSchemaV1, NetworkSchemaV2]);
4056
- var PRINTABLE_ASCII_REGEX = /^[\x20-\x7e]+$/;
4057
- var ResourceInfoSchema = external_exports.object({
4058
- url: NonEmptyString,
4059
- description: external_exports.string().optional(),
4060
- mimeType: external_exports.string().optional(),
4061
- serviceName: external_exports.string().min(1).max(32).regex(PRINTABLE_ASCII_REGEX).optional(),
4062
- tags: external_exports.array(external_exports.string().min(1).max(32).regex(PRINTABLE_ASCII_REGEX)).max(5).optional(),
4063
- iconUrl: external_exports.string().max(2048).optional()
4064
- });
4065
- var PaymentRequirementsV1Schema = external_exports.object({
4066
- scheme: NonEmptyString,
4067
- network: NetworkSchemaV1,
4068
- maxAmountRequired: NonEmptyString,
4069
- resource: NonEmptyString,
4070
- // URL string in V1
4071
- description: external_exports.string(),
4072
- mimeType: external_exports.string().optional(),
4073
- outputSchema: Any.optional().nullable(),
4074
- payTo: NonEmptyString,
4075
- maxTimeoutSeconds: external_exports.number().positive(),
4076
- asset: NonEmptyString,
4077
- extra: OptionalAny
4078
- });
4079
- var PaymentRequiredV1Schema = external_exports.object({
4080
- x402Version: external_exports.literal(1),
4081
- error: external_exports.string().optional(),
4082
- accepts: external_exports.array(PaymentRequirementsV1Schema).min(1)
4083
- });
4084
- var PaymentPayloadV1Schema = external_exports.object({
4085
- x402Version: external_exports.literal(1),
4086
- scheme: NonEmptyString,
4087
- network: NetworkSchemaV1,
4088
- payload: Any
4089
- });
4090
- var PaymentRequirementsV2Schema = external_exports.object({
4091
- scheme: NonEmptyString,
4092
- network: NetworkSchemaV2,
4093
- amount: NonEmptyString,
4094
- asset: NonEmptyString,
4095
- payTo: NonEmptyString,
4096
- maxTimeoutSeconds: external_exports.number().positive(),
4097
- extra: OptionalAny
4098
- });
4099
- var PaymentRequiredV2Schema = external_exports.object({
4100
- x402Version: external_exports.literal(2),
4101
- error: external_exports.string().optional(),
4102
- resource: ResourceInfoSchema,
4103
- accepts: external_exports.array(PaymentRequirementsV2Schema).min(1),
4104
- extensions: OptionalAny
4105
- });
4106
- var PaymentPayloadV2Schema = external_exports.object({
4107
- x402Version: external_exports.literal(2),
4108
- resource: ResourceInfoSchema.optional(),
4109
- accepted: PaymentRequirementsV2Schema,
4110
- payload: Any,
4111
- extensions: OptionalAny
4112
- });
4113
- var PaymentRequirementsSchema = external_exports.union([
4114
- PaymentRequirementsV1Schema,
4115
- PaymentRequirementsV2Schema
4116
- ]);
4117
- var PaymentRequiredSchema = external_exports.discriminatedUnion("x402Version", [
4118
- PaymentRequiredV1Schema,
4119
- PaymentRequiredV2Schema
4120
- ]);
4121
- var PaymentPayloadSchema = external_exports.discriminatedUnion("x402Version", [
4122
- PaymentPayloadV1Schema,
4123
- PaymentPayloadV2Schema
4124
- ]);
4125
-
4126
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/chunk-VE37GDG2.mjs
4127
- var x402Version = 2;
4128
-
4129
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/chunk-AGOUMC4P.mjs
4130
- var VerifyError = class extends Error {
4131
- /**
4132
- * Creates a VerifyError from a failed verification response.
4133
- *
4134
- * @param statusCode - HTTP status code from the facilitator
4135
- * @param response - The verify response containing failure details
4136
- */
4137
- constructor(statusCode, response) {
4138
- const reason = response.invalidReason || "unknown reason";
4139
- const message = response.invalidMessage;
4140
- super(message ? `${reason}: ${message}` : reason);
4141
- this.name = "VerifyError";
4142
- this.statusCode = statusCode;
4143
- this.invalidReason = response.invalidReason;
4144
- this.invalidMessage = response.invalidMessage;
4145
- this.payer = response.payer;
4146
- }
4147
- };
4148
- var SettleError = class extends Error {
4149
- /**
4150
- * Creates a SettleError from a failed settlement response.
4151
- *
4152
- * @param statusCode - HTTP status code from the facilitator
4153
- * @param response - The settle response containing error details
4154
- */
4155
- constructor(statusCode, response) {
4156
- const reason = response.errorReason || "unknown reason";
4157
- const message = response.errorMessage;
4158
- super(message ? `${reason}: ${message}` : reason);
4159
- this.name = "SettleError";
4160
- this.statusCode = statusCode;
4161
- this.errorReason = response.errorReason;
4162
- this.errorMessage = response.errorMessage;
4163
- this.payer = response.payer;
4164
- this.transaction = response.transaction;
4165
- this.network = response.network;
4166
- }
4167
- };
4168
- var FacilitatorResponseError = class extends Error {
4169
- /**
4170
- * Creates a FacilitatorResponseError for malformed facilitator responses.
4171
- *
4172
- * @param message - The boundary error message
4173
- */
4174
- constructor(message) {
4175
- super(message);
4176
- this.name = "FacilitatorResponseError";
4177
- }
4178
- };
4179
-
4180
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/chunk-ABS7D6VX.mjs
4181
- var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4182
- var networkPatternToRegExp = (pattern) => {
4183
- const source = escapeRegExp(pattern).replace(/\\\*/g, ".*");
4184
- return new RegExp(`^${source}$`);
4185
- };
4186
- var networkMatchesPattern = (pattern, network) => {
4187
- return networkPatternToRegExp(pattern).test(network);
4188
- };
4189
- var findSchemesByNetwork = (map, network) => {
4190
- let implementationsByScheme = map.get(network);
4191
- if (!implementationsByScheme) {
4192
- for (const [registeredNetworkPattern, implementations] of map.entries()) {
4193
- if (networkMatchesPattern(registeredNetworkPattern, network)) {
4194
- implementationsByScheme = implementations;
4195
- break;
4196
- }
4197
- }
4198
- }
4199
- return implementationsByScheme;
4200
- };
4201
- var findByNetworkAndScheme = (map, scheme, network) => {
4202
- return findSchemesByNetwork(map, network)?.get(scheme);
4203
- };
4204
- var Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
4205
- function safeBase64Encode(data) {
4206
- if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
4207
- const bytes = new TextEncoder().encode(data);
4208
- const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
4209
- return globalThis.btoa(binaryString);
4210
- }
4211
- return Buffer.from(data, "utf8").toString("base64");
4212
- }
4213
- function safeBase64Decode(data) {
4214
- if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
4215
- const binaryString = globalThis.atob(data);
4216
- const bytes = new Uint8Array(binaryString.length);
4217
- for (let i = 0; i < binaryString.length; i++) {
4218
- bytes[i] = binaryString.charCodeAt(i);
4219
- }
4220
- const decoder = new TextDecoder("utf-8");
4221
- return decoder.decode(bytes);
4222
- }
4223
- return Buffer.from(data, "base64").toString("utf-8");
4224
- }
4225
-
4226
- // node_modules/.pnpm/@x402+core@2.17.0/node_modules/@x402/core/dist/esm/chunk-YEYZQZNL.mjs
4227
- var DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
4228
- var GET_SUPPORTED_RETRIES = 3;
4229
- var GET_SUPPORTED_RETRY_DELAY_MS = 1e3;
4230
- var MAX_RETRY_DELAY_MS = 3e4;
4231
- function computeRetryDelay(retryAfter, attempt) {
4232
- let delay = null;
4233
- if (retryAfter !== null) {
4234
- const trimmedRetryAfter = retryAfter.trim();
4235
- if (/^\d+$/.test(trimmedRetryAfter)) {
4236
- delay = Number(trimmedRetryAfter) * 1e3;
4237
- } else {
4238
- const retryDate = Date.parse(retryAfter);
4239
- if (!isNaN(retryDate)) {
4240
- delay = retryDate - Date.now();
4241
- }
4242
- }
4243
- }
4244
- if (delay === null || delay <= 0) {
4245
- delay = GET_SUPPORTED_RETRY_DELAY_MS * Math.pow(2, attempt);
4246
- }
4247
- return Math.min(delay, MAX_RETRY_DELAY_MS);
4248
- }
4249
- var verifyResponseSchema = external_exports.object({
4250
- isValid: external_exports.boolean(),
4251
- invalidReason: external_exports.string().nullish().transform((v) => v ?? void 0),
4252
- invalidMessage: external_exports.string().nullish().transform((v) => v ?? void 0),
4253
- payer: external_exports.string().nullish().transform((v) => v ?? void 0),
4254
- extensions: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0),
4255
- extra: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0)
4256
- });
4257
- var settleResponseSchema = external_exports.object({
4258
- success: external_exports.boolean(),
4259
- errorReason: external_exports.string().nullish().transform((v) => v ?? void 0),
4260
- errorMessage: external_exports.string().nullish().transform((v) => v ?? void 0),
4261
- payer: external_exports.string().nullish().transform((v) => v ?? void 0),
4262
- transaction: external_exports.string(),
4263
- network: external_exports.custom((value) => typeof value === "string"),
4264
- amount: external_exports.string().nullish().transform((v) => v ?? void 0),
4265
- extensions: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0),
4266
- extra: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0)
4267
- });
4268
- var supportedKindSchema = external_exports.object({
4269
- x402Version: external_exports.number(),
4270
- scheme: external_exports.string(),
4271
- network: external_exports.custom(
4272
- (value) => typeof value === "string"
4273
- ),
4274
- extra: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0)
4275
- });
4276
- var supportedResponseSchema = external_exports.object({
4277
- kinds: external_exports.array(supportedKindSchema),
4278
- extensions: external_exports.array(external_exports.string()).default([]),
4279
- signers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).default({})
4280
- });
4281
- function responseExcerpt(text, limit = 200) {
4282
- const compact = text.trim().replace(/\s+/g, " ");
4283
- if (!compact) {
4284
- return "<empty response>";
4285
- }
4286
- if (compact.length <= limit) {
4287
- return compact;
4288
- }
4289
- return `${compact.slice(0, limit - 3)}...`;
4290
- }
4291
- var EXTENSION_RESPONSE_LOG_FIELD_ALLOWLIST = ["status", "rejectedReason", "reason", "code"];
4292
- function logExtensionResponsesHeader(response) {
4293
- const header = response.headers.get("EXTENSION-RESPONSES");
4294
- if (!header) return;
4295
- try {
4296
- const decoded = JSON.parse(safeBase64Decode(header));
4297
- if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return;
4298
- const sanitized = {};
4299
- for (const [extensionKey, payload] of Object.entries(decoded)) {
4300
- const source = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
4301
- const filtered = {};
4302
- for (const key of EXTENSION_RESPONSE_LOG_FIELD_ALLOWLIST) {
4303
- if (source[key] !== void 0) {
4304
- filtered[key] = source[key];
4305
- }
4306
- }
4307
- sanitized[extensionKey] = filtered;
4308
- }
4309
- console.log(`[x402] extension responses: ${JSON.stringify(sanitized)}`);
4310
- } catch {
4311
- }
4312
- }
4313
- async function parseSuccessResponse(response, schema, operation) {
4314
- const text = await response.text();
4315
- let data;
4316
- try {
4317
- data = JSON.parse(text);
4318
- } catch {
4319
- throw new FacilitatorResponseError(
4320
- `Facilitator ${operation} returned invalid JSON: ${responseExcerpt(text)}`
4321
- );
4322
- }
4323
- const parsed = schema.safeParse(data);
4324
- if (!parsed.success) {
4325
- throw new FacilitatorResponseError(
4326
- `Facilitator ${operation} returned invalid data: ${responseExcerpt(text)}`
4327
- );
4328
- }
4329
- return parsed.data;
4330
- }
4331
- var HTTPFacilitatorClient = class {
4332
- /**
4333
- * Creates a new HTTPFacilitatorClient instance.
4334
- *
4335
- * @param config - Configuration options for the facilitator client
4336
- */
4337
- constructor(config) {
4338
- this.url = (config?.url || DEFAULT_FACILITATOR_URL).replace(/\/+$/, "");
4339
- this._createAuthHeaders = config?.createAuthHeaders;
4340
- }
4341
- /**
4342
- * Verify a payment with the facilitator
4343
- *
4344
- * @param paymentPayload - The payment to verify
4345
- * @param paymentRequirements - The requirements to verify against
4346
- * @returns Verification response
4347
- */
4348
- async verify(paymentPayload, paymentRequirements) {
4349
- let headers = {
4350
- "Content-Type": "application/json"
4351
- };
4352
- if (this._createAuthHeaders) {
4353
- const authHeaders = await this.createAuthHeaders("verify");
4354
- headers = { ...headers, ...authHeaders.headers };
4355
- }
4356
- const response = await fetch(`${this.url}/verify`, {
4357
- method: "POST",
4358
- headers,
4359
- redirect: "follow",
4360
- body: JSON.stringify({
4361
- x402Version: paymentPayload.x402Version,
4362
- paymentPayload: this.toJsonSafe(paymentPayload),
4363
- paymentRequirements: this.toJsonSafe(paymentRequirements)
4364
- })
4365
- });
4366
- if (!response.ok) {
4367
- const text = await response.text();
4368
- let data;
4369
- try {
4370
- data = JSON.parse(text);
4371
- } catch {
4372
- throw new Error(`Facilitator verify failed (${response.status}): ${responseExcerpt(text)}`);
4373
- }
4374
- if (typeof data === "object" && data !== null && "isValid" in data) {
4375
- throw new VerifyError(response.status, data);
4376
- }
4377
- throw new Error(
4378
- `Facilitator verify failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`
4379
- );
4380
- }
4381
- const verifyResult = await parseSuccessResponse(response, verifyResponseSchema, "verify");
4382
- logExtensionResponsesHeader(response);
4383
- return verifyResult;
4384
- }
4385
- /**
4386
- * Settle a payment with the facilitator
4387
- *
4388
- * @param paymentPayload - The payment to settle
4389
- * @param paymentRequirements - The requirements for settlement
4390
- * @returns Settlement response
4391
- */
4392
- async settle(paymentPayload, paymentRequirements) {
4393
- let headers = {
4394
- "Content-Type": "application/json"
4395
- };
4396
- if (this._createAuthHeaders) {
4397
- const authHeaders = await this.createAuthHeaders("settle");
4398
- headers = { ...headers, ...authHeaders.headers };
4399
- }
4400
- const response = await fetch(`${this.url}/settle`, {
4401
- method: "POST",
4402
- headers,
4403
- redirect: "follow",
4404
- body: JSON.stringify({
4405
- x402Version: paymentPayload.x402Version,
4406
- paymentPayload: this.toJsonSafe(paymentPayload),
4407
- paymentRequirements: this.toJsonSafe(paymentRequirements)
4408
- })
4409
- });
4410
- if (!response.ok) {
4411
- const text = await response.text();
4412
- let data;
4413
- try {
4414
- data = JSON.parse(text);
4415
- } catch {
4416
- throw new Error(`Facilitator settle failed (${response.status}): ${responseExcerpt(text)}`);
4417
- }
4418
- if (typeof data === "object" && data !== null && "success" in data) {
4419
- throw new SettleError(response.status, data);
4420
- }
4421
- throw new Error(
4422
- `Facilitator settle failed (${response.status}): ${responseExcerpt(JSON.stringify(data))}`
4423
- );
4424
- }
4425
- const settleResult = await parseSuccessResponse(response, settleResponseSchema, "settle");
4426
- logExtensionResponsesHeader(response);
4427
- return settleResult;
4428
- }
4429
- /**
4430
- * Get supported payment kinds and extensions from the facilitator.
4431
- * Retries with exponential backoff on 429 rate limit errors.
4432
- *
4433
- * @returns Supported payment kinds and extensions
4434
- */
4435
- async getSupported() {
4436
- let headers = {
4437
- "Content-Type": "application/json"
4438
- };
4439
- if (this._createAuthHeaders) {
4440
- const authHeaders = await this.createAuthHeaders("supported");
4441
- headers = { ...headers, ...authHeaders.headers };
4442
- }
4443
- let lastError = null;
4444
- for (let attempt = 0; attempt < GET_SUPPORTED_RETRIES; attempt++) {
4445
- const response = await fetch(`${this.url}/supported`, {
4446
- method: "GET",
4447
- headers,
4448
- redirect: "follow"
4449
- });
4450
- if (response.ok) {
4451
- return parseSuccessResponse(response, supportedResponseSchema, "supported");
4452
- }
4453
- const errorText = await response.text().catch(() => response.statusText);
4454
- lastError = new Error(
4455
- `Facilitator getSupported failed (${response.status}): ${responseExcerpt(errorText)}`
4456
- );
4457
- if (response.status === 429 && attempt < GET_SUPPORTED_RETRIES - 1) {
4458
- const delay = computeRetryDelay(response.headers.get("Retry-After"), attempt);
4459
- await new Promise((resolve) => setTimeout(resolve, delay));
4460
- continue;
4461
- }
4462
- throw lastError;
4463
- }
4464
- throw lastError ?? new Error("Facilitator getSupported failed after retries");
4465
- }
4466
- /**
4467
- * Creates authentication headers for a specific path.
4468
- *
4469
- * @param path - The path to create authentication headers for (e.g., "verify", "settle", "supported")
4470
- * @returns An object containing the authentication headers for the specified path
4471
- */
4472
- async createAuthHeaders(path) {
4473
- if (this._createAuthHeaders) {
4474
- const authHeaders = await this._createAuthHeaders();
4475
- return {
4476
- headers: authHeaders[path] ?? {}
4477
- };
4478
- }
4479
- return {
4480
- headers: {}
4481
- };
4482
- }
4483
- /**
4484
- * Helper to convert objects to JSON-safe format.
4485
- * Handles BigInt and other non-JSON types.
4486
- *
4487
- * @param obj - The object to convert
4488
- * @returns The JSON-safe representation of the object
4489
- */
4490
- toJsonSafe(obj) {
4491
- return JSON.parse(
4492
- JSON.stringify(obj, (_, value) => typeof value === "bigint" ? value.toString() : value)
4493
- );
4494
- }
4495
- };
4496
- var x402HTTPClient = class {
4497
- /**
4498
- * Creates a new x402HTTPClient instance.
4499
- *
4500
- * @param client - The underlying x402Client for payment logic
4501
- */
4502
- constructor(client) {
4503
- this.client = client;
4504
- this.paymentRequiredHooks = [];
4505
- }
4506
- /**
4507
- * Register a hook to handle 402 responses before payment.
4508
- * Hooks run in order; first to return headers wins.
4509
- *
4510
- * @param hook - The hook function to register
4511
- * @returns This instance for chaining
4512
- */
4513
- onPaymentRequired(hook) {
4514
- this.paymentRequiredHooks.push(hook);
4515
- return this;
4516
- }
4517
- /**
4518
- * Run hooks and return headers if any hook provides them.
4519
- *
4520
- * @param paymentRequired - The payment required response from the server
4521
- * @returns Headers to use for retry, or null to proceed to payment
4522
- */
4523
- async handlePaymentRequired(paymentRequired) {
4524
- for (const hook of this.getPaymentRequiredHooks(paymentRequired)) {
4525
- const result = await hook({ paymentRequired });
4526
- if (result?.headers) {
4527
- return result.headers;
4528
- }
4529
- }
4530
- return null;
4531
- }
4532
- /**
4533
- * Encodes a payment payload into appropriate HTTP headers based on version.
4534
- *
4535
- * @param paymentPayload - The payment payload to encode
4536
- * @returns HTTP headers containing the encoded payment signature
4537
- */
4538
- encodePaymentSignatureHeader(paymentPayload) {
4539
- switch (paymentPayload.x402Version) {
4540
- case 2:
4541
- return {
4542
- "PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
4543
- };
4544
- case 1:
4545
- return {
4546
- "X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
4547
- };
4548
- default:
4549
- throw new Error(
4550
- `Unsupported x402 version: ${paymentPayload.x402Version}`
4551
- );
4552
- }
4553
- }
4554
- /**
4555
- * Extracts payment required information from HTTP response.
4556
- *
4557
- * @param getHeader - Function to retrieve header value by name (case-insensitive)
4558
- * @param body - Optional response body for v1 compatibility
4559
- * @returns The payment required object
4560
- */
4561
- getPaymentRequiredResponse(getHeader, body) {
4562
- const paymentRequired = getHeader("PAYMENT-REQUIRED");
4563
- if (paymentRequired) {
4564
- return decodePaymentRequiredHeader(paymentRequired);
4565
- }
4566
- if (body && body instanceof Object && "x402Version" in body && body.x402Version === 1) {
4567
- return body;
4568
- }
4569
- throw new Error("Invalid payment required response");
4570
- }
4571
- /**
4572
- * Extracts payment settlement response from HTTP headers.
4573
- *
4574
- * @param getHeader - Function to retrieve header value by name (case-insensitive)
4575
- * @returns The settlement response object
4576
- */
4577
- getPaymentSettleResponse(getHeader) {
4578
- const paymentResponse = getHeader("PAYMENT-RESPONSE");
4579
- if (paymentResponse) {
4580
- return decodePaymentResponseHeader(paymentResponse);
4581
- }
4582
- const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
4583
- if (xPaymentResponse) {
4584
- return decodePaymentResponseHeader(xPaymentResponse);
4585
- }
4586
- throw new Error("Payment response header not found");
4587
- }
4588
- /**
4589
- * Creates a payment payload for the given payment requirements.
4590
- * Delegates to the underlying x402Client.
4591
- *
4592
- * @param paymentRequired - The payment required response from the server
4593
- * @returns Promise resolving to the payment payload
4594
- */
4595
- async createPaymentPayload(paymentRequired) {
4596
- return this.client.createPaymentPayload(paymentRequired);
4597
- }
4598
- /**
4599
- * Parses response headers into protocol types, fires payment response hooks (v2 only),
4600
- * and returns whether a hook signaled recovery.
4601
- *
4602
- * Called by transport wrappers (fetch, axios) after the paid request completes.
4603
- *
4604
- * @param paymentPayload - The payload that was sent with the request
4605
- * @param getHeader - Function to retrieve a response header by name
4606
- * @param status - The HTTP status code of the response
4607
- * @returns Whether a hook recovered and the parsed settle response (if any)
4608
- */
4609
- async processPaymentResult(paymentPayload, getHeader, status) {
4610
- let settleResponse;
4611
- try {
4612
- settleResponse = this.getPaymentSettleResponse(getHeader);
4613
- } catch {
4614
- }
4615
- if (paymentPayload.x402Version === 1) {
4616
- return { recovered: false, settleResponse };
4617
- }
4618
- let paymentRequired;
4619
- if (!settleResponse && status === 402) {
4620
- try {
4621
- paymentRequired = this.getPaymentRequiredResponse(getHeader);
4622
- } catch {
4623
- }
4624
- }
4625
- const requirements = paymentPayload.accepted;
4626
- if (!requirements) {
4627
- throw new Error("Invalid x402 v2 payment payload: missing `accepted`");
4628
- }
4629
- const ctx = {
4630
- paymentPayload,
4631
- requirements,
4632
- ...settleResponse ? { settleResponse } : {},
4633
- ...paymentRequired ? { paymentRequired } : {}
4634
- };
4635
- const result = await this.client.handlePaymentResponse(ctx);
4636
- return { recovered: result?.recovered === true, settleResponse };
4637
- }
4638
- /**
4639
- * Parses HTTP status, headers, and body into an `HTTPResourceResponse`.
4640
- *
4641
- * Decodes the x402 payment header into `header`: the `PAYMENT-RESPONSE`
4642
- * settlement if present, otherwise the `PAYMENT-REQUIRED` declaration on
4643
- * 402 responses (whose `error` field carries the server's failure reason).
4644
- *
4645
- * @param args - Normalized response inputs from any HTTP transport
4646
- * @param args.status - HTTP response status code
4647
- * @param args.getHeader - Callback to read response headers by name
4648
- * @param args.body - Response body payload
4649
- * @returns The parsed status, body, and decoded payment header
4650
- */
4651
- parsePaymentResult(args) {
4652
- const { status, getHeader, body } = args;
4653
- let header;
4654
- try {
4655
- header = this.getPaymentSettleResponse(getHeader);
4656
- } catch {
4657
- if (status === 402) {
4658
- try {
4659
- header = this.getPaymentRequiredResponse(getHeader, body);
4660
- } catch {
4661
- }
4662
- }
4663
- }
4664
- let paymentStatus = "none";
4665
- if (header && !("success" in header)) {
4666
- paymentStatus = "payment_required";
4667
- }
4668
- if (header && "success" in header) {
4669
- paymentStatus = header.success ? "settled" : "settle_failed";
4670
- }
4671
- return { status, paymentStatus, body, header };
4672
- }
4673
- /**
4674
- * Parses a fetch Response into an `HTTPResourceResponse` for app-level convenience.
4675
- *
4676
- * @param response - The fetch Response to process
4677
- * @returns The parsed status, body, and decoded payment header
4678
- */
4679
- async processResponse(response) {
4680
- const getHeader = (name) => response.headers.get(name);
4681
- const contentType = response.headers.get("content-type") ?? "";
4682
- const body = contentType.includes("application/json") ? await response.json() : await response.text();
4683
- return this.parsePaymentResult({ status: response.status, getHeader, body });
4684
- }
4685
- /**
4686
- * Manual HTTP hooks run before extension hooks scoped to the 402 response.
4687
- *
4688
- * @param paymentRequired - The payment required response from the server
4689
- * @returns Hooks in invocation order
4690
- */
4691
- getPaymentRequiredHooks(paymentRequired) {
4692
- const hooks = [...this.paymentRequiredHooks];
4693
- const declaredExtensions = paymentRequired.extensions;
4694
- if (!declaredExtensions) return hooks;
4695
- for (const extension of this.client.getExtensions()) {
4696
- const httpExtension = extension;
4697
- const hook = httpExtension.transportHooks?.http?.onPaymentRequired;
4698
- if (!hook || !(extension.key in declaredExtensions)) continue;
4699
- hooks.push((context) => hook(declaredExtensions[extension.key], context));
4700
- }
4701
- return hooks;
4702
- }
4703
- };
4704
- function encodePaymentSignatureHeader(paymentPayload) {
4705
- return safeBase64Encode(JSON.stringify(paymentPayload));
4706
- }
4707
- function decodePaymentRequiredHeader(paymentRequiredHeader) {
4708
- if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
4709
- throw new Error("Invalid payment required header");
4710
- }
4711
- return JSON.parse(safeBase64Decode(paymentRequiredHeader));
4712
- }
4713
- function decodePaymentResponseHeader(paymentResponseHeader) {
4714
- if (!Base64EncodedRegex.test(paymentResponseHeader)) {
4715
- throw new Error("Invalid payment response header");
4716
- }
4717
- return JSON.parse(safeBase64Decode(paymentResponseHeader));
4718
- }
4719
-
4720
- export {
4721
- external_exports,
4722
- findSchemesByNetwork,
4723
- findByNetworkAndScheme,
4724
- safeBase64Encode,
4725
- x402Version,
4726
- HTTPFacilitatorClient,
4727
- x402HTTPClient,
4728
- decodePaymentRequiredHeader,
4729
- decodePaymentResponseHeader
4730
- };
4731
- //# sourceMappingURL=chunk-DBU5CXBV.js.map