@composio/json-schema-to-zod 0.3.4 → 0.4.1
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 +31 -3
- package/dist/compile-pattern-D-zr7Yui.d.mts +206 -0
- package/dist/convert-Cte4lEaK.mjs +1768 -0
- package/dist/index.d.mts +4 -209
- package/dist/index.mjs +103 -1731
- package/dist/v4.d.mts +14 -0
- package/dist/v4.mjs +246 -0
- package/package.json +16 -7
package/dist/index.mjs
CHANGED
|
@@ -1,1527 +1,7 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import { dequal } from "dequal/lite";
|
|
4
|
-
import { RE2JS } from "re2js";
|
|
5
|
-
import { Validator, encodePointer, format, ignoredKeyword, schemaArrayKeyword, schemaMapKeyword } from "@cfworker/json-schema";
|
|
1
|
+
import { a as composeGuards, i as buildTuple, n as InvalidPatternError, o as run, r as applyObjectPolicy, s as withPath, t as createConverter } from "./convert-Cte4lEaK.mjs";
|
|
2
|
+
import * as z from "zod/v3";
|
|
6
3
|
|
|
7
|
-
|
|
8
|
-
const half = (arr) => {
|
|
9
|
-
return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
|
|
10
|
-
};
|
|
11
|
-
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/utils/its.ts
|
|
14
|
-
const its = {
|
|
15
|
-
an: {
|
|
16
|
-
object: (x) => x.type === "object" || !x.type && (x.properties !== void 0 || x.additionalProperties !== void 0 || x.patternProperties !== void 0),
|
|
17
|
-
array: (x) => x.type === "array",
|
|
18
|
-
anyOf: (x) => x.anyOf !== void 0,
|
|
19
|
-
allOf: (x) => x.allOf !== void 0,
|
|
20
|
-
enum: (x) => x.enum !== void 0
|
|
21
|
-
},
|
|
22
|
-
a: {
|
|
23
|
-
nullable: (x) => x.nullable === true,
|
|
24
|
-
multipleType: (x) => Array.isArray(x.type),
|
|
25
|
-
not: (x) => x.not !== void 0,
|
|
26
|
-
const: (x) => x.const !== void 0,
|
|
27
|
-
primitive: (x, p) => x.type === p,
|
|
28
|
-
conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
|
|
29
|
-
oneOf: (x) => x.oneOf !== void 0
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
//#endregion
|
|
34
|
-
//#region src/parsers/parse-all-of.ts
|
|
35
|
-
const originalIndex = Symbol("Original index");
|
|
36
|
-
const ensureOriginalIndex = (arr) => {
|
|
37
|
-
const newArr = [];
|
|
38
|
-
for (let i = 0; i < arr.length; i++) {
|
|
39
|
-
const item = arr[i];
|
|
40
|
-
if (typeof item === "boolean") newArr.push(item ? { [originalIndex]: i } : {
|
|
41
|
-
[originalIndex]: i,
|
|
42
|
-
not: {}
|
|
43
|
-
});
|
|
44
|
-
else if (originalIndex in item) return arr;
|
|
45
|
-
else newArr.push({
|
|
46
|
-
...item,
|
|
47
|
-
[originalIndex]: i
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
return newArr;
|
|
51
|
-
};
|
|
52
|
-
const isClosedObjectBranch = (branch) => typeof branch === "object" && its.an.object(branch) && branch.properties !== void 0 && Object.keys(branch.properties).length > 0 && branch.additionalProperties === void 0 && branch.patternProperties === void 0 && !("$ref" in branch);
|
|
53
|
-
const intersect = (branches, refs) => {
|
|
54
|
-
if (branches.length === 1) {
|
|
55
|
-
const item = branches[0];
|
|
56
|
-
return parseSchema(item, {
|
|
57
|
-
...refs,
|
|
58
|
-
path: [
|
|
59
|
-
...refs.path,
|
|
60
|
-
"allOf",
|
|
61
|
-
item[originalIndex]
|
|
62
|
-
]
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
const [left, right] = half(branches);
|
|
66
|
-
return z.intersection(intersect(left, refs), intersect(right, refs));
|
|
67
|
-
};
|
|
68
|
-
function parseAllOf(jsonSchema, refs) {
|
|
69
|
-
if (jsonSchema.allOf.length === 0) return z.never();
|
|
70
|
-
if (jsonSchema.allOf.length === 1) return intersect(ensureOriginalIndex(jsonSchema.allOf), refs);
|
|
71
|
-
const opened = jsonSchema.allOf.map((branch) => isClosedObjectBranch(branch) ? {
|
|
72
|
-
...branch,
|
|
73
|
-
additionalProperties: true
|
|
74
|
-
} : branch);
|
|
75
|
-
const parsed = intersect(ensureOriginalIndex(opened), refs);
|
|
76
|
-
if (!jsonSchema.allOf.every(isClosedObjectBranch)) return parsed;
|
|
77
|
-
const declaredKeys = new Set(jsonSchema.allOf.flatMap((branch) => Object.keys(branch.properties ?? {})));
|
|
78
|
-
return parsed.superRefine((value, ctx) => {
|
|
79
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return;
|
|
80
|
-
const unrecognizedKeys = Object.keys(value).filter((key) => !declaredKeys.has(key));
|
|
81
|
-
if (unrecognizedKeys.length > 0) ctx.addIssue({
|
|
82
|
-
code: z.ZodIssueCode.unrecognized_keys,
|
|
83
|
-
keys: unrecognizedKeys,
|
|
84
|
-
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
85
|
-
});
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
//#endregion
|
|
90
|
-
//#region src/parsers/parse-any-of.ts
|
|
91
|
-
const parseAnyOf = (jsonSchema, refs) => {
|
|
92
|
-
return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
|
|
93
|
-
...refs,
|
|
94
|
-
path: [
|
|
95
|
-
...refs.path,
|
|
96
|
-
"anyOf",
|
|
97
|
-
0
|
|
98
|
-
]
|
|
99
|
-
}) : z.union(jsonSchema.anyOf.map((schema, i) => parseSchema(schema, {
|
|
100
|
-
...refs,
|
|
101
|
-
path: [
|
|
102
|
-
...refs.path,
|
|
103
|
-
"anyOf",
|
|
104
|
-
i
|
|
105
|
-
]
|
|
106
|
-
}))) : z.any();
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
//#endregion
|
|
110
|
-
//#region src/utils/extend-schema.ts
|
|
111
|
-
function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
|
|
112
|
-
const value = jsonSchema[key];
|
|
113
|
-
if (value !== void 0) {
|
|
114
|
-
const errorMessage = jsonSchema.errorMessage?.[key];
|
|
115
|
-
return extend(zodSchema, value, errorMessage);
|
|
116
|
-
}
|
|
117
|
-
return zodSchema;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
//#endregion
|
|
121
|
-
//#region src/parsers/parse-array.ts
|
|
122
|
-
const parseArray = (jsonSchema, refs) => {
|
|
123
|
-
if (its.an.anyOf(jsonSchema)) {
|
|
124
|
-
const types = /* @__PURE__ */ new Set();
|
|
125
|
-
const itemsSchemas = [];
|
|
126
|
-
jsonSchema.anyOf.forEach((option) => {
|
|
127
|
-
if (typeof option === "object" && option.type) types.add(typeof option.type === "string" ? option.type : option.type[0]);
|
|
128
|
-
if (typeof option === "object" && option.items) {
|
|
129
|
-
const optionItems = option.items;
|
|
130
|
-
if (!Array.isArray(optionItems) && typeof optionItems === "object") itemsSchemas.push(optionItems);
|
|
131
|
-
}
|
|
132
|
-
});
|
|
133
|
-
let finalItems;
|
|
134
|
-
if (itemsSchemas.length === 1) finalItems = itemsSchemas[0];
|
|
135
|
-
else if (itemsSchemas.length > 1) finalItems = { anyOf: itemsSchemas };
|
|
136
|
-
const newSchema = {
|
|
137
|
-
...types.size > 0 ? { type: Array.from(types) } : { type: "array" },
|
|
138
|
-
...finalItems && { items: finalItems }
|
|
139
|
-
};
|
|
140
|
-
[
|
|
141
|
-
"default",
|
|
142
|
-
"description",
|
|
143
|
-
"examples",
|
|
144
|
-
"title"
|
|
145
|
-
].forEach((field) => {
|
|
146
|
-
const value = jsonSchema[field];
|
|
147
|
-
if (value !== void 0) newSchema[field] = value;
|
|
148
|
-
});
|
|
149
|
-
return parseSchema(newSchema, refs);
|
|
150
|
-
}
|
|
151
|
-
if (Array.isArray(jsonSchema.items)) {
|
|
152
|
-
const parsedItems = jsonSchema.items.map((item, index) => parseSchema(item, {
|
|
153
|
-
...refs,
|
|
154
|
-
path: [
|
|
155
|
-
...refs.path,
|
|
156
|
-
"items",
|
|
157
|
-
index
|
|
158
|
-
]
|
|
159
|
-
}));
|
|
160
|
-
const prefixSchemas = parsedItems.map((_, length) => z.tuple(parsedItems.slice(0, length)));
|
|
161
|
-
const fullTuple = z.tuple(parsedItems);
|
|
162
|
-
let fullLengthSchema;
|
|
163
|
-
if (jsonSchema.additionalItems === false) fullLengthSchema = fullTuple;
|
|
164
|
-
else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true) fullLengthSchema = fullTuple.rest(parseSchema(jsonSchema.additionalItems, {
|
|
165
|
-
...refs,
|
|
166
|
-
path: [...refs.path, "additionalItems"]
|
|
167
|
-
}));
|
|
168
|
-
else fullLengthSchema = fullTuple.rest(z.any());
|
|
169
|
-
const variants = [...prefixSchemas, fullLengthSchema];
|
|
170
|
-
let tupleSchema = variants.length === 1 ? variants[0] : z.union(variants);
|
|
171
|
-
if (typeof jsonSchema.minItems === "number") tupleSchema = tupleSchema.refine((value) => value.length >= jsonSchema.minItems, { message: `Array must contain at least ${jsonSchema.minItems} element(s)` });
|
|
172
|
-
if (typeof jsonSchema.maxItems === "number") tupleSchema = tupleSchema.refine((value) => value.length <= jsonSchema.maxItems, { message: `Array must contain at most ${jsonSchema.maxItems} element(s)` });
|
|
173
|
-
return tupleSchema;
|
|
174
|
-
}
|
|
175
|
-
let zodSchema = !jsonSchema.items ? z.array(z.any()) : z.array(parseSchema(jsonSchema.items, {
|
|
176
|
-
...refs,
|
|
177
|
-
path: [...refs.path, "items"]
|
|
178
|
-
}));
|
|
179
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
|
|
180
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
|
|
181
|
-
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
182
|
-
...jsonSchema,
|
|
183
|
-
minItems: jsonSchema.min
|
|
184
|
-
}, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
|
|
185
|
-
if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
186
|
-
...jsonSchema,
|
|
187
|
-
maxItems: jsonSchema.max
|
|
188
|
-
}, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
|
|
189
|
-
return zodSchema;
|
|
190
|
-
};
|
|
191
|
-
|
|
192
|
-
//#endregion
|
|
193
|
-
//#region src/parsers/parse-boolean.ts
|
|
194
|
-
const parseBoolean = (_jsonSchema) => {
|
|
195
|
-
return z.boolean();
|
|
196
|
-
};
|
|
197
|
-
|
|
198
|
-
//#endregion
|
|
199
|
-
//#region src/parsers/parse-literal-values.ts
|
|
200
|
-
const parseLiteralValues = (values) => {
|
|
201
|
-
if (values.length === 0) return z.never();
|
|
202
|
-
if (values.every((value) => value === null || typeof value !== "object")) {
|
|
203
|
-
if (values.length === 1) return z.literal(values[0]);
|
|
204
|
-
if (values.every((value) => typeof value === "string")) return z.enum(values);
|
|
205
|
-
return z.union(values.map((value) => z.literal(value)));
|
|
206
|
-
}
|
|
207
|
-
return z.custom((value) => values.some((candidate) => dequal(value, candidate)));
|
|
208
|
-
};
|
|
209
|
-
|
|
210
|
-
//#endregion
|
|
211
|
-
//#region src/parsers/parse-const.ts
|
|
212
|
-
const parseConst = (jsonSchema, refs) => {
|
|
213
|
-
const { const: value, ...baseSchema } = jsonSchema;
|
|
214
|
-
return parseSchema(baseSchema, {
|
|
215
|
-
...refs,
|
|
216
|
-
seen: new Map(refs.seen)
|
|
217
|
-
}, true).and(parseLiteralValues([value]));
|
|
218
|
-
};
|
|
219
|
-
|
|
220
|
-
//#endregion
|
|
221
|
-
//#region src/parsers/parse-default.ts
|
|
222
|
-
const parseDefault = (_jsonSchema) => {
|
|
223
|
-
return z.any();
|
|
224
|
-
};
|
|
225
|
-
|
|
226
|
-
//#endregion
|
|
227
|
-
//#region src/parsers/parse-enum.ts
|
|
228
|
-
const parseEnum = (jsonSchema, refs) => {
|
|
229
|
-
const { enum: values, ...baseSchema } = jsonSchema;
|
|
230
|
-
return parseSchema(baseSchema, {
|
|
231
|
-
...refs,
|
|
232
|
-
seen: new Map(refs.seen)
|
|
233
|
-
}, true).and(parseLiteralValues(values));
|
|
234
|
-
};
|
|
235
|
-
|
|
236
|
-
//#endregion
|
|
237
|
-
//#region src/parsers/parse-if-then-else.ts
|
|
238
|
-
const parseIfThenElse = (jsonSchema, refs) => {
|
|
239
|
-
const $if = parseSchema(jsonSchema.if, {
|
|
240
|
-
...refs,
|
|
241
|
-
path: [...refs.path, "if"]
|
|
242
|
-
});
|
|
243
|
-
const $then = parseSchema(jsonSchema.then, {
|
|
244
|
-
...refs,
|
|
245
|
-
path: [...refs.path, "then"]
|
|
246
|
-
});
|
|
247
|
-
const $else = parseSchema(jsonSchema.else, {
|
|
248
|
-
...refs,
|
|
249
|
-
path: [...refs.path, "else"]
|
|
250
|
-
});
|
|
251
|
-
return z.union([$then, $else]).superRefine((value, ctx) => {
|
|
252
|
-
const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
|
|
253
|
-
if (!result.success) result.error.errors.forEach((error) => ctx.addIssue(error));
|
|
254
|
-
});
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
//#endregion
|
|
258
|
-
//#region src/parsers/parse-multiple-type.ts
|
|
259
|
-
const parseMultipleType = (jsonSchema, refs) => {
|
|
260
|
-
return z.union(jsonSchema.type.map((type) => parseSchema({
|
|
261
|
-
...jsonSchema,
|
|
262
|
-
type
|
|
263
|
-
}, refs)));
|
|
264
|
-
};
|
|
265
|
-
|
|
266
|
-
//#endregion
|
|
267
|
-
//#region src/parsers/parse-not.ts
|
|
268
|
-
const parseNot = (jsonSchema, refs) => {
|
|
269
|
-
return z.any().refine((value) => !parseSchema(jsonSchema.not, {
|
|
270
|
-
...refs,
|
|
271
|
-
path: [...refs.path, "not"]
|
|
272
|
-
}).safeParse(value).success, "Invalid input: Should NOT be valid against schema");
|
|
273
|
-
};
|
|
274
|
-
|
|
275
|
-
//#endregion
|
|
276
|
-
//#region src/parsers/parse-null.ts
|
|
277
|
-
const parseNull = (_jsonSchema) => {
|
|
278
|
-
return z.null();
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
//#endregion
|
|
282
|
-
//#region src/utils/omit.ts
|
|
283
|
-
const omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
|
|
284
|
-
if (!keys.includes(key)) acc[key] = obj[key];
|
|
285
|
-
return acc;
|
|
286
|
-
}, {});
|
|
287
|
-
|
|
288
|
-
//#endregion
|
|
289
|
-
//#region src/parsers/parse-nullable.ts
|
|
290
|
-
/**
|
|
291
|
-
* For compatibility with open api 3.0 nullable
|
|
292
|
-
*/
|
|
293
|
-
const parseNullable = (jsonSchema, refs) => {
|
|
294
|
-
const hasNullDefault = jsonSchema.default === null;
|
|
295
|
-
const baseSchema = hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable");
|
|
296
|
-
const zodSchema = parseSchema(baseSchema, refs, true).nullable();
|
|
297
|
-
return hasNullDefault ? zodSchema.default(null) : zodSchema;
|
|
298
|
-
};
|
|
299
|
-
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region src/parsers/parse-number.ts
|
|
302
|
-
const toDecimalInteger = (value) => {
|
|
303
|
-
if (!Number.isFinite(value)) return void 0;
|
|
304
|
-
const negative = value < 0;
|
|
305
|
-
const [coefficient, exponentText] = Math.abs(value).toString().toLowerCase().split("e");
|
|
306
|
-
const exponent = exponentText === void 0 ? 0 : Number(exponentText);
|
|
307
|
-
const [whole, fraction = ""] = coefficient.split(".");
|
|
308
|
-
let digits = `${whole}${fraction}`.replace(/^0+(?=\d)/, "");
|
|
309
|
-
let scale = fraction.length - exponent;
|
|
310
|
-
if (scale < 0) {
|
|
311
|
-
digits += "0".repeat(-scale);
|
|
312
|
-
scale = 0;
|
|
313
|
-
}
|
|
314
|
-
return {
|
|
315
|
-
integer: BigInt(`${negative ? "-" : ""}${digits}`),
|
|
316
|
-
scale
|
|
317
|
-
};
|
|
318
|
-
};
|
|
319
|
-
const isJsonMultipleOf = (value, multiple) => {
|
|
320
|
-
const dividend = toDecimalInteger(value);
|
|
321
|
-
const divisor = toDecimalInteger(multiple);
|
|
322
|
-
if (!dividend || !divisor || divisor.integer === 0n) return false;
|
|
323
|
-
const scale = Math.max(dividend.scale, divisor.scale);
|
|
324
|
-
return dividend.integer * 10n ** BigInt(scale - dividend.scale) % (divisor.integer * 10n ** BigInt(scale - divisor.scale)) === 0n;
|
|
325
|
-
};
|
|
326
|
-
const parseNumber = (jsonSchema) => {
|
|
327
|
-
let zodSchema = z.number();
|
|
328
|
-
let isInteger = false;
|
|
329
|
-
if (jsonSchema.type === "integer") {
|
|
330
|
-
isInteger = true;
|
|
331
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "type", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
332
|
-
} else if (jsonSchema.format === "int64") {
|
|
333
|
-
isInteger = true;
|
|
334
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
335
|
-
}
|
|
336
|
-
if (typeof jsonSchema.minimum === "number") {
|
|
337
|
-
if (jsonSchema.exclusiveMinimum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg));
|
|
338
|
-
else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
339
|
-
}
|
|
340
|
-
if (typeof jsonSchema.exclusiveMinimum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMinimum", (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg));
|
|
341
|
-
if (typeof jsonSchema.maximum === "number") {
|
|
342
|
-
if (jsonSchema.exclusiveMaximum === true) zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg));
|
|
343
|
-
else zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
344
|
-
}
|
|
345
|
-
if (typeof jsonSchema.exclusiveMaximum === "number") zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMaximum", (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg));
|
|
346
|
-
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
347
|
-
...jsonSchema,
|
|
348
|
-
minimum: jsonSchema.min
|
|
349
|
-
}, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
350
|
-
if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number") zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
351
|
-
...jsonSchema,
|
|
352
|
-
maximum: jsonSchema.max
|
|
353
|
-
}, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
354
|
-
if (typeof jsonSchema.multipleOf === "number") {
|
|
355
|
-
const errorMessage = jsonSchema.errorMessage?.multipleOf;
|
|
356
|
-
if (jsonSchema.multipleOf === 1) return isInteger ? zodSchema : zodSchema.int(errorMessage);
|
|
357
|
-
return zodSchema.refine((value) => isJsonMultipleOf(value, jsonSchema.multipleOf), { message: errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}` });
|
|
358
|
-
}
|
|
359
|
-
return zodSchema;
|
|
360
|
-
};
|
|
361
|
-
|
|
362
|
-
//#endregion
|
|
363
|
-
//#region src/parsers/parse-one-of.ts
|
|
364
|
-
const parseOneOf = (jsonSchema, refs) => {
|
|
365
|
-
if (!jsonSchema.oneOf.length) return z.any();
|
|
366
|
-
if (jsonSchema.oneOf.length === 1) return parseSchema(jsonSchema.oneOf[0], {
|
|
367
|
-
...refs,
|
|
368
|
-
path: [
|
|
369
|
-
...refs.path,
|
|
370
|
-
"oneOf",
|
|
371
|
-
0
|
|
372
|
-
]
|
|
373
|
-
});
|
|
374
|
-
return z.any().superRefine((x, ctx) => {
|
|
375
|
-
const schemas = jsonSchema.oneOf.map((schema, i) => parseSchema(schema, {
|
|
376
|
-
...refs,
|
|
377
|
-
path: [
|
|
378
|
-
...refs.path,
|
|
379
|
-
"oneOf",
|
|
380
|
-
i
|
|
381
|
-
]
|
|
382
|
-
}));
|
|
383
|
-
const unionErrors = schemas.reduce((errors, schema) => ((result) => result.error ? [...errors, result.error] : errors)(schema.safeParse(x)), []);
|
|
384
|
-
if (schemas.length - unionErrors.length !== 1) ctx.addIssue({
|
|
385
|
-
path: ctx.path,
|
|
386
|
-
code: "invalid_union",
|
|
387
|
-
unionErrors,
|
|
388
|
-
message: "Invalid input: Should pass single schema"
|
|
389
|
-
});
|
|
390
|
-
});
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
//#endregion
|
|
394
|
-
//#region src/utils/unicode-pattern.ts
|
|
395
|
-
const compilesAsUnicode = (pattern) => {
|
|
396
|
-
try {
|
|
397
|
-
new RegExp(pattern, "u");
|
|
398
|
-
return true;
|
|
399
|
-
} catch {
|
|
400
|
-
return false;
|
|
401
|
-
}
|
|
402
|
-
};
|
|
403
|
-
const REGEX_SYNTAX_CHARACTERS = /* @__PURE__ */ new Set("^$\\.*+?()[]{}|/");
|
|
404
|
-
const CHARACTER_CLASS_ESCAPES = /* @__PURE__ */ new Set("dDwWsS");
|
|
405
|
-
const CONTROL_ESCAPES$1 = /* @__PURE__ */ new Set("fnrtv");
|
|
406
|
-
const HEX_DIGIT = /^[0-9A-Fa-f]$/;
|
|
407
|
-
const QUANTIFIER = /^\{\d+(?:,\d*)?\}/;
|
|
408
|
-
const hexEscape = (code) => `\\x${code.toString(16).padStart(2, "0")}`;
|
|
409
|
-
/** Capturing group count and whether any is named, as the parser counts them. */
|
|
410
|
-
const scanGroups = (pattern) => {
|
|
411
|
-
let count = 0;
|
|
412
|
-
let named = false;
|
|
413
|
-
let inClass = false;
|
|
414
|
-
for (let index = 0; index < pattern.length; index++) {
|
|
415
|
-
const char = pattern[index];
|
|
416
|
-
if (char === "\\") index++;
|
|
417
|
-
else if (inClass) inClass = char !== "]";
|
|
418
|
-
else if (char === "[") inClass = true;
|
|
419
|
-
else if (char === "(") {
|
|
420
|
-
if (pattern[index + 1] !== "?") count++;
|
|
421
|
-
else if (pattern[index + 2] === "<" && !"=!".includes(pattern[index + 3] ?? "")) {
|
|
422
|
-
count++;
|
|
423
|
-
named = true;
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
return {
|
|
428
|
-
count,
|
|
429
|
-
named
|
|
430
|
-
};
|
|
431
|
-
};
|
|
432
|
-
/**
|
|
433
|
-
* A legacy octal escape (a `\` digit sequence that is not a backreference) as
|
|
434
|
-
* a hex escape. Returns the replacement and how many digits it consumed.
|
|
435
|
-
*/
|
|
436
|
-
const legacyOctalEscape = (pattern, index) => {
|
|
437
|
-
const first = pattern[index];
|
|
438
|
-
if (first === "8" || first === "9") return [first, 1];
|
|
439
|
-
const maxDigits = first <= "3" ? 3 : 2;
|
|
440
|
-
let digits = first;
|
|
441
|
-
while (digits.length < maxDigits && /^[0-7]$/.test(pattern[index + digits.length] ?? "")) digits += pattern[index + digits.length];
|
|
442
|
-
return [hexEscape(parseInt(digits, 8)), digits.length];
|
|
443
|
-
};
|
|
444
|
-
/**
|
|
445
|
-
* The interpreter compiles every pattern with the `u` flag, while
|
|
446
|
-
* `compilePattern` and the native parsers deliberately do not. This spells a
|
|
447
|
-
* pattern written for the legacy (Annex B) grammar in the Unicode grammar with
|
|
448
|
-
* the same meaning: identity escapes such as `\_`, `\:` or `\k` become the
|
|
449
|
-
* literal character, incomplete `\x`, `\u` and `\c` escapes and legacy octal
|
|
450
|
-
* escapes are spelled out, lone `{`, `}` and `]` are escaped, and a hyphen
|
|
451
|
-
* next to a class escape (`[\w-.]`), which is a literal there, is escaped.
|
|
452
|
-
*
|
|
453
|
-
* Returns `undefined` for the few legacy constructs with no Unicode spelling,
|
|
454
|
-
* such as a quantified lookahead. Matching differs only for astral
|
|
455
|
-
* characters, which `.` and negated classes treat as one character, not two.
|
|
456
|
-
*/
|
|
457
|
-
const toUnicodePattern = (pattern) => {
|
|
458
|
-
const { count: groupCount, named: hasNamedGroups } = scanGroups(pattern);
|
|
459
|
-
let rewritten = "";
|
|
460
|
-
let inClass = false;
|
|
461
|
-
let previousAtomWasClassEscape = false;
|
|
462
|
-
let index = 0;
|
|
463
|
-
while (index < pattern.length) {
|
|
464
|
-
const char = pattern[index];
|
|
465
|
-
if (char !== "\\" && inClass) {
|
|
466
|
-
if (char === "]") {
|
|
467
|
-
inClass = false;
|
|
468
|
-
rewritten += char;
|
|
469
|
-
} else if (char === "-" && (previousAtomWasClassEscape || pattern[index + 1] === "\\" && CHARACTER_CLASS_ESCAPES.has(pattern[index + 2] ?? ""))) rewritten += "\\-";
|
|
470
|
-
else rewritten += char;
|
|
471
|
-
previousAtomWasClassEscape = false;
|
|
472
|
-
index++;
|
|
473
|
-
continue;
|
|
474
|
-
}
|
|
475
|
-
if (char !== "\\") {
|
|
476
|
-
const quantifier = char === "{" ? QUANTIFIER.exec(pattern.slice(index)) : null;
|
|
477
|
-
if (char === "[") {
|
|
478
|
-
inClass = true;
|
|
479
|
-
const opening = pattern[index + 1] === "^" ? "[^" : "[";
|
|
480
|
-
rewritten += opening;
|
|
481
|
-
index += opening.length;
|
|
482
|
-
} else if (quantifier) {
|
|
483
|
-
rewritten += quantifier[0];
|
|
484
|
-
index += quantifier[0].length;
|
|
485
|
-
} else {
|
|
486
|
-
rewritten += char === "{" || char === "}" || char === "]" ? `\\${char}` : char;
|
|
487
|
-
index++;
|
|
488
|
-
}
|
|
489
|
-
continue;
|
|
490
|
-
}
|
|
491
|
-
const escaped = pattern[index + 1];
|
|
492
|
-
if (escaped === void 0) return;
|
|
493
|
-
previousAtomWasClassEscape = false;
|
|
494
|
-
if (CHARACTER_CLASS_ESCAPES.has(escaped)) {
|
|
495
|
-
previousAtomWasClassEscape = inClass;
|
|
496
|
-
rewritten += `\\${escaped}`;
|
|
497
|
-
index += 2;
|
|
498
|
-
} else if (CONTROL_ESCAPES$1.has(escaped) || REGEX_SYNTAX_CHARACTERS.has(escaped) || escaped === "b" || escaped === "B" && !inClass || escaped === "-" && inClass || escaped === "k" && hasNamedGroups && !inClass) {
|
|
499
|
-
rewritten += `\\${escaped}`;
|
|
500
|
-
index += 2;
|
|
501
|
-
} else if (escaped === "c") {
|
|
502
|
-
const letter = pattern[index + 2] ?? "";
|
|
503
|
-
if (/^[A-Za-z]$/.test(letter)) {
|
|
504
|
-
rewritten += `\\c${letter}`;
|
|
505
|
-
index += 3;
|
|
506
|
-
} else if (inClass && /^[0-9_]$/.test(letter)) {
|
|
507
|
-
rewritten += hexEscape(letter.charCodeAt(0) % 32);
|
|
508
|
-
index += 3;
|
|
509
|
-
} else {
|
|
510
|
-
rewritten += "\\\\";
|
|
511
|
-
index++;
|
|
512
|
-
}
|
|
513
|
-
} else if (escaped === "x" || escaped === "u") {
|
|
514
|
-
const length = escaped === "x" ? 2 : 4;
|
|
515
|
-
const digits = pattern.slice(index + 2, index + 2 + length);
|
|
516
|
-
if (digits.length === length && [...digits].every((digit) => HEX_DIGIT.test(digit))) {
|
|
517
|
-
rewritten += `\\${escaped}${digits}`;
|
|
518
|
-
index += 2 + length;
|
|
519
|
-
} else {
|
|
520
|
-
rewritten += escaped;
|
|
521
|
-
index += 2;
|
|
522
|
-
}
|
|
523
|
-
} else if (/^[0-9]$/.test(escaped)) {
|
|
524
|
-
const decimal = /^\d+/.exec(pattern.slice(index + 1))?.[0] ?? escaped;
|
|
525
|
-
if (escaped === "0" && !/^[0-9]$/.test(pattern[index + 2] ?? "")) {
|
|
526
|
-
rewritten += "\\0";
|
|
527
|
-
index += 2;
|
|
528
|
-
} else if (!inClass && escaped !== "0" && Number(decimal) <= groupCount) {
|
|
529
|
-
rewritten += `\\${decimal}`;
|
|
530
|
-
index += 1 + decimal.length;
|
|
531
|
-
} else {
|
|
532
|
-
const [replacement, consumed] = legacyOctalEscape(pattern, index + 1);
|
|
533
|
-
rewritten += replacement;
|
|
534
|
-
index += 1 + consumed;
|
|
535
|
-
}
|
|
536
|
-
} else {
|
|
537
|
-
rewritten += escaped;
|
|
538
|
-
index += 2;
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
return compilesAsUnicode(rewritten) ? rewritten : void 0;
|
|
542
|
-
};
|
|
543
|
-
|
|
544
|
-
//#endregion
|
|
545
|
-
//#region src/utils/linear-pattern.ts
|
|
546
|
-
/**
|
|
547
|
-
* ECMAScript `\s`: the characters it matches, spelled for an RE2 class body.
|
|
548
|
-
* RE2's own `\s` is ASCII-only, so both `\s` and `\S` are spelled out.
|
|
549
|
-
*/
|
|
550
|
-
const WHITESPACE = "\\t\\n\\x{B}\\f\\r\\x{20}\\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{2028}\\x{2029}\\x{202F}\\x{205F}\\x{3000}\\x{FEFF}";
|
|
551
|
-
/** The complement of {@link WHITESPACE}, usable inside another class. */
|
|
552
|
-
const NON_WHITESPACE = "\\x{0}-\\x{8}\\x{E}-\\x{1F}\\x{21}-\\x{9F}\\x{A1}-\\x{167F}\\x{1681}-\\x{1FFF}\\x{200B}-\\x{2027}\\x{202A}-\\x{202E}\\x{2030}-\\x{205E}\\x{2060}-\\x{2FFF}\\x{3001}-\\x{FEFE}\\x{FF00}-\\x{10FFFF}";
|
|
553
|
-
const ANY_CHARACTER = "\\x{0}-\\x{10FFFF}";
|
|
554
|
-
/** ECMAScript `.` without the `s` flag excludes every line terminator, not just `\n`. */
|
|
555
|
-
const DOT = "[^\\n\\r\\x{2028}\\x{2029}]";
|
|
556
|
-
const SYNTAX_CHARACTERS = /* @__PURE__ */ new Set("^$\\.*+?()[]{}|/-");
|
|
557
|
-
const CONTROL_ESCAPES = /* @__PURE__ */ new Set("fnrtv");
|
|
558
|
-
const PASSTHROUGH_CLASS_ESCAPES = /* @__PURE__ */ new Set("dDwW");
|
|
559
|
-
const codePoint = (code) => `\\x{${code.toString(16).toUpperCase()}}`;
|
|
560
|
-
/** Thrown inside the translator for constructs RE2 cannot express. */
|
|
561
|
-
var Unsupported = class extends Error {};
|
|
562
|
-
/**
|
|
563
|
-
* Reads one escape at `pattern[index] === '\\'` that is valid in both a class
|
|
564
|
-
* and the top level, returning its RE2 spelling and the index after it.
|
|
565
|
-
*/
|
|
566
|
-
const readEscape = (pattern, index, inClass) => {
|
|
567
|
-
const escaped = pattern[index + 1] ?? "";
|
|
568
|
-
if (PASSTHROUGH_CLASS_ESCAPES.has(escaped) || CONTROL_ESCAPES.has(escaped)) return [`\\${escaped}`, index + 2];
|
|
569
|
-
if (escaped === "s") return [inClass ? WHITESPACE : `[${WHITESPACE}]`, index + 2];
|
|
570
|
-
if (escaped === "S") return [inClass ? NON_WHITESPACE : `[^${WHITESPACE}]`, index + 2];
|
|
571
|
-
if (escaped === "b" || escaped === "B") return [inClass ? codePoint(8) : `\\${escaped}`, index + 2];
|
|
572
|
-
if (escaped === "0") return [codePoint(0), index + 2];
|
|
573
|
-
if (escaped === "c") return [codePoint(pattern.charCodeAt(index + 2) % 32), index + 3];
|
|
574
|
-
if (escaped === "x") return [codePoint(parseInt(pattern.slice(index + 2, index + 4), 16)), index + 4];
|
|
575
|
-
if (escaped === "u") {
|
|
576
|
-
if (pattern[index + 2] === "{") {
|
|
577
|
-
const end = pattern.indexOf("}", index + 3);
|
|
578
|
-
return [codePoint(parseInt(pattern.slice(index + 3, end), 16)), end + 1];
|
|
579
|
-
}
|
|
580
|
-
const unit = parseInt(pattern.slice(index + 2, index + 6), 16);
|
|
581
|
-
const low = /^\\u([Dd][C-Fc-f][0-9A-Fa-f]{2})/.exec(pattern.slice(index + 6));
|
|
582
|
-
if (unit >= 55296 && unit <= 56319 && low) {
|
|
583
|
-
const combined = (unit - 55296) * 1024 + (parseInt(low[1], 16) - 56320) + 65536;
|
|
584
|
-
return [codePoint(combined), index + 12];
|
|
585
|
-
}
|
|
586
|
-
return [codePoint(unit), index + 6];
|
|
587
|
-
}
|
|
588
|
-
if (SYNTAX_CHARACTERS.has(escaped)) return [`\\${escaped}`, index + 2];
|
|
589
|
-
throw new Unsupported();
|
|
590
|
-
};
|
|
591
|
-
/** Translates a class starting at `pattern[index] === '['`. */
|
|
592
|
-
const readClass = (pattern, index) => {
|
|
593
|
-
let cursor = index + 1;
|
|
594
|
-
const negated = pattern[cursor] === "^";
|
|
595
|
-
if (negated) cursor++;
|
|
596
|
-
if (pattern[cursor] === "]") return [negated ? `[${ANY_CHARACTER}]` : `[^${ANY_CHARACTER}]`, cursor + 1];
|
|
597
|
-
let body = "";
|
|
598
|
-
while (pattern[cursor] !== "]") {
|
|
599
|
-
const char = pattern[cursor];
|
|
600
|
-
if (char === "\\") {
|
|
601
|
-
const [spelled, next] = readEscape(pattern, cursor, true);
|
|
602
|
-
body += spelled;
|
|
603
|
-
cursor = next;
|
|
604
|
-
} else {
|
|
605
|
-
body += char === "[" || char === "^" ? `\\${char}` : char;
|
|
606
|
-
cursor += char.length;
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
return [`[${negated ? "^" : ""}${body}]`, cursor + 1];
|
|
610
|
-
};
|
|
611
|
-
/**
|
|
612
|
-
* Translates a pattern written in the ECMAScript Unicode (`u` flag) grammar
|
|
613
|
-
* into RE2 syntax with the same meaning. The input must already compile with
|
|
614
|
-
* the `u` flag. Returns `undefined` for constructs that need a backtracking
|
|
615
|
-
* engine (lookaround, backreferences) or that RE2 spells differently.
|
|
616
|
-
*/
|
|
617
|
-
const unicodePatternToRe2 = (pattern) => {
|
|
618
|
-
let result = "";
|
|
619
|
-
let index = 0;
|
|
620
|
-
try {
|
|
621
|
-
while (index < pattern.length) {
|
|
622
|
-
const char = pattern[index];
|
|
623
|
-
if (char === "\\") {
|
|
624
|
-
const [spelled, next] = readEscape(pattern, index, false);
|
|
625
|
-
result += spelled;
|
|
626
|
-
index = next;
|
|
627
|
-
} else if (char === "[") {
|
|
628
|
-
const [spelled, next] = readClass(pattern, index);
|
|
629
|
-
result += spelled;
|
|
630
|
-
index = next;
|
|
631
|
-
} else if (char === ".") {
|
|
632
|
-
result += DOT;
|
|
633
|
-
index++;
|
|
634
|
-
} else if (char === "(" && pattern[index + 1] === "?") {
|
|
635
|
-
if (pattern[index + 2] === ":") {
|
|
636
|
-
result += "(?:";
|
|
637
|
-
index += 3;
|
|
638
|
-
} else if (pattern[index + 2] === "<" && !"=!".includes(pattern[index + 3] ?? "")) {
|
|
639
|
-
result += "(";
|
|
640
|
-
index = pattern.indexOf(">", index) + 1;
|
|
641
|
-
} else throw new Unsupported();
|
|
642
|
-
} else {
|
|
643
|
-
result += char;
|
|
644
|
-
index++;
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
} catch (error) {
|
|
648
|
-
if (error instanceof Unsupported) return;
|
|
649
|
-
throw error;
|
|
650
|
-
}
|
|
651
|
-
return result;
|
|
652
|
-
};
|
|
653
|
-
/**
|
|
654
|
-
* Compiles a Unicode-grammar pattern for RE2JS, whose matching time is linear
|
|
655
|
-
* in the input for every pattern. Returns `undefined` when RE2 cannot express
|
|
656
|
-
* the pattern.
|
|
657
|
-
*/
|
|
658
|
-
const compileLinearPattern = (unicodePattern) => {
|
|
659
|
-
const re2 = unicodePatternToRe2(unicodePattern);
|
|
660
|
-
if (re2 === void 0) return;
|
|
661
|
-
try {
|
|
662
|
-
return RE2JS.compile(re2);
|
|
663
|
-
} catch {
|
|
664
|
-
return;
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
/** A quantifier whose range (maximum minus minimum) exceeds this counts as unbounded. */
|
|
668
|
-
const LARGE_QUANTIFIER_RANGE = 16;
|
|
669
|
-
/** Bound on the product of the ranges of all small variable quantifiers. */
|
|
670
|
-
const MAX_SMALL_QUANTIFIER_PRODUCT = 64;
|
|
671
|
-
/** Absolute explicit repeat bounds, including repetitions of zero-width assertions. */
|
|
672
|
-
const MAX_FALLBACK_REPEAT_COUNT = 64;
|
|
673
|
-
/** Bound on the polynomial degree of the backtracking search in the input length. */
|
|
674
|
-
const MAX_BACKTRACKING_DEGREE = 2;
|
|
675
|
-
const BRACE_QUANTIFIER = /^\{(\d+)(,(\d*))?\}/;
|
|
676
|
-
/**
|
|
677
|
-
* Whether a pattern that RE2 cannot run (it needs lookaround or a
|
|
678
|
-
* backreference) is still safe for the native backtracking engine on short
|
|
679
|
-
* input. Deliberately conservative, since only such patterns reach it:
|
|
680
|
-
*
|
|
681
|
-
* - no backreferences;
|
|
682
|
-
* - no quantified group that contains a quantifier or an alternation, the
|
|
683
|
-
* shapes behind exponential backtracking (`(a+)+`, `(a|a)*`);
|
|
684
|
-
* - no lookaround nested in another lookaround;
|
|
685
|
-
* - explicit repetition bounds are capped, including fixed assertions;
|
|
686
|
-
* - the search is at most quadratic: one degree for an unanchored start, plus
|
|
687
|
-
* the number of unbounded quantifiers at the top level, plus the largest
|
|
688
|
-
* number inside a single lookaround (lookarounds are atomic, so they add
|
|
689
|
-
* rather than multiply);
|
|
690
|
-
* - small variable quantifiers (`?`, `{1,3}`) and alternations multiply the
|
|
691
|
-
* work by a bounded constant (`(?:a|aa)(?:a|aa)...b` is exponential without
|
|
692
|
-
* any quantifier).
|
|
693
|
-
* A leading anchor removes search work only without a top-level alternative.
|
|
694
|
-
*
|
|
695
|
-
* Callers still bound the input length, which keeps the quadratic case cheap.
|
|
696
|
-
*/
|
|
697
|
-
const isSafeForBacktracking = (pattern) => {
|
|
698
|
-
const hasNamedGroup = /\(\?<(?![=!])/.test(pattern);
|
|
699
|
-
const newGroup = (lookaround) => ({
|
|
700
|
-
lookaround,
|
|
701
|
-
quantified: false,
|
|
702
|
-
alternation: false,
|
|
703
|
-
branches: 1
|
|
704
|
-
});
|
|
705
|
-
const stack = [newGroup(false)];
|
|
706
|
-
let topLevelLarge = 0;
|
|
707
|
-
let lookaroundLarge = 0;
|
|
708
|
-
let maxLookaroundLarge = 0;
|
|
709
|
-
let smallProduct = 1;
|
|
710
|
-
let lastAtomGroup;
|
|
711
|
-
let index = 0;
|
|
712
|
-
const insideLookaround = () => stack.some((group) => group.lookaround);
|
|
713
|
-
const multiply = (factor) => {
|
|
714
|
-
smallProduct *= factor;
|
|
715
|
-
return smallProduct <= MAX_SMALL_QUANTIFIER_PRODUCT;
|
|
716
|
-
};
|
|
717
|
-
while (index < pattern.length) {
|
|
718
|
-
const char = pattern[index];
|
|
719
|
-
const current = stack[stack.length - 1];
|
|
720
|
-
let quantifierLength = 0;
|
|
721
|
-
let range = 0;
|
|
722
|
-
if (char === "*" || char === "+") {
|
|
723
|
-
quantifierLength = 1;
|
|
724
|
-
range = Infinity;
|
|
725
|
-
} else if (char === "?") {
|
|
726
|
-
quantifierLength = 1;
|
|
727
|
-
range = 1;
|
|
728
|
-
} else if (char === "{") {
|
|
729
|
-
const brace = BRACE_QUANTIFIER.exec(pattern.slice(index));
|
|
730
|
-
if (brace) {
|
|
731
|
-
quantifierLength = brace[0].length;
|
|
732
|
-
const minimum = Number(brace[1]);
|
|
733
|
-
const maximum = brace[2] === void 0 ? minimum : Number(brace[3]);
|
|
734
|
-
if (minimum > MAX_FALLBACK_REPEAT_COUNT || brace[3] !== "" && maximum > MAX_FALLBACK_REPEAT_COUNT) return false;
|
|
735
|
-
if (brace[2] !== void 0) range = brace[3] === "" ? Infinity : Number(brace[3]) - Number(brace[1]);
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
if (quantifierLength > 0) {
|
|
739
|
-
if (lastAtomGroup && (lastAtomGroup.quantified || lastAtomGroup.alternation)) return false;
|
|
740
|
-
if (range > LARGE_QUANTIFIER_RANGE) {
|
|
741
|
-
if (insideLookaround()) maxLookaroundLarge = Math.max(maxLookaroundLarge, ++lookaroundLarge);
|
|
742
|
-
else topLevelLarge++;
|
|
743
|
-
} else if (range > 0 && !multiply(range + 1)) return false;
|
|
744
|
-
current.quantified = true;
|
|
745
|
-
index += quantifierLength;
|
|
746
|
-
if (pattern[index] === "?") index++;
|
|
747
|
-
lastAtomGroup = void 0;
|
|
748
|
-
continue;
|
|
749
|
-
}
|
|
750
|
-
lastAtomGroup = void 0;
|
|
751
|
-
if (char === "\\") {
|
|
752
|
-
const escaped = pattern[index + 1] ?? "";
|
|
753
|
-
if (/^[1-9]$/.test(escaped) || escaped === "k" && hasNamedGroup) return false;
|
|
754
|
-
index += 2;
|
|
755
|
-
} else if (char === "[") {
|
|
756
|
-
index++;
|
|
757
|
-
while (index < pattern.length && pattern[index] !== "]") index += pattern[index] === "\\" ? 2 : 1;
|
|
758
|
-
index++;
|
|
759
|
-
} else if (char === "(") {
|
|
760
|
-
const lookaround = pattern[index + 1] === "?" && ("=!".includes(pattern[index + 2] ?? "") || pattern[index + 2] === "<" && "=!".includes(pattern[index + 3] ?? ""));
|
|
761
|
-
if (lookaround) {
|
|
762
|
-
if (insideLookaround()) return false;
|
|
763
|
-
lookaroundLarge = 0;
|
|
764
|
-
}
|
|
765
|
-
stack.push(newGroup(lookaround));
|
|
766
|
-
index++;
|
|
767
|
-
if (pattern[index] === "?") index += lookaround && pattern[index + 1] === "<" ? 3 : 2;
|
|
768
|
-
} else if (char === ")") {
|
|
769
|
-
const closed = stack.length > 1 ? stack.pop() : current;
|
|
770
|
-
if (!multiply(closed.branches)) return false;
|
|
771
|
-
const parent = stack[stack.length - 1];
|
|
772
|
-
parent.quantified ||= closed.quantified;
|
|
773
|
-
parent.alternation ||= closed.alternation;
|
|
774
|
-
lastAtomGroup = closed;
|
|
775
|
-
index++;
|
|
776
|
-
} else {
|
|
777
|
-
if (char === "|") {
|
|
778
|
-
current.alternation = true;
|
|
779
|
-
current.branches++;
|
|
780
|
-
}
|
|
781
|
-
index++;
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
if (!multiply(stack[0].branches)) return false;
|
|
785
|
-
return (pattern.startsWith("^") && stack[0].branches === 1 ? 0 : 1) + topLevelLarge + maxLookaroundLarge <= MAX_BACKTRACKING_DEGREE;
|
|
786
|
-
};
|
|
787
|
-
/**
|
|
788
|
-
* Longest input the backtracking fallback runs on. Longer input is treated as
|
|
789
|
-
* matching: skipping a constraint only widens what the schema accepts, which
|
|
790
|
-
* a hostile schema could do anyway by omitting the pattern.
|
|
791
|
-
*/
|
|
792
|
-
const MAX_BACKTRACKING_INPUT_LENGTH = 1e3;
|
|
793
|
-
/**
|
|
794
|
-
* Builds the matcher for a schema pattern in the legacy (no `u` flag) grammar
|
|
795
|
-
* the rest of this package accepts. `pattern` must already compile as a
|
|
796
|
-
* `RegExp`.
|
|
797
|
-
*/
|
|
798
|
-
const createPatternMatcher = (pattern) => {
|
|
799
|
-
const unicodePattern = toUnicodePattern(pattern);
|
|
800
|
-
const linear = unicodePattern === void 0 ? void 0 : compileLinearPattern(unicodePattern);
|
|
801
|
-
if (linear !== void 0) return {
|
|
802
|
-
kind: "linear",
|
|
803
|
-
regex: linear
|
|
804
|
-
};
|
|
805
|
-
if (isSafeForBacktracking(pattern)) return {
|
|
806
|
-
kind: "backtracking",
|
|
807
|
-
regex: new RegExp(pattern)
|
|
808
|
-
};
|
|
809
|
-
return { kind: "unenforced" };
|
|
810
|
-
};
|
|
811
|
-
/** Whether `input` satisfies the pattern behind `matcher`. */
|
|
812
|
-
const patternMatches = (matcher, input) => {
|
|
813
|
-
switch (matcher.kind) {
|
|
814
|
-
case "linear": return matcher.regex.test(input);
|
|
815
|
-
case "backtracking":
|
|
816
|
-
if (input.length > 1e3) return true;
|
|
817
|
-
matcher.regex.lastIndex = 0;
|
|
818
|
-
return matcher.regex.test(input);
|
|
819
|
-
case "unenforced": return true;
|
|
820
|
-
}
|
|
821
|
-
};
|
|
822
|
-
|
|
823
|
-
//#endregion
|
|
824
|
-
//#region src/utils/compile-pattern.ts
|
|
825
|
-
/**
|
|
826
|
-
* Longest `pattern` / `patternProperties` key this package compiles. Tool
|
|
827
|
-
* schemas come from third-party toolkit definitions; anything past this is
|
|
828
|
-
* far outside what a format constraint needs and is rejected before it can
|
|
829
|
-
* cost anything at validation time.
|
|
830
|
-
*/
|
|
831
|
-
const MAX_PATTERN_LENGTH = 1024;
|
|
832
|
-
/**
|
|
833
|
-
* Raised at conversion time when a schema `pattern` cannot be turned into a
|
|
834
|
-
* `RegExp`. Conversion fails eagerly, in line with how this package and
|
|
835
|
-
* `@composio/json-schema-to-effect-schema` treat other schema defects: a broken
|
|
836
|
-
* schema is the tool author's bug, so it surfaces once at construction rather
|
|
837
|
-
* than on every validation as if the caller's input were wrong.
|
|
838
|
-
*/
|
|
839
|
-
var InvalidPatternError = class extends Error {
|
|
840
|
-
keyword;
|
|
841
|
-
pattern;
|
|
842
|
-
path;
|
|
843
|
-
reason;
|
|
844
|
-
name = "InvalidPatternError";
|
|
845
|
-
constructor(keyword, pattern, path, reason, detail, options) {
|
|
846
|
-
const location = path.length > 0 ? path.join(".") : "<root>";
|
|
847
|
-
super(`Invalid ${keyword} regular expression ${JSON.stringify(pattern)} at ${location}: ${detail}`, options);
|
|
848
|
-
this.keyword = keyword;
|
|
849
|
-
this.pattern = pattern;
|
|
850
|
-
this.path = path;
|
|
851
|
-
this.reason = reason;
|
|
852
|
-
}
|
|
853
|
-
};
|
|
854
|
-
/**
|
|
855
|
-
* A schema pattern as a `RegExp` whose matching cannot be made to backtrack
|
|
856
|
-
* catastrophically. The native `source` stays intact, so JSON Schema emitted
|
|
857
|
-
* from the Zod schema still carries the original pattern for the model, while
|
|
858
|
-
* `test` and `exec` go through a {@link PatternMatcher}: RE2 where it can run
|
|
859
|
-
* the pattern, otherwise a statically vetted, length-bounded native match, or
|
|
860
|
-
* no check at all.
|
|
861
|
-
*/
|
|
862
|
-
var SchemaPatternRegExp = class extends RegExp {
|
|
863
|
-
matcher;
|
|
864
|
-
constructor(pattern, matcher = createPatternMatcher(pattern)) {
|
|
865
|
-
super(pattern);
|
|
866
|
-
this.matcher = matcher;
|
|
867
|
-
}
|
|
868
|
-
test(input) {
|
|
869
|
-
return patternMatches(this.matcher, String(input));
|
|
870
|
-
}
|
|
871
|
-
exec(input) {
|
|
872
|
-
const string = String(input);
|
|
873
|
-
switch (this.matcher.kind) {
|
|
874
|
-
case "linear": return this.matcher.regex.exec(string);
|
|
875
|
-
case "backtracking": return patternMatches(this.matcher, string) ? this.matcher.regex.exec(string) : null;
|
|
876
|
-
case "unenforced": return null;
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
|
-
static get [Symbol.species]() {
|
|
880
|
-
return RegExp;
|
|
881
|
-
}
|
|
882
|
-
};
|
|
883
|
-
/**
|
|
884
|
-
* Compile a schema pattern, rejecting anything that does not compile or that
|
|
885
|
-
* exceeds {@link MAX_PATTERN_LENGTH}.
|
|
886
|
-
*
|
|
887
|
-
* Matching is protected against catastrophic backtracking (ReDoS): tool
|
|
888
|
-
* arguments come from a model that may be steered by untrusted content, and
|
|
889
|
-
* object keys are as attacker-influenced as values. Patterns run on RE2,
|
|
890
|
-
* which is linear-time. A `pattern` RE2 cannot express (lookaround) falls back
|
|
891
|
-
* to the native engine only when it passes a conservative static check, and
|
|
892
|
-
* only on bounded input; otherwise it is left unenforced, which widens the
|
|
893
|
-
* schema no further than omitting the pattern would. A `patternProperties`
|
|
894
|
-
* key decides which schema applies to a property, so it is never silently
|
|
895
|
-
* skipped: one RE2 cannot express is rejected at conversion.
|
|
896
|
-
*
|
|
897
|
-
* No `u` flag is passed: existing tool schemas rely on identity escapes that
|
|
898
|
-
* Unicode mode refuses, and the goal here is to fail on defects, not to
|
|
899
|
-
* tighten which patterns are accepted.
|
|
900
|
-
*/
|
|
901
|
-
const compilePattern = (keyword, pattern, refs) => {
|
|
902
|
-
const path = keyword === "pattern" ? refs.path : [
|
|
903
|
-
...refs.path,
|
|
904
|
-
"patternProperties",
|
|
905
|
-
pattern
|
|
906
|
-
];
|
|
907
|
-
if (pattern.length > 1024) throw new InvalidPatternError(keyword, pattern, path, "too-long", `pattern exceeds ${MAX_PATTERN_LENGTH} characters`);
|
|
908
|
-
try {
|
|
909
|
-
new RegExp(pattern);
|
|
910
|
-
} catch (cause) {
|
|
911
|
-
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
912
|
-
throw new InvalidPatternError(keyword, pattern, path, "syntax", detail, { cause });
|
|
913
|
-
}
|
|
914
|
-
const matcher = createPatternMatcher(pattern);
|
|
915
|
-
if (keyword === "patternProperties" && matcher.kind !== "linear") throw new InvalidPatternError(keyword, pattern, path, "unsupported", "patternProperties keys must not use lookaround or backreferences");
|
|
916
|
-
return new SchemaPatternRegExp(pattern, matcher);
|
|
917
|
-
};
|
|
918
|
-
|
|
919
|
-
//#endregion
|
|
920
|
-
//#region src/parsers/parse-object.ts
|
|
921
|
-
/**
|
|
922
|
-
* Build the static part of an object parser, or `undefined` when the schema
|
|
923
|
-
* declares no named properties.
|
|
924
|
-
*
|
|
925
|
-
* A property-less object (`properties` absent or `{}`) deliberately returns
|
|
926
|
-
* `undefined` so the caller can apply the open-object policy. This supersedes
|
|
927
|
-
* an earlier `z.object({})` fallback that was kept "or else this will break
|
|
928
|
-
* openai responses": collapsing `{ type: "object" }` to a strict empty object
|
|
929
|
-
* is the defect it was masking, and the OpenAI provider suite is part of this
|
|
930
|
-
* package's verification precisely so the claim stays checked.
|
|
931
|
-
*/
|
|
932
|
-
function parseObjectProperties(objectSchema, refs) {
|
|
933
|
-
if (!objectSchema.properties) return;
|
|
934
|
-
const propertyKeys = Object.keys(objectSchema.properties);
|
|
935
|
-
if (propertyKeys.length === 0) return;
|
|
936
|
-
const properties = {};
|
|
937
|
-
for (const key of propertyKeys) {
|
|
938
|
-
const propJsonSchema = objectSchema.properties[key];
|
|
939
|
-
const propZodSchema = parseSchema(propJsonSchema, {
|
|
940
|
-
...refs,
|
|
941
|
-
path: [
|
|
942
|
-
...refs.path,
|
|
943
|
-
"properties",
|
|
944
|
-
key
|
|
945
|
-
]
|
|
946
|
-
});
|
|
947
|
-
const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
|
|
948
|
-
if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) {
|
|
949
|
-
if (propJsonSchema.default === null) {
|
|
950
|
-
const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
951
|
-
const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
952
|
-
const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
|
|
953
|
-
if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) properties[key] = propZodSchema.optional().default(null);
|
|
954
|
-
else properties[key] = propZodSchema.nullable().optional().default(null);
|
|
955
|
-
} else properties[key] = propZodSchema.optional().default(propJsonSchema.default);
|
|
956
|
-
} else properties[key] = required ? propZodSchema : propZodSchema.optional();
|
|
957
|
-
}
|
|
958
|
-
return z$1.object(properties);
|
|
959
|
-
}
|
|
960
|
-
/**
|
|
961
|
-
* Object parser for schemas carrying `patternProperties`.
|
|
962
|
-
*
|
|
963
|
-
* Every key is routed to exactly the schemas that apply to it — each matching
|
|
964
|
-
* pattern, and `additionalProperties` only when no pattern and no named
|
|
965
|
-
* property claims the key. A catch-all union would instead let a key sneak past
|
|
966
|
-
* its own pattern by satisfying an unrelated one.
|
|
967
|
-
*/
|
|
968
|
-
function parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs) {
|
|
969
|
-
const patterns = Object.entries(normalizedSchema.patternProperties ?? {}).map(([pattern, schema]) => ({
|
|
970
|
-
regex: compilePattern("patternProperties", pattern, refs),
|
|
971
|
-
parser: parseSchema(schema, {
|
|
972
|
-
...refs,
|
|
973
|
-
path: [
|
|
974
|
-
...refs.path,
|
|
975
|
-
"patternProperties",
|
|
976
|
-
pattern
|
|
977
|
-
]
|
|
978
|
-
})
|
|
979
|
-
}));
|
|
980
|
-
const declaredKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
|
|
981
|
-
const rejectsUnmatched = additionalProperties instanceof z$1.ZodNever || additionalProperties === void 0 && declaredKeys.size > 0;
|
|
982
|
-
const validatesUnmatched = additionalProperties !== void 0 && !(additionalProperties instanceof z$1.ZodNever) && normalizedSchema.additionalProperties !== true;
|
|
983
|
-
return (propertiesSchema ?? z$1.object({})).passthrough().transform((value, ctx) => {
|
|
984
|
-
const result = { ...value };
|
|
985
|
-
const unrecognizedKeys = [];
|
|
986
|
-
for (const key of Object.keys(value)) {
|
|
987
|
-
const matching = patterns.filter(({ regex }) => regex.test(key));
|
|
988
|
-
for (const { parser } of matching) {
|
|
989
|
-
const parsed = parser.safeParse(value[key]);
|
|
990
|
-
if (!parsed.success) ctx.addIssue({
|
|
991
|
-
path: [...ctx.path, key],
|
|
992
|
-
code: "custom",
|
|
993
|
-
message: `Invalid input: key "${key}" must match its patternProperties schema`,
|
|
994
|
-
params: { issues: parsed.error.issues }
|
|
995
|
-
});
|
|
996
|
-
else if (!declaredKeys.has(key)) result[key] = parsed.data;
|
|
997
|
-
}
|
|
998
|
-
if (matching.length > 0 || declaredKeys.has(key)) continue;
|
|
999
|
-
if (rejectsUnmatched) unrecognizedKeys.push(key);
|
|
1000
|
-
else if (validatesUnmatched) {
|
|
1001
|
-
const parsed = additionalProperties.safeParse(value[key]);
|
|
1002
|
-
if (!parsed.success) ctx.addIssue({
|
|
1003
|
-
path: [...ctx.path, key],
|
|
1004
|
-
code: "custom",
|
|
1005
|
-
message: `Invalid input: key "${key}" must match the additionalProperties schema`,
|
|
1006
|
-
params: { issues: parsed.error.issues }
|
|
1007
|
-
});
|
|
1008
|
-
else result[key] = parsed.data;
|
|
1009
|
-
}
|
|
1010
|
-
}
|
|
1011
|
-
if (unrecognizedKeys.length > 0) ctx.addIssue({
|
|
1012
|
-
path: [...ctx.path],
|
|
1013
|
-
code: "unrecognized_keys",
|
|
1014
|
-
keys: unrecognizedKeys,
|
|
1015
|
-
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
1016
|
-
});
|
|
1017
|
-
return result;
|
|
1018
|
-
});
|
|
1019
|
-
}
|
|
1020
|
-
function parseObject(objectSchema, refs) {
|
|
1021
|
-
const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
|
|
1022
|
-
const normalizedSchema = objectSchema.type === "object" ? objectSchema : {
|
|
1023
|
-
...objectSchema,
|
|
1024
|
-
type: "object"
|
|
1025
|
-
};
|
|
1026
|
-
const propertiesSchema = parseObjectProperties(normalizedSchema, refs);
|
|
1027
|
-
const additionalProperties = normalizedSchema.additionalProperties !== void 0 ? parseSchema(normalizedSchema.additionalProperties, {
|
|
1028
|
-
...refs,
|
|
1029
|
-
path: [...refs.path, "additionalProperties"]
|
|
1030
|
-
}) : void 0;
|
|
1031
|
-
const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
|
|
1032
|
-
let output;
|
|
1033
|
-
if (hasPatternProperties) output = parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs);
|
|
1034
|
-
else if (propertiesSchema) {
|
|
1035
|
-
if (additionalProperties) {
|
|
1036
|
-
if (additionalProperties instanceof z$1.ZodNever) output = propertiesSchema.strict();
|
|
1037
|
-
else if (isAdditionalPropertiesTrue) output = propertiesSchema.passthrough();
|
|
1038
|
-
else output = propertiesSchema.catchall(additionalProperties);
|
|
1039
|
-
} else output = propertiesSchema.strict();
|
|
1040
|
-
} else if (additionalProperties) {
|
|
1041
|
-
if (additionalProperties instanceof z$1.ZodNever) output = z$1.object({}).strict();
|
|
1042
|
-
else if (isAdditionalPropertiesTrue) output = z$1.object({}).passthrough();
|
|
1043
|
-
else output = z$1.record(additionalProperties);
|
|
1044
|
-
} else output = z$1.object({}).passthrough();
|
|
1045
|
-
if (its.an.anyOf(objectSchema)) output = output.and(parseAnyOf({
|
|
1046
|
-
...objectSchema,
|
|
1047
|
-
anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
1048
|
-
...x,
|
|
1049
|
-
type: "object"
|
|
1050
|
-
} : x)
|
|
1051
|
-
}, refs));
|
|
1052
|
-
if (its.a.oneOf(objectSchema)) output = output.and(parseOneOf({
|
|
1053
|
-
...objectSchema,
|
|
1054
|
-
oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
1055
|
-
...x,
|
|
1056
|
-
type: "object"
|
|
1057
|
-
} : x)
|
|
1058
|
-
}, refs));
|
|
1059
|
-
if (its.an.allOf(objectSchema)) output = output.and(parseAllOf({
|
|
1060
|
-
...objectSchema,
|
|
1061
|
-
allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
1062
|
-
...x,
|
|
1063
|
-
type: "object"
|
|
1064
|
-
} : x)
|
|
1065
|
-
}, refs));
|
|
1066
|
-
return output;
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
//#endregion
|
|
1070
|
-
//#region src/parsers/parse-string.ts
|
|
1071
|
-
const parseString = (jsonSchema, refs) => {
|
|
1072
|
-
let zodSchema = z.string();
|
|
1073
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => {
|
|
1074
|
-
switch (format) {
|
|
1075
|
-
case "email": return zs.email(errorMsg);
|
|
1076
|
-
case "ip": return zs.ip(errorMsg);
|
|
1077
|
-
case "ipv4": return zs.ip({
|
|
1078
|
-
version: "v4",
|
|
1079
|
-
message: errorMsg
|
|
1080
|
-
});
|
|
1081
|
-
case "ipv6": return zs.ip({
|
|
1082
|
-
version: "v6",
|
|
1083
|
-
message: errorMsg
|
|
1084
|
-
});
|
|
1085
|
-
case "uri": return zs.url(errorMsg);
|
|
1086
|
-
case "uuid": return zs.uuid(errorMsg);
|
|
1087
|
-
case "date-time": return zs.datetime({
|
|
1088
|
-
offset: true,
|
|
1089
|
-
message: errorMsg
|
|
1090
|
-
});
|
|
1091
|
-
case "time": return zs.time(errorMsg);
|
|
1092
|
-
case "date": return zs.date(errorMsg);
|
|
1093
|
-
case "binary": return zs.base64(errorMsg);
|
|
1094
|
-
case "duration": return zs.duration(errorMsg);
|
|
1095
|
-
default: return zs;
|
|
1096
|
-
}
|
|
1097
|
-
});
|
|
1098
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "contentEncoding", (zs, _, errorMsg) => zs.base64(errorMsg));
|
|
1099
|
-
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "pattern", (zs, pattern, errorMsg) => zs.regex(compilePattern("pattern", pattern, refs), errorMsg));
|
|
1100
|
-
const errorMessages = jsonSchema.errorMessage;
|
|
1101
|
-
const minLength = typeof jsonSchema.minLength === "number" ? jsonSchema.minLength : typeof jsonSchema.min === "number" ? jsonSchema.min : void 0;
|
|
1102
|
-
const maxLength = typeof jsonSchema.maxLength === "number" ? jsonSchema.maxLength : typeof jsonSchema.max === "number" ? jsonSchema.max : void 0;
|
|
1103
|
-
let result = zodSchema;
|
|
1104
|
-
if (minLength !== void 0) result = result.refine((value) => codePointLength(value) >= minLength, { message: errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)` });
|
|
1105
|
-
if (maxLength !== void 0) result = result.refine((value) => codePointLength(value) <= maxLength, { message: errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)` });
|
|
1106
|
-
return result;
|
|
1107
|
-
};
|
|
1108
|
-
const codePointLength = (value) => [...value].length;
|
|
1109
|
-
|
|
1110
|
-
//#endregion
|
|
1111
|
-
//#region src/parsers/parse-typeless-constraints.ts
|
|
1112
|
-
const SCALAR_CONSTRAINT_KEYS = [
|
|
1113
|
-
"minLength",
|
|
1114
|
-
"maxLength",
|
|
1115
|
-
"pattern",
|
|
1116
|
-
"minimum",
|
|
1117
|
-
"maximum",
|
|
1118
|
-
"exclusiveMinimum",
|
|
1119
|
-
"exclusiveMaximum",
|
|
1120
|
-
"multipleOf"
|
|
1121
|
-
];
|
|
1122
|
-
const hasTypelessScalarConstraints = (schema) => schema.type === void 0 && SCALAR_CONSTRAINT_KEYS.some((key) => schema[key] !== void 0);
|
|
1123
|
-
/**
|
|
1124
|
-
* Draft 7 applies scalar constraints to matching instance types even when the
|
|
1125
|
-
* schema declares no `type`: `{ "minLength": 2 }` restricts strings while
|
|
1126
|
-
* leaving every non-string value untouched.
|
|
1127
|
-
*/
|
|
1128
|
-
const parseTypelessConstraints = (schema, refs) => {
|
|
1129
|
-
const stringSchema = parseString({
|
|
1130
|
-
...schema,
|
|
1131
|
-
type: "string"
|
|
1132
|
-
}, refs);
|
|
1133
|
-
const numberSchema = parseNumber({
|
|
1134
|
-
...schema,
|
|
1135
|
-
type: "number"
|
|
1136
|
-
});
|
|
1137
|
-
return z.any().superRefine((value, ctx) => {
|
|
1138
|
-
const applicable = typeof value === "string" ? stringSchema : typeof value === "number" ? numberSchema : void 0;
|
|
1139
|
-
if (applicable === void 0) return;
|
|
1140
|
-
const result = applicable.safeParse(value);
|
|
1141
|
-
if (!result.success) for (const issue of result.error.issues) ctx.addIssue(issue);
|
|
1142
|
-
});
|
|
1143
|
-
};
|
|
1144
|
-
|
|
1145
|
-
//#endregion
|
|
1146
|
-
//#region src/whole-schema-validation.ts
|
|
1147
|
-
const REQUIRES_WHOLE_SCHEMA_VALIDATION = /* @__PURE__ */ new Set([
|
|
1148
|
-
"$ref",
|
|
1149
|
-
"additionalItems",
|
|
1150
|
-
"allOf",
|
|
1151
|
-
"anyOf",
|
|
1152
|
-
"contains",
|
|
1153
|
-
"dependencies",
|
|
1154
|
-
"else",
|
|
1155
|
-
"if",
|
|
1156
|
-
"maxProperties",
|
|
1157
|
-
"minProperties",
|
|
1158
|
-
"not",
|
|
1159
|
-
"oneOf",
|
|
1160
|
-
"propertyNames",
|
|
1161
|
-
"then",
|
|
1162
|
-
"uniqueItems"
|
|
1163
|
-
]);
|
|
1164
|
-
const TYPELESS_TYPE_SCOPED_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1165
|
-
"properties",
|
|
1166
|
-
"patternProperties",
|
|
1167
|
-
"additionalProperties",
|
|
1168
|
-
"propertyNames",
|
|
1169
|
-
"required",
|
|
1170
|
-
"dependencies",
|
|
1171
|
-
"minProperties",
|
|
1172
|
-
"maxProperties",
|
|
1173
|
-
"items",
|
|
1174
|
-
"additionalItems",
|
|
1175
|
-
"contains",
|
|
1176
|
-
"minItems",
|
|
1177
|
-
"maxItems",
|
|
1178
|
-
"uniqueItems"
|
|
1179
|
-
]);
|
|
1180
|
-
const SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1181
|
-
"$defs",
|
|
1182
|
-
"definitions",
|
|
1183
|
-
"dependencies",
|
|
1184
|
-
"patternProperties",
|
|
1185
|
-
"properties"
|
|
1186
|
-
]);
|
|
1187
|
-
const SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1188
|
-
"allOf",
|
|
1189
|
-
"anyOf",
|
|
1190
|
-
"oneOf"
|
|
1191
|
-
]);
|
|
1192
|
-
const SCHEMA_VALUE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1193
|
-
"additionalItems",
|
|
1194
|
-
"additionalProperties",
|
|
1195
|
-
"contains",
|
|
1196
|
-
"else",
|
|
1197
|
-
"if",
|
|
1198
|
-
"items",
|
|
1199
|
-
"not",
|
|
1200
|
-
"propertyNames",
|
|
1201
|
-
"then"
|
|
1202
|
-
]);
|
|
1203
|
-
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1204
|
-
/**
|
|
1205
|
-
* Every object the interpreter registers as a schema, found with its own walk
|
|
1206
|
-
* (`dereference`): each key it does not ignore, extension locations included.
|
|
1207
|
-
* A `$ref` resolves only through that registry, whether it is a JSON Pointer,
|
|
1208
|
-
* an `$id` or an `$anchor`, so these are all the schemas the interpreter can
|
|
1209
|
-
* ever validate against.
|
|
1210
|
-
*/
|
|
1211
|
-
function* interpreterSchemaNodes(value, path = [], seen = /* @__PURE__ */ new WeakSet()) {
|
|
1212
|
-
if (!isObject(value) || seen.has(value)) return;
|
|
1213
|
-
seen.add(value);
|
|
1214
|
-
yield {
|
|
1215
|
-
value,
|
|
1216
|
-
path
|
|
1217
|
-
};
|
|
1218
|
-
for (const [key, child] of Object.entries(value)) {
|
|
1219
|
-
if (ignoredKeyword[key]) continue;
|
|
1220
|
-
if (Array.isArray(child)) {
|
|
1221
|
-
if (schemaArrayKeyword[key]) for (const [index, nested] of child.entries()) yield* interpreterSchemaNodes(nested, [
|
|
1222
|
-
...path,
|
|
1223
|
-
key,
|
|
1224
|
-
index
|
|
1225
|
-
], seen);
|
|
1226
|
-
} else if (schemaMapKeyword[key]) {
|
|
1227
|
-
if (isObject(child)) for (const [name, nested] of Object.entries(child)) yield* interpreterSchemaNodes(nested, [
|
|
1228
|
-
...path,
|
|
1229
|
-
key,
|
|
1230
|
-
name
|
|
1231
|
-
], seen);
|
|
1232
|
-
} else yield* interpreterSchemaNodes(child, [...path, key], seen);
|
|
1233
|
-
}
|
|
1234
|
-
}
|
|
1235
|
-
const hasRequiredDefault = (schema) => {
|
|
1236
|
-
if (!Array.isArray(schema.required) || !isObject(schema.properties)) return false;
|
|
1237
|
-
return schema.required.some((name) => {
|
|
1238
|
-
const property = schema.properties?.[name];
|
|
1239
|
-
return isObject(property) && property.default !== void 0;
|
|
1240
|
-
});
|
|
1241
|
-
};
|
|
1242
|
-
const hasUnparsedRequiredProperty = (schema) => {
|
|
1243
|
-
if (!Array.isArray(schema.required)) return false;
|
|
1244
|
-
const declared = new Set(Object.keys(schema.properties ?? {}));
|
|
1245
|
-
return schema.required.some((name) => !declared.has(name));
|
|
1246
|
-
};
|
|
1247
|
-
/**
|
|
1248
|
-
* The native parsers preserve useful Zod structure and materialize defaults,
|
|
1249
|
-
* but some JSON Schema assertions cannot be represented by their first-match
|
|
1250
|
-
* dispatch. Only those schemas receive an authoritative Draft 7 guard.
|
|
1251
|
-
*/
|
|
1252
|
-
const requiresWholeSchemaValidation = (schema, seen = /* @__PURE__ */ new WeakSet()) => {
|
|
1253
|
-
if (!isObject(schema) || seen.has(schema)) return false;
|
|
1254
|
-
seen.add(schema);
|
|
1255
|
-
if (Object.keys(schema).some((key) => REQUIRES_WHOLE_SCHEMA_VALIDATION.has(key)) || schema.type === void 0 && Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || hasUnparsedRequiredProperty(schema) || hasRequiredDefault(schema)) return true;
|
|
1256
|
-
for (const [key, child] of Object.entries(schema)) if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
|
|
1257
|
-
if (Object.values(child).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
1258
|
-
} else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
|
|
1259
|
-
if (child.some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
1260
|
-
} else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
|
|
1261
|
-
if ((Array.isArray(child) ? child : [child]).some((value) => requiresWholeSchemaValidation(value, seen))) return true;
|
|
1262
|
-
}
|
|
1263
|
-
return false;
|
|
1264
|
-
};
|
|
1265
|
-
/**
|
|
1266
|
-
* Some schemas are valid for JSON instance types that the native parser does
|
|
1267
|
-
* not materialize. Such a node is parsed as `z.any()` so the Draft 7 guard
|
|
1268
|
-
* that every one of these keywords also activates (see
|
|
1269
|
-
* `requiresWholeSchemaValidation`) stays the acceptance authority without
|
|
1270
|
-
* piping into a narrower Zod schema. The check is deliberately local: a
|
|
1271
|
-
* permissive descendant must not widen its enclosing parser, or sibling
|
|
1272
|
-
* defaults would stop materializing.
|
|
1273
|
-
*/
|
|
1274
|
-
const requiresPermissiveMaterialization = (schema) => isObject(schema) && ("$ref" in schema || schema.type === void 0 && (Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || [
|
|
1275
|
-
"if",
|
|
1276
|
-
"then",
|
|
1277
|
-
"else",
|
|
1278
|
-
"not"
|
|
1279
|
-
].some((key) => key in schema)));
|
|
1280
|
-
/**
|
|
1281
|
-
* The guard schema for a node nested at `path` inside `root`: the enclosing
|
|
1282
|
-
* document pointed at that node, so local `$ref`s resolve exactly as they do
|
|
1283
|
-
* for the document root. Draft 7 ignores the keywords next to `$ref`, which
|
|
1284
|
-
* is what lets the root's own assertions be reused as the pointer carrier.
|
|
1285
|
-
*/
|
|
1286
|
-
const guardSchemaAt = (node, refs) => isObject(refs.root) && refs.path.length > 0 ? {
|
|
1287
|
-
...refs.root,
|
|
1288
|
-
$ref: `#/${refs.path.map((part) => encodePointer(String(part))).join("/")}`
|
|
1289
|
-
} : node;
|
|
1290
|
-
/**
|
|
1291
|
-
* Spells each key of a `patternProperties` object with `spell`. Two keys that
|
|
1292
|
-
* spell the same way (`^a\_b$` and `^a_b$`) stay separate entries: the later
|
|
1293
|
-
* one is wrapped in a non-capturing group, which matches the same names, so
|
|
1294
|
-
* neither value schema is dropped. `renamed` collects every spelling that
|
|
1295
|
-
* differs from its key.
|
|
1296
|
-
*/
|
|
1297
|
-
const patternKeyRenamer = (spell, renamed = /* @__PURE__ */ new Map()) => {
|
|
1298
|
-
const cache = /* @__PURE__ */ new WeakMap();
|
|
1299
|
-
return (patternProperties) => {
|
|
1300
|
-
const cached = cache.get(patternProperties);
|
|
1301
|
-
if (cached) return cached;
|
|
1302
|
-
const renames = /* @__PURE__ */ new Map();
|
|
1303
|
-
const used = /* @__PURE__ */ new Set();
|
|
1304
|
-
for (const key of Object.keys(patternProperties)) {
|
|
1305
|
-
let spelling = spell(key);
|
|
1306
|
-
while (used.has(spelling)) spelling = `(?:${spelling})`;
|
|
1307
|
-
used.add(spelling);
|
|
1308
|
-
renames.set(key, spelling);
|
|
1309
|
-
if (spelling !== key) renamed.set(spelling, key);
|
|
1310
|
-
}
|
|
1311
|
-
cache.set(patternProperties, renames);
|
|
1312
|
-
return renames;
|
|
1313
|
-
};
|
|
1314
|
-
};
|
|
1315
|
-
/**
|
|
1316
|
-
* The interpreter matches `patternProperties` keys itself, with a native
|
|
1317
|
-
* backtracking `RegExp`, against object keys that come from the caller. So a
|
|
1318
|
-
* key never reaches it as written. Instead, each validation spells it as the
|
|
1319
|
-
* literal set of instance keys it matches under RE2 (an anchored trie, which
|
|
1320
|
-
* cannot backtrack beyond the key length). Interpreter matching then agrees
|
|
1321
|
-
* with RE2 on every key it can see.
|
|
1322
|
-
*
|
|
1323
|
-
* Returns the RE2 matcher of each key, or `undefined` for a key that does not
|
|
1324
|
-
* compile in the Unicode grammar: the interpreter throws on it when reached,
|
|
1325
|
-
* which fails the guard closed, as it always has. A key that compiles but
|
|
1326
|
-
* needs a backtracking engine is rejected at conversion, as the native object
|
|
1327
|
-
* parser does.
|
|
1328
|
-
*/
|
|
1329
|
-
const collectPatternKeyMatchers = (nodes) => {
|
|
1330
|
-
const matchers = /* @__PURE__ */ new Map();
|
|
1331
|
-
for (const { value, path } of nodes) {
|
|
1332
|
-
if (!isObject(value.patternProperties)) continue;
|
|
1333
|
-
for (const key of Object.keys(value.patternProperties)) {
|
|
1334
|
-
if (matchers.has(key)) continue;
|
|
1335
|
-
let matcher;
|
|
1336
|
-
try {
|
|
1337
|
-
matcher = createPatternMatcher(key);
|
|
1338
|
-
} catch {
|
|
1339
|
-
matcher = void 0;
|
|
1340
|
-
}
|
|
1341
|
-
if (matcher !== void 0 && matcher.kind !== "linear") {
|
|
1342
|
-
if (unicodeSpellingCompiles(key)) throw new InvalidPatternError("patternProperties", key, [
|
|
1343
|
-
...path,
|
|
1344
|
-
"patternProperties",
|
|
1345
|
-
key
|
|
1346
|
-
], "unsupported", "patternProperties keys must not use lookaround or backreferences");
|
|
1347
|
-
matcher = void 0;
|
|
1348
|
-
}
|
|
1349
|
-
matchers.set(key, matcher);
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
return matchers;
|
|
1353
|
-
};
|
|
1354
|
-
/** The Unicode spelling of a key that cannot be matched with RE2. */
|
|
1355
|
-
const fallbackKeySpelling = (pattern) => toUnicodePattern(pattern) ?? pattern;
|
|
1356
|
-
const unicodeSpellingCompiles = (pattern) => {
|
|
1357
|
-
try {
|
|
1358
|
-
new RegExp(fallbackKeySpelling(pattern), "u");
|
|
1359
|
-
return true;
|
|
1360
|
-
} catch {
|
|
1361
|
-
return false;
|
|
1362
|
-
}
|
|
1363
|
-
};
|
|
1364
|
-
/** Every object key anywhere in `value`. */
|
|
1365
|
-
const collectInstanceKeys = (value, keys = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new WeakSet()) => {
|
|
1366
|
-
if (typeof value !== "object" || value === null || seen.has(value)) return keys;
|
|
1367
|
-
seen.add(value);
|
|
1368
|
-
if (Array.isArray(value)) value.forEach((item) => collectInstanceKeys(item, keys, seen));
|
|
1369
|
-
else for (const [key, child] of Object.entries(value)) {
|
|
1370
|
-
keys.add(key);
|
|
1371
|
-
collectInstanceKeys(child, keys, seen);
|
|
1372
|
-
}
|
|
1373
|
-
return keys;
|
|
1374
|
-
};
|
|
1375
|
-
const UNICODE_SYNTAX_CHARACTER = /[$()*+./?[\\\]^{|}]/g;
|
|
1376
|
-
/** Spells a trie node as a Unicode-grammar pattern over its code points. */
|
|
1377
|
-
const spellKeyTrie = (node) => {
|
|
1378
|
-
const branches = [...node.children].map(([char, child]) => {
|
|
1379
|
-
let spelling = char.replace(UNICODE_SYNTAX_CHARACTER, "\\$&");
|
|
1380
|
-
let next = child;
|
|
1381
|
-
while (!next.end && next.children.size === 1) {
|
|
1382
|
-
const [[nextChar, grandchild]] = next.children;
|
|
1383
|
-
spelling += nextChar.replace(UNICODE_SYNTAX_CHARACTER, "\\$&");
|
|
1384
|
-
next = grandchild;
|
|
1385
|
-
}
|
|
1386
|
-
return spelling + spellKeyTrie(next);
|
|
1387
|
-
});
|
|
1388
|
-
if (branches.length === 0) return "";
|
|
1389
|
-
if (branches.length === 1 && !node.end) return branches[0];
|
|
1390
|
-
return `(?:${branches.join("|")}${node.end ? "|" : ""})`;
|
|
1391
|
-
};
|
|
1392
|
-
/**
|
|
1393
|
-
* An anchored Unicode-grammar pattern that matches exactly `keys`. Branches of
|
|
1394
|
-
* a trie start with distinct characters, so matching never backtracks further
|
|
1395
|
-
* than the key being tested. No keys gives `[]`, which matches nothing.
|
|
1396
|
-
*/
|
|
1397
|
-
const literalKeysPattern = (keys) => {
|
|
1398
|
-
if (keys.length === 0) return "[]";
|
|
1399
|
-
const root = {
|
|
1400
|
-
end: false,
|
|
1401
|
-
children: /* @__PURE__ */ new Map()
|
|
1402
|
-
};
|
|
1403
|
-
for (const key of keys) {
|
|
1404
|
-
let node = root;
|
|
1405
|
-
for (const char of key) {
|
|
1406
|
-
let child = node.children.get(char);
|
|
1407
|
-
if (!child) {
|
|
1408
|
-
child = {
|
|
1409
|
-
end: false,
|
|
1410
|
-
children: /* @__PURE__ */ new Map()
|
|
1411
|
-
};
|
|
1412
|
-
node.children.set(char, child);
|
|
1413
|
-
}
|
|
1414
|
-
node = child;
|
|
1415
|
-
}
|
|
1416
|
-
node.end = true;
|
|
1417
|
-
}
|
|
1418
|
-
return `^${spellKeyTrie(root)}$`;
|
|
1419
|
-
};
|
|
1420
|
-
const decodePointerSegment = (segment) => {
|
|
1421
|
-
try {
|
|
1422
|
-
return decodeURI(segment).replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1423
|
-
} catch {
|
|
1424
|
-
return segment;
|
|
1425
|
-
}
|
|
1426
|
-
};
|
|
1427
|
-
const positionAfter = (position, key, child) => {
|
|
1428
|
-
if (position !== "keyword") return position === "other" ? "other" : "keyword";
|
|
1429
|
-
if (key === "patternProperties") return "patternKey";
|
|
1430
|
-
if (SCHEMA_MAP_KEYWORDS.has(key)) return "name";
|
|
1431
|
-
if (SCHEMA_ARRAY_KEYWORDS.has(key) || SCHEMA_VALUE_KEYWORDS.has(key) && Array.isArray(child)) return "index";
|
|
1432
|
-
return SCHEMA_VALUE_KEYWORDS.has(key) ? "keyword" : "other";
|
|
1433
|
-
};
|
|
1434
|
-
/**
|
|
1435
|
-
* A local `$ref` rewritten to address the renamed `patternProperties` keys of
|
|
1436
|
-
* the interpreter copy. `root` is the unrenamed document it points into. Only
|
|
1437
|
-
* a segment in keyword position is a keyword, so a definition that happens to
|
|
1438
|
-
* be named `patternProperties` is not mistaken for one.
|
|
1439
|
-
*/
|
|
1440
|
-
const renameRefThroughPatternKeys = (ref, root, renamePatternKeys, schemaObjects) => {
|
|
1441
|
-
if (!ref.startsWith("#/")) return ref;
|
|
1442
|
-
let node = root;
|
|
1443
|
-
let position = "keyword";
|
|
1444
|
-
let changed = false;
|
|
1445
|
-
const renamed = ref.slice(2).split("/").map((segment) => {
|
|
1446
|
-
if (position === "other" && isObject(node) && schemaObjects.has(node)) position = "keyword";
|
|
1447
|
-
const key = decodePointerSegment(segment);
|
|
1448
|
-
let result = segment;
|
|
1449
|
-
if (position === "patternKey" && isObject(node)) {
|
|
1450
|
-
const renamedKey = renamePatternKeys(node).get(key);
|
|
1451
|
-
if (renamedKey !== void 0 && renamedKey !== key) {
|
|
1452
|
-
result = encodePointer(renamedKey);
|
|
1453
|
-
changed = true;
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
const child = isObject(node) || Array.isArray(node) ? node[key] : void 0;
|
|
1457
|
-
position = positionAfter(position, key, child);
|
|
1458
|
-
node = child;
|
|
1459
|
-
return result;
|
|
1460
|
-
});
|
|
1461
|
-
return changed ? `#/${renamed.join("/")}` : ref;
|
|
1462
|
-
};
|
|
1463
|
-
const PATTERN_FORMAT_PREFIX = "composio-pattern:";
|
|
1464
|
-
/**
|
|
1465
|
-
* Adds `pattern` to `formats` as an interpreter format that tests it as the
|
|
1466
|
-
* native string parser does (legacy grammar, RE2 with a bounded fallback; see
|
|
1467
|
-
* `compilePattern`), and returns the format name. Returns `undefined` for a
|
|
1468
|
-
* pattern that does not compile at all, which the interpreter then reports as
|
|
1469
|
-
* it always has. `matchers` caches compiled patterns across validations.
|
|
1470
|
-
*/
|
|
1471
|
-
const patternFormat = (pattern, formats, matchers) => {
|
|
1472
|
-
const name = `${PATTERN_FORMAT_PREFIX}${pattern}`;
|
|
1473
|
-
if (!formats.has(name)) {
|
|
1474
|
-
let matcher = matchers.get(pattern);
|
|
1475
|
-
if (matcher === void 0) {
|
|
1476
|
-
try {
|
|
1477
|
-
new RegExp(pattern);
|
|
1478
|
-
} catch {
|
|
1479
|
-
return;
|
|
1480
|
-
}
|
|
1481
|
-
matcher = createPatternMatcher(pattern);
|
|
1482
|
-
matchers.set(pattern, matcher);
|
|
1483
|
-
}
|
|
1484
|
-
const compiled = matcher;
|
|
1485
|
-
formats.set(name, (value) => patternMatches(compiled, value));
|
|
1486
|
-
}
|
|
1487
|
-
return name;
|
|
1488
|
-
};
|
|
1489
|
-
/**
|
|
1490
|
-
* Rewrites the guard's private copy of a schema into what the Draft 7
|
|
1491
|
-
* interpreter understands the way the native parsers do:
|
|
1492
|
-
*
|
|
1493
|
-
* - OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
|
|
1494
|
-
* `minimum`/`maximum`. The interpreter ignores the flag, so it receives the
|
|
1495
|
-
* numeric spelling the native number parser already honors.
|
|
1496
|
-
* - The interpreter compiles patterns natively with the `u` flag, which
|
|
1497
|
-
* refuses legacy syntax tool schemas use, such as `\_`, and backtracks. A
|
|
1498
|
-
* `pattern` becomes a format that tests it exactly like the native string
|
|
1499
|
-
* parser. A `patternProperties` key cannot leave the interpreter, so it is
|
|
1500
|
-
* respelled by `renamePatternKeys`, and local `$ref`s through a renamed key
|
|
1501
|
-
* follow the rename. `root` is the unmodified document those refs address.
|
|
1502
|
-
* `formats` collects the pattern formats.
|
|
1503
|
-
*/
|
|
1504
|
-
const prepareInterpreterSchema = (value, root, formats, patternMatchers, renamePatternKeys, schemaObjects) => {
|
|
1505
|
-
if (value.exclusiveMinimum === true && typeof value.minimum === "number") {
|
|
1506
|
-
value.exclusiveMinimum = value.minimum;
|
|
1507
|
-
delete value.minimum;
|
|
1508
|
-
} else if (typeof value.exclusiveMinimum === "boolean") delete value.exclusiveMinimum;
|
|
1509
|
-
if (value.exclusiveMaximum === true && typeof value.maximum === "number") {
|
|
1510
|
-
value.exclusiveMaximum = value.maximum;
|
|
1511
|
-
delete value.maximum;
|
|
1512
|
-
} else if (typeof value.exclusiveMaximum === "boolean") delete value.exclusiveMaximum;
|
|
1513
|
-
if (typeof value.$ref === "string") value.$ref = renameRefThroughPatternKeys(value.$ref, root, renamePatternKeys, schemaObjects);
|
|
1514
|
-
const patternFormatName = typeof value.pattern === "string" ? patternFormat(value.pattern, formats, patternMatchers) : void 0;
|
|
1515
|
-
if (patternFormatName !== void 0) {
|
|
1516
|
-
delete value.pattern;
|
|
1517
|
-
if (value.format === void 0) value.format = patternFormatName;
|
|
1518
|
-
else value.allOf = [...Array.isArray(value.allOf) ? value.allOf : [], { format: patternFormatName }];
|
|
1519
|
-
}
|
|
1520
|
-
if (isObject(value.patternProperties)) {
|
|
1521
|
-
const renames = renamePatternKeys(value.patternProperties);
|
|
1522
|
-
value.patternProperties = Object.fromEntries(Object.entries(value.patternProperties).map(([pattern, schema]) => [renames.get(pattern) ?? pattern, schema]));
|
|
1523
|
-
}
|
|
1524
|
-
};
|
|
4
|
+
// src/backend/zod-v3.ts
|
|
1525
5
|
const guardedSchemaClasses = /* @__PURE__ */ new WeakMap();
|
|
1526
6
|
/**
|
|
1527
7
|
* A subclass of the parsed schema's own class that checks the source value
|
|
@@ -1550,206 +30,108 @@ const guardedSchemaClass = (Base) => {
|
|
|
1550
30
|
guardedSchemaClasses.set(Guarded, Guarded);
|
|
1551
31
|
return Guarded;
|
|
1552
32
|
};
|
|
1553
|
-
const
|
|
1554
|
-
const
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
const keyMatchers = collectPatternKeyMatchers(originalNodes);
|
|
1558
|
-
const prepare = (spell) => {
|
|
1559
|
-
const interpreterSchema = structuredClone(jsonSchema);
|
|
1560
|
-
const formats = /* @__PURE__ */ new Map();
|
|
1561
|
-
const renamed = /* @__PURE__ */ new Map();
|
|
1562
|
-
const renamePatternKeys = patternKeyRenamer(spell, renamed);
|
|
1563
|
-
const nodes = [...interpreterSchemaNodes(interpreterSchema)];
|
|
1564
|
-
for (const { value } of nodes) prepareInterpreterSchema(value, jsonSchema, formats, patternMatchers, renamePatternKeys, schemaObjects);
|
|
1565
|
-
return {
|
|
1566
|
-
validator: new Validator(interpreterSchema, "7", false),
|
|
1567
|
-
formats,
|
|
1568
|
-
renamed
|
|
1569
|
-
};
|
|
1570
|
-
};
|
|
1571
|
-
const shared = keyMatchers.size === 0 ? prepare(fallbackKeySpelling) : void 0;
|
|
1572
|
-
const prepareFor = (value) => {
|
|
1573
|
-
if (shared) return shared;
|
|
1574
|
-
const instanceKeys = [...collectInstanceKeys(value)];
|
|
1575
|
-
const spellings = /* @__PURE__ */ new Map();
|
|
1576
|
-
return prepare((pattern) => {
|
|
1577
|
-
const cached = spellings.get(pattern);
|
|
1578
|
-
if (cached !== void 0) return cached;
|
|
1579
|
-
const matcher = keyMatchers.get(pattern);
|
|
1580
|
-
const spelling = matcher === void 0 ? fallbackKeySpelling(pattern) : literalKeysPattern(instanceKeys.filter((key) => patternMatches(matcher, key)));
|
|
1581
|
-
spellings.set(pattern, spelling);
|
|
1582
|
-
return spelling;
|
|
1583
|
-
});
|
|
1584
|
-
};
|
|
1585
|
-
const innerGuard = parsedSchema._def.wholeSchemaGuard;
|
|
1586
|
-
const wholeSchemaGuard = (value) => {
|
|
1587
|
-
let result;
|
|
1588
|
-
let prepared;
|
|
1589
|
-
try {
|
|
1590
|
-
prepared = prepareFor(value);
|
|
1591
|
-
prepared.formats.forEach((test, name) => {
|
|
1592
|
-
format[name] = test;
|
|
1593
|
-
});
|
|
1594
|
-
result = prepared.validator.validate(value);
|
|
1595
|
-
} catch (cause) {
|
|
1596
|
-
return `JSON Schema validation failed: ${String(cause)}`;
|
|
1597
|
-
} finally {
|
|
1598
|
-
prepared?.formats.forEach((_, name) => {
|
|
1599
|
-
delete format[name];
|
|
1600
|
-
});
|
|
1601
|
-
}
|
|
1602
|
-
if (!result.valid) {
|
|
1603
|
-
let error = result.errors[0]?.error ?? "Input does not satisfy the complete JSON Schema.";
|
|
1604
|
-
prepared.renamed.forEach((key, spelling) => {
|
|
1605
|
-
error = error.split(`"${spelling}"`).join(`"${key}"`);
|
|
1606
|
-
});
|
|
1607
|
-
return error;
|
|
1608
|
-
}
|
|
1609
|
-
return innerGuard?.(value);
|
|
1610
|
-
};
|
|
1611
|
-
return new (guardedSchemaClass(parsedSchema.constructor))({
|
|
1612
|
-
...parsedSchema._def,
|
|
33
|
+
const attachGuard = (schema, guard) => {
|
|
34
|
+
const wholeSchemaGuard = composeGuards(guard, schema._def.wholeSchemaGuard);
|
|
35
|
+
return new (guardedSchemaClass(schema.constructor))({
|
|
36
|
+
...schema._def,
|
|
1613
37
|
wholeSchemaGuard
|
|
1614
38
|
});
|
|
1615
39
|
};
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
}
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
}
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
if (!objectSchema.properties) return {};
|
|
1712
|
-
const propertyKeys = Object.keys(objectSchema.properties);
|
|
1713
|
-
if (propertyKeys.length === 0) return {};
|
|
1714
|
-
const properties = {};
|
|
1715
|
-
for (const key of propertyKeys) {
|
|
1716
|
-
const propJsonSchema = objectSchema.properties[key];
|
|
1717
|
-
const propRefs = {
|
|
1718
|
-
...refs,
|
|
1719
|
-
root: refs.root ?? objectSchema,
|
|
1720
|
-
path: [
|
|
1721
|
-
...refs.path,
|
|
1722
|
-
"properties",
|
|
1723
|
-
key
|
|
1724
|
-
]
|
|
1725
|
-
};
|
|
1726
|
-
const parsedProperty = parseSchema(propJsonSchema, propRefs);
|
|
1727
|
-
const propZodSchema = requiresWholeSchemaValidation(propJsonSchema) ? withWholeSchemaValidation(guardSchemaAt(propJsonSchema, propRefs), parsedProperty) : parsedProperty;
|
|
1728
|
-
const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
|
|
1729
|
-
if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema) {
|
|
1730
|
-
if (propJsonSchema.default === null) {
|
|
1731
|
-
const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
1732
|
-
const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
1733
|
-
const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
|
|
1734
|
-
if (hasAnyOfWithNull || hasOneOfWithNull || isNullable) properties[key] = propZodSchema.optional().default(null);
|
|
1735
|
-
else properties[key] = propZodSchema.nullable().optional().default(null);
|
|
1736
|
-
} else properties[key] = propZodSchema.optional().default(propJsonSchema.default);
|
|
1737
|
-
} else properties[key] = required ? propZodSchema : propZodSchema.optional();
|
|
1738
|
-
}
|
|
1739
|
-
return properties;
|
|
1740
|
-
}
|
|
1741
|
-
|
|
1742
|
-
//#endregion
|
|
1743
|
-
//#region src/json-schema-to-zod.ts
|
|
1744
|
-
const jsonSchemaToZod = (schema, options = {}) => {
|
|
1745
|
-
const parsedSchema = parseSchema(schema, {
|
|
1746
|
-
path: [],
|
|
1747
|
-
seen: /* @__PURE__ */ new Map(),
|
|
1748
|
-
root: schema,
|
|
1749
|
-
...options
|
|
1750
|
-
});
|
|
1751
|
-
return requiresWholeSchemaValidation(schema) ? withWholeSchemaValidation(schema, parsedSchema) : parsedSchema;
|
|
1752
|
-
};
|
|
40
|
+
/** Issues raised through the refinement context; Zod prefixes the context path itself. */
|
|
41
|
+
const sink = (ctx) => ({
|
|
42
|
+
custom(message, options) {
|
|
43
|
+
ctx.addIssue({
|
|
44
|
+
...withPath(options?.path),
|
|
45
|
+
code: z.ZodIssueCode.custom,
|
|
46
|
+
message,
|
|
47
|
+
...options?.params === void 0 ? {} : { params: options.params }
|
|
48
|
+
});
|
|
49
|
+
},
|
|
50
|
+
unrecognizedKeys(keys, message, options) {
|
|
51
|
+
ctx.addIssue({
|
|
52
|
+
...withPath(options?.path),
|
|
53
|
+
code: z.ZodIssueCode.unrecognized_keys,
|
|
54
|
+
keys: [...keys],
|
|
55
|
+
message
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
invalidUnion(message, failures, options) {
|
|
59
|
+
ctx.addIssue({
|
|
60
|
+
...withPath(options?.path),
|
|
61
|
+
code: z.ZodIssueCode.invalid_union,
|
|
62
|
+
unionErrors: failures,
|
|
63
|
+
message
|
|
64
|
+
});
|
|
65
|
+
},
|
|
66
|
+
forward(failure) {
|
|
67
|
+
for (const issue of failure.issues) ctx.addIssue(issue);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
const stringFormat = (schema, format, message) => {
|
|
71
|
+
const string = schema;
|
|
72
|
+
switch (format) {
|
|
73
|
+
case "email": return string.email(message);
|
|
74
|
+
case "ip": return string.ip(message);
|
|
75
|
+
case "ipv4": return string.ip({
|
|
76
|
+
version: "v4",
|
|
77
|
+
message
|
|
78
|
+
});
|
|
79
|
+
case "ipv6": return string.ip({
|
|
80
|
+
version: "v6",
|
|
81
|
+
message
|
|
82
|
+
});
|
|
83
|
+
case "uri": return string.url(message);
|
|
84
|
+
case "uuid": return string.uuid(message);
|
|
85
|
+
case "date-time": return string.datetime({
|
|
86
|
+
offset: true,
|
|
87
|
+
message
|
|
88
|
+
});
|
|
89
|
+
case "time": return string.time(message);
|
|
90
|
+
case "date": return string.date(message);
|
|
91
|
+
case "duration": return string.duration(message);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/** Zod v3 output: descriptions on `_def`, refinements as `ZodEffects`, the guard as a subclass. */
|
|
95
|
+
const zodV3Backend = {
|
|
96
|
+
isSchema: (value) => value instanceof z.ZodType,
|
|
97
|
+
isNever: (schema) => schema instanceof z.ZodNever,
|
|
98
|
+
any: () => z.any(),
|
|
99
|
+
never: () => z.never(),
|
|
100
|
+
boolean: () => z.boolean(),
|
|
101
|
+
null: () => z.null(),
|
|
102
|
+
string: () => z.string(),
|
|
103
|
+
number: () => z.number(),
|
|
104
|
+
literal: (value) => z.literal(value),
|
|
105
|
+
enum: (values) => z.enum(values),
|
|
106
|
+
predicate: (test) => z.custom(test),
|
|
107
|
+
stringFormat,
|
|
108
|
+
base64: (schema, message) => schema.base64(message),
|
|
109
|
+
regex: (schema, pattern, message) => schema.regex(pattern, message),
|
|
110
|
+
integer: (schema, message) => schema.int(message),
|
|
111
|
+
bound: (schema, kind, value, message) => schema[kind](value, message),
|
|
112
|
+
array: (item) => z.array(item),
|
|
113
|
+
minItems: (schema, count, message) => schema.min(count, message),
|
|
114
|
+
maxItems: (schema, count, message) => schema.max(count, message),
|
|
115
|
+
tuple: (items, rest) => buildTuple(z.tuple(items), rest),
|
|
116
|
+
object: (shape, policy) => applyObjectPolicy(z.object(shape), policy),
|
|
117
|
+
record: (value) => z.record(value),
|
|
118
|
+
union: (options) => z.union(options),
|
|
119
|
+
intersection: (left, right) => z.intersection(left, right),
|
|
120
|
+
optional: (schema) => schema.optional(),
|
|
121
|
+
nullable: (schema) => schema.nullable(),
|
|
122
|
+
withDefault: (schema, value) => schema.default(value),
|
|
123
|
+
readonly: (schema) => schema.readonly(),
|
|
124
|
+
decorate: (schema, decorations) => decorations.description === void 0 ? schema : schema.describe(decorations.description),
|
|
125
|
+
refine: (schema, test, message) => schema.refine(test, { message }),
|
|
126
|
+
superRefine: (schema, check) => schema.superRefine((value, ctx) => check(value, sink(ctx))),
|
|
127
|
+
rewrite: (schema, fn) => schema.transform((value, ctx) => fn(value, sink(ctx))),
|
|
128
|
+
run,
|
|
129
|
+
attachGuard
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// src/json-schema-to-zod.ts
|
|
133
|
+
const converter = createConverter(zodV3Backend);
|
|
134
|
+
const jsonSchemaToZod = (schema, options = {}) => converter.jsonSchemaToZod(schema, options);
|
|
1753
135
|
/**
|
|
1754
136
|
* Converts a JSON Schema object to a Zod raw shape.
|
|
1755
137
|
* This is useful when you need the shape object (e.g., `{ name: z.string(), age: z.number() }`)
|
|
@@ -1762,16 +144,6 @@ const jsonSchemaToZod = (schema, options = {}) => {
|
|
|
1762
144
|
* @param options - Optional configuration for the conversion
|
|
1763
145
|
* @returns A Zod raw shape object with property keys mapped to Zod types
|
|
1764
146
|
*/
|
|
1765
|
-
const jsonSchemaToZodShape = (schema, options = {}) =>
|
|
1766
|
-
if (typeof schema !== "object" || schema === null) return {};
|
|
1767
|
-
const objectSchema = schema;
|
|
1768
|
-
return parseObjectShape(objectSchema, {
|
|
1769
|
-
path: [],
|
|
1770
|
-
seen: /* @__PURE__ */ new Map(),
|
|
1771
|
-
root: objectSchema,
|
|
1772
|
-
...options
|
|
1773
|
-
});
|
|
1774
|
-
};
|
|
147
|
+
const jsonSchemaToZodShape = (schema, options = {}) => converter.jsonSchemaToZodShape(schema, options);
|
|
1775
148
|
|
|
1776
|
-
//#endregion
|
|
1777
149
|
export { InvalidPatternError, jsonSchemaToZod, jsonSchemaToZodShape };
|