core.cjs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.globalConfig = exports.$ZodEncodeError = exports.$ZodAsyncError = exports.$brand = exports.NEVER = void 0;
  4. exports.$constructor = $constructor;
  5. exports.config = config;
  6. /** A special constant with type `never` */
  7. exports.NEVER = Object.freeze({
  8. status: "aborted",
  9. });
  10. function $constructor(name, initializer, params) {
  11. function init(inst, def) {
  12. if (!inst._zod) {
  13. Object.defineProperty(inst, "_zod", {
  14. value: {
  15. def,
  16. constr: _,
  17. traits: new Set(),
  18. },
  19. enumerable: false,
  20. });
  21. }
  22. if (inst._zod.traits.has(name)) {
  23. return;
  24. }
  25. inst._zod.traits.add(name);
  26. initializer(inst, def);
  27. // support prototype modifications
  28. const proto = _.prototype;
  29. const keys = Object.keys(proto);
  30. for (let i = 0; i < keys.length; i++) {
  31. const k = keys[i];
  32. if (!(k in inst)) {
  33. inst[k] = proto[k].bind(inst);
  34. }
  35. }
  36. }
  37. // doesn't work if Parent has a constructor with arguments
  38. const Parent = params?.Parent ?? Object;
  39. class Definition extends Parent {
  40. }
  41. Object.defineProperty(Definition, "name", { value: name });
  42. function _(def) {
  43. var _a;
  44. const inst = params?.Parent ? new Definition() : this;
  45. init(inst, def);
  46. (_a = inst._zod).deferred ?? (_a.deferred = []);
  47. for (const fn of inst._zod.deferred) {
  48. fn();
  49. }
  50. return inst;
  51. }
  52. Object.defineProperty(_, "init", { value: init });
  53. Object.defineProperty(_, Symbol.hasInstance, {
  54. value: (inst) => {
  55. if (params?.Parent && inst instanceof params.Parent)
  56. return true;
  57. return inst?._zod?.traits?.has(name);
  58. },
  59. });
  60. Object.defineProperty(_, "name", { value: name });
  61. return _;
  62. }
  63. ////////////////////////////// UTILITIES ///////////////////////////////////////
  64. exports.$brand = Symbol("zod_brand");
  65. class $ZodAsyncError extends Error {
  66. constructor() {
  67. super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  68. }
  69. }
  70. exports.$ZodAsyncError = $ZodAsyncError;
  71. class $ZodEncodeError extends Error {
  72. constructor(name) {
  73. super(`Encountered unidirectional transform during encode: ${name}`);
  74. this.name = "ZodEncodeError";
  75. }
  76. }
  77. exports.$ZodEncodeError = $ZodEncodeError;
  78. exports.globalConfig = {};
  79. function config(newConfig) {
  80. if (newConfig)
  81. Object.assign(exports.globalConfig, newConfig);
  82. return exports.globalConfig;
  83. }