( schema: JsonSchemaType, rootSchema: JsonSchemaType, visitedRefs: Set<string> = new Set(), )
| 163 | * @returns The resolved schema without $ref |
| 164 | */ |
| 165 | export function resolveRef( |
| 166 | schema: JsonSchemaType, |
| 167 | rootSchema: JsonSchemaType, |
| 168 | visitedRefs: Set<string> = new Set(), |
| 169 | ): JsonSchemaType { |
| 170 | if (!schema) return schema; |
| 171 | |
| 172 | if (!("$ref" in schema) || !schema.$ref) { |
| 173 | // Recursively resolve $ref in anyOf (and other nested structures) |
| 174 | if (schema.anyOf && Array.isArray(schema.anyOf)) { |
| 175 | const resolvedAnyOf = schema.anyOf.map((item) => { |
| 176 | if (typeof item === "object" && item !== null) { |
| 177 | return resolveRef(item, rootSchema, visitedRefs); |
| 178 | } |
| 179 | return item; |
| 180 | }); |
| 181 | return { |
| 182 | ...schema, |
| 183 | anyOf: resolvedAnyOf, |
| 184 | }; |
| 185 | } |
| 186 | return schema; |
| 187 | } |
| 188 | |
| 189 | const ref = schema.$ref; |
| 190 | |
| 191 | // Handle all #/ formats (#/properties/, #/$defs/, etc.) |
| 192 | if (ref.startsWith("#/")) { |
| 193 | // Check for circular reference |
| 194 | if (visitedRefs.has(ref)) { |
| 195 | console.warn(`Circular reference detected: ${ref}`); |
| 196 | return schema; |
| 197 | } |
| 198 | |
| 199 | // Add current ref to visited set |
| 200 | visitedRefs.add(ref); |
| 201 | |
| 202 | const path = ref.substring(2).split("/"); |
| 203 | let current: unknown = rootSchema; |
| 204 | |
| 205 | for (const segment of path) { |
| 206 | if ( |
| 207 | current && |
| 208 | typeof current === "object" && |
| 209 | current !== null && |
| 210 | segment in current |
| 211 | ) { |
| 212 | current = (current as Record<string, unknown>)[segment]; |
| 213 | } else { |
| 214 | // If reference cannot be resolved, return the original schema |
| 215 | visitedRefs.delete(ref); // Clean up on failure |
| 216 | console.warn(`Could not resolve $ref: ${ref}`); |
| 217 | return schema; |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | const resolved = current as JsonSchemaType; |
| 222 |
no outgoing calls
no test coverage detected