@devries-cameron20 / composio-1 / commits / 401021deb
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.

refactor(core): flatten dereferenceJsonSchema and extract helpers

Three reviewers (simplicity, kieran-typescript, pattern-recognition) all flagged the same shapes in `dereferenceJsonSchema`. This is a pure refactor — behavior preserved, all 854 core + 43 mastra tests still pass. Changes: - `resolvePointer` drops from 4-deep to 1-deep nesting. Extract `stepInto` (single-segment dispatch) and `failResolution` (single error throw site). The pointer-walk loop becomes a `reduce` one-liner. Three near-identical throw statements collapse to one helper. The dead `canonical` field on the return shape is removed; callers only ever used `target`. - `walk` extracts `cloneChildren` to dedupe the three identical "Object.entries → walk children → Object.fromEntries" blocks. The external-`$ref` branch and the no-`$ref` branch now share the same default clone path. Sibling-merge becomes a single `{ ...resolved, ...cloneChildren(siblings) }` spread. - `path: string[]` (which carried `@ref:${ref}` cycle markers conflated with property-name segments — the segments were never read by any error message) is replaced by `Set<string>` of canonical refs. Pure cycle detection, no double-duty, no fragile string-tagging hack. - `void _omit` lint-suppression replaced with `delete siblings.$ref` on a shallow copy. - `INTERNAL_REF_PREFIX = '#'` (one-char constant used once) inlined as `ref.startsWith('#')`. `Object.freeze` removed from `CYCLE_BREAK_SENTINEL` since it is always spread before use; `as const` keeps the readonly type. - `walk` is now a `function` declaration (hoisted within the closure) so the earlier-declared `cloneChildren` arrow can reference it. Comment added to explain why.

