core.js 2.4 KB

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