@amritk/resolve-refs 0.2.2 → 0.3.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 +5 -0
- package/dist/reference.d.ts +42 -0
- package/dist/reference.js +80 -0
- package/dist/resolve-refs-from-file.js +81 -27
- package/dist/resolve-refs.js +49 -18
- package/dist/safe-assign.d.ts +8 -0
- package/dist/safe-assign.js +15 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -5,6 +5,11 @@ refs, and remote (http/https) documents — into a single dereferenced document.
|
|
|
5
5
|
|
|
6
6
|
- **One-pass, cached.** Every unique ref is resolved once; cycles are broken with
|
|
7
7
|
an empty object so the result is always finite.
|
|
8
|
+
- **Anchors + dynamic refs.** Beyond JSON-pointer `$ref`s, plain-name `$anchor`
|
|
9
|
+
references (`#node`), `$dynamicRef`/`$dynamicAnchor` (2020-12), and
|
|
10
|
+
`$recursiveRef`/`$recursiveAnchor` (2019-09) are dereferenced too. The dynamic
|
|
11
|
+
forms bind to their document-global anchor — the single-bundle case; nested
|
|
12
|
+
`$id` base-URI re-scoping is not modelled.
|
|
8
13
|
- **Cross-file + remote.** Relative refs resolve against the document they appear
|
|
9
14
|
in (a ref inside a remote doc stays remote, one inside a local file stays
|
|
10
15
|
local). Fetched remote documents are cached for the lifetime of the process.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { JsonPath } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The reference keywords JSON Schema uses to point at another schema. `$ref`
|
|
4
|
+
* (all drafts) is a static pointer; `$dynamicRef` (2020-12) and `$recursiveRef`
|
|
5
|
+
* (2019-09) late-bind to an anchor so a recursive/extensible schema can refer to
|
|
6
|
+
* itself. We inline all three; the dynamic forms bind to their document-global
|
|
7
|
+
* anchor (see {@link resolveFragment}).
|
|
8
|
+
*/
|
|
9
|
+
export type RefKeyword = '$ref' | '$dynamicRef' | '$recursiveRef';
|
|
10
|
+
/** A reference carried by an object: which keyword, and its string value. */
|
|
11
|
+
export type Reference = {
|
|
12
|
+
keyword: RefKeyword;
|
|
13
|
+
value: string;
|
|
14
|
+
};
|
|
15
|
+
/** Returns the reference keyword `obj` carries (if any), preferring `$ref`. */
|
|
16
|
+
export declare const readReference: (obj: Record<string, unknown>) => Reference | undefined;
|
|
17
|
+
/** The resolved target of a reference: the node and the path to it within its document. */
|
|
18
|
+
export type ResolvedTarget = {
|
|
19
|
+
value: unknown;
|
|
20
|
+
pointer: JsonPath;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Resolves a reference `fragment` (the part after `#`) within `root`, per its
|
|
24
|
+
* `keyword`. Returns the target node and its in-document path, or `undefined`
|
|
25
|
+
* when nothing matches.
|
|
26
|
+
*
|
|
27
|
+
* - **JSON Pointer** (`''`, `/a/b`) — a plain pointer lookup, for any keyword.
|
|
28
|
+
* - **`$anchor` name** (`node`) — searches for a `$anchor`/`$dynamicAnchor` equal
|
|
29
|
+
* to the name. A `$dynamicRef` prefers a `$dynamicAnchor`, then falls back to a
|
|
30
|
+
* plain `$anchor`, so it degrades to `$ref` semantics when nothing dynamic
|
|
31
|
+
* matches (2020-12).
|
|
32
|
+
* - **`$recursiveRef`** (always `#`) — binds to the object carrying
|
|
33
|
+
* `$recursiveAnchor: true`, falling back to the document root when there is
|
|
34
|
+
* none (2019-09).
|
|
35
|
+
*
|
|
36
|
+
* Anchor search is document-global: we bind to the single matching anchor in
|
|
37
|
+
* `root` rather than walking the dynamic scope. For one bundled document — what a
|
|
38
|
+
* linter dereferences — there is exactly one anchor per name, so this agrees with
|
|
39
|
+
* the full dynamic-scope algorithm. Nested `$id` base-URI re-scoping is not
|
|
40
|
+
* modelled (the common bundled case does not rely on it).
|
|
41
|
+
*/
|
|
42
|
+
export declare const resolveFragment: (root: unknown, keyword: RefKeyword, fragment: string) => ResolvedTarget | undefined;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { getByPointer, pointerToPath } from './get-by-pointer.js';
|
|
2
|
+
// `$ref` is listed first so that a node carrying several reference keywords
|
|
3
|
+
// resolves through the static one, matching how validators treat `$ref`.
|
|
4
|
+
const REF_KEYWORDS = ['$ref', '$dynamicRef', '$recursiveRef'];
|
|
5
|
+
/** Returns the reference keyword `obj` carries (if any), preferring `$ref`. */
|
|
6
|
+
export const readReference = (obj) => {
|
|
7
|
+
for (const keyword of REF_KEYWORDS) {
|
|
8
|
+
const value = obj[keyword];
|
|
9
|
+
if (typeof value === 'string')
|
|
10
|
+
return { keyword, value };
|
|
11
|
+
}
|
|
12
|
+
return undefined;
|
|
13
|
+
};
|
|
14
|
+
/** A fragment is a JSON Pointer when it is empty or begins with `/`; otherwise a plain-name anchor. */
|
|
15
|
+
const isPointerFragment = (fragment) => fragment === '' || fragment.startsWith('/');
|
|
16
|
+
/**
|
|
17
|
+
* Depth-first search for the first object in `root` satisfying `predicate`,
|
|
18
|
+
* returning it with the path to it. `seen` guards against cyclic inputs. Used to
|
|
19
|
+
* locate `$anchor`/`$dynamicAnchor`/`$recursiveAnchor` targets.
|
|
20
|
+
*/
|
|
21
|
+
const search = (root, predicate) => {
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
const walk = (node, pointer) => {
|
|
24
|
+
if (node === null || typeof node !== 'object' || seen.has(node))
|
|
25
|
+
return undefined;
|
|
26
|
+
seen.add(node);
|
|
27
|
+
if (!Array.isArray(node) && predicate(node))
|
|
28
|
+
return { value: node, pointer };
|
|
29
|
+
if (Array.isArray(node)) {
|
|
30
|
+
for (let i = 0; i < node.length; i++) {
|
|
31
|
+
const found = walk(node[i], [...pointer, i]);
|
|
32
|
+
if (found)
|
|
33
|
+
return found;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
for (const key of Object.keys(node)) {
|
|
38
|
+
const found = walk(node[key], [...pointer, key]);
|
|
39
|
+
if (found)
|
|
40
|
+
return found;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
};
|
|
45
|
+
return walk(root, []);
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Resolves a reference `fragment` (the part after `#`) within `root`, per its
|
|
49
|
+
* `keyword`. Returns the target node and its in-document path, or `undefined`
|
|
50
|
+
* when nothing matches.
|
|
51
|
+
*
|
|
52
|
+
* - **JSON Pointer** (`''`, `/a/b`) — a plain pointer lookup, for any keyword.
|
|
53
|
+
* - **`$anchor` name** (`node`) — searches for a `$anchor`/`$dynamicAnchor` equal
|
|
54
|
+
* to the name. A `$dynamicRef` prefers a `$dynamicAnchor`, then falls back to a
|
|
55
|
+
* plain `$anchor`, so it degrades to `$ref` semantics when nothing dynamic
|
|
56
|
+
* matches (2020-12).
|
|
57
|
+
* - **`$recursiveRef`** (always `#`) — binds to the object carrying
|
|
58
|
+
* `$recursiveAnchor: true`, falling back to the document root when there is
|
|
59
|
+
* none (2019-09).
|
|
60
|
+
*
|
|
61
|
+
* Anchor search is document-global: we bind to the single matching anchor in
|
|
62
|
+
* `root` rather than walking the dynamic scope. For one bundled document — what a
|
|
63
|
+
* linter dereferences — there is exactly one anchor per name, so this agrees with
|
|
64
|
+
* the full dynamic-scope algorithm. Nested `$id` base-URI re-scoping is not
|
|
65
|
+
* modelled (the common bundled case does not rely on it).
|
|
66
|
+
*/
|
|
67
|
+
export const resolveFragment = (root, keyword, fragment) => {
|
|
68
|
+
if (keyword === '$recursiveRef') {
|
|
69
|
+
const anchored = search(root, (obj) => obj['$recursiveAnchor'] === true);
|
|
70
|
+
return anchored ?? { value: root, pointer: [] };
|
|
71
|
+
}
|
|
72
|
+
if (isPointerFragment(fragment)) {
|
|
73
|
+
const value = getByPointer(root, fragment);
|
|
74
|
+
return value === undefined ? undefined : { value, pointer: pointerToPath(fragment) };
|
|
75
|
+
}
|
|
76
|
+
if (keyword === '$dynamicRef') {
|
|
77
|
+
return (search(root, (obj) => obj['$dynamicAnchor'] === fragment) ?? search(root, (obj) => obj['$anchor'] === fragment));
|
|
78
|
+
}
|
|
79
|
+
return search(root, (obj) => obj['$anchor'] === fragment || obj['$dynamicAnchor'] === fragment);
|
|
80
|
+
};
|
|
@@ -1,7 +1,8 @@
|
|
|
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 { assignKey } from './safe-assign.js';
|
|
5
6
|
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
6
7
|
// means a cycle, so we return `{}` instead of recursing forever.
|
|
7
8
|
const CYCLE = Symbol('cycle');
|
|
@@ -20,12 +21,12 @@ const joinLocation = (base, ref) => {
|
|
|
20
21
|
return new URL(ref, base).href;
|
|
21
22
|
return resolvePath(dirname(base), ref);
|
|
22
23
|
};
|
|
23
|
-
/** Splits a `$ref` into its document part and
|
|
24
|
+
/** Splits a `$ref` into its document part and its fragment (pointer or anchor name). */
|
|
24
25
|
const splitRef = (ref) => {
|
|
25
26
|
const hashIdx = ref.indexOf('#');
|
|
26
27
|
return {
|
|
27
28
|
filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
|
|
28
|
-
|
|
29
|
+
fragment: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
|
|
29
30
|
};
|
|
30
31
|
};
|
|
31
32
|
// --- Remote document cache -------------------------------------------------
|
|
@@ -47,6 +48,34 @@ export const clearRemoteCache = () => {
|
|
|
47
48
|
// Cap on redirect hops before we give up — generous enough for real services,
|
|
48
49
|
// low enough to stop a redirect loop from spinning forever.
|
|
49
50
|
const MAX_REDIRECTS = 5;
|
|
51
|
+
/** Abort a remote fetch that has not responded within this many milliseconds. */
|
|
52
|
+
const FETCH_TIMEOUT_MS = 30_000;
|
|
53
|
+
/** Refuse to buffer a remote document larger than this (bytes) to bound memory. */
|
|
54
|
+
const MAX_REMOTE_BYTES = 16 * 1024 * 1024;
|
|
55
|
+
/**
|
|
56
|
+
* Reads a response body, refusing to buffer more than {@link MAX_REMOTE_BYTES}.
|
|
57
|
+
* A `Content-Length` over the limit is rejected up front; a missing/lying header
|
|
58
|
+
* is caught while streaming so a chunked response can't exhaust memory either.
|
|
59
|
+
*/
|
|
60
|
+
const readCapped = async (response) => {
|
|
61
|
+
const declared = Number(response.headers.get('content-length'));
|
|
62
|
+
if (Number.isFinite(declared) && declared > MAX_REMOTE_BYTES) {
|
|
63
|
+
throw new Error(`remote document exceeds ${MAX_REMOTE_BYTES} bytes`);
|
|
64
|
+
}
|
|
65
|
+
const body = response.body;
|
|
66
|
+
if (!body)
|
|
67
|
+
return response.text();
|
|
68
|
+
const decoder = new TextDecoder();
|
|
69
|
+
let text = '';
|
|
70
|
+
let total = 0;
|
|
71
|
+
for await (const chunk of body) {
|
|
72
|
+
total += chunk.byteLength;
|
|
73
|
+
if (total > MAX_REMOTE_BYTES)
|
|
74
|
+
throw new Error(`remote document exceeds ${MAX_REMOTE_BYTES} bytes`);
|
|
75
|
+
text += decoder.decode(chunk, { stream: true });
|
|
76
|
+
}
|
|
77
|
+
return text + decoder.decode();
|
|
78
|
+
};
|
|
50
79
|
/**
|
|
51
80
|
* Fetches and parses a remote document, following redirects manually so the
|
|
52
81
|
* SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
|
|
@@ -60,7 +89,11 @@ const fetchRemote = async (location, options) => {
|
|
|
60
89
|
const reason = denialReason(current, options);
|
|
61
90
|
if (reason !== null)
|
|
62
91
|
throw new Error(`refusing to follow redirect (${reason}): ${current}`);
|
|
63
|
-
const response = await fetch(current, {
|
|
92
|
+
const response = await fetch(current, {
|
|
93
|
+
redirect: 'manual',
|
|
94
|
+
// Cap the wait for a response so a stalling host can't hang resolution forever.
|
|
95
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
96
|
+
});
|
|
64
97
|
if (response.status >= 300 && response.status < 400) {
|
|
65
98
|
const next = response.headers.get('location');
|
|
66
99
|
if (!next)
|
|
@@ -73,7 +106,7 @@ const fetchRemote = async (location, options) => {
|
|
|
73
106
|
const parse = options.parse ?? ((c) => JSON.parse(c));
|
|
74
107
|
// Parse against the original request location so the caller's format sniffing
|
|
75
108
|
// (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
|
|
76
|
-
return parse(await response
|
|
109
|
+
return parse(await readCapped(response), location);
|
|
77
110
|
}
|
|
78
111
|
throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`);
|
|
79
112
|
};
|
|
@@ -88,6 +121,12 @@ const denialReason = (location, options) => {
|
|
|
88
121
|
catch {
|
|
89
122
|
return 'the URL is invalid';
|
|
90
123
|
}
|
|
124
|
+
// Only http(s) may be fetched. Without this, a redirect to `file:///etc/passwd`
|
|
125
|
+
// or a `data:` URL passes every host check below (their `hostname` is empty, so
|
|
126
|
+
// `isPrivateHost('')` is false) and Bun's `fetch` would happily read the file.
|
|
127
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
128
|
+
return `unsupported URL protocol "${url.protocol}" (only http and https are allowed)`;
|
|
129
|
+
}
|
|
91
130
|
const allow = options.allowedHosts;
|
|
92
131
|
// An explicit allow-list entry is an intentional opt-in and bypasses the
|
|
93
132
|
// private-host guard; otherwise refuse non-public targets by default.
|
|
@@ -165,15 +204,16 @@ const collectRefTargets = (node, out) => {
|
|
|
165
204
|
return out;
|
|
166
205
|
}
|
|
167
206
|
const obj = node;
|
|
168
|
-
|
|
169
|
-
|
|
207
|
+
const reference = readReference(obj);
|
|
208
|
+
if (reference) {
|
|
209
|
+
const { filePart } = splitRef(reference.value);
|
|
170
210
|
if (filePart !== '')
|
|
171
211
|
out.add(filePart);
|
|
172
212
|
}
|
|
173
|
-
// Recurse into every key — including a
|
|
213
|
+
// Recurse into every key — including a reference node's siblings, which apply
|
|
174
214
|
// alongside the referenced schema (2020-12) and may carry their own refs.
|
|
175
215
|
for (const key of Object.keys(obj)) {
|
|
176
|
-
if (key ===
|
|
216
|
+
if (reference && key === reference.keyword)
|
|
177
217
|
continue;
|
|
178
218
|
collectRefTargets(obj[key], out);
|
|
179
219
|
}
|
|
@@ -216,49 +256,63 @@ const resolveAt = (node, baseLocation, docCache, refCache, origins) => {
|
|
|
216
256
|
return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins));
|
|
217
257
|
}
|
|
218
258
|
const obj = node;
|
|
219
|
-
|
|
220
|
-
|
|
259
|
+
const reference = readReference(obj);
|
|
260
|
+
if (reference) {
|
|
261
|
+
const { keyword, value } = reference;
|
|
262
|
+
const { filePart, fragment } = splitRef(value);
|
|
221
263
|
const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart);
|
|
222
264
|
const targetRoot = docCache.get(targetLocation) ?? {};
|
|
223
|
-
|
|
265
|
+
// Cache/cycle key includes the keyword: `$ref #x` and `$dynamicRef #x` can
|
|
266
|
+
// bind to different targets, so they must not share a cache slot.
|
|
267
|
+
const cacheKey = `${keyword} ${targetLocation}#${fragment}`;
|
|
224
268
|
let resolved;
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
269
|
+
let pointer;
|
|
270
|
+
const cached = refCache.get(cacheKey);
|
|
271
|
+
if (cached === CYCLE) {
|
|
272
|
+
resolved = {};
|
|
273
|
+
pointer = [];
|
|
274
|
+
}
|
|
275
|
+
else if (cached !== undefined) {
|
|
276
|
+
resolved = cached.value;
|
|
277
|
+
pointer = cached.pointer;
|
|
228
278
|
}
|
|
229
279
|
else {
|
|
230
280
|
refCache.set(cacheKey, CYCLE);
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
281
|
+
// `$anchor`/`$dynamicAnchor`/`$recursiveAnchor` are resolved within the
|
|
282
|
+
// target document; a plain pointer is a direct lookup. A fragment that
|
|
283
|
+
// resolves to nothing inlines as `undefined` (kept as-is for parity).
|
|
284
|
+
const found = resolveFragment(targetRoot, keyword, fragment);
|
|
285
|
+
pointer = found?.pointer ?? [];
|
|
286
|
+
resolved = resolveAt(found?.value, targetLocation, docCache, refCache, origins);
|
|
287
|
+
refCache.set(cacheKey, { value: resolved, pointer });
|
|
234
288
|
// Stamp the inlined node with where it was defined so a consumer can map a
|
|
235
289
|
// resolved-tree node back to its source document/path. Only objects/arrays are
|
|
236
290
|
// stamped (primitives can't key the map). First-write-wins: resolution recurses
|
|
237
|
-
// to the deepest
|
|
291
|
+
// to the deepest ref before returning, so the *definition* site stamps first;
|
|
238
292
|
// an outer ref that merely points (transitively) at the same object must not
|
|
239
293
|
// overwrite it with an intermediate location.
|
|
240
294
|
if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
|
|
241
|
-
origins.set(resolved, { location: targetLocation, pointer
|
|
295
|
+
origins.set(resolved, { location: targetLocation, pointer });
|
|
242
296
|
}
|
|
243
297
|
}
|
|
244
|
-
// Keywords sibling to
|
|
245
|
-
// so preserve them by combining both in an `allOf
|
|
246
|
-
const siblingKeys = Object.keys(obj).filter((key) => key !==
|
|
298
|
+
// Keywords sibling to a reference apply alongside the referenced schema
|
|
299
|
+
// (2020-12), so preserve them by combining both in an `allOf`.
|
|
300
|
+
const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
|
|
247
301
|
if (siblingKeys.length === 0)
|
|
248
302
|
return resolved;
|
|
249
303
|
const siblings = {};
|
|
250
304
|
for (const key of siblingKeys)
|
|
251
|
-
siblings
|
|
305
|
+
assignKey(siblings, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
|
|
252
306
|
const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
|
|
253
307
|
const merged = { ...siblings, allOf: [...existingAllOf, resolved] };
|
|
254
|
-
// Stamp the wrapper too, so origin lookups resolve for a
|
|
308
|
+
// Stamp the wrapper too, so origin lookups resolve for a ref-with-siblings node.
|
|
255
309
|
if (origins && !origins.has(merged))
|
|
256
|
-
origins.set(merged, { location: targetLocation, pointer
|
|
310
|
+
origins.set(merged, { location: targetLocation, pointer });
|
|
257
311
|
return merged;
|
|
258
312
|
}
|
|
259
313
|
const result = {};
|
|
260
314
|
for (const key of Object.keys(obj)) {
|
|
261
|
-
result
|
|
315
|
+
assignKey(result, key, resolveAt(obj[key], baseLocation, docCache, refCache, origins));
|
|
262
316
|
}
|
|
263
317
|
return result;
|
|
264
318
|
};
|
package/dist/resolve-refs.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { pointerToPath } from './get-by-pointer.js';
|
|
2
|
+
import { readReference, resolveFragment } from './reference.js';
|
|
3
|
+
import { assignKey } from './safe-assign.js';
|
|
2
4
|
// A ref currently mid-resolution is marked with this sentinel; revisiting it
|
|
3
5
|
// means we have looped, so we return `{}` instead of recursing forever.
|
|
4
6
|
const CYCLE = Symbol('cycle');
|
|
7
|
+
// A ref that resolved to nothing; cached so a repeated bad ref reports once.
|
|
8
|
+
const MISSING = Symbol('missing');
|
|
5
9
|
/**
|
|
6
10
|
* Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
|
|
7
11
|
* exactly once (the `cache`); revisiting a ref that is still mid-resolution
|
|
@@ -9,30 +13,56 @@ const CYCLE = Symbol('cycle');
|
|
|
9
13
|
* files, HTTP) are left untouched — callers that need those should use
|
|
10
14
|
* `resolveRefsFromFile`.
|
|
11
15
|
*/
|
|
12
|
-
const resolveInternal = (node, root, cache, origins) => {
|
|
16
|
+
const resolveInternal = (node, root, cache, origins, errors) => {
|
|
13
17
|
if (node === null || typeof node !== 'object')
|
|
14
18
|
return node;
|
|
15
19
|
if (Array.isArray(node))
|
|
16
|
-
return node.map((item) => resolveInternal(item, root, cache, origins));
|
|
20
|
+
return node.map((item) => resolveInternal(item, root, cache, origins, errors));
|
|
17
21
|
const obj = node;
|
|
18
|
-
|
|
19
|
-
|
|
22
|
+
const reference = readReference(obj);
|
|
23
|
+
if (reference) {
|
|
24
|
+
const { keyword, value: ref } = reference;
|
|
20
25
|
if (!ref.startsWith('#'))
|
|
21
26
|
return obj; // external ref — leave as-is
|
|
27
|
+
// Cache/cycle key includes the keyword: `$ref #x` and `$dynamicRef #x` can
|
|
28
|
+
// bind to different targets, so they must not share a cache slot.
|
|
29
|
+
const cacheKey = `${keyword} ${ref}`;
|
|
22
30
|
let target;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
31
|
+
let pointer;
|
|
32
|
+
const cached = cache.get(cacheKey);
|
|
33
|
+
if (cached === MISSING)
|
|
34
|
+
return obj;
|
|
35
|
+
if (cached === CYCLE) {
|
|
36
|
+
target = {};
|
|
37
|
+
pointer = [];
|
|
38
|
+
}
|
|
39
|
+
else if (cached !== undefined) {
|
|
40
|
+
target = cached.target;
|
|
41
|
+
pointer = cached.pointer;
|
|
26
42
|
}
|
|
27
43
|
else {
|
|
28
|
-
cache.set(
|
|
29
|
-
|
|
30
|
-
|
|
44
|
+
cache.set(cacheKey, CYCLE);
|
|
45
|
+
const found = resolveFragment(root, keyword, ref.slice(1));
|
|
46
|
+
if (found === undefined) {
|
|
47
|
+
// A reference that resolves to nothing (a typo'd pointer or a missing
|
|
48
|
+
// anchor) was previously inlined as literal `undefined` with no trace.
|
|
49
|
+
// Record it and keep the original node so the failure is visible.
|
|
50
|
+
const fragment = ref.slice(1);
|
|
51
|
+
errors.push({
|
|
52
|
+
message: `Cannot resolve internal ${keyword} "${ref}"`,
|
|
53
|
+
path: fragment === '' || fragment.startsWith('/') ? pointerToPath(fragment) : [],
|
|
54
|
+
});
|
|
55
|
+
cache.set(cacheKey, MISSING);
|
|
56
|
+
return obj;
|
|
57
|
+
}
|
|
58
|
+
pointer = found.pointer;
|
|
59
|
+
target = resolveInternal(found.value, root, cache, origins, errors);
|
|
60
|
+
cache.set(cacheKey, { target, pointer });
|
|
31
61
|
// Stamp the inlined node with the path it was defined at (see resolveAt).
|
|
32
62
|
// First-write-wins so the deepest definition stamps before any outer ref that
|
|
33
63
|
// transitively points at the same object. Primitives can't key the map.
|
|
34
64
|
if (origins && target !== null && typeof target === 'object' && !origins.has(target)) {
|
|
35
|
-
origins.set(target, { location: '', pointer
|
|
65
|
+
origins.set(target, { location: '', pointer });
|
|
36
66
|
}
|
|
37
67
|
}
|
|
38
68
|
// Per JSON Schema 2020-12, keywords sibling to `$ref` are *not* ignored: they
|
|
@@ -40,23 +70,23 @@ const resolveInternal = (node, root, cache, origins) => {
|
|
|
40
70
|
// `allOf` (so a constraint present on both sides is never silently dropped)
|
|
41
71
|
// rather than returning the bare target. The cache always stores the
|
|
42
72
|
// sibling-free target so each occurrence applies its own siblings.
|
|
43
|
-
const siblingKeys = Object.keys(obj).filter((key) => key !==
|
|
73
|
+
const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
|
|
44
74
|
if (siblingKeys.length === 0)
|
|
45
75
|
return target;
|
|
46
76
|
const siblings = {};
|
|
47
77
|
for (const key of siblingKeys)
|
|
48
|
-
siblings
|
|
78
|
+
assignKey(siblings, key, resolveInternal(obj[key], root, cache, origins, errors));
|
|
49
79
|
const existingAllOf = Array.isArray(siblings['allOf']) ? siblings['allOf'] : [];
|
|
50
80
|
const merged = { ...siblings, allOf: [...existingAllOf, target] };
|
|
51
81
|
// Stamp the wrapper too, so a consumer mapping the resolved node back to its
|
|
52
82
|
// origin finds one for a `$ref`-with-siblings node (not only the inner target).
|
|
53
83
|
if (origins && !origins.has(merged))
|
|
54
|
-
origins.set(merged, { location: '', pointer
|
|
84
|
+
origins.set(merged, { location: '', pointer });
|
|
55
85
|
return merged;
|
|
56
86
|
}
|
|
57
87
|
const result = {};
|
|
58
88
|
for (const key of Object.keys(obj)) {
|
|
59
|
-
result
|
|
89
|
+
assignKey(result, key, resolveInternal(obj[key], root, cache, origins, errors));
|
|
60
90
|
}
|
|
61
91
|
return result;
|
|
62
92
|
};
|
|
@@ -67,6 +97,7 @@ const resolveInternal = (node, root, cache, origins) => {
|
|
|
67
97
|
*/
|
|
68
98
|
export const resolveRefs = (data, options = {}) => {
|
|
69
99
|
const origins = options.trackOrigins ? new Map() : undefined;
|
|
70
|
-
const
|
|
71
|
-
|
|
100
|
+
const errors = [];
|
|
101
|
+
const resolved = resolveInternal(data, data, new Map(), origins, errors);
|
|
102
|
+
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
72
103
|
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
|
|
3
|
+
* key hit the prototype setter. Ref resolution rebuilds every object node of a
|
|
4
|
+
* document — including remote/external content — so a plain `target[key] = value`
|
|
5
|
+
* would let a `{ "__proto__": … }` node corrupt the rebuilt object's prototype.
|
|
6
|
+
* Defining it as an own data property preserves the key verbatim instead.
|
|
7
|
+
*/
|
|
8
|
+
export declare const assignKey: (target: Record<string, unknown>, key: string, value: unknown) => void;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
|
|
3
|
+
* key hit the prototype setter. Ref resolution rebuilds every object node of a
|
|
4
|
+
* document — including remote/external content — so a plain `target[key] = value`
|
|
5
|
+
* would let a `{ "__proto__": … }` node corrupt the rebuilt object's prototype.
|
|
6
|
+
* Defining it as an own data property preserves the key verbatim instead.
|
|
7
|
+
*/
|
|
8
|
+
export const assignKey = (target, key, value) => {
|
|
9
|
+
if (key === '__proto__') {
|
|
10
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
target[key] = value;
|
|
14
|
+
}
|
|
15
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/resolve-refs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Resolve and inline JSON Schema / OpenAPI $refs — internal, cross-file, and remote — with session caching and a default-deny SSRF guard.",
|
|
5
5
|
"module": "./dist/index.js",
|
|
6
6
|
"type": "module",
|