@contentful/experiences-sdk-react 0.0.1-alpha.8 → 0.0.1-beta.0

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