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