@baseplate-dev/plugin-auth 3.0.1 → 3.0.3

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