switchroom 0.18.26 → 0.18.28

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