@stackone/core 1.52.4 → 1.52.5

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