Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
fix(json-schema-to-zod): scope pattern formats to each guard's validation
jkomyno committed
Sep 30, 2026 at 12:15 UTC
9cb9b97b8ed8439a57d30310370bdee9bf31a938
2 files changed
+47
-15
ts/packages/json-schema-to-zod/src/whole-schema-validation.ts
+33
-15
@@ -261,23 +261,25 @@ const renameRefThroughPatternKeys = (ref: string, root: unknown): string => {
261
262
const PATTERN_FORMAT_PREFIX = 'composio-pattern:';
263
264
+/** Pattern formats of one guard, installed on the interpreter only while it validates. */
265
+type PatternFormats = Map<string, (value: string) => boolean>;
266
+
267
/**
265
- * Registers `pattern` as an interpreter format that tests it exactly as the
266
- * native string parser does, without the `u` flag, and returns the format
267
- * name. The name is derived from the pattern, so every schema using the same
268
- * pattern shares one entry. Returns `undefined` for a pattern that does not
269
- * compile at all, which the interpreter then reports as it always has.
268
+ * Adds `pattern` to `formats` as an interpreter format that tests it exactly as
269
+ * the native string parser does, without the `u` flag, and returns the format
270
+ * name. Returns `undefined` for a pattern that does not compile at all, which
271
+ * the interpreter then reports as it always has.
272
*/
271
-const patternFormat = (pattern: string): string | undefined => {
273
+const patternFormat = (pattern: string, formats: PatternFormats): string | undefined => {
274
const name = `${PATTERN_FORMAT_PREFIX}${pattern}`;
273
- if (!Object.hasOwn(format, name)) {
275
+ if (!formats.has(name)) {
276
let regex: RegExp;
277
try {
278
regex = new RegExp(pattern);
279
} catch {
280
return undefined;
281
}
280
- format[name] = value => regex.test(value);
282
+ formats.set(name, value => regex.test(value));
283
}
284
return name;
285
};
@@ -295,9 +297,14 @@ const patternFormat = (pattern: string): string | undefined => {
297
* `patternProperties` key cannot leave the interpreter, so it gets its
298
* Unicode spelling (`toUnicodePattern`), and local `$ref`s through a renamed
299
* key follow the rename. `root` is the unmodified document those refs
298
- * address.
300
+ * address. `formats` collects the pattern formats.
301
*/
300
-const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>, root: unknown): void => {
302
+const prepareInterpreterSchema = (
303
+ value: unknown,
304
+ seen: WeakSet<object>,
305
+ root: unknown,
306
+ formats: PatternFormats
307
+): void => {
308
if (!isObject(value) || seen.has(value)) {
309
return;
310
}
@@ -320,7 +327,7 @@ const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>, root: u
327
value.$ref = renameRefThroughPatternKeys(value.$ref, root);
328
}
329
const patternFormatName =
323
- typeof value.pattern === 'string' ? patternFormat(value.pattern) : undefined;
330
+ typeof value.pattern === 'string' ? patternFormat(value.pattern, formats) : undefined;
331
if (patternFormatName !== undefined) {
332
delete value.pattern;
333
if (value.format === undefined) {
@@ -342,12 +349,12 @@ const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>, root: u
349
350
for (const [key, child] of Object.entries(value)) {
351
if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
345
- Object.values(child).forEach(nested => prepareInterpreterSchema(nested, seen, root));
352
+ Object.values(child).forEach(nested => prepareInterpreterSchema(nested, seen, root, formats));
353
} else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
347
- child.forEach(nested => prepareInterpreterSchema(nested, seen, root));
354
+ child.forEach(nested => prepareInterpreterSchema(nested, seen, root, formats));
355
} else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
356
(Array.isArray(child) ? child : [child]).forEach(nested =>
350
- prepareInterpreterSchema(nested, seen, root)
357
+ prepareInterpreterSchema(nested, seen, root, formats)
358
);
359
}
360
}
@@ -401,7 +408,8 @@ export const withWholeSchemaValidation = (
408
parsedSchema: z.ZodTypeAny
409
): z.ZodTypeAny => {
410
const interpreterSchema = structuredClone(jsonSchema);
404
- prepareInterpreterSchema(interpreterSchema, new WeakSet(), jsonSchema);
411
+ const formats: PatternFormats = new Map();
412
+ prepareInterpreterSchema(interpreterSchema, new WeakSet(), jsonSchema, formats);
413
const validator = new Validator(interpreterSchema as InterpreterSchema, '7', false);
414
415
// Validate the source value before defaults and other Zod transforms run.
@@ -409,11 +417,21 @@ export const withWholeSchemaValidation = (
417
// appear valid to the JSON Schema interpreter.
418
const innerGuard = (parsedSchema._def as GuardedDef).wholeSchemaGuard;
419
const wholeSchemaGuard: WholeSchemaGuard = value => {
420
+ // The interpreter only reads formats from its process-wide table. This
421
+ // guard's pattern formats live there only for this synchronous call, so
422
+ // the table does not grow with every distinct pattern ever converted.
423
let result: ReturnType<Validator['validate']>;
424
try {
425
+ formats.forEach((test, name) => {
426
+ format[name] = test;
427
+ });
428
result = validator.validate(value);
429
} catch (cause) {
430
return `JSON Schema validation failed: ${String(cause)}`;
431
+ } finally {
432
+ formats.forEach((_, name) => {
433
+ delete format[name];
434
+ });
435
}
436
437
if (!result.valid) {
ts/packages/json-schema-to-zod/test/semantic-regressions.test.ts
+14
@@ -1,4 +1,5 @@
1
import Ajv from 'ajv';
2
+import { format } from '@cfworker/json-schema';
3
import { describe, expect, it } from 'vitest';
4
5
import { z } from 'zod/v3';
@@ -373,6 +374,19 @@ describe('whole-schema semantic regressions', () => {
374
expect(parsed.safeParse({ handle: invalid }).success).toBe(false);
375
});
376
377
+ it('leaves no pattern formats in the interpreter format table', () => {
378
+ const schema: JsonSchema = {
379
+ type: 'object',
380
+ properties: { handle: { $ref: '#/$defs/handle' } },
381
+ $defs: { handle: { type: 'string', pattern: '^leak-check-\\d+$' } },
382
+ };
383
+ const parsed = jsonSchemaToZod(schema);
384
+
385
+ expect(parsed.safeParse({ handle: 'leak-check-1' }).success).toBe(true);
386
+ expect(parsed.safeParse({ handle: 'wrong' }).success).toBe(false);
387
+ expect(Object.keys(format).filter(name => name.includes('leak-check'))).toEqual([]);
388
+ });
389
+
390
it('enforces every patternProperties key, including keys that differ only in escapes', () => {
391
const schema: JsonSchema = {
392
patternProperties: {