jkomyno committed Apr 30, 2026 at 01:51 UTC 401021deb8a9add0aa4a9d694731bfa28ee633d3
1 file changed +69 -87
ts/packages/core/src/utils/jsonSchema.ts
+69 -87
@@ -4,51 +4,41 @@ import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
4
5 const MAX_REF_CHAIN_DEPTH = 100;
6 const MAX_NODE_DEPTH = 512;
7 -const CYCLE_BREAK_SENTINEL = Object.freeze({ type: 'object', additionalProperties: true });
8 -const INTERNAL_REF_PREFIX = '#';
7 +const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
8
9 const decodePointerSegment = (segment: string): string =>
10 segment.replace(/~1/g, '/').replace(/~0/g, '~');
11
13 -const resolvePointer = (
14 - root: Record<string, unknown>,
15 - pointer: string
16 -): { target: unknown; canonical: string } => {
17 - if (pointer === '#' || pointer === '') {
18 - return { target: root, canonical: '#' };
12 +const failResolution = (pointer: string, segment: string): never => {
13 + throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
14 + meta: { ref: pointer, failedAt: segment },
15 + });
16 +};
17 +
18 +const stepInto = (cursor: unknown, segment: string, pointer: string): unknown => {
19 + if (cursor === null || typeof cursor !== 'object') failResolution(pointer, segment);
20 + if (Array.isArray(cursor)) {
21 + const i = Number(segment);
22 + if (!Number.isInteger(i) || i < 0 || i >= cursor.length) failResolution(pointer, segment);
23 + return cursor[i];
24 }
25 + const obj = cursor as Record<string, unknown>;
26 + if (!Object.prototype.hasOwnProperty.call(obj, segment)) failResolution(pointer, segment);
27 + return obj[segment];
28 +};
29 +
30 +const resolvePointer = (root: Record<string, unknown>, pointer: string): unknown => {
31 + if (pointer === '#' || pointer === '') return root;
32 if (!pointer.startsWith('#/')) {
33 throw new JsonSchemaRefResolutionError(`Unsupported $ref pointer: ${pointer}`, {
34 meta: { ref: pointer },
35 });
36 }
25 - const segments = pointer.slice(2).split('/').map(decodePointerSegment);
26 - let cursor: unknown = root;
27 - for (const segment of segments) {
28 - if (cursor === null || typeof cursor !== 'object') {
29 - throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
30 - meta: { ref: pointer, failedAt: segment },
31 - });
32 - }
33 - if (Array.isArray(cursor)) {
34 - const index = Number(segment);
35 - if (!Number.isInteger(index) || index < 0 || index >= cursor.length) {
36 - throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
37 - meta: { ref: pointer, failedAt: segment },
38 - });
39 - }
40 - cursor = cursor[index];
41 - } else {
42 - const obj = cursor as Record<string, unknown>;
43 - if (!Object.prototype.hasOwnProperty.call(obj, segment)) {
44 - throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
45 - meta: { ref: pointer, failedAt: segment },
46 - });
47 - }
48 - cursor = obj[segment];
49 - }
50 - }
51 - return { target: cursor, canonical: pointer };
37 + return pointer
38 + .slice(2)
39 + .split('/')
40 + .map(decodePointerSegment)
41 + .reduce<unknown>((cursor, seg) => stepInto(cursor, seg, pointer), root);
42 };
43
44 const isPlainObject = (value: unknown): value is Record<string, unknown> =>
@@ -105,7 +95,24 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
95 const root = schema as Record<string, unknown>;
96 const visiting = new WeakSet<object>();
97
108 - const walk = (node: unknown, path: string[], depth: number, nodeDepth: number): unknown => {
98 + const cloneChildren = (
99 + obj: Record<string, unknown>,
100 + visitedRefs: ReadonlySet<string>,
101 + chainDepth: number,
102 + nodeDepth: number
103 + ): Record<string, unknown> =>
104 + Object.fromEntries(
105 + Object.entries(obj).map(([k, v]) => [k, walk(v, visitedRefs, chainDepth, nodeDepth + 1)])
106 + );
107 +
108 + // Function declaration so `cloneChildren` can reference `walk` despite being
109 + // declared earlier (function declarations are hoisted within the closure).
110 + function walk(
111 + node: unknown,
112 + visitedRefs: ReadonlySet<string>,
113 + chainDepth: number,
114 + nodeDepth: number
115 + ): unknown {
116 if (nodeDepth >= MAX_NODE_DEPTH) {
117 throw new JsonSchemaRefResolutionError(
118 `JSON Schema node depth exceeded cap (${MAX_NODE_DEPTH})`
@@ -115,9 +122,7 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
122 if (visiting.has(node)) return { ...CYCLE_BREAK_SENTINEL };
123 visiting.add(node);
124 try {
118 - return node.map((item, index) =>
119 - walk(item, [...path, String(index)], depth, nodeDepth + 1)
120 - );
125 + return node.map(item => walk(item, visitedRefs, chainDepth, nodeDepth + 1));
126 } finally {
127 visiting.delete(node);
128 }
@@ -126,62 +131,39 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
131 if (visiting.has(node)) return { ...CYCLE_BREAK_SENTINEL };
132 visiting.add(node);
133 try {
129 - if (typeof node.$ref === 'string') {
130 - const ref = node.$ref;
131 - // External refs are out of scope; leave them alone.
132 - if (!ref.startsWith(INTERNAL_REF_PREFIX)) {
133 - const cloned: Record<string, unknown> = {};
134 - for (const [key, value] of Object.entries(node)) {
135 - cloned[key] = walk(value, [...path, key], depth, nodeDepth + 1);
136 - }
137 - return cloned;
138 - }
139 -
140 - if (depth >= MAX_REF_CHAIN_DEPTH) {
141 - throw new JsonSchemaRefResolutionError(
142 - `JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`,
143 - { meta: { ref } }
144 - );
145 - }
146 -
147 - // Cycle detection: if `ref` already appears in the current path, this
148 - // resolution would re-enter itself. Break the cycle.
149 - if (path.includes(`@ref:${ref}`)) {
150 - return { ...CYCLE_BREAK_SENTINEL };
151 - }
152 -
153 - const { target } = resolvePointer(root, ref);
154 - const resolved = walk(target, [...path, `@ref:${ref}`], depth + 1, nodeDepth + 1);
134 + const ref = typeof node.$ref === 'string' ? node.$ref : null;
135 + // External refs and non-$ref nodes both pass through the same clone path.
136 + if (ref === null || !ref.startsWith('#')) {
137 + return cloneChildren(node, visitedRefs, chainDepth, nodeDepth);
138 + }
139
156 - // Shallow-merge sibling keywords (Draft 2020-12 semantics: siblings win
157 - // on collision). Draft 7 ignores siblings entirely, but the Composio
158 - // tool surface admits both drafts so we honor siblings for safety.
159 - const { $ref: _omit, ...siblings } = node;
160 - void _omit;
161 - if (Object.keys(siblings).length === 0) {
162 - return resolved;
163 - }
164 - if (!isPlainObject(resolved)) {
165 - return resolved;
166 - }
167 - const merged: Record<string, unknown> = { ...resolved };
168 - for (const [key, value] of Object.entries(siblings)) {
169 - merged[key] = walk(value, [...path, key], depth, nodeDepth + 1);
170 - }
171 - return merged;
140 + if (chainDepth >= MAX_REF_CHAIN_DEPTH) {
141 + throw new JsonSchemaRefResolutionError(
142 + `JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`,
143 + { meta: { ref } }
144 + );
145 }
146 + if (visitedRefs.has(ref)) return { ...CYCLE_BREAK_SENTINEL };
147 +
148 + const target = resolvePointer(root, ref);
149 + const nextRefs = new Set(visitedRefs).add(ref);
150 + const resolved = walk(target, nextRefs, chainDepth + 1, nodeDepth + 1);
151
174 - const cloned: Record<string, unknown> = {};
175 - for (const [key, value] of Object.entries(node)) {
176 - cloned[key] = walk(value, [...path, key], depth, nodeDepth + 1);
152 + // Shallow-merge sibling keywords (Draft 2020-12 semantics: siblings win
153 + // on collision). Draft 7 ignores siblings entirely, but the Composio
154 + // tool surface admits both drafts so we honor siblings for safety.
155 + const siblings: Record<string, unknown> = { ...node };
156 + delete siblings.$ref;
157 + if (Object.keys(siblings).length === 0 || !isPlainObject(resolved)) {
158 + return resolved;
159 }
178 - return cloned;
160 + return { ...resolved, ...cloneChildren(siblings, visitedRefs, chainDepth, nodeDepth) };
161 } finally {
162 visiting.delete(node);
163 }
182 - };
164 + }
165
184 - const out = walk(root, [], 0, 0);
166 + const out = walk(root, new Set(), 0, 0);
167 if (isPlainObject(out)) {
168 delete out.$defs;
169 delete out.definitions;