@composio/json-schema-to-zod 0.3.4 → 0.4.0

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