@amritk/resolve-refs 0.2.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -4
- package/dist/is-private-host.js +7 -1
- package/dist/reference.d.ts +42 -0
- package/dist/reference.js +80 -0
- package/dist/resolve-refs-from-file.d.ts +3 -1
- package/dist/resolve-refs-from-file.js +358 -134
- package/dist/resolve-refs.d.ts +7 -3
- package/dist/resolve-refs.js +147 -40
- package/dist/resource-registry.d.ts +100 -0
- package/dist/resource-registry.js +186 -0
- package/dist/types.d.ts +34 -0
- package/package.json +1 -1
|
@@ -1,17 +1,24 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
import { dirname, resolve as resolvePath } from 'node:path';
|
|
3
|
-
import { getByPointer, pointerToPath } from './get-by-pointer.js';
|
|
4
3
|
import { isPrivateHost } from './is-private-host.js';
|
|
4
|
+
import { readReference, resolveFragment } from './reference.js';
|
|
5
|
+
import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE, } from './resource-registry.js';
|
|
5
6
|
import { assignKey } from './safe-assign.js';
|
|
6
7
|
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
7
|
-
// means a cycle, so
|
|
8
|
+
// means a cycle, so the reference is kept (rewritten to a root-document ref,
|
|
9
|
+
// hoisting the target into `$defs` when it lives in another file) instead of
|
|
10
|
+
// recursing forever.
|
|
8
11
|
const CYCLE = Symbol('cycle');
|
|
12
|
+
/** See {@link ANNOTATION_ONLY_SIBLINGS} in resolve-refs.ts — same rule here. */
|
|
13
|
+
const ANNOTATION_ONLY_SIBLINGS = new Set(['summary', 'description']);
|
|
9
14
|
// --- Document location helpers ---------------------------------------------
|
|
10
15
|
//
|
|
11
16
|
// A "location" is the absolute identity of a document: either an absolute file
|
|
12
17
|
// path or an absolute http(s) URL. Refs are resolved relative to the location
|
|
13
18
|
// of the document they appear in, so a relative ref inside a remote document
|
|
14
19
|
// resolves to another remote URL, and one inside a local file to another path.
|
|
20
|
+
// A document's `$id` never changes which file/URL a ref loads from — it only
|
|
21
|
+
// scopes *in-document* resolution (see resource-registry.ts).
|
|
15
22
|
const isRemote = (location) => /^https?:\/\//i.test(location);
|
|
16
23
|
/** Resolves the location of `ref` (its file/URL part) relative to `base`. */
|
|
17
24
|
const joinLocation = (base, ref) => {
|
|
@@ -21,12 +28,12 @@ const joinLocation = (base, ref) => {
|
|
|
21
28
|
return new URL(ref, base).href;
|
|
22
29
|
return resolvePath(dirname(base), ref);
|
|
23
30
|
};
|
|
24
|
-
/** Splits a `$ref` into its document part and
|
|
31
|
+
/** Splits a `$ref` into its document part and its fragment (pointer or anchor name). */
|
|
25
32
|
const splitRef = (ref) => {
|
|
26
33
|
const hashIdx = ref.indexOf('#');
|
|
27
34
|
return {
|
|
28
35
|
filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
|
|
29
|
-
|
|
36
|
+
fragment: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
|
|
30
37
|
};
|
|
31
38
|
};
|
|
32
39
|
// --- Remote document cache -------------------------------------------------
|
|
@@ -35,7 +42,8 @@ const splitRef = (ref) => {
|
|
|
35
42
|
// process ("the session"). Local files are intentionally NOT cached across
|
|
36
43
|
// resolve passes — they can change on disk during a long-lived session (e.g.
|
|
37
44
|
// an editor/LSP), so each pass re-reads them. Remote documents are assumed
|
|
38
|
-
// stable for the session; call `clearRemoteCache()` to drop them
|
|
45
|
+
// stable for the session; call `clearRemoteCache()` to drop them, or pass
|
|
46
|
+
// `cache: false` to bypass the session cache for a single call.
|
|
39
47
|
const remoteCache = new Map();
|
|
40
48
|
// In-flight remote loads, keyed by location. Two resolve passes that start at
|
|
41
49
|
// the same time and reach the same URL share a single fetch instead of racing
|
|
@@ -53,14 +61,14 @@ const FETCH_TIMEOUT_MS = 30_000;
|
|
|
53
61
|
/** Refuse to buffer a remote document larger than this (bytes) to bound memory. */
|
|
54
62
|
const MAX_REMOTE_BYTES = 16 * 1024 * 1024;
|
|
55
63
|
/**
|
|
56
|
-
* Reads a response body, refusing to buffer more than
|
|
57
|
-
*
|
|
64
|
+
* Reads a response body, refusing to buffer more than `maxBytes`. A
|
|
65
|
+
* `Content-Length` over the limit is rejected up front; a missing/lying header
|
|
58
66
|
* is caught while streaming so a chunked response can't exhaust memory either.
|
|
59
67
|
*/
|
|
60
|
-
const readCapped = async (response) => {
|
|
68
|
+
const readCapped = async (response, maxBytes) => {
|
|
61
69
|
const declared = Number(response.headers.get('content-length'));
|
|
62
|
-
if (Number.isFinite(declared) && declared >
|
|
63
|
-
throw new Error(`remote document exceeds ${
|
|
70
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
71
|
+
throw new Error(`remote document exceeds ${maxBytes} bytes`);
|
|
64
72
|
}
|
|
65
73
|
const body = response.body;
|
|
66
74
|
if (!body)
|
|
@@ -70,29 +78,44 @@ const readCapped = async (response) => {
|
|
|
70
78
|
let total = 0;
|
|
71
79
|
for await (const chunk of body) {
|
|
72
80
|
total += chunk.byteLength;
|
|
73
|
-
if (total >
|
|
74
|
-
throw new Error(`remote document exceeds ${
|
|
81
|
+
if (total > maxBytes)
|
|
82
|
+
throw new Error(`remote document exceeds ${maxBytes} bytes`);
|
|
75
83
|
text += decoder.decode(chunk, { stream: true });
|
|
76
84
|
}
|
|
77
85
|
return text + decoder.decode();
|
|
78
86
|
};
|
|
87
|
+
/** The caller-supplied headers for `url`, if any. */
|
|
88
|
+
const headersFor = (url, options) => {
|
|
89
|
+
if (options.headers === undefined)
|
|
90
|
+
return undefined;
|
|
91
|
+
return typeof options.headers === 'function' ? options.headers(url) : options.headers;
|
|
92
|
+
};
|
|
79
93
|
/**
|
|
80
94
|
* Fetches and parses a remote document, following redirects manually so the
|
|
81
95
|
* SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
|
|
82
96
|
* which would let an allow-listed public URL bounce to a private/loopback
|
|
83
97
|
* address (e.g. the `169.254.169.254` metadata endpoint) — so we set
|
|
84
98
|
* `redirect: 'manual'` and re-run {@link denialReason} on each `Location`.
|
|
99
|
+
* Caller-supplied headers are only sent on hops that share the original URL's
|
|
100
|
+
* origin, so a cross-origin redirect can't exfiltrate credentials.
|
|
85
101
|
*/
|
|
86
102
|
const fetchRemote = async (location, options) => {
|
|
103
|
+
const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
|
|
104
|
+
const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
|
|
105
|
+
const maxBytes = options.maxBytes ?? MAX_REMOTE_BYTES;
|
|
106
|
+
const doFetch = options.fetch ?? fetch;
|
|
107
|
+
const origin = new URL(location).origin;
|
|
87
108
|
let current = location;
|
|
88
|
-
for (let hop = 0; hop <=
|
|
109
|
+
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
89
110
|
const reason = denialReason(current, options);
|
|
90
111
|
if (reason !== null)
|
|
91
112
|
throw new Error(`refusing to follow redirect (${reason}): ${current}`);
|
|
92
|
-
const
|
|
113
|
+
const headers = new URL(current).origin === origin ? headersFor(location, options) : undefined;
|
|
114
|
+
const response = await doFetch(current, {
|
|
93
115
|
redirect: 'manual',
|
|
94
116
|
// Cap the wait for a response so a stalling host can't hang resolution forever.
|
|
95
|
-
signal: AbortSignal.timeout(
|
|
117
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
118
|
+
...(headers !== undefined ? { headers } : {}),
|
|
96
119
|
});
|
|
97
120
|
if (response.status >= 300 && response.status < 400) {
|
|
98
121
|
const next = response.headers.get('location');
|
|
@@ -106,9 +129,9 @@ const fetchRemote = async (location, options) => {
|
|
|
106
129
|
const parse = options.parse ?? ((c) => JSON.parse(c));
|
|
107
130
|
// Parse against the original request location so the caller's format sniffing
|
|
108
131
|
// (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
|
|
109
|
-
return parse(await readCapped(response), location);
|
|
132
|
+
return parse(await readCapped(response, maxBytes), location);
|
|
110
133
|
}
|
|
111
|
-
throw new Error(`too many redirects (>${
|
|
134
|
+
throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
|
|
112
135
|
};
|
|
113
136
|
/** Returns why a remote location may not be fetched, or `null` if it is allowed. */
|
|
114
137
|
const denialReason = (location, options) => {
|
|
@@ -140,25 +163,45 @@ const denialReason = (location, options) => {
|
|
|
140
163
|
};
|
|
141
164
|
/**
|
|
142
165
|
* Loads a document into `docCache`, fetching/reading it if needed. Remote
|
|
143
|
-
* documents are additionally cached for the session in `remoteCache
|
|
144
|
-
* failure an error is recorded and the location is cached
|
|
145
|
-
* pointer lookups degrade gracefully instead of throwing.
|
|
146
|
-
* document loaded successfully.
|
|
166
|
+
* documents are additionally cached for the session in `remoteCache` (unless
|
|
167
|
+
* `cache: false`). On failure an error is recorded and the location is cached
|
|
168
|
+
* as `{}` so that pointer lookups degrade gracefully instead of throwing.
|
|
169
|
+
* Returns whether the document loaded successfully.
|
|
147
170
|
*/
|
|
148
171
|
const loadDoc = async (location, docCache, options, errors) => {
|
|
149
172
|
if (docCache.has(location))
|
|
150
173
|
return true;
|
|
151
174
|
if (isRemote(location)) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
175
|
+
// Evaluate the policy before serving anything for a remote location —
|
|
176
|
+
// including a cache hit. `remoteCache` is process-global and outlives a
|
|
177
|
+
// single resolve call, so a URL fetched earlier under permissive options
|
|
178
|
+
// must not be handed to a later call whose options (a disabled `remote`,
|
|
179
|
+
// a stricter `allowedHosts`, no `allowPrivateHosts`) would refuse it.
|
|
156
180
|
const reason = denialReason(location, options);
|
|
157
181
|
if (reason !== null) {
|
|
158
182
|
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] });
|
|
159
183
|
docCache.set(location, {});
|
|
160
184
|
return false;
|
|
161
185
|
}
|
|
186
|
+
const useSessionCache = options.cache !== false;
|
|
187
|
+
if (useSessionCache && remoteCache.has(location)) {
|
|
188
|
+
docCache.set(location, remoteCache.get(location));
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
if (!useSessionCache) {
|
|
192
|
+
// A cache-bypassing call must not serve (or poison) concurrent callers'
|
|
193
|
+
// in-flight loads either — fetch independently.
|
|
194
|
+
try {
|
|
195
|
+
const doc = await fetchRemote(location, options);
|
|
196
|
+
docCache.set(location, doc);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
catch (err) {
|
|
200
|
+
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
|
|
201
|
+
docCache.set(location, {});
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
162
205
|
// Coalesce concurrent loads of the same URL onto one in-flight request; the
|
|
163
206
|
// owner (first caller) clears the slot once it settles.
|
|
164
207
|
let pending = inFlight.get(location);
|
|
@@ -194,117 +237,32 @@ const loadDoc = async (location, docCache, options, errors) => {
|
|
|
194
237
|
return false;
|
|
195
238
|
}
|
|
196
239
|
};
|
|
197
|
-
/**
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
continue;
|
|
217
|
-
collectRefTargets(obj[key], out);
|
|
218
|
-
}
|
|
219
|
-
return out;
|
|
220
|
-
};
|
|
221
|
-
/**
|
|
222
|
-
* Walks every reachable document starting from `rootLocation`, loading each one
|
|
223
|
-
* so the synchronous resolve pass can look them up. This is the only async part
|
|
224
|
-
* of resolution: remote documents are fetched here (in dependency order) and
|
|
225
|
-
* cached for the session.
|
|
226
|
-
*/
|
|
227
|
-
const prefetch = async (rootLocation, docCache, options, errors) => {
|
|
228
|
-
const seen = new Set([rootLocation]);
|
|
229
|
-
const queue = [rootLocation];
|
|
230
|
-
while (queue.length > 0) {
|
|
231
|
-
const location = queue.shift();
|
|
232
|
-
for (const filePart of collectRefTargets(docCache.get(location), new Set())) {
|
|
233
|
-
const target = joinLocation(location, filePart);
|
|
234
|
-
if (seen.has(target))
|
|
235
|
-
continue;
|
|
236
|
-
seen.add(target);
|
|
237
|
-
await loadDoc(target, docCache, options, errors);
|
|
238
|
-
queue.push(target);
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
};
|
|
242
|
-
/**
|
|
243
|
-
* Single-pass resolver that inlines internal and external (`$ref` to other
|
|
244
|
-
* file/URL) references. Every reachable document has already been loaded into
|
|
245
|
-
* `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
|
|
246
|
-
* (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
|
|
247
|
-
*
|
|
248
|
-
* `baseLocation` is the location of the document `node` belongs to, used to
|
|
249
|
-
* resolve relative refs and `#/...` pointers within it.
|
|
250
|
-
*/
|
|
251
|
-
const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
|
|
252
|
-
if (node === null || typeof node !== 'object')
|
|
253
|
-
return node;
|
|
254
|
-
if (Array.isArray(node)) {
|
|
255
|
-
return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins));
|
|
256
|
-
}
|
|
257
|
-
const obj = node;
|
|
258
|
-
if (typeof obj['$ref'] === 'string') {
|
|
259
|
-
const { filePart, pointer } = splitRef(obj['$ref']);
|
|
260
|
-
const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart);
|
|
261
|
-
const targetRoot = docCache.get(targetLocation) ?? {};
|
|
262
|
-
const cacheKey = `${targetLocation}#${pointer}`;
|
|
263
|
-
let resolved;
|
|
264
|
-
if (refCache.has(cacheKey)) {
|
|
265
|
-
const cached = refCache.get(cacheKey);
|
|
266
|
-
resolved = cached === CYCLE ? {} : cached;
|
|
267
|
-
}
|
|
268
|
-
else {
|
|
269
|
-
refCache.set(cacheKey, CYCLE);
|
|
270
|
-
const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot;
|
|
271
|
-
resolved = resolveAt(target, targetLocation, docCache, refCache, origins);
|
|
272
|
-
refCache.set(cacheKey, resolved);
|
|
273
|
-
// Stamp the inlined node with where it was defined so a consumer can map a
|
|
274
|
-
// resolved-tree node back to its source document/path. Only objects/arrays are
|
|
275
|
-
// stamped (primitives can't key the map). First-write-wins: resolution recurses
|
|
276
|
-
// to the deepest `$ref` before returning, so the *definition* site stamps first;
|
|
277
|
-
// an outer ref that merely points (transitively) at the same object must not
|
|
278
|
-
// overwrite it with an intermediate location.
|
|
279
|
-
if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
|
|
280
|
-
origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) });
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
// Keywords sibling to `$ref` apply alongside the referenced schema (2020-12),
|
|
284
|
-
// so preserve them by combining both in an `allOf` rather than dropping them.
|
|
285
|
-
const siblingKeys = Object.keys(obj).filter((key) => key !== '$ref');
|
|
286
|
-
if (siblingKeys.length === 0)
|
|
287
|
-
return resolved;
|
|
288
|
-
const siblings = {};
|
|
289
|
-
for (const key of siblingKeys)
|
|
290
|
-
assignKey(siblings, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
|
|
291
|
-
const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
|
|
292
|
-
const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
|
|
293
|
-
// Stamp the wrapper too, so origin lookups resolve for a `$ref`-with-siblings node.
|
|
294
|
-
if (origins && !origins.has(merged))
|
|
295
|
-
origins.set(merged, { location: targetLocation, pointer: pointerToPath(pointer) });
|
|
296
|
-
return merged;
|
|
297
|
-
}
|
|
298
|
-
const result = {};
|
|
299
|
-
for (const key of Object.keys(obj)) {
|
|
300
|
-
assignKey(result, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
|
|
301
|
-
}
|
|
302
|
-
return result;
|
|
240
|
+
/** Escapes a JSON Pointer segment (RFC 6901): `~` → `~0`, `/` → `~1`. */
|
|
241
|
+
const escapeSegment = (segment) => segment.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
242
|
+
/** Renders a {@link JsonPath} as a `#/...` ref string. */
|
|
243
|
+
const pathToRef = (path) => path.length === 0 ? '#' : `#/${path.map((segment) => escapeSegment(String(segment))).join('/')}`;
|
|
244
|
+
/** Derives a readable `$defs` key for a hoisted cycle target. */
|
|
245
|
+
const hoistName = (targetLocation, fragment, taken) => {
|
|
246
|
+
const fragmentTail = fragment.split('/').filter(Boolean).pop();
|
|
247
|
+
const locationTail = targetLocation
|
|
248
|
+
.split('/')
|
|
249
|
+
.filter(Boolean)
|
|
250
|
+
.pop()
|
|
251
|
+
?.replace(/\.[a-z0-9]+$/i, '');
|
|
252
|
+
const raw = fragmentTail || locationTail || 'cycle';
|
|
253
|
+
const sanitized = raw.replace(/[^A-Za-z0-9_.-]/g, '-') || 'cycle';
|
|
254
|
+
let name = sanitized;
|
|
255
|
+
for (let n = 2; taken.has(name); n++)
|
|
256
|
+
name = `${sanitized}-${n}`;
|
|
257
|
+
taken.add(name);
|
|
258
|
+
return name;
|
|
303
259
|
};
|
|
304
260
|
/**
|
|
305
261
|
* Resolves `$ref`s in a document on disk (or at a URL), including cross-file
|
|
306
262
|
* and remote refs. Remote documents are fetched on the fly and cached in memory
|
|
307
|
-
* for the session; `options` governs whether/which remote hosts are allowed
|
|
263
|
+
* for the session; `options` governs whether/which remote hosts are allowed,
|
|
264
|
+
* how they are fetched (`headers`, `fetch`, `timeoutMs`, `maxRedirects`,
|
|
265
|
+
* `maxBytes`), and whether the session cache is used (`cache`).
|
|
308
266
|
*/
|
|
309
267
|
export const resolveRefsFromFile = async (filename, options = {}) => {
|
|
310
268
|
const rootLocation = isRemote(filename) ? filename : resolvePath(filename);
|
|
@@ -313,8 +271,274 @@ export const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
313
271
|
if (!(await loadDoc(rootLocation, docCache, options, errors))) {
|
|
314
272
|
return { resolved: {}, errors };
|
|
315
273
|
}
|
|
316
|
-
|
|
274
|
+
// Per-document `$id` registries, built lazily. A document's registry scopes
|
|
275
|
+
// anchor lookups and lets URI refs match embedded resources without fetching.
|
|
276
|
+
const registries = new Map();
|
|
277
|
+
const registryFor = (location) => {
|
|
278
|
+
let registry = registries.get(location);
|
|
279
|
+
if (registry === undefined) {
|
|
280
|
+
registry = buildResourceRegistry(docCache.get(location), isRemote(location) ? location : SYNTHETIC_BASE);
|
|
281
|
+
registries.set(location, registry);
|
|
282
|
+
}
|
|
283
|
+
return registry;
|
|
284
|
+
};
|
|
285
|
+
/** Collects the document parts of refs under `node` that are NOT `$id`-internal. */
|
|
286
|
+
const collectRefTargets = (node, location, base, out) => {
|
|
287
|
+
if (node === null || typeof node !== 'object')
|
|
288
|
+
return;
|
|
289
|
+
if (Array.isArray(node)) {
|
|
290
|
+
for (const item of node)
|
|
291
|
+
collectRefTargets(item, location, base, out);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const obj = node;
|
|
295
|
+
const registry = registryFor(location);
|
|
296
|
+
const nodeBase = typeof obj['$id'] === 'string' ? baseOfNode(registry, obj, base) : base;
|
|
297
|
+
const reference = readReference(obj);
|
|
298
|
+
if (reference && reference.keyword !== '$recursiveRef') {
|
|
299
|
+
const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
|
|
300
|
+
if (scoped === 'external') {
|
|
301
|
+
const { filePart } = splitRef(reference.value);
|
|
302
|
+
if (filePart !== '')
|
|
303
|
+
out.add(filePart);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// Recurse into every key — including a reference node's siblings, which apply
|
|
307
|
+
// alongside the referenced schema (2020-12) and may carry their own refs.
|
|
308
|
+
for (const key of Object.keys(obj)) {
|
|
309
|
+
if (reference && key === reference.keyword)
|
|
310
|
+
continue;
|
|
311
|
+
collectRefTargets(obj[key], location, nodeBase, out);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* Walks every reachable document starting from the root, loading each one so
|
|
316
|
+
* the synchronous resolve pass can look them up. This is the only async part
|
|
317
|
+
* of resolution: remote documents are fetched here (in dependency order) and
|
|
318
|
+
* cached for the session.
|
|
319
|
+
*/
|
|
320
|
+
const prefetch = async () => {
|
|
321
|
+
const seen = new Set([rootLocation]);
|
|
322
|
+
const queue = [rootLocation];
|
|
323
|
+
while (queue.length > 0) {
|
|
324
|
+
const location = queue.shift();
|
|
325
|
+
const out = new Set();
|
|
326
|
+
collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out);
|
|
327
|
+
for (const filePart of out) {
|
|
328
|
+
const target = joinLocation(location, filePart);
|
|
329
|
+
if (seen.has(target))
|
|
330
|
+
continue;
|
|
331
|
+
seen.add(target);
|
|
332
|
+
await loadDoc(target, docCache, options, errors);
|
|
333
|
+
queue.push(target);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
await prefetch();
|
|
317
338
|
const origins = options.trackOrigins ? new Map() : undefined;
|
|
318
|
-
const
|
|
339
|
+
const refCache = new Map();
|
|
340
|
+
// Cycle targets living in other documents are hoisted into the root's `$defs`
|
|
341
|
+
// under these names once resolution completes (see the CYCLE branch).
|
|
342
|
+
const hoists = new Map();
|
|
343
|
+
const hoistTaken = new Set();
|
|
344
|
+
/**
|
|
345
|
+
* Single-pass resolver that inlines internal and external (`$ref` to other
|
|
346
|
+
* file/URL) references. Every reachable document has already been loaded into
|
|
347
|
+
* `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
|
|
348
|
+
* (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
|
|
349
|
+
*
|
|
350
|
+
* `baseLocation` is the location of the document `node` belongs to; `base` is
|
|
351
|
+
* the current `$id` base URI within that document.
|
|
352
|
+
*/
|
|
353
|
+
const resolveAt = (node, baseLocation, base) => {
|
|
354
|
+
if (node === null || typeof node !== 'object')
|
|
355
|
+
return node;
|
|
356
|
+
if (Array.isArray(node)) {
|
|
357
|
+
return node.map((item) => resolveAt(item, baseLocation, base));
|
|
358
|
+
}
|
|
359
|
+
const obj = node;
|
|
360
|
+
const registry = registryFor(baseLocation);
|
|
361
|
+
const nodeBase = typeof obj['$id'] === 'string' ? baseOfNode(registry, obj, base) : base;
|
|
362
|
+
const reference = readReference(obj);
|
|
363
|
+
if (reference) {
|
|
364
|
+
const { keyword, value } = reference;
|
|
365
|
+
// Classify the ref: `$id`-internal (this document), or external (another
|
|
366
|
+
// document, or a fragment resolved the legacy way against this one).
|
|
367
|
+
// A resolved in-scope target, or undefined when the ref is external / an
|
|
368
|
+
// anchor to look up in the target document below. Typed narrowly (never
|
|
369
|
+
// `'external'`) so the later `scoped !== undefined` branches read as
|
|
370
|
+
// `ScopedTarget`; the `'external'` case is handled here and never escapes.
|
|
371
|
+
let scoped;
|
|
372
|
+
let targetLocation = baseLocation;
|
|
373
|
+
let fragment = '';
|
|
374
|
+
if (keyword === '$recursiveRef') {
|
|
375
|
+
fragment = value.startsWith('#') ? value.slice(1) : value;
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
|
|
379
|
+
if (inScope === 'external' || inScope === undefined) {
|
|
380
|
+
const parts = splitRef(value);
|
|
381
|
+
fragment = parts.fragment;
|
|
382
|
+
if (inScope === 'external' && parts.filePart !== '') {
|
|
383
|
+
targetLocation = joinLocation(baseLocation, parts.filePart);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
scoped = inScope;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
// Cache/cycle key includes the keyword (`$ref #x` and `$dynamicRef #x`
|
|
391
|
+
// can bind to different targets) and, for scoped refs, the base URI (the
|
|
392
|
+
// same anchor name can bind differently inside different resources).
|
|
393
|
+
const cacheKey = scoped !== undefined
|
|
394
|
+
? `${keyword} ${baseLocation} ${nodeBase} ${value}`
|
|
395
|
+
: `${keyword} ${targetLocation}#${fragment}`;
|
|
396
|
+
let resolved;
|
|
397
|
+
let pointer;
|
|
398
|
+
const cached = refCache.get(cacheKey);
|
|
399
|
+
if (cached === CYCLE) {
|
|
400
|
+
// Mid-resolution revisit — a reference cycle. Keep a reference instead
|
|
401
|
+
// of collapsing the branch to `{}`:
|
|
402
|
+
// - target in the ROOT document → a root-relative ref (the target still
|
|
403
|
+
// exists in the resolved output);
|
|
404
|
+
// - target in ANOTHER document → `#/$defs/<name>`, and the resolved
|
|
405
|
+
// target is attached there once resolution completes.
|
|
406
|
+
let keptRef;
|
|
407
|
+
if (scoped !== undefined && baseLocation === rootLocation) {
|
|
408
|
+
keptRef = pathToRef(scoped.pointer);
|
|
409
|
+
}
|
|
410
|
+
else if (scoped === undefined && targetLocation === rootLocation) {
|
|
411
|
+
keptRef = `#${fragment}`;
|
|
412
|
+
}
|
|
413
|
+
else {
|
|
414
|
+
let name = hoists.get(cacheKey);
|
|
415
|
+
if (name === undefined) {
|
|
416
|
+
name = hoistName(targetLocation, fragment, hoistTaken);
|
|
417
|
+
hoists.set(cacheKey, name);
|
|
418
|
+
}
|
|
419
|
+
keptRef = `#/$defs/${name}`;
|
|
420
|
+
}
|
|
421
|
+
const kept = {};
|
|
422
|
+
for (const key of Object.keys(obj)) {
|
|
423
|
+
if (key === keyword)
|
|
424
|
+
continue;
|
|
425
|
+
assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase));
|
|
426
|
+
}
|
|
427
|
+
// Always rewritten to a static `$ref`: the dynamic binding was already
|
|
428
|
+
// decided when the cycle was entered.
|
|
429
|
+
assignKey(kept, '$ref', keptRef);
|
|
430
|
+
return kept;
|
|
431
|
+
}
|
|
432
|
+
if (cached !== undefined) {
|
|
433
|
+
resolved = cached.value;
|
|
434
|
+
pointer = cached.pointer;
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
refCache.set(cacheKey, CYCLE);
|
|
438
|
+
let found;
|
|
439
|
+
let targetBase;
|
|
440
|
+
if (scoped !== undefined) {
|
|
441
|
+
found = scoped;
|
|
442
|
+
targetBase = scoped.base;
|
|
443
|
+
}
|
|
444
|
+
else {
|
|
445
|
+
// `$anchor`/`$dynamicAnchor`/`$recursiveAnchor` resolve within the
|
|
446
|
+
// target document — scoped by its own `$id`s where possible, falling
|
|
447
|
+
// back to the document-global search. A fragment that resolves to
|
|
448
|
+
// nothing inlines as `undefined` (kept as-is for parity).
|
|
449
|
+
const targetRegistry = registryFor(targetLocation);
|
|
450
|
+
const targetRoot = docCache.get(targetLocation) ?? {};
|
|
451
|
+
if (keyword === '$recursiveRef') {
|
|
452
|
+
found = resolveFragment(targetRoot, keyword, fragment);
|
|
453
|
+
targetBase = targetRegistry.rootBase;
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
|
|
457
|
+
if (scopedFragment !== 'external' && scopedFragment !== undefined) {
|
|
458
|
+
found = scopedFragment;
|
|
459
|
+
targetBase = scopedFragment.base;
|
|
460
|
+
}
|
|
461
|
+
else {
|
|
462
|
+
found = resolveFragment(targetRoot, keyword, fragment);
|
|
463
|
+
targetBase = targetRegistry.rootBase;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
pointer = found?.pointer ?? [];
|
|
468
|
+
resolved = resolveAt(found?.value, targetLocation, targetBase);
|
|
469
|
+
refCache.set(cacheKey, { value: resolved, pointer });
|
|
470
|
+
// Stamp the inlined node with where it was defined so a consumer can map a
|
|
471
|
+
// resolved-tree node back to its source document/path. Only objects/arrays are
|
|
472
|
+
// stamped (primitives can't key the map). First-write-wins: resolution recurses
|
|
473
|
+
// to the deepest ref before returning, so the *definition* site stamps first;
|
|
474
|
+
// an outer ref that merely points (transitively) at the same object must not
|
|
475
|
+
// overwrite it with an intermediate location.
|
|
476
|
+
if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
|
|
477
|
+
origins.set(resolved, { location: targetLocation, pointer });
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
|
|
481
|
+
if (siblingKeys.length === 0)
|
|
482
|
+
return resolved;
|
|
483
|
+
const siblings = {};
|
|
484
|
+
for (const key of siblingKeys)
|
|
485
|
+
assignKey(siblings, key, resolveAt(obj[key], baseLocation, nodeBase));
|
|
486
|
+
// Annotation-only siblings (OpenAPI Reference Objects): inline the target
|
|
487
|
+
// with the annotations overriding — never wrap in `allOf`, which is not
|
|
488
|
+
// valid where those references appear (Path Item, Response, Parameter).
|
|
489
|
+
if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
|
|
490
|
+
if (resolved !== null && typeof resolved === 'object' && !Array.isArray(resolved)) {
|
|
491
|
+
const overridden = {};
|
|
492
|
+
for (const key of Object.keys(resolved)) {
|
|
493
|
+
assignKey(overridden, key, resolved[key]);
|
|
494
|
+
}
|
|
495
|
+
for (const key of Object.keys(siblings))
|
|
496
|
+
assignKey(overridden, key, siblings[key]);
|
|
497
|
+
if (origins && !origins.has(overridden))
|
|
498
|
+
origins.set(overridden, { location: targetLocation, pointer });
|
|
499
|
+
return overridden;
|
|
500
|
+
}
|
|
501
|
+
// A non-object target (boolean schema, primitive) has no members to
|
|
502
|
+
// override; the annotations have nowhere to live, so return the target.
|
|
503
|
+
return resolved;
|
|
504
|
+
}
|
|
505
|
+
// Keywords sibling to a reference apply alongside the referenced schema
|
|
506
|
+
// (2020-12), so preserve them by combining both in an `allOf`.
|
|
507
|
+
const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
|
|
508
|
+
const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
|
|
509
|
+
// Stamp the wrapper too, so origin lookups resolve for a ref-with-siblings node.
|
|
510
|
+
if (origins && !origins.has(merged))
|
|
511
|
+
origins.set(merged, { location: targetLocation, pointer });
|
|
512
|
+
return merged;
|
|
513
|
+
}
|
|
514
|
+
const result = {};
|
|
515
|
+
for (const key of Object.keys(obj)) {
|
|
516
|
+
assignKey(result, key, resolveAt(obj[key], baseLocation, nodeBase));
|
|
517
|
+
}
|
|
518
|
+
return result;
|
|
519
|
+
};
|
|
520
|
+
const rootRegistry = registryFor(rootLocation);
|
|
521
|
+
const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase);
|
|
522
|
+
// Attach cross-document cycle targets under `$defs` so every `#/$defs/<name>`
|
|
523
|
+
// ref emitted by the CYCLE branch resolves within the output document.
|
|
524
|
+
if (hoists.size > 0) {
|
|
525
|
+
if (resolved !== null && typeof resolved === 'object' && !Array.isArray(resolved)) {
|
|
526
|
+
const container = resolved;
|
|
527
|
+
const defs = container['$defs'] !== null && typeof container['$defs'] === 'object' && !Array.isArray(container['$defs'])
|
|
528
|
+
? container['$defs']
|
|
529
|
+
: {};
|
|
530
|
+
for (const [cacheKey, name] of hoists) {
|
|
531
|
+
const cached = refCache.get(cacheKey);
|
|
532
|
+
assignKey(defs, name, cached !== undefined && cached !== CYCLE ? (cached.value ?? {}) : {});
|
|
533
|
+
}
|
|
534
|
+
assignKey(container, '$defs', defs);
|
|
535
|
+
}
|
|
536
|
+
else {
|
|
537
|
+
errors.push({
|
|
538
|
+
message: 'Cannot attach hoisted cycle definitions: the resolved root document is not an object',
|
|
539
|
+
path: [],
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
}
|
|
319
543
|
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
320
544
|
};
|
package/dist/resolve-refs.d.ts
CHANGED
|
@@ -10,8 +10,12 @@ export type ResolveRefsOptions = {
|
|
|
10
10
|
trackOrigins?: boolean;
|
|
11
11
|
};
|
|
12
12
|
/**
|
|
13
|
-
* Resolves all internal
|
|
14
|
-
*
|
|
15
|
-
* an
|
|
13
|
+
* Resolves all internal `$ref`s in an in-memory document — plain `#/...`
|
|
14
|
+
* pointers, `$anchor`/`$dynamicAnchor` names (scoped by `$id`), and refs whose
|
|
15
|
+
* URI matches an embedded resource's `$id` — inlining each target. Refs to
|
|
16
|
+
* other files/URLs are left in place and reported on `errors` (this resolver
|
|
17
|
+
* can't load other documents — use `resolveRefsFromFile` for those). Cycles are
|
|
18
|
+
* broken by keeping the original reference node, so recursive schemas keep
|
|
19
|
+
* their recursive branch.
|
|
16
20
|
*/
|
|
17
21
|
export declare const resolveRefs: (data: unknown, options?: ResolveRefsOptions) => ResolveResult;
|