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