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

next
ts 106 lines 4 KB
Raw
1 // Fumadocs keeps local `$ref`s in bundled OpenAPI documents and resolves them
2 // lazily in its UI. This module creates the concrete schema tree needed by
3 // server-side renderers that read fields directly.
4
5 const dereferencedDocuments = new WeakMap<object, object>();
6
7 /**
8 * Returns a non-mutating copy of `spec` with local JSON Pointers inlined.
9 *
10 * External references remain unchanged. Cached output objects preserve
11 * identity for recursive schemas and let alias chains terminate safely.
12 * Repeated calls with the same immutable input object reuse that copy.
13 */
14 export function dereferenceDocument<T extends object>(spec: T): T {
15 const cachedDocument = dereferencedDocuments.get(spec);
16 if (cachedDocument) return cachedDocument as T;
17
18 const cache = new Map<string, unknown>();
19
20 function resolvePointer(ref: string): unknown {
21 // JSON Pointer per RFC 6901: '~1' encodes '/', '~0' encodes '~'.
22 const parts = ref
23 .slice(2)
24 .split('/')
25 .map(part => part.replace(/~1/g, '/').replace(/~0/g, '~'));
26
27 let current: unknown = spec;
28 for (const part of parts) {
29 if (current === null || typeof current !== 'object') return undefined;
30 current = (current as Record<string, unknown>)[part];
31 }
32 return current;
33 }
34
35 function resolveRef(ref: string): unknown {
36 if (cache.has(ref)) return cache.get(ref);
37
38 const target = resolvePointer(ref);
39 if (target === null || typeof target !== 'object') {
40 cache.set(ref, target);
41 return target;
42 }
43
44 // Seed the cache before walking so self-referential schemas terminate.
45 const out: Record<string, unknown> | unknown[] = Array.isArray(target) ? [] : {};
46 cache.set(ref, out);
47
48 if (Array.isArray(target)) {
49 for (const item of target) (out as unknown[]).push(walk(item));
50 return out;
51 }
52
53 const entries = Object.entries(target as Record<string, unknown>);
54 const aliased = (target as Record<string, unknown>).$ref;
55
56 // A component can itself be a Reference Object (an alias chain such as
57 // `Alias: { $ref: Real }`). Walking its entries alone would copy the `$ref`
58 // string through untouched, so follow it and fold the target's fields in
59 // first; sibling keywords below then override them. A cyclic alias chain
60 // terminates here because the seeded cache entry is returned as-is.
61 if (typeof aliased === 'string' && aliased.startsWith('#/')) {
62 const resolved = resolveRef(aliased);
63 if (resolved !== null && typeof resolved === 'object' && !Array.isArray(resolved)) {
64 Object.assign(out as Record<string, unknown>, resolved);
65 }
66 }
67
68 for (const [key, value] of entries) {
69 if (key === '$ref' && typeof aliased === 'string' && aliased.startsWith('#/')) continue;
70 (out as Record<string, unknown>)[key] = walk(value);
71 }
72 return out;
73 }
74
75 function walk(node: unknown): unknown {
76 if (Array.isArray(node)) return node.map(walk);
77 if (node === null || typeof node !== 'object') return node;
78
79 const obj = node as Record<string, unknown>;
80 const ref = obj.$ref;
81
82 if (typeof ref === 'string') {
83 // Leave external references alone - nothing local can resolve them.
84 if (!ref.startsWith('#/')) return node;
85
86 const resolved = resolveRef(ref);
87 const siblings = Object.entries(obj).filter(([key]) => key !== '$ref');
88 if (siblings.length === 0) return resolved;
89 if (resolved === null || typeof resolved !== 'object') return node;
90
91 // Sibling keywords (description, deprecated, ...) override the target.
92 // Spread into a fresh object so the shared cached value is never mutated.
93 const merged: Record<string, unknown> = { ...(resolved as Record<string, unknown>) };
94 for (const [key, value] of siblings) merged[key] = walk(value);
95 return merged;
96 }
97
98 const out: Record<string, unknown> = {};
99 for (const [key, value] of Object.entries(obj)) out[key] = walk(value);
100 return out;
101 }
102
103 const dereferenced = walk(spec) as T;
104 dereferencedDocuments.set(spec, dereferenced);
105 return dereferenced;
106 }