@atrim/instrument-web 0.1.0

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