@stackone/core 1.52.5 → 1.52.7

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,4794 +1,26 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
- key = keys[i];
11
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
- get: ((k) => from[k]).bind(null, key),
13
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
- });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
- value: mod,
20
- enumerable: true
21
- }) : target, mod));
22
-
23
- //#endregion
24
- const __stackone_utils = __toESM(require("@stackone/utils"));
25
- const __stackone_expressions = __toESM(require("@stackone/expressions"));
26
- const __stackone_transport = __toESM(require("@stackone/transport"));
27
-
28
- //#region src/categories/index.ts
29
- const CATEGORIES = {
30
- hris: {
31
- title: "HRIS",
32
- key: "hris",
33
- description: "Human Resource Information System"
34
- },
35
- crm: {
36
- title: "CRM",
37
- key: "crm",
38
- description: "Customer Relationship Management"
39
- },
40
- ats: {
41
- title: "ATS",
42
- key: "ats",
43
- description: "Applicant Tracking System"
44
- },
45
- lms: {
46
- title: "LMS",
47
- key: "lms",
48
- description: "Learning Management System"
49
- },
50
- marketing: {
51
- title: "Marketing",
52
- key: "marketing",
53
- description: "Marketing"
54
- },
55
- filestorage: {
56
- title: "File Storage",
57
- key: "filestorage",
58
- description: "File Storage"
59
- }
60
- };
61
- const getCategoryDetails = (category) => {
62
- const details = CATEGORIES[category.toLowerCase()];
63
- return details ?? null;
64
- };
65
- const isValidCategory = (category) => {
66
- return !!CATEGORIES[category.toLowerCase()];
67
- };
68
-
69
- //#endregion
70
- //#region src/compositeIds/constants.ts
71
- const COMPOSITE_ID_HEADER_V1 = "so1!";
72
- const ENCODED_COMPOSITE_ID_HEADER_V1 = (0, __stackone_utils.encodeToBase64)(COMPOSITE_ID_HEADER_V1);
73
- const COMPOSITE_ID_FIELD_SEPARATOR = ":";
74
- const COMPOSITE_ID_COMPOSED_SEPARATOR = ",";
75
- const COMPOSITE_ID_FIELD_SEPARATOR_REGEX = new RegExp(`(?<!\\\\)${COMPOSITE_ID_FIELD_SEPARATOR}`, "g");
76
- const COMPOSITE_ID_COMPOSED_SEPARATOR_REGEX = new RegExp(`(?<!\\\\)${COMPOSITE_ID_COMPOSED_SEPARATOR}`, "g");
77
- const COMPOSITE_ID_LATEST_VERSION = 1;
78
-
79
- //#endregion
80
- //#region src/errors/coreError.ts
81
- /**
82
- * Represents a core error within the system.
83
- *
84
- * @remarks
85
- * This class is intended as a base error type for errors and should not be used directly.
86
- * Instead, extend this class to create more specific error types.
87
- *
88
- * @param category - The category of the error.
89
- * @param name - The name of the error.
90
- * @param type - The specific type of the error.
91
- * @param context - Optional. The block context in which the error occurred.
92
- * @param message - Optional. The error message.
93
- *
94
- * @public
95
- */
96
- var CoreError = class CoreError extends Error {
97
- type;
98
- category;
99
- context;
100
- constructor({ category, name, type, context, message }) {
101
- super(message);
102
- this.name = name ?? "CoreError";
103
- this.type = type;
104
- this.category = category;
105
- this.context = context;
106
- if (Error.captureStackTrace) Error.captureStackTrace(this, CoreError);
107
- }
108
- toString() {
109
- const message = this.message ? `: ${this.message}` : "";
110
- return `${this.category}-${this.name} [${this.type}]${message}`;
111
- }
112
- };
113
-
114
- //#endregion
115
- //#region src/compositeIds/errors.ts
116
- var BaseCompositeIdError = class extends CoreError {
117
- constructor(type, name, message) {
118
- super({
119
- category: "CompositeId",
120
- name: name ?? "BaseCompositeIdError",
121
- type,
122
- message
123
- });
124
- }
125
- };
126
- var CompositeIdMissingHeaderError = class extends BaseCompositeIdError {
127
- constructor(message) {
128
- super("COMPOSITE_ID_MISSING_HEADER_ERROR", "CompositeIdMissingHeaderError", message ?? "Invalid compositeId, missing header");
129
- }
130
- };
131
- var CompositeIdMissingBodyError = class extends BaseCompositeIdError {
132
- constructor(message) {
133
- super("COMPOSITE_ID_MISSING_BODY_ERROR", "CompositeIdMissingBodyError", message ?? "Invalid compositeId, missing body");
134
- }
135
- };
136
- var CompositeIdUnknownIdentifierError = class extends BaseCompositeIdError {
137
- constructor(message) {
138
- super("COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR", "CompositeIdUnknownIdentifierError", message ?? "Invalid compositeId, unknown identifier");
139
- }
140
- };
141
- var CompositeIdUnsupportedVersionError = class extends BaseCompositeIdError {
142
- constructor(message) {
143
- super("COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR", "CompositeIdUnsupportedVersionError", message ?? "Invalid compositeId, unsupported version");
144
- }
145
- };
146
-
147
- //#endregion
148
- //#region src/compositeIds/typeguards.ts
149
- const isSingleIdentifier = (identifier) => {
150
- return !(0, __stackone_utils.isMissing)(identifier) && "value" in identifier && identifier.value !== void 0;
151
- };
152
- const isMultipleIdentifier = (identifier) => {
153
- return !(0, __stackone_utils.isMissing)(identifier) && "identifiers" in identifier && identifier.identifiers !== void 0;
154
- };
155
-
156
- //#endregion
157
- //#region src/compositeIds/index.ts
158
- /**
159
- * Encodes a composite ID from an identifier object.
160
- * If aliases are provided, they will be used to map the components to their given aliases.
161
- * Intended to be used to shorten the size of the generated ID.
162
- *
163
- * @param {CompositeIdentifier} identifier - The composite identifier object to generate the ID from.
164
- * @param {CompositeIdentifierConfig} [compositeIdConfig={ version: COMPOSITE_ID_LATEST_VERSION }] - Configuration for the composite ID, including version and optional aliases.
165
- * @returns {string} The generated composite ID as a string.
166
- * @throws {CompositeIdUnsupportedVersionError} If the version is not supported.
167
- */
168
- const encodeCompositeId = (identifier, compositeIdConfig = { version: COMPOSITE_ID_LATEST_VERSION }) => {
169
- if (compositeIdConfig.version === 1) return encodeIdV1(getComposedIdV1(identifier, compositeIdConfig.aliases));
170
- else throw new CompositeIdUnsupportedVersionError(`Cannot generate ID, unsupported version number: ${compositeIdConfig.version}`);
171
- };
172
- /**
173
- * Decodes a composite ID to its original components.
174
- * Returns a record with the components of the composite ID.
175
- * If compositeIdAliases is provided, it will use them to map the components to their original keys.
176
- *
177
- * @param {string} compositeId - The composite ID string to extract components from.
178
- * @param {CompositeIdentifierConfig} [compositeIdConfig={ version: COMPOSITE_ID_LATEST_VERSION }] - Configuration for the composite ID, including version and optional aliases.
179
- * @returns {Record<string, string>} A record containing the extracted components.
180
- */
181
- const decodeCompositeId = (compositeId, compositeIdConfig = { version: COMPOSITE_ID_LATEST_VERSION }) => {
182
- const rawId = decodeId(compositeId, compositeIdConfig);
183
- const values = {};
184
- if (!rawId) return values;
185
- rawId.split(COMPOSITE_ID_COMPOSED_SEPARATOR_REGEX).forEach((element) => {
186
- const [field, value] = element.split(COMPOSITE_ID_FIELD_SEPARATOR_REGEX);
187
- const originalKey = getOriginalKey(field, compositeIdConfig.aliases ?? {});
188
- values[originalKey] = unescapeValue(value);
189
- });
190
- return values;
191
- };
192
- const getComposedIdV1 = (identifier, compositeIdAliases = {}) => {
193
- if (isSingleIdentifier(identifier)) return getSingleIdentifierString({
194
- identifier,
195
- compositeIdAliases,
196
- isSoleIdentifier: true
197
- });
198
- else if (isMultipleIdentifier(identifier)) return identifier.identifiers.map((id) => {
199
- return getSingleIdentifierString({
200
- identifier: id,
201
- compositeIdAliases,
202
- isSoleIdentifier: false
203
- });
204
- }).join(COMPOSITE_ID_COMPOSED_SEPARATOR);
205
- else throw new CompositeIdUnknownIdentifierError();
206
- };
207
- const getSingleIdentifierString = ({ identifier, compositeIdAliases, isSoleIdentifier }) => {
208
- const aliasedKey = isSoleIdentifier ? "id" : compositeIdAliases[identifier.key] || identifier.key;
209
- return [aliasedKey, escapeValue(identifier.value)].filter(Boolean).join(COMPOSITE_ID_FIELD_SEPARATOR);
210
- };
211
- const getOriginalKey = (alias, compositeIdAliases) => {
212
- return Object.keys(compositeIdAliases).find((key) => compositeIdAliases[key] === alias) ?? alias;
213
- };
214
- const decodeId = (compositeId, compositeIdConfig) => {
215
- if (compositeIdConfig.version === 1) return decodeIdV1(compositeId);
216
- else throw new CompositeIdUnsupportedVersionError(`Cannot decode ID, unsupported version number: ${compositeIdConfig.version}`);
217
- };
218
- const encodeIdV1 = (id) => {
219
- return `${ENCODED_COMPOSITE_ID_HEADER_V1}${(0, __stackone_utils.encodeToBase64)(id)}`;
220
- };
221
- const decodeIdV1 = (compositeId) => {
222
- if (!compositeId.startsWith(ENCODED_COMPOSITE_ID_HEADER_V1)) throw new CompositeIdMissingHeaderError(`Trying to decode an ID without the header: ${compositeId}`);
223
- const body = compositeId.split(ENCODED_COMPOSITE_ID_HEADER_V1)[1];
224
- if (!body) throw new CompositeIdMissingBodyError(`Trying to decode an ID without a body: ${compositeId}`);
225
- return (0, __stackone_utils.decodeFromBase64)(body);
226
- };
227
- const escapeValue = (value) => {
228
- return [COMPOSITE_ID_COMPOSED_SEPARATOR, COMPOSITE_ID_FIELD_SEPARATOR].reduce((result, separator) => {
229
- return result.replace(separator, "\\" + separator);
230
- }, value);
231
- };
232
- const unescapeValue = (value) => {
233
- return [COMPOSITE_ID_COMPOSED_SEPARATOR, COMPOSITE_ID_FIELD_SEPARATOR].reduce((result, separator) => {
234
- const escapedSeparator = "\\" + separator;
235
- return result.replace(new RegExp("\\\\" + escapedSeparator, "g"), separator);
236
- }, value);
237
- };
238
- const isCompositeId = (value) => {
239
- if ((0, __stackone_utils.isMissing)(value)) return false;
240
- return value.startsWith(ENCODED_COMPOSITE_ID_HEADER_V1);
241
- };
242
-
243
- //#endregion
244
- //#region ../../node_modules/zod/v3/helpers/util.js
245
- var util;
246
- (function(util$1) {
247
- util$1.assertEqual = (_) => {};
248
- function assertIs(_arg) {}
249
- util$1.assertIs = assertIs;
250
- function assertNever(_x) {
251
- throw new Error();
252
- }
253
- util$1.assertNever = assertNever;
254
- util$1.arrayToEnum = (items) => {
255
- const obj = {};
256
- for (const item of items) obj[item] = item;
257
- return obj;
258
- };
259
- util$1.getValidEnumValues = (obj) => {
260
- const validKeys = util$1.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
261
- const filtered = {};
262
- for (const k of validKeys) filtered[k] = obj[k];
263
- return util$1.objectValues(filtered);
264
- };
265
- util$1.objectValues = (obj) => {
266
- return util$1.objectKeys(obj).map(function(e) {
267
- return obj[e];
268
- });
269
- };
270
- util$1.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
271
- const keys = [];
272
- for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
273
- return keys;
274
- };
275
- util$1.find = (arr, checker) => {
276
- for (const item of arr) if (checker(item)) return item;
277
- return void 0;
278
- };
279
- util$1.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
280
- function joinValues(array, separator = " | ") {
281
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
282
- }
283
- util$1.joinValues = joinValues;
284
- util$1.jsonStringifyReplacer = (_, value) => {
285
- if (typeof value === "bigint") return value.toString();
286
- return value;
287
- };
288
- })(util || (util = {}));
289
- var objectUtil;
290
- (function(objectUtil$1) {
291
- objectUtil$1.mergeShapes = (first, second) => {
292
- return {
293
- ...first,
294
- ...second
295
- };
296
- };
297
- })(objectUtil || (objectUtil = {}));
298
- const ZodParsedType = util.arrayToEnum([
299
- "string",
300
- "nan",
301
- "number",
302
- "integer",
303
- "float",
304
- "boolean",
305
- "date",
306
- "bigint",
307
- "symbol",
308
- "function",
309
- "undefined",
310
- "null",
311
- "array",
312
- "object",
313
- "unknown",
314
- "promise",
315
- "void",
316
- "never",
317
- "map",
318
- "set"
319
- ]);
320
- const getParsedType = (data) => {
321
- const t = typeof data;
322
- switch (t) {
323
- case "undefined": return ZodParsedType.undefined;
324
- case "string": return ZodParsedType.string;
325
- case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
326
- case "boolean": return ZodParsedType.boolean;
327
- case "function": return ZodParsedType.function;
328
- case "bigint": return ZodParsedType.bigint;
329
- case "symbol": return ZodParsedType.symbol;
330
- case "object":
331
- if (Array.isArray(data)) return ZodParsedType.array;
332
- if (data === null) return ZodParsedType.null;
333
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise;
334
- if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map;
335
- if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set;
336
- if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date;
337
- return ZodParsedType.object;
338
- default: return ZodParsedType.unknown;
339
- }
340
- };
341
-
342
- //#endregion
343
- //#region ../../node_modules/zod/v3/ZodError.js
344
- const ZodIssueCode = util.arrayToEnum([
345
- "invalid_type",
346
- "invalid_literal",
347
- "custom",
348
- "invalid_union",
349
- "invalid_union_discriminator",
350
- "invalid_enum_value",
351
- "unrecognized_keys",
352
- "invalid_arguments",
353
- "invalid_return_type",
354
- "invalid_date",
355
- "invalid_string",
356
- "too_small",
357
- "too_big",
358
- "invalid_intersection_types",
359
- "not_multiple_of",
360
- "not_finite"
361
- ]);
362
- var ZodError = class ZodError extends Error {
363
- get errors() {
364
- return this.issues;
365
- }
366
- constructor(issues) {
367
- super();
368
- this.issues = [];
369
- this.addIssue = (sub) => {
370
- this.issues = [...this.issues, sub];
371
- };
372
- this.addIssues = (subs = []) => {
373
- this.issues = [...this.issues, ...subs];
374
- };
375
- const actualProto = new.target.prototype;
376
- if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
377
- else this.__proto__ = actualProto;
378
- this.name = "ZodError";
379
- this.issues = issues;
380
- }
381
- format(_mapper) {
382
- const mapper = _mapper || function(issue) {
383
- return issue.message;
384
- };
385
- const fieldErrors = { _errors: [] };
386
- const processError = (error) => {
387
- for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError);
388
- else if (issue.code === "invalid_return_type") processError(issue.returnTypeError);
389
- else if (issue.code === "invalid_arguments") processError(issue.argumentsError);
390
- else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
391
- else {
392
- let curr = fieldErrors;
393
- let i = 0;
394
- while (i < issue.path.length) {
395
- const el = issue.path[i];
396
- const terminal = i === issue.path.length - 1;
397
- if (!terminal) curr[el] = curr[el] || { _errors: [] };
398
- else {
399
- curr[el] = curr[el] || { _errors: [] };
400
- curr[el]._errors.push(mapper(issue));
401
- }
402
- curr = curr[el];
403
- i++;
404
- }
405
- }
406
- };
407
- processError(this);
408
- return fieldErrors;
409
- }
410
- static assert(value) {
411
- if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
412
- }
413
- toString() {
414
- return this.message;
415
- }
416
- get message() {
417
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
418
- }
419
- get isEmpty() {
420
- return this.issues.length === 0;
421
- }
422
- flatten(mapper = (issue) => issue.message) {
423
- const fieldErrors = {};
424
- const formErrors = [];
425
- for (const sub of this.issues) if (sub.path.length > 0) {
426
- const firstEl = sub.path[0];
427
- fieldErrors[firstEl] = fieldErrors[firstEl] || [];
428
- fieldErrors[firstEl].push(mapper(sub));
429
- } else formErrors.push(mapper(sub));
430
- return {
431
- formErrors,
432
- fieldErrors
433
- };
434
- }
435
- get formErrors() {
436
- return this.flatten();
437
- }
438
- };
439
- ZodError.create = (issues) => {
440
- const error = new ZodError(issues);
441
- return error;
442
- };
443
-
444
- //#endregion
445
- //#region ../../node_modules/zod/v3/locales/en.js
446
- const errorMap = (issue, _ctx) => {
447
- let message;
448
- switch (issue.code) {
449
- case ZodIssueCode.invalid_type:
450
- if (issue.received === ZodParsedType.undefined) message = "Required";
451
- else message = `Expected ${issue.expected}, received ${issue.received}`;
452
- break;
453
- case ZodIssueCode.invalid_literal:
454
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
455
- break;
456
- case ZodIssueCode.unrecognized_keys:
457
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
458
- break;
459
- case ZodIssueCode.invalid_union:
460
- message = `Invalid input`;
461
- break;
462
- case ZodIssueCode.invalid_union_discriminator:
463
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
464
- break;
465
- case ZodIssueCode.invalid_enum_value:
466
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
467
- break;
468
- case ZodIssueCode.invalid_arguments:
469
- message = `Invalid function arguments`;
470
- break;
471
- case ZodIssueCode.invalid_return_type:
472
- message = `Invalid function return type`;
473
- break;
474
- case ZodIssueCode.invalid_date:
475
- message = `Invalid date`;
476
- break;
477
- case ZodIssueCode.invalid_string:
478
- if (typeof issue.validation === "object") if ("includes" in issue.validation) {
479
- message = `Invalid input: must include "${issue.validation.includes}"`;
480
- if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
481
- } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
482
- else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
483
- else util.assertNever(issue.validation);
484
- else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
485
- else message = "Invalid";
486
- break;
487
- case ZodIssueCode.too_small:
488
- if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
489
- else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
490
- else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
491
- else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
492
- else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
493
- else message = "Invalid input";
494
- break;
495
- case ZodIssueCode.too_big:
496
- if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
497
- else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
498
- else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
499
- else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
500
- else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
501
- else message = "Invalid input";
502
- break;
503
- case ZodIssueCode.custom:
504
- message = `Invalid input`;
505
- break;
506
- case ZodIssueCode.invalid_intersection_types:
507
- message = `Intersection results could not be merged`;
508
- break;
509
- case ZodIssueCode.not_multiple_of:
510
- message = `Number must be a multiple of ${issue.multipleOf}`;
511
- break;
512
- case ZodIssueCode.not_finite:
513
- message = "Number must be finite";
514
- break;
515
- default:
516
- message = _ctx.defaultError;
517
- util.assertNever(issue);
518
- }
519
- return { message };
520
- };
521
- var en_default = errorMap;
522
-
523
- //#endregion
524
- //#region ../../node_modules/zod/v3/errors.js
525
- let overrideErrorMap = en_default;
526
- function getErrorMap() {
527
- return overrideErrorMap;
528
- }
529
-
530
- //#endregion
531
- //#region ../../node_modules/zod/v3/helpers/parseUtil.js
532
- const makeIssue = (params) => {
533
- const { data, path, errorMaps, issueData } = params;
534
- const fullPath = [...path, ...issueData.path || []];
535
- const fullIssue = {
536
- ...issueData,
537
- path: fullPath
538
- };
539
- if (issueData.message !== void 0) return {
540
- ...issueData,
541
- path: fullPath,
542
- message: issueData.message
543
- };
544
- let errorMessage = "";
545
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
546
- for (const map of maps) errorMessage = map(fullIssue, {
547
- data,
548
- defaultError: errorMessage
549
- }).message;
550
- return {
551
- ...issueData,
552
- path: fullPath,
553
- message: errorMessage
554
- };
555
- };
556
- function addIssueToContext(ctx, issueData) {
557
- const overrideMap = getErrorMap();
558
- const issue = makeIssue({
559
- issueData,
560
- data: ctx.data,
561
- path: ctx.path,
562
- errorMaps: [
563
- ctx.common.contextualErrorMap,
564
- ctx.schemaErrorMap,
565
- overrideMap,
566
- overrideMap === en_default ? void 0 : en_default
567
- ].filter((x) => !!x)
568
- });
569
- ctx.common.issues.push(issue);
570
- }
571
- var ParseStatus = class ParseStatus {
572
- constructor() {
573
- this.value = "valid";
574
- }
575
- dirty() {
576
- if (this.value === "valid") this.value = "dirty";
577
- }
578
- abort() {
579
- if (this.value !== "aborted") this.value = "aborted";
580
- }
581
- static mergeArray(status, results) {
582
- const arrayValue = [];
583
- for (const s of results) {
584
- if (s.status === "aborted") return INVALID;
585
- if (s.status === "dirty") status.dirty();
586
- arrayValue.push(s.value);
587
- }
588
- return {
589
- status: status.value,
590
- value: arrayValue
591
- };
592
- }
593
- static async mergeObjectAsync(status, pairs) {
594
- const syncPairs = [];
595
- for (const pair of pairs) {
596
- const key = await pair.key;
597
- const value = await pair.value;
598
- syncPairs.push({
599
- key,
600
- value
601
- });
602
- }
603
- return ParseStatus.mergeObjectSync(status, syncPairs);
604
- }
605
- static mergeObjectSync(status, pairs) {
606
- const finalObject = {};
607
- for (const pair of pairs) {
608
- const { key, value } = pair;
609
- if (key.status === "aborted") return INVALID;
610
- if (value.status === "aborted") return INVALID;
611
- if (key.status === "dirty") status.dirty();
612
- if (value.status === "dirty") status.dirty();
613
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
614
- }
615
- return {
616
- status: status.value,
617
- value: finalObject
618
- };
619
- }
620
- };
621
- const INVALID = Object.freeze({ status: "aborted" });
622
- const DIRTY = (value) => ({
623
- status: "dirty",
624
- value
625
- });
626
- const OK = (value) => ({
627
- status: "valid",
628
- value
629
- });
630
- const isAborted = (x) => x.status === "aborted";
631
- const isDirty = (x) => x.status === "dirty";
632
- const isValid = (x) => x.status === "valid";
633
- const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
634
-
635
- //#endregion
636
- //#region ../../node_modules/zod/v3/helpers/errorUtil.js
637
- var errorUtil;
638
- (function(errorUtil$1) {
639
- errorUtil$1.errToObj = (message) => typeof message === "string" ? { message } : message || {};
640
- errorUtil$1.toString = (message) => typeof message === "string" ? message : message?.message;
641
- })(errorUtil || (errorUtil = {}));
642
-
643
- //#endregion
644
- //#region ../../node_modules/zod/v3/types.js
645
- var ParseInputLazyPath = class {
646
- constructor(parent, value, path, key) {
647
- this._cachedPath = [];
648
- this.parent = parent;
649
- this.data = value;
650
- this._path = path;
651
- this._key = key;
652
- }
653
- get path() {
654
- if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
655
- else this._cachedPath.push(...this._path, this._key);
656
- return this._cachedPath;
657
- }
658
- };
659
- const handleResult = (ctx, result) => {
660
- if (isValid(result)) return {
661
- success: true,
662
- data: result.value
663
- };
664
- else {
665
- if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
666
- return {
667
- success: false,
668
- get error() {
669
- if (this._error) return this._error;
670
- const error = new ZodError(ctx.common.issues);
671
- this._error = error;
672
- return this._error;
673
- }
674
- };
675
- }
676
- };
677
- function processCreateParams(params) {
678
- if (!params) return {};
679
- const { errorMap: errorMap$1, invalid_type_error, required_error, description } = params;
680
- if (errorMap$1 && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
681
- if (errorMap$1) return {
682
- errorMap: errorMap$1,
683
- description
684
- };
685
- const customMap = (iss, ctx) => {
686
- const { message } = params;
687
- if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
688
- if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
689
- if (iss.code !== "invalid_type") return { message: ctx.defaultError };
690
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
691
- };
692
- return {
693
- errorMap: customMap,
694
- description
695
- };
696
- }
697
- var ZodType = class {
698
- get description() {
699
- return this._def.description;
700
- }
701
- _getType(input) {
702
- return getParsedType(input.data);
703
- }
704
- _getOrReturnCtx(input, ctx) {
705
- return ctx || {
706
- common: input.parent.common,
707
- data: input.data,
708
- parsedType: getParsedType(input.data),
709
- schemaErrorMap: this._def.errorMap,
710
- path: input.path,
711
- parent: input.parent
712
- };
713
- }
714
- _processInputParams(input) {
715
- return {
716
- status: new ParseStatus(),
717
- ctx: {
718
- common: input.parent.common,
719
- data: input.data,
720
- parsedType: getParsedType(input.data),
721
- schemaErrorMap: this._def.errorMap,
722
- path: input.path,
723
- parent: input.parent
724
- }
725
- };
726
- }
727
- _parseSync(input) {
728
- const result = this._parse(input);
729
- if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
730
- return result;
731
- }
732
- _parseAsync(input) {
733
- const result = this._parse(input);
734
- return Promise.resolve(result);
735
- }
736
- parse(data, params) {
737
- const result = this.safeParse(data, params);
738
- if (result.success) return result.data;
739
- throw result.error;
740
- }
741
- safeParse(data, params) {
742
- const ctx = {
743
- common: {
744
- issues: [],
745
- async: params?.async ?? false,
746
- contextualErrorMap: params?.errorMap
747
- },
748
- path: params?.path || [],
749
- schemaErrorMap: this._def.errorMap,
750
- parent: null,
751
- data,
752
- parsedType: getParsedType(data)
753
- };
754
- const result = this._parseSync({
755
- data,
756
- path: ctx.path,
757
- parent: ctx
758
- });
759
- return handleResult(ctx, result);
760
- }
761
- "~validate"(data) {
762
- const ctx = {
763
- common: {
764
- issues: [],
765
- async: !!this["~standard"].async
766
- },
767
- path: [],
768
- schemaErrorMap: this._def.errorMap,
769
- parent: null,
770
- data,
771
- parsedType: getParsedType(data)
772
- };
773
- if (!this["~standard"].async) try {
774
- const result = this._parseSync({
775
- data,
776
- path: [],
777
- parent: ctx
778
- });
779
- return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
780
- } catch (err) {
781
- if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
782
- ctx.common = {
783
- issues: [],
784
- async: true
785
- };
786
- }
787
- return this._parseAsync({
788
- data,
789
- path: [],
790
- parent: ctx
791
- }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
792
- }
793
- async parseAsync(data, params) {
794
- const result = await this.safeParseAsync(data, params);
795
- if (result.success) return result.data;
796
- throw result.error;
797
- }
798
- async safeParseAsync(data, params) {
799
- const ctx = {
800
- common: {
801
- issues: [],
802
- contextualErrorMap: params?.errorMap,
803
- async: true
804
- },
805
- path: params?.path || [],
806
- schemaErrorMap: this._def.errorMap,
807
- parent: null,
808
- data,
809
- parsedType: getParsedType(data)
810
- };
811
- const maybeAsyncResult = this._parse({
812
- data,
813
- path: ctx.path,
814
- parent: ctx
815
- });
816
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
817
- return handleResult(ctx, result);
818
- }
819
- refine(check, message) {
820
- const getIssueProperties = (val) => {
821
- if (typeof message === "string" || typeof message === "undefined") return { message };
822
- else if (typeof message === "function") return message(val);
823
- else return message;
824
- };
825
- return this._refinement((val, ctx) => {
826
- const result = check(val);
827
- const setError = () => ctx.addIssue({
828
- code: ZodIssueCode.custom,
829
- ...getIssueProperties(val)
830
- });
831
- if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
832
- if (!data) {
833
- setError();
834
- return false;
835
- } else return true;
836
- });
837
- if (!result) {
838
- setError();
839
- return false;
840
- } else return true;
841
- });
842
- }
843
- refinement(check, refinementData) {
844
- return this._refinement((val, ctx) => {
845
- if (!check(val)) {
846
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
847
- return false;
848
- } else return true;
849
- });
850
- }
851
- _refinement(refinement) {
852
- return new ZodEffects({
853
- schema: this,
854
- typeName: ZodFirstPartyTypeKind.ZodEffects,
855
- effect: {
856
- type: "refinement",
857
- refinement
858
- }
859
- });
860
- }
861
- superRefine(refinement) {
862
- return this._refinement(refinement);
863
- }
864
- constructor(def) {
865
- /** Alias of safeParseAsync */
866
- this.spa = this.safeParseAsync;
867
- this._def = def;
868
- this.parse = this.parse.bind(this);
869
- this.safeParse = this.safeParse.bind(this);
870
- this.parseAsync = this.parseAsync.bind(this);
871
- this.safeParseAsync = this.safeParseAsync.bind(this);
872
- this.spa = this.spa.bind(this);
873
- this.refine = this.refine.bind(this);
874
- this.refinement = this.refinement.bind(this);
875
- this.superRefine = this.superRefine.bind(this);
876
- this.optional = this.optional.bind(this);
877
- this.nullable = this.nullable.bind(this);
878
- this.nullish = this.nullish.bind(this);
879
- this.array = this.array.bind(this);
880
- this.promise = this.promise.bind(this);
881
- this.or = this.or.bind(this);
882
- this.and = this.and.bind(this);
883
- this.transform = this.transform.bind(this);
884
- this.brand = this.brand.bind(this);
885
- this.default = this.default.bind(this);
886
- this.catch = this.catch.bind(this);
887
- this.describe = this.describe.bind(this);
888
- this.pipe = this.pipe.bind(this);
889
- this.readonly = this.readonly.bind(this);
890
- this.isNullable = this.isNullable.bind(this);
891
- this.isOptional = this.isOptional.bind(this);
892
- this["~standard"] = {
893
- version: 1,
894
- vendor: "zod",
895
- validate: (data) => this["~validate"](data)
896
- };
897
- }
898
- optional() {
899
- return ZodOptional.create(this, this._def);
900
- }
901
- nullable() {
902
- return ZodNullable.create(this, this._def);
903
- }
904
- nullish() {
905
- return this.nullable().optional();
906
- }
907
- array() {
908
- return ZodArray.create(this);
909
- }
910
- promise() {
911
- return ZodPromise.create(this, this._def);
912
- }
913
- or(option) {
914
- return ZodUnion.create([this, option], this._def);
915
- }
916
- and(incoming) {
917
- return ZodIntersection.create(this, incoming, this._def);
918
- }
919
- transform(transform) {
920
- return new ZodEffects({
921
- ...processCreateParams(this._def),
922
- schema: this,
923
- typeName: ZodFirstPartyTypeKind.ZodEffects,
924
- effect: {
925
- type: "transform",
926
- transform
927
- }
928
- });
929
- }
930
- default(def) {
931
- const defaultValueFunc = typeof def === "function" ? def : () => def;
932
- return new ZodDefault({
933
- ...processCreateParams(this._def),
934
- innerType: this,
935
- defaultValue: defaultValueFunc,
936
- typeName: ZodFirstPartyTypeKind.ZodDefault
937
- });
938
- }
939
- brand() {
940
- return new ZodBranded({
941
- typeName: ZodFirstPartyTypeKind.ZodBranded,
942
- type: this,
943
- ...processCreateParams(this._def)
944
- });
945
- }
946
- catch(def) {
947
- const catchValueFunc = typeof def === "function" ? def : () => def;
948
- return new ZodCatch({
949
- ...processCreateParams(this._def),
950
- innerType: this,
951
- catchValue: catchValueFunc,
952
- typeName: ZodFirstPartyTypeKind.ZodCatch
953
- });
954
- }
955
- describe(description) {
956
- const This = this.constructor;
957
- return new This({
958
- ...this._def,
959
- description
960
- });
961
- }
962
- pipe(target) {
963
- return ZodPipeline.create(this, target);
964
- }
965
- readonly() {
966
- return ZodReadonly.create(this);
967
- }
968
- isOptional() {
969
- return this.safeParse(void 0).success;
970
- }
971
- isNullable() {
972
- return this.safeParse(null).success;
973
- }
974
- };
975
- const cuidRegex = /^c[^\s-]{8,}$/i;
976
- const cuid2Regex = /^[0-9a-z]+$/;
977
- const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
978
- 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;
979
- const nanoidRegex = /^[a-z0-9_-]{21}$/i;
980
- const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
981
- const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
982
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
983
- const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
984
- let emojiRegex;
985
- const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
986
- const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
987
- const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
988
- const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
989
- const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
990
- const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
991
- const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
992
- const dateRegex = /* @__PURE__ */ new RegExp(`^${dateRegexSource}$`);
993
- function timeRegexSource(args) {
994
- let secondsRegexSource = `[0-5]\\d`;
995
- if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
996
- else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
997
- const secondsQuantifier = args.precision ? "+" : "?";
998
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
999
- }
1000
- function timeRegex(args) {
1001
- return /* @__PURE__ */ new RegExp(`^${timeRegexSource(args)}$`);
1002
- }
1003
- function datetimeRegex(args) {
1004
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1005
- const opts = [];
1006
- opts.push(args.local ? `Z?` : `Z`);
1007
- if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
1008
- regex = `${regex}(${opts.join("|")})`;
1009
- return /* @__PURE__ */ new RegExp(`^${regex}$`);
1010
- }
1011
- function isValidIP(ip, version) {
1012
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true;
1013
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true;
1014
- return false;
1015
- }
1016
- function isValidJWT(jwt, alg) {
1017
- if (!jwtRegex.test(jwt)) return false;
1018
- try {
1019
- const [header] = jwt.split(".");
1020
- if (!header) return false;
1021
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1022
- const decoded = JSON.parse(atob(base64));
1023
- if (typeof decoded !== "object" || decoded === null) return false;
1024
- if ("typ" in decoded && decoded?.typ !== "JWT") return false;
1025
- if (!decoded.alg) return false;
1026
- if (alg && decoded.alg !== alg) return false;
1027
- return true;
1028
- } catch {
1029
- return false;
1030
- }
1031
- }
1032
- function isValidCidr(ip, version) {
1033
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true;
1034
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true;
1035
- return false;
1036
- }
1037
- var ZodString = class ZodString extends ZodType {
1038
- _parse(input) {
1039
- if (this._def.coerce) input.data = String(input.data);
1040
- const parsedType = this._getType(input);
1041
- if (parsedType !== ZodParsedType.string) {
1042
- const ctx$1 = this._getOrReturnCtx(input);
1043
- addIssueToContext(ctx$1, {
1044
- code: ZodIssueCode.invalid_type,
1045
- expected: ZodParsedType.string,
1046
- received: ctx$1.parsedType
1047
- });
1048
- return INVALID;
1049
- }
1050
- const status = new ParseStatus();
1051
- let ctx = void 0;
1052
- for (const check of this._def.checks) if (check.kind === "min") {
1053
- if (input.data.length < check.value) {
1054
- ctx = this._getOrReturnCtx(input, ctx);
1055
- addIssueToContext(ctx, {
1056
- code: ZodIssueCode.too_small,
1057
- minimum: check.value,
1058
- type: "string",
1059
- inclusive: true,
1060
- exact: false,
1061
- message: check.message
1062
- });
1063
- status.dirty();
1064
- }
1065
- } else if (check.kind === "max") {
1066
- if (input.data.length > check.value) {
1067
- ctx = this._getOrReturnCtx(input, ctx);
1068
- addIssueToContext(ctx, {
1069
- code: ZodIssueCode.too_big,
1070
- maximum: check.value,
1071
- type: "string",
1072
- inclusive: true,
1073
- exact: false,
1074
- message: check.message
1075
- });
1076
- status.dirty();
1077
- }
1078
- } else if (check.kind === "length") {
1079
- const tooBig = input.data.length > check.value;
1080
- const tooSmall = input.data.length < check.value;
1081
- if (tooBig || tooSmall) {
1082
- ctx = this._getOrReturnCtx(input, ctx);
1083
- if (tooBig) addIssueToContext(ctx, {
1084
- code: ZodIssueCode.too_big,
1085
- maximum: check.value,
1086
- type: "string",
1087
- inclusive: true,
1088
- exact: true,
1089
- message: check.message
1090
- });
1091
- else if (tooSmall) addIssueToContext(ctx, {
1092
- code: ZodIssueCode.too_small,
1093
- minimum: check.value,
1094
- type: "string",
1095
- inclusive: true,
1096
- exact: true,
1097
- message: check.message
1098
- });
1099
- status.dirty();
1100
- }
1101
- } else if (check.kind === "email") {
1102
- if (!emailRegex.test(input.data)) {
1103
- ctx = this._getOrReturnCtx(input, ctx);
1104
- addIssueToContext(ctx, {
1105
- validation: "email",
1106
- code: ZodIssueCode.invalid_string,
1107
- message: check.message
1108
- });
1109
- status.dirty();
1110
- }
1111
- } else if (check.kind === "emoji") {
1112
- if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u");
1113
- if (!emojiRegex.test(input.data)) {
1114
- ctx = this._getOrReturnCtx(input, ctx);
1115
- addIssueToContext(ctx, {
1116
- validation: "emoji",
1117
- code: ZodIssueCode.invalid_string,
1118
- message: check.message
1119
- });
1120
- status.dirty();
1121
- }
1122
- } else if (check.kind === "uuid") {
1123
- if (!uuidRegex.test(input.data)) {
1124
- ctx = this._getOrReturnCtx(input, ctx);
1125
- addIssueToContext(ctx, {
1126
- validation: "uuid",
1127
- code: ZodIssueCode.invalid_string,
1128
- message: check.message
1129
- });
1130
- status.dirty();
1131
- }
1132
- } else if (check.kind === "nanoid") {
1133
- if (!nanoidRegex.test(input.data)) {
1134
- ctx = this._getOrReturnCtx(input, ctx);
1135
- addIssueToContext(ctx, {
1136
- validation: "nanoid",
1137
- code: ZodIssueCode.invalid_string,
1138
- message: check.message
1139
- });
1140
- status.dirty();
1141
- }
1142
- } else if (check.kind === "cuid") {
1143
- if (!cuidRegex.test(input.data)) {
1144
- ctx = this._getOrReturnCtx(input, ctx);
1145
- addIssueToContext(ctx, {
1146
- validation: "cuid",
1147
- code: ZodIssueCode.invalid_string,
1148
- message: check.message
1149
- });
1150
- status.dirty();
1151
- }
1152
- } else if (check.kind === "cuid2") {
1153
- if (!cuid2Regex.test(input.data)) {
1154
- ctx = this._getOrReturnCtx(input, ctx);
1155
- addIssueToContext(ctx, {
1156
- validation: "cuid2",
1157
- code: ZodIssueCode.invalid_string,
1158
- message: check.message
1159
- });
1160
- status.dirty();
1161
- }
1162
- } else if (check.kind === "ulid") {
1163
- if (!ulidRegex.test(input.data)) {
1164
- ctx = this._getOrReturnCtx(input, ctx);
1165
- addIssueToContext(ctx, {
1166
- validation: "ulid",
1167
- code: ZodIssueCode.invalid_string,
1168
- message: check.message
1169
- });
1170
- status.dirty();
1171
- }
1172
- } else if (check.kind === "url") try {
1173
- new URL(input.data);
1174
- } catch {
1175
- ctx = this._getOrReturnCtx(input, ctx);
1176
- addIssueToContext(ctx, {
1177
- validation: "url",
1178
- code: ZodIssueCode.invalid_string,
1179
- message: check.message
1180
- });
1181
- status.dirty();
1182
- }
1183
- else if (check.kind === "regex") {
1184
- check.regex.lastIndex = 0;
1185
- const testResult = check.regex.test(input.data);
1186
- if (!testResult) {
1187
- ctx = this._getOrReturnCtx(input, ctx);
1188
- addIssueToContext(ctx, {
1189
- validation: "regex",
1190
- code: ZodIssueCode.invalid_string,
1191
- message: check.message
1192
- });
1193
- status.dirty();
1194
- }
1195
- } else if (check.kind === "trim") input.data = input.data.trim();
1196
- else if (check.kind === "includes") {
1197
- if (!input.data.includes(check.value, check.position)) {
1198
- ctx = this._getOrReturnCtx(input, ctx);
1199
- addIssueToContext(ctx, {
1200
- code: ZodIssueCode.invalid_string,
1201
- validation: {
1202
- includes: check.value,
1203
- position: check.position
1204
- },
1205
- message: check.message
1206
- });
1207
- status.dirty();
1208
- }
1209
- } else if (check.kind === "toLowerCase") input.data = input.data.toLowerCase();
1210
- else if (check.kind === "toUpperCase") input.data = input.data.toUpperCase();
1211
- else if (check.kind === "startsWith") {
1212
- if (!input.data.startsWith(check.value)) {
1213
- ctx = this._getOrReturnCtx(input, ctx);
1214
- addIssueToContext(ctx, {
1215
- code: ZodIssueCode.invalid_string,
1216
- validation: { startsWith: check.value },
1217
- message: check.message
1218
- });
1219
- status.dirty();
1220
- }
1221
- } else if (check.kind === "endsWith") {
1222
- if (!input.data.endsWith(check.value)) {
1223
- ctx = this._getOrReturnCtx(input, ctx);
1224
- addIssueToContext(ctx, {
1225
- code: ZodIssueCode.invalid_string,
1226
- validation: { endsWith: check.value },
1227
- message: check.message
1228
- });
1229
- status.dirty();
1230
- }
1231
- } else if (check.kind === "datetime") {
1232
- const regex = datetimeRegex(check);
1233
- if (!regex.test(input.data)) {
1234
- ctx = this._getOrReturnCtx(input, ctx);
1235
- addIssueToContext(ctx, {
1236
- code: ZodIssueCode.invalid_string,
1237
- validation: "datetime",
1238
- message: check.message
1239
- });
1240
- status.dirty();
1241
- }
1242
- } else if (check.kind === "date") {
1243
- const regex = dateRegex;
1244
- if (!regex.test(input.data)) {
1245
- ctx = this._getOrReturnCtx(input, ctx);
1246
- addIssueToContext(ctx, {
1247
- code: ZodIssueCode.invalid_string,
1248
- validation: "date",
1249
- message: check.message
1250
- });
1251
- status.dirty();
1252
- }
1253
- } else if (check.kind === "time") {
1254
- const regex = timeRegex(check);
1255
- if (!regex.test(input.data)) {
1256
- ctx = this._getOrReturnCtx(input, ctx);
1257
- addIssueToContext(ctx, {
1258
- code: ZodIssueCode.invalid_string,
1259
- validation: "time",
1260
- message: check.message
1261
- });
1262
- status.dirty();
1263
- }
1264
- } else if (check.kind === "duration") {
1265
- if (!durationRegex.test(input.data)) {
1266
- ctx = this._getOrReturnCtx(input, ctx);
1267
- addIssueToContext(ctx, {
1268
- validation: "duration",
1269
- code: ZodIssueCode.invalid_string,
1270
- message: check.message
1271
- });
1272
- status.dirty();
1273
- }
1274
- } else if (check.kind === "ip") {
1275
- if (!isValidIP(input.data, check.version)) {
1276
- ctx = this._getOrReturnCtx(input, ctx);
1277
- addIssueToContext(ctx, {
1278
- validation: "ip",
1279
- code: ZodIssueCode.invalid_string,
1280
- message: check.message
1281
- });
1282
- status.dirty();
1283
- }
1284
- } else if (check.kind === "jwt") {
1285
- if (!isValidJWT(input.data, check.alg)) {
1286
- ctx = this._getOrReturnCtx(input, ctx);
1287
- addIssueToContext(ctx, {
1288
- validation: "jwt",
1289
- code: ZodIssueCode.invalid_string,
1290
- message: check.message
1291
- });
1292
- status.dirty();
1293
- }
1294
- } else if (check.kind === "cidr") {
1295
- if (!isValidCidr(input.data, check.version)) {
1296
- ctx = this._getOrReturnCtx(input, ctx);
1297
- addIssueToContext(ctx, {
1298
- validation: "cidr",
1299
- code: ZodIssueCode.invalid_string,
1300
- message: check.message
1301
- });
1302
- status.dirty();
1303
- }
1304
- } else if (check.kind === "base64") {
1305
- if (!base64Regex.test(input.data)) {
1306
- ctx = this._getOrReturnCtx(input, ctx);
1307
- addIssueToContext(ctx, {
1308
- validation: "base64",
1309
- code: ZodIssueCode.invalid_string,
1310
- message: check.message
1311
- });
1312
- status.dirty();
1313
- }
1314
- } else if (check.kind === "base64url") {
1315
- if (!base64urlRegex.test(input.data)) {
1316
- ctx = this._getOrReturnCtx(input, ctx);
1317
- addIssueToContext(ctx, {
1318
- validation: "base64url",
1319
- code: ZodIssueCode.invalid_string,
1320
- message: check.message
1321
- });
1322
- status.dirty();
1323
- }
1324
- } else util.assertNever(check);
1325
- return {
1326
- status: status.value,
1327
- value: input.data
1328
- };
1329
- }
1330
- _regex(regex, validation, message) {
1331
- return this.refinement((data) => regex.test(data), {
1332
- validation,
1333
- code: ZodIssueCode.invalid_string,
1334
- ...errorUtil.errToObj(message)
1335
- });
1336
- }
1337
- _addCheck(check) {
1338
- return new ZodString({
1339
- ...this._def,
1340
- checks: [...this._def.checks, check]
1341
- });
1342
- }
1343
- email(message) {
1344
- return this._addCheck({
1345
- kind: "email",
1346
- ...errorUtil.errToObj(message)
1347
- });
1348
- }
1349
- url(message) {
1350
- return this._addCheck({
1351
- kind: "url",
1352
- ...errorUtil.errToObj(message)
1353
- });
1354
- }
1355
- emoji(message) {
1356
- return this._addCheck({
1357
- kind: "emoji",
1358
- ...errorUtil.errToObj(message)
1359
- });
1360
- }
1361
- uuid(message) {
1362
- return this._addCheck({
1363
- kind: "uuid",
1364
- ...errorUtil.errToObj(message)
1365
- });
1366
- }
1367
- nanoid(message) {
1368
- return this._addCheck({
1369
- kind: "nanoid",
1370
- ...errorUtil.errToObj(message)
1371
- });
1372
- }
1373
- cuid(message) {
1374
- return this._addCheck({
1375
- kind: "cuid",
1376
- ...errorUtil.errToObj(message)
1377
- });
1378
- }
1379
- cuid2(message) {
1380
- return this._addCheck({
1381
- kind: "cuid2",
1382
- ...errorUtil.errToObj(message)
1383
- });
1384
- }
1385
- ulid(message) {
1386
- return this._addCheck({
1387
- kind: "ulid",
1388
- ...errorUtil.errToObj(message)
1389
- });
1390
- }
1391
- base64(message) {
1392
- return this._addCheck({
1393
- kind: "base64",
1394
- ...errorUtil.errToObj(message)
1395
- });
1396
- }
1397
- base64url(message) {
1398
- return this._addCheck({
1399
- kind: "base64url",
1400
- ...errorUtil.errToObj(message)
1401
- });
1402
- }
1403
- jwt(options) {
1404
- return this._addCheck({
1405
- kind: "jwt",
1406
- ...errorUtil.errToObj(options)
1407
- });
1408
- }
1409
- ip(options) {
1410
- return this._addCheck({
1411
- kind: "ip",
1412
- ...errorUtil.errToObj(options)
1413
- });
1414
- }
1415
- cidr(options) {
1416
- return this._addCheck({
1417
- kind: "cidr",
1418
- ...errorUtil.errToObj(options)
1419
- });
1420
- }
1421
- datetime(options) {
1422
- if (typeof options === "string") return this._addCheck({
1423
- kind: "datetime",
1424
- precision: null,
1425
- offset: false,
1426
- local: false,
1427
- message: options
1428
- });
1429
- return this._addCheck({
1430
- kind: "datetime",
1431
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1432
- offset: options?.offset ?? false,
1433
- local: options?.local ?? false,
1434
- ...errorUtil.errToObj(options?.message)
1435
- });
1436
- }
1437
- date(message) {
1438
- return this._addCheck({
1439
- kind: "date",
1440
- message
1441
- });
1442
- }
1443
- time(options) {
1444
- if (typeof options === "string") return this._addCheck({
1445
- kind: "time",
1446
- precision: null,
1447
- message: options
1448
- });
1449
- return this._addCheck({
1450
- kind: "time",
1451
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
1452
- ...errorUtil.errToObj(options?.message)
1453
- });
1454
- }
1455
- duration(message) {
1456
- return this._addCheck({
1457
- kind: "duration",
1458
- ...errorUtil.errToObj(message)
1459
- });
1460
- }
1461
- regex(regex, message) {
1462
- return this._addCheck({
1463
- kind: "regex",
1464
- regex,
1465
- ...errorUtil.errToObj(message)
1466
- });
1467
- }
1468
- includes(value, options) {
1469
- return this._addCheck({
1470
- kind: "includes",
1471
- value,
1472
- position: options?.position,
1473
- ...errorUtil.errToObj(options?.message)
1474
- });
1475
- }
1476
- startsWith(value, message) {
1477
- return this._addCheck({
1478
- kind: "startsWith",
1479
- value,
1480
- ...errorUtil.errToObj(message)
1481
- });
1482
- }
1483
- endsWith(value, message) {
1484
- return this._addCheck({
1485
- kind: "endsWith",
1486
- value,
1487
- ...errorUtil.errToObj(message)
1488
- });
1489
- }
1490
- min(minLength, message) {
1491
- return this._addCheck({
1492
- kind: "min",
1493
- value: minLength,
1494
- ...errorUtil.errToObj(message)
1495
- });
1496
- }
1497
- max(maxLength, message) {
1498
- return this._addCheck({
1499
- kind: "max",
1500
- value: maxLength,
1501
- ...errorUtil.errToObj(message)
1502
- });
1503
- }
1504
- length(len, message) {
1505
- return this._addCheck({
1506
- kind: "length",
1507
- value: len,
1508
- ...errorUtil.errToObj(message)
1509
- });
1510
- }
1511
- /**
1512
- * Equivalent to `.min(1)`
1513
- */
1514
- nonempty(message) {
1515
- return this.min(1, errorUtil.errToObj(message));
1516
- }
1517
- trim() {
1518
- return new ZodString({
1519
- ...this._def,
1520
- checks: [...this._def.checks, { kind: "trim" }]
1521
- });
1522
- }
1523
- toLowerCase() {
1524
- return new ZodString({
1525
- ...this._def,
1526
- checks: [...this._def.checks, { kind: "toLowerCase" }]
1527
- });
1528
- }
1529
- toUpperCase() {
1530
- return new ZodString({
1531
- ...this._def,
1532
- checks: [...this._def.checks, { kind: "toUpperCase" }]
1533
- });
1534
- }
1535
- get isDatetime() {
1536
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
1537
- }
1538
- get isDate() {
1539
- return !!this._def.checks.find((ch) => ch.kind === "date");
1540
- }
1541
- get isTime() {
1542
- return !!this._def.checks.find((ch) => ch.kind === "time");
1543
- }
1544
- get isDuration() {
1545
- return !!this._def.checks.find((ch) => ch.kind === "duration");
1546
- }
1547
- get isEmail() {
1548
- return !!this._def.checks.find((ch) => ch.kind === "email");
1549
- }
1550
- get isURL() {
1551
- return !!this._def.checks.find((ch) => ch.kind === "url");
1552
- }
1553
- get isEmoji() {
1554
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1555
- }
1556
- get isUUID() {
1557
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1558
- }
1559
- get isNANOID() {
1560
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1561
- }
1562
- get isCUID() {
1563
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1564
- }
1565
- get isCUID2() {
1566
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1567
- }
1568
- get isULID() {
1569
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1570
- }
1571
- get isIP() {
1572
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1573
- }
1574
- get isCIDR() {
1575
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1576
- }
1577
- get isBase64() {
1578
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1579
- }
1580
- get isBase64url() {
1581
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1582
- }
1583
- get minLength() {
1584
- let min = null;
1585
- for (const ch of this._def.checks) if (ch.kind === "min") {
1586
- if (min === null || ch.value > min) min = ch.value;
1587
- }
1588
- return min;
1589
- }
1590
- get maxLength() {
1591
- let max = null;
1592
- for (const ch of this._def.checks) if (ch.kind === "max") {
1593
- if (max === null || ch.value < max) max = ch.value;
1594
- }
1595
- return max;
1596
- }
1597
- };
1598
- ZodString.create = (params) => {
1599
- return new ZodString({
1600
- checks: [],
1601
- typeName: ZodFirstPartyTypeKind.ZodString,
1602
- coerce: params?.coerce ?? false,
1603
- ...processCreateParams(params)
1604
- });
1605
- };
1606
- function floatSafeRemainder(val, step) {
1607
- const valDecCount = (val.toString().split(".")[1] || "").length;
1608
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1609
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1610
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1611
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1612
- return valInt % stepInt / 10 ** decCount;
1613
- }
1614
- var ZodNumber = class ZodNumber extends ZodType {
1615
- constructor() {
1616
- super(...arguments);
1617
- this.min = this.gte;
1618
- this.max = this.lte;
1619
- this.step = this.multipleOf;
1620
- }
1621
- _parse(input) {
1622
- if (this._def.coerce) input.data = Number(input.data);
1623
- const parsedType = this._getType(input);
1624
- if (parsedType !== ZodParsedType.number) {
1625
- const ctx$1 = this._getOrReturnCtx(input);
1626
- addIssueToContext(ctx$1, {
1627
- code: ZodIssueCode.invalid_type,
1628
- expected: ZodParsedType.number,
1629
- received: ctx$1.parsedType
1630
- });
1631
- return INVALID;
1632
- }
1633
- let ctx = void 0;
1634
- const status = new ParseStatus();
1635
- for (const check of this._def.checks) if (check.kind === "int") {
1636
- if (!util.isInteger(input.data)) {
1637
- ctx = this._getOrReturnCtx(input, ctx);
1638
- addIssueToContext(ctx, {
1639
- code: ZodIssueCode.invalid_type,
1640
- expected: "integer",
1641
- received: "float",
1642
- message: check.message
1643
- });
1644
- status.dirty();
1645
- }
1646
- } else if (check.kind === "min") {
1647
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1648
- if (tooSmall) {
1649
- ctx = this._getOrReturnCtx(input, ctx);
1650
- addIssueToContext(ctx, {
1651
- code: ZodIssueCode.too_small,
1652
- minimum: check.value,
1653
- type: "number",
1654
- inclusive: check.inclusive,
1655
- exact: false,
1656
- message: check.message
1657
- });
1658
- status.dirty();
1659
- }
1660
- } else if (check.kind === "max") {
1661
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1662
- if (tooBig) {
1663
- ctx = this._getOrReturnCtx(input, ctx);
1664
- addIssueToContext(ctx, {
1665
- code: ZodIssueCode.too_big,
1666
- maximum: check.value,
1667
- type: "number",
1668
- inclusive: check.inclusive,
1669
- exact: false,
1670
- message: check.message
1671
- });
1672
- status.dirty();
1673
- }
1674
- } else if (check.kind === "multipleOf") {
1675
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1676
- ctx = this._getOrReturnCtx(input, ctx);
1677
- addIssueToContext(ctx, {
1678
- code: ZodIssueCode.not_multiple_of,
1679
- multipleOf: check.value,
1680
- message: check.message
1681
- });
1682
- status.dirty();
1683
- }
1684
- } else if (check.kind === "finite") {
1685
- if (!Number.isFinite(input.data)) {
1686
- ctx = this._getOrReturnCtx(input, ctx);
1687
- addIssueToContext(ctx, {
1688
- code: ZodIssueCode.not_finite,
1689
- message: check.message
1690
- });
1691
- status.dirty();
1692
- }
1693
- } else util.assertNever(check);
1694
- return {
1695
- status: status.value,
1696
- value: input.data
1697
- };
1698
- }
1699
- gte(value, message) {
1700
- return this.setLimit("min", value, true, errorUtil.toString(message));
1701
- }
1702
- gt(value, message) {
1703
- return this.setLimit("min", value, false, errorUtil.toString(message));
1704
- }
1705
- lte(value, message) {
1706
- return this.setLimit("max", value, true, errorUtil.toString(message));
1707
- }
1708
- lt(value, message) {
1709
- return this.setLimit("max", value, false, errorUtil.toString(message));
1710
- }
1711
- setLimit(kind, value, inclusive, message) {
1712
- return new ZodNumber({
1713
- ...this._def,
1714
- checks: [...this._def.checks, {
1715
- kind,
1716
- value,
1717
- inclusive,
1718
- message: errorUtil.toString(message)
1719
- }]
1720
- });
1721
- }
1722
- _addCheck(check) {
1723
- return new ZodNumber({
1724
- ...this._def,
1725
- checks: [...this._def.checks, check]
1726
- });
1727
- }
1728
- int(message) {
1729
- return this._addCheck({
1730
- kind: "int",
1731
- message: errorUtil.toString(message)
1732
- });
1733
- }
1734
- positive(message) {
1735
- return this._addCheck({
1736
- kind: "min",
1737
- value: 0,
1738
- inclusive: false,
1739
- message: errorUtil.toString(message)
1740
- });
1741
- }
1742
- negative(message) {
1743
- return this._addCheck({
1744
- kind: "max",
1745
- value: 0,
1746
- inclusive: false,
1747
- message: errorUtil.toString(message)
1748
- });
1749
- }
1750
- nonpositive(message) {
1751
- return this._addCheck({
1752
- kind: "max",
1753
- value: 0,
1754
- inclusive: true,
1755
- message: errorUtil.toString(message)
1756
- });
1757
- }
1758
- nonnegative(message) {
1759
- return this._addCheck({
1760
- kind: "min",
1761
- value: 0,
1762
- inclusive: true,
1763
- message: errorUtil.toString(message)
1764
- });
1765
- }
1766
- multipleOf(value, message) {
1767
- return this._addCheck({
1768
- kind: "multipleOf",
1769
- value,
1770
- message: errorUtil.toString(message)
1771
- });
1772
- }
1773
- finite(message) {
1774
- return this._addCheck({
1775
- kind: "finite",
1776
- message: errorUtil.toString(message)
1777
- });
1778
- }
1779
- safe(message) {
1780
- return this._addCheck({
1781
- kind: "min",
1782
- inclusive: true,
1783
- value: Number.MIN_SAFE_INTEGER,
1784
- message: errorUtil.toString(message)
1785
- })._addCheck({
1786
- kind: "max",
1787
- inclusive: true,
1788
- value: Number.MAX_SAFE_INTEGER,
1789
- message: errorUtil.toString(message)
1790
- });
1791
- }
1792
- get minValue() {
1793
- let min = null;
1794
- for (const ch of this._def.checks) if (ch.kind === "min") {
1795
- if (min === null || ch.value > min) min = ch.value;
1796
- }
1797
- return min;
1798
- }
1799
- get maxValue() {
1800
- let max = null;
1801
- for (const ch of this._def.checks) if (ch.kind === "max") {
1802
- if (max === null || ch.value < max) max = ch.value;
1803
- }
1804
- return max;
1805
- }
1806
- get isInt() {
1807
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1808
- }
1809
- get isFinite() {
1810
- let max = null;
1811
- let min = null;
1812
- for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
1813
- else if (ch.kind === "min") {
1814
- if (min === null || ch.value > min) min = ch.value;
1815
- } else if (ch.kind === "max") {
1816
- if (max === null || ch.value < max) max = ch.value;
1817
- }
1818
- return Number.isFinite(min) && Number.isFinite(max);
1819
- }
1820
- };
1821
- ZodNumber.create = (params) => {
1822
- return new ZodNumber({
1823
- checks: [],
1824
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1825
- coerce: params?.coerce || false,
1826
- ...processCreateParams(params)
1827
- });
1828
- };
1829
- var ZodBigInt = class ZodBigInt extends ZodType {
1830
- constructor() {
1831
- super(...arguments);
1832
- this.min = this.gte;
1833
- this.max = this.lte;
1834
- }
1835
- _parse(input) {
1836
- if (this._def.coerce) try {
1837
- input.data = BigInt(input.data);
1838
- } catch {
1839
- return this._getInvalidInput(input);
1840
- }
1841
- const parsedType = this._getType(input);
1842
- if (parsedType !== ZodParsedType.bigint) return this._getInvalidInput(input);
1843
- let ctx = void 0;
1844
- const status = new ParseStatus();
1845
- for (const check of this._def.checks) if (check.kind === "min") {
1846
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1847
- if (tooSmall) {
1848
- ctx = this._getOrReturnCtx(input, ctx);
1849
- addIssueToContext(ctx, {
1850
- code: ZodIssueCode.too_small,
1851
- type: "bigint",
1852
- minimum: check.value,
1853
- inclusive: check.inclusive,
1854
- message: check.message
1855
- });
1856
- status.dirty();
1857
- }
1858
- } else if (check.kind === "max") {
1859
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1860
- if (tooBig) {
1861
- ctx = this._getOrReturnCtx(input, ctx);
1862
- addIssueToContext(ctx, {
1863
- code: ZodIssueCode.too_big,
1864
- type: "bigint",
1865
- maximum: check.value,
1866
- inclusive: check.inclusive,
1867
- message: check.message
1868
- });
1869
- status.dirty();
1870
- }
1871
- } else if (check.kind === "multipleOf") {
1872
- if (input.data % check.value !== BigInt(0)) {
1873
- ctx = this._getOrReturnCtx(input, ctx);
1874
- addIssueToContext(ctx, {
1875
- code: ZodIssueCode.not_multiple_of,
1876
- multipleOf: check.value,
1877
- message: check.message
1878
- });
1879
- status.dirty();
1880
- }
1881
- } else util.assertNever(check);
1882
- return {
1883
- status: status.value,
1884
- value: input.data
1885
- };
1886
- }
1887
- _getInvalidInput(input) {
1888
- const ctx = this._getOrReturnCtx(input);
1889
- addIssueToContext(ctx, {
1890
- code: ZodIssueCode.invalid_type,
1891
- expected: ZodParsedType.bigint,
1892
- received: ctx.parsedType
1893
- });
1894
- return INVALID;
1895
- }
1896
- gte(value, message) {
1897
- return this.setLimit("min", value, true, errorUtil.toString(message));
1898
- }
1899
- gt(value, message) {
1900
- return this.setLimit("min", value, false, errorUtil.toString(message));
1901
- }
1902
- lte(value, message) {
1903
- return this.setLimit("max", value, true, errorUtil.toString(message));
1904
- }
1905
- lt(value, message) {
1906
- return this.setLimit("max", value, false, errorUtil.toString(message));
1907
- }
1908
- setLimit(kind, value, inclusive, message) {
1909
- return new ZodBigInt({
1910
- ...this._def,
1911
- checks: [...this._def.checks, {
1912
- kind,
1913
- value,
1914
- inclusive,
1915
- message: errorUtil.toString(message)
1916
- }]
1917
- });
1918
- }
1919
- _addCheck(check) {
1920
- return new ZodBigInt({
1921
- ...this._def,
1922
- checks: [...this._def.checks, check]
1923
- });
1924
- }
1925
- positive(message) {
1926
- return this._addCheck({
1927
- kind: "min",
1928
- value: BigInt(0),
1929
- inclusive: false,
1930
- message: errorUtil.toString(message)
1931
- });
1932
- }
1933
- negative(message) {
1934
- return this._addCheck({
1935
- kind: "max",
1936
- value: BigInt(0),
1937
- inclusive: false,
1938
- message: errorUtil.toString(message)
1939
- });
1940
- }
1941
- nonpositive(message) {
1942
- return this._addCheck({
1943
- kind: "max",
1944
- value: BigInt(0),
1945
- inclusive: true,
1946
- message: errorUtil.toString(message)
1947
- });
1948
- }
1949
- nonnegative(message) {
1950
- return this._addCheck({
1951
- kind: "min",
1952
- value: BigInt(0),
1953
- inclusive: true,
1954
- message: errorUtil.toString(message)
1955
- });
1956
- }
1957
- multipleOf(value, message) {
1958
- return this._addCheck({
1959
- kind: "multipleOf",
1960
- value,
1961
- message: errorUtil.toString(message)
1962
- });
1963
- }
1964
- get minValue() {
1965
- let min = null;
1966
- for (const ch of this._def.checks) if (ch.kind === "min") {
1967
- if (min === null || ch.value > min) min = ch.value;
1968
- }
1969
- return min;
1970
- }
1971
- get maxValue() {
1972
- let max = null;
1973
- for (const ch of this._def.checks) if (ch.kind === "max") {
1974
- if (max === null || ch.value < max) max = ch.value;
1975
- }
1976
- return max;
1977
- }
1978
- };
1979
- ZodBigInt.create = (params) => {
1980
- return new ZodBigInt({
1981
- checks: [],
1982
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1983
- coerce: params?.coerce ?? false,
1984
- ...processCreateParams(params)
1985
- });
1986
- };
1987
- var ZodBoolean = class extends ZodType {
1988
- _parse(input) {
1989
- if (this._def.coerce) input.data = Boolean(input.data);
1990
- const parsedType = this._getType(input);
1991
- if (parsedType !== ZodParsedType.boolean) {
1992
- const ctx = this._getOrReturnCtx(input);
1993
- addIssueToContext(ctx, {
1994
- code: ZodIssueCode.invalid_type,
1995
- expected: ZodParsedType.boolean,
1996
- received: ctx.parsedType
1997
- });
1998
- return INVALID;
1999
- }
2000
- return OK(input.data);
2001
- }
2002
- };
2003
- ZodBoolean.create = (params) => {
2004
- return new ZodBoolean({
2005
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
2006
- coerce: params?.coerce || false,
2007
- ...processCreateParams(params)
2008
- });
2009
- };
2010
- var ZodDate = class ZodDate extends ZodType {
2011
- _parse(input) {
2012
- if (this._def.coerce) input.data = new Date(input.data);
2013
- const parsedType = this._getType(input);
2014
- if (parsedType !== ZodParsedType.date) {
2015
- const ctx$1 = this._getOrReturnCtx(input);
2016
- addIssueToContext(ctx$1, {
2017
- code: ZodIssueCode.invalid_type,
2018
- expected: ZodParsedType.date,
2019
- received: ctx$1.parsedType
2020
- });
2021
- return INVALID;
2022
- }
2023
- if (Number.isNaN(input.data.getTime())) {
2024
- const ctx$1 = this._getOrReturnCtx(input);
2025
- addIssueToContext(ctx$1, { code: ZodIssueCode.invalid_date });
2026
- return INVALID;
2027
- }
2028
- const status = new ParseStatus();
2029
- let ctx = void 0;
2030
- for (const check of this._def.checks) if (check.kind === "min") {
2031
- if (input.data.getTime() < check.value) {
2032
- ctx = this._getOrReturnCtx(input, ctx);
2033
- addIssueToContext(ctx, {
2034
- code: ZodIssueCode.too_small,
2035
- message: check.message,
2036
- inclusive: true,
2037
- exact: false,
2038
- minimum: check.value,
2039
- type: "date"
2040
- });
2041
- status.dirty();
2042
- }
2043
- } else if (check.kind === "max") {
2044
- if (input.data.getTime() > check.value) {
2045
- ctx = this._getOrReturnCtx(input, ctx);
2046
- addIssueToContext(ctx, {
2047
- code: ZodIssueCode.too_big,
2048
- message: check.message,
2049
- inclusive: true,
2050
- exact: false,
2051
- maximum: check.value,
2052
- type: "date"
2053
- });
2054
- status.dirty();
2055
- }
2056
- } else util.assertNever(check);
2057
- return {
2058
- status: status.value,
2059
- value: new Date(input.data.getTime())
2060
- };
2061
- }
2062
- _addCheck(check) {
2063
- return new ZodDate({
2064
- ...this._def,
2065
- checks: [...this._def.checks, check]
2066
- });
2067
- }
2068
- min(minDate, message) {
2069
- return this._addCheck({
2070
- kind: "min",
2071
- value: minDate.getTime(),
2072
- message: errorUtil.toString(message)
2073
- });
2074
- }
2075
- max(maxDate, message) {
2076
- return this._addCheck({
2077
- kind: "max",
2078
- value: maxDate.getTime(),
2079
- message: errorUtil.toString(message)
2080
- });
2081
- }
2082
- get minDate() {
2083
- let min = null;
2084
- for (const ch of this._def.checks) if (ch.kind === "min") {
2085
- if (min === null || ch.value > min) min = ch.value;
2086
- }
2087
- return min != null ? new Date(min) : null;
2088
- }
2089
- get maxDate() {
2090
- let max = null;
2091
- for (const ch of this._def.checks) if (ch.kind === "max") {
2092
- if (max === null || ch.value < max) max = ch.value;
2093
- }
2094
- return max != null ? new Date(max) : null;
2095
- }
2096
- };
2097
- ZodDate.create = (params) => {
2098
- return new ZodDate({
2099
- checks: [],
2100
- coerce: params?.coerce || false,
2101
- typeName: ZodFirstPartyTypeKind.ZodDate,
2102
- ...processCreateParams(params)
2103
- });
2104
- };
2105
- var ZodSymbol = class extends ZodType {
2106
- _parse(input) {
2107
- const parsedType = this._getType(input);
2108
- if (parsedType !== ZodParsedType.symbol) {
2109
- const ctx = this._getOrReturnCtx(input);
2110
- addIssueToContext(ctx, {
2111
- code: ZodIssueCode.invalid_type,
2112
- expected: ZodParsedType.symbol,
2113
- received: ctx.parsedType
2114
- });
2115
- return INVALID;
2116
- }
2117
- return OK(input.data);
2118
- }
2119
- };
2120
- ZodSymbol.create = (params) => {
2121
- return new ZodSymbol({
2122
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
2123
- ...processCreateParams(params)
2124
- });
2125
- };
2126
- var ZodUndefined = class extends ZodType {
2127
- _parse(input) {
2128
- const parsedType = this._getType(input);
2129
- if (parsedType !== ZodParsedType.undefined) {
2130
- const ctx = this._getOrReturnCtx(input);
2131
- addIssueToContext(ctx, {
2132
- code: ZodIssueCode.invalid_type,
2133
- expected: ZodParsedType.undefined,
2134
- received: ctx.parsedType
2135
- });
2136
- return INVALID;
2137
- }
2138
- return OK(input.data);
2139
- }
2140
- };
2141
- ZodUndefined.create = (params) => {
2142
- return new ZodUndefined({
2143
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
2144
- ...processCreateParams(params)
2145
- });
2146
- };
2147
- var ZodNull = class extends ZodType {
2148
- _parse(input) {
2149
- const parsedType = this._getType(input);
2150
- if (parsedType !== ZodParsedType.null) {
2151
- const ctx = this._getOrReturnCtx(input);
2152
- addIssueToContext(ctx, {
2153
- code: ZodIssueCode.invalid_type,
2154
- expected: ZodParsedType.null,
2155
- received: ctx.parsedType
2156
- });
2157
- return INVALID;
2158
- }
2159
- return OK(input.data);
2160
- }
2161
- };
2162
- ZodNull.create = (params) => {
2163
- return new ZodNull({
2164
- typeName: ZodFirstPartyTypeKind.ZodNull,
2165
- ...processCreateParams(params)
2166
- });
2167
- };
2168
- var ZodAny = class extends ZodType {
2169
- constructor() {
2170
- super(...arguments);
2171
- this._any = true;
2172
- }
2173
- _parse(input) {
2174
- return OK(input.data);
2175
- }
2176
- };
2177
- ZodAny.create = (params) => {
2178
- return new ZodAny({
2179
- typeName: ZodFirstPartyTypeKind.ZodAny,
2180
- ...processCreateParams(params)
2181
- });
2182
- };
2183
- var ZodUnknown = class extends ZodType {
2184
- constructor() {
2185
- super(...arguments);
2186
- this._unknown = true;
2187
- }
2188
- _parse(input) {
2189
- return OK(input.data);
2190
- }
2191
- };
2192
- ZodUnknown.create = (params) => {
2193
- return new ZodUnknown({
2194
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
2195
- ...processCreateParams(params)
2196
- });
2197
- };
2198
- var ZodNever = class extends ZodType {
2199
- _parse(input) {
2200
- const ctx = this._getOrReturnCtx(input);
2201
- addIssueToContext(ctx, {
2202
- code: ZodIssueCode.invalid_type,
2203
- expected: ZodParsedType.never,
2204
- received: ctx.parsedType
2205
- });
2206
- return INVALID;
2207
- }
2208
- };
2209
- ZodNever.create = (params) => {
2210
- return new ZodNever({
2211
- typeName: ZodFirstPartyTypeKind.ZodNever,
2212
- ...processCreateParams(params)
2213
- });
2214
- };
2215
- var ZodVoid = class extends ZodType {
2216
- _parse(input) {
2217
- const parsedType = this._getType(input);
2218
- if (parsedType !== ZodParsedType.undefined) {
2219
- const ctx = this._getOrReturnCtx(input);
2220
- addIssueToContext(ctx, {
2221
- code: ZodIssueCode.invalid_type,
2222
- expected: ZodParsedType.void,
2223
- received: ctx.parsedType
2224
- });
2225
- return INVALID;
2226
- }
2227
- return OK(input.data);
2228
- }
2229
- };
2230
- ZodVoid.create = (params) => {
2231
- return new ZodVoid({
2232
- typeName: ZodFirstPartyTypeKind.ZodVoid,
2233
- ...processCreateParams(params)
2234
- });
2235
- };
2236
- var ZodArray = class ZodArray extends ZodType {
2237
- _parse(input) {
2238
- const { ctx, status } = this._processInputParams(input);
2239
- const def = this._def;
2240
- if (ctx.parsedType !== ZodParsedType.array) {
2241
- addIssueToContext(ctx, {
2242
- code: ZodIssueCode.invalid_type,
2243
- expected: ZodParsedType.array,
2244
- received: ctx.parsedType
2245
- });
2246
- return INVALID;
2247
- }
2248
- if (def.exactLength !== null) {
2249
- const tooBig = ctx.data.length > def.exactLength.value;
2250
- const tooSmall = ctx.data.length < def.exactLength.value;
2251
- if (tooBig || tooSmall) {
2252
- addIssueToContext(ctx, {
2253
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2254
- minimum: tooSmall ? def.exactLength.value : void 0,
2255
- maximum: tooBig ? def.exactLength.value : void 0,
2256
- type: "array",
2257
- inclusive: true,
2258
- exact: true,
2259
- message: def.exactLength.message
2260
- });
2261
- status.dirty();
2262
- }
2263
- }
2264
- if (def.minLength !== null) {
2265
- if (ctx.data.length < def.minLength.value) {
2266
- addIssueToContext(ctx, {
2267
- code: ZodIssueCode.too_small,
2268
- minimum: def.minLength.value,
2269
- type: "array",
2270
- inclusive: true,
2271
- exact: false,
2272
- message: def.minLength.message
2273
- });
2274
- status.dirty();
2275
- }
2276
- }
2277
- if (def.maxLength !== null) {
2278
- if (ctx.data.length > def.maxLength.value) {
2279
- addIssueToContext(ctx, {
2280
- code: ZodIssueCode.too_big,
2281
- maximum: def.maxLength.value,
2282
- type: "array",
2283
- inclusive: true,
2284
- exact: false,
2285
- message: def.maxLength.message
2286
- });
2287
- status.dirty();
2288
- }
2289
- }
2290
- if (ctx.common.async) return Promise.all([...ctx.data].map((item, i) => {
2291
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2292
- })).then((result$1) => {
2293
- return ParseStatus.mergeArray(status, result$1);
2294
- });
2295
- const result = [...ctx.data].map((item, i) => {
2296
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2297
- });
2298
- return ParseStatus.mergeArray(status, result);
2299
- }
2300
- get element() {
2301
- return this._def.type;
2302
- }
2303
- min(minLength, message) {
2304
- return new ZodArray({
2305
- ...this._def,
2306
- minLength: {
2307
- value: minLength,
2308
- message: errorUtil.toString(message)
2309
- }
2310
- });
2311
- }
2312
- max(maxLength, message) {
2313
- return new ZodArray({
2314
- ...this._def,
2315
- maxLength: {
2316
- value: maxLength,
2317
- message: errorUtil.toString(message)
2318
- }
2319
- });
2320
- }
2321
- length(len, message) {
2322
- return new ZodArray({
2323
- ...this._def,
2324
- exactLength: {
2325
- value: len,
2326
- message: errorUtil.toString(message)
2327
- }
2328
- });
2329
- }
2330
- nonempty(message) {
2331
- return this.min(1, message);
2332
- }
2333
- };
2334
- ZodArray.create = (schema, params) => {
2335
- return new ZodArray({
2336
- type: schema,
2337
- minLength: null,
2338
- maxLength: null,
2339
- exactLength: null,
2340
- typeName: ZodFirstPartyTypeKind.ZodArray,
2341
- ...processCreateParams(params)
2342
- });
2343
- };
2344
- function deepPartialify(schema) {
2345
- if (schema instanceof ZodObject) {
2346
- const newShape = {};
2347
- for (const key in schema.shape) {
2348
- const fieldSchema = schema.shape[key];
2349
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2350
- }
2351
- return new ZodObject({
2352
- ...schema._def,
2353
- shape: () => newShape
2354
- });
2355
- } else if (schema instanceof ZodArray) return new ZodArray({
2356
- ...schema._def,
2357
- type: deepPartialify(schema.element)
2358
- });
2359
- else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
2360
- else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
2361
- else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2362
- else return schema;
2363
- }
2364
- var ZodObject = class ZodObject extends ZodType {
2365
- constructor() {
2366
- super(...arguments);
2367
- this._cached = null;
2368
- /**
2369
- * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2370
- * If you want to pass through unknown properties, use `.passthrough()` instead.
2371
- */
2372
- this.nonstrict = this.passthrough;
2373
- /**
2374
- * @deprecated Use `.extend` instead
2375
- * */
2376
- this.augment = this.extend;
2377
- }
2378
- _getCached() {
2379
- if (this._cached !== null) return this._cached;
2380
- const shape = this._def.shape();
2381
- const keys = util.objectKeys(shape);
2382
- this._cached = {
2383
- shape,
2384
- keys
2385
- };
2386
- return this._cached;
2387
- }
2388
- _parse(input) {
2389
- const parsedType = this._getType(input);
2390
- if (parsedType !== ZodParsedType.object) {
2391
- const ctx$1 = this._getOrReturnCtx(input);
2392
- addIssueToContext(ctx$1, {
2393
- code: ZodIssueCode.invalid_type,
2394
- expected: ZodParsedType.object,
2395
- received: ctx$1.parsedType
2396
- });
2397
- return INVALID;
2398
- }
2399
- const { status, ctx } = this._processInputParams(input);
2400
- const { shape, keys: shapeKeys } = this._getCached();
2401
- const extraKeys = [];
2402
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2403
- for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
2404
- }
2405
- const pairs = [];
2406
- for (const key of shapeKeys) {
2407
- const keyValidator = shape[key];
2408
- const value = ctx.data[key];
2409
- pairs.push({
2410
- key: {
2411
- status: "valid",
2412
- value: key
2413
- },
2414
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2415
- alwaysSet: key in ctx.data
2416
- });
2417
- }
2418
- if (this._def.catchall instanceof ZodNever) {
2419
- const unknownKeys = this._def.unknownKeys;
2420
- if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
2421
- key: {
2422
- status: "valid",
2423
- value: key
2424
- },
2425
- value: {
2426
- status: "valid",
2427
- value: ctx.data[key]
2428
- }
2429
- });
2430
- else if (unknownKeys === "strict") {
2431
- if (extraKeys.length > 0) {
2432
- addIssueToContext(ctx, {
2433
- code: ZodIssueCode.unrecognized_keys,
2434
- keys: extraKeys
2435
- });
2436
- status.dirty();
2437
- }
2438
- } else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2439
- } else {
2440
- const catchall = this._def.catchall;
2441
- for (const key of extraKeys) {
2442
- const value = ctx.data[key];
2443
- pairs.push({
2444
- key: {
2445
- status: "valid",
2446
- value: key
2447
- },
2448
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2449
- alwaysSet: key in ctx.data
2450
- });
2451
- }
2452
- }
2453
- if (ctx.common.async) return Promise.resolve().then(async () => {
2454
- const syncPairs = [];
2455
- for (const pair of pairs) {
2456
- const key = await pair.key;
2457
- const value = await pair.value;
2458
- syncPairs.push({
2459
- key,
2460
- value,
2461
- alwaysSet: pair.alwaysSet
2462
- });
2463
- }
2464
- return syncPairs;
2465
- }).then((syncPairs) => {
2466
- return ParseStatus.mergeObjectSync(status, syncPairs);
2467
- });
2468
- else return ParseStatus.mergeObjectSync(status, pairs);
2469
- }
2470
- get shape() {
2471
- return this._def.shape();
2472
- }
2473
- strict(message) {
2474
- errorUtil.errToObj;
2475
- return new ZodObject({
2476
- ...this._def,
2477
- unknownKeys: "strict",
2478
- ...message !== void 0 ? { errorMap: (issue, ctx) => {
2479
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2480
- if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
2481
- return { message: defaultError };
2482
- } } : {}
2483
- });
2484
- }
2485
- strip() {
2486
- return new ZodObject({
2487
- ...this._def,
2488
- unknownKeys: "strip"
2489
- });
2490
- }
2491
- passthrough() {
2492
- return new ZodObject({
2493
- ...this._def,
2494
- unknownKeys: "passthrough"
2495
- });
2496
- }
2497
- extend(augmentation) {
2498
- return new ZodObject({
2499
- ...this._def,
2500
- shape: () => ({
2501
- ...this._def.shape(),
2502
- ...augmentation
2503
- })
2504
- });
2505
- }
2506
- /**
2507
- * Prior to zod@1.0.12 there was a bug in the
2508
- * inferred type of merged objects. Please
2509
- * upgrade if you are experiencing issues.
2510
- */
2511
- merge(merging) {
2512
- const merged = new ZodObject({
2513
- unknownKeys: merging._def.unknownKeys,
2514
- catchall: merging._def.catchall,
2515
- shape: () => ({
2516
- ...this._def.shape(),
2517
- ...merging._def.shape()
2518
- }),
2519
- typeName: ZodFirstPartyTypeKind.ZodObject
2520
- });
2521
- return merged;
2522
- }
2523
- setKey(key, schema) {
2524
- return this.augment({ [key]: schema });
2525
- }
2526
- catchall(index) {
2527
- return new ZodObject({
2528
- ...this._def,
2529
- catchall: index
2530
- });
2531
- }
2532
- pick(mask) {
2533
- const shape = {};
2534
- for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
2535
- return new ZodObject({
2536
- ...this._def,
2537
- shape: () => shape
2538
- });
2539
- }
2540
- omit(mask) {
2541
- const shape = {};
2542
- for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
2543
- return new ZodObject({
2544
- ...this._def,
2545
- shape: () => shape
2546
- });
2547
- }
2548
- /**
2549
- * @deprecated
2550
- */
2551
- deepPartial() {
2552
- return deepPartialify(this);
2553
- }
2554
- partial(mask) {
2555
- const newShape = {};
2556
- for (const key of util.objectKeys(this.shape)) {
2557
- const fieldSchema = this.shape[key];
2558
- if (mask && !mask[key]) newShape[key] = fieldSchema;
2559
- else newShape[key] = fieldSchema.optional();
2560
- }
2561
- return new ZodObject({
2562
- ...this._def,
2563
- shape: () => newShape
2564
- });
2565
- }
2566
- required(mask) {
2567
- const newShape = {};
2568
- for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
2569
- else {
2570
- const fieldSchema = this.shape[key];
2571
- let newField = fieldSchema;
2572
- while (newField instanceof ZodOptional) newField = newField._def.innerType;
2573
- newShape[key] = newField;
2574
- }
2575
- return new ZodObject({
2576
- ...this._def,
2577
- shape: () => newShape
2578
- });
2579
- }
2580
- keyof() {
2581
- return createZodEnum(util.objectKeys(this.shape));
2582
- }
2583
- };
2584
- ZodObject.create = (shape, params) => {
2585
- return new ZodObject({
2586
- shape: () => shape,
2587
- unknownKeys: "strip",
2588
- catchall: ZodNever.create(),
2589
- typeName: ZodFirstPartyTypeKind.ZodObject,
2590
- ...processCreateParams(params)
2591
- });
2592
- };
2593
- ZodObject.strictCreate = (shape, params) => {
2594
- return new ZodObject({
2595
- shape: () => shape,
2596
- unknownKeys: "strict",
2597
- catchall: ZodNever.create(),
2598
- typeName: ZodFirstPartyTypeKind.ZodObject,
2599
- ...processCreateParams(params)
2600
- });
2601
- };
2602
- ZodObject.lazycreate = (shape, params) => {
2603
- return new ZodObject({
2604
- shape,
2605
- unknownKeys: "strip",
2606
- catchall: ZodNever.create(),
2607
- typeName: ZodFirstPartyTypeKind.ZodObject,
2608
- ...processCreateParams(params)
2609
- });
2610
- };
2611
- var ZodUnion = class extends ZodType {
2612
- _parse(input) {
2613
- const { ctx } = this._processInputParams(input);
2614
- const options = this._def.options;
2615
- function handleResults(results) {
2616
- for (const result of results) if (result.result.status === "valid") return result.result;
2617
- for (const result of results) if (result.result.status === "dirty") {
2618
- ctx.common.issues.push(...result.ctx.common.issues);
2619
- return result.result;
2620
- }
2621
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2622
- addIssueToContext(ctx, {
2623
- code: ZodIssueCode.invalid_union,
2624
- unionErrors
2625
- });
2626
- return INVALID;
2627
- }
2628
- if (ctx.common.async) return Promise.all(options.map(async (option) => {
2629
- const childCtx = {
2630
- ...ctx,
2631
- common: {
2632
- ...ctx.common,
2633
- issues: []
2634
- },
2635
- parent: null
2636
- };
2637
- return {
2638
- result: await option._parseAsync({
2639
- data: ctx.data,
2640
- path: ctx.path,
2641
- parent: childCtx
2642
- }),
2643
- ctx: childCtx
2644
- };
2645
- })).then(handleResults);
2646
- else {
2647
- let dirty = void 0;
2648
- const issues = [];
2649
- for (const option of options) {
2650
- const childCtx = {
2651
- ...ctx,
2652
- common: {
2653
- ...ctx.common,
2654
- issues: []
2655
- },
2656
- parent: null
2657
- };
2658
- const result = option._parseSync({
2659
- data: ctx.data,
2660
- path: ctx.path,
2661
- parent: childCtx
2662
- });
2663
- if (result.status === "valid") return result;
2664
- else if (result.status === "dirty" && !dirty) dirty = {
2665
- result,
2666
- ctx: childCtx
2667
- };
2668
- if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
2669
- }
2670
- if (dirty) {
2671
- ctx.common.issues.push(...dirty.ctx.common.issues);
2672
- return dirty.result;
2673
- }
2674
- const unionErrors = issues.map((issues$1) => new ZodError(issues$1));
2675
- addIssueToContext(ctx, {
2676
- code: ZodIssueCode.invalid_union,
2677
- unionErrors
2678
- });
2679
- return INVALID;
2680
- }
2681
- }
2682
- get options() {
2683
- return this._def.options;
2684
- }
2685
- };
2686
- ZodUnion.create = (types, params) => {
2687
- return new ZodUnion({
2688
- options: types,
2689
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2690
- ...processCreateParams(params)
2691
- });
2692
- };
2693
- const getDiscriminator = (type) => {
2694
- if (type instanceof ZodLazy) return getDiscriminator(type.schema);
2695
- else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
2696
- else if (type instanceof ZodLiteral) return [type.value];
2697
- else if (type instanceof ZodEnum) return type.options;
2698
- else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
2699
- else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
2700
- else if (type instanceof ZodUndefined) return [void 0];
2701
- else if (type instanceof ZodNull) return [null];
2702
- else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
2703
- else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
2704
- else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
2705
- else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
2706
- else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
2707
- else return [];
2708
- };
2709
- var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
2710
- _parse(input) {
2711
- const { ctx } = this._processInputParams(input);
2712
- if (ctx.parsedType !== ZodParsedType.object) {
2713
- addIssueToContext(ctx, {
2714
- code: ZodIssueCode.invalid_type,
2715
- expected: ZodParsedType.object,
2716
- received: ctx.parsedType
2717
- });
2718
- return INVALID;
2719
- }
2720
- const discriminator = this.discriminator;
2721
- const discriminatorValue = ctx.data[discriminator];
2722
- const option = this.optionsMap.get(discriminatorValue);
2723
- if (!option) {
2724
- addIssueToContext(ctx, {
2725
- code: ZodIssueCode.invalid_union_discriminator,
2726
- options: Array.from(this.optionsMap.keys()),
2727
- path: [discriminator]
2728
- });
2729
- return INVALID;
2730
- }
2731
- if (ctx.common.async) return option._parseAsync({
2732
- data: ctx.data,
2733
- path: ctx.path,
2734
- parent: ctx
2735
- });
2736
- else return option._parseSync({
2737
- data: ctx.data,
2738
- path: ctx.path,
2739
- parent: ctx
2740
- });
2741
- }
2742
- get discriminator() {
2743
- return this._def.discriminator;
2744
- }
2745
- get options() {
2746
- return this._def.options;
2747
- }
2748
- get optionsMap() {
2749
- return this._def.optionsMap;
2750
- }
2751
- /**
2752
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2753
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2754
- * have a different value for each object in the union.
2755
- * @param discriminator the name of the discriminator property
2756
- * @param types an array of object schemas
2757
- * @param params
2758
- */
2759
- static create(discriminator, options, params) {
2760
- const optionsMap = /* @__PURE__ */ new Map();
2761
- for (const type of options) {
2762
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2763
- if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2764
- for (const value of discriminatorValues) {
2765
- if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2766
- optionsMap.set(value, type);
2767
- }
2768
- }
2769
- return new ZodDiscriminatedUnion({
2770
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2771
- discriminator,
2772
- options,
2773
- optionsMap,
2774
- ...processCreateParams(params)
2775
- });
2776
- }
2777
- };
2778
- function mergeValues(a, b) {
2779
- const aType = getParsedType(a);
2780
- const bType = getParsedType(b);
2781
- if (a === b) return {
2782
- valid: true,
2783
- data: a
2784
- };
2785
- else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2786
- const bKeys = util.objectKeys(b);
2787
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2788
- const newObj = {
2789
- ...a,
2790
- ...b
2791
- };
2792
- for (const key of sharedKeys) {
2793
- const sharedValue = mergeValues(a[key], b[key]);
2794
- if (!sharedValue.valid) return { valid: false };
2795
- newObj[key] = sharedValue.data;
2796
- }
2797
- return {
2798
- valid: true,
2799
- data: newObj
2800
- };
2801
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2802
- if (a.length !== b.length) return { valid: false };
2803
- const newArray = [];
2804
- for (let index = 0; index < a.length; index++) {
2805
- const itemA = a[index];
2806
- const itemB = b[index];
2807
- const sharedValue = mergeValues(itemA, itemB);
2808
- if (!sharedValue.valid) return { valid: false };
2809
- newArray.push(sharedValue.data);
2810
- }
2811
- return {
2812
- valid: true,
2813
- data: newArray
2814
- };
2815
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
2816
- valid: true,
2817
- data: a
2818
- };
2819
- else return { valid: false };
2820
- }
2821
- var ZodIntersection = class extends ZodType {
2822
- _parse(input) {
2823
- const { status, ctx } = this._processInputParams(input);
2824
- const handleParsed = (parsedLeft, parsedRight) => {
2825
- if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
2826
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2827
- if (!merged.valid) {
2828
- addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
2829
- return INVALID;
2830
- }
2831
- if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
2832
- return {
2833
- status: status.value,
2834
- value: merged.data
2835
- };
2836
- };
2837
- if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
2838
- data: ctx.data,
2839
- path: ctx.path,
2840
- parent: ctx
2841
- }), this._def.right._parseAsync({
2842
- data: ctx.data,
2843
- path: ctx.path,
2844
- parent: ctx
2845
- })]).then(([left, right]) => handleParsed(left, right));
2846
- else return handleParsed(this._def.left._parseSync({
2847
- data: ctx.data,
2848
- path: ctx.path,
2849
- parent: ctx
2850
- }), this._def.right._parseSync({
2851
- data: ctx.data,
2852
- path: ctx.path,
2853
- parent: ctx
2854
- }));
2855
- }
2856
- };
2857
- ZodIntersection.create = (left, right, params) => {
2858
- return new ZodIntersection({
2859
- left,
2860
- right,
2861
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
2862
- ...processCreateParams(params)
2863
- });
2864
- };
2865
- var ZodTuple = class ZodTuple extends ZodType {
2866
- _parse(input) {
2867
- const { status, ctx } = this._processInputParams(input);
2868
- if (ctx.parsedType !== ZodParsedType.array) {
2869
- addIssueToContext(ctx, {
2870
- code: ZodIssueCode.invalid_type,
2871
- expected: ZodParsedType.array,
2872
- received: ctx.parsedType
2873
- });
2874
- return INVALID;
2875
- }
2876
- if (ctx.data.length < this._def.items.length) {
2877
- addIssueToContext(ctx, {
2878
- code: ZodIssueCode.too_small,
2879
- minimum: this._def.items.length,
2880
- inclusive: true,
2881
- exact: false,
2882
- type: "array"
2883
- });
2884
- return INVALID;
2885
- }
2886
- const rest = this._def.rest;
2887
- if (!rest && ctx.data.length > this._def.items.length) {
2888
- addIssueToContext(ctx, {
2889
- code: ZodIssueCode.too_big,
2890
- maximum: this._def.items.length,
2891
- inclusive: true,
2892
- exact: false,
2893
- type: "array"
2894
- });
2895
- status.dirty();
2896
- }
2897
- const items = [...ctx.data].map((item, itemIndex) => {
2898
- const schema = this._def.items[itemIndex] || this._def.rest;
2899
- if (!schema) return null;
2900
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2901
- }).filter((x) => !!x);
2902
- if (ctx.common.async) return Promise.all(items).then((results) => {
2903
- return ParseStatus.mergeArray(status, results);
2904
- });
2905
- else return ParseStatus.mergeArray(status, items);
2906
- }
2907
- get items() {
2908
- return this._def.items;
2909
- }
2910
- rest(rest) {
2911
- return new ZodTuple({
2912
- ...this._def,
2913
- rest
2914
- });
2915
- }
2916
- };
2917
- ZodTuple.create = (schemas, params) => {
2918
- if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2919
- return new ZodTuple({
2920
- items: schemas,
2921
- typeName: ZodFirstPartyTypeKind.ZodTuple,
2922
- rest: null,
2923
- ...processCreateParams(params)
2924
- });
2925
- };
2926
- var ZodRecord = class ZodRecord extends ZodType {
2927
- get keySchema() {
2928
- return this._def.keyType;
2929
- }
2930
- get valueSchema() {
2931
- return this._def.valueType;
2932
- }
2933
- _parse(input) {
2934
- const { status, ctx } = this._processInputParams(input);
2935
- if (ctx.parsedType !== ZodParsedType.object) {
2936
- addIssueToContext(ctx, {
2937
- code: ZodIssueCode.invalid_type,
2938
- expected: ZodParsedType.object,
2939
- received: ctx.parsedType
2940
- });
2941
- return INVALID;
2942
- }
2943
- const pairs = [];
2944
- const keyType = this._def.keyType;
2945
- const valueType = this._def.valueType;
2946
- for (const key in ctx.data) pairs.push({
2947
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2948
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2949
- alwaysSet: key in ctx.data
2950
- });
2951
- if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
2952
- else return ParseStatus.mergeObjectSync(status, pairs);
2953
- }
2954
- get element() {
2955
- return this._def.valueType;
2956
- }
2957
- static create(first, second, third) {
2958
- if (second instanceof ZodType) return new ZodRecord({
2959
- keyType: first,
2960
- valueType: second,
2961
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2962
- ...processCreateParams(third)
2963
- });
2964
- return new ZodRecord({
2965
- keyType: ZodString.create(),
2966
- valueType: first,
2967
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2968
- ...processCreateParams(second)
2969
- });
2970
- }
2971
- };
2972
- var ZodMap = class extends ZodType {
2973
- get keySchema() {
2974
- return this._def.keyType;
2975
- }
2976
- get valueSchema() {
2977
- return this._def.valueType;
2978
- }
2979
- _parse(input) {
2980
- const { status, ctx } = this._processInputParams(input);
2981
- if (ctx.parsedType !== ZodParsedType.map) {
2982
- addIssueToContext(ctx, {
2983
- code: ZodIssueCode.invalid_type,
2984
- expected: ZodParsedType.map,
2985
- received: ctx.parsedType
2986
- });
2987
- return INVALID;
2988
- }
2989
- const keyType = this._def.keyType;
2990
- const valueType = this._def.valueType;
2991
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2992
- return {
2993
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2994
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2995
- };
2996
- });
2997
- if (ctx.common.async) {
2998
- const finalMap = /* @__PURE__ */ new Map();
2999
- return Promise.resolve().then(async () => {
3000
- for (const pair of pairs) {
3001
- const key = await pair.key;
3002
- const value = await pair.value;
3003
- if (key.status === "aborted" || value.status === "aborted") return INVALID;
3004
- if (key.status === "dirty" || value.status === "dirty") status.dirty();
3005
- finalMap.set(key.value, value.value);
3006
- }
3007
- return {
3008
- status: status.value,
3009
- value: finalMap
3010
- };
3011
- });
3012
- } else {
3013
- const finalMap = /* @__PURE__ */ new Map();
3014
- for (const pair of pairs) {
3015
- const key = pair.key;
3016
- const value = pair.value;
3017
- if (key.status === "aborted" || value.status === "aborted") return INVALID;
3018
- if (key.status === "dirty" || value.status === "dirty") status.dirty();
3019
- finalMap.set(key.value, value.value);
3020
- }
3021
- return {
3022
- status: status.value,
3023
- value: finalMap
3024
- };
3025
- }
3026
- }
3027
- };
3028
- ZodMap.create = (keyType, valueType, params) => {
3029
- return new ZodMap({
3030
- valueType,
3031
- keyType,
3032
- typeName: ZodFirstPartyTypeKind.ZodMap,
3033
- ...processCreateParams(params)
3034
- });
3035
- };
3036
- var ZodSet = class ZodSet extends ZodType {
3037
- _parse(input) {
3038
- const { status, ctx } = this._processInputParams(input);
3039
- if (ctx.parsedType !== ZodParsedType.set) {
3040
- addIssueToContext(ctx, {
3041
- code: ZodIssueCode.invalid_type,
3042
- expected: ZodParsedType.set,
3043
- received: ctx.parsedType
3044
- });
3045
- return INVALID;
3046
- }
3047
- const def = this._def;
3048
- if (def.minSize !== null) {
3049
- if (ctx.data.size < def.minSize.value) {
3050
- addIssueToContext(ctx, {
3051
- code: ZodIssueCode.too_small,
3052
- minimum: def.minSize.value,
3053
- type: "set",
3054
- inclusive: true,
3055
- exact: false,
3056
- message: def.minSize.message
3057
- });
3058
- status.dirty();
3059
- }
3060
- }
3061
- if (def.maxSize !== null) {
3062
- if (ctx.data.size > def.maxSize.value) {
3063
- addIssueToContext(ctx, {
3064
- code: ZodIssueCode.too_big,
3065
- maximum: def.maxSize.value,
3066
- type: "set",
3067
- inclusive: true,
3068
- exact: false,
3069
- message: def.maxSize.message
3070
- });
3071
- status.dirty();
3072
- }
3073
- }
3074
- const valueType = this._def.valueType;
3075
- function finalizeSet(elements$1) {
3076
- const parsedSet = /* @__PURE__ */ new Set();
3077
- for (const element of elements$1) {
3078
- if (element.status === "aborted") return INVALID;
3079
- if (element.status === "dirty") status.dirty();
3080
- parsedSet.add(element.value);
3081
- }
3082
- return {
3083
- status: status.value,
3084
- value: parsedSet
3085
- };
3086
- }
3087
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3088
- if (ctx.common.async) return Promise.all(elements).then((elements$1) => finalizeSet(elements$1));
3089
- else return finalizeSet(elements);
3090
- }
3091
- min(minSize, message) {
3092
- return new ZodSet({
3093
- ...this._def,
3094
- minSize: {
3095
- value: minSize,
3096
- message: errorUtil.toString(message)
3097
- }
3098
- });
3099
- }
3100
- max(maxSize, message) {
3101
- return new ZodSet({
3102
- ...this._def,
3103
- maxSize: {
3104
- value: maxSize,
3105
- message: errorUtil.toString(message)
3106
- }
3107
- });
3108
- }
3109
- size(size, message) {
3110
- return this.min(size, message).max(size, message);
3111
- }
3112
- nonempty(message) {
3113
- return this.min(1, message);
3114
- }
3115
- };
3116
- ZodSet.create = (valueType, params) => {
3117
- return new ZodSet({
3118
- valueType,
3119
- minSize: null,
3120
- maxSize: null,
3121
- typeName: ZodFirstPartyTypeKind.ZodSet,
3122
- ...processCreateParams(params)
3123
- });
3124
- };
3125
- var ZodFunction = class ZodFunction extends ZodType {
3126
- constructor() {
3127
- super(...arguments);
3128
- this.validate = this.implement;
3129
- }
3130
- _parse(input) {
3131
- const { ctx } = this._processInputParams(input);
3132
- if (ctx.parsedType !== ZodParsedType.function) {
3133
- addIssueToContext(ctx, {
3134
- code: ZodIssueCode.invalid_type,
3135
- expected: ZodParsedType.function,
3136
- received: ctx.parsedType
3137
- });
3138
- return INVALID;
3139
- }
3140
- function makeArgsIssue(args, error) {
3141
- return makeIssue({
3142
- data: args,
3143
- path: ctx.path,
3144
- errorMaps: [
3145
- ctx.common.contextualErrorMap,
3146
- ctx.schemaErrorMap,
3147
- getErrorMap(),
3148
- en_default
3149
- ].filter((x) => !!x),
3150
- issueData: {
3151
- code: ZodIssueCode.invalid_arguments,
3152
- argumentsError: error
3153
- }
3154
- });
3155
- }
3156
- function makeReturnsIssue(returns, error) {
3157
- return makeIssue({
3158
- data: returns,
3159
- path: ctx.path,
3160
- errorMaps: [
3161
- ctx.common.contextualErrorMap,
3162
- ctx.schemaErrorMap,
3163
- getErrorMap(),
3164
- en_default
3165
- ].filter((x) => !!x),
3166
- issueData: {
3167
- code: ZodIssueCode.invalid_return_type,
3168
- returnTypeError: error
3169
- }
3170
- });
3171
- }
3172
- const params = { errorMap: ctx.common.contextualErrorMap };
3173
- const fn = ctx.data;
3174
- if (this._def.returns instanceof ZodPromise) {
3175
- const me = this;
3176
- return OK(async function(...args) {
3177
- const error = new ZodError([]);
3178
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3179
- error.addIssue(makeArgsIssue(args, e));
3180
- throw error;
3181
- });
3182
- const result = await Reflect.apply(fn, this, parsedArgs);
3183
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3184
- error.addIssue(makeReturnsIssue(result, e));
3185
- throw error;
3186
- });
3187
- return parsedReturns;
3188
- });
3189
- } else {
3190
- const me = this;
3191
- return OK(function(...args) {
3192
- const parsedArgs = me._def.args.safeParse(args, params);
3193
- if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3194
- const result = Reflect.apply(fn, this, parsedArgs.data);
3195
- const parsedReturns = me._def.returns.safeParse(result, params);
3196
- if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3197
- return parsedReturns.data;
3198
- });
3199
- }
3200
- }
3201
- parameters() {
3202
- return this._def.args;
3203
- }
3204
- returnType() {
3205
- return this._def.returns;
3206
- }
3207
- args(...items) {
3208
- return new ZodFunction({
3209
- ...this._def,
3210
- args: ZodTuple.create(items).rest(ZodUnknown.create())
3211
- });
3212
- }
3213
- returns(returnType) {
3214
- return new ZodFunction({
3215
- ...this._def,
3216
- returns: returnType
3217
- });
3218
- }
3219
- implement(func) {
3220
- const validatedFunc = this.parse(func);
3221
- return validatedFunc;
3222
- }
3223
- strictImplement(func) {
3224
- const validatedFunc = this.parse(func);
3225
- return validatedFunc;
3226
- }
3227
- static create(args, returns, params) {
3228
- return new ZodFunction({
3229
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3230
- returns: returns || ZodUnknown.create(),
3231
- typeName: ZodFirstPartyTypeKind.ZodFunction,
3232
- ...processCreateParams(params)
3233
- });
3234
- }
3235
- };
3236
- var ZodLazy = class extends ZodType {
3237
- get schema() {
3238
- return this._def.getter();
3239
- }
3240
- _parse(input) {
3241
- const { ctx } = this._processInputParams(input);
3242
- const lazySchema = this._def.getter();
3243
- return lazySchema._parse({
3244
- data: ctx.data,
3245
- path: ctx.path,
3246
- parent: ctx
3247
- });
3248
- }
3249
- };
3250
- ZodLazy.create = (getter, params) => {
3251
- return new ZodLazy({
3252
- getter,
3253
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3254
- ...processCreateParams(params)
3255
- });
3256
- };
3257
- var ZodLiteral = class extends ZodType {
3258
- _parse(input) {
3259
- if (input.data !== this._def.value) {
3260
- const ctx = this._getOrReturnCtx(input);
3261
- addIssueToContext(ctx, {
3262
- received: ctx.data,
3263
- code: ZodIssueCode.invalid_literal,
3264
- expected: this._def.value
3265
- });
3266
- return INVALID;
3267
- }
3268
- return {
3269
- status: "valid",
3270
- value: input.data
3271
- };
3272
- }
3273
- get value() {
3274
- return this._def.value;
3275
- }
3276
- };
3277
- ZodLiteral.create = (value, params) => {
3278
- return new ZodLiteral({
3279
- value,
3280
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3281
- ...processCreateParams(params)
3282
- });
3283
- };
3284
- function createZodEnum(values, params) {
3285
- return new ZodEnum({
3286
- values,
3287
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3288
- ...processCreateParams(params)
3289
- });
3290
- }
3291
- var ZodEnum = class ZodEnum extends ZodType {
3292
- _parse(input) {
3293
- if (typeof input.data !== "string") {
3294
- const ctx = this._getOrReturnCtx(input);
3295
- const expectedValues = this._def.values;
3296
- addIssueToContext(ctx, {
3297
- expected: util.joinValues(expectedValues),
3298
- received: ctx.parsedType,
3299
- code: ZodIssueCode.invalid_type
3300
- });
3301
- return INVALID;
3302
- }
3303
- if (!this._cache) this._cache = new Set(this._def.values);
3304
- if (!this._cache.has(input.data)) {
3305
- const ctx = this._getOrReturnCtx(input);
3306
- const expectedValues = this._def.values;
3307
- addIssueToContext(ctx, {
3308
- received: ctx.data,
3309
- code: ZodIssueCode.invalid_enum_value,
3310
- options: expectedValues
3311
- });
3312
- return INVALID;
3313
- }
3314
- return OK(input.data);
3315
- }
3316
- get options() {
3317
- return this._def.values;
3318
- }
3319
- get enum() {
3320
- const enumValues = {};
3321
- for (const val of this._def.values) enumValues[val] = val;
3322
- return enumValues;
3323
- }
3324
- get Values() {
3325
- const enumValues = {};
3326
- for (const val of this._def.values) enumValues[val] = val;
3327
- return enumValues;
3328
- }
3329
- get Enum() {
3330
- const enumValues = {};
3331
- for (const val of this._def.values) enumValues[val] = val;
3332
- return enumValues;
3333
- }
3334
- extract(values, newDef = this._def) {
3335
- return ZodEnum.create(values, {
3336
- ...this._def,
3337
- ...newDef
3338
- });
3339
- }
3340
- exclude(values, newDef = this._def) {
3341
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3342
- ...this._def,
3343
- ...newDef
3344
- });
3345
- }
3346
- };
3347
- ZodEnum.create = createZodEnum;
3348
- var ZodNativeEnum = class extends ZodType {
3349
- _parse(input) {
3350
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3351
- const ctx = this._getOrReturnCtx(input);
3352
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3353
- const expectedValues = util.objectValues(nativeEnumValues);
3354
- addIssueToContext(ctx, {
3355
- expected: util.joinValues(expectedValues),
3356
- received: ctx.parsedType,
3357
- code: ZodIssueCode.invalid_type
3358
- });
3359
- return INVALID;
3360
- }
3361
- if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
3362
- if (!this._cache.has(input.data)) {
3363
- const expectedValues = util.objectValues(nativeEnumValues);
3364
- addIssueToContext(ctx, {
3365
- received: ctx.data,
3366
- code: ZodIssueCode.invalid_enum_value,
3367
- options: expectedValues
3368
- });
3369
- return INVALID;
3370
- }
3371
- return OK(input.data);
3372
- }
3373
- get enum() {
3374
- return this._def.values;
3375
- }
3376
- };
3377
- ZodNativeEnum.create = (values, params) => {
3378
- return new ZodNativeEnum({
3379
- values,
3380
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3381
- ...processCreateParams(params)
3382
- });
3383
- };
3384
- var ZodPromise = class extends ZodType {
3385
- unwrap() {
3386
- return this._def.type;
3387
- }
3388
- _parse(input) {
3389
- const { ctx } = this._processInputParams(input);
3390
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3391
- addIssueToContext(ctx, {
3392
- code: ZodIssueCode.invalid_type,
3393
- expected: ZodParsedType.promise,
3394
- received: ctx.parsedType
3395
- });
3396
- return INVALID;
3397
- }
3398
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3399
- return OK(promisified.then((data) => {
3400
- return this._def.type.parseAsync(data, {
3401
- path: ctx.path,
3402
- errorMap: ctx.common.contextualErrorMap
3403
- });
3404
- }));
3405
- }
3406
- };
3407
- ZodPromise.create = (schema, params) => {
3408
- return new ZodPromise({
3409
- type: schema,
3410
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3411
- ...processCreateParams(params)
3412
- });
3413
- };
3414
- var ZodEffects = class extends ZodType {
3415
- innerType() {
3416
- return this._def.schema;
3417
- }
3418
- sourceType() {
3419
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3420
- }
3421
- _parse(input) {
3422
- const { status, ctx } = this._processInputParams(input);
3423
- const effect = this._def.effect || null;
3424
- const checkCtx = {
3425
- addIssue: (arg) => {
3426
- addIssueToContext(ctx, arg);
3427
- if (arg.fatal) status.abort();
3428
- else status.dirty();
3429
- },
3430
- get path() {
3431
- return ctx.path;
3432
- }
3433
- };
3434
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3435
- if (effect.type === "preprocess") {
3436
- const processed = effect.transform(ctx.data, checkCtx);
3437
- if (ctx.common.async) return Promise.resolve(processed).then(async (processed$1) => {
3438
- if (status.value === "aborted") return INVALID;
3439
- const result = await this._def.schema._parseAsync({
3440
- data: processed$1,
3441
- path: ctx.path,
3442
- parent: ctx
3443
- });
3444
- if (result.status === "aborted") return INVALID;
3445
- if (result.status === "dirty") return DIRTY(result.value);
3446
- if (status.value === "dirty") return DIRTY(result.value);
3447
- return result;
3448
- });
3449
- else {
3450
- if (status.value === "aborted") return INVALID;
3451
- const result = this._def.schema._parseSync({
3452
- data: processed,
3453
- path: ctx.path,
3454
- parent: ctx
3455
- });
3456
- if (result.status === "aborted") return INVALID;
3457
- if (result.status === "dirty") return DIRTY(result.value);
3458
- if (status.value === "dirty") return DIRTY(result.value);
3459
- return result;
3460
- }
3461
- }
3462
- if (effect.type === "refinement") {
3463
- const executeRefinement = (acc) => {
3464
- const result = effect.refinement(acc, checkCtx);
3465
- if (ctx.common.async) return Promise.resolve(result);
3466
- if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3467
- return acc;
3468
- };
3469
- if (ctx.common.async === false) {
3470
- const inner = this._def.schema._parseSync({
3471
- data: ctx.data,
3472
- path: ctx.path,
3473
- parent: ctx
3474
- });
3475
- if (inner.status === "aborted") return INVALID;
3476
- if (inner.status === "dirty") status.dirty();
3477
- executeRefinement(inner.value);
3478
- return {
3479
- status: status.value,
3480
- value: inner.value
3481
- };
3482
- } else return this._def.schema._parseAsync({
3483
- data: ctx.data,
3484
- path: ctx.path,
3485
- parent: ctx
3486
- }).then((inner) => {
3487
- if (inner.status === "aborted") return INVALID;
3488
- if (inner.status === "dirty") status.dirty();
3489
- return executeRefinement(inner.value).then(() => {
3490
- return {
3491
- status: status.value,
3492
- value: inner.value
3493
- };
3494
- });
3495
- });
3496
- }
3497
- if (effect.type === "transform") if (ctx.common.async === false) {
3498
- const base = this._def.schema._parseSync({
3499
- data: ctx.data,
3500
- path: ctx.path,
3501
- parent: ctx
3502
- });
3503
- if (!isValid(base)) return INVALID;
3504
- const result = effect.transform(base.value, checkCtx);
3505
- if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3506
- return {
3507
- status: status.value,
3508
- value: result
3509
- };
3510
- } else return this._def.schema._parseAsync({
3511
- data: ctx.data,
3512
- path: ctx.path,
3513
- parent: ctx
3514
- }).then((base) => {
3515
- if (!isValid(base)) return INVALID;
3516
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3517
- status: status.value,
3518
- value: result
3519
- }));
3520
- });
3521
- util.assertNever(effect);
3522
- }
3523
- };
3524
- ZodEffects.create = (schema, effect, params) => {
3525
- return new ZodEffects({
3526
- schema,
3527
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3528
- effect,
3529
- ...processCreateParams(params)
3530
- });
3531
- };
3532
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3533
- return new ZodEffects({
3534
- schema,
3535
- effect: {
3536
- type: "preprocess",
3537
- transform: preprocess
3538
- },
3539
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3540
- ...processCreateParams(params)
3541
- });
3542
- };
3543
- var ZodOptional = class extends ZodType {
3544
- _parse(input) {
3545
- const parsedType = this._getType(input);
3546
- if (parsedType === ZodParsedType.undefined) return OK(void 0);
3547
- return this._def.innerType._parse(input);
3548
- }
3549
- unwrap() {
3550
- return this._def.innerType;
3551
- }
3552
- };
3553
- ZodOptional.create = (type, params) => {
3554
- return new ZodOptional({
3555
- innerType: type,
3556
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3557
- ...processCreateParams(params)
3558
- });
3559
- };
3560
- var ZodNullable = class extends ZodType {
3561
- _parse(input) {
3562
- const parsedType = this._getType(input);
3563
- if (parsedType === ZodParsedType.null) return OK(null);
3564
- return this._def.innerType._parse(input);
3565
- }
3566
- unwrap() {
3567
- return this._def.innerType;
3568
- }
3569
- };
3570
- ZodNullable.create = (type, params) => {
3571
- return new ZodNullable({
3572
- innerType: type,
3573
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3574
- ...processCreateParams(params)
3575
- });
3576
- };
3577
- var ZodDefault = class extends ZodType {
3578
- _parse(input) {
3579
- const { ctx } = this._processInputParams(input);
3580
- let data = ctx.data;
3581
- if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
3582
- return this._def.innerType._parse({
3583
- data,
3584
- path: ctx.path,
3585
- parent: ctx
3586
- });
3587
- }
3588
- removeDefault() {
3589
- return this._def.innerType;
3590
- }
3591
- };
3592
- ZodDefault.create = (type, params) => {
3593
- return new ZodDefault({
3594
- innerType: type,
3595
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3596
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3597
- ...processCreateParams(params)
3598
- });
3599
- };
3600
- var ZodCatch = class extends ZodType {
3601
- _parse(input) {
3602
- const { ctx } = this._processInputParams(input);
3603
- const newCtx = {
3604
- ...ctx,
3605
- common: {
3606
- ...ctx.common,
3607
- issues: []
3608
- }
3609
- };
3610
- const result = this._def.innerType._parse({
3611
- data: newCtx.data,
3612
- path: newCtx.path,
3613
- parent: { ...newCtx }
3614
- });
3615
- if (isAsync(result)) return result.then((result$1) => {
3616
- return {
3617
- status: "valid",
3618
- value: result$1.status === "valid" ? result$1.value : this._def.catchValue({
3619
- get error() {
3620
- return new ZodError(newCtx.common.issues);
3621
- },
3622
- input: newCtx.data
3623
- })
3624
- };
3625
- });
3626
- else return {
3627
- status: "valid",
3628
- value: result.status === "valid" ? result.value : this._def.catchValue({
3629
- get error() {
3630
- return new ZodError(newCtx.common.issues);
3631
- },
3632
- input: newCtx.data
3633
- })
3634
- };
3635
- }
3636
- removeCatch() {
3637
- return this._def.innerType;
3638
- }
3639
- };
3640
- ZodCatch.create = (type, params) => {
3641
- return new ZodCatch({
3642
- innerType: type,
3643
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3644
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3645
- ...processCreateParams(params)
3646
- });
3647
- };
3648
- var ZodNaN = class extends ZodType {
3649
- _parse(input) {
3650
- const parsedType = this._getType(input);
3651
- if (parsedType !== ZodParsedType.nan) {
3652
- const ctx = this._getOrReturnCtx(input);
3653
- addIssueToContext(ctx, {
3654
- code: ZodIssueCode.invalid_type,
3655
- expected: ZodParsedType.nan,
3656
- received: ctx.parsedType
3657
- });
3658
- return INVALID;
3659
- }
3660
- return {
3661
- status: "valid",
3662
- value: input.data
3663
- };
3664
- }
3665
- };
3666
- ZodNaN.create = (params) => {
3667
- return new ZodNaN({
3668
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3669
- ...processCreateParams(params)
3670
- });
3671
- };
3672
- const BRAND = Symbol("zod_brand");
3673
- var ZodBranded = class extends ZodType {
3674
- _parse(input) {
3675
- const { ctx } = this._processInputParams(input);
3676
- const data = ctx.data;
3677
- return this._def.type._parse({
3678
- data,
3679
- path: ctx.path,
3680
- parent: ctx
3681
- });
3682
- }
3683
- unwrap() {
3684
- return this._def.type;
3685
- }
3686
- };
3687
- var ZodPipeline = class ZodPipeline extends ZodType {
3688
- _parse(input) {
3689
- const { status, ctx } = this._processInputParams(input);
3690
- if (ctx.common.async) {
3691
- const handleAsync = async () => {
3692
- const inResult = await this._def.in._parseAsync({
3693
- data: ctx.data,
3694
- path: ctx.path,
3695
- parent: ctx
3696
- });
3697
- if (inResult.status === "aborted") return INVALID;
3698
- if (inResult.status === "dirty") {
3699
- status.dirty();
3700
- return DIRTY(inResult.value);
3701
- } else return this._def.out._parseAsync({
3702
- data: inResult.value,
3703
- path: ctx.path,
3704
- parent: ctx
3705
- });
3706
- };
3707
- return handleAsync();
3708
- } else {
3709
- const inResult = this._def.in._parseSync({
3710
- data: ctx.data,
3711
- path: ctx.path,
3712
- parent: ctx
3713
- });
3714
- if (inResult.status === "aborted") return INVALID;
3715
- if (inResult.status === "dirty") {
3716
- status.dirty();
3717
- return {
3718
- status: "dirty",
3719
- value: inResult.value
3720
- };
3721
- } else return this._def.out._parseSync({
3722
- data: inResult.value,
3723
- path: ctx.path,
3724
- parent: ctx
3725
- });
3726
- }
3727
- }
3728
- static create(a, b) {
3729
- return new ZodPipeline({
3730
- in: a,
3731
- out: b,
3732
- typeName: ZodFirstPartyTypeKind.ZodPipeline
3733
- });
3734
- }
3735
- };
3736
- var ZodReadonly = class extends ZodType {
3737
- _parse(input) {
3738
- const result = this._def.innerType._parse(input);
3739
- const freeze = (data) => {
3740
- if (isValid(data)) data.value = Object.freeze(data.value);
3741
- return data;
3742
- };
3743
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3744
- }
3745
- unwrap() {
3746
- return this._def.innerType;
3747
- }
3748
- };
3749
- ZodReadonly.create = (type, params) => {
3750
- return new ZodReadonly({
3751
- innerType: type,
3752
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3753
- ...processCreateParams(params)
3754
- });
3755
- };
3756
- const late = { object: ZodObject.lazycreate };
3757
- var ZodFirstPartyTypeKind;
3758
- (function(ZodFirstPartyTypeKind$1) {
3759
- ZodFirstPartyTypeKind$1["ZodString"] = "ZodString";
3760
- ZodFirstPartyTypeKind$1["ZodNumber"] = "ZodNumber";
3761
- ZodFirstPartyTypeKind$1["ZodNaN"] = "ZodNaN";
3762
- ZodFirstPartyTypeKind$1["ZodBigInt"] = "ZodBigInt";
3763
- ZodFirstPartyTypeKind$1["ZodBoolean"] = "ZodBoolean";
3764
- ZodFirstPartyTypeKind$1["ZodDate"] = "ZodDate";
3765
- ZodFirstPartyTypeKind$1["ZodSymbol"] = "ZodSymbol";
3766
- ZodFirstPartyTypeKind$1["ZodUndefined"] = "ZodUndefined";
3767
- ZodFirstPartyTypeKind$1["ZodNull"] = "ZodNull";
3768
- ZodFirstPartyTypeKind$1["ZodAny"] = "ZodAny";
3769
- ZodFirstPartyTypeKind$1["ZodUnknown"] = "ZodUnknown";
3770
- ZodFirstPartyTypeKind$1["ZodNever"] = "ZodNever";
3771
- ZodFirstPartyTypeKind$1["ZodVoid"] = "ZodVoid";
3772
- ZodFirstPartyTypeKind$1["ZodArray"] = "ZodArray";
3773
- ZodFirstPartyTypeKind$1["ZodObject"] = "ZodObject";
3774
- ZodFirstPartyTypeKind$1["ZodUnion"] = "ZodUnion";
3775
- ZodFirstPartyTypeKind$1["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3776
- ZodFirstPartyTypeKind$1["ZodIntersection"] = "ZodIntersection";
3777
- ZodFirstPartyTypeKind$1["ZodTuple"] = "ZodTuple";
3778
- ZodFirstPartyTypeKind$1["ZodRecord"] = "ZodRecord";
3779
- ZodFirstPartyTypeKind$1["ZodMap"] = "ZodMap";
3780
- ZodFirstPartyTypeKind$1["ZodSet"] = "ZodSet";
3781
- ZodFirstPartyTypeKind$1["ZodFunction"] = "ZodFunction";
3782
- ZodFirstPartyTypeKind$1["ZodLazy"] = "ZodLazy";
3783
- ZodFirstPartyTypeKind$1["ZodLiteral"] = "ZodLiteral";
3784
- ZodFirstPartyTypeKind$1["ZodEnum"] = "ZodEnum";
3785
- ZodFirstPartyTypeKind$1["ZodEffects"] = "ZodEffects";
3786
- ZodFirstPartyTypeKind$1["ZodNativeEnum"] = "ZodNativeEnum";
3787
- ZodFirstPartyTypeKind$1["ZodOptional"] = "ZodOptional";
3788
- ZodFirstPartyTypeKind$1["ZodNullable"] = "ZodNullable";
3789
- ZodFirstPartyTypeKind$1["ZodDefault"] = "ZodDefault";
3790
- ZodFirstPartyTypeKind$1["ZodCatch"] = "ZodCatch";
3791
- ZodFirstPartyTypeKind$1["ZodPromise"] = "ZodPromise";
3792
- ZodFirstPartyTypeKind$1["ZodBranded"] = "ZodBranded";
3793
- ZodFirstPartyTypeKind$1["ZodPipeline"] = "ZodPipeline";
3794
- ZodFirstPartyTypeKind$1["ZodReadonly"] = "ZodReadonly";
3795
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3796
- const stringType = ZodString.create;
3797
- const numberType = ZodNumber.create;
3798
- const nanType = ZodNaN.create;
3799
- const bigIntType = ZodBigInt.create;
3800
- const booleanType = ZodBoolean.create;
3801
- const dateType = ZodDate.create;
3802
- const symbolType = ZodSymbol.create;
3803
- const undefinedType = ZodUndefined.create;
3804
- const nullType = ZodNull.create;
3805
- const anyType = ZodAny.create;
3806
- const unknownType = ZodUnknown.create;
3807
- const neverType = ZodNever.create;
3808
- const voidType = ZodVoid.create;
3809
- const arrayType = ZodArray.create;
3810
- const objectType = ZodObject.create;
3811
- const strictObjectType = ZodObject.strictCreate;
3812
- const unionType = ZodUnion.create;
3813
- const discriminatedUnionType = ZodDiscriminatedUnion.create;
3814
- const intersectionType = ZodIntersection.create;
3815
- const tupleType = ZodTuple.create;
3816
- const recordType = ZodRecord.create;
3817
- const mapType = ZodMap.create;
3818
- const setType = ZodSet.create;
3819
- const functionType = ZodFunction.create;
3820
- const lazyType = ZodLazy.create;
3821
- const literalType = ZodLiteral.create;
3822
- const enumType = ZodEnum.create;
3823
- const nativeEnumType = ZodNativeEnum.create;
3824
- const promiseType = ZodPromise.create;
3825
- const effectsType = ZodEffects.create;
3826
- const optionalType = ZodOptional.create;
3827
- const nullableType = ZodNullable.create;
3828
- const preprocessType = ZodEffects.createWithPreprocess;
3829
- const pipelineType = ZodPipeline.create;
3830
-
3831
- //#endregion
3832
- //#region src/cursor/schemas.ts
3833
- const MINIFIED_CURSOR_SCHEMA = objectType({
3834
- r: recordType(stringType(), objectType({
3835
- n: numberType().optional().nullable(),
3836
- c: stringType().optional().nullable(),
3837
- p: numberType().optional().nullable()
3838
- })),
3839
- v: numberType(),
3840
- t: numberType()
3841
- });
3842
- const CURSOR_SCHEMA = objectType({
3843
- remote: recordType(stringType(), objectType({
3844
- pageNumber: numberType().optional(),
3845
- providerPageCursor: stringType().optional(),
3846
- position: numberType().optional()
3847
- })),
3848
- version: numberType(),
3849
- timestamp: numberType()
3850
- });
3851
-
3852
- //#endregion
3853
- //#region src/cursor/index.ts
3854
- const minifyCursor = (cursor) => (0, __stackone_utils.encodeToBase64)(JSON.stringify(minifyCursorObject(cursor)));
3855
- const minifyCursorObject = (cursor) => {
3856
- const { remote, version, timestamp } = cursor;
3857
- const minifiedRemote = Object.fromEntries(Object.entries(remote).map(([stepIndex, { pageNumber, providerPageCursor, position }]) => [stepIndex, {
3858
- n: pageNumber,
3859
- c: providerPageCursor,
3860
- p: position
3861
- }]));
3862
- const minifiedCursor = {
3863
- r: minifiedRemote,
3864
- v: version,
3865
- t: timestamp
3866
- };
3867
- return minifiedCursor;
3868
- };
3869
- const expandCursor = (minifiedCursor) => {
3870
- try {
3871
- if ((0, __stackone_utils.isString)(minifiedCursor)) {
3872
- const decodedString = (0, __stackone_utils.decodeFromBase64)(minifiedCursor);
3873
- const minifiedCursorObject = JSON.parse(decodedString);
3874
- const parsedObject = MINIFIED_CURSOR_SCHEMA.parse(minifiedCursorObject);
3875
- return expandCursorObject(parsedObject);
3876
- } else {
3877
- CURSOR_SCHEMA.parse(minifiedCursor);
3878
- return minifiedCursor;
3879
- }
3880
- } catch {
3881
- return null;
3882
- }
3883
- };
3884
- const expandCursorObject = (minifiedCursor) => {
3885
- const { r: minifiedRemote, v: minifiedVersion, t: minifiedTimestamp } = minifiedCursor;
3886
- const remote = Object.fromEntries(Object.entries(minifiedRemote).map(([stepIndex, { n, c, p }]) => [stepIndex, {
3887
- pageNumber: n,
3888
- providerPageCursor: c,
3889
- position: p
3890
- }]));
3891
- const expandedCursor = {
3892
- remote,
3893
- version: minifiedVersion,
3894
- timestamp: minifiedTimestamp
3895
- };
3896
- return expandedCursor;
3897
- };
3898
- const areCursorsEqual = (first, second) => {
3899
- const firstCursor = typeof first === "string" ? expandCursor(first) : first;
3900
- const secondCursor = typeof second === "string" ? expandCursor(second) : second;
3901
- if (firstCursor === null || secondCursor === null) return firstCursor === secondCursor;
3902
- const { timestamp: _t1,...firstWithoutTimestamp } = firstCursor;
3903
- const { timestamp: _t2,...secondWithoutTimestamp } = secondCursor;
3904
- return (0, __stackone_utils.getContentHash)(firstWithoutTimestamp) === (0, __stackone_utils.getContentHash)(secondWithoutTimestamp);
3905
- };
3906
- const isCursorEmpty = ({ cursor, ignoreStepIndex }) => {
3907
- if ((0, __stackone_utils.isMissing)(cursor)) return true;
3908
- return Object.keys(cursor?.remote ?? {}).reduce((acc, key) => {
3909
- const value = cursor?.remote?.[key];
3910
- if ((0, __stackone_utils.isMissing)(ignoreStepIndex) || key !== ignoreStepIndex.toString()) acc = acc && (0, __stackone_utils.isMissing)(value.pageNumber) && (0, __stackone_utils.isMissing)(value.position) && (0, __stackone_utils.isMissing)(value.providerPageCursor);
3911
- return acc;
3912
- }, true);
3913
- };
3914
- const updateCursor = ({ cursor, stepIndex, pageNumber, providerPageCursor, position }) => {
3915
- const cursorPosition = {
3916
- pageNumber: pageNumber ?? void 0,
3917
- providerPageCursor: providerPageCursor ?? void 0,
3918
- position: position ?? void 0
3919
- };
3920
- const emptyValues = (0, __stackone_utils.isMissing)(pageNumber) && (0, __stackone_utils.isMissing)(providerPageCursor) && (0, __stackone_utils.isMissing)(position);
3921
- if ((0, __stackone_utils.isMissing)(cursor)) return {
3922
- remote: emptyValues ? {} : { [stepIndex]: cursorPosition },
3923
- version: 2,
3924
- timestamp: Date.now()
3925
- };
3926
- if (emptyValues) {
3927
- delete cursor.remote[stepIndex];
3928
- return cursor;
3929
- }
3930
- return {
3931
- ...cursor,
3932
- remote: {
3933
- ...cursor.remote,
3934
- [stepIndex]: cursorPosition
3935
- }
3936
- };
3937
- };
3938
-
3939
- //#endregion
3940
- //#region src/errors/typeguards.ts
3941
- const isCoreError = (error) => {
3942
- return error instanceof CoreError;
3943
- };
3944
-
3945
- //#endregion
3946
- //#region src/stepFunctions/groupData/schemas.ts
3947
- const GROUP_DATA_INPUT_PARAMS = objectType({
3948
- stepsDataToGroup: arrayType(stringType()),
3949
- isSingleRecord: booleanType().optional()
3950
- });
3951
- const GROUP_DATA_OUTPUT = objectType({ data: unknownType() });
3952
-
3953
- //#endregion
3954
- //#region src/stepFunctions/groupData/groupDataStepFunction.ts
3955
- const groupDataStepFunction = async ({ block, params }) => {
3956
- const { stepsDataToGroup, isSingleRecord } = GROUP_DATA_INPUT_PARAMS.parse(params);
3957
- const newData = stepsDataToGroup.reduce((acc, stepDataKey) => {
3958
- const stepData = block.steps?.[stepDataKey]?.output?.data;
3959
- if (!stepData) return acc;
3960
- if (isSingleRecord) return {
3961
- ...acc,
3962
- [stepDataKey]: { ...stepData }
3963
- };
3964
- else Object.keys(stepData).forEach((key) => {
3965
- const tmp = (0, __stackone_utils.notMissing)(acc[key]) ? acc[key] : {};
3966
- acc[key] = {
3967
- ...tmp,
3968
- [stepDataKey]: { ...stepData[key] }
3969
- };
3970
- });
3971
- return acc;
3972
- }, {});
3973
- return {
3974
- block: { ...block },
3975
- successful: true,
3976
- output: { data: isSingleRecord ? newData : Object.values(newData) }
3977
- };
3978
- };
3979
-
3980
- //#endregion
3981
- //#region src/stepFunctions/mapFields/mapFieldsStepFunction.ts
3982
- const mapFieldsStepFunction = async ({ block }) => {
3983
- const blockConfigs = block?.fieldConfigs;
3984
- const customMappingErrors = [];
3985
- const stepsData = block.steps;
3986
- if (!blockConfigs || block?.debug?.custom_mappings === "disabled" || !stepsData) return {
3987
- block,
3988
- successful: true
3989
- };
3990
- let mappedResult;
3991
- if (Array.isArray(block.result)) {
3992
- const totalRecords = block.result.length;
3993
- mappedResult = block.result.map((record, index) => {
3994
- const singleRecordData = extractSingleRecordBlockStepData(stepsData, totalRecords, index);
3995
- const mapResult = mapSingleRecord$3(record, blockConfigs, singleRecordData);
3996
- customMappingErrors.push(...mapResult.errors || []);
3997
- return mapResult.record;
3998
- });
3999
- } else {
4000
- const mapResult = mapSingleRecord$3(block.result, blockConfigs, stepsData);
4001
- mappedResult = mapResult.record;
4002
- customMappingErrors.push(...mapResult.errors || []);
4003
- }
4004
- return {
4005
- block: {
4006
- ...block,
4007
- result: mappedResult
4008
- },
4009
- successful: true,
4010
- errors: Object.keys(customMappingErrors).length > 0 ? customMappingErrors : void 0
4011
- };
4012
- };
4013
- const extractSingleRecordBlockStepData = (stepsData, totalRecords, recordIdx) => {
4014
- return Object.entries(stepsData).reduce((acc, [key, value]) => {
4015
- const sourceArray = value?.output?.data;
4016
- if (Array.isArray(sourceArray) && sourceArray.length === totalRecords) acc[key] = { output: { data: sourceArray[recordIdx] } };
4017
- else acc[key] = value;
4018
- return acc;
4019
- }, {});
4020
- };
4021
- const mapSingleRecord$3 = (record, blockConfigs, sourceRecord) => {
4022
- if (!record || !sourceRecord) return { record };
4023
- const completeSourceRecord = {
4024
- unified: { ...record },
4025
- ...typeof sourceRecord === "object" ? sourceRecord : {}
4026
- };
4027
- const customFields = {};
4028
- const errors = [];
4029
- const newRecord = { ...record };
4030
- for (const config of blockConfigs) {
4031
- const { error, value } = extractFieldValue$1(completeSourceRecord, record.id, config);
4032
- if (error) {
4033
- errors.push(error);
4034
- continue;
4035
- }
4036
- if (config.custom) customFields[config.targetFieldKey] = value;
4037
- else newRecord[config.targetFieldKey] = value;
4038
- }
4039
- return {
4040
- record: {
4041
- ...newRecord,
4042
- unified_custom_fields: Object.keys(customFields).length > 0 ? customFields : void 0
4043
- },
4044
- errors: errors.length > 0 ? errors : void 0
4045
- };
4046
- };
4047
- const extractFieldValue$1 = (sourceRecord, recordId, config) => {
4048
- const { expression, targetFieldKey } = config;
4049
- if (!expression) return { error: {
4050
- message: "Expression is empty",
4051
- id: recordId,
4052
- targetField: targetFieldKey
4053
- } };
4054
- let value;
4055
- try {
4056
- value = (0, __stackone_expressions.evaluate)(expression, sourceRecord);
4057
- } catch {
4058
- return { error: {
4059
- message: "Invalid expression",
4060
- id: recordId,
4061
- targetField: targetFieldKey
4062
- } };
4063
- }
4064
- if (value === void 0) return { error: {
4065
- message: "Expression returned no value",
4066
- id: recordId,
4067
- targetField: targetFieldKey
4068
- } };
4069
- else return { value };
4070
- };
4071
-
4072
- //#endregion
4073
- //#region src/stepFunctions/mapFields/getEnumMatcher.ts
4074
- const getEnumMatcher = (matcher) => {
4075
- switch (matcher) {
4076
- case "country_alpha2code_by_alpha2code": return __stackone_utils.getCountryAlpha2CodeByAlpha2Code;
4077
- case "country_alpha3code_by_alpha3code": return __stackone_utils.getCountryAlpha3CodeByAlpha3Code;
4078
- case "country_code_by_country_code": return __stackone_utils.getCountryCodeByCountryCode;
4079
- case "country_name_by_country_name": return __stackone_utils.getCountryNameByCountryName;
4080
- case "country_name_by_alpha3code": return __stackone_utils.getCountryNameByAlpha3Code;
4081
- case "country_name_by_alpha2code": return __stackone_utils.getCountryNameByAlpha2Code;
4082
- case "country_name_by_country_code": return __stackone_utils.getCountryNameByCountryCode;
4083
- case "country_alpha3code_by_alpha2code": return __stackone_utils.getCountryAlpha3CodeByAlpha2Code;
4084
- case "country_alpha3code_by_country_name": return __stackone_utils.getCountryAlpha3CodeByCountryName;
4085
- case "country_alpha3code_by_country_code": return __stackone_utils.getCountryAlpha3CodeByCountryCode;
4086
- case "country_alpha2code_by_alpha3code": return __stackone_utils.getCountryAlpha2CodeByAlpha3Code;
4087
- case "country_alpha2code_by_country_name": return __stackone_utils.getCountryAlpha2CodeByCountryName;
4088
- case "country_alpha2code_by_country_code": return __stackone_utils.getCountryAlpha2CodeByCountryCode;
4089
- case "country_code_by_alpha2code": return __stackone_utils.getCountryCodeByAlpha2Code;
4090
- case "country_code_by_alpha3code": return __stackone_utils.getCountryCodeByAlpha3Code;
4091
- case "country_code_by_country_name": return __stackone_utils.getCountryCodeByCountryName;
4092
- case "country_subdivisions_by_alpha2code": return __stackone_utils.getCountrySubDivisionsByAlpha2Code;
4093
- case "country_subdivision_code_by_subdivision_name": return __stackone_utils.getCountrySubDivisionCodeBySubDivisionName;
4094
- case "country_alpha2code_by_citizenship": return __stackone_utils.getCountryAlpha2CodeByCitizenship;
4095
- case "country_subdivision_name_by_subdivision_code": return __stackone_utils.getCountrySubDivisionNameBySubDivisionCode;
4096
- default: return void 0;
4097
- }
4098
- };
4099
-
4100
- //#endregion
4101
- //#region src/stepFunctions/mapFields/schemas.ts
4102
- const MAP_FIELDS_INPUT_PARAMS = objectType({
4103
- fields: objectType({
4104
- targetFieldKey: stringType(),
4105
- alias: stringType().optional(),
4106
- expression: stringType(),
4107
- type: enumType([
4108
- "string",
4109
- "number",
4110
- "boolean",
4111
- "datetime_string",
4112
- "enum"
4113
- ]),
4114
- custom: booleanType().default(false),
4115
- hidden: booleanType().default(false),
4116
- enumMapper: objectType({ matcher: stringType().or(objectType({
4117
- matchExpression: stringType(),
4118
- value: stringType()
4119
- }).array()) }).optional()
4120
- }).array(),
4121
- dataSource: stringType()
4122
- });
4123
- const MAP_FIELDS_OUTPUT = objectType({ data: unknownType() });
4124
-
4125
- //#endregion
4126
- //#region src/stepFunctions/mapFields/mapFieldsStepFunction.v2.ts
4127
- const mapFieldsStepFunction$1 = async ({ block, params }) => {
4128
- const customMappingErrors = [];
4129
- const { fields: fieldConfigs, dataSource } = MAP_FIELDS_INPUT_PARAMS.parse(params);
4130
- const sourceData = (0, __stackone_expressions.evaluate)(dataSource, block);
4131
- if (!fieldConfigs || !dataSource || block?.debug?.custom_mappings === "disabled" || !sourceData) return {
4132
- block,
4133
- successful: true
4134
- };
4135
- let mappedResult;
4136
- if (Array.isArray(sourceData)) mappedResult = sourceData.map((record) => {
4137
- const mapResult = mapSingleRecord$2(fieldConfigs, record);
4138
- customMappingErrors.push(...mapResult?.errors || []);
4139
- return mapResult?.record;
4140
- });
4141
- else {
4142
- const mapResult = mapSingleRecord$2(fieldConfigs, sourceData);
4143
- mappedResult = mapResult?.record;
4144
- customMappingErrors.push(...mapResult?.errors || []);
4145
- }
4146
- return {
4147
- block: { ...block },
4148
- successful: true,
4149
- output: { data: mappedResult },
4150
- errors: Object.keys(customMappingErrors).length > 0 ? customMappingErrors : void 0
4151
- };
4152
- };
4153
- const mapSingleRecord$2 = (blockConfigs, sourceRecord) => {
4154
- if (!sourceRecord) return void 0;
4155
- const customFields = {};
4156
- const errors = [];
4157
- const newRecord = {};
4158
- for (const config of blockConfigs) {
4159
- const { error, value } = extractFieldValue(sourceRecord, sourceRecord?.["id"], config);
4160
- if (error) {
4161
- errors.push(error);
4162
- continue;
4163
- }
4164
- if (config.custom) customFields[config.targetFieldKey] = value;
4165
- else newRecord[config.targetFieldKey] = value;
4166
- }
4167
- return {
4168
- record: {
4169
- ...newRecord,
4170
- unified_custom_fields: Object.keys(customFields).length > 0 ? customFields : void 0
4171
- },
4172
- errors: errors.length > 0 ? errors : void 0
4173
- };
4174
- };
4175
- const extractFieldValue = (sourceRecord, recordId, config) => {
4176
- switch (config.type) {
4177
- case "string":
4178
- case "number":
4179
- case "boolean":
4180
- case "datetime_string": return evaluateValue(config, recordId, sourceRecord);
4181
- case "enum": return evaluateEnumValue(config, recordId, sourceRecord);
4182
- default: return { error: {
4183
- message: "Invalid type",
4184
- id: recordId,
4185
- targetField: config.targetFieldKey
4186
- } };
4187
- }
4188
- };
4189
- const evaluateValue = (config, recordId, sourceRecord) => {
4190
- if (!config.expression) return { error: {
4191
- message: "Expression is empty",
4192
- id: recordId,
4193
- targetField: config.targetFieldKey
4194
- } };
4195
- let value;
4196
- try {
4197
- value = (0, __stackone_expressions.evaluate)(config.expression, sourceRecord);
4198
- } catch {
4199
- return { error: {
4200
- message: "Invalid expression",
4201
- id: recordId,
4202
- targetField: config.targetFieldKey
4203
- } };
4204
- }
4205
- if (value === void 0) return { error: {
4206
- message: "Expression returned no value",
4207
- id: recordId,
4208
- targetField: config.targetFieldKey
4209
- } };
4210
- return { value };
4211
- };
4212
- const evaluateEnumValue = (config, recordId, sourceRecord) => {
4213
- const evaluatedSourceValue = evaluateValue(config, recordId, sourceRecord);
4214
- const sourceValue = (0, __stackone_utils.notMissing)(evaluatedSourceValue.value) ? evaluatedSourceValue.value : null;
4215
- if (config.enumMapper === void 0) return { error: {
4216
- message: "Enum mapper was not defined",
4217
- id: recordId,
4218
- targetField: config.targetFieldKey
4219
- } };
4220
- const configMatcher = config.enumMapper.matcher;
4221
- if ((0, __stackone_utils.isString)(configMatcher)) {
4222
- const enumMatcher = getEnumMatcher(configMatcher);
4223
- if ((0, __stackone_utils.notMissing)(enumMatcher)) {
4224
- const matchedValue = (0, __stackone_utils.notMissing)(sourceValue) ? enumMatcher(sourceValue) : null;
4225
- return { value: {
4226
- value: matchedValue ?? "unmapped_value",
4227
- source_value: sourceValue
4228
- } };
4229
- } else return { error: {
4230
- message: `The built-in matcher "${configMatcher}" is not supported`,
4231
- id: recordId,
4232
- targetField: config.targetFieldKey
4233
- } };
4234
- }
4235
- for (const match of configMatcher) {
4236
- const { matchExpression, value } = match;
4237
- const matchedExpression = (0, __stackone_expressions.evaluate)(matchExpression, sourceRecord);
4238
- if (matchedExpression === true) return { value: {
4239
- value,
4240
- source_value: sourceValue
4241
- } };
4242
- }
4243
- return { value: {
4244
- value: "unmapped_value",
4245
- source_value: sourceValue
4246
- } };
4247
- };
4248
-
4249
- //#endregion
4250
- //#region src/stepFunctions/paginatedRequest/schemas.ts
4251
- const BASIC_AUTHENTICATION$1 = objectType({
4252
- type: literalType("basic"),
4253
- username: stringType().optional(),
4254
- password: stringType().optional(),
4255
- encoding: stringType().optional()
4256
- });
4257
- const BEARER_AUTHENTICATION$1 = objectType({
4258
- type: literalType("bearer"),
4259
- token: stringType()
4260
- });
4261
- const AUTHENTICATION_SCHEMA$1 = discriminatedUnionType("type", [BASIC_AUTHENTICATION$1, BEARER_AUTHENTICATION$1]);
4262
- const PAGINATED_REQUEST_INPUT_PARAMS = objectType({
4263
- baseUrl: stringType(),
4264
- url: stringType(),
4265
- method: enumType(__stackone_transport.HttpMethods),
4266
- response: objectType({
4267
- indexField: stringType().optional(),
4268
- dataKey: stringType().optional(),
4269
- nextKey: stringType().optional()
4270
- }).optional(),
4271
- iterator: objectType({
4272
- key: stringType(),
4273
- in: enumType(__stackone_transport.RequestParameterLocations)
4274
- }),
4275
- cursor: objectType({
4276
- token: stringType().optional().nullable(),
4277
- position: numberType().optional().nullable()
4278
- }).optional(),
4279
- customErrors: __stackone_transport.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),
4280
- args: objectType({
4281
- name: stringType(),
4282
- value: unknownType(),
4283
- in: enumType(__stackone_transport.RequestParameterLocations),
4284
- condition: stringType().optional()
4285
- }).array().optional()
4286
- });
4287
- const PAGINATED_REQUEST_OUTPUT = objectType({
4288
- data: unknownType().optional(),
4289
- raw: unknownType().optional(),
4290
- statusCode: numberType(),
4291
- message: stringType().optional(),
4292
- next: stringType().optional().nullable(),
4293
- position: numberType().optional()
4294
- }).optional();
4295
-
4296
- //#endregion
4297
- //#region src/stepFunctions/paginatedRequest/paginatedRequestStepFunction.ts
4298
- const DEFAULT_PAGE_SIZE = 25;
4299
- const getPageSize = (block) => {
4300
- const inputPageSize = Number(block.inputs?.["page_size"]);
4301
- return Number.isNaN(inputPageSize) ? DEFAULT_PAGE_SIZE : inputPageSize;
4302
- };
4303
- const filterAndEvaluateArgs = (params, block) => {
4304
- const { args: argsToFilter } = params;
4305
- const filteredArgs = argsToFilter ? argsToFilter.filter((arg) => !arg.condition || (0, __stackone_expressions.evaluate)(arg.condition, block) === true).map((arg) => ({
4306
- ...arg,
4307
- condition: void 0
4308
- })) : void 0;
4309
- const evaluatedParams = params ? (0, __stackone_expressions.safeEvaluateRecord)({
4310
- ...params,
4311
- args: filteredArgs
4312
- }, block) : {};
4313
- return {
4314
- ...evaluatedParams,
4315
- customErrors: params?.customErrors
4316
- };
4317
- };
4318
- const prepareRequestConfig = (finalParams, block) => {
4319
- const requestConfig = PAGINATED_REQUEST_INPUT_PARAMS.parse(finalParams);
4320
- const authenticationData = finalParams?.authentication?.[block.context.authenticationType]?.[block.context.environment]?.authorization;
4321
- const parsedAuthentication = AUTHENTICATION_SCHEMA$1.parse(authenticationData);
4322
- const parsedArgs = requestConfig.args ? (0, __stackone_transport.parseRequestParameters)(requestConfig.args) : {
4323
- query: {},
4324
- body: {},
4325
- headers: {}
4326
- };
4327
- const authorizationHeaders = (0, __stackone_transport.createAuthorizationHeaders)(parsedAuthentication);
4328
- const requestHeaders = {
4329
- ...parsedArgs?.headers ?? {},
4330
- ...authorizationHeaders
4331
- };
4332
- const pageSize = getPageSize(block);
4333
- return {
4334
- requestConfig,
4335
- preparedRequest: {
4336
- parsedArgs,
4337
- requestHeaders,
4338
- pageSize
4339
- }
4340
- };
4341
- };
4342
- const initializePaginationState = (cursor, pageSize) => {
4343
- return {
4344
- nextIterator: cursor?.token ?? null,
4345
- lastUsedIterator: null,
4346
- lastStatusCode: null,
4347
- data: [],
4348
- raw: [],
4349
- recordsLeft: pageSize,
4350
- pagePosition: cursor?.position ?? 0,
4351
- firstPage: true,
4352
- noMoreData: true
4353
- };
4354
- };
4355
- const updateIteratorInArgs = (parsedArgs, iterator, nextIterator) => {
4356
- if (nextIterator !== null) {
4357
- if (iterator.in === "query") parsedArgs.query[iterator.key] = nextIterator.toString();
4358
- else if (iterator.in === "body") parsedArgs.body[iterator.key] = nextIterator;
4359
- }
4360
- };
4361
- const performSingleRequest = async (client, block, requestConfig, preparedRequest) => {
4362
- if (!block.httpClient) throw new Error("HTTP client is not configured");
4363
- try {
4364
- return await client.performRequest({
4365
- httpClient: block.httpClient,
4366
- url: `${requestConfig.baseUrl}${requestConfig.url}`,
4367
- queryParams: preparedRequest.parsedArgs?.query,
4368
- method: requestConfig.method,
4369
- headers: preparedRequest.requestHeaders,
4370
- body: preparedRequest.parsedArgs?.body,
4371
- customErrorConfigs: requestConfig.customErrors
4372
- });
4373
- } catch (error) {
4374
- const httpError = error;
4375
- return {
4376
- block,
4377
- successful: false,
4378
- errors: [error],
4379
- output: {
4380
- statusCode: httpError?.response?.status ?? 500,
4381
- message: httpError?.response?.message
4382
- }
4383
- };
4384
- }
4385
- };
4386
- const processPageData = (result, response, state) => {
4387
- const resultData = response?.dataKey ? result.data[response?.dataKey] : result.data;
4388
- const slicedData = resultData?.slice(state.pagePosition, state.recordsLeft) ?? [];
4389
- state.recordsLeft = state.recordsLeft - slicedData.length;
4390
- state.pagePosition = state.pagePosition + slicedData.length;
4391
- state.raw.push(result);
4392
- state.data = state.data.concat(slicedData);
4393
- state.lastStatusCode = result?.status;
4394
- return {
4395
- resultData,
4396
- slicedData
4397
- };
4398
- };
4399
- const updatePaginationState = (result, response, state, slicedData, resultData, pageSize) => {
4400
- const nextIteratorValue = response?.nextKey ? result.data[response?.nextKey] : void 0;
4401
- state.nextIterator = typeof nextIteratorValue === "string" || typeof nextIteratorValue === "number" ? nextIteratorValue : null;
4402
- if (slicedData.length === resultData.length && state.recordsLeft === 0) {
4403
- state.pagePosition = 0;
4404
- state.lastUsedIterator = state.nextIterator;
4405
- }
4406
- state.noMoreData = (0, __stackone_utils.isMissing)(state.nextIterator) && state.data.length < pageSize;
4407
- };
4408
- const shouldContinuePagination = (state, pageSize, resultData) => {
4409
- return (0, __stackone_utils.notMissing)(state.nextIterator) && state.data.length < pageSize && resultData?.length > 0;
4410
- };
4411
- const buildSuccessResponse = (block, state, response) => {
4412
- const responseData = indexResponseData$1(state.data, response);
4413
- return {
4414
- block,
4415
- successful: true,
4416
- output: {
4417
- data: responseData,
4418
- raw: state.raw,
4419
- statusCode: state.lastStatusCode,
4420
- next: state.noMoreData ? void 0 : state.lastUsedIterator,
4421
- position: state.noMoreData ? void 0 : state.pagePosition
4422
- }
4423
- };
4424
- };
4425
- const paginatedRequestStepFunction = async ({ block, params }) => {
4426
- const client = __stackone_transport.RequestClientFactory.build();
4427
- if (!block.httpClient) throw new Error("HTTP client is not configured");
4428
- const finalParams = filterAndEvaluateArgs(params ?? {}, block);
4429
- const { requestConfig, preparedRequest } = prepareRequestConfig(finalParams, block);
4430
- const state = initializePaginationState(requestConfig.cursor, preparedRequest.pageSize);
4431
- do {
4432
- if (!state.firstPage) state.pagePosition = 0;
4433
- else state.firstPage = false;
4434
- updateIteratorInArgs(preparedRequest.parsedArgs, requestConfig.iterator, state.nextIterator);
4435
- const requestResult = await performSingleRequest(client, block, requestConfig, preparedRequest);
4436
- if ("successful" in requestResult && requestResult.successful === false) return requestResult;
4437
- const result = requestResult;
4438
- state.lastUsedIterator = state.nextIterator;
4439
- const { resultData, slicedData } = processPageData(result, requestConfig.response, state);
4440
- updatePaginationState(result, requestConfig.response, state, slicedData, resultData, preparedRequest.pageSize);
4441
- } while (shouldContinuePagination(state, preparedRequest.pageSize, state.data));
4442
- return buildSuccessResponse(block, state, requestConfig.response);
4443
- };
4444
- const indexResponseData$1 = (data, response) => {
4445
- if (response?.indexField && Array.isArray(data)) return data.reduce((acc, item) => {
4446
- const indexField = response.indexField;
4447
- if (indexField && item[indexField]) acc[item[indexField]] = item;
4448
- return acc;
4449
- }, {});
4450
- if (response?.indexField) {
4451
- const indexField = response.indexField;
4452
- return indexField && data[indexField] ? { [data[indexField]]: data } : data;
4453
- }
4454
- return data;
4455
- };
4456
-
4457
- //#endregion
4458
- //#region src/stepFunctions/request/schemas.ts
4459
- const BASIC_AUTHENTICATION = objectType({
4460
- type: literalType("basic"),
4461
- username: stringType().optional(),
4462
- password: stringType().optional(),
4463
- encoding: stringType().optional()
4464
- });
4465
- const BEARER_AUTHENTICATION = objectType({
4466
- type: literalType("bearer"),
4467
- token: stringType()
4468
- });
4469
- const AUTHENTICATION_SCHEMA = discriminatedUnionType("type", [BASIC_AUTHENTICATION, BEARER_AUTHENTICATION]);
4470
- const REQUEST_INPUT_PARAMS = objectType({
4471
- baseUrl: stringType(),
4472
- url: stringType(),
4473
- method: enumType(__stackone_transport.HttpMethods),
4474
- response: objectType({
4475
- collection: booleanType().optional(),
4476
- indexField: stringType().optional(),
4477
- dataKey: stringType().optional()
4478
- }).optional(),
4479
- customErrors: __stackone_transport.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),
4480
- args: objectType({
4481
- name: stringType(),
4482
- value: unknownType(),
4483
- in: enumType(__stackone_transport.RequestParameterLocations),
4484
- condition: stringType().optional()
4485
- }).array().optional()
4486
- });
4487
- const REQUEST_OUTPUT = objectType({
4488
- data: unknownType().optional(),
4489
- raw: unknownType().optional(),
4490
- statusCode: numberType(),
4491
- message: stringType().optional()
4492
- }).optional();
4493
-
4494
- //#endregion
4495
- //#region src/stepFunctions/request/requestStepFunction.ts
4496
- const requestStepFunction = async ({ block, params }) => {
4497
- const client = __stackone_transport.RequestClientFactory.build();
4498
- if (!block.httpClient) throw new Error("HTTP client is not configured");
4499
- const { args: argsToFilter } = params;
4500
- const filteredArgs = argsToFilter ? argsToFilter.filter((arg) => !arg.condition || (0, __stackone_expressions.evaluate)(arg.condition, block) === true).map((arg) => ({
4501
- ...arg,
4502
- condition: void 0
4503
- })) : void 0;
4504
- const evaluatedParams = params ? (0, __stackone_expressions.safeEvaluateRecord)({
4505
- ...params,
4506
- args: filteredArgs
4507
- }, block) : {};
4508
- const finalParams = {
4509
- ...evaluatedParams,
4510
- customErrors: params?.customErrors
4511
- };
4512
- const { baseUrl, url, method, response, customErrors, args } = REQUEST_INPUT_PARAMS.parse(finalParams);
4513
- const authenticationData = evaluatedParams?.authentication?.[block.context.authenticationType]?.[block.context.environment]?.authorization;
4514
- const parsedAuthentication = AUTHENTICATION_SCHEMA.parse(authenticationData);
4515
- const parsedArgs = args ? (0, __stackone_transport.parseRequestParameters)(args) : {
4516
- query: {},
4517
- body: {},
4518
- headers: {}
4519
- };
4520
- const authorizationHeaders = (0, __stackone_transport.createAuthorizationHeaders)(parsedAuthentication);
4521
- const requestHeaders = {
4522
- ...parsedArgs?.headers ?? {},
4523
- ...authorizationHeaders
4524
- };
4525
- let result;
4526
- try {
4527
- result = await client.performRequest({
4528
- httpClient: block.httpClient,
4529
- url: `${baseUrl}${url}`,
4530
- queryParams: parsedArgs?.query,
4531
- method,
4532
- headers: requestHeaders,
4533
- body: parsedArgs?.body,
4534
- customErrorConfigs: customErrors
4535
- });
4536
- } catch (error) {
4537
- const httpError = error;
4538
- return {
4539
- block,
4540
- successful: false,
4541
- errors: [error],
4542
- output: {
4543
- statusCode: httpError?.response?.status ?? 500,
4544
- message: httpError?.response?.message
4545
- }
4546
- };
4547
- }
4548
- const data = response?.dataKey ? result.data[response?.dataKey] : result.data;
4549
- const responseData = indexResponseData(data, response);
4550
- return {
4551
- block,
4552
- successful: true,
4553
- output: {
4554
- data: responseData,
4555
- raw: result,
4556
- statusCode: result?.status,
4557
- message: result?.message
4558
- }
4559
- };
4560
- };
4561
- const indexResponseData = (data, response) => {
4562
- if (response?.collection && response?.indexField && Array.isArray(data)) return data.reduce((acc, item) => {
4563
- const indexField = response.indexField;
4564
- if (indexField && item[indexField]) acc[item[indexField]] = item;
4565
- return acc;
4566
- }, {});
4567
- if (!response?.collection && response?.indexField) {
4568
- const indexField = response.indexField;
4569
- return indexField && data[indexField] ? { [data[indexField]]: data } : data;
4570
- }
4571
- return data;
4572
- };
4573
-
4574
- //#endregion
4575
- //#region src/stepFunctions/typecast/schemas.ts
4576
- const TYPECAST_INPUT_PARAMS = objectType({
4577
- fields: objectType({
4578
- targetFieldKey: stringType(),
4579
- alias: stringType().optional(),
4580
- type: stringType(),
4581
- custom: booleanType().default(false),
4582
- hidden: booleanType().default(false)
4583
- }).array().optional(),
4584
- dataSource: stringType()
4585
- });
4586
- const TYPECAST_OUTPUT = objectType({ data: unknownType() });
4587
-
4588
- //#endregion
4589
- //#region src/stepFunctions/typecast/types.ts
4590
- let FieldSupportedTypes = /* @__PURE__ */ function(FieldSupportedTypes$1) {
4591
- FieldSupportedTypes$1["String"] = "string";
4592
- FieldSupportedTypes$1["Number"] = "number";
4593
- FieldSupportedTypes$1["Boolean"] = "boolean";
4594
- FieldSupportedTypes$1["DateTimeString"] = "datetime_string";
4595
- return FieldSupportedTypes$1;
4596
- }({});
4597
-
4598
- //#endregion
4599
- //#region src/stepFunctions/typecast/typecast.ts
4600
- const typecast = ({ value, type, format }) => {
4601
- if ((0, __stackone_utils.isMissing)(value)) return null;
4602
- switch (type) {
4603
- case FieldSupportedTypes.String: return (0, __stackone_utils.safeParseToString)({ value });
4604
- case FieldSupportedTypes.Number: return (0, __stackone_utils.safeParseToNumber)({ value });
4605
- case FieldSupportedTypes.Boolean: return (0, __stackone_utils.safeParseToBoolean)({ value });
4606
- case FieldSupportedTypes.DateTimeString: return (0, __stackone_utils.safeParseToDateTimeString)({
4607
- value,
4608
- format
4609
- });
4610
- default: return value;
4611
- }
4612
- };
4613
- const isFieldSupportedType = (type) => {
4614
- const supportedTypes = Object.values(FieldSupportedTypes);
4615
- return supportedTypes.includes(type);
4616
- };
4617
-
4618
- //#endregion
4619
- //#region src/stepFunctions/typecast/typecastStepFunction.ts
4620
- const typecastStepFunction = async ({ block }) => {
4621
- const blockConfigs = block?.fieldConfigs;
4622
- if (!blockConfigs || block?.debug?.custom_mappings === "disabled") return {
4623
- block,
4624
- successful: true
4625
- };
4626
- let typecastedResult;
4627
- if (Array.isArray(block.result)) typecastedResult = block.result.map((record) => {
4628
- return mapSingleRecord$1(record, blockConfigs);
4629
- });
4630
- else typecastedResult = mapSingleRecord$1(block.result, blockConfigs);
4631
- return {
4632
- block: {
4633
- ...block,
4634
- result: typecastedResult
4635
- },
4636
- successful: true
4637
- };
4638
- };
4639
- const mapSingleRecord$1 = (record, blockConfigs) => {
4640
- const newRecord = { ...record };
4641
- blockConfigs.forEach((config) => {
4642
- const { targetFieldKey, type } = config;
4643
- if (isFieldSupportedType(type)) {
4644
- if (!config.custom && (0, __stackone_utils.notMissing)(newRecord[targetFieldKey])) newRecord[targetFieldKey] = typecast({
4645
- value: record[targetFieldKey],
4646
- type
4647
- });
4648
- else if (newRecord.unified_custom_fields && (0, __stackone_utils.notMissing)(newRecord.unified_custom_fields?.[targetFieldKey])) newRecord.unified_custom_fields[targetFieldKey] = typecast({
4649
- value: record.unified_custom_fields?.[targetFieldKey],
4650
- type
4651
- });
4652
- }
4653
- });
4654
- return { ...newRecord };
4655
- };
4656
-
4657
- //#endregion
4658
- //#region src/stepFunctions/typecast/typecastStepFunction.v2.ts
4659
- const typecastStepFunction$1 = async ({ block, params }) => {
4660
- const { fields: fieldConfigs, dataSource } = TYPECAST_INPUT_PARAMS.parse(params);
4661
- const sourceData = (0, __stackone_expressions.evaluate)(dataSource, block);
4662
- if (!fieldConfigs || block?.debug?.custom_mappings === "disabled") return {
4663
- block,
4664
- successful: true
4665
- };
4666
- let typecastedResult;
4667
- if (Array.isArray(sourceData)) typecastedResult = sourceData.map((record) => {
4668
- return mapSingleRecord(record, fieldConfigs);
4669
- });
4670
- else typecastedResult = mapSingleRecord(sourceData, fieldConfigs);
4671
- return {
4672
- block: { ...block },
4673
- successful: true,
4674
- output: { data: typecastedResult }
4675
- };
4676
- };
4677
- const mapSingleRecord = (record, fieldConfigs) => {
4678
- const newRecord = { ...record };
4679
- fieldConfigs.forEach((config) => {
4680
- const { targetFieldKey, type } = config;
4681
- if (isFieldSupportedType(type)) {
4682
- if (!config.custom && (0, __stackone_utils.notMissing)(newRecord[targetFieldKey])) newRecord[targetFieldKey] = typecast({
4683
- value: record[targetFieldKey],
4684
- type
4685
- });
4686
- else if (newRecord.unified_custom_fields && (0, __stackone_utils.notMissing)(newRecord.unified_custom_fields?.[targetFieldKey])) newRecord.unified_custom_fields[targetFieldKey] = typecast({
4687
- value: record.unified_custom_fields?.[targetFieldKey],
4688
- type
4689
- });
4690
- }
4691
- });
4692
- return { ...newRecord };
4693
- };
4694
-
4695
- //#endregion
4696
- //#region src/stepFunctions/stepFunctionsList.ts
4697
- let StepFunctionName = /* @__PURE__ */ function(StepFunctionName$1) {
4698
- StepFunctionName$1["TYPECAST"] = "typecast";
4699
- StepFunctionName$1["MAP_FIELDS"] = "map_fields";
4700
- StepFunctionName$1["GROUP_DATA"] = "group_data";
4701
- StepFunctionName$1["REQUEST"] = "request";
4702
- StepFunctionName$1["PAGINATED_REQUEST"] = "paginated_request";
4703
- return StepFunctionName$1;
4704
- }({});
4705
- const stepFunctions = {
4706
- [StepFunctionName.TYPECAST]: {
4707
- v1: { fn: typecastStepFunction },
4708
- v2: {
4709
- fn: typecastStepFunction$1,
4710
- inputSchema: TYPECAST_INPUT_PARAMS,
4711
- outputSchema: TYPECAST_OUTPUT
4712
- }
4713
- },
4714
- [StepFunctionName.MAP_FIELDS]: {
4715
- v1: { fn: mapFieldsStepFunction },
4716
- v2: {
4717
- fn: mapFieldsStepFunction$1,
4718
- inputSchema: MAP_FIELDS_INPUT_PARAMS,
4719
- outputSchema: MAP_FIELDS_OUTPUT
4720
- }
4721
- },
4722
- [StepFunctionName.REQUEST]: { v1: {
4723
- fn: requestStepFunction,
4724
- inputSchema: REQUEST_INPUT_PARAMS,
4725
- outputSchema: REQUEST_OUTPUT
4726
- } },
4727
- [StepFunctionName.GROUP_DATA]: { v1: {
4728
- fn: groupDataStepFunction,
4729
- inputSchema: GROUP_DATA_INPUT_PARAMS,
4730
- outputSchema: GROUP_DATA_OUTPUT
4731
- } },
4732
- [StepFunctionName.PAGINATED_REQUEST]: { v1: {
4733
- fn: paginatedRequestStepFunction,
4734
- inputSchema: PAGINATED_REQUEST_INPUT_PARAMS,
4735
- outputSchema: PAGINATED_REQUEST_OUTPUT
4736
- } }
4737
- };
4738
-
4739
- //#endregion
4740
- //#region src/stepFunctions/factory.ts
4741
- const stepFunctionEnhancedWithSchemasValidation = (functionInstance, functionName) => {
4742
- return async ({ block, params }) => {
4743
- try {
4744
- if (functionInstance.inputSchema) functionInstance.inputSchema.parse(params);
4745
- } catch {
4746
- return {
4747
- block,
4748
- successful: false,
4749
- errors: [{ message: `Input parameters for ${functionName} are invalid` }]
4750
- };
4751
- }
4752
- const result = await functionInstance.fn({
4753
- block,
4754
- params
4755
- });
4756
- try {
4757
- if (functionInstance.outputSchema) functionInstance.outputSchema.parse(result.output);
4758
- } catch {
4759
- return {
4760
- block,
4761
- successful: false,
4762
- errors: [{ message: `Output data of ${functionName} has unexpected format` }]
4763
- };
4764
- }
4765
- return result;
4766
- };
4767
- };
4768
- const StepFunctionsFactory = { build({ functionName, version = "1", validateSchemas = false, stepFunctionsList = stepFunctions }) {
4769
- const stepFunctionInstance = stepFunctionsList?.[functionName]?.[`v${version}`];
4770
- if (!stepFunctionInstance) throw new Error(`Unknown step function: ${functionName} v${version}`);
4771
- if (validateSchemas) return {
4772
- ...stepFunctionInstance,
4773
- fn: stepFunctionEnhancedWithSchemasValidation(stepFunctionInstance, functionName)
4774
- };
4775
- else return stepFunctionInstance;
4776
- } };
4777
-
4778
- //#endregion
4779
- exports.AUTHENTICATION_SCHEMA = AUTHENTICATION_SCHEMA;
4780
- exports.COMPOSITE_ID_LATEST_VERSION = COMPOSITE_ID_LATEST_VERSION;
4781
- exports.CoreError = CoreError;
4782
- exports.StepFunctionName = StepFunctionName;
4783
- exports.StepFunctionsFactory = StepFunctionsFactory;
4784
- exports.areCursorsEqual = areCursorsEqual;
4785
- exports.decodeCompositeId = decodeCompositeId;
4786
- exports.encodeCompositeId = encodeCompositeId;
4787
- exports.expandCursor = expandCursor;
4788
- exports.getCategoryDetails = getCategoryDetails;
4789
- exports.isCompositeId = isCompositeId;
4790
- exports.isCoreError = isCoreError;
4791
- exports.isCursorEmpty = isCursorEmpty;
4792
- exports.isValidCategory = isValidCategory;
4793
- exports.minifyCursor = minifyCursor;
4794
- exports.updateCursor = updateCursor;
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`@stackone/utils`)),l=s(require(`@stackone/expressions`)),u=s(require(`@stackone/transport`)),d={hris:{title:`HRIS`,key:`hris`,description:`Human Resource Information System`},crm:{title:`CRM`,key:`crm`,description:`Customer Relationship Management`},ats:{title:`ATS`,key:`ats`,description:`Applicant Tracking System`},lms:{title:`LMS`,key:`lms`,description:`Learning Management System`},marketing:{title:`Marketing`,key:`marketing`,description:`Marketing`},filestorage:{title:`File Storage`,key:`filestorage`,description:`File Storage`}},f=e=>{let t=d[e.toLowerCase()];return t??null},p=e=>!!d[e.toLowerCase()],m=`so1!`,h=(0,c.encodeToBase64)(m),g=`:`,_=`,`,ee=RegExp(`(?<!\\\\)${g}`,`g`),te=RegExp(`(?<!\\\\)${_}`,`g`),v=1;var y=class e extends Error{type;category;context;constructor({category:t,name:n,type:r,context:i,message:a}){super(a),this.name=n??`CoreError`,this.type=r,this.category=t,this.context=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.category}-${this.name} [${this.type}]${e}`}},b=class extends y{constructor(e,t,n){super({category:`CompositeId`,name:t??`BaseCompositeIdError`,type:e,message:n})}},ne=class extends b{constructor(e){super(`COMPOSITE_ID_MISSING_HEADER_ERROR`,`CompositeIdMissingHeaderError`,e??`Invalid compositeId, missing header`)}},re=class extends b{constructor(e){super(`COMPOSITE_ID_MISSING_BODY_ERROR`,`CompositeIdMissingBodyError`,e??`Invalid compositeId, missing body`)}},ie=class extends b{constructor(e){super(`COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR`,`CompositeIdUnknownIdentifierError`,e??`Invalid compositeId, unknown identifier`)}},ae=class extends b{constructor(e){super(`COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR`,`CompositeIdUnsupportedVersionError`,e??`Invalid compositeId, unsupported version`)}};const oe=e=>!(0,c.isMissing)(e)&&`value`in e&&e.value!==void 0,se=e=>!(0,c.isMissing)(e)&&`identifiers`in e&&e.identifiers!==void 0,ce=(e,t={version:v})=>{if(t.version===1)return me(ue(e,t.aliases));throw new ae(`Cannot generate ID, unsupported version number: ${t.version}`)},le=(e,t={version:v})=>{let n=pe(e,t),r={};return n&&n.split(te).forEach(e=>{let[n,i]=e.split(ee),a=fe(n,t.aliases??{});r[a]=_e(i)}),r},ue=(e,t={})=>{if(oe(e))return de({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if(se(e))return e.identifiers.map(e=>de({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1})).join(_);throw new ie},de=({identifier:e,compositeIdAliases:t,isSoleIdentifier:n})=>{let r=n?`id`:t[e.key]||e.key;return[r,ge(e.value)].filter(Boolean).join(g)},fe=(e,t)=>Object.keys(t).find(n=>t[n]===e)??e,pe=(e,t)=>{if(t.version===1)return he(e);throw new ae(`Cannot decode ID, unsupported version number: ${t.version}`)},me=e=>`${h}${(0,c.encodeToBase64)(e)}`,he=e=>{if(!e.startsWith(h))throw new ne(`Trying to decode an ID without the header: ${e}`);let t=e.split(h)[1];if(!t)throw new re(`Trying to decode an ID without a body: ${e}`);return(0,c.decodeFromBase64)(t)},ge=e=>[_,g].reduce((e,t)=>e.replace(t,`\\`+t),e),_e=e=>[_,g].reduce((e,t)=>{let n=`\\`+t;return e.replace(RegExp(`\\\\`+n,`g`),t)},e),ve=e=>(0,c.isMissing)(e)?!1:e.startsWith(h),ye=Object.freeze({status:`aborted`});function x(e,t,n){function r(n,r){var i;for(let a in Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r),o.prototype)a in n||Object.defineProperty(n,a,{value:o.prototype[a].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}const be=Symbol(`zod_brand`);var S=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};const xe={};function C(e){return e&&Object.assign(xe,e),xe}function Se(e){let t=Object.values(e).filter(e=>typeof e==`number`),n=Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t);return n}function Ce(e,t){return typeof t==`bigint`?t.toString():t}function we(e){let t=!1;return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}}}}function Te(e){return e==null}function Ee(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function De(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r,a=Number.parseInt(e.toFixed(i).replace(`.`,``)),o=Number.parseInt(t.toFixed(i).replace(`.`,``));return a%o/10**i}function w(e,t,n){let r=!1;Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Oe(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function T(e){return JSON.stringify(e)}const ke=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function E(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ae=we(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{let e=Function;return new e(``),!0}catch{return!1}});function je(e){if(E(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(E(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}const Me=new Set([`string`,`number`,`symbol`]);function D(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function O(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function k(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ne(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Pe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Fe(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);if(!t[e])continue;n[e]=r.shape[e]}return O(e,{...e._zod.def,shape:n,checks:[]})}function Ie(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);if(!t[e])continue;delete n[e]}return O(e,{...e._zod.def,shape:n,checks:[]})}function Le(e,t){if(!je(t))throw Error(`Invalid input to extend: expected a plain object`);let n={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Oe(this,`shape`,n),n},checks:[]};return O(e,n)}function Re(e,t){return O(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Oe(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function ze(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);if(!n[t])continue;i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t]}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return O(t,{...t._zod.def,shape:i,checks:[]})}function Be(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);if(!n[t])continue;i[t]=new e({type:`nonoptional`,innerType:r[t]})}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return O(t,{...t._zod.def,shape:i,checks:[]})}function A(e,t=0){for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function j(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function M(e){return typeof e==`string`?e:e?.message}function N(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let i=M(e.inst?._zod.def?.error?.(e))??M(t?.error?.(e))??M(n.customError?.(e))??M(n.localeError?.(e))??`Invalid input`;r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Ve(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function P(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const He=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),Object.defineProperty(e,`message`,{get(){return JSON.stringify(t,Ce,2)},enumerable:!0})},Ue=x(`$ZodError`,He),We=x(`$ZodError`,He,{Parent:Error});function Ge(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ke(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i],a=i===t.path.length-1;a?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const qe=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new S;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>N(e,a,C())));throw ke(t,i?.callee),t}return o.value},Je=qe(We),Ye=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>N(e,a,C())));throw ke(t,i?.callee),t}return o.value},Xe=Ye(We),Ze=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new S;return a.issues.length?{success:!1,error:new(e??Ue)(a.issues.map(e=>N(e,i,C())))}:{success:!0,data:a.value}},Qe=Ze(We),$e=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>N(e,i,C())))}:{success:!0,data:a.value}},et=$e(We),tt=/^[cC][^\s-]{8,}$/,nt=/^[0-9a-z]+$/,rt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,it=/^[0-9a-vA-V]{20}$/,at=/^[A-Za-z0-9]{27}$/,ot=/^[a-zA-Z0-9_-]{21}$/,st=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ct=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,lt=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,ut=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,dt=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;function ft(){return new RegExp(dt,`u`)}const pt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,mt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,ht=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,gt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_t=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,vt=/^[A-Za-z0-9_-]*$/,yt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,bt=/^\+(?:[0-9]){6,14}[0-9]$/,xt=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,St=RegExp(`^${xt}$`);function Ct(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`,n=typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`;return n}function wt(e){return RegExp(`^${Ct(e)}$`)}function Tt(e){let t=Ct({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-]\\d{2}:\\d{2})`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${xt}T(?:${r})$`)}const Et=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Dt=/^\d+$/,Ot=/^-?\d+(?:\.\d+)?/i,kt=/true|false/i,At=/^[^A-Z]*$/,jt=/^[^a-z]*$/,F=x(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Mt={number:`number`,bigint:`bigint`,object:`date`},Nt=x(`$ZodCheckLessThan`,(e,t)=>{F.init(e,t);let n=Mt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Pt=x(`$ZodCheckGreaterThan`,(e,t)=>{F.init(e,t);let n=Mt[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ft=x(`$ZodCheckMultipleOf`,(e,t)=>{F.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);let r=typeof n.value==`bigint`?n.value%t.value===BigInt(0):De(n.value,t.value)===0;r||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),It=x(`$ZodCheckNumberFormat`,(e,t)=>{F.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Pe[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Dt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),Lt=x(`$ZodCheckMaxLength`,(e,t)=>{F.init(e,t),e._zod.when=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value,i=r.length;if(i<=t.maximum)return;let a=Ve(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Rt=x(`$ZodCheckMinLength`,(e,t)=>{F.init(e,t),e._zod.when=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if(i>=t.minimum)return;let a=Ve(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),zt=x(`$ZodCheckLengthEquals`,(e,t)=>{F.init(e,t),e._zod.when=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Ve(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),I=x(`$ZodCheckStringFormat`,(e,t)=>{var n,r;F.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Bt=x(`$ZodCheckRegex`,(e,t)=>{I.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Vt=x(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=At,I.init(e,t)}),Ht=x(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=jt,I.init(e,t)}),Ut=x(`$ZodCheckIncludes`,(e,t)=>{F.init(e,t);let n=D(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Wt=x(`$ZodCheckStartsWith`,(e,t)=>{F.init(e,t);let n=RegExp(`^${D(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Gt=x(`$ZodCheckEndsWith`,(e,t)=>{F.init(e,t);let n=RegExp(`.*${D(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Kt=x(`$ZodCheckOverwrite`,(e,t)=>{F.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var qt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e,n=t.split(`
2
+ `).filter(e=>e),r=Math.min(...n.map(e=>e.length-e.trimStart().length)),i=n.map(e=>e.slice(r)).map(e=>` `.repeat(this.indent*2)+e);for(let e of i)this.content.push(e)}compile(){let e=Function,t=this?.args,n=this?.content??[``],r=[...n.map(e=>` ${e}`)];return new e(...t,r.join(`
3
+ `))}};const Jt={major:4,minor:0,patch:0},L=x(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Jt;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=A(e),i;for(let a of t){if(a._zod.when){let t=a._zod.when(e);if(!t)continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new S;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o;let n=e.issues.length;n!==t&&(r||=A(e,t))});else{let n=e.issues.length;if(n===t)continue;r||=A(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let a=e._zod.parse(n,i);if(a instanceof Promise){if(i.async===!1)throw new S;return a.then(e=>t(e,r,i))}return t(a,r,i)}}e[`~standard`]={validate:t=>{try{let n=Qe(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return et(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),Yt=x(`$ZodString`,(e,t)=>{L.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Et(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),R=x(`$ZodStringFormat`,(e,t)=>{I.init(e,t),Yt.init(e,t)}),Xt=x(`$ZodGUID`,(e,t)=>{t.pattern??=ct,R.init(e,t)}),Zt=x(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8},n=e[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=lt(n)}else t.pattern??=lt();R.init(e,t)}),Qt=x(`$ZodEmail`,(e,t)=>{t.pattern??=ut,R.init(e,t)}),$t=x(`$ZodURL`,(e,t)=>{R.init(e,t),e._zod.check=n=>{try{let r=n.value,i=new URL(r),a=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:yt.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith(`/`)&&a.endsWith(`/`)?n.value=a.slice(0,-1):n.value=a;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),en=x(`$ZodEmoji`,(e,t)=>{t.pattern??=ft(),R.init(e,t)}),tn=x(`$ZodNanoID`,(e,t)=>{t.pattern??=ot,R.init(e,t)}),nn=x(`$ZodCUID`,(e,t)=>{t.pattern??=tt,R.init(e,t)}),rn=x(`$ZodCUID2`,(e,t)=>{t.pattern??=nt,R.init(e,t)}),an=x(`$ZodULID`,(e,t)=>{t.pattern??=rt,R.init(e,t)}),on=x(`$ZodXID`,(e,t)=>{t.pattern??=it,R.init(e,t)}),sn=x(`$ZodKSUID`,(e,t)=>{t.pattern??=at,R.init(e,t)}),cn=x(`$ZodISODateTime`,(e,t)=>{t.pattern??=Tt(t),R.init(e,t)}),ln=x(`$ZodISODate`,(e,t)=>{t.pattern??=St,R.init(e,t)}),un=x(`$ZodISOTime`,(e,t)=>{t.pattern??=wt(t),R.init(e,t)}),dn=x(`$ZodISODuration`,(e,t)=>{t.pattern??=st,R.init(e,t)}),fn=x(`$ZodIPv4`,(e,t)=>{t.pattern??=pt,R.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),pn=x(`$ZodIPv6`,(e,t)=>{t.pattern??=mt,R.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),mn=x(`$ZodCIDRv4`,(e,t)=>{t.pattern??=ht,R.init(e,t)}),hn=x(`$ZodCIDRv6`,(e,t)=>{t.pattern??=gt,R.init(e,t),e._zod.check=n=>{let[r,i]=n.value.split(`/`);try{if(!i)throw Error();let e=Number(i);if(`${e}`!==i||e<0||e>128)throw Error();new URL(`http://[${r}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function gn(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const _n=x(`$ZodBase64`,(e,t)=>{t.pattern??=_t,R.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{gn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function vn(e){if(!vt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`),n=t.padEnd(Math.ceil(t.length/4)*4,`=`);return gn(n)}const yn=x(`$ZodBase64URL`,(e,t)=>{t.pattern??=vt,R.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{vn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),bn=x(`$ZodE164`,(e,t)=>{t.pattern??=bt,R.init(e,t)});function xn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Sn=x(`$ZodJWT`,(e,t)=>{R.init(e,t),e._zod.check=n=>{xn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Cn=x(`$ZodNumber`,(e,t)=>{L.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ot,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),wn=x(`$ZodNumber`,(e,t)=>{It.init(e,t),Cn.init(e,t)}),Tn=x(`$ZodBoolean`,(e,t)=>{L.init(e,t),e._zod.pattern=kt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),En=x(`$ZodUnknown`,(e,t)=>{L.init(e,t),e._zod.parse=e=>e}),Dn=x(`$ZodNever`,(e,t)=>{L.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function On(e,t,n){e.issues.length&&t.issues.push(...j(n,e.issues)),t.value[n]=e.value}const kn=x(`$ZodArray`,(e,t)=>{L.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>On(t,n,e))):On(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function z(e,t,n){e.issues.length&&t.issues.push(...j(n,e.issues)),t.value[n]=e.value}function An(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...j(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const jn=x(`$ZodObject`,(e,t)=>{L.init(e,t);let n=we(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof L))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Ne(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});w(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new qt([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=T(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=T(e);t.write(`
4
+ if (${n}.issues.length) {
5
+ if (input[${r}] === undefined) {
6
+ if (${r} in input) {
7
+ newResult[${r}] = undefined;
8
+ }
9
+ } else {
10
+ payload.issues = payload.issues.concat(
11
+ ${n}.issues.map((iss) => ({
12
+ ...iss,
13
+ path: iss.path ? [${r}, ...iss.path] : [${r}],
14
+ }))
15
+ );
16
+ }
17
+ } else if (${n}.value === undefined) {
18
+ if (${r} in input) newResult[${r}] = undefined;
19
+ } else {
20
+ newResult[${r}] = ${n}.value;
21
+ }
22
+ `)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(`
23
+ if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
24
+ ...iss,
25
+ path: iss.path ? [${T(e)}, ...iss.path] : [${T(e)}]
26
+ })));`),t.write(`newResult[${T(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=E,o=!xe.jitless,s=Ae,c=o&&s.value,l=t.catchall,u;e._zod.parse=(s,d)=>{u??=n.value;let f=s.value;if(!a(f))return s.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),s;let p=[];if(o&&c&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),s=i(s,d);else{s.value={};let e=u.shape;for(let t of u.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?An(e,s,t,f):z(e,s,t))):i?An(r,s,t,f):z(r,s,t)}}if(!l)return p.length?Promise.all(p).then(()=>s):s;let m=[],h=u.keySet,g=l._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>z(t,s,e))):z(t,s,e)}return m.length&&s.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>s):s}});function Mn(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>N(e,r,C())))}),t}const Nn=x(`$ZodUnion`,(e,t)=>{L.init(e,t),w(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),w(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),w(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),w(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Ee(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>Mn(t,n,e,r)):Mn(a,n,e,r)}}),Pn=x(`$ZodDiscriminatedUnion`,(e,t)=>{Nn.init(e,t);let n=e._zod.parse;w(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=we(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!E(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,input:o,path:[t.discriminator],inst:e}),i)}}),Fn=x(`$ZodIntersection`,(e,t)=>{L.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n),o=i instanceof Promise||a instanceof Promise;return o?Promise.all([i,a]).then(([t,n])=>Ln(e,t,n)):Ln(e,i,a)}});function In(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(je(e)&&je(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=In(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=In(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ln(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),A(e))return e;let r=In(t.value,n.value);if(!r.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const Rn=x(`$ZodRecord`,(e,t)=>{L.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!je(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...j(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...j(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>N(e,r,C())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...j(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...j(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),zn=x(`$ZodEnum`,(e,t)=>{L.init(e,t);let n=Se(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>Me.has(typeof e)).map(e=>typeof e==`string`?D(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),Bn=x(`$ZodLiteral`,(e,t)=>{L.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?D(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),Vn=x(`$ZodTransform`,(e,t)=>{L.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async){let t=r instanceof Promise?r:Promise.resolve(r);return t.then(t=>(e.value=t,e))}if(r instanceof Promise)throw new S;return e.value=r,e}}),Hn=x(`$ZodOptional`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,w(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),w(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Ee(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),Un=x(`$ZodNullable`,(e,t)=>{L.init(e,t),w(e._zod,`optin`,()=>t.innerType._zod.optin),w(e._zod,`optout`,()=>t.innerType._zod.optout),w(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Ee(e.source)}|null)$`):void 0}),w(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Wn=x(`$ZodDefault`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,w(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Gn(e,t)):Gn(r,t)}});function Gn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Kn=x(`$ZodPrefault`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,w(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),qn=x(`$ZodNonOptional`,(e,t)=>{L.init(e,t),w(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Jn(t,e)):Jn(i,e)}});function Jn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const Yn=x(`$ZodCatch`,(e,t)=>{L.init(e,t),e._zod.optin=`optional`,w(e._zod,`optout`,()=>t.innerType._zod.optout),w(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>N(e,n,C()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>N(e,n,C()))},input:e.value}),e.issues=[]),e)}}),Xn=x(`$ZodPipe`,(e,t)=>{L.init(e,t),w(e._zod,`values`,()=>t.in._zod.values),w(e._zod,`optin`,()=>t.in._zod.optin),w(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Zn(e,t,n)):Zn(r,t,n)}});function Zn(e,t,n){return A(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const Qn=x(`$ZodReadonly`,(e,t)=>{L.init(e,t),w(e._zod,`propValues`,()=>t.innerType._zod.propValues),w(e._zod,`values`,()=>t.innerType._zod.values),w(e._zod,`optin`,()=>t.innerType._zod.optin),w(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then($n):$n(r)}});function $n(e){return e.value=Object.freeze(e.value),e}const er=x(`$ZodCustom`,(e,t)=>{F.init(e,t),L.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>tr(t,n,r,e));tr(i,n,r,e)}});function tr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(P(e))}}const nr=Symbol(`ZodOutput`),rr=Symbol(`ZodInput`);var ir=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function ar(){return new ir}const B=ar();function or(e,t){return new e({type:`string`,...k(t)})}function sr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...k(t)})}function cr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...k(t)})}function lr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...k(t)})}function ur(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...k(t)})}function dr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...k(t)})}function fr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...k(t)})}function pr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...k(t)})}function mr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...k(t)})}function hr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...k(t)})}function gr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...k(t)})}function _r(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...k(t)})}function vr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...k(t)})}function yr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...k(t)})}function br(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...k(t)})}function xr(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...k(t)})}function Sr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...k(t)})}function Cr(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...k(t)})}function wr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...k(t)})}function Tr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...k(t)})}function Er(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...k(t)})}function Dr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...k(t)})}function Or(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...k(t)})}function kr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...k(t)})}function Ar(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...k(t)})}function jr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...k(t)})}function Mr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...k(t)})}function Nr(e,t){return new e({type:`number`,checks:[],...k(t)})}function Pr(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...k(t)})}function Fr(e,t){return new e({type:`boolean`,...k(t)})}function Ir(e){return new e({type:`unknown`})}function Lr(e,t){return new e({type:`never`,...k(t)})}function Rr(e,t){return new Nt({check:`less_than`,...k(t),value:e,inclusive:!1})}function zr(e,t){return new Nt({check:`less_than`,...k(t),value:e,inclusive:!0})}function Br(e,t){return new Pt({check:`greater_than`,...k(t),value:e,inclusive:!1})}function Vr(e,t){return new Pt({check:`greater_than`,...k(t),value:e,inclusive:!0})}function Hr(e,t){return new Ft({check:`multiple_of`,...k(t),value:e})}function Ur(e,t){let n=new Lt({check:`max_length`,...k(t),maximum:e});return n}function V(e,t){return new Rt({check:`min_length`,...k(t),minimum:e})}function Wr(e,t){return new zt({check:`length_equals`,...k(t),length:e})}function Gr(e,t){return new Bt({check:`string_format`,format:`regex`,...k(t),pattern:e})}function Kr(e){return new Vt({check:`string_format`,format:`lowercase`,...k(e)})}function qr(e){return new Ht({check:`string_format`,format:`uppercase`,...k(e)})}function Jr(e,t){return new Ut({check:`string_format`,format:`includes`,...k(t),includes:e})}function Yr(e,t){return new Wt({check:`string_format`,format:`starts_with`,...k(t),prefix:e})}function Xr(e,t){return new Gt({check:`string_format`,format:`ends_with`,...k(t),suffix:e})}function H(e){return new Kt({check:`overwrite`,tx:e})}function Zr(e){return H(t=>t.normalize(e))}function Qr(){return H(e=>e.trim())}function $r(){return H(e=>e.toLowerCase())}function ei(){return H(e=>e.toUpperCase())}function ti(e,t,n){return new e({type:`array`,element:t,...k(n)})}function ni(e,t,n){let r=new e({type:`custom`,check:`custom`,fn:t,...k(n)});return r}const ri=x(`ZodISODateTime`,(e,t)=>{cn.init(e,t),K.init(e,t)});function ii(e){return kr(ri,e)}const ai=x(`ZodISODate`,(e,t)=>{ln.init(e,t),K.init(e,t)});function oi(e){return Ar(ai,e)}const si=x(`ZodISOTime`,(e,t)=>{un.init(e,t),K.init(e,t)});function ci(e){return jr(si,e)}const li=x(`ZodISODuration`,(e,t)=>{dn.init(e,t),K.init(e,t)});function ui(e){return Mr(li,e)}const di=(e,t)=>{Ue.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Ke(e,t)},flatten:{value:t=>Ge(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})},fi=x(`ZodError`,di),U=x(`ZodError`,di,{Parent:Error}),pi=qe(U),mi=Ye(U),hi=Ze(U),gi=$e(U),W=x(`ZodType`,(e,t)=>(L.init(e,t),e.def=t,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>O(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>pi(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>hi(e,t,n),e.parseAsync=async(t,n)=>mi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>gi(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(Ta(t,n)),e.superRefine=t=>e.check(Ea(t)),e.overwrite=t=>e.check(H(t)),e.optional=()=>ca(e),e.nullable=()=>ua(e),e.nullish=()=>ca(ua(e)),e.nonoptional=t=>ga(e,t),e.array=()=>Ki(e),e.or=t=>Yi([e,t]),e.and=t=>$i(e,t),e.transform=t=>ba(e,oa(t)),e.default=t=>fa(e,t),e.prefault=t=>ma(e,t),e.catch=t=>va(e,t),e.pipe=t=>ba(e,t),e.readonly=()=>Sa(e),e.describe=t=>{let n=e.clone();return B.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return B.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return B.get(e);let n=e.clone();return B.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),_i=x(`_ZodString`,(e,t)=>{Yt.init(e,t),W.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(Gr(...t)),e.includes=(...t)=>e.check(Jr(...t)),e.startsWith=(...t)=>e.check(Yr(...t)),e.endsWith=(...t)=>e.check(Xr(...t)),e.min=(...t)=>e.check(V(...t)),e.max=(...t)=>e.check(Ur(...t)),e.length=(...t)=>e.check(Wr(...t)),e.nonempty=(...t)=>e.check(V(1,...t)),e.lowercase=t=>e.check(Kr(t)),e.uppercase=t=>e.check(qr(t)),e.trim=()=>e.check(Qr()),e.normalize=(...t)=>e.check(Zr(...t)),e.toLowerCase=()=>e.check($r()),e.toUpperCase=()=>e.check(ei())}),vi=x(`ZodString`,(e,t)=>{Yt.init(e,t),_i.init(e,t),e.email=t=>e.check(sr(yi,t)),e.url=t=>e.check(pr(Si,t)),e.jwt=t=>e.check(Or(Li,t)),e.emoji=t=>e.check(mr(Ci,t)),e.guid=t=>e.check(cr(bi,t)),e.uuid=t=>e.check(lr(xi,t)),e.uuidv4=t=>e.check(ur(xi,t)),e.uuidv6=t=>e.check(dr(xi,t)),e.uuidv7=t=>e.check(fr(xi,t)),e.nanoid=t=>e.check(hr(wi,t)),e.guid=t=>e.check(cr(bi,t)),e.cuid=t=>e.check(gr(Ti,t)),e.cuid2=t=>e.check(_r(Ei,t)),e.ulid=t=>e.check(vr(Di,t)),e.base64=t=>e.check(Tr(Pi,t)),e.base64url=t=>e.check(Er(Fi,t)),e.xid=t=>e.check(yr(Oi,t)),e.ksuid=t=>e.check(br(ki,t)),e.ipv4=t=>e.check(xr(Ai,t)),e.ipv6=t=>e.check(Sr(ji,t)),e.cidrv4=t=>e.check(Cr(Mi,t)),e.cidrv6=t=>e.check(wr(Ni,t)),e.e164=t=>e.check(Dr(Ii,t)),e.datetime=t=>e.check(ii(t)),e.date=t=>e.check(oi(t)),e.time=t=>e.check(ci(t)),e.duration=t=>e.check(ui(t))});function G(e){return or(vi,e)}const K=x(`ZodStringFormat`,(e,t)=>{R.init(e,t),_i.init(e,t)}),yi=x(`ZodEmail`,(e,t)=>{Qt.init(e,t),K.init(e,t)}),bi=x(`ZodGUID`,(e,t)=>{Xt.init(e,t),K.init(e,t)}),xi=x(`ZodUUID`,(e,t)=>{Zt.init(e,t),K.init(e,t)}),Si=x(`ZodURL`,(e,t)=>{$t.init(e,t),K.init(e,t)}),Ci=x(`ZodEmoji`,(e,t)=>{en.init(e,t),K.init(e,t)}),wi=x(`ZodNanoID`,(e,t)=>{tn.init(e,t),K.init(e,t)}),Ti=x(`ZodCUID`,(e,t)=>{nn.init(e,t),K.init(e,t)}),Ei=x(`ZodCUID2`,(e,t)=>{rn.init(e,t),K.init(e,t)}),Di=x(`ZodULID`,(e,t)=>{an.init(e,t),K.init(e,t)}),Oi=x(`ZodXID`,(e,t)=>{on.init(e,t),K.init(e,t)}),ki=x(`ZodKSUID`,(e,t)=>{sn.init(e,t),K.init(e,t)}),Ai=x(`ZodIPv4`,(e,t)=>{fn.init(e,t),K.init(e,t)}),ji=x(`ZodIPv6`,(e,t)=>{pn.init(e,t),K.init(e,t)}),Mi=x(`ZodCIDRv4`,(e,t)=>{mn.init(e,t),K.init(e,t)}),Ni=x(`ZodCIDRv6`,(e,t)=>{hn.init(e,t),K.init(e,t)}),Pi=x(`ZodBase64`,(e,t)=>{_n.init(e,t),K.init(e,t)}),Fi=x(`ZodBase64URL`,(e,t)=>{yn.init(e,t),K.init(e,t)}),Ii=x(`ZodE164`,(e,t)=>{bn.init(e,t),K.init(e,t)}),Li=x(`ZodJWT`,(e,t)=>{Sn.init(e,t),K.init(e,t)}),Ri=x(`ZodNumber`,(e,t)=>{Cn.init(e,t),W.init(e,t),e.gt=(t,n)=>e.check(Br(t,n)),e.gte=(t,n)=>e.check(Vr(t,n)),e.min=(t,n)=>e.check(Vr(t,n)),e.lt=(t,n)=>e.check(Rr(t,n)),e.lte=(t,n)=>e.check(zr(t,n)),e.max=(t,n)=>e.check(zr(t,n)),e.int=t=>e.check(Bi(t)),e.safe=t=>e.check(Bi(t)),e.positive=t=>e.check(Br(0,t)),e.nonnegative=t=>e.check(Vr(0,t)),e.negative=t=>e.check(Rr(0,t)),e.nonpositive=t=>e.check(zr(0,t)),e.multipleOf=(t,n)=>e.check(Hr(t,n)),e.step=(t,n)=>e.check(Hr(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function q(e){return Nr(Ri,e)}const zi=x(`ZodNumberFormat`,(e,t)=>{wn.init(e,t),Ri.init(e,t)});function Bi(e){return Pr(zi,e)}const Vi=x(`ZodBoolean`,(e,t)=>{Tn.init(e,t),W.init(e,t)});function J(e){return Fr(Vi,e)}const Hi=x(`ZodUnknown`,(e,t)=>{En.init(e,t),W.init(e,t)});function Y(){return Ir(Hi)}const Ui=x(`ZodNever`,(e,t)=>{Dn.init(e,t),W.init(e,t)});function Wi(e){return Lr(Ui,e)}const Gi=x(`ZodArray`,(e,t)=>{kn.init(e,t),W.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(V(t,n)),e.nonempty=t=>e.check(V(1,t)),e.max=(t,n)=>e.check(Ur(t,n)),e.length=(t,n)=>e.check(Wr(t,n)),e.unwrap=()=>e.element});function Ki(e,t){return ti(Gi,e,t)}const qi=x(`ZodObject`,(e,t)=>{jn.init(e,t),W.init(e,t),w(e,`shape`,()=>t.shape),e.keyof=()=>Z(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Y()}),e.loose=()=>e.clone({...e._zod.def,catchall:Y()}),e.strict=()=>e.clone({...e._zod.def,catchall:Wi()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Le(e,t),e.merge=t=>Re(e,t),e.pick=t=>Fe(e,t),e.omit=t=>Ie(e,t),e.partial=(...t)=>ze(sa,e,t[0]),e.required=(...t)=>Be(ha,e,t[0])});function X(e,t){let n={type:`object`,get shape(){return Oe(this,`shape`,{...e}),this.shape},...k(t)};return new qi(n)}const Ji=x(`ZodUnion`,(e,t)=>{Nn.init(e,t),W.init(e,t),e.options=t.options});function Yi(e,t){return new Ji({type:`union`,options:e,...k(t)})}const Xi=x(`ZodDiscriminatedUnion`,(e,t)=>{Ji.init(e,t),Pn.init(e,t)});function Zi(e,t,n){return new Xi({type:`union`,options:t,discriminator:e,...k(n)})}const Qi=x(`ZodIntersection`,(e,t)=>{Fn.init(e,t),W.init(e,t)});function $i(e,t){return new Qi({type:`intersection`,left:e,right:t})}const ea=x(`ZodRecord`,(e,t)=>{Rn.init(e,t),W.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function ta(e,t,n){return new ea({type:`record`,keyType:e,valueType:t,...k(n)})}const na=x(`ZodEnum`,(e,t)=>{zn.init(e,t),W.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new na({...t,checks:[],...k(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new na({...t,checks:[],...k(r),entries:i})}});function Z(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new na({type:`enum`,entries:n,...k(t)})}const ra=x(`ZodLiteral`,(e,t)=>{Bn.init(e,t),W.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function ia(e,t){return new ra({type:`literal`,values:Array.isArray(e)?e:[e],...k(t)})}const aa=x(`ZodTransform`,(e,t)=>{Vn.init(e,t),W.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(P(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(P(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function oa(e){return new aa({type:`transform`,transform:e})}const sa=x(`ZodOptional`,(e,t)=>{Hn.init(e,t),W.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ca(e){return new sa({type:`optional`,innerType:e})}const la=x(`ZodNullable`,(e,t)=>{Un.init(e,t),W.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ua(e){return new la({type:`nullable`,innerType:e})}const da=x(`ZodDefault`,(e,t)=>{Wn.init(e,t),W.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function fa(e,t){return new da({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const pa=x(`ZodPrefault`,(e,t)=>{Kn.init(e,t),W.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ma(e,t){return new pa({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}const ha=x(`ZodNonOptional`,(e,t)=>{qn.init(e,t),W.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ga(e,t){return new ha({type:`nonoptional`,innerType:e,...k(t)})}const _a=x(`ZodCatch`,(e,t)=>{Yn.init(e,t),W.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function va(e,t){return new _a({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ya=x(`ZodPipe`,(e,t)=>{Xn.init(e,t),W.init(e,t),e.in=t.in,e.out=t.out});function ba(e,t){return new ya({type:`pipe`,in:e,out:t})}const xa=x(`ZodReadonly`,(e,t)=>{Qn.init(e,t),W.init(e,t)});function Sa(e){return new xa({type:`readonly`,innerType:e})}const Ca=x(`ZodCustom`,(e,t)=>{er.init(e,t),W.init(e,t)});function wa(e,t){let n=new F({check:`custom`,...k(t)});return n._zod.check=e,n}function Ta(e,t={}){return ni(Ca,e,t)}function Ea(e,t){let n=wa(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(P(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(P(r))}},e(t.value,t)),t);return n}const Da=X({r:ta(G(),X({n:q().optional().nullable(),c:G().optional().nullable(),p:q().optional().nullable()})),v:q(),t:q()}),Oa=X({remote:ta(G(),X({pageNumber:q().optional(),providerPageCursor:G().optional(),position:q().optional()})),version:q(),timestamp:q()}),ka=e=>(0,c.encodeToBase64)(JSON.stringify(Aa(e))),Aa=e=>{let{remote:t,version:n,timestamp:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{pageNumber:t,providerPageCursor:n,position:r}])=>[e,{n:t,c:n,p:r}])),a={r:i,v:n,t:r};return a},ja=e=>{try{if((0,c.isString)(e)){let t=(0,c.decodeFromBase64)(e),n=JSON.parse(t),r=Da.parse(n);return Ma(r)}else return Oa.parse(e),e}catch{return null}},Ma=e=>{let{r:t,v:n,t:r}=e,i=Object.fromEntries(Object.entries(t).map(([e,{n:t,c:n,p:r}])=>[e,{pageNumber:t,providerPageCursor:n,position:r}])),a={remote:i,version:n,timestamp:r};return a},Na=(e,t)=>{let n=typeof e==`string`?ja(e):e,r=typeof t==`string`?ja(t):t;if(n===null||r===null)return n===r;let{timestamp:i,...a}=n,{timestamp:o,...s}=r;return(0,c.getContentHash)(a)===(0,c.getContentHash)(s)},Pa=({cursor:e,ignoreStepIndex:t})=>(0,c.isMissing)(e)?!0:Object.keys(e?.remote??{}).reduce((n,r)=>{let i=e?.remote?.[r];return((0,c.isMissing)(t)||r!==t.toString())&&(n=n&&(0,c.isMissing)(i.pageNumber)&&(0,c.isMissing)(i.position)&&(0,c.isMissing)(i.providerPageCursor)),n},!0),Fa=({cursor:e,stepIndex:t,pageNumber:n,providerPageCursor:r,position:i})=>{let a={pageNumber:n??void 0,providerPageCursor:r??void 0,position:i??void 0},o=(0,c.isMissing)(n)&&(0,c.isMissing)(r)&&(0,c.isMissing)(i);return(0,c.isMissing)(e)?{remote:o?{}:{[t]:a},version:2,timestamp:Date.now()}:o?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:a}}},Ia=e=>e instanceof y,La=X({stepsDataToGroup:Ki(G()),isSingleRecord:J().optional()}),Ra=X({data:Y()}),za=async({block:e,params:t})=>{let{stepsDataToGroup:n,isSingleRecord:r}=La.parse(t),i=n.reduce((t,n)=>{let i=e.steps?.[n]?.output?.data;return i?r?{...t,[n]:{...i}}:(Object.keys(i).forEach(e=>{let r=(0,c.notMissing)(t[e])?t[e]:{};t[e]={...r,[n]:{...i[e]}}}),t):t},{});return{block:{...e},successful:!0,output:{data:r?i:Object.values(i)}}},Ba=async({block:e})=>{let t=e?.fieldConfigs,n=[],r=e.steps;if(!t||e?.debug?.custom_mappings===`disabled`||!r)return{block:e,successful:!0};let i;if(Array.isArray(e.result)){let a=e.result.length;i=e.result.map((e,i)=>{let o=Va(r,a,i),s=Ha(e,t,o);return n.push(...s.errors||[]),s.record})}else{let a=Ha(e.result,t,r);i=a.record,n.push(...a.errors||[])}return{block:{...e,result:i},successful:!0,errors:Object.keys(n).length>0?n:void 0}},Va=(e,t,n)=>Object.entries(e).reduce((e,[r,i])=>{let a=i?.output?.data;return Array.isArray(a)&&a.length===t?e[r]={output:{data:a[n]}}:e[r]=i,e},{}),Ha=(e,t,n)=>{if(!e||!n)return{record:e};let r={unified:{...e},...typeof n==`object`?n:{}},i={},a=[],o={...e};for(let n of t){let{error:t,value:s}=Ua(r,e.id,n);if(t){a.push(t);continue}n.custom?i[n.targetFieldKey]=s:o[n.targetFieldKey]=s}return{record:{...o,unified_custom_fields:Object.keys(i).length>0?i:void 0},errors:a.length>0?a:void 0}},Ua=(e,t,n)=>{let{expression:r,targetFieldKey:i}=n;if(!r)return{error:{message:`Expression is empty`,id:t,targetField:i}};let a;try{a=(0,l.evaluate)(r,e)}catch{return{error:{message:`Invalid expression`,id:t,targetField:i}}}return a===void 0?{error:{message:`Expression returned no value`,id:t,targetField:i}}:{value:a}},Wa=e=>{switch(e){case`country_alpha2code_by_alpha2code`:return c.getCountryAlpha2CodeByAlpha2Code;case`country_alpha3code_by_alpha3code`:return c.getCountryAlpha3CodeByAlpha3Code;case`country_code_by_country_code`:return c.getCountryCodeByCountryCode;case`country_name_by_country_name`:return c.getCountryNameByCountryName;case`country_name_by_alpha3code`:return c.getCountryNameByAlpha3Code;case`country_name_by_alpha2code`:return c.getCountryNameByAlpha2Code;case`country_name_by_country_code`:return c.getCountryNameByCountryCode;case`country_alpha3code_by_alpha2code`:return c.getCountryAlpha3CodeByAlpha2Code;case`country_alpha3code_by_country_name`:return c.getCountryAlpha3CodeByCountryName;case`country_alpha3code_by_country_code`:return c.getCountryAlpha3CodeByCountryCode;case`country_alpha2code_by_alpha3code`:return c.getCountryAlpha2CodeByAlpha3Code;case`country_alpha2code_by_country_name`:return c.getCountryAlpha2CodeByCountryName;case`country_alpha2code_by_country_code`:return c.getCountryAlpha2CodeByCountryCode;case`country_code_by_alpha2code`:return c.getCountryCodeByAlpha2Code;case`country_code_by_alpha3code`:return c.getCountryCodeByAlpha3Code;case`country_code_by_country_name`:return c.getCountryCodeByCountryName;case`country_subdivisions_by_alpha2code`:return c.getCountrySubDivisionsByAlpha2Code;case`country_subdivision_code_by_subdivision_name`:return c.getCountrySubDivisionCodeBySubDivisionName;case`country_alpha2code_by_citizenship`:return c.getCountryAlpha2CodeByCitizenship;case`country_subdivision_name_by_subdivision_code`:return c.getCountrySubDivisionNameBySubDivisionCode;default:return}},Ga=X({fields:X({targetFieldKey:G(),alias:G().optional(),expression:G(),type:Z([`string`,`number`,`boolean`,`datetime_string`,`enum`]),custom:J().default(!1),hidden:J().default(!1),enumMapper:X({matcher:G().or(X({matchExpression:G(),value:G()}).array())}).optional()}).array(),dataSource:G()}),Ka=X({data:Y()}),qa=async({block:e,params:t})=>{let n=[],{fields:r,dataSource:i}=Ga.parse(t),a=(0,l.evaluate)(i,e);if(!r||!i||e?.debug?.custom_mappings===`disabled`||!a)return{block:e,successful:!0};let o;if(Array.isArray(a))o=a.map(e=>{let t=Ja(r,e);return n.push(...t?.errors||[]),t?.record});else{let e=Ja(r,a);o=e?.record,n.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:o},errors:Object.keys(n).length>0?n:void 0}},Ja=(e,t)=>{if(!t)return;let n={},r=[],i={};for(let a of e){let{error:e,value:o}=Ya(t,t?.id,a);if(e){r.push(e);continue}a.custom?n[a.targetFieldKey]=o:i[a.targetFieldKey]=o}return{record:{...i,unified_custom_fields:Object.keys(n).length>0?n:void 0},errors:r.length>0?r:void 0}},Ya=(e,t,n)=>{switch(n.type){case`string`:case`number`:case`boolean`:case`datetime_string`:return Xa(n,t,e);case`enum`:return Za(n,t,e);default:return{error:{message:`Invalid type`,id:t,targetField:n.targetFieldKey}}}},Xa=(e,t,n)=>{if(!e.expression)return{error:{message:`Expression is empty`,id:t,targetField:e.targetFieldKey}};let r;try{r=(0,l.evaluate)(e.expression,n)}catch{return{error:{message:`Invalid expression`,id:t,targetField:e.targetFieldKey}}}return r===void 0?{error:{message:`Expression returned no value`,id:t,targetField:e.targetFieldKey}}:{value:r}},Za=(e,t,n)=>{let r=Xa(e,t,n),i=(0,c.notMissing)(r.value)?r.value:null;if(e.enumMapper===void 0)return{error:{message:`Enum mapper was not defined`,id:t,targetField:e.targetFieldKey}};let a=e.enumMapper.matcher;if((0,c.isString)(a)){let n=Wa(a);if((0,c.notMissing)(n)){let e=(0,c.notMissing)(i)?n(i):null;return{value:{value:e??`unmapped_value`,source_value:i}}}else return{error:{message:`The built-in matcher "${a}" is not supported`,id:t,targetField:e.targetFieldKey}}}for(let e of a){let{matchExpression:t,value:r}=e,a=(0,l.evaluate)(t,n);if(a===!0)return{value:{value:r,source_value:i}}}return{value:{value:`unmapped_value`,source_value:i}}},Qa=X({type:ia(`basic`),username:G().optional(),password:G().optional(),encoding:G().optional()}),$a=X({type:ia(`bearer`),token:G()}),eo=Zi(`type`,[Qa,$a]),to=X({baseUrl:G(),url:G(),method:Z(u.HttpMethods),response:X({indexField:G().optional(),dataKey:G().optional(),nextKey:G().optional()}).optional(),iterator:X({key:G(),in:Z(u.RequestParameterLocations)}),cursor:X({token:G().optional().nullable(),position:q().optional().nullable()}).optional(),customErrors:u.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:X({name:G(),value:Y(),in:Z(u.RequestParameterLocations),condition:G().optional()}).array().optional()}),no=X({data:Y().optional(),raw:Y().optional(),statusCode:q(),message:G().optional(),next:G().optional().nullable(),position:q().optional()}).optional(),ro=25,io=e=>{let t=Number(e.inputs?.page_size);return Number.isNaN(t)?ro:t},ao=(e,t)=>{let{args:n}=e,r=n?n.filter(e=>!e.condition||(0,l.evaluate)(e.condition,t)===!0).map(e=>({...e,condition:void 0})):void 0,i=e?(0,l.safeEvaluateRecord)({...e,args:r},t):{};return{...i,customErrors:e?.customErrors}},oo=(e,t)=>{let n=to.parse(e),r=e?.authentication?.[t.context.authenticationType]?.[t.context.environment]?.authorization,i=eo.parse(r),a=n.args?(0,u.parseRequestParameters)(n.args):{query:{},body:{},headers:{}},o=(0,u.createAuthorizationHeaders)(i),s={...a?.headers??{},...o},c=io(t);return{requestConfig:n,preparedRequest:{parsedArgs:a,requestHeaders:s,pageSize:c}}},so=(e,t)=>({nextIterator:e?.token??null,lastUsedIterator:null,lastStatusCode:null,data:[],raw:[],recordsLeft:t,pagePosition:e?.position??0,firstPage:!0,noMoreData:!0}),co=(e,t,n)=>{n!==null&&(t.in===`query`?e.query[t.key]=n.toString():t.in===`body`&&(e.body[t.key]=n))},lo=async(e,t,n,r)=>{if(!t.httpClient)throw Error(`HTTP client is not configured`);try{return await e.performRequest({httpClient:t.httpClient,url:`${n.baseUrl}${n.url}`,queryParams:r.parsedArgs?.query,method:n.method,headers:r.requestHeaders,body:r.parsedArgs?.body,customErrorConfigs:n.customErrors})}catch(e){let n=e;return{block:t,successful:!1,errors:[e],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}},uo=(e,t,n)=>{let r=t?.dataKey?e.data[t?.dataKey]:e.data,i=r?.slice(n.pagePosition,n.recordsLeft)??[];return n.recordsLeft-=i.length,n.pagePosition+=i.length,n.raw.push(e),n.data=n.data.concat(i),n.lastStatusCode=e?.status,{resultData:r,slicedData:i}},fo=(e,t,n,r,i,a)=>{let o=t?.nextKey?e.data[t?.nextKey]:void 0;n.nextIterator=typeof o==`string`||typeof o==`number`?o:null,r.length===i.length&&n.recordsLeft===0&&(n.pagePosition=0,n.lastUsedIterator=n.nextIterator),n.noMoreData=(0,c.isMissing)(n.nextIterator)&&n.data.length<a},po=(e,t,n)=>(0,c.notMissing)(e.nextIterator)&&e.data.length<t&&n?.length>0,mo=(e,t,n)=>{let r=go(t.data,n);return{block:e,successful:!0,output:{data:r,raw:t.raw,statusCode:t.lastStatusCode,next:t.noMoreData?void 0:t.lastUsedIterator,position:t.noMoreData?void 0:t.pagePosition}}},ho=async({block:e,params:t})=>{let n=u.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let r=ao(t??{},e),{requestConfig:i,preparedRequest:a}=oo(r,e),o=so(i.cursor,a.pageSize);do{o.firstPage?o.firstPage=!1:o.pagePosition=0,co(a.parsedArgs,i.iterator,o.nextIterator);let t=await lo(n,e,i,a);if(`successful`in t&&t.successful===!1)return t;let r=t;o.lastUsedIterator=o.nextIterator;let{resultData:s,slicedData:c}=uo(r,i.response,o);fo(r,i.response,o,c,s,a.pageSize)}while(po(o,a.pageSize,o.data));return mo(e,o,i.response)},go=(e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},_o=X({type:ia(`basic`),username:G().optional(),password:G().optional(),encoding:G().optional()}),vo=X({type:ia(`bearer`),token:G()}),yo=Zi(`type`,[_o,vo]),bo=X({baseUrl:G(),url:G(),method:Z(u.HttpMethods),response:X({collection:J().optional(),indexField:G().optional(),dataKey:G().optional()}).optional(),customErrors:u.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:X({name:G(),value:Y(),in:Z(u.RequestParameterLocations),condition:G().optional()}).array().optional()}),xo=X({data:Y().optional(),raw:Y().optional(),statusCode:q(),message:G().optional()}).optional(),So=async({block:e,params:t})=>{let n=u.RequestClientFactory.build();if(!e.httpClient)throw Error(`HTTP client is not configured`);let{args:r}=t,i=r?r.filter(t=>!t.condition||(0,l.evaluate)(t.condition,e)===!0).map(e=>({...e,condition:void 0})):void 0,a=t?(0,l.safeEvaluateRecord)({...t,args:i},e):{},o={...a,customErrors:t?.customErrors},{baseUrl:s,url:c,method:d,response:f,customErrors:p,args:m}=bo.parse(o),h=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,g=yo.parse(h),_=m?(0,u.parseRequestParameters)(m):{query:{},body:{},headers:{}},ee=(0,u.createAuthorizationHeaders)(g),te={..._?.headers??{},...ee},v;try{v=await n.performRequest({httpClient:e.httpClient,url:`${s}${c}`,queryParams:_?.query,method:d,headers:te,body:_?.body,customErrorConfigs:p})}catch(t){let n=t;return{block:e,successful:!1,errors:[t],output:{statusCode:n?.response?.status??500,message:n?.response?.message}}}let y=f?.dataKey?v.data[f?.dataKey]:v.data,b=Co(y,f);return{block:e,successful:!0,output:{data:b,raw:v,statusCode:v?.status,message:v?.message}}},Co=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce((e,n)=>{let r=t.indexField;return r&&n[r]&&(e[n[r]]=n),e},{});if(!t?.collection&&t?.indexField){let n=t.indexField;return n&&e[n]?{[e[n]]:e}:e}return e},wo=X({fields:X({targetFieldKey:G(),alias:G().optional(),type:G(),custom:J().default(!1),hidden:J().default(!1)}).array().optional(),dataSource:G()}),To=X({data:Y()});let Q=function(e){return e.String=`string`,e.Number=`number`,e.Boolean=`boolean`,e.DateTimeString=`datetime_string`,e}({});const Eo=({value:e,type:t,format:n})=>{if((0,c.isMissing)(e))return null;switch(t){case Q.String:return(0,c.safeParseToString)({value:e});case Q.Number:return(0,c.safeParseToNumber)({value:e});case Q.Boolean:return(0,c.safeParseToBoolean)({value:e});case Q.DateTimeString:return(0,c.safeParseToDateTimeString)({value:e,format:n});default:return e}},Do=e=>{let t=Object.values(Q);return t.includes(e)},Oo=async({block:e})=>{let t=e?.fieldConfigs;if(!t||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let n;return n=Array.isArray(e.result)?e.result.map(e=>ko(e,t)):ko(e.result,t),{block:{...e,result:n},successful:!0}},ko=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;Do(i)&&(!t.custom&&(0,c.notMissing)(n[r])?n[r]=Eo({value:e[r],type:i}):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=Eo({value:e.unified_custom_fields?.[r],type:i})))}),{...n}},Ao=async({block:e,params:t})=>{let{fields:n,dataSource:r}=wo.parse(t),i=(0,l.evaluate)(r,e);if(!n||e?.debug?.custom_mappings===`disabled`)return{block:e,successful:!0};let a;return a=Array.isArray(i)?i.map(e=>jo(e,n)):jo(i,n),{block:{...e},successful:!0,output:{data:a}}},jo=(e,t)=>{let n={...e};return t.forEach(t=>{let{targetFieldKey:r,type:i}=t;Do(i)&&(!t.custom&&(0,c.notMissing)(n[r])?n[r]=Eo({value:e[r],type:i}):n.unified_custom_fields&&(0,c.notMissing)(n.unified_custom_fields?.[r])&&(n.unified_custom_fields[r]=Eo({value:e.unified_custom_fields?.[r],type:i})))}),{...n}};let $=function(e){return e.TYPECAST=`typecast`,e.MAP_FIELDS=`map_fields`,e.GROUP_DATA=`group_data`,e.REQUEST=`request`,e.PAGINATED_REQUEST=`paginated_request`,e}({});const Mo={[$.TYPECAST]:{v1:{fn:Oo},v2:{fn:Ao,inputSchema:wo,outputSchema:To}},[$.MAP_FIELDS]:{v1:{fn:Ba},v2:{fn:qa,inputSchema:Ga,outputSchema:Ka}},[$.REQUEST]:{v1:{fn:So,inputSchema:bo,outputSchema:xo}},[$.GROUP_DATA]:{v1:{fn:za,inputSchema:La,outputSchema:Ra}},[$.PAGINATED_REQUEST]:{v1:{fn:ho,inputSchema:to,outputSchema:no}}},No=(e,t)=>async({block:n,params:r})=>{try{e.inputSchema&&e.inputSchema.parse(r)}catch{return{block:n,successful:!1,errors:[{message:`Input parameters for ${t} are invalid`}]}}let i=await e.fn({block:n,params:r});try{e.outputSchema&&e.outputSchema.parse(i.output)}catch{return{block:n,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return i},Po={build({functionName:e,version:t=`1`,validateSchemas:n=!1,stepFunctionsList:r=Mo}){let i=r?.[e]?.[`v${t}`];if(!i)throw Error(`Unknown step function: ${e} v${t}`);return n?{...i,fn:No(i,e)}:i}};exports.AUTHENTICATION_SCHEMA=yo,exports.COMPOSITE_ID_LATEST_VERSION=v,exports.CoreError=y,exports.StepFunctionName=$,exports.StepFunctionsFactory=Po,exports.areCursorsEqual=Na,exports.decodeCompositeId=le,exports.encodeCompositeId=ce,exports.expandCursor=ja,exports.getCategoryDetails=f,exports.isCompositeId=ve,exports.isCoreError=Ia,exports.isCursorEmpty=Pa,exports.isValidCategory=p,exports.minifyCursor=ka,exports.updateCursor=Fa;