@devries-cameron20 / composio Mirror · read-only / commits / ab289d622
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 13:30 UTC

fix(sdk): preserve primitive JSON Schema semantics (#4316)

## Summary - preserve boolean, empty, null, type-array, enum, const, and scalar-constraint semantics across every Python conversion entry point - intersect Zod enum and const values with declared types and constraints, including compound JSON values - default unversioned exact validation to Draft 7 and apply inclusive and numeric exclusive bounds independently - run one byte-identical corpus through Python, Zod, and Effect so accepted and rejected inputs stay aligned - keep exact JSON Schema acceptance separate from Pydantic default materialization ## Review follow-up (second push) - Python: exact Draft 7 acceptance now wraps all three entry points (`json_schema_to_pydantic_type`, `json_schema_to_model`, `pydantic_model_from_param_schema`), so they can no longer disagree - Python: draft-4 boolean `exclusiveMinimum`/`exclusiveMaximum` (OpenAPI 3.0 style) no longer crash conversion — exact validation falls back to Draft 4, and the library input is translated to the numeric spelling - Python: ECMA-only regex patterns (look-around) no longer crash pydantic model builds — Rust-incompatible patterns fall back to Python `re` - Python: type arrays with sibling constraints no longer raise `TypeError` on valid input — constraints are scoped per member before the library sees them - Python: integral floats satisfy `integer`, `const` intersects `enum`, annotation-only schemas accept anything, and an optional property with an empty `enum` tolerates absence - Zod: typeless scalar constraints apply per instance type, and string lengths count Unicode code points instead of UTF-16 code units - Effect: draft-4 boolean exclusive bounds are enforced instead of silently ignored - `multipleOf` uses decimal scaling in all three converters (declared `divergesFromJsonSchema` on the corpus case) - shared corpus grows by 13 primitive cases; new property-based tests check acceptance against real Draft 7 oracles (hypothesis + `jsonschema` in Python, fast-check + Ajv in TypeScript) ## Verification - Python `make chk` (ruff + mypy) - Python pytest: 1,572 passed (5 langchain-extra tests need an env this sandbox lacks; unchanged from base) - `@composio/json-schema-to-zod`: 187 passed incl. 300-run fast-check property test; typecheck + build - `@composio/json-schema-to-effect-schema`: 133 passed; typecheck - `@composio/core` corpus ingress tests: 61 passed - shared Python/TypeScript corpus files are byte-identical (shasum-verified) - `git diff --check` ## Contributor context This replaces four narrow proposals after independent local reproduction: - [#4301](https://github.com/ComposioHQ/composio/pull/4301) · [Glen](https://app.tryglen.com/ComposioHQ/composio/pull/4301) - [#4302](https://github.com/ComposioHQ/composio/pull/4302) · [Glen](https://app.tryglen.com/ComposioHQ/composio/pull/4302) - [#4303](https://github.com/ComposioHQ/composio/pull/4303) · [Glen](https://app.tryglen.com/ComposioHQ/composio/pull/4303) - [#4307](https://github.com/ComposioHQ/composio/pull/4307) · [Glen](https://app.tryglen.com/ComposioHQ/composio/pull/4307) --------- Co-authored-by: simpleqt <89645338+simpleqt@users.noreply.github.com>

Alberto Schiabel committed Sep 4, 2026 at 14:19 UTC ab289d62245da106e8d1c519115989becb779d27
38 files changed +4497 -327
.changeset/draft4-exclusive-bounds.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/json-schema-to-effect-schema': patch
3 +---
4 +
5 +Translate draft-4 boolean `exclusiveMinimum`/`exclusiveMaximum` flags (as emitted by OpenAPI 3.0 exporters) into their Draft 7 numeric spelling so exclusive bounds are enforced instead of silently ignored.
.changeset/honest-schema-primitives.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/json-schema-to-zod': patch
3 +---
4 +
5 +Preserve Draft 7 acceptance across primitive, composed, referenced, conditional, and typeless schemas. Enforce sibling and object/array assertions, retain positional tuple and `additionalItems` behavior, and prevent native Zod materialization from rejecting values already accepted by the source schema.
.github/workflows/py.test.yml
+1 -1
@@ -88,7 +88,7 @@ jobs:
88 uv pip install -e providers/crewai
89 uv pip install -e providers/langchain
90 uv pip install -e providers/langgraph
91 - uv pip install pytest pytest-mock
91 + uv pip install hypothesis pytest pytest-mock
92
93 - name: Run Import Tests
94 run: |
pnpm-lock.yaml
+79 -53
@@ -187,7 +187,7 @@ importers:
187 version: 7.8.5
188 tsdown:
189 specifier: 'catalog:'
190 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
190 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
191 tsx:
192 specifier: 'catalog:'
193 version: 4.23.12
@@ -719,7 +719,7 @@ importers:
719 version: 2.18.0(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))
720 '@modelcontextprotocol/sdk':
721 specifier: 'catalog:'
722 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
722 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
723 dotenv:
724 specifier: 'catalog:'
725 version: 17.4.2
@@ -871,7 +871,7 @@ importers:
871 version: link:../../packages/providers/vercel
872 '@modelcontextprotocol/sdk':
873 specifier: 'catalog:'
874 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
874 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
875 ai:
876 specifier: 'catalog:'
877 version: 7.0.79(zod@4.4.3)
@@ -924,7 +924,7 @@ importers:
924 version: link:../../packages/providers/openai-agents
925 '@modelcontextprotocol/sdk':
926 specifier: 'catalog:'
927 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
927 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
928 '@openai/agents':
929 specifier: ^0.17.0
930 version: 0.17.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)
@@ -1125,7 +1125,7 @@ importers:
1125 version: link:../../packages/providers/vercel
1126 '@modelcontextprotocol/sdk':
1127 specifier: 'catalog:'
1128 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
1128 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
1129 ai:
1130 specifier: 'catalog:'
1131 version: 7.0.79(zod@4.4.3)
@@ -1208,7 +1208,7 @@ importers:
1208 version: 0.61.1(@effect/cluster@0.60.2(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/workflow@0.19.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(@effect/rpc@0.76.2(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/sql@0.52.1(@effect/experimental@0.61.1(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(@effect/platform@0.97.1(effect@3.22.1))(effect@3.22.1))(effect@3.22.1)
1209 '@modelcontextprotocol/sdk':
1210 specifier: 'catalog:'
1211 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
1211 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
1212 '@zed-industries/claude-code-acp':
1213 specifier: ^0.16.2
1214 version: 0.16.2(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
@@ -1305,7 +1305,7 @@ importers:
1305 version: 3.2.0
1306 tsdown:
1307 specifier: 'catalog:'
1308 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.12)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1308 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.12)(unrun@0.2.27)
1309 tsx:
1310 specifier: 'catalog:'
1311 version: 4.23.12
@@ -1329,7 +1329,7 @@ importers:
1329 version: 3.22.1
1330 tsdown:
1331 specifier: 'catalog:'
1332 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1332 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1333 typescript:
1334 specifier: 'catalog:'
1335 version: 7.0.2
@@ -1344,7 +1344,7 @@ importers:
1344 version: link:../core
1345 '@modelcontextprotocol/sdk':
1346 specifier: 'catalog:'
1347 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
1347 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
1348 extract-zip:
1349 specifier: ^2.0.1
1350 version: 2.0.1(supports-color@10.2.2)
@@ -1360,7 +1360,7 @@ importers:
1360 version: 1.7.0
1361 tsdown:
1362 specifier: 'catalog:'
1363 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1363 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1364 typescript:
1365 specifier: 'catalog:'
1366 version: 7.0.2
@@ -1409,7 +1409,7 @@ importers:
1409 version: 7.8.0
1410 tsdown:
1411 specifier: 'catalog:'
1412 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.12)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1412 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.12)(unrun@0.2.27)
1413 tsx:
1414 specifier: 'catalog:'
1415 version: 4.23.12
@@ -1440,13 +1440,13 @@ importers:
1440 version: link:../core
1441 '@earendil-works/pi-coding-agent':
1442 specifier: ^0.84.3
1443 - version: 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)
1443 + version: 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)
1444 eve:
1445 specifier: ^0.44.4
1446 version: 0.44.4(@opentelemetry/api@1.9.1)(ai@7.0.79(zod@4.4.3))(dotenv@17.4.2)(jiti@2.7.0)(lru-cache@11.5.2)(miniflare@4.20260722.0)(rollup@4.62.5)(vite@7.3.5(@types/node@26.3.0)(jiti@2.7.0)(tsx@4.23.12)(yaml@2.9.0))(wrangler@4.125.0(@cloudflare/workers-types@5.20260825.1))
1447 tsdown:
1448 specifier: 'catalog:'
1449 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1449 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1450 tsx:
1451 specifier: 'catalog:'
1452 version: 4.23.12
@@ -1471,7 +1471,7 @@ importers:
1471 version: link:../json-schema-to-zod
1472 tsdown:
1473 specifier: 'catalog:'
1474 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1474 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1475 typescript:
1476 specifier: 'catalog:'
1477 version: 7.0.2
@@ -1483,6 +1483,13 @@ importers:
1483 version: 4.4.3
1484
1485 ts/packages/json-schema-to-zod:
1486 + dependencies:
1487 + '@cfworker/json-schema':
1488 + specifier: ^4.1.1
1489 + version: 4.1.1
1490 + dequal:
1491 + specifier: ^2.0.3
1492 + version: 2.0.3
1493 devDependencies:
1494 '@types/json-schema':
1495 specifier: ^7.0.15
@@ -1490,9 +1497,15 @@ importers:
1497 '@types/node':
1498 specifier: ^26.3.0
1499 version: 26.3.0
1500 + ajv:
1501 + specifier: ^8.20.0
1502 + version: 8.20.0
1503 + fast-check:
1504 + specifier: ^4.9.0
1505 + version: 4.9.0
1506 tsdown:
1507 specifier: 'catalog:'
1495 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1508 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1509 typescript:
1510 specifier: 'catalog:'
1511 version: 7.0.2
@@ -1522,7 +1535,7 @@ importers:
1535 version: 6.0.266(zod@4.4.3)
1536 tsdown:
1537 specifier: 'catalog:'
1525 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1538 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1539 typescript:
1540 specifier: 'catalog:'
1541 version: 7.0.2
@@ -1544,10 +1557,10 @@ importers:
1557 version: link:../../core
1558 '@modelcontextprotocol/sdk':
1559 specifier: 'catalog:'
1547 - version: 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
1560 + version: 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
1561 tsdown:
1562 specifier: 'catalog:'
1550 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1563 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1564 typescript:
1565 specifier: 'catalog:'
1566 version: 7.0.2
@@ -1566,7 +1579,7 @@ importers:
1579 version: link:../../core
1580 tsdown:
1581 specifier: 'catalog:'
1569 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1582 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1583 typescript:
1584 specifier: 'catalog:'
1585 version: 7.0.2
@@ -1585,7 +1598,7 @@ importers:
1598 version: link:../../core
1599 tsdown:
1600 specifier: 'catalog:'
1588 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1601 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1602 typescript:
1603 specifier: 'catalog:'
1604 version: 7.0.2
@@ -1600,7 +1613,7 @@ importers:
1613 version: 1.2.9(@opentelemetry/api@1.9.1)(openai@7.5.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(ws@8.21.3)(zod@4.4.3))(ws@8.21.3)
1614 tsdown:
1615 specifier: 'catalog:'
1603 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1616 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1617 typescript:
1618 specifier: 'catalog:'
1619 version: 7.0.2
@@ -1622,7 +1635,7 @@ importers:
1635 version: link:../../core
1636 tsdown:
1637 specifier: 'catalog:'
1625 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1638 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1639 typescript:
1640 specifier: 'catalog:'
1641 version: 7.0.2
@@ -1644,7 +1657,7 @@ importers:
1657 version: 6.0.266(zod@4.4.3)
1658 tsdown:
1659 specifier: 'catalog:'
1647 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1660 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1661 typescript:
1662 specifier: 'catalog:'
1663 version: 7.0.2
@@ -1665,7 +1678,7 @@ importers:
1678 version: 7.3.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(ws@8.21.3)(zod@4.4.3)
1679 tsdown:
1680 specifier: 'catalog:'
1668 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1681 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1682 typescript:
1683 specifier: 'catalog:'
1684 version: 7.0.2
@@ -1683,7 +1696,7 @@ importers:
1696 version: 0.17.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)
1697 tsdown:
1698 specifier: 'catalog:'
1686 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1699 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1700 typescript:
1701 specifier: 'catalog:'
1702 version: 7.0.2
@@ -1704,7 +1717,7 @@ importers:
1717 version: 7.0.79(zod@4.4.3)
1718 tsdown:
1719 specifier: 'catalog:'
1707 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1720 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1721 typescript:
1722 specifier: 'catalog:'
1723 version: 7.0.2
@@ -1769,7 +1782,7 @@ importers:
1782 version: link:@types/@babel/helper-validator-identifier
1783 tsdown:
1784 specifier: 'catalog:'
1772 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2))
1785 + version: 0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27)
1786 vitest:
1787 specifier: 'catalog:'
1788 version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@26.2.0)(@vitest/ui@4.1.11)(vite@7.3.5(@types/node@26.3.0)(jiti@2.7.0)(tsx@4.23.12)(yaml@2.9.0))
@@ -5100,6 +5113,10 @@ packages:
5113 resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==}
5114 engines: {node: '>=8.0.0'}
5115
5116 + fast-check@4.9.0:
5117 + resolution: {integrity: sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg==}
5118 + engines: {node: '>=12.17.0'}
5119 +
5120 fast-deep-equal@3.1.3:
5121 resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
5122
@@ -6159,6 +6176,9 @@ packages:
6176 pure-rand@6.1.0:
6177 resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==}
6178
6179 + pure-rand@8.4.2:
6180 + resolution: {integrity: sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==}
6181 +
6182 pusher-js@8.6.0:
6183 resolution: {integrity: sha512-wShJPfCS/kYkCBVzVW67wa9cnQIgHTszEK2XHNrFkOgGruuGw081aERAxfRjfdFU+WcIt8x6dvbwkTW4iZuQ8Q==}
6184
@@ -7239,7 +7259,7 @@ snapshots:
7259 '@anthropic-ai/claude-agent-sdk@0.3.245(@anthropic-ai/sdk@0.120.0(zod@4.4.3))(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(zod@4.4.3)':
7260 dependencies:
7261 '@anthropic-ai/sdk': 0.120.0(zod@4.4.3)
7242 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
7262 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
7263 zod: 4.4.3
7264 optionalDependencies:
7265 '@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.245
@@ -7725,7 +7745,7 @@ snapshots:
7745
7746 '@earendil-works/pi-agent-core@0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)':
7747 dependencies:
7728 - '@earendil-works/pi-ai': 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)
7748 + '@earendil-works/pi-ai': 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)
7749 '@earendil-works/pi-telemetry': 0.84.3
7750 diff: 8.0.4
7751 ignore: 7.0.5
@@ -7739,14 +7759,14 @@ snapshots:
7759 - ws
7760 - zod
7761
7742 - '@earendil-works/pi-ai@0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)':
7762 + '@earendil-works/pi-ai@0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)':
7763 dependencies:
7764 '@anthropic-ai/sdk': 0.91.1(zod@4.4.3)
7765 '@aws-sdk/client-bedrock-runtime': 3.1048.0
7766 '@earendil-works/pi-telemetry': 0.84.3
7767 '@google/genai': 1.52.0(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))
7768 '@smithy/node-http-handler': 4.7.3
7749 - http-proxy-agent: 7.0.2
7769 + http-proxy-agent: 7.0.2(supports-color@10.2.2)
7770 https-proxy-agent: 7.0.6(supports-color@10.2.2)
7771 openai: 6.40.0(ws@8.21.3)(zod@4.4.3)
7772 partial-json: 0.1.7
@@ -7763,10 +7783,10 @@ snapshots:
7783 dependencies:
7784 '@earendil-works/pi-protocol': 0.84.3
7785
7766 - '@earendil-works/pi-coding-agent@0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)':
7786 + '@earendil-works/pi-coding-agent@0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)':
7787 dependencies:
7788 '@earendil-works/pi-agent-core': 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)
7769 - '@earendil-works/pi-ai': 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(ws@8.21.3)(zod@4.4.3)
7789 + '@earendil-works/pi-ai': 0.84.3(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(supports-color@10.2.2)(ws@8.21.3)(zod@4.4.3)
7790 '@earendil-works/pi-client': 0.84.3
7791 '@earendil-works/pi-protocol': 0.84.3
7792 '@earendil-works/pi-tui': 0.84.3
@@ -8025,7 +8045,7 @@ snapshots:
8045 protobufjs: 7.6.5
8046 ws: 8.21.3
8047 optionalDependencies:
8028 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8048 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8049 transitivePeerDependencies:
8050 - bufferutil
8051 - supports-color
@@ -8038,7 +8058,7 @@ snapshots:
8058 protobufjs: 7.6.5
8059 ws: 8.21.3
8060 optionalDependencies:
8041 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8061 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8062 transitivePeerDependencies:
8063 - bufferutil
8064 - supports-color
@@ -8296,7 +8316,7 @@ snapshots:
8316 dependencies:
8317 '@langchain/core': 1.2.9(@opentelemetry/api@1.9.1)(openai@7.3.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(ws@8.21.3)(zod@4.4.3))(ws@8.21.3)
8318 '@langchain/langgraph': 1.4.12(@langchain/core@1.2.9(@opentelemetry/api@1.9.1)(openai@7.3.0(@aws-sdk/credential-provider-node@3.972.78)(@smithy/signature-v4@5.6.12)(ws@8.21.3)(zod@4.4.3))(ws@8.21.3))(zod@4.4.3)
8299 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8319 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8320 debug: 4.4.3(supports-color@10.2.2)
8321 zod: 4.4.3
8322 optionalDependencies:
@@ -8372,7 +8392,7 @@ snapshots:
8392
8393 '@llamaindex/workflow-core@1.3.4(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(hono@4.13.4)(zod@4.4.3)':
8394 optionalDependencies:
8375 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8395 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8396 hono: 4.13.4
8397 zod: 4.4.3
8398
@@ -8530,7 +8550,7 @@ snapshots:
8550 '@isaacs/ttlcache': 2.1.5
8551 '@lukeed/uuid': 2.0.1
8552 '@mastra/schema-compat': 1.3.4(zod@4.4.3)
8533 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8553 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8554 '@sindresorhus/slugify': 2.2.1
8555 '@standard-schema/spec': 1.1.0
8556 ajv: 8.20.0
@@ -8591,7 +8611,7 @@ snapshots:
8611 '@modelcontextprotocol/core': 2.0.0
8612 '@modelcontextprotocol/ext-apps': 1.7.5(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(zod@4.4.3)
8613 '@modelcontextprotocol/node': 2.0.0(@modelcontextprotocol/server@2.0.0)(hono@4.13.4)
8594 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8614 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8615 '@modelcontextprotocol/server': 2.0.0
8616 '@modelcontextprotocol/server-legacy': 2.0.0(express@5.2.1)
8617 exit-hook: 5.1.0
@@ -8649,7 +8669,7 @@ snapshots:
8669
8670 '@modelcontextprotocol/ext-apps@1.7.5(@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3))(zod@4.4.3)':
8671 dependencies:
8652 - '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)
8672 + '@modelcontextprotocol/sdk': 1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)
8673 '@standard-schema/spec': 1.1.0
8674 zod: 4.4.3
8675
@@ -8684,7 +8704,7 @@ snapshots:
8704 transitivePeerDependencies:
8705 - supports-color
8706
8687 - '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)':
8707 + '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(supports-color@10.2.2)(zod@4.4.3)':
8708 dependencies:
8709 '@hono/node-server': 2.1.1(hono@4.13.4)
8710 ajv: 8.20.0
@@ -8695,20 +8715,20 @@ snapshots:
8715 eventsource: 3.0.7
8716 eventsource-parser: 3.1.1
8717 express: 5.2.1
8698 - express-rate-limit: 8.6.2(express@5.2.1)
8718 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8719 hono: 4.13.4
8720 jose: 6.2.9
8721 json-schema-typed: 8.0.2
8722 pkce-challenge: 5.0.1
8723 raw-body: 3.0.2
8704 - zod: 3.25.76
8705 - zod-to-json-schema: 3.25.2(zod@3.25.76)
8724 + zod: 4.4.3
8725 + zod-to-json-schema: 3.25.2(zod@4.4.3)
8726 optionalDependencies:
8727 '@cfworker/json-schema': 4.1.1
8728 transitivePeerDependencies:
8729 - supports-color
8730
8711 - '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@4.4.3)':
8731 + '@modelcontextprotocol/sdk@1.30.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)':
8732 dependencies:
8733 '@hono/node-server': 2.1.1(hono@4.13.4)
8734 ajv: 8.20.0
@@ -8719,14 +8739,14 @@ snapshots:
8739 eventsource: 3.0.7
8740 eventsource-parser: 3.1.1
8741 express: 5.2.1
8722 - express-rate-limit: 8.6.2(express@5.2.1)
8742 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8743 hono: 4.13.4
8744 jose: 6.2.9
8745 json-schema-typed: 8.0.2
8746 pkce-challenge: 5.0.1
8747 raw-body: 3.0.2
8728 - zod: 4.4.3
8729 - zod-to-json-schema: 3.25.2(zod@4.4.3)
8748 + zod: 3.25.76
8749 + zod-to-json-schema: 3.25.2(zod@3.25.76)
8750 optionalDependencies:
8751 '@cfworker/json-schema': 4.1.1
8752 transitivePeerDependencies:
@@ -8737,7 +8757,7 @@ snapshots:
8757 '@modelcontextprotocol/core': 2.0.0
8758 content-type: 1.0.5
8759 cors: 2.8.6
8740 - express-rate-limit: 8.6.2(express@5.2.1)
8760 + express-rate-limit: 8.6.2(express@5.2.1)(supports-color@10.2.2)
8761 pkce-challenge: 5.0.1
8762 raw-body: 3.0.2
8763 zod: 4.4.3
@@ -10182,7 +10202,7 @@ snapshots:
10202 transitivePeerDependencies:
10203 - supports-color
10204
10185 - express-rate-limit@8.6.2(express@5.2.1):
10205 + express-rate-limit@8.6.2(express@5.2.1)(supports-color@10.2.2):
10206 dependencies:
10207 debug: 4.4.3(supports-color@10.2.2)
10208 express: 5.2.1
@@ -10248,6 +10268,10 @@ snapshots:
10268 dependencies:
10269 pure-rand: 6.1.0
10270
10271 + fast-check@4.9.0:
10272 + dependencies:
10273 + pure-rand: 8.4.2
10274 +
10275 fast-deep-equal@3.1.3: {}
10276
10277 fast-sha256@1.3.0: {}
@@ -10440,7 +10464,7 @@ snapshots:
10464 statuses: 2.0.2
10465 toidentifier: 1.0.1
10466
10443 - http-proxy-agent@7.0.2:
10467 + http-proxy-agent@7.0.2(supports-color@10.2.2):
10468 dependencies:
10469 agent-base: 7.1.4
10470 debug: 4.4.3(supports-color@10.2.2)
@@ -11446,6 +11470,8 @@ snapshots:
11470
11471 pure-rand@6.1.0: {}
11472
11473 + pure-rand@8.4.2: {}
11474 +
11475 pusher-js@8.6.0:
11476 dependencies:
11477 tweetnacl: 1.0.3
@@ -11900,7 +11926,7 @@ snapshots:
11926 '@ts-morph/common': 0.29.0
11927 code-block-writer: 13.0.3
11928
11903 - tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.12)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)):
11929 + tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(@typescript/typescript6@6.0.2)(publint@0.3.24)(tsx@4.23.12)(unrun@0.2.27):
11930 dependencies:
11931 ansis: 4.3.1
11932 cac: 7.0.0
@@ -11929,7 +11955,7 @@ snapshots:
11955 - oxc-resolver
11956 - vue-tsc
11957
11932 - tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)):
11958 + tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(publint@0.3.24)(tsx@4.23.12)(typescript@7.0.2)(unrun@0.2.27):
11959 dependencies:
11960 ansis: 4.3.1
11961 cac: 7.0.0
python/composio/core/models/_files.py
+5
@@ -966,6 +966,11 @@ class FileHelper(WithLogger):
966 return schema
967 required = schema.get("required") or []
968 for _param, _schema in schema["properties"].items():
969 + if not isinstance(_schema, dict):
970 + # Boolean schemas have no description to enhance. They are
971 + # valid property schemas and reach this unconditional helper
972 + # before schema conversion.
973 + continue
974 if _schema.get("type") in ["string", "integer", "number", "boolean"]:
975 ext = f"Please provide a value of type {_schema['type']}."
976 description = _schema.get("description", "").rstrip(".")
python/composio/utils/schema_converter.py
+1182 -33
@@ -9,6 +9,7 @@ boolean schemas (true/false values that are valid in JSON Schema draft-06+).
9 We handle those by pre-filtering them before passing to the library.
10 """
11
12 +import decimal
13 import re
14 import types
15 import typing as t
@@ -22,19 +23,24 @@ from json_schema_to_pydantic import (
23 from json_schema_to_pydantic import (
24 create_model as create_model_from_schema,
25 )
26 +from jsonschema import exceptions as jsonschema_exceptions
27 from jsonschema import validators as jsonschema_validators
28 from jsonschema.protocols import Validator
29 from pydantic import (
30 + AfterValidator,
31 BaseModel,
32 + BeforeValidator,
33 ConfigDict,
34 Field,
35 TypeAdapter,
36 + ValidationError,
37 model_validator,
38 )
39 from pydantic import (
40 create_model as create_pydantic_model,
41 )
42 from pydantic_core import core_schema
43 +from referencing import Registry
44
45 from composio.utils.logging import get as get_logger
46
@@ -45,7 +51,14 @@ _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE = "__composio_explicit_default_fields__"
51
52
53 class _UnsatisfiableSchema:
48 - """Pydantic type for JSON schemas that reject every value."""
54 + """Pydantic type for JSON schemas that reject every value.
55 +
56 + JSON Schema (draft-06+) allows the literal ``false`` anywhere a schema is
57 + expected, meaning "no value is valid". This marker stands in for it during
58 + conversion so combiners can tell an always-rejecting member apart from an
59 + absent one, and so the exact validator can turn it back into ``false``.
60 + The literal ``true`` ("any value is valid") simply becomes ``t.Any``.
61 + """
62
63 @staticmethod
64 def _reject(_value: t.Any) -> t.NoReturn:
@@ -80,11 +93,128 @@ PYDANTIC_TYPE_TO_PYTHON_TYPE = {
93 "boolean": bool,
94 "array": t.List,
95 "object": t.Dict,
83 - "null": t.Optional[t.Any],
96 + "null": type(None),
97 }
98
99 CONTAINER_TYPE = ("array", "object")
100
101 +# Keywords that constrain which instances a schema accepts. A schema whose keys
102 +# are all outside this set (title, description, default, examples, ...) is pure
103 +# annotation and accepts every value, exactly like the empty schema.
104 +_ASSERTION_KEYWORDS = frozenset(
105 + {
106 + "type",
107 + "enum",
108 + "const",
109 + "anyOf",
110 + "allOf",
111 + "oneOf",
112 + "not",
113 + "if",
114 + "then",
115 + "else",
116 + "$ref",
117 + "properties",
118 + "patternProperties",
119 + "additionalProperties",
120 + "propertyNames",
121 + "required",
122 + "dependencies",
123 + "minProperties",
124 + "maxProperties",
125 + "items",
126 + "additionalItems",
127 + "contains",
128 + "minItems",
129 + "maxItems",
130 + "uniqueItems",
131 + "minLength",
132 + "maxLength",
133 + "pattern",
134 + "minimum",
135 + "maximum",
136 + "exclusiveMinimum",
137 + "exclusiveMaximum",
138 + "multipleOf",
139 + }
140 +)
141 +
142 +_SCALAR_CONSTRAINT_KEYWORDS = frozenset(
143 + {
144 + "minLength",
145 + "maxLength",
146 + "pattern",
147 + "minimum",
148 + "maximum",
149 + "exclusiveMinimum",
150 + "exclusiveMaximum",
151 + "multipleOf",
152 + }
153 +)
154 +
155 +_STRUCTURAL_KEYWORDS = frozenset(
156 + {"anyOf", "allOf", "oneOf", "not", "if", "$ref", "properties", "items"}
157 +)
158 +
159 +_TYPELESS_TYPE_SCOPED_KEYWORDS = frozenset(
160 + {
161 + "properties",
162 + "patternProperties",
163 + "additionalProperties",
164 + "propertyNames",
165 + "required",
166 + "dependencies",
167 + "minProperties",
168 + "maxProperties",
169 + "items",
170 + "additionalItems",
171 + "contains",
172 + "minItems",
173 + "maxItems",
174 + "uniqueItems",
175 + }
176 +)
177 +
178 +# Keywords each type-array member keeps when the array is rewritten to anyOf.
179 +_TYPE_SCOPED_KEYWORDS: t.Dict[str, frozenset] = {
180 + "string": frozenset({"minLength", "maxLength", "pattern"}),
181 + "integer": frozenset(
182 + {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
183 + ),
184 + "number": frozenset(
185 + {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
186 + ),
187 + "array": frozenset(
188 + {
189 + "items",
190 + "additionalItems",
191 + "contains",
192 + "minItems",
193 + "maxItems",
194 + "uniqueItems",
195 + }
196 + ),
197 + "object": frozenset(
198 + {
199 + "properties",
200 + "patternProperties",
201 + "additionalProperties",
202 + "propertyNames",
203 + "required",
204 + "dependencies",
205 + "minProperties",
206 + "maxProperties",
207 + }
208 + ),
209 + "boolean": frozenset(),
210 + "null": frozenset(),
211 +}
212 +
213 +_TYPE_ARRAY_SHARED_KEYWORDS = frozenset({"enum", "const", "format"})
214 +_TYPE_ARRAY_WRAPPER_KEYWORDS = frozenset(
215 + {"title", "description", "default", "examples"}
216 +)
217 +
218 # Should be deprecated,
219 # required values will always be provided by users
220 # Non-required values are nullable(None) if default value not provided.
@@ -138,6 +268,12 @@ def _filter_boolean_schemas(
268 if not isinstance(schema, dict):
269 return schema
270
271 + # A schema that enumerates no acceptable values rejects everything, exactly
272 + # like `false`. Normalizing here routes both spellings through the same
273 + # unsatisfiable-property handling (which tolerates the property's absence).
274 + if schema.get("enum") == [] or schema.get("type") == []:
275 + return _UnsatisfiableSchema
276 +
277 # Make a copy to avoid mutating the original
278 result = {}
279 for key, value in schema.items():
@@ -442,6 +578,10 @@ def _mark_explicit_default_fields(
578 """Attach recursive default-presence metadata to generated model classes."""
579 origin = t.get_origin(annotation)
580 arguments = t.get_args(annotation)
581 + if origin is t.Annotated:
582 + # Exact-validation wrappers must not hide the materialized type below.
583 + _mark_explicit_default_fields(arguments[0], schema, root_schema, visiting)
584 + return
585 if origin in (t.Union, types.UnionType):
586 options: t.List[t.Dict[str, t.Any]] = []
587 resolved_schema = _resolve_default_metadata_schema(schema, root_schema)
@@ -999,22 +1139,40 @@ def json_schema_to_pydantic_type(
1139 :param root_schema: Full schema document used to resolve nested local references.
1140 :return: A Pydantic type.
1141 """
1002 - # Handle boolean schemas (JSON Schema draft-06+)
1142 + # A schema may be the literal `true` or `false` instead of an object
1143 + # (JSON Schema draft-06+), e.g. `additionalProperties: false` or a member
1144 + # of `anyOf`. `true` accepts every value; `false` rejects every value.
1145 if isinstance(json_schema, bool):
1146 if json_schema:
1005 - return t.Any # true schema accepts any value
1006 - else:
1007 - return None # false schema - will be filtered out in union processing
1147 + return t.Any
1148 + return _UnsatisfiableSchema
1149
1150 # Pre-filter boolean schemas from combiners
1151 filtered_schema = _filter_boolean_schemas(json_schema)
1152 filtered_schema = _resolve_unsatisfiable_references(filtered_schema)
1153 document_root = root_schema if root_schema is not None else json_schema
1154 _validate_dynamic_object_policies(json_schema, document_root)
1014 - return _filtered_schema_to_pydantic_type(
1155 + annotation = _filtered_schema_to_pydantic_type(
1156 filtered_schema,
1157 root_schema=document_root,
1158 )
1159 + # Two layers: Pydantic materializes the value (defaults, aliases, models),
1160 + # while the source schema decides acceptance. Keywords Pydantic cannot
1161 + # express get a Draft 7 "exact" check that runs before Pydantic coercion.
1162 + # Generated models already carry that check (see `_with_exact_validation`),
1163 + # so only non-model annotations are wrapped here. When Pydantic would
1164 + # narrow a valid value (e.g. `$ref`, `allOf`), the value is kept as-is.
1165 + if (
1166 + _requires_whole_schema_validation(json_schema)
1167 + and not _is_unsatisfiable_schema(annotation)
1168 + and not (isinstance(annotation, type) and issubclass(annotation, BaseModel))
1169 + ):
1170 + return _with_exact_validation_annotation(
1171 + t.Any if _needs_permissive_materialization(json_schema) else annotation,
1172 + json_schema,
1173 + document_root,
1174 + )
1175 + return annotation
1176
1177
1178 def _filtered_schema_to_pydantic_type(
@@ -1026,6 +1184,33 @@ def _filtered_schema_to_pydantic_type(
1184 if schema is None or _is_unsatisfiable_schema(schema):
1185 return _UnsatisfiableSchema
1186
1187 + if not _ASSERTION_KEYWORDS.intersection(schema):
1188 + # Pure-annotation schemas (only title/description/default/...) accept
1189 + # every value, exactly like the empty schema.
1190 + return t.Any
1191 +
1192 + schema_type = schema.get("type")
1193 + if isinstance(schema_type, list):
1194 + if not schema_type:
1195 + return _UnsatisfiableSchema
1196 + return _build_union_from_options(
1197 + [
1198 + {**schema, "type": member, "x-composio-strict-type": True}
1199 + for member in schema_type
1200 + ],
1201 + root_schema=root_schema,
1202 + )
1203 +
1204 + if schema_type is None and (
1205 + "enum" in schema
1206 + or "const" in schema
1207 + or (
1208 + _SCALAR_CONSTRAINT_KEYWORDS.intersection(schema)
1209 + and not _STRUCTURAL_KEYWORDS.intersection(schema)
1210 + )
1211 + ):
1212 + return _apply_scalar_constraints(t.Any, schema)
1213 +
1214 # Handle simple primitive types without complex combiners
1215 if _is_simple_primitive(schema):
1216 return _convert_simple_type(schema)
@@ -1048,10 +1233,801 @@ def _is_simple_primitive(schema: t.Dict[str, t.Any]) -> bool:
1233 )
1234
1235
1236 +def _matches_json_type(type_: str, value: t.Any) -> bool:
1237 + """JSON type membership per Draft 7 (booleans are not numbers, 2.0 is an integer)."""
1238 + if type_ == "string":
1239 + return isinstance(value, str)
1240 + if type_ == "boolean":
1241 + return isinstance(value, bool)
1242 + if type_ == "null":
1243 + return value is None
1244 + if type_ == "integer":
1245 + if isinstance(value, bool):
1246 + return False
1247 + return isinstance(value, int) or (
1248 + isinstance(value, float) and value.is_integer()
1249 + )
1250 + if type_ == "number":
1251 + return isinstance(value, (int, float)) and not isinstance(value, bool)
1252 + if type_ == "array":
1253 + return isinstance(value, list)
1254 + if type_ == "object":
1255 + return isinstance(value, dict)
1256 + return True
1257 +
1258 +
1259 +def _json_type_guard(type_: str) -> t.Callable[[t.Any], t.Any]:
1260 + def validate(value: t.Any) -> t.Any:
1261 + if not _matches_json_type(type_, value):
1262 + raise ValueError(f"value is not of JSON type {type_!r}")
1263 + return value
1264 +
1265 + return validate
1266 +
1267 +
1268 +def _strict_json_type_annotation(type_: str) -> t.Any:
1269 + """A type-checked annotation that still coerces integral floats for `integer`."""
1270 + if type_ == "null":
1271 + return type(None)
1272 + base = PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str)
1273 + return t.Annotated[base, BeforeValidator(_json_type_guard(type_))]
1274 +
1275 +
1276 def _convert_simple_type(schema: t.Dict[str, t.Any]) -> t.Type[t.Any]:
1277 """Convert simple primitive types directly."""
1278 type_ = schema.get("type", "string")
1054 - return t.cast(t.Type[t.Any], PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str))
1279 + use_strict_type = (
1280 + schema.get("x-composio-strict-type") is True
1281 + or "enum" in schema
1282 + or "const" in schema
1283 + )
1284 + base_type = (
1285 + _strict_json_type_annotation(type_)
1286 + if use_strict_type
1287 + else t.cast(t.Type[t.Any], PYDANTIC_TYPE_TO_PYTHON_TYPE.get(type_, str))
1288 + )
1289 + return _apply_scalar_constraints(base_type, schema)
1290 +
1291 +
1292 +def _json_values_equal(left: t.Any, right: t.Any) -> bool:
1293 + """Compare JSON values without treating booleans as numbers."""
1294 + if isinstance(left, bool) or isinstance(right, bool):
1295 + return type(left) is type(right) and left == right
1296 +
1297 + if isinstance(left, list) and isinstance(right, list):
1298 + return len(left) == len(right) and all(
1299 + _json_values_equal(left_item, right_item)
1300 + for left_item, right_item in zip(left, right)
1301 + )
1302 +
1303 + if isinstance(left, dict) and isinstance(right, dict):
1304 + return left.keys() == right.keys() and all(
1305 + _json_values_equal(left[key], right[key]) for key in left
1306 + )
1307 +
1308 + return bool(left == right)
1309 +
1310 +
1311 +def _allowed_values_validator(
1312 + allowed: t.Tuple[t.Any, ...],
1313 +) -> t.Callable[[t.Any], t.Any]:
1314 + """Create a Pydantic validator for JSON Schema enum/const values."""
1315 +
1316 + def validate(value: t.Any) -> t.Any:
1317 + if not any(_json_values_equal(value, candidate) for candidate in allowed):
1318 + raise ValueError(f"value must be one of {allowed!r}")
1319 + return value
1320 +
1321 + return validate
1322 +
1323 +
1324 +def _is_numeric(value: t.Any) -> bool:
1325 + return isinstance(value, (int, float)) and not isinstance(value, bool)
1326 +
1327 +
1328 +def _is_json_multiple_of(value: t.Any, multiple: t.Any) -> bool:
1329 + """Decimal-scaled multipleOf, matching the Zod and Effect converters.
1330 +
1331 + Raw float modulo misreports common decimal steps (0.3 % 0.1 != 0 in
1332 + binary floating point); comparing through `Decimal(str(...))` recovers the
1333 + author's decimal intent.
1334 + """
1335 + try:
1336 + return (decimal.Decimal(str(value)) % decimal.Decimal(str(multiple))) == 0
1337 + except (decimal.InvalidOperation, decimal.DivisionByZero):
1338 + return False
1339 +
1340 +
1341 +def _multiple_of_validator(multiple: t.Any) -> t.Callable[[t.Any], t.Any]:
1342 + def validate(value: t.Any) -> t.Any:
1343 + if _is_numeric(value) and not _is_json_multiple_of(value, multiple):
1344 + raise ValueError(f"value is not a multiple of {multiple!r}")
1345 + return value
1346 +
1347 + return validate
1348 +
1349 +
1350 +def _compile_pattern(pattern: str) -> t.Optional[t.Pattern[str]]:
1351 + try:
1352 + return re.compile(pattern)
1353 + except re.error:
1354 + logger.warning(
1355 + "Ignoring JSON Schema pattern %r: not a valid Python regular expression",
1356 + pattern,
1357 + )
1358 + return None
1359 +
1360 +
1361 +def _with_string_constraints(annotation: t.Any, schema: t.Dict[str, t.Any]) -> t.Any:
1362 + field_constraints: t.Dict[str, t.Any] = {}
1363 + if "minLength" in schema:
1364 + field_constraints["min_length"] = schema["minLength"]
1365 + if "maxLength" in schema:
1366 + field_constraints["max_length"] = schema["maxLength"]
1367 + if field_constraints:
1368 + annotation = t.Annotated[annotation, Field(**field_constraints)]
1369 + if "pattern" in schema:
1370 + annotation = _with_pattern_constraint(annotation, schema["pattern"])
1371 + return annotation
1372 +
1373 +
1374 +def _with_pattern_constraint(annotation: t.Any, pattern: str) -> t.Any:
1375 + """Prefer pydantic's native pattern; fall back to Python `re` when the Rust
1376 + regex crate rejects an ECMA construct such as look-around (legal in
1377 + Draft 7, whose regex dialect is ECMA-262)."""
1378 + candidate = t.Annotated[annotation, Field(pattern=pattern)]
1379 + try:
1380 + TypeAdapter(candidate)
1381 + return candidate
1382 + except Exception: # noqa: BLE001 - pydantic raises SchemaError subclasses
1383 + pass
1384 +
1385 + compiled = _compile_pattern(pattern)
1386 + if compiled is None:
1387 + return annotation
1388 +
1389 + def validate(value: t.Any) -> t.Any:
1390 + if isinstance(value, str) and compiled.search(value) is None:
1391 + raise ValueError(f"string does not match pattern {pattern!r}")
1392 + return value
1393 +
1394 + return t.Annotated[annotation, AfterValidator(validate)]
1395 +
1396 +
1397 +def _with_numeric_constraints(annotation: t.Any, schema: t.Dict[str, t.Any]) -> t.Any:
1398 + field_constraints: t.Dict[str, t.Any] = {}
1399 + if "minimum" in schema:
1400 + field_constraints["gt" if schema.get("exclusiveMinimum") is True else "ge"] = (
1401 + schema["minimum"]
1402 + )
1403 + if _is_numeric(schema.get("exclusiveMinimum")):
1404 + field_constraints["gt"] = schema["exclusiveMinimum"]
1405 +
1406 + if "maximum" in schema:
1407 + field_constraints["lt" if schema.get("exclusiveMaximum") is True else "le"] = (
1408 + schema["maximum"]
1409 + )
1410 + if _is_numeric(schema.get("exclusiveMaximum")):
1411 + field_constraints["lt"] = schema["exclusiveMaximum"]
1412 +
1413 + if field_constraints:
1414 + annotation = t.Annotated[annotation, Field(**field_constraints)]
1415 + if "multipleOf" in schema:
1416 + annotation = t.Annotated[
1417 + annotation, AfterValidator(_multiple_of_validator(schema["multipleOf"]))
1418 + ]
1419 + return annotation
1420 +
1421 +
1422 +def _check_numeric_keywords(schema: t.Dict[str, t.Any], value: t.Any) -> None:
1423 + minimum = schema.get("minimum")
1424 + if _is_numeric(minimum):
1425 + if schema.get("exclusiveMinimum") is True:
1426 + if value <= minimum:
1427 + raise ValueError(f"value must be greater than {minimum!r}")
1428 + elif value < minimum:
1429 + raise ValueError(f"value must be at least {minimum!r}")
1430 + exclusive_minimum = schema.get("exclusiveMinimum")
1431 + if _is_numeric(exclusive_minimum) and value <= exclusive_minimum:
1432 + raise ValueError(f"value must be greater than {exclusive_minimum!r}")
1433 +
1434 + maximum = schema.get("maximum")
1435 + if _is_numeric(maximum):
1436 + if schema.get("exclusiveMaximum") is True:
1437 + if value >= maximum:
1438 + raise ValueError(f"value must be less than {maximum!r}")
1439 + elif value > maximum:
1440 + raise ValueError(f"value must be at most {maximum!r}")
1441 + exclusive_maximum = schema.get("exclusiveMaximum")
1442 + if _is_numeric(exclusive_maximum) and value >= exclusive_maximum:
1443 + raise ValueError(f"value must be less than {exclusive_maximum!r}")
1444 +
1445 + if "multipleOf" in schema and not _is_json_multiple_of(value, schema["multipleOf"]):
1446 + raise ValueError(f"value is not a multiple of {schema['multipleOf']!r}")
1447 +
1448 +
1449 +def _typeless_constraint_validator(
1450 + schema: t.Dict[str, t.Any],
1451 +) -> t.Optional[t.Callable[[t.Any], t.Any]]:
1452 + """Draft 7 applies scalar constraints per instance type even without `type`."""
1453 + if not _SCALAR_CONSTRAINT_KEYWORDS.intersection(schema):
1454 + return None
1455 +
1456 + compiled_pattern = (
1457 + _compile_pattern(schema["pattern"]) if "pattern" in schema else None
1458 + )
1459 +
1460 + def validate(value: t.Any) -> t.Any:
1461 + if isinstance(value, str):
1462 + if "minLength" in schema and len(value) < schema["minLength"]:
1463 + raise ValueError(
1464 + f"string must contain at least {schema['minLength']} characters"
1465 + )
1466 + if "maxLength" in schema and len(value) > schema["maxLength"]:
1467 + raise ValueError(
1468 + f"string must contain at most {schema['maxLength']} characters"
1469 + )
1470 + if compiled_pattern is not None and compiled_pattern.search(value) is None:
1471 + raise ValueError(f"string does not match pattern {schema['pattern']!r}")
1472 + if _is_numeric(value):
1473 + _check_numeric_keywords(schema, value)
1474 + return value
1475 +
1476 + return validate
1477 +
1478 +
1479 +def _apply_scalar_constraints(
1480 + base_type: t.Type[t.Any],
1481 + schema: t.Dict[str, t.Any],
1482 +) -> t.Type[t.Any]:
1483 + """Apply scalar JSON Schema validation keywords to a Python annotation."""
1484 + type_ = schema.get("type")
1485 + annotation: t.Any = base_type
1486 +
1487 + if type_ == "string":
1488 + annotation = _with_string_constraints(annotation, schema)
1489 + elif type_ in ("integer", "number"):
1490 + annotation = _with_numeric_constraints(annotation, schema)
1491 + elif type_ is None:
1492 + validator = _typeless_constraint_validator(schema)
1493 + if validator is not None:
1494 + annotation = t.Annotated[annotation, AfterValidator(validator)]
1495 +
1496 + allowed: t.Optional[t.Tuple[t.Any, ...]] = None
1497 + if "const" in schema and "enum" in schema:
1498 + # Both keywords assert independently, so only their intersection is
1499 + # acceptable; a const outside the enum makes the schema unsatisfiable.
1500 + allowed = tuple(
1501 + candidate
1502 + for candidate in (schema["const"],)
1503 + if any(_json_values_equal(candidate, member) for member in schema["enum"])
1504 + )
1505 + elif "const" in schema:
1506 + allowed = (schema["const"],)
1507 + elif "enum" in schema:
1508 + allowed = tuple(schema["enum"])
1509 +
1510 + if allowed is not None:
1511 + if not allowed:
1512 + return _UnsatisfiableSchema
1513 + annotation = t.Annotated[
1514 + annotation,
1515 + AfterValidator(_allowed_values_validator(allowed)),
1516 + ]
1517 +
1518 + return t.cast(t.Type[t.Any], annotation)
1519 +
1520 +
1521 +def _schema_for_exact_validation(value: t.Any) -> t.Any:
1522 + """Turn internal boolean-schema markers back into JSON Schema values.
1523 +
1524 + Conversion replaces the literal ``false`` with `_UnsatisfiableSchema`; the
1525 + `jsonschema` validator needs the original ``false`` back.
1526 + """
1527 + if _is_unsatisfiable_schema(value):
1528 + return False
1529 + if isinstance(value, dict):
1530 + return {key: _schema_for_exact_validation(item) for key, item in value.items()}
1531 + if isinstance(value, list):
1532 + return [_schema_for_exact_validation(item) for item in value]
1533 + return value
1534 +
1535 +
1536 +_EXACT_SCHEMA_MAP_KEYWORDS = frozenset(
1537 + {
1538 + "$defs",
1539 + "definitions",
1540 + "dependencies",
1541 + "patternProperties",
1542 + "properties",
1543 + }
1544 +)
1545 +_EXACT_SCHEMA_ARRAY_KEYWORDS = frozenset({"allOf", "anyOf", "oneOf"})
1546 +_EXACT_SCHEMA_VALUE_KEYWORDS = frozenset(
1547 + {
1548 + "additionalItems",
1549 + "additionalProperties",
1550 + "contains",
1551 + "else",
1552 + "if",
1553 + "items",
1554 + "not",
1555 + "propertyNames",
1556 + "then",
1557 + }
1558 +)
1559 +
1560 +_REQUIRES_WHOLE_SCHEMA_VALIDATION = frozenset(
1561 + {
1562 + "$ref",
1563 + "additionalItems",
1564 + "contains",
1565 + "dependencies",
1566 + "else",
1567 + "if",
1568 + "maxItems",
1569 + "maxProperties",
1570 + "minItems",
1571 + "minProperties",
1572 + "not",
1573 + "propertyNames",
1574 + "required",
1575 + "then",
1576 + "uniqueItems",
1577 + }
1578 +)
1579 +
1580 +
1581 +def _contains_compound_literal(schema: t.Dict[str, t.Any]) -> bool:
1582 + values: t.List[t.Any] = []
1583 + if "const" in schema:
1584 + values.append(schema["const"])
1585 + enum = schema.get("enum")
1586 + if isinstance(enum, list):
1587 + values.extend(enum)
1588 + return any(isinstance(value, (dict, list)) for value in values)
1589 +
1590 +
1591 +def _one_of_needs_exact_validation(options: t.Any) -> bool:
1592 + """Return whether two oneOf branches can accept the same JSON type."""
1593 + if not isinstance(options, list) or len(options) < 2:
1594 + return False
1595 +
1596 + branch_types: t.List[t.Set[str]] = []
1597 + all_types = {"array", "boolean", "integer", "null", "number", "object", "string"}
1598 + for option in options:
1599 + if option is True or not isinstance(option, dict) or "type" not in option:
1600 + branch_types.append(set(all_types))
1601 + continue
1602 + if option is False:
1603 + branch_types.append(set())
1604 + continue
1605 + declared = option["type"]
1606 + types = {declared} if isinstance(declared, str) else set(declared)
1607 + if "number" in types:
1608 + types.add("integer")
1609 + branch_types.append(types)
1610 +
1611 + return any(
1612 + left.intersection(right)
1613 + for index, left in enumerate(branch_types)
1614 + for right in branch_types[index + 1 :]
1615 + )
1616 +
1617 +
1618 +def _combiner_has_assertion_siblings(schema: t.Dict[str, t.Any], keyword: str) -> bool:
1619 + return bool(_ASSERTION_KEYWORDS.intersection(schema) - {keyword})
1620 +
1621 +
1622 +def _requires_whole_schema_validation(schema: t.Any) -> bool:
1623 + """Whether the materializing converter needs an authoritative final guard.
1624 +
1625 + True when the schema (or any nested schema) uses a keyword that Pydantic
1626 + field constraints cannot express faithfully: `required`, `contains`,
1627 + `if`/`then`/`else`, `not`, `$ref`, unions (which Pydantic coerces across),
1628 + and so on. Those schemas get a Draft 7 check on the raw value first.
1629 + """
1630 + if isinstance(schema, bool) or not isinstance(schema, dict):
1631 + return False
1632 + if (
1633 + _REQUIRES_WHOLE_SCHEMA_VALIDATION.intersection(schema)
1634 + or "allOf" in schema
1635 + or (
1636 + schema.get("type") is None
1637 + and _TYPELESS_TYPE_SCOPED_KEYWORDS.intersection(schema)
1638 + )
1639 + # Pydantic unions coerce across members (`True` satisfies `integer |
1640 + # null`), so every combiner needs the exact check, not only those with
1641 + # sibling assertions or overlapping branches.
1642 + or "anyOf" in schema
1643 + or "oneOf" in schema
1644 + or _contains_compound_literal(schema)
1645 + ):
1646 + return True
1647 +
1648 + for key, child in schema.items():
1649 + if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
1650 + if any(
1651 + _requires_whole_schema_validation(value) for value in child.values()
1652 + ):
1653 + return True
1654 + elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
1655 + if any(_requires_whole_schema_validation(value) for value in child):
1656 + return True
1657 + elif key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1658 + values = child if isinstance(child, list) else [child]
1659 + if any(_requires_whole_schema_validation(value) for value in values):
1660 + return True
1661 +
1662 + return False
1663 +
1664 +
1665 +def _needs_permissive_materialization(
1666 + schema: t.Any,
1667 + visited: t.Optional[t.Set[int]] = None,
1668 +) -> bool:
1669 + """Detect schemas whose exact validator must not pipe into a narrower type.
1670 +
1671 + For `$ref`, `allOf`, and typeless assertions the Pydantic type the library
1672 + builds can be narrower than what the schema accepts. Once the Draft 7 check
1673 + has accepted the raw value, it is passed through as `t.Any` rather than
1674 + risk a second, stricter rejection or a lossy coercion.
1675 + """
1676 + if isinstance(schema, bool) or not isinstance(schema, dict):
1677 + return False
1678 + if visited is None:
1679 + visited = set()
1680 + if id(schema) in visited:
1681 + return False
1682 + visited.add(id(schema))
1683 +
1684 + if "$ref" in schema or "allOf" in schema:
1685 + return True
1686 + if schema.get("type") is None and (
1687 + _TYPELESS_TYPE_SCOPED_KEYWORDS.intersection(schema)
1688 + or {"if", "then", "else", "not"}.intersection(schema)
1689 + ):
1690 + return True
1691 + for key, child in schema.items():
1692 + if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
1693 + if any(
1694 + _needs_permissive_materialization(value, visited)
1695 + for value in child.values()
1696 + ):
1697 + return True
1698 + elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
1699 + if any(
1700 + _needs_permissive_materialization(value, visited) for value in child
1701 + ):
1702 + return True
1703 + elif key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1704 + values = child if isinstance(child, list) else [child]
1705 + if any(
1706 + _needs_permissive_materialization(value, visited) for value in values
1707 + ):
1708 + return True
1709 + return False
1710 +
1711 +
1712 +def _relax_exact_model_fields(
1713 + schema: t.Dict[str, t.Any],
1714 + base_model: t.Type[BaseModel],
1715 +) -> t.Type[BaseModel]:
1716 + """Let exact source validation own fields the library would over-narrow."""
1717 + properties = schema.get("properties")
1718 + if not isinstance(properties, dict):
1719 + return base_model
1720 +
1721 + field_definitions = {}
1722 + for internal_name, model_field in base_model.model_fields.items():
1723 + external_name = (
1724 + model_field.alias if isinstance(model_field.alias, str) else internal_name
1725 + )
1726 + property_schema = properties.get(external_name)
1727 + if not _needs_permissive_materialization(property_schema):
1728 + continue
1729 +
1730 + default = ... if model_field.is_required() else model_field.default
1731 + field_definitions[internal_name] = (
1732 + t.Any,
1733 + Field(
1734 + default,
1735 + alias=model_field.alias,
1736 + description=model_field.description,
1737 + examples=model_field.examples,
1738 + title=model_field.title,
1739 + ),
1740 + )
1741 +
1742 + if not field_definitions:
1743 + return base_model
1744 + return create_pydantic_model( # type: ignore[call-overload]
1745 + base_model.__name__,
1746 + __base__=base_model,
1747 + **field_definitions,
1748 + )
1749 +
1750 +
1751 +def _normalize_draft4_exclusive_bounds(value: t.Any) -> t.Any:
1752 + """Translate OpenAPI 3.0 boolean bounds without changing nearby keywords."""
1753 + if isinstance(value, bool) or not isinstance(value, dict):
1754 + return value
1755 +
1756 + normalized: t.Dict[str, t.Any] = {}
1757 + for key, child in value.items():
1758 + if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(child, dict):
1759 + normalized[key] = {
1760 + name: _normalize_draft4_exclusive_bounds(schema)
1761 + for name, schema in child.items()
1762 + }
1763 + elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS and isinstance(child, list):
1764 + normalized[key] = [
1765 + _normalize_draft4_exclusive_bounds(schema) for schema in child
1766 + ]
1767 + elif key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1768 + if isinstance(child, list):
1769 + normalized[key] = [
1770 + _normalize_draft4_exclusive_bounds(schema) for schema in child
1771 + ]
1772 + else:
1773 + normalized[key] = _normalize_draft4_exclusive_bounds(child)
1774 + else:
1775 + # Values under enum/const/default/examples are instance data, not
1776 + # schemas, and must remain byte-for-byte equivalent.
1777 + normalized[key] = child
1778 +
1779 + if normalized.get("exclusiveMinimum") is True and _is_numeric(
1780 + normalized.get("minimum")
1781 + ):
1782 + normalized["exclusiveMinimum"] = normalized.pop("minimum")
1783 + elif isinstance(normalized.get("exclusiveMinimum"), bool):
1784 + normalized.pop("exclusiveMinimum")
1785 +
1786 + if normalized.get("exclusiveMaximum") is True and _is_numeric(
1787 + normalized.get("maximum")
1788 + ):
1789 + normalized["exclusiveMaximum"] = normalized.pop("maximum")
1790 + elif isinstance(normalized.get("exclusiveMaximum"), bool):
1791 + normalized.pop("exclusiveMaximum")
1792 +
1793 + return normalized
1794 +
1795 +
1796 +def _exact_validation_multiple_of(
1797 + _validator: t.Any,
1798 + multiple: t.Any,
1799 + instance: t.Any,
1800 + _schema: t.Any,
1801 +) -> t.Iterator[t.Any]:
1802 + if _is_numeric(instance) and not _is_json_multiple_of(instance, multiple):
1803 + yield jsonschema_exceptions.ValidationError(
1804 + f"{instance!r} is not a multiple of {multiple!r}"
1805 + )
1806 +
1807 +
1808 +_PATTERN_MATCHER_CACHE: t.Dict[str, t.Optional[t.Callable[[str], bool]]] = {}
1809 +
1810 +
1811 +def _pattern_matcher(pattern: str) -> t.Optional[t.Callable[[str], bool]]:
1812 + """Match `pattern` with pydantic's linear-time Rust regex when it can
1813 + compile it, falling back to Python `re` only for ECMA-only constructs."""
1814 + if pattern in _PATTERN_MATCHER_CACHE:
1815 + return _PATTERN_MATCHER_CACHE[pattern]
1816 + matcher: t.Optional[t.Callable[[str], bool]] = None
1817 + if _pattern_supported_by_pydantic(pattern):
1818 + adapter = TypeAdapter(t.Annotated[str, Field(pattern=pattern)])
1819 +
1820 + def match_with_pydantic(value: str) -> bool:
1821 + try:
1822 + adapter.validate_python(value, strict=True)
1823 + except ValidationError:
1824 + return False
1825 + return True
1826 +
1827 + matcher = match_with_pydantic
1828 + else:
1829 + compiled = _compile_pattern(pattern)
1830 + if compiled is not None:
1831 +
1832 + def match_with_re(value: str) -> bool:
1833 + return compiled.search(value) is not None
1834 +
1835 + matcher = match_with_re
1836 + _PATTERN_MATCHER_CACHE[pattern] = matcher
1837 + return matcher
1838 +
1839 +
1840 +def _exact_validation_pattern(
1841 + _validator: Validator,
1842 + pattern: t.Any,
1843 + instance: t.Any,
1844 + _schema: t.Any,
1845 +) -> t.Iterator[t.Any]:
1846 + if not isinstance(instance, str) or not isinstance(pattern, str):
1847 + return
1848 + matcher = _pattern_matcher(pattern)
1849 + if matcher is not None and not matcher(instance):
1850 + yield jsonschema_exceptions.ValidationError(
1851 + f"{instance!r} does not match {pattern!r}"
1852 + )
1853 +
1854 +
1855 +# A bare registry resolves only references inside the schema document and
1856 +# raises on anything else; jsonschema's default registry falls back to
1857 +# fetching unknown URIs over the network.
1858 +_LOCAL_ONLY_REGISTRY: Registry[t.Any] = Registry()
1859 +
1860 +
1861 +def _reject_external_references(schema: t.Any) -> None:
1862 + """Fail at conversion time on any `$ref` that is not a local JSON Pointer.
1863 +
1864 + Only schema positions are walked; `const`, `default`, `enum`, and
1865 + `examples` hold instance data.
1866 + """
1867 + if isinstance(schema, list):
1868 + for item in schema:
1869 + _reject_external_references(item)
1870 + return
1871 + if not isinstance(schema, dict):
1872 + return
1873 + reference = schema.get("$ref")
1874 + if isinstance(reference, str) and not reference.startswith("#"):
1875 + raise ValueError(
1876 + f"External schema reference {reference!r} is not supported; "
1877 + "only local references (#/...) are resolved"
1878 + )
1879 + for keyword, value in schema.items():
1880 + if keyword in _SCHEMA_VALUED_KEYWORDS or keyword in _SCHEMA_LIST_KEYWORDS:
1881 + _reject_external_references(value)
1882 + elif keyword in _SCHEMA_MAP_KEYWORDS:
1883 + if isinstance(value, dict):
1884 + for entry in value.values():
1885 + _reject_external_references(entry)
1886 + elif keyword == "items":
1887 + _reject_external_references(value)
1888 + elif keyword == "dependencies" and isinstance(value, dict):
1889 + for entry in value.values():
1890 + if isinstance(entry, (dict, bool)):
1891 + _reject_external_references(entry)
1892 +
1893 +
1894 +def _is_closed_object_branch(branch: t.Any) -> bool:
1895 + return (
1896 + isinstance(branch, dict)
1897 + and isinstance(branch.get("properties"), dict)
1898 + and len(branch["properties"]) > 0
1899 + and "additionalProperties" not in branch
1900 + and "patternProperties" not in branch
1901 + and "$ref" not in branch
1902 + )
1903 +
1904 +
1905 +def _close_all_of_branches(schema: t.Any) -> t.Any:
1906 + """Apply the omitted-`additionalProperties` strictness rule once per `allOf`.
1907 +
1908 + Draft 7 already lets sibling object branches accept each other's keys, so
1909 + the exact validator only needs the strictness a lone named-property object
1910 + would have had: the union of every branch's declared keys, applied at the
1911 + `allOf` node. Mirrors `parseAllOf` in @composio/json-schema-to-zod and
1912 + `openAllOfBranches` in @composio/json-schema-to-effect-schema.
1913 + """
1914 + if isinstance(schema, list):
1915 + return [_close_all_of_branches(item) for item in schema]
1916 + if not isinstance(schema, dict):
1917 + return schema
1918 +
1919 + result: t.Dict[str, t.Any] = {}
1920 + for key, value in schema.items():
1921 + if key in _EXACT_SCHEMA_MAP_KEYWORDS and isinstance(value, dict):
1922 + result[key] = {
1923 + name: _close_all_of_branches(child) for name, child in value.items()
1924 + }
1925 + elif key in _EXACT_SCHEMA_ARRAY_KEYWORDS or key in _EXACT_SCHEMA_VALUE_KEYWORDS:
1926 + result[key] = _close_all_of_branches(value)
1927 + else:
1928 + result[key] = value
1929 +
1930 + branches = schema.get("allOf")
1931 + if (
1932 + isinstance(branches, list)
1933 + and len(branches) >= 2
1934 + and all(_is_closed_object_branch(branch) for branch in branches)
1935 + and not {"properties", "patternProperties", "additionalProperties"}
1936 + & set(schema)
1937 + ):
1938 + result["properties"] = {
1939 + name: True for branch in branches for name in branch["properties"]
1940 + }
1941 + result["additionalProperties"] = False
1942 + return result
1943 +
1944 +
1945 +def _validate_json_schema(
1946 + schema: t.Dict[str, t.Any],
1947 + root_schema: t.Dict[str, t.Any],
1948 +) -> t.Callable[[t.Any], t.Any]:
1949 + """Compile an exact JSON Schema acceptance check for a Pydantic model."""
1950 + validation_schema = _close_all_of_branches(
1951 + _normalize_draft4_exclusive_bounds(_schema_for_exact_validation(schema))
1952 + )
1953 + validation_root = _close_all_of_branches(
1954 + _normalize_draft4_exclusive_bounds(_schema_for_exact_validation(root_schema))
1955 + )
1956 + _reject_external_references(validation_root)
1957 + _reject_external_references(validation_schema)
1958 + # The SDK contract is Draft 7 plus the OpenAPI 3.0 boolean spelling for
1959 + # exclusive bounds. Falling the entire document back to Draft 4 would make
1960 + # `contains`, `const`, `if`/`then`/`else`, and `propertyNames` disappear.
1961 + validator_class = jsonschema_validators.Draft7Validator
1962 + # Align multipleOf with the decimal-scaled checks in the Zod and Effect
1963 + # converters instead of raw float modulo.
1964 + # `pattern` goes through pydantic's Rust regex where possible so a
1965 + # backtracking pattern cannot stall validation (Python `re` is exponential
1966 + # on inputs such as `(a+)+$`).
1967 + validator_class = jsonschema_validators.extend(
1968 + validator_class,
1969 + {
1970 + "multipleOf": _exact_validation_multiple_of,
1971 + "pattern": _exact_validation_pattern,
1972 + },
1973 + )
1974 + validator = validator_class(
1975 + validation_root,
1976 + registry=_LOCAL_ONLY_REGISTRY,
1977 + ).evolve(schema=validation_schema)
1978 +
1979 + def validate(value: t.Any) -> t.Any:
1980 + error = next(validator.iter_errors(value), None)
1981 + if error is not None:
1982 + location = ".".join(str(part) for part in error.path)
1983 + message = f"{location}: {error.message}" if location else error.message
1984 + raise ValueError(message)
1985 + return value
1986 +
1987 + return validate
1988 +
1989 +
1990 +def _with_exact_validation_annotation(
1991 + annotation: t.Any,
1992 + schema: t.Dict[str, t.Any],
1993 + root_schema: t.Dict[str, t.Any],
1994 +) -> t.Type[t.Any]:
1995 + """Validate the raw value before Pydantic coercion or default handling."""
1996 + validate_schema = _validate_json_schema(schema, root_schema)
1997 + return t.cast(
1998 + t.Type[t.Any],
1999 + t.Annotated[annotation, BeforeValidator(validate_schema)],
2000 + )
2001 +
2002 +
2003 +def _with_exact_validation(
2004 + model: t.Type[BaseModel],
2005 + schema: t.Dict[str, t.Any],
2006 + root_schema: t.Dict[str, t.Any],
2007 +) -> t.Type[t.Any]:
2008 + """Keep model materialization while enforcing the source schema first."""
2009 + validate_schema = _validate_json_schema(schema, root_schema)
2010 +
2011 + def validate_source_schema(cls, value: t.Any) -> t.Any:
2012 + return validate_schema(value)
2013 +
2014 + validator = model_validator(mode="before")(
2015 + t.cast(t.Any, classmethod(validate_source_schema))
2016 + )
2017 +
2018 + name = model.__name__
2019 + return t.cast(
2020 + t.Type[BaseModel],
2021 + type(
2022 + name,
2023 + (model,),
2024 + {
2025 + "__module__": __name__,
2026 + "__qualname__": name,
2027 + "_validate_source_schema": validator,
2028 + },
2029 + ),
2030 + )
2031
2032
2033 def _convert_object_with_unsatisfiable_properties(
@@ -1083,7 +2059,7 @@ def _convert_object_with_unsatisfiable_properties(
2059 ],
2060 }
2061 base_model = create_model_from_schema(
1086 - base_schema,
2062 + _normalize_schema_for_library(base_schema),
2063 allow_undefined_array_items=True,
2064 allow_undefined_type=True,
2065 )
@@ -1118,6 +2094,130 @@ def _convert_object_with_unsatisfiable_properties(
2094 )
2095
2096
2097 +_TYPE_ARRAY_CHILD_KEYWORDS_MAPS = (
2098 + "properties",
2099 + "patternProperties",
2100 + "$defs",
2101 + "definitions",
2102 +)
2103 +_TYPE_ARRAY_CHILD_KEYWORDS_LISTS = ("anyOf", "allOf", "oneOf")
2104 +_TYPE_ARRAY_CHILD_KEYWORDS_SCHEMAS = (
2105 + "items",
2106 + "additionalItems",
2107 + "additionalProperties",
2108 + "contains",
2109 + "propertyNames",
2110 + "not",
2111 + "if",
2112 + "then",
2113 + "else",
2114 +)
2115 +
2116 +
2117 +_PYDANTIC_PATTERN_SUPPORT_CACHE: t.Dict[str, bool] = {}
2118 +
2119 +
2120 +def _pattern_supported_by_pydantic(pattern: str) -> bool:
2121 + cached = _PYDANTIC_PATTERN_SUPPORT_CACHE.get(pattern)
2122 + if cached is not None:
2123 + return cached
2124 + try:
2125 + TypeAdapter(t.Annotated[str, Field(pattern=pattern)])
2126 + supported = True
2127 + except Exception: # noqa: BLE001 - pydantic raises SchemaError subclasses
2128 + supported = False
2129 + _PYDANTIC_PATTERN_SUPPORT_CACHE[pattern] = supported
2130 + return supported
2131 +
2132 +
2133 +def _normalize_schema_for_library(schema: t.Any) -> t.Any:
2134 + """Rewrite constructs the json-schema-to-pydantic library mishandles.
2135 +
2136 + - `type: [...]` becomes an equivalent `anyOf` of single-type schemas: the
2137 + library applies every sibling constraint to every union member, so
2138 + `{"type": ["string", "number"], "minLength": 2, "minimum": 10}` raises
2139 + `TypeError` at validation time when a valid string hits the numeric
2140 + constraint. Scoping constraints per member is semantically identical
2141 + under Draft 7 (mismatched-type keywords are ignored).
2142 + - `pattern` values the Rust regex crate rejects (ECMA look-around) are
2143 + dropped from the library input; the exact-validation layer still
2144 + enforces them through Python `re`.
2145 + """
2146 + if not isinstance(schema, dict):
2147 + return schema
2148 +
2149 + result: t.Dict[str, t.Any] = {}
2150 + for key, value in schema.items():
2151 + if key in _TYPE_ARRAY_CHILD_KEYWORDS_MAPS and isinstance(value, dict):
2152 + result[key] = {
2153 + name: _normalize_schema_for_library(child)
2154 + for name, child in value.items()
2155 + }
2156 + elif key in _TYPE_ARRAY_CHILD_KEYWORDS_LISTS and isinstance(value, list):
2157 + result[key] = [_normalize_schema_for_library(child) for child in value]
2158 + elif key in _TYPE_ARRAY_CHILD_KEYWORDS_SCHEMAS:
2159 + result[key] = _normalize_schema_for_library(value)
2160 + else:
2161 + result[key] = value
2162 +
2163 + pattern = result.get("pattern")
2164 + if isinstance(pattern, str) and not _pattern_supported_by_pydantic(pattern):
2165 + del result["pattern"]
2166 +
2167 + # Draft-4 boolean exclusive flags: the library reads the boolean itself as
2168 + # the numeric bound (lt=True becomes "less than 1"). Translate them to the
2169 + # Draft 7 numeric spelling before the library sees them.
2170 + if result.get("exclusiveMinimum") is True and _is_numeric(result.get("minimum")):
2171 + result["exclusiveMinimum"] = result.pop("minimum")
2172 + elif isinstance(result.get("exclusiveMinimum"), bool):
2173 + del result["exclusiveMinimum"]
2174 + if result.get("exclusiveMaximum") is True and _is_numeric(result.get("maximum")):
2175 + result["exclusiveMaximum"] = result.pop("maximum")
2176 + elif isinstance(result.get("exclusiveMaximum"), bool):
2177 + del result["exclusiveMaximum"]
2178 +
2179 + # A one-member type array is the same as the bare type, and collapsing it
2180 + # lets the constraint scoping below apply.
2181 + if isinstance(result.get("type"), list) and len(result["type"]) == 1:
2182 + result["type"] = result["type"][0]
2183 +
2184 + # The library applies scalar keywords unconditionally, so a keyword that
2185 + # does not scope to the declared type (or any keyword on a typeless
2186 + # schema) raises TypeError at validation time on mismatched instances.
2187 + # Drop them from the library input; the exact-validation layer that wraps
2188 + # every object conversion still enforces them per Draft 7.
2189 + declared_type = result.get("type")
2190 + if isinstance(declared_type, str):
2191 + scoped_keywords = _TYPE_SCOPED_KEYWORDS.get(declared_type)
2192 + if scoped_keywords is not None:
2193 + for keyword in _SCALAR_CONSTRAINT_KEYWORDS - scoped_keywords:
2194 + result.pop(keyword, None)
2195 + elif declared_type is None:
2196 + for keyword in _SCALAR_CONSTRAINT_KEYWORDS:
2197 + result.pop(keyword, None)
2198 +
2199 + type_ = result.get("type")
2200 + if not isinstance(type_, list) or len(type_) < 2:
2201 + return result
2202 +
2203 + members = []
2204 + for member in type_:
2205 + member_schema: t.Dict[str, t.Any] = {"type": member}
2206 + scoped = _TYPE_SCOPED_KEYWORDS.get(member, frozenset())
2207 + for keyword in scoped | _TYPE_ARRAY_SHARED_KEYWORDS:
2208 + if keyword in result:
2209 + member_schema[keyword] = result[keyword]
2210 + members.append(member_schema)
2211 +
2212 + wrapper: t.Dict[str, t.Any] = {
2213 + key: value
2214 + for key, value in result.items()
2215 + if key in _TYPE_ARRAY_WRAPPER_KEYWORDS
2216 + }
2217 + wrapper["anyOf"] = members
2218 + return wrapper
2219 +
2220 +
2221 def _convert_with_library(
2222 schema: t.Dict[str, t.Any],
2223 *,
@@ -1137,18 +2237,30 @@ def _convert_with_library(
2237 )
2238 except (SchemaError, CombinerError) as e:
2239 logger.debug(
1140 - f"Library schema conversion failed: {e}, falling back to string"
2240 + f"Library schema conversion failed: {e}, preserving exact validation"
2241 + )
2242 + return _with_exact_validation_annotation(
2243 + t.Any,
2244 + schema,
2245 + document_root,
2246 )
1142 - return str
2247 except Exception as e:
2248 logger.debug(
1145 - f"Unexpected error in schema conversion: {e}, falling back to string"
2249 + f"Unexpected error in schema conversion: {e}, preserving exact validation"
2250 )
1147 - return str
1148 - return apply_object_policy(
2251 + return _with_exact_validation_annotation(
2252 + t.Any,
2253 + schema,
2254 + document_root,
2255 + )
2256 + return _with_exact_validation(
2257 + apply_object_policy(
2258 + schema,
2259 + _apply_nested_object_policies(schema, base_model, document_root),
2260 + root_schema=document_root,
2261 + ),
2262 schema,
1150 - _apply_nested_object_policies(schema, base_model, document_root),
1151 - root_schema=document_root,
2263 + document_root,
2264 )
2265 # A property-less object with no dynamic-key constraints accepts and
2266 # preserves arbitrary content. Modelling it as an empty Pydantic
@@ -1160,25 +2272,38 @@ def _convert_with_library(
2272
2273 try:
2274 base_model = create_model_from_schema(
1163 - schema,
2275 + _normalize_schema_for_library(schema),
2276 allow_undefined_array_items=True,
2277 allow_undefined_type=True,
2278 )
2279 except (SchemaError, CombinerError) as e:
2280 logger.debug(
1169 - f"Library schema conversion failed: {e}, falling back to string"
2281 + f"Library schema conversion failed: {e}, preserving exact validation"
2282 + )
2283 + return _with_exact_validation_annotation(
2284 + t.Any,
2285 + schema,
2286 + document_root,
2287 )
1171 - return str
2288 except Exception as e:
2289 logger.debug(
1174 - f"Unexpected error in schema conversion: {e}, falling back to string"
2290 + f"Unexpected error in schema conversion: {e}, preserving exact validation"
2291 + )
2292 + return _with_exact_validation_annotation(
2293 + t.Any,
2294 + schema,
2295 + document_root,
2296 )
1176 - return str
2297
1178 - return apply_object_policy(
2298 + base_model = _relax_exact_model_fields(schema, base_model)
2299 + return _with_exact_validation(
2300 + apply_object_policy(
2301 + schema,
2302 + _apply_nested_object_policies(schema, base_model, document_root),
2303 + root_schema=document_root,
2304 + ),
2305 schema,
1180 - _apply_nested_object_policies(schema, base_model, document_root),
1181 - root_schema=document_root,
2306 + document_root,
2307 )
2308
2309 try:
@@ -1206,13 +2331,17 @@ def _convert_with_library(
2331 return _convert_simple_type(schema)
2332
2333 except (SchemaError, CombinerError) as e:
1209 - logger.debug(f"Library schema conversion failed: {e}, falling back to string")
1210 - return str
2334 + logger.debug(
2335 + f"Library schema conversion failed: {e}, preserving exact validation"
2336 + )
2337 + document_root = root_schema if root_schema is not None else schema
2338 + return _with_exact_validation_annotation(t.Any, schema, document_root)
2339 except Exception as e:
2340 logger.debug(
1213 - f"Unexpected error in schema conversion: {e}, falling back to string"
2341 + f"Unexpected error in schema conversion: {e}, preserving exact validation"
2342 )
1215 - return str
2343 + document_root = root_schema if root_schema is not None else schema
2344 + return _with_exact_validation_annotation(t.Any, schema, document_root)
2345
2346
2347 def _handle_toplevel_combiner(
@@ -1228,14 +2357,34 @@ def _handle_toplevel_combiner(
2357 try:
2358 # Try direct conversion - library handles anyOf/oneOf/allOf at top level
2359 result = create_model_from_schema(
1231 - schema,
2360 + _normalize_schema_for_library(schema),
2361 allow_undefined_array_items=True,
2362 allow_undefined_type=True,
2363 )
2364 if result is type(None):
1236 - return t.Optional[t.Any]
1237 - # If result is a type (like a Union or Optional), return it directly
1238 - # If result is a model class, return it
2365 + return type(None)
2366 + if "allOf" in schema:
2367 + options = schema.get("allOf")
2368 + requires_object = isinstance(options, list) and any(
2369 + isinstance(option, dict) and option.get("type") == "object"
2370 + for option in options
2371 + )
2372 + if (
2373 + requires_object
2374 + and isinstance(result, type)
2375 + and issubclass(result, BaseModel)
2376 + ):
2377 + document_root = root_schema if root_schema is not None else schema
2378 + return _with_exact_validation(result, schema, document_root)
2379 +
2380 + # The library models scalar intersections as object models.
2381 + # Preserve the JSON value and let exact validation own acceptance.
2382 + return t.Any
2383 + # A library model for anyOf/oneOf drops sibling assertions such as
2384 + # `required` and exclusive oneOf matching; let the source schema own it.
2385 + if isinstance(result, type) and issubclass(result, BaseModel):
2386 + document_root = root_schema if root_schema is not None else schema
2387 + return _with_exact_validation(result, schema, document_root)
2388 return result
2389 except (SchemaError, CombinerError):
2390 pass
@@ -1277,7 +2426,7 @@ def _build_union_from_options(
2426 pydantic_types.append(ptype)
2427
2428 if len(pydantic_types) == 0:
1280 - return t.Optional[t.Any] if has_null else _UnsatisfiableSchema # type: ignore
2429 + return type(None) if has_null else _UnsatisfiableSchema
2430
2431 if len(pydantic_types) == 1:
2432 base_type = pydantic_types[0]
python/composio/utils/shared.py
+46 -44
@@ -19,11 +19,12 @@ from composio.exceptions import InvalidParams, InvalidSchemaError
19 from composio.utils.json_schema import dereference_json_schema
20 from composio.utils.logging import get as get_logger
21 from composio.utils.schema_converter import (
22 + _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE,
23 CONTAINER_TYPE,
24 FALLBACK_VALUES,
25 PYDANTIC_TYPE_TO_PYTHON_TYPE,
25 - _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE,
26 _mark_explicit_default_fields,
27 + _with_exact_validation,
28 apply_object_policy,
29 json_schema_to_pydantic_type,
30 )
@@ -471,7 +472,7 @@ def _coerce_default_value(
472
473 def json_schema_to_pydantic_field(
474 name: str,
474 - json_schema: t.Dict[str, t.Any],
475 + json_schema: t.Union[t.Dict[str, t.Any], bool],
476 required: t.List[str],
477 skip_default: bool = False,
478 *,
@@ -486,19 +487,23 @@ def json_schema_to_pydantic_field(
487 :param root_schema: Full schema document used to resolve local references.
488 :return: A Pydantic field definition.
489 """
489 - description = json_schema.get("description")
490 - if "oneOf" in json_schema:
490 + # A property schema may be the literal `true`/`false` (JSON Schema
491 + # draft-06+); those carry no metadata, so read annotations from an empty
492 + # object and let `json_schema_to_pydantic_type` decide the type.
493 + schema_object = json_schema if isinstance(json_schema, dict) else {}
494 + description = schema_object.get("description")
495 + if "oneOf" in schema_object:
496 description = " | ".join(
492 - [option.get("description", "") for option in json_schema["oneOf"]]
497 + [option.get("description", "") for option in schema_object["oneOf"]]
498 )
499 description = f"Any of the following options(separated by |): {description}"
500
496 - examples = json_schema.get("examples", [])
497 - default = json_schema.get("default")
501 + examples = schema_object.get("examples", [])
502 + default = schema_object.get("default")
503
504 # Coerce default value to match expected type from schema
505 if default is not None:
501 - default = _coerce_default_value(default, json_schema)
506 + default = _coerce_default_value(default, schema_object)
507
508 # Check if the field name is a reserved Pydantic name
509 original_name = name
@@ -588,10 +593,17 @@ def json_schema_to_model(
593 setattr(base_model, _EXPLICIT_DEFAULT_FIELDS_ATTRIBUTE, frozenset())
594 else:
595 _mark_explicit_default_fields(base_model, json_schema, json_schema)
591 - return apply_object_policy(
596 + # Exact acceptance is shared with `json_schema_to_pydantic_type` so every
597 + # Python entry point agrees with the Zod and Effect converters about which
598 + # inputs a schema admits.
599 + return _with_exact_validation(
600 + apply_object_policy(
601 + json_schema,
602 + base_model,
603 + model_name=model_name,
604 + ),
605 + json_schema,
606 json_schema,
593 - base_model,
594 - model_name=model_name,
607 )
608
609
@@ -616,41 +628,27 @@ def pydantic_model_from_param_schema(param_schema: t.Dict) -> t.Type:
628 required_props = param_schema.get("required", [])
629
630 if param_schema.get("type") == "array":
619 - # print("param_schema inside array - ", param_schema)
620 - item_schema = param_schema.get("items")
621 - if item_schema:
622 - ItemType = t.cast(
623 - t.Type,
624 - json_schema_to_pydantic_type(
625 - json_schema=item_schema,
626 - ),
627 - )
628 - return t.List[ItemType] # type: ignore
629 - return t.List
631 + return t.cast(t.Type, json_schema_to_pydantic_type(param_schema))
632
633 for prop_name, prop_info in param_schema.get("properties", {}).items():
632 - prop_type = prop_info.get("type")
633 - prop_title = prop_info.get("title", prop_name).replace(" ", "")
634 - prop_default = prop_info.get("default", FALLBACK_VALUES.get(prop_type))
635 - if (
636 - prop_type is not None
637 - and prop_type in PYDANTIC_TYPE_TO_PYTHON_TYPE
638 - and prop_type not in CONTAINER_TYPE
639 - ):
640 - signature_prop_type = PYDANTIC_TYPE_TO_PYTHON_TYPE[prop_type]
641 - elif prop_type is None:
642 - # Schema uses anyOf/allOf/oneOf/$ref instead of a top-level "type" key.
643 - # Delegate to json_schema_to_pydantic_type which handles all combiners.
644 - signature_prop_type = t.cast(
645 - t.Type,
646 - json_schema_to_pydantic_type(json_schema=prop_info),
647 - )
648 - else:
649 - signature_prop_type = pydantic_model_from_param_schema(prop_info)
634 + prop_object = prop_info if isinstance(prop_info, dict) else {}
635 + prop_type = prop_object.get("type")
636 + prop_title = prop_object.get("title", prop_name).replace(" ", "")
637 + fallback = (
638 + FALLBACK_VALUES.get(prop_type) if isinstance(prop_type, str) else None
639 + )
640 + prop_default = prop_object.get("default", fallback)
641 + signature_prop_type = t.cast(
642 + t.Type,
643 + json_schema_to_pydantic_type(
644 + json_schema=prop_info,
645 + root_schema=param_schema,
646 + ),
647 + )
648
649 field_kwargs = {
652 - "description": prop_info.get(
653 - "description", prop_info.get("desc", prop_title)
650 + "description": prop_object.get(
651 + "description", prop_object.get("desc", prop_title)
652 ),
653 }
654
@@ -673,13 +671,17 @@ def pydantic_model_from_param_schema(param_schema: t.Dict) -> t.Type:
671 )
672
673 if not required_fields and not optional_fields:
676 - return t.Dict
674 + # Nothing to materialize: let the shared converter pick the annotation
675 + # so `allOf`/`anyOf`/`$ref` and typeless assertions keep the same exact
676 + # validation and permissive materialization as the other entry points.
677 + return t.cast(t.Type, json_schema_to_pydantic_type(param_schema))
678
678 - return create_model( # type: ignore
679 + model = create_model( # type: ignore
680 param_title,
681 **required_fields,
682 **optional_fields,
683 )
684 + return _with_exact_validation(model, param_schema, param_schema)
685
686
687 def get_signature_format_from_schema_params(
python/providers/gemini/composio_gemini/provider.py
+23 -8
@@ -9,6 +9,8 @@ import types as pytypes
9 import typing as t
10 from inspect import Parameter, Signature
11
12 +from pydantic import BaseModel
13 +
14 from composio.client.types import Tool
15 from composio.core.provider import AgenticProvider
16 from composio.core.provider.agentic import AgenticProviderExecuteFn
@@ -16,7 +18,9 @@ from composio.utils.shared import (
18 ToolSchemaAliases,
19 alias_tool_input_schema,
20 get_pydantic_signature_format_from_schema_params,
21 + json_schema_to_model,
22 normalize_tool_arguments,
23 + validate_and_serialize_tool_arguments,
24 )
25
26 # google-genai is only needed for handle_response (backward compat)
@@ -83,7 +87,8 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
87 def __init__(self, **kwargs: t.Any):
88 super().__init__(**kwargs)
89 self._executors: t.Dict[
86 - str, t.Tuple[AgenticProviderExecuteFn, ToolSchemaAliases]
90 + str,
91 + t.Tuple[AgenticProviderExecuteFn, ToolSchemaAliases, t.Type[BaseModel]],
92 ] = {}
93
94 def wrap_tool(
@@ -100,14 +105,21 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
105 2. Store it in the AFC ``function_map`` for automatic execution
106 """
107 aliases = alias_tool_input_schema(schema=tool.input_parameters)
103 - self._executors[tool.slug] = (execute_tool, aliases)
108 + args_schema = json_schema_to_model(
109 + aliases.schema,
110 + skip_default=self.skip_default,
111 + )
112 + self._executors[tool.slug] = (execute_tool, aliases, args_schema)
113
114 def function(**kwargs: t.Any) -> t.Dict:
115 """Composio tool execution wrapper."""
116 kwargs = _to_serializable(kwargs)
117 + kwargs = validate_and_serialize_tool_arguments(
118 + args_schema,
119 + normalize_tool_arguments(kwargs),
120 + )
121 kwargs = aliases.restore_arguments(kwargs)
109 - # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
110 - result = execute_tool(tool.slug, normalize_tool_arguments(kwargs))
122 + result = execute_tool(tool.slug, kwargs)
123 return _process_execution_result(result)
124
125 # Create a real function object (passes inspect.isfunction)
@@ -186,11 +198,14 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
198 if fc.name not in self._executors:
199 continue
200
189 - execute_tool, aliases = self._executors[fc.name]
190 - arguments = aliases.restore_arguments(dict(fc.args))
191 - result = execute_tool(
192 - slug=fc.name, arguments=normalize_tool_arguments(arguments)
201 + # Same validate -> serialize -> alias sequence as the AFC callable.
202 + execute_tool, aliases, args_schema = self._executors[fc.name]
203 + arguments = validate_and_serialize_tool_arguments(
204 + args_schema,
205 + normalize_tool_arguments(_to_serializable(dict(fc.args))),
206 )
207 + arguments = aliases.restore_arguments(arguments)
208 + result = execute_tool(slug=fc.name, arguments=arguments)
209 processed = _process_execution_result(result)
210
211 function_responses.append(
python/pyproject.toml
+1
@@ -34,6 +34,7 @@ dev = [
34 "pytest>=9.1.1",
35 "pytest-timeout>=2.4.0",
36 "pytest-mock>=3.15.1",
37 + "hypothesis>=6.140.3",
38 "requests>=2.34.2",
39 "ruff>=0.16.0",
40 # Langchain provider demo
python/tests/fixtures/json-schema-conversion/object-cases.json
+491
@@ -645,6 +645,333 @@
645 }
646 ]
647 },
648 + {
649 + "id": "primitive-boolean-property-schemas",
650 + "description": "Boolean property schemas accept every value for true and reject every supplied value for false.",
651 + "schema": {
652 + "type": "object",
653 + "properties": { "allowed": true, "forbidden": false },
654 + "required": ["allowed"]
655 + },
656 + "instances": [
657 + { "input": { "allowed": { "nested": 1 } }, "accepted": true },
658 + { "input": { "allowed": 42, "forbidden": "present" }, "accepted": false }
659 + ]
660 + },
661 + {
662 + "id": "primitive-empty-and-null-schemas",
663 + "description": "An empty schema accepts any value while a pure null schema accepts only null.",
664 + "schema": {
665 + "type": "object",
666 + "properties": { "anything": {}, "nullOnly": { "type": "null" } },
667 + "required": ["anything", "nullOnly"]
668 + },
669 + "instances": [
670 + { "input": { "anything": 42, "nullOnly": null }, "accepted": true },
671 + { "input": { "anything": null, "nullOnly": "not-null" }, "accepted": false }
672 + ]
673 + },
674 + {
675 + "id": "primitive-type-array-union",
676 + "description": "Every member of a JSON Schema type array remains accepted.",
677 + "schema": {
678 + "type": "object",
679 + "properties": { "value": { "type": ["string", "integer", "null"] } },
680 + "required": ["value"]
681 + },
682 + "instances": [
683 + { "input": { "value": "ready" }, "accepted": true },
684 + { "input": { "value": 2 }, "accepted": true },
685 + { "input": { "value": null }, "accepted": true },
686 + { "input": { "value": true }, "accepted": false }
687 + ]
688 + },
689 + {
690 + "id": "primitive-enum-intersects-declared-type",
691 + "description": "Enum values cannot bypass the schema's declared JSON type.",
692 + "schema": {
693 + "type": "object",
694 + "properties": { "value": { "type": "string", "enum": [1, "ready"] } },
695 + "required": ["value"]
696 + },
697 + "instances": [
698 + { "input": { "value": "ready" }, "accepted": true },
699 + { "input": { "value": 1 }, "accepted": false },
700 + { "input": { "value": "other" }, "accepted": false }
701 + ]
702 + },
703 + {
704 + "id": "primitive-null-only-unions",
705 + "description": "A union containing only null accepts only null.",
706 + "schema": {
707 + "type": "object",
708 + "properties": {
709 + "typeArray": { "type": ["null"] },
710 + "anyOf": { "anyOf": [{ "type": "null" }] }
711 + },
712 + "required": ["typeArray", "anyOf"]
713 + },
714 + "instances": [
715 + { "input": { "typeArray": null, "anyOf": null }, "accepted": true },
716 + { "input": { "typeArray": "anything", "anyOf": null }, "accepted": false },
717 + { "input": { "typeArray": null, "anyOf": 1 }, "accepted": false }
718 + ]
719 + },
720 + {
721 + "id": "primitive-scalar-constraints",
722 + "description": "String and numeric constraints survive conversion together.",
723 + "schema": {
724 + "type": "object",
725 + "properties": {
726 + "code": { "type": "string", "pattern": "^[A-Z]{2}$", "minLength": 2, "maxLength": 2 },
727 + "count": { "type": "number", "exclusiveMinimum": 0, "multipleOf": 2 }
728 + },
729 + "required": ["code", "count"]
730 + },
731 + "instances": [
732 + { "input": { "code": "OK", "count": 2 }, "accepted": true },
733 + { "input": { "code": "ok", "count": 2 }, "accepted": false },
734 + { "input": { "code": "OK", "count": 0 }, "accepted": false },
735 + { "input": { "code": "OK", "count": 3 }, "accepted": false }
736 + ]
737 + },
738 + {
739 + "id": "primitive-independent-numeric-bounds",
740 + "description": "Inclusive and numeric exclusive bounds apply independently under Draft 7.",
741 + "schema": {
742 + "type": "object",
743 + "properties": {
744 + "lower": { "type": "number", "minimum": 0, "exclusiveMinimum": 5 },
745 + "upper": { "type": "number", "maximum": 10, "exclusiveMaximum": 5 }
746 + },
747 + "required": ["lower", "upper"]
748 + },
749 + "instances": [
750 + { "input": { "lower": 6, "upper": 4 }, "accepted": true },
751 + { "input": { "lower": 1, "upper": 4 }, "accepted": false },
752 + { "input": { "lower": 6, "upper": 9 }, "accepted": false },
753 + { "input": { "lower": 5, "upper": 5 }, "accepted": false }
754 + ]
755 + },
756 + {
757 + "id": "primitive-const-intersects-declared-type",
758 + "description": "A const that conflicts with the declared type is unsatisfiable.",
759 + "schema": {
760 + "type": "object",
761 + "properties": { "value": { "type": "string", "const": 1 } },
762 + "required": ["value"]
763 + },
764 + "instances": [
765 + { "input": { "value": 1 }, "accepted": false },
766 + { "input": { "value": "1" }, "accepted": false }
767 + ]
768 + },
769 + {
770 + "id": "primitive-compound-enum-values",
771 + "description": "Enum values may contain any JSON value, including objects and arrays.",
772 + "schema": {
773 + "type": "object",
774 + "properties": {
775 + "value": { "enum": [{ "mode": "safe" }, ["ready", 1]] }
776 + },
777 + "required": ["value"]
778 + },
779 + "instances": [
780 + { "input": { "value": { "mode": "safe" } }, "accepted": true },
781 + { "input": { "value": ["ready", 1] }, "accepted": true },
782 + { "input": { "value": ["ready", true] }, "accepted": false },
783 + { "input": { "value": { "mode": true } }, "accepted": false },
784 + { "input": { "value": { "mode": "unsafe" } }, "accepted": false }
785 + ]
786 + },
787 + {
788 + "id": "primitive-const-null-and-false",
789 + "description": "Falsy consts keep their identity: null and false accept only themselves.",
790 + "schema": {
791 + "type": "object",
792 + "properties": { "maybe": { "const": null }, "flag": { "const": false } },
793 + "required": ["maybe", "flag"]
794 + },
795 + "instances": [
796 + { "input": { "maybe": null, "flag": false }, "accepted": true },
797 + { "input": { "maybe": null, "flag": 0 }, "accepted": false },
798 + { "input": { "maybe": "null", "flag": false }, "accepted": false }
799 + ]
800 + },
801 + {
802 + "id": "primitive-enum-boolean-number-identity",
803 + "description": "Enum membership distinguishes booleans from the numbers they equal in most host languages.",
804 + "schema": {
805 + "type": "object",
806 + "properties": { "bits": { "enum": [0, 1] }, "toggle": { "enum": [true] } },
807 + "required": ["bits", "toggle"]
808 + },
809 + "instances": [
810 + { "input": { "bits": 1, "toggle": true }, "accepted": true },
811 + { "input": { "bits": 0, "toggle": true }, "accepted": true },
812 + { "input": { "bits": true, "toggle": true }, "accepted": false },
813 + { "input": { "bits": 1, "toggle": 1 }, "accepted": false },
814 + { "input": { "bits": false, "toggle": true }, "accepted": false }
815 + ]
816 + },
817 + {
818 + "id": "primitive-enum-with-null-member",
819 + "description": "A null enum member is accepted alongside other literal values.",
820 + "schema": {
821 + "type": "object",
822 + "properties": { "value": { "enum": ["a", null] } },
823 + "required": ["value"]
824 + },
825 + "instances": [
826 + { "input": { "value": "a" }, "accepted": true },
827 + { "input": { "value": null }, "accepted": true },
828 + { "input": { "value": "b" }, "accepted": false }
829 + ]
830 + },
831 + {
832 + "id": "primitive-const-constraint-conjunction",
833 + "description": "A const must still satisfy sibling constraints; a conflict rejects everything.",
834 + "schema": {
835 + "type": "object",
836 + "properties": { "code": { "type": "string", "const": "a", "minLength": 2 } },
837 + "required": ["code"]
838 + },
839 + "instances": [
840 + { "input": { "code": "a" }, "accepted": false },
841 + { "input": { "code": "ab" }, "accepted": false }
842 + ]
843 + },
844 + {
845 + "id": "primitive-inclusive-numeric-boundaries",
846 + "description": "Draft 7 minimum and maximum are inclusive bounds.",
847 + "schema": {
848 + "type": "object",
849 + "properties": { "count": { "type": "integer", "minimum": 5, "maximum": 10 } },
850 + "required": ["count"]
851 + },
852 + "instances": [
853 + { "input": { "count": 5 }, "accepted": true },
854 + { "input": { "count": 10 }, "accepted": true },
855 + { "input": { "count": 4 }, "accepted": false },
856 + { "input": { "count": 11 }, "accepted": false }
857 + ]
858 + },
859 + {
860 + "id": "primitive-const-narrows-enum",
861 + "description": "When const and enum are both present, only their intersection is accepted.",
862 + "schema": {
863 + "type": "object",
864 + "properties": { "value": { "enum": ["a", "b"], "const": "b" } },
865 + "required": ["value"]
866 + },
867 + "instances": [
868 + { "input": { "value": "b" }, "accepted": true },
869 + { "input": { "value": "a" }, "accepted": false }
870 + ]
871 + },
872 + {
873 + "id": "primitive-compound-const-deep-equality",
874 + "description": "A compound const compares by deep JSON equality, including boolean identity inside containers.",
875 + "schema": {
876 + "type": "object",
877 + "properties": { "value": { "const": { "a": [1, "x", null] } } },
878 + "required": ["value"]
879 + },
880 + "instances": [
881 + { "input": { "value": { "a": [1, "x", null] } }, "accepted": true },
882 + { "input": { "value": { "a": [1, "x", null], "b": 1 } }, "accepted": false },
883 + { "input": { "value": { "a": [true, "x", null] } }, "accepted": false },
884 + { "input": { "value": { "a": [1, "x"] } }, "accepted": false }
885 + ]
886 + },
887 + {
888 + "id": "primitive-unicode-code-point-length",
889 + "description": "String length constraints count Unicode code points, not UTF-16 code units.",
890 + "schema": {
891 + "type": "object",
892 + "properties": { "glyph": { "type": "string", "maxLength": 1 } },
893 + "required": ["glyph"]
894 + },
895 + "instances": [
896 + { "input": { "glyph": "𝄞" }, "accepted": true },
897 + { "input": { "glyph": "ab" }, "accepted": false }
898 + ]
899 + },
900 + {
901 + "id": "primitive-typeless-constraint-scoping",
902 + "description": "Draft 7 applies string constraints to string instances even without a declared type.",
903 + "schema": {
904 + "type": "object",
905 + "properties": { "value": { "enum": ["a", "abc"], "minLength": 2 } },
906 + "required": ["value"]
907 + },
908 + "instances": [
909 + { "input": { "value": "abc" }, "accepted": true },
910 + { "input": { "value": "a" }, "accepted": false }
911 + ]
912 + },
913 + {
914 + "id": "primitive-float-multiple-of",
915 + "description": "Decimal multipleOf checks tolerate binary floating-point representation error.",
916 + "divergesFromJsonSchema": "A literal Draft 7 multipleOf uses raw float arithmetic and rejects 0.3 for 0.1; every Composio converter scales decimals before comparing.",
917 + "schema": {
918 + "type": "object",
919 + "properties": { "step": { "type": "number", "multipleOf": 0.1 } },
920 + "required": ["step"]
921 + },
922 + "instances": [
923 + { "input": { "step": 0.3 }, "accepted": true },
924 + { "input": { "step": 0.35 }, "accepted": false }
925 + ]
926 + },
927 + {
928 + "id": "primitive-draft4-boolean-exclusive-bounds",
929 + "description": "OpenAPI 3.0 style boolean exclusiveMinimum/exclusiveMaximum flags turn the paired bound exclusive.",
930 + "schema": {
931 + "type": "object",
932 + "properties": {
933 + "lower": { "type": "number", "minimum": 5, "exclusiveMinimum": true },
934 + "upper": { "type": "number", "maximum": 5, "exclusiveMaximum": true }
935 + },
936 + "required": ["lower", "upper"]
937 + },
938 + "instances": [
939 + { "input": { "lower": 6, "upper": 4 }, "accepted": true },
940 + { "input": { "lower": 5, "upper": 4 }, "accepted": false },
941 + { "input": { "lower": 6, "upper": 5 }, "accepted": false }
942 + ]
943 + },
944 + {
945 + "id": "primitive-type-array-constraint-scoping",
946 + "description": "Constraints on a type array apply only to instances of their matching type.",
947 + "schema": {
948 + "type": "object",
949 + "properties": {
950 + "value": { "type": ["string", "number"], "minLength": 2, "minimum": 10 }
951 + },
952 + "required": ["value"]
953 + },
954 + "instances": [
955 + { "input": { "value": "ab" }, "accepted": true },
956 + { "input": { "value": 15 }, "accepted": true },
957 + { "input": { "value": "a" }, "accepted": false },
958 + { "input": { "value": 5 }, "accepted": false },
959 + { "input": { "value": true }, "accepted": false }
960 + ]
961 + },
962 + {
963 + "id": "primitive-empty-enum-optional-property",
964 + "description": "An optional property with an empty enum rejects every supplied value but tolerates absence.",
965 + "schema": {
966 + "type": "object",
967 + "properties": { "value": { "enum": [] } },
968 + "required": []
969 + },
970 + "instances": [
971 + { "input": {}, "accepted": true },
972 + { "input": { "value": null }, "accepted": false }
973 + ]
974 + },
975 {
976 "id": "additional-property-default-materialization",
977 "description": "Composio divergence: a schema-valued `additionalProperties` also materializes defaults in Zod and Pydantic while Effect leaves the input unchanged.",
@@ -677,6 +1004,170 @@
1004 "python": { "output": { "name": "a", "extra": { "enabled": false } } }
1005 }
1006 ]
1007 + },
1008 + {
1009 + "id": "composition-fixed-tuple-items",
1010 + "description": "Draft 7 tuple items preserve position, optional shorter arrays, and an additionalItems false bound.",
1011 + "schema": {
1012 + "$schema": "http://json-schema.org/draft-07/schema#",
1013 + "type": "object",
1014 + "properties": {
1015 + "value": {
1016 + "type": "array",
1017 + "items": [{ "type": "string" }, { "type": "integer" }],
1018 + "additionalItems": false
1019 + }
1020 + },
1021 + "required": ["value"]
1022 + },
1023 + "instances": [
1024 + { "input": { "value": [] }, "accepted": true },
1025 + { "input": { "value": ["ready"] }, "accepted": true },
1026 + { "input": { "value": ["ready", 2] }, "accepted": true },
1027 + { "input": { "value": [2, "ready"] }, "accepted": false },
1028 + { "input": { "value": ["ready", 2, true] }, "accepted": false }
1029 + ]
1030 + },
1031 + {
1032 + "id": "composition-open-tuple-items",
1033 + "description": "Tuple items default to Draft 7 and allow unconstrained trailing values unless additionalItems closes them.",
1034 + "schema": {
1035 + "type": "object",
1036 + "properties": {
1037 + "value": {
1038 + "type": "array",
1039 + "items": [{ "type": "string" }, { "type": "integer" }]
1040 + }
1041 + },
1042 + "required": ["value"]
1043 + },
1044 + "instances": [
1045 + { "input": { "value": ["ready", 2, { "extra": true }] }, "accepted": true },
1046 + { "input": { "value": ["ready", "wrong"] }, "accepted": false }
1047 + ]
1048 + },
1049 + {
1050 + "id": "composition-false-tuple-position",
1051 + "description": "A false positional schema rejects a value only when that position is present.",
1052 + "schema": {
1053 + "$schema": "http://json-schema.org/draft-07/schema#",
1054 + "type": "object",
1055 + "properties": {
1056 + "value": {
1057 + "type": "array",
1058 + "items": [{ "type": "string" }, false],
1059 + "additionalItems": false
1060 + }
1061 + },
1062 + "required": ["value"]
1063 + },
1064 + "instances": [
1065 + { "input": { "value": ["ready"] }, "accepted": true },
1066 + { "input": { "value": ["ready", "forbidden"] }, "accepted": false }
1067 + ]
1068 + },
1069 + {
1070 + "id": "composition-allof-object-intersection",
1071 + "description": "Every allOf object branch remains required after conversion.",
1072 + "schema": {
1073 + "type": "object",
1074 + "properties": {
1075 + "value": {
1076 + "allOf": [
1077 + {
1078 + "type": "object",
1079 + "properties": { "a": { "type": "string" } },
1080 + "required": ["a"],
1081 + "additionalProperties": true
1082 + },
1083 + {
1084 + "type": "object",
1085 + "properties": { "b": { "type": "integer" } },
1086 + "required": ["b"],
1087 + "additionalProperties": true
1088 + }
1089 + ]
1090 + }
1091 + },
1092 + "required": ["value"]
1093 + },
1094 + "instances": [
1095 + { "input": { "value": { "a": "ready", "b": 2 } }, "accepted": true },
1096 + { "input": { "value": { "a": "ready" } }, "accepted": false },
1097 + { "input": { "value": { "b": 2 } }, "accepted": false }
1098 + ]
1099 + },
1100 + {
1101 + "id": "composition-allof-closed-object-branches",
1102 + "description": "Closed allOf object branches merge instead of rejecting each other's keys; the union of declared keys stays strict.",
1103 + "schema": {
1104 + "type": "object",
1105 + "properties": {
1106 + "value": {
1107 + "allOf": [
1108 + {
1109 + "type": "object",
1110 + "properties": { "a": { "type": "string" } },
1111 + "required": ["a"]
1112 + },
1113 + {
1114 + "type": "object",
1115 + "properties": { "b": { "type": "string" } },
1116 + "required": ["b"]
1117 + }
1118 + ]
1119 + }
1120 + },
1121 + "required": ["value"]
1122 + },
1123 + "instances": [
1124 + { "input": { "value": { "a": "ready", "b": "set" } }, "accepted": true },
1125 + { "input": { "value": { "a": "ready" } }, "accepted": false },
1126 + { "input": { "value": { "a": "ready", "b": "set", "c": 1 } }, "accepted": false }
1127 + ]
1128 + },
1129 + {
1130 + "id": "composition-scalar-allof",
1131 + "description": "Scalar allOf branches combine rather than selecting the first branch.",
1132 + "schema": {
1133 + "type": "object",
1134 + "properties": {
1135 + "value": {
1136 + "allOf": [
1137 + { "type": "string", "minLength": 2 },
1138 + { "type": "string", "pattern": "^[A-Z]+$" }
1139 + ]
1140 + }
1141 + },
1142 + "required": ["value"]
1143 + },
1144 + "instances": [
1145 + { "input": { "value": "OK" }, "accepted": true },
1146 + { "input": { "value": "O" }, "accepted": false },
1147 + { "input": { "value": "ok" }, "accepted": false }
1148 + ]
1149 + },
1150 + {
1151 + "id": "composition-oneof-exclusive-match",
1152 + "description": "oneOf accepts exactly one matching branch, not a plain union of branches.",
1153 + "schema": {
1154 + "type": "object",
1155 + "properties": {
1156 + "value": {
1157 + "oneOf": [
1158 + { "type": "number", "minimum": 0 },
1159 + { "type": "number", "maximum": 0 }
1160 + ]
1161 + }
1162 + },
1163 + "required": ["value"]
1164 + },
1165 + "instances": [
1166 + { "input": { "value": 1 }, "accepted": true },
1167 + { "input": { "value": -1 }, "accepted": true },
1168 + { "input": { "value": 0 }, "accepted": false },
1169 + { "input": { "value": "0" }, "accepted": false }
1170 + ]
1171 }
1172 ]
1173 }
python/tests/test_files.py
+18
@@ -3384,6 +3384,24 @@ class TestEnhanceSchemaDescriptionsEmptySchema:
3384 assert "string" in description
3385 assert "required" in description
3386
3387 + def test_boolean_property_schemas_are_left_unchanged(self, file_helper):
3388 + schema = {
3389 + "type": "object",
3390 + "properties": {
3391 + "anything": True,
3392 + "never": False,
3393 + "query": {"type": "string"},
3394 + },
3395 + "required": ["anything", "query"],
3396 + }
3397 +
3398 + result = file_helper.enhance_schema_descriptions(schema)
3399 +
3400 + assert result["properties"]["anything"] is True
3401 + assert result["properties"]["never"] is False
3402 + assert "string" in result["properties"]["query"]["description"]
3403 + assert "required" in result["properties"]["query"]["description"]
3404 +
3405
3406 class TestFromPathSensitiveGuard:
3407 """`FileUploadable.from_path` is the single upload primitive in the Python
python/tests/test_gemini_provider.py
+93 -3
@@ -225,7 +225,9 @@ class TestWrapTool:
225 provider.wrap_tool(tool, execute_tool)
226
227 assert "GITHUB_STAR_REPO" in provider._executors
228 - stored_execute_tool, _aliases = provider._executors["GITHUB_STAR_REPO"]
228 + stored_execute_tool, _aliases, _args_schema = provider._executors[
229 + "GITHUB_STAR_REPO"
230 + ]
231 assert stored_execute_tool is execute_tool
232
233 def test_callable_executes_correctly(self):
@@ -277,9 +279,8 @@ class TestWrapTool:
279 converted to plain dicts before reaching execute_tool so the Composio
280 API can JSON-serialize them.
281 """
280 - from pydantic import BaseModel
281 -
282 from composio_gemini import GeminiProvider
283 + from pydantic import BaseModel
284
285 class FakeQuery(BaseModel):
286 use_case: str = ""
@@ -319,6 +320,61 @@ class TestWrapTool:
320 assert isinstance(call_args["queries"][0], dict)
321 assert call_args["queries"][0]["use_case"] == "summarize email"
322
323 + @pytest.mark.parametrize(
324 + ("property_schema", "invalid", "valid"),
325 + [
326 + (
327 + {"minLength": 2, "required": ["x"]},
328 + {},
329 + {"x": 1},
330 + ),
331 + (
332 + {"type": "array", "contains": {"const": 1}},
333 + [2],
334 + [1, 2],
335 + ),
336 + (
337 + {
338 + "type": "number",
339 + "if": {"minimum": 0},
340 + "then": {"maximum": 10},
341 + },
342 + 20,
343 + 5,
344 + ),
345 + ],
346 + ids=["typeless-object", "contains", "conditional"],
347 + )
348 + def test_callable_validates_assertions_missing_from_function_declaration(
349 + self,
350 + property_schema,
351 + invalid,
352 + valid,
353 + ):
354 + """AFC type generation is lossy, so the callable validates the source schema."""
355 + from composio_gemini import GeminiProvider
356 + from pydantic import ValidationError
357 +
358 + provider = GeminiProvider()
359 + tool = create_mock_tool(
360 + "VALIDATE_SOURCE_SCHEMA",
361 + "test",
362 + input_parameters={
363 + "type": "object",
364 + "properties": {"value": property_schema},
365 + "required": ["value"],
366 + },
367 + )
368 + execute_tool = create_mock_execute_tool()
369 + func = provider.wrap_tool(tool, execute_tool)
370 +
371 + with pytest.raises(ValidationError):
372 + func(value=invalid)
373 + execute_tool.assert_not_called()
374 +
375 + func(value=valid)
376 + assert execute_tool.call_args.args[1] == {"value": valid}
377 +
378 def test_array_param_has_parameterized_type(self):
379 """Array parameters must produce List[X], not bare List.
380
@@ -598,6 +654,40 @@ class TestHandleResponse:
654 arguments={"repo": "composio/composio"},
655 )
656
657 + def test_rejects_invalid_arguments_like_afc(self):
658 + """Manual function calling validates the source schema like the AFC callable."""
659 + from composio_gemini import GeminiProvider
660 + from pydantic import ValidationError
661 +
662 + provider = GeminiProvider()
663 + tool = create_mock_tool(
664 + "VALIDATE_SOURCE_SCHEMA",
665 + "test",
666 + input_parameters={
667 + "type": "object",
668 + "properties": {"value": {"type": "integer", "minimum": 1}},
669 + "required": ["value"],
670 + },
671 + )
672 + execute_tool = create_mock_execute_tool()
673 + provider.wrap_tools([tool], execute_tool)
674 +
675 + response = self._create_mock_response(
676 + [("VALIDATE_SOURCE_SCHEMA", {"value": 0})]
677 + )
678 + with pytest.raises(ValidationError):
679 + provider.handle_response(response)
680 + execute_tool.assert_not_called()
681 +
682 + response = self._create_mock_response(
683 + [("VALIDATE_SOURCE_SCHEMA", {"value": 3})]
684 + )
685 + _responses, executed = provider.handle_response(response)
686 + assert executed is True
687 + execute_tool.assert_called_once_with(
688 + slug="VALIDATE_SOURCE_SCHEMA", arguments={"value": 3}
689 + )
690 +
691 def test_no_function_calls(self):
692 from composio_gemini import GeminiProvider
693
python/tests/test_schema_composition_parity.py new
+53
@@ -0,0 +1,53 @@
1 +"""Cross-entry-point checks for composed JSON Schema conversion."""
2 +
3 +import pytest
4 +from pydantic import TypeAdapter, ValidationError
5 +
6 +from composio.utils.shared import pydantic_model_from_param_schema
7 +from tests.fixtures.json_schema_conversion_corpus import find_case
8 +
9 +COMPOSITION_CASE_IDS = (
10 + "composition-fixed-tuple-items",
11 + "composition-open-tuple-items",
12 + "composition-false-tuple-position",
13 + "composition-allof-object-intersection",
14 + "composition-scalar-allof",
15 + "composition-oneof-exclusive-match",
16 +)
17 +
18 +
19 +@pytest.mark.parametrize("case_id", COMPOSITION_CASE_IDS)
20 +def test_legacy_model_entry_point_matches_shared_composition_corpus(
21 + case_id: str,
22 +) -> None:
23 + case = find_case(case_id)
24 + model = pydantic_model_from_param_schema(
25 + {**case.schema_, "title": f"Composition_{case_id}"}
26 + )
27 +
28 + for instance in case.instances:
29 + if instance.accepted_for("python"):
30 + model.model_validate(instance.input)
31 + else:
32 + with pytest.raises(ValidationError):
33 + model.model_validate(instance.input)
34 +
35 +
36 +def test_standalone_draft7_tuple_preserves_positional_validation() -> None:
37 + adapter = TypeAdapter(
38 + pydantic_model_from_param_schema(
39 + {
40 + "title": "StandaloneTuple",
41 + "type": "array",
42 + "items": [{"type": "string"}, {"type": "integer"}],
43 + "additionalItems": False,
44 + }
45 + )
46 + )
47 +
48 + assert adapter.validate_python([]) == []
49 + assert adapter.validate_python(["ready"]) == ["ready"]
50 + assert adapter.validate_python(["ready", 2]) == ["ready", 2]
51 + for value in ([2, "ready"], ["ready", 2, True]):
52 + with pytest.raises(ValidationError):
53 + adapter.validate_python(value)
python/tests/test_schema_parser.py
+80 -72
@@ -11,8 +11,6 @@ import pytest
11 from pydantic import BaseModel, TypeAdapter, ValidationError
12 from pydantic.fields import PydanticUndefined
13
14 -from tests.fixtures.json_schema_conversion_corpus import find_case, load_object_cases
15 -
14 from composio.utils.shared import (
15 get_signature_format_from_schema_params,
16 json_schema_to_fields_dict,
@@ -21,6 +19,7 @@ from composio.utils.shared import (
19 json_schema_to_pydantic_type,
20 pydantic_model_from_param_schema,
21 )
22 +from tests.fixtures.json_schema_conversion_corpus import find_case, load_object_cases
23
24
25 class TestJsonSchemaToPydanticField:
@@ -429,6 +428,13 @@ class TestPydanticModelFromParamSchema:
428 pydantic_model_from_param_schema(param_schema)
429
430
431 +def _materialized(annotation: t.Any) -> t.Any:
432 + """Strip the exact-validation `Annotated` wrapper to reach the Pydantic type."""
433 + while t.get_origin(annotation) is t.Annotated:
434 + annotation = t.get_args(annotation)[0]
435 + return annotation
436 +
437 +
438 class TestJsonSchemaToPydanticType:
439 """Test cases for json_schema_to_pydantic_type function."""
440
@@ -446,12 +452,12 @@ class TestJsonSchemaToPydanticType:
452 assert result == expected_type
453
454 def test_anyof_null_only_preserves_nullability(self):
449 - """Test that anyOf with only null maps to Optional[Any] instead of str."""
450 - result = json_schema_to_pydantic_type({"anyOf": [{"type": "null"}]})
455 + """Test that anyOf with only null accepts no non-null value."""
456 + result = _materialized(
457 + json_schema_to_pydantic_type({"anyOf": [{"type": "null"}]})
458 + )
459
452 - assert t.get_origin(result) is t.Union
453 - assert t.Any in t.get_args(result)
454 - assert type(None) in t.get_args(result)
460 + assert result is type(None)
461
462 def test_array_type(self):
463 """Test array type conversion."""
@@ -493,13 +499,17 @@ class TestJsonSchemaToPydanticType:
499 ]
500 }
501 result_4 = json_schema_to_pydantic_type(json_schema_4)
496 - assert hasattr(result_4, "__origin__")
497 - assert result_4.__origin__ is t.Union
498 - assert len(result_4.__args__) == 4
499 - assert str in result_4.__args__
500 - assert int in result_4.__args__
501 - assert bool in result_4.__args__
502 - assert float in result_4.__args__
502 + union_4 = t.get_args(result_4)[0]
503 + assert t.get_origin(union_4) is t.Union
504 + assert len(t.get_args(union_4)) == 4
505 + assert str in t.get_args(union_4)
506 + assert int in t.get_args(union_4)
507 + assert bool in t.get_args(union_4)
508 + assert float in t.get_args(union_4)
509 + # `integer` is a subset of `number`, so 42 matches two branches and
510 + # must be rejected by oneOf's exactly-one rule.
511 + with pytest.raises(ValidationError):
512 + TypeAdapter(result_4).validate_python(42)
513
514 # Test 5 types
515 json_schema_5 = {
@@ -512,9 +522,9 @@ class TestJsonSchemaToPydanticType:
522 ]
523 }
524 result_5 = json_schema_to_pydantic_type(json_schema_5)
515 - assert hasattr(result_5, "__origin__")
516 - assert result_5.__origin__ is t.Union
517 - assert len(result_5.__args__) == 5
525 + union_5 = t.get_args(result_5)[0]
526 + assert t.get_origin(union_5) is t.Union
527 + assert len(t.get_args(union_5)) == 5
528
529 # Test 6 types (stress test, avoiding null which expands to Optional[Any])
530 json_schema_6 = {
@@ -528,14 +538,14 @@ class TestJsonSchemaToPydanticType:
538 ]
539 }
540 result_6 = json_schema_to_pydantic_type(json_schema_6)
531 - assert hasattr(result_6, "__origin__")
532 - assert result_6.__origin__ is t.Union
533 - assert len(result_6.__args__) == 6
541 + union_6 = t.get_args(result_6)[0]
542 + assert t.get_origin(union_6) is t.Union
543 + assert len(t.get_args(union_6)) == 6
544
545 def test_oneof_single_type(self):
546 """Test oneOf with single type returns the type directly."""
547 json_schema = {"oneOf": [{"type": "string"}]}
538 - result = json_schema_to_pydantic_type(json_schema)
548 + result = _materialized(json_schema_to_pydantic_type(json_schema))
549 assert result is str
550 # Single type should not create a Union
551 assert not hasattr(result, "__origin__")
@@ -553,7 +563,7 @@ class TestJsonSchemaToPydanticType:
563 },
564 ]
565 }
556 - result = json_schema_to_pydantic_type(json_schema)
566 + result = _materialized(json_schema_to_pydantic_type(json_schema))
567 assert hasattr(result, "__origin__")
568 assert result.__origin__ is t.Union
569 assert len(result.__args__) == 3
@@ -595,21 +605,25 @@ class TestJsonSchemaToPydanticType:
605
606 # Test with different oneOf values
607 instance1 = model_class(flexible_field="hello", normal_field="world")
598 - instance2 = model_class(flexible_field=42, normal_field="world")
608 instance3 = model_class(flexible_field=True, normal_field="world")
609 instance4 = model_class(flexible_field=3.14, normal_field="world")
610
611 assert instance1.flexible_field == "hello"
603 - assert instance2.flexible_field == 42
612 assert instance3.flexible_field is True
613 assert instance4.flexible_field == 3.14
614
607 - def test_fallback_to_string(self):
608 - """Test that missing type defaults to string."""
615 + # Draft 7 `oneOf` requires exactly one branch to match. An integer
616 + # satisfies both {"type": "integer"} and {"type": "number"}, so it is
617 + # rejected — the Zod and Effect converters agree.
618 + with pytest.raises(ValidationError):
619 + model_class(flexible_field=42, normal_field="world")
620 +
621 + def test_empty_schema_accepts_any_value(self):
622 + """An empty JSON Schema accepts every value."""
623 json_schema = {} # No type specified
624
625 result = json_schema_to_pydantic_type(json_schema)
612 - assert result is str
626 + assert result is t.Any
627
628 def test_unsupported_type_fallback(self):
629 """Test that unsupported types fall back to string (graceful degradation)."""
@@ -624,7 +638,7 @@ class TestJsonSchemaToPydanticType:
638 json_schema = {
639 "anyOf": [{"type": "object", "additionalProperties": {}}, {"type": "null"}]
640 }
627 - result = json_schema_to_pydantic_type(json_schema)
641 + result = _materialized(json_schema_to_pydantic_type(json_schema))
642 # Should return Optional[dict], not str (to allow both dict and None)
643 assert hasattr(result, "__origin__")
644 assert result.__origin__ is t.Union
@@ -644,7 +658,7 @@ class TestJsonSchemaToPydanticType:
658 {"type": "null"},
659 ]
660 }
647 - result = json_schema_to_pydantic_type(json_schema)
661 + result = _materialized(json_schema_to_pydantic_type(json_schema))
662 # Should return Optional[BaseModel subclass] (Union with None)
663 assert hasattr(result, "__origin__")
664 assert result.__origin__ is t.Union
@@ -663,19 +677,19 @@ class TestJsonSchemaToPydanticType:
677 json_schema = {
678 "anyOf": [{"type": "string"}, {"type": "integer"}, {"type": "object"}]
679 }
666 - result = json_schema_to_pydantic_type(json_schema)
680 + result = _materialized(json_schema_to_pydantic_type(json_schema))
681 assert hasattr(result, "__origin__")
682 assert result.__origin__ is t.Union
683
684 def test_anyof_single_type(self):
685 """Test anyOf with single type returns the type directly."""
686 json_schema = {"anyOf": [{"type": "string"}]}
673 - result = json_schema_to_pydantic_type(json_schema)
687 + result = _materialized(json_schema_to_pydantic_type(json_schema))
688 assert result is str
689 assert not hasattr(result, "__origin__")
690
691 def test_allof_single_option(self):
678 - """Test allOf with single option."""
692 + """A single allOf option preserves its acceptance behavior."""
693 json_schema = {
694 "allOf": [
695 {
@@ -685,29 +699,28 @@ class TestJsonSchemaToPydanticType:
699 }
700 ]
701 }
688 - result = json_schema_to_pydantic_type(json_schema)
689 - assert isinstance(result, type)
690 - assert issubclass(result, BaseModel)
702 + adapter = TypeAdapter(json_schema_to_pydantic_type(json_schema))
703 + result = adapter.validate_python({"name": "Ada"})
704 + assert adapter.dump_python(result, mode="json") == {"name": "Ada"}
705 + with pytest.raises(ValidationError):
706 + adapter.validate_python({"name": 42})
707
708 def test_allof_multiple_options_with_type(self):
709 """Test allOf with multiple options where one has type."""
710 json_schema = {
711 "allOf": [{"description": "Some description"}, {"type": "string"}]
712 }
697 - result = json_schema_to_pydantic_type(json_schema)
698 - # The library creates an AllOfModel class that combines the schemas
699 - # or returns str depending on the schema structure
700 - assert result is not None
701 - # Either it's str or a model class (both are valid)
702 - assert result is str or (
703 - isinstance(result, type) and issubclass(result, BaseModel)
704 - )
713 + adapter = TypeAdapter(json_schema_to_pydantic_type(json_schema))
714 + assert adapter.validate_python("value") == "value"
715 + with pytest.raises(ValidationError):
716 + adapter.validate_python(42)
717
718 def test_allof_empty_options(self):
719 """Test allOf with empty options accepts any value."""
720 json_schema = {"allOf": []}
709 - result = json_schema_to_pydantic_type(json_schema)
710 - assert result is t.Any
721 + adapter = TypeAdapter(json_schema_to_pydantic_type(json_schema))
722 + assert adapter.validate_python(42) == 42
723 + assert adapter.validate_python({"anything": True}) == {"anything": True}
724
725
726 class TestJsonSchemaToFieldsDict:
@@ -1044,7 +1057,7 @@ class TestBooleanSchemas:
1057 True, # Boolean schema
1058 ]
1059 }
1047 - result = json_schema_to_pydantic_type(json_schema)
1060 + result = _materialized(json_schema_to_pydantic_type(json_schema))
1061 # Should handle gracefully, creating a union including Any
1062 assert result is not None
1063 # The result should include Any type from the true schema
@@ -1061,45 +1074,38 @@ class TestBooleanSchemas:
1074 False, # Boolean schema - should be filtered out
1075 ]
1076 }
1064 - result = json_schema_to_pydantic_type(json_schema)
1077 + result = _materialized(json_schema_to_pydantic_type(json_schema))
1078 # Should handle gracefully, false schema filtered out leaving just string
1079 assert result is str
1080
1081 @pytest.mark.unit
1082 @pytest.mark.schema
1083 def test_boolean_schema_in_allof_with_type(self):
1071 - """Test that boolean schemas in allOf don't crash when combined with typed schema."""
1084 + """A true allOf branch leaves the typed branch unchanged."""
1085 json_schema = {
1086 "allOf": [
1087 {"type": "string"},
1088 True,
1089 ]
1090 }
1078 - result = json_schema_to_pydantic_type(json_schema)
1079 - # Should not crash - may return str or an AllOf model
1080 - assert result is not None
1081 - # Either it's str or a model class (library creates AllOfModel)
1082 - assert result is str or (
1083 - isinstance(result, type) and issubclass(result, BaseModel)
1084 - )
1091 + adapter = TypeAdapter(json_schema_to_pydantic_type(json_schema))
1092 + assert adapter.validate_python("value") == "value"
1093 + with pytest.raises(ValidationError):
1094 + adapter.validate_python(42)
1095
1096 @pytest.mark.unit
1097 @pytest.mark.schema
1098 def test_boolean_schema_in_allof_single(self):
1089 - """Test that single boolean schema in allOf returns appropriate type."""
1099 + """A single true allOf branch accepts every value."""
1100 json_schema = {"allOf": [True]}
1091 - result = json_schema_to_pydantic_type(json_schema)
1092 - # Single true schema filtered to {} - library may return Any or a model
1093 - assert result is not None
1094 - # Could be Any, or a generated model (both are valid)
1095 - assert result is t.Any or (
1096 - isinstance(result, type) and issubclass(result, BaseModel)
1097 - )
1101 + adapter = TypeAdapter(json_schema_to_pydantic_type(json_schema))
1102 + assert adapter.validate_python(42) == 42
1103 + assert adapter.validate_python({"anything": True}) == {"anything": True}
1104
1105 @pytest.mark.unit
1106 @pytest.mark.schema
1107 def test_boolean_schema_in_oneof(self):
1102 - """Test that boolean schemas in oneOf don't crash."""
1108 + """A true branch still participates in oneOf's exactly-one rule."""
1109 json_schema = {
1110 "oneOf": [
1111 {"type": "string"},
@@ -1107,10 +1113,10 @@ class TestBooleanSchemas:
1113 ]
1114 }
1115 result = json_schema_to_pydantic_type(json_schema)
1110 - # Should handle gracefully
1111 - assert result is not None
1112 - assert hasattr(result, "__origin__")
1113 - assert result.__origin__ is t.Union
1116 + adapter = TypeAdapter(result)
1117 + assert adapter.validate_python(42) == 42
1118 + with pytest.raises(ValidationError):
1119 + adapter.validate_python("matches both branches")
1120
1121 @pytest.mark.unit
1122 @pytest.mark.schema
@@ -1122,9 +1128,11 @@ class TestBooleanSchemas:
1128 @pytest.mark.unit
1129 @pytest.mark.schema
1130 def test_standalone_false_schema(self):
1125 - """Test that standalone false schema returns None (to be filtered out)."""
1126 - result = json_schema_to_pydantic_type(False)
1127 - assert result is None
1131 + """Test that standalone false schema rejects every value."""
1132 + adapter = TypeAdapter(json_schema_to_pydantic_type(False))
1133 + for value in (None, "value", 1, {}, []):
1134 + with pytest.raises(ValidationError):
1135 + adapter.validate_python(value)
1136
1137 @pytest.mark.unit
1138 @pytest.mark.schema
@@ -1153,7 +1161,7 @@ class TestBooleanSchemas:
1161 {"type": "integer"},
1162 ]
1163 }
1156 - result = json_schema_to_pydantic_type(json_schema)
1164 + result = _materialized(json_schema_to_pydantic_type(json_schema))
1165 # Should create union of Any and int (false filtered out)
1166 assert result is not None
1167 assert hasattr(result, "__origin__")
python/tests/test_schema_primitive_parity.py new
+47
@@ -0,0 +1,47 @@
1 +"""Cross-entry-point checks for primitive JSON Schema conversion."""
2 +
3 +import pytest
4 +from pydantic import ValidationError
5 +
6 +from composio.utils.shared import pydantic_model_from_param_schema
7 +from tests.fixtures.json_schema_conversion_corpus import find_case
8 +
9 +PRIMITIVE_CASE_IDS = (
10 + "primitive-boolean-property-schemas",
11 + "primitive-empty-and-null-schemas",
12 + "primitive-type-array-union",
13 + "primitive-null-only-unions",
14 + "primitive-enum-intersects-declared-type",
15 + "primitive-scalar-constraints",
16 + "primitive-independent-numeric-bounds",
17 + "primitive-const-intersects-declared-type",
18 + "primitive-compound-enum-values",
19 + "primitive-const-null-and-false",
20 + "primitive-enum-boolean-number-identity",
21 + "primitive-enum-with-null-member",
22 + "primitive-const-constraint-conjunction",
23 + "primitive-inclusive-numeric-boundaries",
24 + "primitive-const-narrows-enum",
25 + "primitive-compound-const-deep-equality",
26 + "primitive-unicode-code-point-length",
27 + "primitive-typeless-constraint-scoping",
28 + "primitive-float-multiple-of",
29 + "primitive-draft4-boolean-exclusive-bounds",
30 + "primitive-type-array-constraint-scoping",
31 + "primitive-empty-enum-optional-property",
32 +)
33 +
34 +
35 +@pytest.mark.parametrize("case_id", PRIMITIVE_CASE_IDS)
36 +def test_legacy_model_entry_point_matches_shared_primitive_corpus(case_id: str) -> None:
37 + case = find_case(case_id)
38 + model = pydantic_model_from_param_schema(
39 + {**case.schema_, "title": f"Primitive_{case_id}"}
40 + )
41 +
42 + for instance in case.instances:
43 + if instance.accepted_for("python"):
44 + model.model_validate(instance.input)
45 + else:
46 + with pytest.raises(ValidationError):
47 + model.model_validate(instance.input)
python/tests/test_schema_property_semantics.py new
+215
@@ -0,0 +1,215 @@
1 +"""Property-based acceptance parity for scalar JSON Schema conversion.
2 +
3 +The oracle is the `jsonschema` Draft 7 validator: for every generated scalar
4 +schema and instance, the converted Pydantic artifacts must agree with it.
5 +
6 +The generator deliberately stays inside the semantics the converters claim to
7 +support today; shrinking an exclusion is the way to turn a fixed behavior into
8 +a permanent regression guard. The remaining exclusions are deliberate
9 +divergences or oracle limits, not open bugs:
10 +
11 +- ``multipleOf`` is always an integer: the converters check decimal multiples
12 + through decimal scaling (see the ``primitive-float-multiple-of`` corpus
13 + case), while the oracle uses raw float modulo
14 +- draft-4 boolean ``exclusiveMinimum``/``exclusiveMaximum`` are never
15 + generated: they are not Draft 7, so the oracle cannot express them (the
16 + ``primitive-draft4-boolean-exclusive-bounds`` corpus case covers them)
17 +"""
18 +
19 +import typing as t
20 +
21 +import pytest
22 +from hypothesis import HealthCheck, given, settings
23 +from hypothesis import strategies as st
24 +from jsonschema import Draft7Validator
25 +from pydantic import TypeAdapter, ValidationError
26 +
27 +from composio.utils.schema_converter import json_schema_to_pydantic_type
28 +from composio.utils.shared import pydantic_model_from_param_schema
29 +
30 +SCALAR_TYPES = ("string", "integer", "number", "boolean", "null")
31 +
32 +PATTERN_POOL = ("^[a-z]+$", "^[A-Z]{2}$", "[0-9]", "^a.*z$", "^(?=.*[a-y])a")
33 +
34 +scalar_values = st.one_of(
35 + st.none(),
36 + st.booleans(),
37 + st.integers(min_value=-100, max_value=100),
38 + st.floats(
39 + min_value=-100,
40 + max_value=100,
41 + allow_nan=False,
42 + allow_infinity=False,
43 + ),
44 + st.text(
45 + alphabet=st.characters(min_codepoint=97, max_codepoint=122),
46 + max_size=6,
47 + ),
48 +)
49 +
50 +
51 +@st.composite
52 +def scalar_schemas(draw: st.DrawFn) -> dict[str, t.Any]:
53 + schema: dict[str, t.Any] = {}
54 + declared: tuple[str, ...] = ()
55 +
56 + if draw(st.booleans()):
57 + members = draw(
58 + st.lists(st.sampled_from(SCALAR_TYPES), min_size=1, max_size=3, unique=True)
59 + )
60 + if len(members) == 1 and draw(st.booleans()):
61 + schema["type"] = members[0]
62 + declared = (members[0],)
63 + else:
64 + schema["type"] = members
65 + declared = tuple(members)
66 +
67 + literal_kind = draw(st.sampled_from(("none", "enum", "const", "both")))
68 + if literal_kind in ("enum", "both"):
69 + schema["enum"] = draw(
70 + st.lists(scalar_values, min_size=1, max_size=4, unique_by=repr)
71 + )
72 + if literal_kind in ("const", "both"):
73 + schema["const"] = draw(scalar_values)
74 +
75 + # Constraints attach independently of the declared type (or its absence):
76 + # Draft 7 scopes every scalar keyword to matching instance types anyway.
77 + del declared
78 + if draw(st.booleans()):
79 + schema["minLength"] = draw(st.integers(min_value=0, max_value=4))
80 + if draw(st.booleans()):
81 + schema["maxLength"] = draw(st.integers(min_value=0, max_value=6))
82 + if draw(st.booleans()):
83 + schema["pattern"] = draw(st.sampled_from(PATTERN_POOL))
84 + if draw(st.booleans()):
85 + schema["minimum"] = draw(st.integers(min_value=-20, max_value=20))
86 + if draw(st.booleans()):
87 + schema["maximum"] = draw(st.integers(min_value=-20, max_value=20))
88 + if draw(st.booleans()):
89 + schema["exclusiveMinimum"] = draw(st.integers(min_value=-20, max_value=20))
90 + if draw(st.booleans()):
91 + schema["exclusiveMaximum"] = draw(st.integers(min_value=-20, max_value=20))
92 + if draw(st.booleans()):
93 + schema["multipleOf"] = draw(st.integers(min_value=1, max_value=5))
94 +
95 + return schema
96 +
97 +
98 +@st.composite
99 +def schema_and_instance(draw: st.DrawFn) -> tuple[dict[str, t.Any], t.Any]:
100 + schema = draw(scalar_schemas())
101 +
102 + pools: list[st.SearchStrategy[t.Any]] = [scalar_values]
103 + interesting: list[t.Any] = []
104 + if "enum" in schema:
105 + interesting.extend(schema["enum"])
106 + if "const" in schema:
107 + interesting.append(schema["const"])
108 + for keyword in ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"):
109 + if keyword in schema:
110 + bound = schema[keyword]
111 + interesting.extend((bound, bound + 1, bound - 1))
112 + if interesting:
113 + pools.append(st.sampled_from(interesting))
114 +
115 + return schema, draw(st.one_of(pools))
116 +
117 +
118 +def _oracle_accepts(object_schema: dict[str, t.Any], instance: t.Any) -> bool:
119 + return Draft7Validator(object_schema).is_valid(instance)
120 +
121 +
122 +def _pydantic_accepts(annotation: t.Any, instance: t.Any) -> bool:
123 + try:
124 + TypeAdapter(annotation).validate_python(instance)
125 + return True
126 + except ValidationError:
127 + return False
128 +
129 +
130 +def _wrap(schema: dict[str, t.Any]) -> dict[str, t.Any]:
131 + return {
132 + "type": "object",
133 + "properties": {"value": schema},
134 + "required": ["value"],
135 + "title": "PropertyCase",
136 + }
137 +
138 +
139 +@pytest.mark.unit
140 +@pytest.mark.schema
141 +@settings(
142 + max_examples=200,
143 + deadline=None,
144 + suppress_health_check=[HealthCheck.too_slow],
145 +)
146 +@given(schema_and_instance())
147 +def test_object_conversion_matches_draft7_oracle(
148 + case: tuple[dict[str, t.Any], t.Any],
149 +) -> None:
150 + """`json_schema_to_pydantic_type` on an object schema must agree with Draft 7."""
151 + schema, value = case
152 + object_schema = _wrap(schema)
153 + instance = {"value": value}
154 +
155 + expected = _oracle_accepts(object_schema, instance)
156 + actual = _pydantic_accepts(json_schema_to_pydantic_type(object_schema), instance)
157 +
158 + assert actual == expected, (
159 + f"object path disagreed with Draft 7 oracle for schema={schema!r} "
160 + f"value={value!r}: oracle={expected} converted={actual}"
161 + )
162 +
163 +
164 +@pytest.mark.unit
165 +@pytest.mark.schema
166 +@settings(
167 + max_examples=200,
168 + deadline=None,
169 + suppress_health_check=[HealthCheck.too_slow],
170 +)
171 +@given(schema_and_instance())
172 +def test_legacy_model_matches_draft7_oracle(
173 + case: tuple[dict[str, t.Any], t.Any],
174 +) -> None:
175 + """`pydantic_model_from_param_schema` enforces exact Draft 7 acceptance."""
176 + schema, value = case
177 + object_schema = _wrap(schema)
178 + instance = {"value": value}
179 +
180 + expected = _oracle_accepts(object_schema, instance)
181 + model = pydantic_model_from_param_schema(object_schema)
182 + try:
183 + model.model_validate(instance)
184 + actual = True
185 + except ValidationError:
186 + actual = False
187 +
188 + assert actual == expected, (
189 + f"legacy path disagreed with Draft 7 oracle for schema={schema!r} "
190 + f"value={value!r}: oracle={expected} converted={actual}"
191 + )
192 +
193 +
194 +@pytest.mark.unit
195 +@pytest.mark.schema
196 +@settings(
197 + max_examples=200,
198 + deadline=None,
199 + suppress_health_check=[HealthCheck.too_slow],
200 +)
201 +@given(schema_and_instance())
202 +def test_toplevel_conversion_never_rejects_draft7_valid_input(
203 + case: tuple[dict[str, t.Any], t.Any],
204 +) -> None:
205 + """The top-level scalar path may coerce, but must not over-reject."""
206 + schema, value = case
207 +
208 + if not Draft7Validator(schema).is_valid(value):
209 + return
210 +
211 + annotation = json_schema_to_pydantic_type(schema)
212 + assert _pydantic_accepts(annotation, value), (
213 + f"top-level path rejected a Draft 7-valid instance for schema={schema!r} "
214 + f"value={value!r}"
215 + )
python/tests/test_schema_semantic_regressions.py new
+424
@@ -0,0 +1,424 @@
1 +"""Regression matrix for whole-schema JSON Schema acceptance.
2 +
3 +These cases combine keywords that previously took different conversion paths.
4 +Every fixture is checked against the Draft 7 oracle before the public Pydantic
5 +entry point, so a passing test cannot merely preserve two matching mistakes.
6 +"""
7 +
8 +import json
9 +import threading
10 +import time
11 +import typing as t
12 +from http.server import BaseHTTPRequestHandler, HTTPServer
13 +
14 +import pytest
15 +from jsonschema import Draft7Validator
16 +from pydantic import TypeAdapter, ValidationError
17 +
18 +from composio.utils.schema_converter import json_schema_to_pydantic_type
19 +from composio.utils.shared import (
20 + json_schema_to_model,
21 + pydantic_model_from_param_schema,
22 +)
23 +
24 +REJECTION_CASES: tuple[tuple[str, dict[str, t.Any], t.Any], ...] = (
25 + (
26 + "typeless scalar dispatch must not discard object assertions",
27 + {"minLength": 2, "required": ["x"]},
28 + {},
29 + ),
30 + (
31 + "anyOf must compose with adjacent assertions",
32 + {
33 + "type": "string",
34 + "minLength": 2,
35 + "anyOf": [{"const": "a"}, {"const": "abc"}],
36 + },
37 + "a",
38 + ),
39 + (
40 + "allOf must compose with adjacent assertions",
41 + {"type": "string", "maxLength": 1, "allOf": [{"pattern": "^ab"}]},
42 + "ab",
43 + ),
44 + (
45 + "oneOf must compose with adjacent assertions",
46 + {
47 + "type": "number",
48 + "minimum": 10,
49 + "oneOf": [{"maximum": 5}, {"minimum": 0}],
50 + },
51 + 7,
52 + ),
53 + (
54 + "not must compose with adjacent assertions",
55 + {"type": "string", "minLength": 2, "not": {"const": "x"}},
56 + "a",
57 + ),
58 + (
59 + "if and then are a complete conditional without else",
60 + {"if": {"type": "string"}, "then": {"minLength": 2}},
61 + "a",
62 + ),
63 + (
64 + "conditionals must compose with adjacent primitive assertions",
65 + {
66 + "type": "number",
67 + "if": {"minimum": 0},
68 + "then": {"maximum": 10},
69 + "else": {"minimum": -10},
70 + },
71 + 20,
72 + ),
73 + (
74 + "contains must be enforced for typed arrays",
75 + {"type": "array", "contains": {"const": 1}},
76 + [2],
77 + ),
78 + (
79 + "uniqueItems must be enforced for typed arrays",
80 + {"type": "array", "uniqueItems": True},
81 + [1, 1],
82 + ),
83 + (
84 + "minItems must be enforced for typed arrays",
85 + {"type": "array", "minItems": 2},
86 + [1],
87 + ),
88 + (
89 + "maxItems must be enforced for typed arrays",
90 + {"type": "array", "maxItems": 1},
91 + [1, 2],
92 + ),
93 + (
94 + "propertyNames must be enforced for typed objects",
95 + {"type": "object", "propertyNames": {"pattern": "^x"}},
96 + {"bad": 1},
97 + ),
98 + (
99 + "required must be enforced for property-less typed objects",
100 + {"type": "object", "required": ["x"]},
101 + {},
102 + ),
103 + (
104 + "local references must constrain direct converter callers",
105 + {
106 + "$defs": {"positive": {"type": "number", "minimum": 1}},
107 + "$ref": "#/$defs/positive",
108 + },
109 + 0,
110 + ),
111 +)
112 +
113 +
114 +@pytest.mark.unit
115 +@pytest.mark.schema
116 +@pytest.mark.parametrize(
117 + ("name", "schema", "value"),
118 + REJECTION_CASES,
119 + ids=[case[0] for case in REJECTION_CASES],
120 +)
121 +def test_whole_schema_rejections_match_draft7(
122 + name: str,
123 + schema: dict[str, t.Any],
124 + value: t.Any,
125 +) -> None:
126 + del name
127 + Draft7Validator.check_schema(schema)
128 + assert not Draft7Validator(schema).is_valid(value)
129 +
130 + adapter = TypeAdapter(json_schema_to_pydantic_type(schema))
131 + with pytest.raises(ValidationError):
132 + adapter.validate_python(value)
133 +
134 +
135 +@pytest.mark.unit
136 +@pytest.mark.schema
137 +@pytest.mark.parametrize("literal_keyword", ["const", "enum"])
138 +def test_typed_object_compound_literals_do_not_fall_back_to_string(
139 + literal_keyword: str,
140 +) -> None:
141 + literal = {} if literal_keyword == "const" else [{}]
142 + schema = {
143 + "type": "object",
144 + "properties": {"x": {"type": "string", "default": "generated"}},
145 + literal_keyword: literal,
146 + }
147 + Draft7Validator.check_schema(schema)
148 +
149 + adapter = TypeAdapter(json_schema_to_pydantic_type(schema))
150 + result = adapter.validate_python({})
151 + assert adapter.dump_python(result, mode="json") == {}
152 +
153 +
154 +@pytest.mark.unit
155 +@pytest.mark.schema
156 +@pytest.mark.parametrize(
157 + ("schema", "value"),
158 + [
159 + (
160 + {
161 + "type": "array",
162 + "minimum": 0,
163 + "exclusiveMinimum": True,
164 + "contains": {"const": 1},
165 + },
166 + [2],
167 + ),
168 + (
169 + {
170 + "type": "object",
171 + "minimum": 0,
172 + "exclusiveMinimum": True,
173 + "propertyNames": {"pattern": "^x"},
174 + },
175 + {"bad": 1},
176 + ),
177 + ],
178 + ids=["contains", "property-names"],
179 +)
180 +def test_draft4_bounds_do_not_disable_draft7_siblings(
181 + schema: dict[str, t.Any],
182 + value: t.Any,
183 +) -> None:
184 + adapter = TypeAdapter(json_schema_to_pydantic_type(schema))
185 + with pytest.raises(ValidationError):
186 + adapter.validate_python(value)
187 +
188 +
189 +@pytest.mark.unit
190 +@pytest.mark.schema
191 +def test_scalar_allof_acceptance_survives_pydantic_materialization() -> None:
192 + schema = {
193 + "title": "ScalarAllOf",
194 + "type": "object",
195 + "properties": {
196 + "value": {
197 + "allOf": [
198 + {"type": "string", "minLength": 2},
199 + {"type": "string", "pattern": "^[A-Z]+$"},
200 + ]
201 + }
202 + },
203 + "required": ["value"],
204 + }
205 + Draft7Validator.check_schema(schema)
206 + assert Draft7Validator(schema).is_valid({"value": "OK"})
207 +
208 + annotations = (
209 + json_schema_to_pydantic_type(schema),
210 + json_schema_to_model(schema),
211 + pydantic_model_from_param_schema(schema),
212 + )
213 + for annotation in annotations:
214 + TypeAdapter(annotation).validate_python({"value": "OK"})
215 +
216 +
217 +@pytest.mark.unit
218 +@pytest.mark.schema
219 +@pytest.mark.parametrize(
220 + ("schema", "value"),
221 + [
222 + ({"properties": {"x": {"type": "string"}}}, 42),
223 + ({"required": ["x"]}, 42),
224 + ({"items": {"type": "string"}}, 42),
225 + ({"minItems": 2}, {"not": "an array"}),
226 + ({"propertyNames": {"pattern": "^x"}}, 42),
227 + ({"dependencies": {"a": ["b"]}}, 42),
228 + ({"not": {"type": "string"}}, 42),
229 + ({"if": {"type": "string"}, "then": {"minLength": 2}}, 42),
230 + ],
231 +)
232 +def test_typeless_assertions_accept_nonmatching_instance_types(
233 + schema: dict[str, t.Any],
234 + value: t.Any,
235 +) -> None:
236 + Draft7Validator.check_schema(schema)
237 + assert Draft7Validator(schema).is_valid(value)
238 + TypeAdapter(json_schema_to_pydantic_type(schema)).validate_python(value)
239 +
240 +
241 +@pytest.mark.unit
242 +@pytest.mark.schema
243 +def test_direct_local_ref_accepts_a_valid_referenced_value() -> None:
244 + schema = {
245 + "$defs": {"positive": {"type": "number", "minimum": 1}},
246 + "$ref": "#/$defs/positive",
247 + }
248 + Draft7Validator.check_schema(schema)
249 + assert Draft7Validator(schema).is_valid(2)
250 + TypeAdapter(json_schema_to_pydantic_type(schema)).validate_python(2)
251 +
252 +
253 +@pytest.mark.unit
254 +@pytest.mark.schema
255 +def test_nested_typeless_object_assertion_accepts_a_non_object_property() -> None:
256 + schema = {
257 + "title": "NestedTypelessObject",
258 + "type": "object",
259 + "properties": {
260 + "value": {"properties": {"x": {"type": "string"}}},
261 + },
262 + "required": ["value"],
263 + }
264 + value = {"value": 42}
265 + Draft7Validator.check_schema(schema)
266 + assert Draft7Validator(schema).is_valid(value)
267 +
268 + annotations = (
269 + json_schema_to_pydantic_type(schema),
270 + json_schema_to_model(schema),
271 + pydantic_model_from_param_schema(schema),
272 + )
273 + for annotation in annotations:
274 + TypeAdapter(annotation).validate_python(value)
275 +
276 +
277 +@pytest.mark.unit
278 +@pytest.mark.schema
279 +@pytest.mark.parametrize("entry_point", ("pydantic_type", "model", "param_schema"))
280 +def test_external_ref_is_refused_without_network_io(entry_point: str) -> None:
281 + """A remote `$ref` must never make the validator fetch over the network."""
282 + requests: list[str] = []
283 +
284 + class Handler(BaseHTTPRequestHandler):
285 + def do_GET(self) -> None: # noqa: N802 - http.server API
286 + requests.append(self.path)
287 + body = json.dumps({"type": "string"}).encode()
288 + self.send_response(200)
289 + self.send_header("Content-Type", "application/json")
290 + self.send_header("Content-Length", str(len(body)))
291 + self.end_headers()
292 + self.wfile.write(body)
293 +
294 + def log_message(self, *args: t.Any) -> None:
295 + pass
296 +
297 + server = HTTPServer(("127.0.0.1", 0), Handler)
298 + thread = threading.Thread(target=server.serve_forever, daemon=True)
299 + thread.start()
300 + try:
301 + url = f"http://127.0.0.1:{server.server_address[1]}/schema"
302 + schema = {
303 + "title": "ExternalRef",
304 + "type": "object",
305 + "properties": {"value": {"$ref": url}},
306 + "required": ["value"],
307 + }
308 + converters: t.Dict[str, t.Callable[..., t.Any]] = {
309 + "pydantic_type": json_schema_to_pydantic_type,
310 + "model": json_schema_to_model,
311 + "param_schema": pydantic_model_from_param_schema,
312 + }
313 + convert = converters[entry_point]
314 + with pytest.raises(ValueError, match="External schema reference"):
315 + annotation = convert(schema)
316 + TypeAdapter(annotation).validate_python({"value": "x"})
317 + finally:
318 + server.shutdown()
319 + server.server_close()
320 + assert requests == []
321 +
322 +
323 +@pytest.mark.unit
324 +@pytest.mark.schema
325 +def test_backtracking_pattern_rejects_in_linear_time() -> None:
326 + schema = {
327 + "type": "object",
328 + "properties": {"value": {"type": "string", "pattern": "(a+)+$"}},
329 + }
330 + value = {"value": "a" * 24 + "!"}
331 + assert not Draft7Validator(schema).is_valid(value)
332 + model = json_schema_to_model(schema)
333 +
334 + started = time.perf_counter()
335 + with pytest.raises(ValidationError):
336 + model.model_validate(value)
337 + assert time.perf_counter() - started < 0.2
338 +
339 + model.model_validate({"value": "aaa"})
340 +
341 +
342 +@pytest.mark.unit
343 +@pytest.mark.schema
344 +@pytest.mark.parametrize("combiner", ("anyOf", "oneOf"))
345 +def test_simple_union_rejects_bool_for_integer_or_null(combiner: str) -> None:
346 + schema = {combiner: [{"type": "integer"}, {"type": "null"}]}
347 + assert not Draft7Validator(schema).is_valid(True)
348 +
349 + adapter = TypeAdapter(json_schema_to_pydantic_type(schema))
350 + with pytest.raises(ValidationError):
351 + adapter.validate_python(True)
352 + assert adapter.validate_python(1) == 1
353 + assert adapter.validate_python(None) is None
354 +
355 +
356 +@pytest.mark.unit
357 +@pytest.mark.schema
358 +@pytest.mark.parametrize("combiner", ("anyOf", "oneOf"))
359 +def test_toplevel_combiner_model_keeps_sibling_assertions(combiner: str) -> None:
360 + schema = {
361 + combiner: [{"type": "object", "properties": {"a": {"type": "string"}}}],
362 + "required": ["a"],
363 + }
364 + assert not Draft7Validator(schema).is_valid({})
365 +
366 + adapter = TypeAdapter(json_schema_to_pydantic_type(schema))
367 + with pytest.raises(ValidationError):
368 + adapter.validate_python({})
369 + assert adapter.dump_python(adapter.validate_python({"a": "x"}), mode="json") == {
370 + "a": "x"
371 + }
372 +
373 +
374 +@pytest.mark.unit
375 +@pytest.mark.schema
376 +def test_property_less_param_schema_keeps_assertions() -> None:
377 + schema = {"title": "NonEmpty", "type": "object", "minProperties": 1}
378 + assert not Draft7Validator(schema).is_valid({})
379 +
380 + adapter = TypeAdapter(pydantic_model_from_param_schema(schema))
381 + with pytest.raises(ValidationError):
382 + adapter.validate_python({})
383 + assert adapter.validate_python({"k": 1}) == {"k": 1}
384 +
385 +
386 +@pytest.mark.unit
387 +@pytest.mark.schema
388 +def test_exact_validated_array_items_keep_materialized_defaults() -> None:
389 + schema = {
390 + "type": "object",
391 + "title": "DynamicArrayArguments",
392 + "patternProperties": {
393 + "^items_": {
394 + "type": "array",
395 + "items": {
396 + "type": "object",
397 + "properties": {
398 + "null_default": {
399 + "anyOf": [{"type": "string"}, {"type": "null"}],
400 + "default": None,
401 + }
402 + },
403 + },
404 + }
405 + },
406 + "additionalProperties": False,
407 + }
408 + adapter = TypeAdapter(json_schema_to_pydantic_type(schema))
409 + assert adapter.dump_python(
410 + adapter.validate_python({"items_a": [{}]}), mode="json"
411 + ) == {"items_a": [{"null_default": None}]}
412 +
413 +
414 +@pytest.mark.unit
415 +@pytest.mark.schema
416 +def test_property_less_param_schema_admits_non_objects() -> None:
417 + schema = {"title": "Either", "anyOf": [{"type": "string"}, {"type": "object"}]}
418 + assert Draft7Validator(schema).is_valid("x")
419 +
420 + adapter = TypeAdapter(pydantic_model_from_param_schema(schema))
421 + assert adapter.validate_python("x") == "x"
422 + assert adapter.validate_python({"k": 1}) == {"k": 1}
423 + with pytest.raises(ValidationError):
424 + adapter.validate_python(1)
ts/packages/core/test/fixtures/json-schema-conversion/object-cases.json
+491
@@ -645,6 +645,333 @@
645 }
646 ]
647 },
648 + {
649 + "id": "primitive-boolean-property-schemas",
650 + "description": "Boolean property schemas accept every value for true and reject every supplied value for false.",
651 + "schema": {
652 + "type": "object",
653 + "properties": { "allowed": true, "forbidden": false },
654 + "required": ["allowed"]
655 + },
656 + "instances": [
657 + { "input": { "allowed": { "nested": 1 } }, "accepted": true },
658 + { "input": { "allowed": 42, "forbidden": "present" }, "accepted": false }
659 + ]
660 + },
661 + {
662 + "id": "primitive-empty-and-null-schemas",
663 + "description": "An empty schema accepts any value while a pure null schema accepts only null.",
664 + "schema": {
665 + "type": "object",
666 + "properties": { "anything": {}, "nullOnly": { "type": "null" } },
667 + "required": ["anything", "nullOnly"]
668 + },
669 + "instances": [
670 + { "input": { "anything": 42, "nullOnly": null }, "accepted": true },
671 + { "input": { "anything": null, "nullOnly": "not-null" }, "accepted": false }
672 + ]
673 + },
674 + {
675 + "id": "primitive-type-array-union",
676 + "description": "Every member of a JSON Schema type array remains accepted.",
677 + "schema": {
678 + "type": "object",
679 + "properties": { "value": { "type": ["string", "integer", "null"] } },
680 + "required": ["value"]
681 + },
682 + "instances": [
683 + { "input": { "value": "ready" }, "accepted": true },
684 + { "input": { "value": 2 }, "accepted": true },
685 + { "input": { "value": null }, "accepted": true },
686 + { "input": { "value": true }, "accepted": false }
687 + ]
688 + },
689 + {
690 + "id": "primitive-enum-intersects-declared-type",
691 + "description": "Enum values cannot bypass the schema's declared JSON type.",
692 + "schema": {
693 + "type": "object",
694 + "properties": { "value": { "type": "string", "enum": [1, "ready"] } },
695 + "required": ["value"]
696 + },
697 + "instances": [
698 + { "input": { "value": "ready" }, "accepted": true },
699 + { "input": { "value": 1 }, "accepted": false },
700 + { "input": { "value": "other" }, "accepted": false }
701 + ]
702 + },
703 + {
704 + "id": "primitive-null-only-unions",
705 + "description": "A union containing only null accepts only null.",
706 + "schema": {
707 + "type": "object",
708 + "properties": {
709 + "typeArray": { "type": ["null"] },
710 + "anyOf": { "anyOf": [{ "type": "null" }] }
711 + },
712 + "required": ["typeArray", "anyOf"]
713 + },
714 + "instances": [
715 + { "input": { "typeArray": null, "anyOf": null }, "accepted": true },
716 + { "input": { "typeArray": "anything", "anyOf": null }, "accepted": false },
717 + { "input": { "typeArray": null, "anyOf": 1 }, "accepted": false }
718 + ]
719 + },
720 + {
721 + "id": "primitive-scalar-constraints",
722 + "description": "String and numeric constraints survive conversion together.",
723 + "schema": {
724 + "type": "object",
725 + "properties": {
726 + "code": { "type": "string", "pattern": "^[A-Z]{2}$", "minLength": 2, "maxLength": 2 },
727 + "count": { "type": "number", "exclusiveMinimum": 0, "multipleOf": 2 }
728 + },
729 + "required": ["code", "count"]
730 + },
731 + "instances": [
732 + { "input": { "code": "OK", "count": 2 }, "accepted": true },
733 + { "input": { "code": "ok", "count": 2 }, "accepted": false },
734 + { "input": { "code": "OK", "count": 0 }, "accepted": false },
735 + { "input": { "code": "OK", "count": 3 }, "accepted": false }
736 + ]
737 + },
738 + {
739 + "id": "primitive-independent-numeric-bounds",
740 + "description": "Inclusive and numeric exclusive bounds apply independently under Draft 7.",
741 + "schema": {
742 + "type": "object",
743 + "properties": {
744 + "lower": { "type": "number", "minimum": 0, "exclusiveMinimum": 5 },
745 + "upper": { "type": "number", "maximum": 10, "exclusiveMaximum": 5 }
746 + },
747 + "required": ["lower", "upper"]
748 + },
749 + "instances": [
750 + { "input": { "lower": 6, "upper": 4 }, "accepted": true },
751 + { "input": { "lower": 1, "upper": 4 }, "accepted": false },
752 + { "input": { "lower": 6, "upper": 9 }, "accepted": false },
753 + { "input": { "lower": 5, "upper": 5 }, "accepted": false }
754 + ]
755 + },
756 + {
757 + "id": "primitive-const-intersects-declared-type",
758 + "description": "A const that conflicts with the declared type is unsatisfiable.",
759 + "schema": {
760 + "type": "object",
761 + "properties": { "value": { "type": "string", "const": 1 } },
762 + "required": ["value"]
763 + },
764 + "instances": [
765 + { "input": { "value": 1 }, "accepted": false },
766 + { "input": { "value": "1" }, "accepted": false }
767 + ]
768 + },
769 + {
770 + "id": "primitive-compound-enum-values",
771 + "description": "Enum values may contain any JSON value, including objects and arrays.",
772 + "schema": {
773 + "type": "object",
774 + "properties": {
775 + "value": { "enum": [{ "mode": "safe" }, ["ready", 1]] }
776 + },
777 + "required": ["value"]
778 + },
779 + "instances": [
780 + { "input": { "value": { "mode": "safe" } }, "accepted": true },
781 + { "input": { "value": ["ready", 1] }, "accepted": true },
782 + { "input": { "value": ["ready", true] }, "accepted": false },
783 + { "input": { "value": { "mode": true } }, "accepted": false },
784 + { "input": { "value": { "mode": "unsafe" } }, "accepted": false }
785 + ]
786 + },
787 + {
788 + "id": "primitive-const-null-and-false",
789 + "description": "Falsy consts keep their identity: null and false accept only themselves.",
790 + "schema": {
791 + "type": "object",
792 + "properties": { "maybe": { "const": null }, "flag": { "const": false } },
793 + "required": ["maybe", "flag"]
794 + },
795 + "instances": [
796 + { "input": { "maybe": null, "flag": false }, "accepted": true },
797 + { "input": { "maybe": null, "flag": 0 }, "accepted": false },
798 + { "input": { "maybe": "null", "flag": false }, "accepted": false }
799 + ]
800 + },
801 + {
802 + "id": "primitive-enum-boolean-number-identity",
803 + "description": "Enum membership distinguishes booleans from the numbers they equal in most host languages.",
804 + "schema": {
805 + "type": "object",
806 + "properties": { "bits": { "enum": [0, 1] }, "toggle": { "enum": [true] } },
807 + "required": ["bits", "toggle"]
808 + },
809 + "instances": [
810 + { "input": { "bits": 1, "toggle": true }, "accepted": true },
811 + { "input": { "bits": 0, "toggle": true }, "accepted": true },
812 + { "input": { "bits": true, "toggle": true }, "accepted": false },
813 + { "input": { "bits": 1, "toggle": 1 }, "accepted": false },
814 + { "input": { "bits": false, "toggle": true }, "accepted": false }
815 + ]
816 + },
817 + {
818 + "id": "primitive-enum-with-null-member",
819 + "description": "A null enum member is accepted alongside other literal values.",
820 + "schema": {
821 + "type": "object",
822 + "properties": { "value": { "enum": ["a", null] } },
823 + "required": ["value"]
824 + },
825 + "instances": [
826 + { "input": { "value": "a" }, "accepted": true },
827 + { "input": { "value": null }, "accepted": true },
828 + { "input": { "value": "b" }, "accepted": false }
829 + ]
830 + },
831 + {
832 + "id": "primitive-const-constraint-conjunction",
833 + "description": "A const must still satisfy sibling constraints; a conflict rejects everything.",
834 + "schema": {
835 + "type": "object",
836 + "properties": { "code": { "type": "string", "const": "a", "minLength": 2 } },
837 + "required": ["code"]
838 + },
839 + "instances": [
840 + { "input": { "code": "a" }, "accepted": false },
841 + { "input": { "code": "ab" }, "accepted": false }
842 + ]
843 + },
844 + {
845 + "id": "primitive-inclusive-numeric-boundaries",
846 + "description": "Draft 7 minimum and maximum are inclusive bounds.",
847 + "schema": {
848 + "type": "object",
849 + "properties": { "count": { "type": "integer", "minimum": 5, "maximum": 10 } },
850 + "required": ["count"]
851 + },
852 + "instances": [
853 + { "input": { "count": 5 }, "accepted": true },
854 + { "input": { "count": 10 }, "accepted": true },
855 + { "input": { "count": 4 }, "accepted": false },
856 + { "input": { "count": 11 }, "accepted": false }
857 + ]
858 + },
859 + {
860 + "id": "primitive-const-narrows-enum",
861 + "description": "When const and enum are both present, only their intersection is accepted.",
862 + "schema": {
863 + "type": "object",
864 + "properties": { "value": { "enum": ["a", "b"], "const": "b" } },
865 + "required": ["value"]
866 + },
867 + "instances": [
868 + { "input": { "value": "b" }, "accepted": true },
869 + { "input": { "value": "a" }, "accepted": false }
870 + ]
871 + },
872 + {
873 + "id": "primitive-compound-const-deep-equality",
874 + "description": "A compound const compares by deep JSON equality, including boolean identity inside containers.",
875 + "schema": {
876 + "type": "object",
877 + "properties": { "value": { "const": { "a": [1, "x", null] } } },
878 + "required": ["value"]
879 + },
880 + "instances": [
881 + { "input": { "value": { "a": [1, "x", null] } }, "accepted": true },
882 + { "input": { "value": { "a": [1, "x", null], "b": 1 } }, "accepted": false },
883 + { "input": { "value": { "a": [true, "x", null] } }, "accepted": false },
884 + { "input": { "value": { "a": [1, "x"] } }, "accepted": false }
885 + ]
886 + },
887 + {
888 + "id": "primitive-unicode-code-point-length",
889 + "description": "String length constraints count Unicode code points, not UTF-16 code units.",
890 + "schema": {
891 + "type": "object",
892 + "properties": { "glyph": { "type": "string", "maxLength": 1 } },
893 + "required": ["glyph"]
894 + },
895 + "instances": [
896 + { "input": { "glyph": "𝄞" }, "accepted": true },
897 + { "input": { "glyph": "ab" }, "accepted": false }
898 + ]
899 + },
900 + {
901 + "id": "primitive-typeless-constraint-scoping",
902 + "description": "Draft 7 applies string constraints to string instances even without a declared type.",
903 + "schema": {
904 + "type": "object",
905 + "properties": { "value": { "enum": ["a", "abc"], "minLength": 2 } },
906 + "required": ["value"]
907 + },
908 + "instances": [
909 + { "input": { "value": "abc" }, "accepted": true },
910 + { "input": { "value": "a" }, "accepted": false }
911 + ]
912 + },
913 + {
914 + "id": "primitive-float-multiple-of",
915 + "description": "Decimal multipleOf checks tolerate binary floating-point representation error.",
916 + "divergesFromJsonSchema": "A literal Draft 7 multipleOf uses raw float arithmetic and rejects 0.3 for 0.1; every Composio converter scales decimals before comparing.",
917 + "schema": {
918 + "type": "object",
919 + "properties": { "step": { "type": "number", "multipleOf": 0.1 } },
920 + "required": ["step"]
921 + },
922 + "instances": [
923 + { "input": { "step": 0.3 }, "accepted": true },
924 + { "input": { "step": 0.35 }, "accepted": false }
925 + ]
926 + },
927 + {
928 + "id": "primitive-draft4-boolean-exclusive-bounds",
929 + "description": "OpenAPI 3.0 style boolean exclusiveMinimum/exclusiveMaximum flags turn the paired bound exclusive.",
930 + "schema": {
931 + "type": "object",
932 + "properties": {
933 + "lower": { "type": "number", "minimum": 5, "exclusiveMinimum": true },
934 + "upper": { "type": "number", "maximum": 5, "exclusiveMaximum": true }
935 + },
936 + "required": ["lower", "upper"]
937 + },
938 + "instances": [
939 + { "input": { "lower": 6, "upper": 4 }, "accepted": true },
940 + { "input": { "lower": 5, "upper": 4 }, "accepted": false },
941 + { "input": { "lower": 6, "upper": 5 }, "accepted": false }
942 + ]
943 + },
944 + {
945 + "id": "primitive-type-array-constraint-scoping",
946 + "description": "Constraints on a type array apply only to instances of their matching type.",
947 + "schema": {
948 + "type": "object",
949 + "properties": {
950 + "value": { "type": ["string", "number"], "minLength": 2, "minimum": 10 }
951 + },
952 + "required": ["value"]
953 + },
954 + "instances": [
955 + { "input": { "value": "ab" }, "accepted": true },
956 + { "input": { "value": 15 }, "accepted": true },
957 + { "input": { "value": "a" }, "accepted": false },
958 + { "input": { "value": 5 }, "accepted": false },
959 + { "input": { "value": true }, "accepted": false }
960 + ]
961 + },
962 + {
963 + "id": "primitive-empty-enum-optional-property",
964 + "description": "An optional property with an empty enum rejects every supplied value but tolerates absence.",
965 + "schema": {
966 + "type": "object",
967 + "properties": { "value": { "enum": [] } },
968 + "required": []
969 + },
970 + "instances": [
971 + { "input": {}, "accepted": true },
972 + { "input": { "value": null }, "accepted": false }
973 + ]
974 + },
975 {
976 "id": "additional-property-default-materialization",
977 "description": "Composio divergence: a schema-valued `additionalProperties` also materializes defaults in Zod and Pydantic while Effect leaves the input unchanged.",
@@ -677,6 +1004,170 @@
1004 "python": { "output": { "name": "a", "extra": { "enabled": false } } }
1005 }
1006 ]
1007 + },
1008 + {
1009 + "id": "composition-fixed-tuple-items",
1010 + "description": "Draft 7 tuple items preserve position, optional shorter arrays, and an additionalItems false bound.",
1011 + "schema": {
1012 + "$schema": "http://json-schema.org/draft-07/schema#",
1013 + "type": "object",
1014 + "properties": {
1015 + "value": {
1016 + "type": "array",
1017 + "items": [{ "type": "string" }, { "type": "integer" }],
1018 + "additionalItems": false
1019 + }
1020 + },
1021 + "required": ["value"]
1022 + },
1023 + "instances": [
1024 + { "input": { "value": [] }, "accepted": true },
1025 + { "input": { "value": ["ready"] }, "accepted": true },
1026 + { "input": { "value": ["ready", 2] }, "accepted": true },
1027 + { "input": { "value": [2, "ready"] }, "accepted": false },
1028 + { "input": { "value": ["ready", 2, true] }, "accepted": false }
1029 + ]
1030 + },
1031 + {
1032 + "id": "composition-open-tuple-items",
1033 + "description": "Tuple items default to Draft 7 and allow unconstrained trailing values unless additionalItems closes them.",
1034 + "schema": {
1035 + "type": "object",
1036 + "properties": {
1037 + "value": {
1038 + "type": "array",
1039 + "items": [{ "type": "string" }, { "type": "integer" }]
1040 + }
1041 + },
1042 + "required": ["value"]
1043 + },
1044 + "instances": [
1045 + { "input": { "value": ["ready", 2, { "extra": true }] }, "accepted": true },
1046 + { "input": { "value": ["ready", "wrong"] }, "accepted": false }
1047 + ]
1048 + },
1049 + {
1050 + "id": "composition-false-tuple-position",
1051 + "description": "A false positional schema rejects a value only when that position is present.",
1052 + "schema": {
1053 + "$schema": "http://json-schema.org/draft-07/schema#",
1054 + "type": "object",
1055 + "properties": {
1056 + "value": {
1057 + "type": "array",
1058 + "items": [{ "type": "string" }, false],
1059 + "additionalItems": false
1060 + }
1061 + },
1062 + "required": ["value"]
1063 + },
1064 + "instances": [
1065 + { "input": { "value": ["ready"] }, "accepted": true },
1066 + { "input": { "value": ["ready", "forbidden"] }, "accepted": false }
1067 + ]
1068 + },
1069 + {
1070 + "id": "composition-allof-object-intersection",
1071 + "description": "Every allOf object branch remains required after conversion.",
1072 + "schema": {
1073 + "type": "object",
1074 + "properties": {
1075 + "value": {
1076 + "allOf": [
1077 + {
1078 + "type": "object",
1079 + "properties": { "a": { "type": "string" } },
1080 + "required": ["a"],
1081 + "additionalProperties": true
1082 + },
1083 + {
1084 + "type": "object",
1085 + "properties": { "b": { "type": "integer" } },
1086 + "required": ["b"],
1087 + "additionalProperties": true
1088 + }
1089 + ]
1090 + }
1091 + },
1092 + "required": ["value"]
1093 + },
1094 + "instances": [
1095 + { "input": { "value": { "a": "ready", "b": 2 } }, "accepted": true },
1096 + { "input": { "value": { "a": "ready" } }, "accepted": false },
1097 + { "input": { "value": { "b": 2 } }, "accepted": false }
1098 + ]
1099 + },
1100 + {
1101 + "id": "composition-allof-closed-object-branches",
1102 + "description": "Closed allOf object branches merge instead of rejecting each other's keys; the union of declared keys stays strict.",
1103 + "schema": {
1104 + "type": "object",
1105 + "properties": {
1106 + "value": {
1107 + "allOf": [
1108 + {
1109 + "type": "object",
1110 + "properties": { "a": { "type": "string" } },
1111 + "required": ["a"]
1112 + },
1113 + {
1114 + "type": "object",
1115 + "properties": { "b": { "type": "string" } },
1116 + "required": ["b"]
1117 + }
1118 + ]
1119 + }
1120 + },
1121 + "required": ["value"]
1122 + },
1123 + "instances": [
1124 + { "input": { "value": { "a": "ready", "b": "set" } }, "accepted": true },
1125 + { "input": { "value": { "a": "ready" } }, "accepted": false },
1126 + { "input": { "value": { "a": "ready", "b": "set", "c": 1 } }, "accepted": false }
1127 + ]
1128 + },
1129 + {
1130 + "id": "composition-scalar-allof",
1131 + "description": "Scalar allOf branches combine rather than selecting the first branch.",
1132 + "schema": {
1133 + "type": "object",
1134 + "properties": {
1135 + "value": {
1136 + "allOf": [
1137 + { "type": "string", "minLength": 2 },
1138 + { "type": "string", "pattern": "^[A-Z]+$" }
1139 + ]
1140 + }
1141 + },
1142 + "required": ["value"]
1143 + },
1144 + "instances": [
1145 + { "input": { "value": "OK" }, "accepted": true },
1146 + { "input": { "value": "O" }, "accepted": false },
1147 + { "input": { "value": "ok" }, "accepted": false }
1148 + ]
1149 + },
1150 + {
1151 + "id": "composition-oneof-exclusive-match",
1152 + "description": "oneOf accepts exactly one matching branch, not a plain union of branches.",
1153 + "schema": {
1154 + "type": "object",
1155 + "properties": {
1156 + "value": {
1157 + "oneOf": [
1158 + { "type": "number", "minimum": 0 },
1159 + { "type": "number", "maximum": 0 }
1160 + ]
1161 + }
1162 + },
1163 + "required": ["value"]
1164 + },
1165 + "instances": [
1166 + { "input": { "value": 1 }, "accepted": true },
1167 + { "input": { "value": -1 }, "accepted": true },
1168 + { "input": { "value": 0 }, "accepted": false },
1169 + { "input": { "value": "0" }, "accepted": false }
1170 + ]
1171 }
1172 ]
1173 }
ts/packages/json-schema-to-effect-schema/src/index.ts
+88 -8
@@ -56,6 +56,53 @@ const isObjectSchema = (schema: JsonObject): boolean =>
56 const hasNamedProperties = (schema: JsonObject): boolean =>
57 isJsonObject(schema.properties) && Object.keys(schema.properties).length > 0;
58
59 +const isClosedObjectBranch = (branch: unknown): branch is JsonObject =>
60 + isJsonObject(branch) &&
61 + isObjectSchema(branch) &&
62 + hasNamedProperties(branch) &&
63 + branch.additionalProperties === undefined &&
64 + branch.patternProperties === undefined &&
65 + branch.$ref === undefined;
66 +
67 +// Sibling `allOf` object branches must not reject each other's keys, so each
68 +// closed branch is materialized open and the strictness a lone named-property
69 +// object would have had is re-applied once, over the union of every branch's
70 +// properties. Mirrors `parseAllOf` in @composio/json-schema-to-zod.
71 +const openAllOfBranches = (source: JsonObject, normalized: JsonObject): void => {
72 + const sourceBranches = source.allOf;
73 + const branches = normalized.allOf;
74 + if (!Array.isArray(sourceBranches) || !Array.isArray(branches) || branches.length < 2) {
75 + return;
76 + }
77 +
78 + const closed = sourceBranches.map(isClosedObjectBranch);
79 + if (!closed.some(Boolean)) {
80 + return;
81 + }
82 +
83 + branches.forEach((branch, index) => {
84 + if (closed[index] && isJsonObject(branch)) {
85 + branch.additionalProperties = true;
86 + }
87 + });
88 +
89 + if (
90 + !closed.every(Boolean) ||
91 + normalized.properties !== undefined ||
92 + normalized.patternProperties !== undefined ||
93 + normalized.additionalProperties !== undefined
94 + ) {
95 + return;
96 + }
97 +
98 + normalized.properties = Object.fromEntries(
99 + sourceBranches.flatMap(branch =>
100 + Object.keys((branch as JsonObject).properties as JsonObject).map(key => [key, true])
101 + )
102 + );
103 + normalized.additionalProperties = false;
104 +};
105 +
106 const appendAllOf = (schema: JsonObject, constraint: JsonObject): void => {
107 const current = schema.allOf;
108 schema.allOf = Array.isArray(current) ? [...current, constraint] : [constraint];
@@ -87,6 +134,26 @@ const normalizeBounds = (schema: JsonObject): void => {
134 }
135 };
136
137 +// OpenAPI 3.0 / JSON Schema draft-4 express exclusive bounds as a boolean flag
138 +// on `minimum`/`maximum`. The Draft 7 interpreter expects numeric
139 +// `exclusiveMinimum`/`exclusiveMaximum` and would silently ignore the flag,
140 +// turning an exclusive bound into an inclusive one.
141 +const normalizeExclusiveBounds = (schema: JsonObject): void => {
142 + if (schema.exclusiveMinimum === true && typeof schema.minimum === 'number') {
143 + schema.exclusiveMinimum = schema.minimum;
144 + delete schema.minimum;
145 + } else if (typeof schema.exclusiveMinimum === 'boolean') {
146 + delete schema.exclusiveMinimum;
147 + }
148 +
149 + if (schema.exclusiveMaximum === true && typeof schema.maximum === 'number') {
150 + schema.exclusiveMaximum = schema.maximum;
151 + delete schema.maximum;
152 + } else if (typeof schema.exclusiveMaximum === 'boolean') {
153 + delete schema.exclusiveMaximum;
154 + }
155 +};
156 +
157 const normalizeFormats = (schema: JsonObject): void => {
158 if (schema.type === 'number' && schema.format === 'int64') {
159 schema.type = 'integer';
@@ -132,6 +199,7 @@ const normalizeNullable = (schema: JsonObject): JsonObject => {
199
200 const normalizeSchemaNode = (
201 value: unknown,
202 + draft: SchemaDraft,
203 seen: WeakMap<object, InterpreterSchema | boolean>
204 ): InterpreterSchema | boolean => {
205 if (typeof value === 'boolean') {
@@ -152,14 +220,17 @@ const normalizeSchemaNode = (
220 for (const [key, child] of Object.entries(value)) {
221 if (schemaMapKeywords.has(key) && isJsonObject(child)) {
222 normalized[key] = Object.fromEntries(
155 - Object.entries(child).map(([name, nested]) => [name, normalizeSchemaNode(nested, seen)])
223 + Object.entries(child).map(([name, nested]) => [
224 + name,
225 + normalizeSchemaNode(nested, draft, seen),
226 + ])
227 );
228 } else if (schemaArrayKeywords.has(key) && Array.isArray(child)) {
158 - normalized[key] = child.map(nested => normalizeSchemaNode(nested, seen));
229 + normalized[key] = child.map(nested => normalizeSchemaNode(nested, draft, seen));
230 } else if (schemaValueKeywords.has(key)) {
231 normalized[key] = Array.isArray(child)
161 - ? child.map(nested => normalizeSchemaNode(nested, seen))
162 - : normalizeSchemaNode(child, seen);
232 + ? child.map(nested => normalizeSchemaNode(nested, draft, seen))
233 + : normalizeSchemaNode(child, draft, seen);
234 } else {
235 normalized[key] = child;
236 }
@@ -178,15 +249,23 @@ const normalizeSchemaNode = (
249 normalized.additionalProperties = false;
250 }
251
252 + openAllOfBranches(value, normalized);
253 +
254 normalizeBounds(normalized);
255 + // Draft 4 is the dialect that defines the boolean spelling, and the
256 + // interpreter honors it there; rewriting would hand it a numeric bound it
257 + // ignores under that draft.
258 + if (draft !== '4') {
259 + normalizeExclusiveBounds(normalized);
260 + }
261 normalizeFormats(normalized);
262 const withNullable = normalizeNullable(normalized);
263 seen.set(value, withNullable as InterpreterSchema);
264 return withNullable as InterpreterSchema;
265 };
266
188 -const normalizeJsonSchema = (schema: JsonObject): InterpreterSchema =>
189 - normalizeSchemaNode(schema, new WeakMap()) as InterpreterSchema;
267 +const normalizeJsonSchema = (schema: JsonObject, draft: SchemaDraft): InterpreterSchema =>
268 + normalizeSchemaNode(schema, draft, new WeakMap()) as InterpreterSchema;
269
270 // Walks the same child positions `normalizeSchemaNode` does, so a node is
271 // visited exactly where the interpreter would descend into it.
@@ -450,8 +529,9 @@ export const jsonSchemaToEffectSchema = (
529 jsonSchema: JsonObject,
530 options: JsonSchemaToEffectSchemaOptions = {}
531 ): Schema.Schema<unknown> => {
453 - const normalizedSchema = normalizeJsonSchema(jsonSchema);
454 - const validator = new Validator(normalizedSchema, options.draft ?? '7', false);
532 + const draft = options.draft ?? '7';
533 + const normalizedSchema = normalizeJsonSchema(jsonSchema, draft);
534 + const validator = new Validator(normalizedSchema, draft, false);
535 assertSchemaIsInterpretable(normalizedSchema);
536 const formatIssues = options.formatIssues ?? defaultFormatIssues;
537
ts/packages/json-schema-to-effect-schema/test/json-schema-to-effect-schema.test.ts
+11
@@ -56,6 +56,17 @@ describe('jsonSchemaToEffectSchema', () => {
56 expectParity({ type: 'string', format: 'ip' }, 'not-an-ip', false);
57 });
58
59 + it('honors the boolean exclusive bound under an explicit Draft 4', () => {
60 + const schema = { type: 'number', minimum: 1, exclusiveMinimum: true } satisfies JsonSchema;
61 + const accepts = (input: unknown, draft?: '4'): boolean =>
62 + Option.isSome(Schema.decodeUnknownOption(jsonSchemaToEffectSchema(schema, { draft }))(input));
63 +
64 + expect(accepts(1, '4')).toBe(false);
65 + expect(accepts(2, '4')).toBe(true);
66 + expect(accepts(1)).toBe(false);
67 + expect(accepts(2)).toBe(true);
68 + });
69 +
70 it('supports JSON Schema composition without generated code', () => {
71 const schema = {
72 type: 'object',
ts/packages/json-schema-to-zod/package.json
+6
@@ -48,6 +48,8 @@
48 "devDependencies": {
49 "@types/json-schema": "^7.0.15",
50 "@types/node": "^26.3.0",
51 + "ajv": "^8.20.0",
52 + "fast-check": "^4.9.0",
53 "tsdown": "catalog:",
54 "typescript": "catalog:",
55 "vitest": "catalog:",
@@ -55,5 +57,9 @@
57 },
58 "peerDependencies": {
59 "zod": ">=3.25.76 <5"
60 + },
61 + "dependencies": {
62 + "@cfworker/json-schema": "^4.1.1",
63 + "dequal": "^2.0.3"
64 }
65 }
ts/packages/json-schema-to-zod/src/json-schema-to-zod.ts
+12 -2
@@ -1,18 +1,27 @@
1 -import type { z, ZodTypeAny } from 'zod/v3';
1 +import { z, type ZodTypeAny } from 'zod/v3';
2
3 import { parseSchema } from './parsers/parse-schema';
4 import { parseObjectShape } from './parsers/parse-object-shape';
5 import type { JsonSchemaToZodOptions, JsonSchema, JsonSchemaObject } from './types';
6 +import {
7 + requiresWholeSchemaValidation,
8 + withWholeSchemaValidation,
9 +} from './whole-schema-validation';
10
11 export const jsonSchemaToZod = (
12 schema: JsonSchema,
13 options: JsonSchemaToZodOptions = {}
14 ): z.ZodType => {
11 - return parseSchema(schema, {
15 + const parsedSchema = parseSchema(schema, {
16 path: [],
17 seen: new Map(),
18 + root: schema,
19 ...options,
20 });
21 +
22 + return requiresWholeSchemaValidation(schema)
23 + ? withWholeSchemaValidation(schema, parsedSchema)
24 + : parsedSchema;
25 };
26
27 /**
@@ -46,6 +55,7 @@ export const jsonSchemaToZodShape = (
55 return parseObjectShape(objectSchema, {
56 path: [],
57 seen: new Map(),
58 + root: objectSchema,
59 ...options,
60 });
61 };
ts/packages/json-schema-to-zod/src/parsers/parse-all-of.ts
+52 -7
@@ -3,6 +3,7 @@ import { z } from 'zod/v3';
3 import { parseSchema } from './parse-schema';
4 import type { JsonSchemaObject, JsonSchema, Refs } from '../types';
5 import { half } from '../utils/half';
6 +import { its } from '../utils/its';
7
8 const originalIndex = Symbol('Original index');
9
@@ -23,6 +24,31 @@ const ensureOriginalIndex = (arr: JsonSchema[]) => {
24 return newArr;
25 };
26
27 +const isClosedObjectBranch = (
28 + branch: JsonSchema
29 +): branch is JsonSchemaObject & { properties: Record<string, JsonSchema> } =>
30 + typeof branch === 'object' &&
31 + its.an.object(branch) &&
32 + branch.properties !== undefined &&
33 + Object.keys(branch.properties).length > 0 &&
34 + branch.additionalProperties === undefined &&
35 + branch.patternProperties === undefined &&
36 + !('$ref' in branch);
37 +
38 +const intersect = (branches: JsonSchema[], refs: Refs): z.ZodTypeAny => {
39 + if (branches.length === 1) {
40 + const item = branches[0];
41 +
42 + return parseSchema(item, {
43 + ...refs,
44 + path: [...refs.path, 'allOf', (item as never)[originalIndex]],
45 + });
46 + }
47 +
48 + const [left, right] = half(branches);
49 + return z.intersection(intersect(left, refs), intersect(right, refs));
50 +};
51 +
52 export function parseAllOf(
53 jsonSchema: JsonSchemaObject & { allOf: JsonSchema[] },
54 refs: Refs
@@ -32,15 +58,34 @@ export function parseAllOf(
58 }
59
60 if (jsonSchema.allOf.length === 1) {
35 - const item = jsonSchema.allOf[0];
61 + return intersect(ensureOriginalIndex(jsonSchema.allOf), refs);
62 + }
63
37 - return parseSchema(item, {
38 - ...refs,
39 - path: [...refs.path, 'allOf', (item as never)[originalIndex]],
40 - });
64 + // Sibling object branches must not reject each other's keys: each branch is
65 + // materialized open, and the strictness a lone named-property object would
66 + // have had is re-applied once over the union of every branch's properties.
67 + const opened = jsonSchema.allOf.map(branch =>
68 + isClosedObjectBranch(branch) ? { ...branch, additionalProperties: true } : branch
69 + );
70 + const parsed = intersect(ensureOriginalIndex(opened), refs);
71 +
72 + if (!jsonSchema.allOf.every(isClosedObjectBranch)) {
73 + return parsed;
74 }
75
43 - const [left, right] = half(ensureOriginalIndex(jsonSchema.allOf));
76 + const declaredKeys = new Set(
77 + jsonSchema.allOf.flatMap(branch => Object.keys((branch as JsonSchemaObject).properties ?? {}))
78 + );
79
45 - return z.intersection(parseAllOf({ allOf: left }, refs), parseAllOf({ allOf: right }, refs));
80 + return parsed.superRefine((value, ctx) => {
81 + if (typeof value !== 'object' || value === null || Array.isArray(value)) return;
82 + const unrecognizedKeys = Object.keys(value).filter(key => !declaredKeys.has(key));
83 + if (unrecognizedKeys.length > 0) {
84 + ctx.addIssue({
85 + code: z.ZodIssueCode.unrecognized_keys,
86 + keys: unrecognizedKeys,
87 + message: `Unrecognized key(s) in object: ${unrecognizedKeys.map(key => `'${key}'`).join(', ')}`,
88 + });
89 + }
90 + });
91 }
ts/packages/json-schema-to-zod/src/parsers/parse-array.ts
+39 -4
@@ -58,11 +58,46 @@ export const parseArray = (jsonSchema: JsonSchemaObject & { type: 'array' }, ref
58
59 // Handle regular array schema
60 if (Array.isArray(jsonSchema.items)) {
61 - return z.tuple(
62 - jsonSchema.items.map((v, i) =>
63 - parseSchema(v, { ...refs, path: [...refs.path, 'items', i] })
64 - ) as [z.ZodTypeAny]
61 + const parsedItems = jsonSchema.items.map((item, index) =>
62 + parseSchema(item, { ...refs, path: [...refs.path, 'items', index] })
63 );
64 + const prefixSchemas = parsedItems.map((_, length) =>
65 + z.tuple(parsedItems.slice(0, length) as unknown as [z.ZodTypeAny])
66 + );
67 + const fullTuple = z.tuple(parsedItems as unknown as [z.ZodTypeAny]);
68 +
69 + let fullLengthSchema: z.ZodTypeAny;
70 + if (jsonSchema.additionalItems === false) {
71 + fullLengthSchema = fullTuple;
72 + } else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true) {
73 + fullLengthSchema = fullTuple.rest(
74 + parseSchema(jsonSchema.additionalItems, {
75 + ...refs,
76 + path: [...refs.path, 'additionalItems'],
77 + })
78 + );
79 + } else {
80 + fullLengthSchema = fullTuple.rest(z.any());
81 + }
82 +
83 + const variants = [...prefixSchemas, fullLengthSchema];
84 + let tupleSchema: z.ZodTypeAny =
85 + variants.length === 1
86 + ? variants[0]
87 + : z.union(variants as unknown as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]);
88 +
89 + if (typeof jsonSchema.minItems === 'number') {
90 + tupleSchema = tupleSchema.refine(value => value.length >= jsonSchema.minItems!, {
91 + message: `Array must contain at least ${jsonSchema.minItems} element(s)`,
92 + });
93 + }
94 + if (typeof jsonSchema.maxItems === 'number') {
95 + tupleSchema = tupleSchema.refine(value => value.length <= jsonSchema.maxItems!, {
96 + message: `Array must contain at most ${jsonSchema.maxItems} element(s)`,
97 + });
98 + }
99 +
100 + return tupleSchema;
101 }
102
103 let zodSchema = !jsonSchema.items
ts/packages/json-schema-to-zod/src/parsers/parse-const.ts
+8 -5
@@ -1,7 +1,10 @@
1 -import { z } from 'zod/v3';
1 +import { parseLiteralValues } from './parse-literal-values';
2 +import { parseSchema } from './parse-schema';
3 +import type { JsonSchemaObject, Refs, Serializable } from '../types';
4
3 -import type { JsonSchemaObject, Serializable } from '../types';
4 -
5 -export const parseConst = (jsonSchema: JsonSchemaObject & { const: Serializable }) => {
6 - return z.literal(jsonSchema.const as z.Primitive);
5 +export const parseConst = (jsonSchema: JsonSchemaObject & { const: Serializable }, refs: Refs) => {
6 + const { const: value, ...baseSchema } = jsonSchema;
7 + return parseSchema(baseSchema, { ...refs, seen: new Map(refs.seen) }, true).and(
8 + parseLiteralValues([value])
9 + );
10 };
ts/packages/json-schema-to-zod/src/parsers/parse-enum.ts
+8 -20
@@ -1,22 +1,10 @@
1 -import { z } from 'zod/v3';
2 -
3 -import type { JsonSchemaObject, Serializable } from '../types';
4 -
5 -export const parseEnum = (jsonSchema: JsonSchemaObject & { enum: Serializable[] }) => {
6 - if (jsonSchema.enum.length === 0) {
7 - return z.never();
8 - }
9 -
10 - if (jsonSchema.enum.length === 1) {
11 - // union does not work when there is only one element
12 - return z.literal(jsonSchema.enum[0] as z.Primitive);
13 - }
14 -
15 - if (jsonSchema.enum.every(x => typeof x === 'string')) {
16 - return z.enum(jsonSchema.enum as [string]);
17 - }
18 -
19 - return z.union(
20 - jsonSchema.enum.map(x => z.literal(x as z.Primitive)) as unknown as [z.ZodTypeAny, z.ZodTypeAny]
1 +import { parseLiteralValues } from './parse-literal-values';
2 +import { parseSchema } from './parse-schema';
3 +import type { JsonSchemaObject, Refs, Serializable } from '../types';
4 +
5 +export const parseEnum = (jsonSchema: JsonSchemaObject & { enum: Serializable[] }, refs: Refs) => {
6 + const { enum: values, ...baseSchema } = jsonSchema;
7 + return parseSchema(baseSchema, { ...refs, seen: new Map(refs.seen) }, true).and(
8 + parseLiteralValues(values)
9 );
10 };
ts/packages/json-schema-to-zod/src/parsers/parse-literal-values.ts new
+21
@@ -0,0 +1,21 @@
1 +import { dequal } from 'dequal/lite';
2 +import { z } from 'zod/v3';
3 +
4 +import type { Serializable } from '../types';
5 +
6 +export const parseLiteralValues = (values: ReadonlyArray<Serializable>): z.ZodTypeAny => {
7 + if (values.length === 0) return z.never();
8 +
9 + if (values.every(value => value === null || typeof value !== 'object')) {
10 + if (values.length === 1) return z.literal(values[0] as z.Primitive);
11 + if (values.every(value => typeof value === 'string')) return z.enum(values as [string]);
12 + return z.union(
13 + values.map(value => z.literal(value as z.Primitive)) as unknown as [
14 + z.ZodTypeAny,
15 + z.ZodTypeAny,
16 + ]
17 + );
18 + }
19 +
20 + return z.custom<Serializable>(value => values.some(candidate => dequal(value, candidate)));
21 +};
ts/packages/json-schema-to-zod/src/parsers/parse-number.ts
+51 -17
@@ -3,6 +3,41 @@ import { z } from 'zod/v3';
3 import type { JsonSchemaObject } from '../types';
4 import { extendSchemaWithMessage } from '../utils/extend-schema';
5
6 +type DecimalInteger = {
7 + readonly integer: bigint;
8 + readonly scale: number;
9 +};
10 +
11 +const toDecimalInteger = (value: number): DecimalInteger | undefined => {
12 + if (!Number.isFinite(value)) return undefined;
13 +
14 + const negative = value < 0;
15 + const [coefficient, exponentText] = Math.abs(value).toString().toLowerCase().split('e');
16 + const exponent = exponentText === undefined ? 0 : Number(exponentText);
17 + const [whole, fraction = ''] = coefficient.split('.');
18 + let digits = `${whole}${fraction}`.replace(/^0+(?=\d)/, '');
19 + let scale = fraction.length - exponent;
20 +
21 + if (scale < 0) {
22 + digits += '0'.repeat(-scale);
23 + scale = 0;
24 + }
25 +
26 + const integer = BigInt(`${negative ? '-' : ''}${digits}`);
27 + return { integer, scale };
28 +};
29 +
30 +const isJsonMultipleOf = (value: number, multiple: number): boolean => {
31 + const dividend = toDecimalInteger(value);
32 + const divisor = toDecimalInteger(multiple);
33 + if (!dividend || !divisor || divisor.integer === 0n) return false;
34 +
35 + const scale = Math.max(dividend.scale, divisor.scale);
36 + const scaledDividend = dividend.integer * 10n ** BigInt(scale - dividend.scale);
37 + const scaledDivisor = divisor.integer * 10n ** BigInt(scale - divisor.scale);
38 + return scaledDividend % scaledDivisor === 0n;
39 +};
40 +
41 export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'integer' }) => {
42 let zodSchema = z.number();
43
@@ -19,21 +54,6 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
54 );
55 }
56
22 - zodSchema = extendSchemaWithMessage(
23 - zodSchema,
24 - jsonSchema,
25 - 'multipleOf',
26 - (zs, multipleOf, errorMsg) => {
27 - if (multipleOf === 1) {
28 - if (isInteger) return zs;
29 -
30 - return zs.int(errorMsg);
31 - }
32 -
33 - return zs.multipleOf(multipleOf, errorMsg);
34 - }
35 - );
36 -
57 if (typeof jsonSchema.minimum === 'number') {
58 if ((jsonSchema as unknown as { exclusiveMinimum?: boolean }).exclusiveMinimum === true) {
59 zodSchema = extendSchemaWithMessage(
@@ -50,7 +70,8 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
70 (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg)
71 );
72 }
53 - } else if (typeof jsonSchema.exclusiveMinimum === 'number') {
73 + }
74 + if (typeof jsonSchema.exclusiveMinimum === 'number') {
75 zodSchema = extendSchemaWithMessage(
76 zodSchema,
77 jsonSchema,
@@ -75,7 +96,8 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
96 (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg)
97 );
98 }
78 - } else if (typeof jsonSchema.exclusiveMaximum === 'number') {
99 + }
100 + if (typeof jsonSchema.exclusiveMaximum === 'number') {
101 zodSchema = extendSchemaWithMessage(
102 zodSchema,
103 jsonSchema,
@@ -104,5 +126,17 @@ export const parseNumber = (jsonSchema: JsonSchemaObject & { type: 'number' | 'i
126 );
127 }
128
129 + if (typeof jsonSchema.multipleOf === 'number') {
130 + const errorMessage = (
131 + jsonSchema as JsonSchemaObject & { errorMessage?: Record<string, string> }
132 + ).errorMessage?.multipleOf;
133 + if (jsonSchema.multipleOf === 1) {
134 + return isInteger ? zodSchema : zodSchema.int(errorMessage);
135 + }
136 + return zodSchema.refine(value => isJsonMultipleOf(value, jsonSchema.multipleOf!), {
137 + message: errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}`,
138 + });
139 + }
140 +
141 return zodSchema;
142 };
ts/packages/json-schema-to-zod/src/parsers/parse-object-shape.ts
+13 -3
@@ -2,6 +2,11 @@ import * as z from 'zod/v3';
2
3 import { parseSchema } from './parse-schema';
4 import type { JsonSchemaObject, Refs, JsonSchema } from '../types';
5 +import {
6 + guardSchemaAt,
7 + requiresWholeSchemaValidation,
8 + withWholeSchemaValidation,
9 +} from '../whole-schema-validation';
10
11 /**
12 * Parses a JSON Schema object and returns the raw shape (property keys mapped to Zod types).
@@ -25,11 +30,16 @@ export function parseObjectShape(objectSchema: JsonSchemaObject, refs: Refs): z.
30
31 for (const key of propertyKeys) {
32 const propJsonSchema = objectSchema.properties[key];
28 -
29 - const propZodSchema = parseSchema(propJsonSchema, {
33 + const propRefs = {
34 ...refs,
35 + root: refs.root ?? objectSchema,
36 path: [...refs.path, 'properties', key],
32 - });
37 + };
38 +
39 + const parsedProperty = parseSchema(propJsonSchema, propRefs);
40 + const propZodSchema = requiresWholeSchemaValidation(propJsonSchema)
41 + ? withWholeSchemaValidation(guardSchemaAt(propJsonSchema, propRefs), parsedProperty)
42 + : parsedProperty;
43
44 const required = Array.isArray(objectSchema.required)
45 ? objectSchema.required.includes(key)
ts/packages/json-schema-to-zod/src/parsers/parse-schema.ts
+22 -5
@@ -16,8 +16,17 @@ import { parseNumber } from './parse-number';
16 import { parseObject } from './parse-object';
17 import { parseOneOf } from './parse-one-of';
18 import { parseString } from './parse-string';
19 +import {
20 + hasTypelessScalarConstraints,
21 + parseTypelessConstraints,
22 +} from './parse-typeless-constraints';
23 import type { ParserSelector, Refs, JsonSchemaObject, JsonSchema } from '../types';
24 import { its } from '../utils/its';
25 +import {
26 + guardSchemaAt,
27 + requiresPermissiveMaterialization,
28 + withWholeSchemaValidation,
29 +} from '../whole-schema-validation';
30
31 const addDescribes = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny): z.ZodTypeAny => {
32 let description = '';
@@ -88,8 +97,18 @@ const addAnnotations = (jsonSchema: JsonSchemaObject, zodSchema: z.ZodTypeAny):
97 };
98
99 const selectParser: ParserSelector = (schema, refs) => {
91 - if (its.a.nullable(schema)) {
100 + if (requiresPermissiveMaterialization(schema)) {
101 + // Widen only this node, and let it guard itself so combinators such as
102 + // `oneOf` still discriminate between branches that were widened.
103 + return withWholeSchemaValidation(guardSchemaAt(schema, refs), z.any());
104 + } else if (its.a.nullable(schema)) {
105 return parseNullable(schema, refs);
106 + } else if (its.an.enum(schema)) {
107 + // `enum`/`const` intersect the declared type, so they must win over the
108 + // object and array parsers or a literal object/array value is never checked.
109 + return parseEnum(schema, refs);
110 + } else if (its.a.const(schema)) {
111 + return parseConst(schema, refs);
112 } else if (its.an.object(schema)) {
113 return parseObject(schema, refs);
114 } else if (its.an.array(schema)) {
@@ -102,10 +121,8 @@ const selectParser: ParserSelector = (schema, refs) => {
121 return parseOneOf(schema, refs);
122 } else if (its.a.not(schema)) {
123 return parseNot(schema, refs);
105 - } else if (its.an.enum(schema)) {
106 - return parseEnum(schema); //<-- needs to come before primitives
107 - } else if (its.a.const(schema)) {
108 - return parseConst(schema);
124 + } else if (hasTypelessScalarConstraints(schema)) {
125 + return parseTypelessConstraints(schema);
126 } else if (its.a.multipleType(schema)) {
127 return parseMultipleType(schema, refs);
128 } else if (its.a.primitive(schema, 'string')) {
ts/packages/json-schema-to-zod/src/parsers/parse-string.ts
+29 -30
@@ -41,38 +41,37 @@ export const parseString = (jsonSchema: JsonSchemaObject & { type: 'string' }) =
41 zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, 'pattern', (zs, pattern, errorMsg) =>
42 zs.regex(new RegExp(pattern), errorMsg)
43 );
44 - zodSchema = extendSchemaWithMessage(
45 - zodSchema,
46 - jsonSchema,
47 - 'minLength',
48 - (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
49 - );
50 - zodSchema = extendSchemaWithMessage(
51 - zodSchema,
52 - jsonSchema,
53 - 'maxLength',
54 - (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
55 - );
44 + // JSON Schema length constraints count Unicode code points, while Zod's
45 + // built-in `.min()`/`.max()` count UTF-16 code units and overcount astral
46 + // glyphs, so both bounds are applied as code-point refinements.
47 + const errorMessages = (jsonSchema as { errorMessage?: Record<string, string> }).errorMessage;
48 + // 'min'/'max' are generic aliases for 'minLength'/'maxLength'
49 + const minLength =
50 + typeof jsonSchema.minLength === 'number'
51 + ? jsonSchema.minLength
52 + : typeof jsonSchema.min === 'number'
53 + ? jsonSchema.min
54 + : undefined;
55 + const maxLength =
56 + typeof jsonSchema.maxLength === 'number'
57 + ? jsonSchema.maxLength
58 + : typeof jsonSchema.max === 'number'
59 + ? jsonSchema.max
60 + : undefined;
61
57 - // Handle generic 'min' property as alias for 'minLength'
58 - if (typeof jsonSchema.min === 'number' && typeof jsonSchema.minLength !== 'number') {
59 - zodSchema = extendSchemaWithMessage(
60 - zodSchema,
61 - { ...jsonSchema, minLength: jsonSchema.min },
62 - 'minLength',
63 - (zs, minLength, errorMsg) => zs.min(minLength, errorMsg)
64 - );
62 + let result: z.ZodTypeAny = zodSchema;
63 + if (minLength !== undefined) {
64 + result = result.refine(value => codePointLength(value) >= minLength, {
65 + message: errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)`,
66 + });
67 }
66 -
67 - // Handle generic 'max' property as alias for 'maxLength'
68 - if (typeof jsonSchema.max === 'number' && typeof jsonSchema.maxLength !== 'number') {
69 - zodSchema = extendSchemaWithMessage(
70 - zodSchema,
71 - { ...jsonSchema, maxLength: jsonSchema.max },
72 - 'maxLength',
73 - (zs, maxLength, errorMsg) => zs.max(maxLength, errorMsg)
74 - );
68 + if (maxLength !== undefined) {
69 + result = result.refine(value => codePointLength(value) <= maxLength, {
70 + message: errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)`,
71 + });
72 }
73
77 - return zodSchema;
74 + return result;
75 };
76 +
77 +const codePointLength = (value: string): number => [...value].length;
ts/packages/json-schema-to-zod/src/parsers/parse-typeless-constraints.ts new
+46
@@ -0,0 +1,46 @@
1 +import { z } from 'zod/v3';
2 +
3 +import { parseNumber } from './parse-number';
4 +import { parseString } from './parse-string';
5 +import type { JsonSchemaObject } from '../types';
6 +
7 +const SCALAR_CONSTRAINT_KEYS = [
8 + 'minLength',
9 + 'maxLength',
10 + 'pattern',
11 + 'minimum',
12 + 'maximum',
13 + 'exclusiveMinimum',
14 + 'exclusiveMaximum',
15 + 'multipleOf',
16 +] as const;
17 +
18 +export const hasTypelessScalarConstraints = (schema: JsonSchemaObject): boolean =>
19 + schema.type === undefined && SCALAR_CONSTRAINT_KEYS.some(key => schema[key] !== undefined);
20 +
21 +/**
22 + * Draft 7 applies scalar constraints to matching instance types even when the
23 + * schema declares no `type`: `{ "minLength": 2 }` restricts strings while
24 + * leaving every non-string value untouched.
25 + */
26 +export const parseTypelessConstraints = (schema: JsonSchemaObject): z.ZodTypeAny => {
27 + const stringSchema = parseString({ ...schema, type: 'string' });
28 + const numberSchema = parseNumber({ ...schema, type: 'number' });
29 +
30 + return z.any().superRefine((value, ctx) => {
31 + const applicable =
32 + typeof value === 'string'
33 + ? stringSchema
34 + : typeof value === 'number'
35 + ? numberSchema
36 + : undefined;
37 + if (applicable === undefined) return;
38 +
39 + const result = applicable.safeParse(value);
40 + if (!result.success) {
41 + for (const issue of result.error.issues) {
42 + ctx.addIssue(issue);
43 + }
44 + }
45 + });
46 +};
ts/packages/json-schema-to-zod/src/types.ts
+2
@@ -63,4 +63,6 @@ export type JsonSchemaToZodOptions = {
63 export type Refs = JsonSchemaToZodOptions & {
64 path: Array<string | number>;
65 seen: Map<object | boolean, { n: number; r: ZodTypeAny | undefined }>;
66 + /** The document that local `$ref` pointers resolve against. */
67 + root?: JsonSchema;
68 };
ts/packages/json-schema-to-zod/src/whole-schema-validation.ts new
+238
@@ -0,0 +1,238 @@
1 +import { encodePointer, Validator } from '@cfworker/json-schema';
2 +import type { Schema as InterpreterSchema } from '@cfworker/json-schema';
3 +import { z } from 'zod/v3';
4 +
5 +import type { JsonSchema, JsonSchemaObject } from './types';
6 +
7 +const REQUIRES_WHOLE_SCHEMA_VALIDATION = new Set([
8 + '$ref',
9 + 'additionalItems',
10 + 'allOf',
11 + 'anyOf',
12 + 'contains',
13 + 'dependencies',
14 + 'else',
15 + 'if',
16 + 'maxProperties',
17 + 'minProperties',
18 + 'not',
19 + 'oneOf',
20 + 'propertyNames',
21 + 'then',
22 + 'uniqueItems',
23 +]);
24 +
25 +const TYPELESS_TYPE_SCOPED_KEYWORDS = new Set([
26 + 'properties',
27 + 'patternProperties',
28 + 'additionalProperties',
29 + 'propertyNames',
30 + 'required',
31 + 'dependencies',
32 + 'minProperties',
33 + 'maxProperties',
34 + 'items',
35 + 'additionalItems',
36 + 'contains',
37 + 'minItems',
38 + 'maxItems',
39 + 'uniqueItems',
40 +]);
41 +
42 +const SCHEMA_MAP_KEYWORDS = new Set([
43 + '$defs',
44 + 'definitions',
45 + 'dependencies',
46 + 'patternProperties',
47 + 'properties',
48 +]);
49 +
50 +const SCHEMA_ARRAY_KEYWORDS = new Set(['allOf', 'anyOf', 'oneOf']);
51 +
52 +const SCHEMA_VALUE_KEYWORDS = new Set([
53 + 'additionalItems',
54 + 'additionalProperties',
55 + 'contains',
56 + 'else',
57 + 'if',
58 + 'items',
59 + 'not',
60 + 'propertyNames',
61 + 'then',
62 +]);
63 +
64 +const isObject = (value: unknown): value is Record<string, unknown> =>
65 + typeof value === 'object' && value !== null && !Array.isArray(value);
66 +
67 +const hasRequiredDefault = (schema: JsonSchemaObject): boolean => {
68 + if (!Array.isArray(schema.required) || !isObject(schema.properties)) {
69 + return false;
70 + }
71 +
72 + return schema.required.some(name => {
73 + const property = schema.properties?.[name];
74 + return isObject(property) && property.default !== undefined;
75 + });
76 +};
77 +
78 +const hasUnparsedRequiredProperty = (schema: JsonSchemaObject): boolean => {
79 + if (!Array.isArray(schema.required)) {
80 + return false;
81 + }
82 + const declared = new Set(Object.keys(schema.properties ?? {}));
83 + return schema.required.some(name => !declared.has(name));
84 +};
85 +
86 +/**
87 + * The native parsers preserve useful Zod structure and materialize defaults,
88 + * but some JSON Schema assertions cannot be represented by their first-match
89 + * dispatch. Only those schemas receive an authoritative Draft 7 guard.
90 + */
91 +export const requiresWholeSchemaValidation = (
92 + schema: JsonSchema,
93 + seen: WeakSet<object> = new WeakSet()
94 +): boolean => {
95 + if (!isObject(schema) || seen.has(schema)) {
96 + return false;
97 + }
98 + seen.add(schema);
99 +
100 + if (
101 + Object.keys(schema).some(key => REQUIRES_WHOLE_SCHEMA_VALIDATION.has(key)) ||
102 + (schema.type === undefined &&
103 + Object.keys(schema).some(key => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key))) ||
104 + hasUnparsedRequiredProperty(schema) ||
105 + hasRequiredDefault(schema)
106 + ) {
107 + return true;
108 + }
109 +
110 + for (const [key, child] of Object.entries(schema)) {
111 + if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
112 + if (
113 + Object.values(child).some(value => requiresWholeSchemaValidation(value as JsonSchema, seen))
114 + ) {
115 + return true;
116 + }
117 + } else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
118 + if (child.some(value => requiresWholeSchemaValidation(value as JsonSchema, seen))) {
119 + return true;
120 + }
121 + } else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
122 + const values = Array.isArray(child) ? child : [child];
123 + if (values.some(value => requiresWholeSchemaValidation(value as JsonSchema, seen))) {
124 + return true;
125 + }
126 + }
127 + }
128 +
129 + return false;
130 +};
131 +
132 +/**
133 + * Some schemas are valid for JSON instance types that the native parser does
134 + * not materialize. Such a node is parsed as `z.any()` so the Draft 7 guard
135 + * that every one of these keywords also activates (see
136 + * `requiresWholeSchemaValidation`) stays the acceptance authority without
137 + * piping into a narrower Zod schema. The check is deliberately local: a
138 + * permissive descendant must not widen its enclosing parser, or sibling
139 + * defaults would stop materializing.
140 + */
141 +export const requiresPermissiveMaterialization = (schema: JsonSchema): boolean =>
142 + isObject(schema) &&
143 + ('$ref' in schema ||
144 + (schema.type === undefined &&
145 + (Object.keys(schema).some(key => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) ||
146 + ['if', 'then', 'else', 'not'].some(key => key in schema))));
147 +
148 +/**
149 + * The guard schema for a node nested at `path` inside `root`: the enclosing
150 + * document pointed at that node, so local `$ref`s resolve exactly as they do
151 + * for the document root. Draft 7 ignores the keywords next to `$ref`, which
152 + * is what lets the root's own assertions be reused as the pointer carrier.
153 + */
154 +export const guardSchemaAt = (
155 + node: JsonSchema,
156 + refs: { root?: JsonSchema; path: ReadonlyArray<string | number> }
157 +): JsonSchema =>
158 + isObject(refs.root) && refs.path.length > 0
159 + ? // `encodePointer` is the interpreter's own key encoding, so the pointer
160 + // lands on exactly the lookup entry `dereference` registered.
161 + { ...refs.root, $ref: `#/${refs.path.map(part => encodePointer(String(part))).join('/')}` }
162 + : node;
163 +
164 +/**
165 + * OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
166 + * `minimum`/`maximum`. The Draft 7 interpreter ignores the flag, so the guard
167 + * receives the numeric spelling the native number parser already honors.
168 + */
169 +const normalizeExclusiveBounds = (value: unknown, seen: WeakSet<object>): void => {
170 + if (!isObject(value) || seen.has(value)) {
171 + return;
172 + }
173 + seen.add(value);
174 +
175 + if (value.exclusiveMinimum === true && typeof value.minimum === 'number') {
176 + value.exclusiveMinimum = value.minimum;
177 + delete value.minimum;
178 + } else if (typeof value.exclusiveMinimum === 'boolean') {
179 + delete value.exclusiveMinimum;
180 + }
181 + if (value.exclusiveMaximum === true && typeof value.maximum === 'number') {
182 + value.exclusiveMaximum = value.maximum;
183 + delete value.maximum;
184 + } else if (typeof value.exclusiveMaximum === 'boolean') {
185 + delete value.exclusiveMaximum;
186 + }
187 +
188 + for (const [key, child] of Object.entries(value)) {
189 + if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
190 + Object.values(child).forEach(nested => normalizeExclusiveBounds(nested, seen));
191 + } else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
192 + child.forEach(nested => normalizeExclusiveBounds(nested, seen));
193 + } else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
194 + (Array.isArray(child) ? child : [child]).forEach(nested =>
195 + normalizeExclusiveBounds(nested, seen)
196 + );
197 + }
198 + }
199 +};
200 +
201 +export const withWholeSchemaValidation = (
202 + jsonSchema: JsonSchema,
203 + parsedSchema: z.ZodTypeAny
204 +): z.ZodTypeAny => {
205 + const interpreterSchema = structuredClone(jsonSchema);
206 + normalizeExclusiveBounds(interpreterSchema, new WeakSet());
207 + const validator = new Validator(interpreterSchema as InterpreterSchema, '7', false);
208 +
209 + // Validate the source value before defaults and other Zod transforms run.
210 + // Otherwise a missing required field can be synthesized and incorrectly
211 + // appear valid to the JSON Schema interpreter.
212 + const guardedSchema = z
213 + .any()
214 + .superRefine((value, ctx) => {
215 + let result: ReturnType<Validator['validate']>;
216 + try {
217 + result = validator.validate(value);
218 + } catch (cause) {
219 + ctx.addIssue({
220 + code: z.ZodIssueCode.custom,
221 + message: `JSON Schema validation failed: ${String(cause)}`,
222 + });
223 + return;
224 + }
225 +
226 + if (!result.valid) {
227 + ctx.addIssue({
228 + code: z.ZodIssueCode.custom,
229 + message: result.errors[0]?.error ?? 'Input does not satisfy the complete JSON Schema.',
230 + });
231 + }
232 + })
233 + .pipe(parsedSchema);
234 +
235 + return parsedSchema.description
236 + ? guardedSchema.describe(parsedSchema.description)
237 + : guardedSchema;
238 +};
ts/packages/json-schema-to-zod/test/json-to-zod.test.ts
+9 -12
@@ -593,8 +593,9 @@ describe('jsonSchemaToZod', () => {
593 // Should accept number arrays
594 expect(zodSchema.parse([1, 2, 3])).toEqual([1, 2, 3]);
595
596 - // Should accept mixed arrays (union of item types)
597 - expect(zodSchema.parse(['hello', 123])).toEqual(['hello', 123]);
596 + // Each anyOf branch constrains the entire array, so a mixed array
597 + // satisfies neither the all-string nor the all-number branch.
598 + expect(() => zodSchema.parse(['hello', 123])).toThrow();
599 });
600
601 it('should handle arrays with anyOf at top level without explicit types', () => {
@@ -1132,8 +1133,8 @@ describe('jsonSchemaToZod', () => {
1133 });
1134 });
1135
1135 - describe('Object Detection Without Explicit Type', () => {
1136 - it('should detect object schema with only properties defined', () => {
1136 + describe('Object Assertions Without Explicit Type', () => {
1137 + it('should apply properties only to object instances', () => {
1138 const schema: JsonSchema = {
1139 properties: {
1140 name: { type: 'string' },
@@ -1143,11 +1144,10 @@ describe('jsonSchemaToZod', () => {
1144 };
1145 const zodSchema = jsonSchemaToZod(schema);
1146
1146 - // Should parse as an object
1147 expect(zodSchema.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 });
1148 expect(zodSchema.parse({ name: 'Jane' })).toEqual({ name: 'Jane' });
1149 expect(() => zodSchema.parse({ age: 30 })).toThrow(); // Missing required field
1150 - expect(() => zodSchema.parse('not an object')).toThrow();
1150 + expect(zodSchema.parse('not an object')).toBe('not an object');
1151 });
1152
1153 it('should detect object schema with only additionalProperties defined', () => {
@@ -1156,14 +1156,13 @@ describe('jsonSchemaToZod', () => {
1156 };
1157 const zodSchema = jsonSchemaToZod(schema);
1158
1159 - // Should parse as an object with string additional properties
1159 expect(zodSchema.parse({})).toEqual({});
1160 expect(zodSchema.parse({ key1: 'value1', key2: 'value2' })).toEqual({
1161 key1: 'value1',
1162 key2: 'value2',
1163 });
1164 expect(() => zodSchema.parse({ key1: 123 })).toThrow(); // Wrong type
1166 - expect(() => zodSchema.parse('not an object')).toThrow();
1165 + expect(zodSchema.parse('not an object')).toBe('not an object');
1166 });
1167
1168 it('should detect object schema with only patternProperties defined', () => {
@@ -1175,14 +1174,13 @@ describe('jsonSchemaToZod', () => {
1174 };
1175 const zodSchema = jsonSchemaToZod(schema);
1176
1178 - // Should parse as an object
1177 expect(zodSchema.parse({})).toEqual({});
1178 expect(zodSchema.parse({ prefix_one: 'value', num_one: 123 })).toEqual({
1179 prefix_one: 'value',
1180 num_one: 123,
1181 });
1182 expect(() => zodSchema.parse({ prefix_one: 123 })).toThrow(); // Wrong type for pattern
1185 - expect(() => zodSchema.parse('not an object')).toThrow();
1183 + expect(zodSchema.parse('not an object')).toBe('not an object');
1184 });
1185
1186 it('should detect object schema with properties and additionalProperties but no type', () => {
@@ -1493,9 +1491,8 @@ describe('jsonSchemaToZod', () => {
1491 };
1492 const zodSchema = jsonSchemaToZod(schema);
1493
1496 - // Should be treated as an object
1494 expect(zodSchema.parse({})).toEqual({});
1498 - expect(() => zodSchema.parse('not an object')).toThrow();
1495 + expect(zodSchema.parse('not an object')).toBe('not an object');
1496 });
1497
1498 it('should handle objects with only required field but no type', () => {
ts/packages/json-schema-to-zod/test/property-semantics.test.ts new
+150
@@ -0,0 +1,150 @@
1 +/**
2 + * Property-based acceptance parity for scalar JSON Schema conversion.
3 + *
4 + * The oracle is Ajv in Draft 7 mode: for every generated scalar schema and
5 + * instance, the converted Zod schema must accept exactly what the oracle
6 + * accepts.
7 + *
8 + * The generator deliberately stays inside the semantics the converter claims
9 + * to support today; shrinking an exclusion is the way to turn a fixed
10 + * behavior into a permanent regression guard. The remaining exclusions are
11 + * deliberate divergences or oracle limits, not open bugs:
12 + *
13 + * - `multipleOf` is always an integer: the converter checks decimal
14 + * multiples through decimal scaling (see the `primitive-float-multiple-of`
15 + * corpus case) while the oracle uses raw float modulo
16 + * - draft-4 boolean `exclusiveMinimum`/`exclusiveMaximum` are never
17 + * generated: they are not part of Draft 7, so the oracle cannot express
18 + * them (the `primitive-draft4-boolean-exclusive-bounds` corpus case covers
19 + * them)
20 + */
21 +import Ajv from 'ajv';
22 +import fc from 'fast-check';
23 +import { describe, expect, it } from 'vitest';
24 +
25 +import { jsonSchemaToZod } from '../src/index';
26 +import type { JsonSchema, Serializable } from '../src/types';
27 +
28 +const SCALAR_TYPES = ['string', 'integer', 'number', 'boolean', 'null'] as const;
29 +type ScalarType = (typeof SCALAR_TYPES)[number];
30 +
31 +const PATTERN_POOL = ['^[a-z]+$', '^[A-Z]{2}$', '[0-9]', '^a.*z$', '^(?=.*[a-y])a'] as const;
32 +const scalarValue: fc.Arbitrary<Serializable> = fc.oneof(
33 + fc.constant(null),
34 + fc.boolean(),
35 + fc.integer({ min: -100, max: 100 }),
36 + fc.double({ min: -100, max: 100, noNaN: true, noDefaultInfinity: true }),
37 + fc.string({
38 + unit: fc.constantFrom(...'abcdefghijklmnopqrstuvwxyz', '\u{1D11E}'),
39 + maxLength: 6,
40 + })
41 +);
42 +
43 +type SchemaRecord = Record<string, unknown>;
44 +
45 +const scalarSchema: fc.Arbitrary<SchemaRecord> = fc
46 + .record(
47 + {
48 + types: fc.option(
49 + fc.uniqueArray(fc.constantFrom<ScalarType>(...SCALAR_TYPES), {
50 + minLength: 1,
51 + maxLength: 3,
52 + }),
53 + { nil: undefined }
54 + ),
55 + collapseSingle: fc.boolean(),
56 + literalKind: fc.constantFrom('none', 'enum', 'const', 'both'),
57 + enumValues: fc.uniqueArray(scalarValue, {
58 + minLength: 1,
59 + maxLength: 4,
60 + comparator: 'SameValue',
61 + }),
62 + constValue: scalarValue,
63 + minLength: fc.option(fc.integer({ min: 0, max: 4 }), { nil: undefined }),
64 + maxLength: fc.option(fc.integer({ min: 0, max: 6 }), { nil: undefined }),
65 + pattern: fc.option(fc.constantFrom(...PATTERN_POOL), { nil: undefined }),
66 + minimum: fc.option(fc.integer({ min: -20, max: 20 }), { nil: undefined }),
67 + maximum: fc.option(fc.integer({ min: -20, max: 20 }), { nil: undefined }),
68 + exclusiveMinimum: fc.option(fc.integer({ min: -20, max: 20 }), { nil: undefined }),
69 + exclusiveMaximum: fc.option(fc.integer({ min: -20, max: 20 }), { nil: undefined }),
70 + multipleOf: fc.option(fc.integer({ min: 1, max: 5 }), { nil: undefined }),
71 + },
72 + { noNullPrototype: true }
73 + )
74 + .map(parts => {
75 + const schema: SchemaRecord = {};
76 + const declared: ScalarType[] = parts.types ?? [];
77 +
78 + if (parts.types) {
79 + schema.type = parts.types.length === 1 && parts.collapseSingle ? parts.types[0] : parts.types;
80 + }
81 + if (parts.literalKind === 'enum' || parts.literalKind === 'both')
82 + schema.enum = parts.enumValues;
83 + if (parts.literalKind === 'const' || parts.literalKind === 'both')
84 + schema.const = parts.constValue;
85 +
86 + // Constraints attach independently of the declared type (or its absence):
87 + // Draft 7 scopes every scalar keyword to matching instance types anyway.
88 + void declared;
89 + for (const key of [
90 + 'minLength',
91 + 'maxLength',
92 + 'pattern',
93 + 'minimum',
94 + 'maximum',
95 + 'exclusiveMinimum',
96 + 'exclusiveMaximum',
97 + 'multipleOf',
98 + ] as const) {
99 + if (parts[key] !== undefined) schema[key] = parts[key];
100 + }
101 + return schema;
102 + });
103 +
104 +const schemaAndInstance: fc.Arbitrary<{ schema: SchemaRecord; value: Serializable }> =
105 + scalarSchema.chain(schema => {
106 + const interesting: Serializable[] = [];
107 + if (Array.isArray(schema.enum)) interesting.push(...(schema.enum as Serializable[]));
108 + if ('const' in schema) interesting.push(schema.const as Serializable);
109 + for (const key of ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum'] as const) {
110 + const bound = schema[key];
111 + if (typeof bound === 'number') interesting.push(bound, bound + 1, bound - 1);
112 + }
113 + const pools = [scalarValue];
114 + if (interesting.length > 0) pools.push(fc.constantFrom(...interesting));
115 + return fc.oneof(...pools).map(value => ({ schema, value }));
116 + });
117 +
118 +const ajv = new Ajv({ strict: false });
119 +
120 +describe('scalar conversion matches the Draft 7 oracle', () => {
121 + it('accepts exactly what Ajv accepts, standalone and object-wrapped', () => {
122 + fc.assert(
123 + fc.property(schemaAndInstance, ({ schema, value }) => {
124 + const objectSchema = {
125 + type: 'object',
126 + properties: { value: schema },
127 + required: ['value'],
128 + additionalProperties: false,
129 + };
130 + const instance = { value };
131 +
132 + const oracleScalar = ajv.compile(schema)(value);
133 + const zodScalar = jsonSchemaToZod(schema as JsonSchema).safeParse(value).success;
134 + expect(
135 + zodScalar,
136 + `standalone schema=${JSON.stringify(schema)} value=${JSON.stringify(value)}`
137 + ).toBe(oracleScalar);
138 +
139 + const oracleObject = ajv.compile(objectSchema)(instance);
140 + const zodObject = jsonSchemaToZod(objectSchema as JsonSchema).safeParse(instance).success;
141 + expect(
142 + zodObject,
143 + `wrapped schema=${JSON.stringify(schema)} value=${JSON.stringify(value)}`
144 + ).toBe(oracleObject);
145 + }),
146 + { numRuns: 300 }
147 + );
148 + // 300 Ajv-compiled runs sit close to vitest's 5s default on CI runners.
149 + }, 30_000);
150 +});
ts/packages/json-schema-to-zod/test/semantic-regressions.test.ts new
+330
@@ -0,0 +1,330 @@
1 +import Ajv from 'ajv';
2 +import { describe, expect, it } from 'vitest';
3 +
4 +import { z } from 'zod/v3';
5 +
6 +import { jsonSchemaToZod, jsonSchemaToZodShape } from '../src/index';
7 +import type { JsonSchema } from '../src/types';
8 +
9 +type RejectionCase = {
10 + readonly name: string;
11 + readonly schema: JsonSchema;
12 + readonly value: unknown;
13 +};
14 +
15 +type AcceptanceCase = RejectionCase;
16 +
17 +const ajv = new Ajv({ strict: false });
18 +
19 +const rejectionCases: ReadonlyArray<RejectionCase> = [
20 + {
21 + name: 'typeless scalar dispatch must not discard object assertions',
22 + schema: { minLength: 2, required: ['x'] },
23 + value: {},
24 + },
25 + {
26 + name: 'anyOf must compose with adjacent assertions',
27 + schema: {
28 + type: 'string',
29 + minLength: 2,
30 + anyOf: [{ const: 'a' }, { const: 'abc' }],
31 + },
32 + value: 'a',
33 + },
34 + {
35 + name: 'allOf must compose with adjacent assertions',
36 + schema: {
37 + type: 'string',
38 + maxLength: 1,
39 + allOf: [{ pattern: '^ab' }],
40 + },
41 + value: 'ab',
42 + },
43 + {
44 + name: 'oneOf must compose with adjacent assertions',
45 + schema: {
46 + type: 'number',
47 + minimum: 10,
48 + oneOf: [{ maximum: 5 }, { minimum: 0 }],
49 + },
50 + value: 7,
51 + },
52 + {
53 + name: 'not must compose with adjacent assertions',
54 + schema: { type: 'string', minLength: 2, not: { const: 'x' } },
55 + value: 'a',
56 + },
57 + {
58 + name: 'if and then are a complete conditional without else',
59 + schema: { if: { type: 'string' }, then: { minLength: 2 } },
60 + value: 'a',
61 + },
62 + {
63 + name: 'conditionals must compose with adjacent primitive assertions',
64 + schema: {
65 + type: 'number',
66 + if: { minimum: 0 },
67 + then: { maximum: 10 },
68 + else: { minimum: -10 },
69 + },
70 + value: 20,
71 + },
72 + {
73 + name: 'contains must be enforced for typed arrays',
74 + schema: { type: 'array', contains: { const: 1 } },
75 + value: [2],
76 + },
77 + {
78 + name: 'uniqueItems must be enforced for typed arrays',
79 + schema: { type: 'array', uniqueItems: true },
80 + value: [1, 1],
81 + },
82 + {
83 + name: 'propertyNames must be enforced for typed objects',
84 + schema: { type: 'object', propertyNames: { pattern: '^x' } },
85 + value: { bad: 1 },
86 + },
87 + {
88 + name: 'required must be enforced for property-less typed objects',
89 + schema: { type: 'object', required: ['x'] },
90 + value: {},
91 + },
92 + {
93 + name: 'required properties must be checked before defaults materialize',
94 + schema: {
95 + type: 'object',
96 + properties: { x: { type: 'string', default: 'generated' } },
97 + required: ['x'],
98 + },
99 + value: {},
100 + },
101 + {
102 + name: 'const must be enforced for typed objects',
103 + schema: { type: 'object', const: { x: 1 } },
104 + value: { x: 2 },
105 + },
106 + {
107 + name: 'enum must be enforced for typed arrays',
108 + schema: { type: 'array', enum: [[1, 2]] },
109 + value: [2],
110 + },
111 + {
112 + name: 'local references must constrain direct converter callers',
113 + schema: {
114 + $defs: { positive: { type: 'number', minimum: 1 } },
115 + $ref: '#/$defs/positive',
116 + },
117 + value: 0,
118 + },
119 +];
120 +
121 +const acceptanceCases: ReadonlyArray<AcceptanceCase> = [
122 + {
123 + name: 'typeless properties must accept non-object instances',
124 + schema: { properties: { x: { type: 'string' } } },
125 + value: 42,
126 + },
127 + {
128 + name: 'typeless required must accept non-object instances',
129 + schema: { required: ['x'] },
130 + value: 42,
131 + },
132 + {
133 + name: 'typeless items must accept non-array instances',
134 + schema: { items: { type: 'string' } },
135 + value: 42,
136 + },
137 + {
138 + name: 'typeless array bounds must accept non-array instances',
139 + schema: { minItems: 2 },
140 + value: { not: 'an array' },
141 + },
142 + {
143 + name: 'typeless propertyNames must accept non-object instances',
144 + schema: { propertyNames: { pattern: '^x' } },
145 + value: 42,
146 + },
147 + {
148 + name: 'typeless dependencies must accept non-object instances',
149 + schema: { dependencies: { a: ['b'] } },
150 + value: 42,
151 + },
152 + {
153 + name: 'typeless not can accept a different instance type',
154 + schema: { not: { type: 'string' } },
155 + value: 42,
156 + },
157 + {
158 + name: 'typeless conditionals leave nonmatching instance types untouched',
159 + schema: { if: { type: 'string' }, then: { minLength: 2 } },
160 + value: 42,
161 + },
162 + {
163 + name: 'a direct local ref accepts values admitted by its target',
164 + schema: {
165 + $defs: { positive: { type: 'number', minimum: 1 } },
166 + $ref: '#/$defs/positive',
167 + },
168 + value: 2,
169 + },
170 + {
171 + name: 'const accepts the matching typed object',
172 + schema: { type: 'object', const: { x: 1 } },
173 + value: { x: 1 },
174 + },
175 + {
176 + name: 'sibling allOf object branches accept each other declared keys',
177 + schema: {
178 + allOf: [
179 + { type: 'object', properties: { a: { type: 'string' } }, required: ['a'] },
180 + { type: 'object', properties: { b: { type: 'string' } }, required: ['b'] },
181 + ],
182 + },
183 + value: { a: 'ready', b: 'set' },
184 + },
185 + {
186 + name: 'nested typeless object assertions accept non-object property values',
187 + schema: {
188 + type: 'object',
189 + properties: { value: { properties: { x: { type: 'string' } } } },
190 + required: ['value'],
191 + },
192 + value: { value: 42 },
193 + },
194 +];
195 +
196 +describe('whole-schema semantic regressions', () => {
197 + it.each(rejectionCases)('$name', ({ schema, value }) => {
198 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must reject the fixture').toBe(false);
199 + expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(false);
200 + });
201 +
202 + it.each(acceptanceCases)('$name', ({ schema, value }) => {
203 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
204 + expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(true);
205 + });
206 +
207 + it('resolves local references from a raw shape against the enclosing document', () => {
208 + const schema: JsonSchema = {
209 + type: 'object',
210 + properties: { name: { $ref: '#/$defs/name' } },
211 + required: ['name'],
212 + $defs: { name: { type: 'string' } },
213 + };
214 + const shape = z.object(jsonSchemaToZodShape(schema));
215 +
216 + expect(shape.safeParse({ name: 'Ada' }).success).toBe(true);
217 + expect(shape.safeParse({ name: 1 }).success).toBe(false);
218 + });
219 +
220 + it('keeps sibling defaults when a nested reference widens only its own property', () => {
221 + const schema: JsonSchema = {
222 + type: 'object',
223 + properties: {
224 + name: { $ref: '#/$defs/n' },
225 + enabled: { type: 'boolean', default: true },
226 + },
227 + $defs: { n: { type: 'string' } },
228 + };
229 + const parsed = jsonSchemaToZod(schema);
230 +
231 + expect(parsed.parse({ name: 'Ada' })).toEqual({ name: 'Ada', enabled: true });
232 + expect(parsed.safeParse({ name: 1 }).success).toBe(false);
233 + });
234 +
235 + it('keeps allOf branch defaults and stays strict over the union of declared keys', () => {
236 + const schema: JsonSchema = {
237 + allOf: [
238 + { type: 'object', properties: { a: { type: 'string' } }, required: ['a'] },
239 + { type: 'object', properties: { b: { type: 'string', default: 'set' } } },
240 + ],
241 + };
242 + const parsed = jsonSchemaToZod(schema);
243 +
244 + expect(parsed.parse({ a: 'ready' })).toEqual({ a: 'ready', b: 'set' });
245 + expect(parsed.safeParse({ a: 'ready', c: 1 }).success).toBe(false);
246 + });
247 +
248 + it('normalizes Draft 4 exclusive bounds before the whole-schema guard runs', () => {
249 + const schema = {
250 + type: 'object',
251 + propertyNames: { pattern: '^[a-z]+$' },
252 + properties: { v: { type: 'number', minimum: 0, exclusiveMinimum: true } },
253 + } as unknown as JsonSchema;
254 + const parsed = jsonSchemaToZod(schema);
255 +
256 + expect(parsed.safeParse({ v: 0.5 }).success).toBe(true);
257 + expect(parsed.safeParse({ v: 0 }).success).toBe(false);
258 + });
259 +
260 + it('keeps Draft 4 exclusive flags and adjacent Draft 7 keywords active together', () => {
261 + const schema = {
262 + type: 'array',
263 + minimum: 0,
264 + exclusiveMinimum: true,
265 + contains: { const: 1 },
266 + } as unknown as JsonSchema;
267 +
268 + // Ajv intentionally cannot serve as the oracle for the Draft 4 boolean
269 + // bound. This value isolates `contains`, which remains a Draft 7 assertion
270 + // even when an OpenAPI 3.0 exporter emits the older bound spelling nearby.
271 + expect(jsonSchemaToZod(schema).safeParse([2]).success).toBe(false);
272 + });
273 +
274 + it('accepts every valid prefix of a closed Draft 7 tuple', () => {
275 + const schema: JsonSchema = {
276 + type: 'array',
277 + items: [{ type: 'string' }, { type: 'integer' }],
278 + additionalItems: false,
279 + };
280 + const parsed = jsonSchemaToZod(schema);
281 +
282 + for (const value of [[], ['ready'], ['ready', 2]]) {
283 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
284 + expect(parsed.safeParse(value).success).toBe(true);
285 + }
286 + for (const value of [
287 + [2, 'ready'],
288 + ['ready', 2, true],
289 + ]) {
290 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must reject the fixture').toBe(false);
291 + expect(parsed.safeParse(value).success).toBe(false);
292 + }
293 + });
294 +
295 + it('allows unconstrained trailing values when additionalItems is omitted', () => {
296 + const schema: JsonSchema = {
297 + type: 'array',
298 + items: [{ type: 'string' }, { type: 'integer' }],
299 + };
300 + const value = ['ready', 2, { extra: true }];
301 +
302 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must accept the fixture').toBe(true);
303 + expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(true);
304 + });
305 +
306 + it('validates trailing tuple values against schema-valued additionalItems', () => {
307 + const schema: JsonSchema = {
308 + type: 'array',
309 + items: [{ type: 'string' }],
310 + additionalItems: { type: 'integer' },
311 + };
312 + const parsed = jsonSchemaToZod(schema);
313 +
314 + expect(parsed.safeParse(['ready', 1, 2]).success).toBe(true);
315 + expect(parsed.safeParse(['ready', 'wrong']).success).toBe(false);
316 + });
317 +
318 + it('does not round tiny nonzero numbers into integer multiples', () => {
319 + const schema: JsonSchema = { type: 'number', multipleOf: 3 };
320 + const value = 2 ** -1022;
321 +
322 + expect(ajv.compile(schema)(value), 'Draft 7 oracle must reject the fixture').toBe(false);
323 + expect(jsonSchemaToZod(schema).safeParse(value).success).toBe(false);
324 + });
325 +
326 + it('compares decimal multiples by their JSON number spelling', () => {
327 + const schema: JsonSchema = { type: 'number', multipleOf: 0.1 };
328 + expect(jsonSchemaToZod(schema).safeParse(0.3).success).toBe(true);
329 + });
330 +});
uv.lock
+103
@@ -733,6 +733,7 @@ dev = [
733 { name = "click" },
734 { name = "composio" },
735 { name = "fastapi" },
736 + { name = "hypothesis" },
737 { name = "langchain-openai" },
738 { name = "nox" },
739 { name = "pytest" },
@@ -763,6 +764,7 @@ dev = [
764 { name = "click", specifier = ">=8.4.2" },
765 { name = "composio", editable = "python" },
766 { name = "fastapi", specifier = ">=0.140.0" },
767 + { name = "hypothesis", specifier = ">=6.140.3" },
768 { name = "langchain-openai", specifier = "==1.6.0" },
769 { name = "nox", specifier = ">=2026.7.11" },
770 { name = "pytest", specifier = ">=9.1.1" },
@@ -1885,6 +1887,98 @@ wheels = [
1887 { url = "https://files.pythonhosted.org/packages/b0/aa/0b7365d30fed43e7a3449aba1fe20a0a7174d9cf13e282af4e69ac825441/humanize-4.16.0-py3-none-any.whl", hash = "sha256:353eb2f34c09d098b2880eee8bef21832eae6d174f48c5762fff7e5fcb74d01d", size = 137209, upload-time = "2026-06-30T16:17:28.36Z" },
1888 ]
1889
1890 +[[package]]
1891 +name = "hypothesis"
1892 +version = "6.167.1"
1893 +source = { registry = "https://pypi.org/simple" }
1894 +dependencies = [
1895 + { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
1896 + { name = "sortedcontainers" },
1897 +]
1898 +sdist = { url = "https://files.pythonhosted.org/packages/c2/c9/8cee74c1390b2932406faaab76980f18946f258fa5a8afca17189b3bc655/hypothesis-6.167.1.tar.gz", hash = "sha256:62eefcb4d2791423626e9901c3027a6e0c5ffda2ac0b44b3c7e797ab9d2d5a4c", size = 505849, upload-time = "2026-08-30T19:53:09.05Z" }
1899 +wheels = [
1900 + { url = "https://files.pythonhosted.org/packages/53/4d/3592ca336deafbd3e9b0f47dc4c727aa32d30e765ef6370da8ecd590d388/hypothesis-6.167.1-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d28118fd70e4e15ff9c308a98b312b544b6145ae45aaa3b566328c1fdee8058f", size = 785476, upload-time = "2026-08-30T19:51:02.154Z" },
1901 + { url = "https://files.pythonhosted.org/packages/18/bf/e33c431148994cbcb3332c6df94b833ecfb4aa6a8e51ea4b83da55ddd581/hypothesis-6.167.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:e517be7f82a0a917758cc489a88b826b5371f56381fd94b4a8a09ce82d8de406", size = 781033, upload-time = "2026-08-30T19:51:27.314Z" },
1902 + { url = "https://files.pythonhosted.org/packages/94/a3/e0de9a82c7e790a1def0801076e0ef43110f98e95ed54a3554877d0cb66d/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:26f8cec74c4fad7aeb0852cb34c2134b16db05d878ad3946a53337dace7016f4", size = 1117814, upload-time = "2026-08-30T19:53:04.109Z" },
1903 + { url = "https://files.pythonhosted.org/packages/71/a4/8dd6bdc909324d1c39da1c86d65f75512ae049c159952af4cfe8feb5f8d4/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fd202d02d129197a5e771f8a11c7d30559927284c23ec3a8bd4f37a7955964d1", size = 1141639, upload-time = "2026-08-30T19:51:50.399Z" },
1904 + { url = "https://files.pythonhosted.org/packages/fa/bd/c13ed6145c360d0770415efd7d5a7e63c29905aeef52ab88004fe7e7f924/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b1e393ab01b71f683ba2a783785871cc6b81a6e41017780c64a5bc0b99759ae", size = 1143334, upload-time = "2026-08-30T19:50:38.045Z" },
1905 + { url = "https://files.pythonhosted.org/packages/c0/a8/060d79ed8504b54ced9ad16f33d674b1b98a9debe9733c02709d7dd5c71c/hypothesis-6.167.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8c385c7741893404306f9e5559ab3835432e85e7c153e25f854c502c410bbcbb", size = 1163345, upload-time = "2026-08-30T19:53:06.583Z" },
1906 + { url = "https://files.pythonhosted.org/packages/cb/f7/6e68e2b705f729a6f7b4f41030022b1a5264c5434d3bcd917233d6801c6a/hypothesis-6.167.1-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:94920ca1fae70c26b0bd3fabbeef9437ffc17a39fe85696fb9a86187d92f6dba", size = 1123029, upload-time = "2026-08-30T19:52:03.134Z" },
1907 + { url = "https://files.pythonhosted.org/packages/a5/c0/d274fe37ed5ecd5ad8ed555edc1f5e2abc8e1c3be3d5404b7edd5cc353a8/hypothesis-6.167.1-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b8d90ded2ffdc7e56b5e571993f384b52fade0a7b424e614f999cc2491789970", size = 1154003, upload-time = "2026-08-30T19:50:55.053Z" },
1908 + { url = "https://files.pythonhosted.org/packages/b4/2f/2b5bb386f43fc965eb86fd69fcb2bd62c08cb6d7c6708a40dc39b3b97440/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:40cd5de7dd252942a08480639f5850594b1aca4a463e8a7f15e1fb6c2c3760c1", size = 1293729, upload-time = "2026-08-30T19:52:59.481Z" },
1909 + { url = "https://files.pythonhosted.org/packages/ac/32/22436b072d79011fe81abb933edcd2476057c7b971588c5f3caf07519a88/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:b9c33f921ddc7fea93660eca408b25fe755516e22ec7ab21cb9951031f1cd608", size = 1419248, upload-time = "2026-08-30T19:50:52.903Z" },
1910 + { url = "https://files.pythonhosted.org/packages/9e/3e/abf39faaff0f78112112a82316a5c9fe472574480c1ecee526734775b812/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:495989cf0a5ee03f7f9598ee9efeaabf15fd861ec52b5a9d6435849453e17e5d", size = 1274903, upload-time = "2026-08-30T19:52:27.25Z" },
1911 + { url = "https://files.pythonhosted.org/packages/29/83/69b89ed5692ba3aad117facfb9ce099633a22c35acc3d64829b72253ec8c/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:bc73c46ce8ff93b0eb220f2b75adcbd9fcc9112078a74d3522d2532ad8069bad", size = 1294185, upload-time = "2026-08-30T19:50:35.038Z" },
1912 + { url = "https://files.pythonhosted.org/packages/2b/1e/55dfcbe45c72df0a5c5b86a6b7c9365121acab69c2cc060bd55336a48c8f/hypothesis-6.167.1-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:36e83e1d7e97aaacbf6cd778e14a841344f848a674b20dfe4fe997546a6a2151", size = 1330013, upload-time = "2026-08-30T19:52:54.841Z" },
1913 + { url = "https://files.pythonhosted.org/packages/3b/a6/0a36cead4ccff58bedb5d1aa2f894f7a580c317424b4fa788c6b22232b2d/hypothesis-6.167.1-cp310-abi3-win32.whl", hash = "sha256:fb4d87454d2459c2ccb541a4c61c92ce13058b91305ed3304695a409a1d886e4", size = 671942, upload-time = "2026-08-30T19:51:32.732Z" },
1914 + { url = "https://files.pythonhosted.org/packages/ec/5b/360285ed42109f5ef48d98ca9ffcf71d1477130c0ff1f1a8d535c8507259/hypothesis-6.167.1-cp310-abi3-win_amd64.whl", hash = "sha256:5e35f98b427bf438a946203426b485dd5b62485f3d5a69a0e0862870a545e518", size = 678637, upload-time = "2026-08-30T19:50:33.573Z" },
1915 + { url = "https://files.pythonhosted.org/packages/79/2d/cc084c1a8bfa296048ec0461f0fa11731abe0097f5c2310c8d39d94c8dc4/hypothesis-6.167.1-cp310-abi3-win_arm64.whl", hash = "sha256:dd6a0808a2eb8b5b1ac06bca4244eee18ed2c0e7b105599e1662203d164317b5", size = 676657, upload-time = "2026-08-30T19:51:34.494Z" },
1916 + { url = "https://files.pythonhosted.org/packages/4a/8e/e0f470823bc301a97a8e6156806f6322f5ab99a2f40b6c604261966b3393/hypothesis-6.167.1-cp310-cp310-macosx_10_12_x86_64.whl", hash = "sha256:64cf8b7ac9a0cc80dad8884f81a2e50f0b79956694927d40e21e0cfa48830b8a", size = 786180, upload-time = "2026-08-30T19:52:09.714Z" },
1917 + { url = "https://files.pythonhosted.org/packages/6c/4d/6e9e430ded5e226f245cd7e55923c7675311fa2115bc4262b5802edfcbb2/hypothesis-6.167.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:69b92f037080cefb949c5f9683873abac12283e0dc77201df089369c1ef67e4c", size = 781901, upload-time = "2026-08-30T19:50:42.641Z" },
1918 + { url = "https://files.pythonhosted.org/packages/bd/aa/8df2711daf3ace849045482492b7f178fb55b79201f332477f6eef590b46/hypothesis-6.167.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:19b334180260de636a0b3017dd96d63709da0c4182c9cb28f52dd6cda78dc933", size = 1118135, upload-time = "2026-08-30T19:51:54.599Z" },
1919 + { url = "https://files.pythonhosted.org/packages/8c/4f/6040b58ffc511013394ba027191dd7e2886c5ae39e0b7872ab15503803fe/hypothesis-6.167.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:769d0242531067e6daf16b6c9894fd9584139884de887023328e3c5658993597", size = 1163947, upload-time = "2026-08-30T19:50:45.908Z" },
1920 + { url = "https://files.pythonhosted.org/packages/ca/66/24aedbae1b56e71308d0aef4415e37c6bb22068c77e95337cdf9d74cd8b1/hypothesis-6.167.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:22b6c3def5446016148523b74ef9da4948bec5ef05865d56c99ba187f4092663", size = 1294290, upload-time = "2026-08-30T19:52:45.383Z" },
1921 + { url = "https://files.pythonhosted.org/packages/e5/e8/a063e3ab97851f4425918f0fcd407d0f426184c26b09f3bda7369e3d38d7/hypothesis-6.167.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cbbb6bc17a5a04120a5bfd830335b8b301a22d21d2262804be330c235031b4c5", size = 1330694, upload-time = "2026-08-30T19:51:21.626Z" },
1922 + { url = "https://files.pythonhosted.org/packages/bd/f6/6ebb84d532c0d5b36b3bab7b477a167685b2210a0246c7101557bfa4751c/hypothesis-6.167.1-cp310-cp310-win_amd64.whl", hash = "sha256:cdc7e20161f21f14c2d7a057054521db0a8c4bbb647d2e50c90c84f28e4621a0", size = 678586, upload-time = "2026-08-30T19:52:31.618Z" },
1923 + { url = "https://files.pythonhosted.org/packages/ff/14/2445b7b1a0c8db61c6812b74606ed7a4f41e3ea0e0c103313e25995b82d5/hypothesis-6.167.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:613bf10e6e490daaa88eb4bf06fb3aacf6572b887e2f9fa5d0bac1be96a18c00", size = 785945, upload-time = "2026-08-30T19:51:19.221Z" },
1924 + { url = "https://files.pythonhosted.org/packages/8b/f6/67926d308a9ab19bb7dfb5118832fa74b508f94871fadbb3370629decbfc/hypothesis-6.167.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f715d912560dd4df3daab4c1fd98c01132eea7ab292f5b9e1d28fc419fe63348", size = 781726, upload-time = "2026-08-30T19:52:57.179Z" },
1925 + { url = "https://files.pythonhosted.org/packages/33/de/22ac0e272530b36ad840170bf661ff89df8648052bb6a37dba520b312f1f/hypothesis-6.167.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8cdd2fc0232b47910e9621f8c1b5732381438055b03fcc69180e1ef3659b7e70", size = 1117929, upload-time = "2026-08-30T19:51:58.828Z" },
1926 + { url = "https://files.pythonhosted.org/packages/4d/1f/b72b51bac9a7d330bcdda01dc0ab1abe76e1c29ff522effd2d1be4e23702/hypothesis-6.167.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:163e4cebd4b2380ff92f5d36bd04697e82b13973794440694da768521e1e2eab", size = 1163855, upload-time = "2026-08-30T19:52:33.689Z" },
1927 + { url = "https://files.pythonhosted.org/packages/a7/b4/02424328951f0244f7dd3f620775ed22d39dc234e92759f9d2980150252b/hypothesis-6.167.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:2de4e67289f86e358732eb16b345f9d1f987c33e44b10d4ffa3ccd715dea9316", size = 1294177, upload-time = "2026-08-30T19:50:44.418Z" },
1928 + { url = "https://files.pythonhosted.org/packages/d8/09/2262d6b362c81066ad451fda48633b2d3ea6cf2d0d673ee6554ad8f86c58/hypothesis-6.167.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:fcfd20792f62d65729f850ea50328c1f8b09874d5960b122715b9e6784a7a547", size = 1330267, upload-time = "2026-08-30T19:51:23.5Z" },
1929 + { url = "https://files.pythonhosted.org/packages/70/5d/19e8c02eebfe89592dfd12372032e8868ad40e6d40b38e5ecc4935ce194f/hypothesis-6.167.1-cp311-cp311-win_amd64.whl", hash = "sha256:ebb841d21156039d7da0a41fa9de4ccf468510a4e4d8144f4fe2b3f31239ef3b", size = 678401, upload-time = "2026-08-30T19:51:44.77Z" },
1930 + { url = "https://files.pythonhosted.org/packages/72/82/07987292cfb59c73ce6574e2912c015f678d5aa4d8c0712b78ae4415a535/hypothesis-6.167.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1937ae4e23f7dde6d4202d3d08c2633bcd535a091bdf866b8799abaabcb1e6f0", size = 787050, upload-time = "2026-08-30T19:51:10.782Z" },
1931 + { url = "https://files.pythonhosted.org/packages/c7/e9/0d37051bec44ec433d87da03c9a7fe389b1b58210790c1f166af249bf941/hypothesis-6.167.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1434bbd25d05aaf75c4e6829b4cad8e9931b690f840d92b747b2e6e5af575922", size = 778617, upload-time = "2026-08-30T19:50:31.939Z" },
1932 + { url = "https://files.pythonhosted.org/packages/13/2a/60c18a493215c22c9cfcb4574b381497bd1971eed9fb5f9831b26e73cffb/hypothesis-6.167.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:af3c09428e553b1dd2f9abbc4738377c58bf6d74cb0b8b528cc1dde3a9cdfbe8", size = 1116743, upload-time = "2026-08-30T19:50:49.293Z" },
1933 + { url = "https://files.pythonhosted.org/packages/12/1f/b6796f11d6502e0b1764aec99f2792ca60382b6a45e26bbe163dc5757980/hypothesis-6.167.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:04f807b85d425a7005e8a24498ca832bf5590f0d306737471d94c842569cecef", size = 1162718, upload-time = "2026-08-30T19:52:47.544Z" },
1934 + { url = "https://files.pythonhosted.org/packages/a8/6c/e3cf35474b799e299fa08980b6756f500d730781686916ab65f87cbc0613/hypothesis-6.167.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:803c6a98ff66cee4caf03245bfd00e442a907264031b994a3a650dc6e4786f51", size = 1292417, upload-time = "2026-08-30T19:50:56.822Z" },
1935 + { url = "https://files.pythonhosted.org/packages/9a/4c/875803c80c373a1628f8eb62f215ad23ce7b50ed61f884d6be0838ebea4a/hypothesis-6.167.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:21a7122ddf072906083e3704fe3961ecbc49d7d30a9b51bcd525d977b3afe65e", size = 1329035, upload-time = "2026-08-30T19:51:46.659Z" },
1936 + { url = "https://files.pythonhosted.org/packages/90/a8/a8daed3796623884471dc0ee8ed63917b1e2b979b4074bcea19a964fcd71/hypothesis-6.167.1-cp312-cp312-win_amd64.whl", hash = "sha256:a2837c60d782eb0b8a910c541264675b9d11486e186af8c82a5e2920b5fe4fe8", size = 675966, upload-time = "2026-08-30T19:51:56.58Z" },
1937 + { url = "https://files.pythonhosted.org/packages/4b/44/dca7b211804f60c789aced2792b1e7803ccd8b70b79041cbb92788df5d19/hypothesis-6.167.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:6478d19a7887731cc2afaa1ec15f62811c9ceb6fd18e5b7563e0a18399a9528f", size = 786947, upload-time = "2026-08-30T19:51:29.165Z" },
1938 + { url = "https://files.pythonhosted.org/packages/b9/6a/3cffa138492c9e3d5f98f4ff8b467273dc87af6ca3c18084272d106bde10/hypothesis-6.167.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8f13167a4b81c93e7e051d1f02790814a6495fb79cacf3fb89560a796a2f7d00", size = 778584, upload-time = "2026-08-30T19:52:25.091Z" },
1939 + { url = "https://files.pythonhosted.org/packages/7a/7d/e8039791aaca3b21557bc520a71cdb88751892f66fd1a0a459b59872e463/hypothesis-6.167.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ef7dd225f7df7d74d1c5a905592cd8b4cd348e6be639b189a43def8b0b5dd79", size = 1116749, upload-time = "2026-08-30T19:52:38.178Z" },
1940 + { url = "https://files.pythonhosted.org/packages/ee/b8/f9b8d93bd6178870f0daa868ca99915f6d9df1f99dc7291e9ce2743a6dc5/hypothesis-6.167.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7d7585429f2263d3ceeb3474bae3871024630a7a598e71eeb4b0dcf03e291623", size = 1162599, upload-time = "2026-08-30T19:52:11.72Z" },
1941 + { url = "https://files.pythonhosted.org/packages/a1/0d/53d419094e6f8a7e7377c09de15ac23f842ab698ff07241f7b73e19bd559/hypothesis-6.167.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:fb9194f450417cf35f66b6c72737cc6b8f21f20567ba4d39822c64f0d1075784", size = 1292230, upload-time = "2026-08-30T19:52:49.732Z" },
1942 + { url = "https://files.pythonhosted.org/packages/5c/df/cf4c482323ae4f06b5326b5bdd89cf17d8232fdb3186c9913e0b19a5fa58/hypothesis-6.167.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:c63a0d292a5dde3c0fe999892e76d8375a003ca40c0c00d763f3360f91be5b96", size = 1328899, upload-time = "2026-08-30T19:51:05.366Z" },
1943 + { url = "https://files.pythonhosted.org/packages/49/05/780c4b0396491d294fda69a541cb1dedb37fb9eb2e3a696e85fe19064c40/hypothesis-6.167.1-cp313-cp313-win_amd64.whl", hash = "sha256:ff07f98a0b230632bb2836b5dad3e94d85c114ae155a316afd251c58760958ae", size = 675927, upload-time = "2026-08-30T19:50:58.472Z" },
1944 + { url = "https://files.pythonhosted.org/packages/6a/f1/1e602f090dcb7e38655f1f7909482742891332275fc01f241e255cdfa514/hypothesis-6.167.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:fcfc2a78fc1025644f889a74684b3201f4652ce8e6694c2a01af0f100d0348cf", size = 787054, upload-time = "2026-08-30T19:50:40.88Z" },
1945 + { url = "https://files.pythonhosted.org/packages/52/57/cfa930719c7af5a33627abba826a3fa2efa61a5f23e38d4111eace5dfe53/hypothesis-6.167.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:769bdd9aa0af08c063327730ab6dc18b7a23837a2912f2aeaab3912f11a7e3ad", size = 778721, upload-time = "2026-08-30T19:50:36.503Z" },
1946 + { url = "https://files.pythonhosted.org/packages/01/37/4c4bc3d319eac85bfe17515c9786bf49e57181ca8757886110d2cfb13d10/hypothesis-6.167.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d75d44bdead6679b6ee9a7c90d10207db865ca0c77c5212103b5ff421379f99e", size = 1116972, upload-time = "2026-08-30T19:51:52.472Z" },
1947 + { url = "https://files.pythonhosted.org/packages/33/45/0d61ceef2739e7b96ea1faa0f3d5aa5917c8156797993bf3acbadfcd7f0a/hypothesis-6.167.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:742be00d7bb53d10634e6435e5b98f51fcdbe7ed377d473ab7387d9499c87169", size = 1162776, upload-time = "2026-08-30T19:51:09.084Z" },
1948 + { url = "https://files.pythonhosted.org/packages/4a/cf/756666ce2262e90fd61fec41a95548cceab94b0669381d8f0387cd89af93/hypothesis-6.167.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b6fcdc8d03b37a902262be13112d113bb4ac87edf3b08afb47f3d1210deb038a", size = 1292748, upload-time = "2026-08-30T19:51:17.22Z" },
1949 + { url = "https://files.pythonhosted.org/packages/e8/b4/87eb3c695d6c37fb44f4d49f9faa2033af496e24965658942a1706e22620/hypothesis-6.167.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:e56e7841514276c308c2bb4d033cf01860d0fc8c76e2b79ce748a9f123eaf83b", size = 1329101, upload-time = "2026-08-30T19:51:36.313Z" },
1950 + { url = "https://files.pythonhosted.org/packages/a7/3b/87faa4a86533eaaa19037741fb9cdde8647f7ffdf8fd4279828ac9d81f8b/hypothesis-6.167.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:bbf4f0cad201d0b8e821e82ad828b2aec99ce6d9967779eecb2cad4d4a93debd", size = 618079, upload-time = "2026-08-30T19:52:43.226Z" },
1951 + { url = "https://files.pythonhosted.org/packages/e0/46/96b7ac9605887447d267b4b3a9ecf61c6caaabf39eef667173b0cc9222b3/hypothesis-6.167.1-cp314-cp314-win_amd64.whl", hash = "sha256:3e04f6001299708b6fd4512267b189c0b029ef1e34500deb4e4c9639023598d7", size = 675812, upload-time = "2026-08-30T19:52:52.298Z" },
1952 + { url = "https://files.pythonhosted.org/packages/6e/f6/0337a91c50ce4be323c3d6aa852fcf08199ffbb1072da09fbe6d602f4dfe/hypothesis-6.167.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:47c99256df28555ecc2aed0e22ca17cd61c63c8c44207a07b4e402cc49661fae", size = 785525, upload-time = "2026-08-30T19:51:03.637Z" },
1953 + { url = "https://files.pythonhosted.org/packages/5a/08/9bb52de855169d31888c7033ee2f94b94138fde021c1af9dbc7ba5e83cd5/hypothesis-6.167.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5d6614e88fd267bbd870e3ec02f8a5387897d2d573626a02f5ac06d81533afa6", size = 777142, upload-time = "2026-08-30T19:52:18.472Z" },
1954 + { url = "https://files.pythonhosted.org/packages/85/79/f1a7e088e13a641357abb9b43d75c116c2a0902711b1a25a203864b96c9b/hypothesis-6.167.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:27829aa89fe2e47c5c8d13b3ce31e0f53a01a98f76a4f99cfa3369ab35362f33", size = 1115311, upload-time = "2026-08-30T19:52:40.975Z" },
1955 + { url = "https://files.pythonhosted.org/packages/e0/38/e28b1fc20bd3d67d43cf1aab7a15daa2a24ec01d17a153e82fcf38c882f3/hypothesis-6.167.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e936777d92ae27393b4a941839bbb43c1f339b5a0e394c7f3730454cdf091b3a", size = 1161238, upload-time = "2026-08-30T19:52:20.501Z" },
1956 + { url = "https://files.pythonhosted.org/packages/5a/de/9b4fc7992166299e0fc5c13c8766919ae57d0fb9eed5319b7a3bad4f2f17/hypothesis-6.167.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:971ce0d8a367a37c4690b83a2e7f6ef832fa3543357eb6da0da27ba078e5088a", size = 1290974, upload-time = "2026-08-30T19:51:15.673Z" },
1957 + { url = "https://files.pythonhosted.org/packages/cc/79/ca086eea02588212ab796ee4bd7fe6ed514e10d1a99967e478691608e8d9/hypothesis-6.167.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:af84ce2416be2a65bc0ea18e64d2dbb9796b7692593b5b2064d60ea1d52ec1e2", size = 1327969, upload-time = "2026-08-30T19:52:35.846Z" },
1958 + { url = "https://files.pythonhosted.org/packages/26/79/1875380fa30e8411553e76b3e9695aca0845f9f265523f20f879bdea2b82/hypothesis-6.167.1-cp314-cp314t-win_amd64.whl", hash = "sha256:3b596efec5bd714588e3bb269544d993c5258c979f3a26f51fadf62c215d0e68", size = 675735, upload-time = "2026-08-30T19:52:22.821Z" },
1959 + { url = "https://files.pythonhosted.org/packages/b0/45/59abecd75e52b9dfb5b3eb991276f54954c44917a1c83d148cfb3580bd39/hypothesis-6.167.1-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:c25c556d51d55d94988dc0a2c716d471ff19cf9632cd33f5e6db2914d802428a", size = 785097, upload-time = "2026-08-30T19:51:12.528Z" },
1960 + { url = "https://files.pythonhosted.org/packages/01/7c/e6d978dc9564ba70352da60c00f55f6ad7d66d99ecbf336a228978206cb4/hypothesis-6.167.1-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:b57e950f9d5c93ca335bc612e8fa8fb49abb187c3fc9d5e7d9966d52eb27d747", size = 776798, upload-time = "2026-08-30T19:50:47.247Z" },
1961 + { url = "https://files.pythonhosted.org/packages/d1/a4/f8ecedcf96790aab69d750afe3fcbf503229d0bb4e0c32be655385a4fc8c/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0807ae8d399162827fc1c396ab4c697a41921c2a2baacfada439771e9dc2b867", size = 1115116, upload-time = "2026-08-30T19:52:16.029Z" },
1962 + { url = "https://files.pythonhosted.org/packages/7e/97/8bca7c262ac4fcb1ee684c04e4ba75f26541d3a30417e3743d19912d257e/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:546fef39c7aadba74bf3e592585694a71340d1775e9b3274bb3f94106dbde4b7", size = 1137812, upload-time = "2026-08-30T19:51:25.507Z" },
1963 + { url = "https://files.pythonhosted.org/packages/d6/07/9cb4a7fc2aa2b2ad063b446c378f0d7acfa5303e84afd1b1374ba23fd6f3/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a17a5618b6a5b84f17c8acb3bce37122647cf7a3e48b660a39d68a773bd627dd", size = 1140384, upload-time = "2026-08-30T19:52:05.264Z" },
1964 + { url = "https://files.pythonhosted.org/packages/1c/18/813bf7efa18f11ce938a0da22a7518a54db46d4a181ebf4cb0a8061c263f/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0ff5ad833480c1e34ae902cb52fc00802b08ac6c87bd22d7e5f04fd925869608", size = 1160569, upload-time = "2026-08-30T19:51:40.099Z" },
1965 + { url = "https://files.pythonhosted.org/packages/52/1d/6658d9294ed33bb17da4acf06fe63b010b205ea1861f6921c38060793255/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:630eb37df80b5bc4ec6f391b13caaecc06942ff5da3aadebacf85f53bbc55757", size = 1120605, upload-time = "2026-08-30T19:53:01.848Z" },
1966 + { url = "https://files.pythonhosted.org/packages/a6/81/a75821c0e879223a2635b8eded84ae874cb6c711b23e9930668008d0b13f/hypothesis-6.167.1-cp315-abi3.abi3t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bc4e65f7c43b187f7a40964706b5ded1073e0c1839e9fb5e041d7ed973bb65fe", size = 1149479, upload-time = "2026-08-30T19:51:30.972Z" },
1967 + { url = "https://files.pythonhosted.org/packages/4e/f2/c8c3faf4ec796d6dbf36b84662806696434aef38616e5a65b46188c04262/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:e849f518cbc4e76ab15f2f1473c60dd3103da8d32399187325ceb84309105976", size = 1290423, upload-time = "2026-08-30T19:50:51.114Z" },
1968 + { url = "https://files.pythonhosted.org/packages/a4/e3/e0903abe7e8634cedb5414931452e82daacdd3b8b46d6348bbefcaa45f2a/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:5c5a26d4d3dca0c84e01bde41df4cabaa5a373c7393f9eef372d19fe93b07ccd", size = 1415749, upload-time = "2026-08-30T19:51:48.456Z" },
1969 + { url = "https://files.pythonhosted.org/packages/a6/9b/03f09c1ecac1dfb0f4cd7fcc6dc50d9c6ea8067b295a728e242650bafe32/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:4819adbc5911648f6bfaeb574f276add184b4b49f54731dbde46fd71256bb157", size = 1272086, upload-time = "2026-08-30T19:52:29.368Z" },
1970 + { url = "https://files.pythonhosted.org/packages/7c/7c/7a63bfc0bfbaf000f71352c4faac72ff611376330a2ce2e9a1bf4668848a/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:3ad7206de9c398c8da5745b69b5ba2ef45100082eeb174656490bc4f262b112c", size = 1291553, upload-time = "2026-08-30T19:52:07.545Z" },
1971 + { url = "https://files.pythonhosted.org/packages/e8/5c/8065bdab53bc81743ca68fc76ca53fc7531a5b3f01c0de4ba40467955d6a/hypothesis-6.167.1-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:96d5e8017a9508f06c8a61a6130cb0d0b4810847ed5c76923cb5cfb9952b31af", size = 1327734, upload-time = "2026-08-30T19:51:42.306Z" },
1972 + { url = "https://files.pythonhosted.org/packages/0d/a0/5c15d480aea3a8e6e5c17c7cb1170171707ac643ffd319473bc194743ad8/hypothesis-6.167.1-cp315-abi3.abi3t-win32.whl", hash = "sha256:a4e4de36a397cba49d949d89cbc26135977c15f9d797caa95317962ceb5b5674", size = 669115, upload-time = "2026-08-30T19:51:14.192Z" },
1973 + { url = "https://files.pythonhosted.org/packages/1b/36/4cf494bc96384189fedb7d3f272580315f2284a9f8a7f6a59796612eb76d/hypothesis-6.167.1-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:f6fe9c40ab14def363d9e7ab22863fa31652bd5e08f8495b34ff7bd0062b3f8d", size = 675438, upload-time = "2026-08-30T19:51:06.881Z" },
1974 + { url = "https://files.pythonhosted.org/packages/b0/7f/db1a37e5f45be32c0e64f9ed1268eba56aeedcb2ef20d195fa60c6610347/hypothesis-6.167.1-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:627ce3bd166799a6c0ddcf1351049be5b9a772d5bce436216d42b41a935f42c0", size = 673123, upload-time = "2026-08-30T19:52:13.991Z" },
1975 + { url = "https://files.pythonhosted.org/packages/53/bc/a77ee57eb8fb13f2b5bdfb4a1ea3f32713c50420f0208e84fbe590fad1ad/hypothesis-6.167.1-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:436027c9a00eb11a2ca3d608147ca2d0d623b4f02878c56a50fc3f3f58c2b41b", size = 786862, upload-time = "2026-08-30T19:51:38.287Z" },
1976 + { url = "https://files.pythonhosted.org/packages/f8/3f/cc9c9120fad719e683914b9204b38f1a30721bc06344f465fc36427cc45e/hypothesis-6.167.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:35e90c121b1518d7428a45e6b0d5c6d06e0ed9eaa567f1106e1f09dae006d6da", size = 782711, upload-time = "2026-08-30T19:50:28.733Z" },
1977 + { url = "https://files.pythonhosted.org/packages/98/a6/a48824ba4ad1257904bde4654099851febf0b4c3f018c8174b33d4ba0308/hypothesis-6.167.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c903b4f1c8531736fc7e8e537f47ef509756b731a32a5e5e7014e5291343acb", size = 1118685, upload-time = "2026-08-30T19:52:01.045Z" },
1978 + { url = "https://files.pythonhosted.org/packages/b4/f3/c6bcfb38c4b4cd22494902f5368b5815425f03eeb5159741c7d910a69af5/hypothesis-6.167.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:27ca252991fdbe2ff5c611a1cc4d972d4e009eb45292c7802faa2190f995dc50", size = 1165389, upload-time = "2026-08-30T19:50:39.44Z" },
1979 + { url = "https://files.pythonhosted.org/packages/3b/f6/d1d19d115a4c0aa35c87b9e5d570b0a7c9f42f816087849cf29c58664426/hypothesis-6.167.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:6c91f6f2f15b8bc6e474b824f931247c39711231e7b1b2f68277726e0ae1c728", size = 679392, upload-time = "2026-08-30T19:51:00.264Z" },
1980 +]
1981 +
1982 [[package]]
1983 name = "id"
1984 version = "1.6.1"
@@ -5162,6 +5256,15 @@ wheels = [
5256 { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" },
5257 ]
5258
5259 +[[package]]
5260 +name = "sortedcontainers"
5261 +version = "2.4.0"
5262 +source = { registry = "https://pypi.org/simple" }
5263 +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" }
5264 +wheels = [
5265 + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" },
5266 +]
5267 +
5268 [[package]]
5269 name = "sse-starlette"
5270 version = "3.4.6"