1
import { z } from 'zod/v3';
2
-import { JsonSchemaToZodError } from '../errors';
2
+import { JsonSchemaRefResolutionError, JsonSchemaToZodError } from '../errors';
3
import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
4
5
+const MAX_REF_CHAIN_DEPTH = 100;
6
+const CYCLE_BREAK_SENTINEL = Object.freeze({ type: 'object', additionalProperties: true });
7
+const INTERNAL_REF_PREFIX = '#';
8
+
9
+const decodePointerSegment = (segment: string): string =>
10
+ segment.replace(/~1/g, '/').replace(/~0/g, '~');
11
+
12
+const resolvePointer = (
13
+ root: Record<string, unknown>,
14
+ pointer: string
15
+): { target: unknown; canonical: string } => {
16
+ if (pointer === '#' || pointer === '') {
17
+ return { target: root, canonical: '#' };
18
+ }
19
+ if (!pointer.startsWith('#/')) {
20
+ throw new JsonSchemaRefResolutionError(`Unsupported $ref pointer: ${pointer}`, {
21
+ meta: { ref: pointer },
22
+ });
23
+ }
24
+ const segments = pointer.slice(2).split('/').map(decodePointerSegment);
25
+ let cursor: unknown = root;
26
+ for (const segment of segments) {
27
+ if (cursor === null || typeof cursor !== 'object') {
28
+ throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
29
+ meta: { ref: pointer, failedAt: segment },
30
+ });
31
+ }
32
+ if (Array.isArray(cursor)) {
33
+ const index = Number(segment);
34
+ if (!Number.isInteger(index) || index < 0 || index >= cursor.length) {
35
+ throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
36
+ meta: { ref: pointer, failedAt: segment },
37
+ });
38
+ }
39
+ cursor = cursor[index];
40
+ } else {
41
+ const obj = cursor as Record<string, unknown>;
42
+ if (!Object.prototype.hasOwnProperty.call(obj, segment)) {
43
+ throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
44
+ meta: { ref: pointer, failedAt: segment },
45
+ });
46
+ }
47
+ cursor = obj[segment];
48
+ }
49
+ }
50
+ return { target: cursor, canonical: pointer };
51
+};
52
+
53
+const isPlainObject = (value: unknown): value is Record<string, unknown> =>
54
+ value !== null && typeof value === 'object' && !Array.isArray(value);
55
+
56
+/**
57
+ * Inlines internal JSON Schema `$ref` pointers (`#/$defs/...` and the
58
+ * legacy `#/definitions/...`) so the returned schema can be safely handed
59
+ * to consumers — like AJV in `@mastra/schema-compat` — that don't tolerate
60
+ * unresolved references.
61
+ *
62
+ * The traversal is reflective (no allow-list of JSON Schema keywords), so
63
+ * future applicators (`unevaluatedProperties`, `dependentSchemas`, …) are
64
+ * covered automatically. Sibling keywords next to `$ref` are shallow-merged
65
+ * per Draft 2020-12 semantics — the sibling wins on collision so a caller's
66
+ * `description` or `default` overrides the target's. Recursive `$ref`
67
+ * chains are broken with `{ type: 'object', additionalProperties: true }`,
68
+ * matching the upstream Mastra recommendation in
69
+ * {@link https://github.com/mastra-ai/mastra/issues/15341 mastra-ai/mastra#15341}.
70
+ *
71
+ * The input schema is not mutated: every node is deep-cloned. `$defs` and
72
+ * `definitions` are stripped from the returned root once everything
73
+ * reachable is inlined — AJV strict-mode otherwise complains about unused
74
+ * definitions.
75
+ *
76
+ * External `$ref` pointers (`http://`, `https://`, `file://`, …) are left
77
+ * untouched: the caller may forward them to a consumer that resolves them
78
+ * natively.
79
+ *
80
+ * @param schema - The JSON Schema to dereference. May be any plain object.
81
+ * @returns A new schema with internal `$ref` pointers inlined.
82
+ *
83
+ * @throws {JsonSchemaRefResolutionError} When an internal pointer is
84
+ * malformed, points at a missing target, or chains past the depth cap.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * dereferenceJsonSchema({
89
+ * type: 'object',
90
+ * properties: { user: { $ref: '#/$defs/User' } },
91
+ * $defs: { User: { type: 'object', properties: { id: { type: 'string' } } } },
92
+ * });
93
+ * // {
94
+ * // type: 'object',
95
+ * // properties: {
96
+ * // user: { type: 'object', properties: { id: { type: 'string' } } },
97
+ * // },
98
+ * // }
99
+ * ```
100
+ */
101
+export function dereferenceJsonSchema<T = unknown>(schema: T): T {
102
+ if (!isPlainObject(schema)) return schema;
103
+
104
+ const root = schema as Record<string, unknown>;
105
+
106
+ const walk = (node: unknown, path: string[], depth: number): unknown => {
107
+ if (Array.isArray(node)) {
108
+ return node.map((item, index) => walk(item, [...path, String(index)], depth));
109
+ }
110
+ if (!isPlainObject(node)) return node;
111
+
112
+ if (typeof node.$ref === 'string') {
113
+ const ref = node.$ref;
114
+ // External refs are out of scope; leave them alone.
115
+ if (!ref.startsWith(INTERNAL_REF_PREFIX)) {
116
+ const cloned: Record<string, unknown> = {};
117
+ for (const [key, value] of Object.entries(node)) {
118
+ cloned[key] = walk(value, [...path, key], depth);
119
+ }
120
+ return cloned;
121
+ }
122
+
123
+ if (depth >= MAX_REF_CHAIN_DEPTH) {
124
+ throw new JsonSchemaRefResolutionError(
125
+ `JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`,
126
+ { meta: { ref } }
127
+ );
128
+ }
129
+
130
+ // Cycle detection: if `ref` already appears in the current path, this
131
+ // resolution would re-enter itself. Break the cycle.
132
+ if (path.includes(`@ref:${ref}`)) {
133
+ return { ...CYCLE_BREAK_SENTINEL };
134
+ }
135
+
136
+ const { target } = resolvePointer(root, ref);
137
+ const resolved = walk(target, [...path, `@ref:${ref}`], depth + 1);
138
+
139
+ // Shallow-merge sibling keywords (Draft 2020-12 semantics: siblings win
140
+ // on collision). Draft 7 ignores siblings entirely, but the Composio
141
+ // tool surface admits both drafts so we honor siblings for safety.
142
+ const { $ref: _omit, ...siblings } = node;
143
+ void _omit;
144
+ if (Object.keys(siblings).length === 0) {
145
+ return resolved;
146
+ }
147
+ if (!isPlainObject(resolved)) {
148
+ return resolved;
149
+ }
150
+ const merged: Record<string, unknown> = { ...resolved };
151
+ for (const [key, value] of Object.entries(siblings)) {
152
+ merged[key] = walk(value, [...path, key], depth);
153
+ }
154
+ return merged;
155
+ }
156
+
157
+ const cloned: Record<string, unknown> = {};
158
+ for (const [key, value] of Object.entries(node)) {
159
+ cloned[key] = walk(value, [...path, key], depth);
160
+ }
161
+ return cloned;
162
+ };
163
+
164
+ const out = walk(root, [], 0);
165
+ if (isPlainObject(out)) {
166
+ delete out.$defs;
167
+ delete out.definitions;
168
+ }
169
+ return out as T;
170
+}
171
+
172
/**
173
* Removes all non-required properties from the schema
174
*