adsinagents 0.1.0

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