@decku/cli 0.1.0

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