@amritk/resolve-refs 0.4.1 → 0.4.3
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/LICENSE +21 -0
- package/dist/get-by-pointer.js +29 -49
- package/dist/index.js +12 -4
- package/dist/is-private-host.js +112 -158
- package/dist/reference.js +50 -76
- package/dist/resolve-refs-from-file.js +350 -507
- package/dist/resolve-refs.js +114 -184
- package/dist/resource-registry.js +125 -170
- package/dist/safe-assign.js +9 -14
- package/package.json +4 -4
|
@@ -1,544 +1,387 @@
|
|
|
1
|
-
import { readFileSync } from
|
|
2
|
-
import { dirname, resolve as resolvePath } from
|
|
3
|
-
import { isPrivateHost } from
|
|
4
|
-
import { readReference, resolveFragment } from
|
|
5
|
-
import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE
|
|
6
|
-
import { assignKey } from
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
// hoisting the target into `$defs` when it lives in another file) instead of
|
|
10
|
-
// recursing forever.
|
|
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']);
|
|
14
|
-
// --- Document location helpers ---------------------------------------------
|
|
15
|
-
//
|
|
16
|
-
// A "location" is the absolute identity of a document: either an absolute file
|
|
17
|
-
// path or an absolute http(s) URL. Refs are resolved relative to the location
|
|
18
|
-
// of the document they appear in, so a relative ref inside a remote document
|
|
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).
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve as resolvePath } from "node:path";
|
|
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";
|
|
6
|
+
import { assignKey } from "./safe-assign.js";
|
|
7
|
+
const CYCLE = /* @__PURE__ */ Symbol("cycle");
|
|
8
|
+
const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
|
|
22
9
|
const isRemote = (location) => /^https?:\/\//i.test(location);
|
|
23
|
-
/** Resolves the location of `ref` (its file/URL part) relative to `base`. */
|
|
24
10
|
const joinLocation = (base, ref) => {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
11
|
+
if (isRemote(ref))
|
|
12
|
+
return ref;
|
|
13
|
+
if (isRemote(base))
|
|
14
|
+
return new URL(ref, base).href;
|
|
15
|
+
return resolvePath(dirname(base), ref);
|
|
30
16
|
};
|
|
31
|
-
/** Splits a `$ref` into its document part and its fragment (pointer or anchor name). */
|
|
32
17
|
const splitRef = (ref) => {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
18
|
+
const hashIdx = ref.indexOf("#");
|
|
19
|
+
return {
|
|
20
|
+
filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
|
|
21
|
+
fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
|
|
22
|
+
};
|
|
38
23
|
};
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
// resolve passes — they can change on disk during a long-lived session (e.g.
|
|
44
|
-
// an editor/LSP), so each pass re-reads them. Remote documents are assumed
|
|
45
|
-
// stable for the session; call `clearRemoteCache()` to drop them, or pass
|
|
46
|
-
// `cache: false` to bypass the session cache for a single call.
|
|
47
|
-
const remoteCache = new Map();
|
|
48
|
-
// In-flight remote loads, keyed by location. Two resolve passes that start at
|
|
49
|
-
// the same time and reach the same URL share a single fetch instead of racing
|
|
50
|
-
// two requests; whichever arrives first installs the promise, the rest await it.
|
|
51
|
-
const inFlight = new Map();
|
|
52
|
-
/** Drops every cached remote document. Mainly useful for tests/long sessions. */
|
|
53
|
-
export const clearRemoteCache = () => {
|
|
54
|
-
remoteCache.clear();
|
|
24
|
+
const remoteCache = /* @__PURE__ */ new Map();
|
|
25
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
26
|
+
const clearRemoteCache = () => {
|
|
27
|
+
remoteCache.clear();
|
|
55
28
|
};
|
|
56
|
-
// Cap on redirect hops before we give up — generous enough for real services,
|
|
57
|
-
// low enough to stop a redirect loop from spinning forever.
|
|
58
29
|
const MAX_REDIRECTS = 5;
|
|
59
|
-
|
|
60
|
-
const FETCH_TIMEOUT_MS = 30_000;
|
|
61
|
-
/** Refuse to buffer a remote document larger than this (bytes) to bound memory. */
|
|
30
|
+
const FETCH_TIMEOUT_MS = 3e4;
|
|
62
31
|
const MAX_REMOTE_BYTES = 16 * 1024 * 1024;
|
|
63
|
-
/**
|
|
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
|
|
66
|
-
* is caught while streaming so a chunked response can't exhaust memory either.
|
|
67
|
-
*/
|
|
68
32
|
const readCapped = async (response, maxBytes) => {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
33
|
+
const declared = Number(response.headers.get("content-length"));
|
|
34
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
35
|
+
throw new Error(`remote document exceeds ${maxBytes} bytes`);
|
|
36
|
+
}
|
|
37
|
+
const body = response.body;
|
|
38
|
+
if (!body)
|
|
39
|
+
return response.text();
|
|
40
|
+
const decoder = new TextDecoder();
|
|
41
|
+
let text = "";
|
|
42
|
+
let total = 0;
|
|
43
|
+
for await (const chunk of body) {
|
|
44
|
+
total += chunk.byteLength;
|
|
45
|
+
if (total > maxBytes)
|
|
46
|
+
throw new Error(`remote document exceeds ${maxBytes} bytes`);
|
|
47
|
+
text += decoder.decode(chunk, { stream: true });
|
|
48
|
+
}
|
|
49
|
+
return text + decoder.decode();
|
|
86
50
|
};
|
|
87
|
-
/** The caller-supplied headers for `url`, if any. */
|
|
88
51
|
const headersFor = (url, options) => {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
52
|
+
if (options.headers === void 0)
|
|
53
|
+
return void 0;
|
|
54
|
+
return typeof options.headers === "function" ? options.headers(url) : options.headers;
|
|
92
55
|
};
|
|
93
|
-
/**
|
|
94
|
-
* Fetches and parses a remote document, following redirects manually so the
|
|
95
|
-
* SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
|
|
96
|
-
* which would let an allow-listed public URL bounce to a private/loopback
|
|
97
|
-
* address (e.g. the `169.254.169.254` metadata endpoint) — so we set
|
|
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.
|
|
101
|
-
*/
|
|
102
56
|
const fetchRemote = async (location, options) => {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
if (!response.ok)
|
|
128
|
-
throw new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
129
|
-
const parse = options.parse ?? ((c) => JSON.parse(c));
|
|
130
|
-
// Parse against the original request location so the caller's format sniffing
|
|
131
|
-
// (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
|
|
132
|
-
return parse(await readCapped(response, maxBytes), location);
|
|
57
|
+
const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
|
|
58
|
+
const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
|
|
59
|
+
const maxBytes = options.maxBytes ?? MAX_REMOTE_BYTES;
|
|
60
|
+
const doFetch = options.fetch ?? fetch;
|
|
61
|
+
const origin = new URL(location).origin;
|
|
62
|
+
let current = location;
|
|
63
|
+
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
64
|
+
const reason = denialReason(current, options);
|
|
65
|
+
if (reason !== null)
|
|
66
|
+
throw new Error(`refusing to follow redirect (${reason}): ${current}`);
|
|
67
|
+
const headers = new URL(current).origin === origin ? headersFor(location, options) : void 0;
|
|
68
|
+
const response = await doFetch(current, {
|
|
69
|
+
redirect: "manual",
|
|
70
|
+
// Cap the wait for a response so a stalling host can't hang resolution forever.
|
|
71
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
72
|
+
...headers !== void 0 ? { headers } : {}
|
|
73
|
+
});
|
|
74
|
+
if (response.status >= 300 && response.status < 400) {
|
|
75
|
+
const next = response.headers.get("location");
|
|
76
|
+
if (!next)
|
|
77
|
+
throw new Error(`HTTP ${response.status} redirect with no Location header`);
|
|
78
|
+
current = new URL(next, current).href;
|
|
79
|
+
continue;
|
|
133
80
|
}
|
|
134
|
-
|
|
81
|
+
if (!response.ok)
|
|
82
|
+
throw new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
83
|
+
const parse = options.parse ?? ((c) => JSON.parse(c));
|
|
84
|
+
return parse(await readCapped(response, maxBytes), location);
|
|
85
|
+
}
|
|
86
|
+
throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
|
|
135
87
|
};
|
|
136
|
-
/** Returns why a remote location may not be fetched, or `null` if it is allowed. */
|
|
137
88
|
const denialReason = (location, options) => {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
return allow.includes(url.host) ? null : 'host is not in the allow-list';
|
|
158
|
-
}
|
|
159
|
-
if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
|
|
160
|
-
return 'host resolves to a private or loopback address (set allowPrivateHosts to permit)';
|
|
161
|
-
}
|
|
162
|
-
return null;
|
|
89
|
+
if (options.remote === false)
|
|
90
|
+
return "remote $ref resolution is disabled";
|
|
91
|
+
let url;
|
|
92
|
+
try {
|
|
93
|
+
url = new URL(location);
|
|
94
|
+
} catch {
|
|
95
|
+
return "the URL is invalid";
|
|
96
|
+
}
|
|
97
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
98
|
+
return `unsupported URL protocol "${url.protocol}" (only http and https are allowed)`;
|
|
99
|
+
}
|
|
100
|
+
const allow = options.allowedHosts;
|
|
101
|
+
if (allow && allow.length > 0) {
|
|
102
|
+
return allow.includes(url.host) ? null : "host is not in the allow-list";
|
|
103
|
+
}
|
|
104
|
+
if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
|
|
105
|
+
return "host resolves to a private or loopback address (set allowPrivateHosts to permit)";
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
163
108
|
};
|
|
164
|
-
/**
|
|
165
|
-
* Loads a document into `docCache`, fetching/reading it if needed. Remote
|
|
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.
|
|
170
|
-
*/
|
|
171
109
|
const loadDoc = async (location, docCache, options, errors) => {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const reason = denialReason(location, options);
|
|
181
|
-
if (reason !== null) {
|
|
182
|
-
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] });
|
|
183
|
-
docCache.set(location, {});
|
|
184
|
-
return false;
|
|
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
|
-
}
|
|
205
|
-
// Coalesce concurrent loads of the same URL onto one in-flight request; the
|
|
206
|
-
// owner (first caller) clears the slot once it settles.
|
|
207
|
-
let pending = inFlight.get(location);
|
|
208
|
-
const owner = pending === undefined;
|
|
209
|
-
if (pending === undefined) {
|
|
210
|
-
pending = fetchRemote(location, options);
|
|
211
|
-
inFlight.set(location, pending);
|
|
212
|
-
}
|
|
213
|
-
try {
|
|
214
|
-
const doc = await pending;
|
|
215
|
-
remoteCache.set(location, doc);
|
|
216
|
-
docCache.set(location, doc);
|
|
217
|
-
return true;
|
|
218
|
-
}
|
|
219
|
-
catch (err) {
|
|
220
|
-
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
|
|
221
|
-
docCache.set(location, {});
|
|
222
|
-
return false;
|
|
223
|
-
}
|
|
224
|
-
finally {
|
|
225
|
-
if (owner)
|
|
226
|
-
inFlight.delete(location);
|
|
227
|
-
}
|
|
110
|
+
if (docCache.has(location))
|
|
111
|
+
return true;
|
|
112
|
+
if (isRemote(location)) {
|
|
113
|
+
const reason = denialReason(location, options);
|
|
114
|
+
if (reason !== null) {
|
|
115
|
+
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] });
|
|
116
|
+
docCache.set(location, {});
|
|
117
|
+
return false;
|
|
228
118
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
119
|
+
const useSessionCache = options.cache !== false;
|
|
120
|
+
if (useSessionCache && remoteCache.has(location)) {
|
|
121
|
+
docCache.set(location, remoteCache.get(location));
|
|
122
|
+
return true;
|
|
233
123
|
}
|
|
234
|
-
|
|
235
|
-
|
|
124
|
+
if (!useSessionCache) {
|
|
125
|
+
try {
|
|
126
|
+
const doc = await fetchRemote(location, options);
|
|
127
|
+
docCache.set(location, doc);
|
|
128
|
+
return true;
|
|
129
|
+
} catch (err) {
|
|
130
|
+
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
|
|
236
131
|
docCache.set(location, {});
|
|
237
132
|
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
let pending = inFlight.get(location);
|
|
136
|
+
const owner = pending === void 0;
|
|
137
|
+
if (pending === void 0) {
|
|
138
|
+
pending = fetchRemote(location, options);
|
|
139
|
+
inFlight.set(location, pending);
|
|
238
140
|
}
|
|
141
|
+
try {
|
|
142
|
+
const doc = await pending;
|
|
143
|
+
remoteCache.set(location, doc);
|
|
144
|
+
docCache.set(location, doc);
|
|
145
|
+
return true;
|
|
146
|
+
} catch (err) {
|
|
147
|
+
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] });
|
|
148
|
+
docCache.set(location, {});
|
|
149
|
+
return false;
|
|
150
|
+
} finally {
|
|
151
|
+
if (owner)
|
|
152
|
+
inFlight.delete(location);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
const parse = options.parse ?? ((c) => JSON.parse(c));
|
|
157
|
+
docCache.set(location, parse(readFileSync(location, "utf8"), location));
|
|
158
|
+
return true;
|
|
159
|
+
} catch (err) {
|
|
160
|
+
errors.push({ message: String(err), path: [] });
|
|
161
|
+
docCache.set(location, {});
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
239
164
|
};
|
|
240
|
-
|
|
241
|
-
const
|
|
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. */
|
|
165
|
+
const escapeSegment = (segment) => segment.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
166
|
+
const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
|
|
245
167
|
const hoistName = (targetLocation, fragment, taken) => {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
for (let n = 2; taken.has(name); n++)
|
|
256
|
-
name = `${sanitized}-${n}`;
|
|
257
|
-
taken.add(name);
|
|
258
|
-
return name;
|
|
168
|
+
const fragmentTail = fragment.split("/").filter(Boolean).pop();
|
|
169
|
+
const locationTail = targetLocation.split("/").filter(Boolean).pop()?.replace(/\.[a-z0-9]+$/i, "");
|
|
170
|
+
const raw = fragmentTail || locationTail || "cycle";
|
|
171
|
+
const sanitized = raw.replace(/[^A-Za-z0-9_.-]/g, "-") || "cycle";
|
|
172
|
+
let name = sanitized;
|
|
173
|
+
for (let n = 2; taken.has(name); n++)
|
|
174
|
+
name = `${sanitized}-${n}`;
|
|
175
|
+
taken.add(name);
|
|
176
|
+
return name;
|
|
259
177
|
};
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
178
|
+
const resolveRefsFromFile = async (filename, options = {}) => {
|
|
179
|
+
const rootLocation = isRemote(filename) ? filename : resolvePath(filename);
|
|
180
|
+
const errors = [];
|
|
181
|
+
const docCache = /* @__PURE__ */ new Map();
|
|
182
|
+
if (!await loadDoc(rootLocation, docCache, options, errors)) {
|
|
183
|
+
return { resolved: {}, errors };
|
|
184
|
+
}
|
|
185
|
+
const registries = /* @__PURE__ */ new Map();
|
|
186
|
+
const registryFor = (location) => {
|
|
187
|
+
let registry = registries.get(location);
|
|
188
|
+
if (registry === void 0) {
|
|
189
|
+
registry = buildResourceRegistry(docCache.get(location), isRemote(location) ? location : SYNTHETIC_BASE);
|
|
190
|
+
registries.set(location, registry);
|
|
273
191
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
192
|
+
return registry;
|
|
193
|
+
};
|
|
194
|
+
const collectRefTargets = (node, location, base, out) => {
|
|
195
|
+
if (node === null || typeof node !== "object")
|
|
196
|
+
return;
|
|
197
|
+
if (Array.isArray(node)) {
|
|
198
|
+
for (const item of node)
|
|
199
|
+
collectRefTargets(item, location, base, out);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const obj = node;
|
|
203
|
+
const registry = registryFor(location);
|
|
204
|
+
const nodeBase = typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
|
|
205
|
+
const reference = readReference(obj);
|
|
206
|
+
if (reference && reference.keyword !== "$recursiveRef") {
|
|
207
|
+
const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
|
|
208
|
+
if (scoped === "external") {
|
|
209
|
+
const { filePart } = splitRef(reference.value);
|
|
210
|
+
if (filePart !== "")
|
|
211
|
+
out.add(filePart);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
for (const key of Object.keys(obj)) {
|
|
215
|
+
if (reference && key === reference.keyword)
|
|
216
|
+
continue;
|
|
217
|
+
collectRefTargets(obj[key], location, nodeBase, out);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
const prefetch = async () => {
|
|
221
|
+
const seen = /* @__PURE__ */ new Set([rootLocation]);
|
|
222
|
+
const queue = [rootLocation];
|
|
223
|
+
while (queue.length > 0) {
|
|
224
|
+
const location = queue.shift();
|
|
225
|
+
const out = /* @__PURE__ */ new Set();
|
|
226
|
+
collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out);
|
|
227
|
+
for (const filePart of out) {
|
|
228
|
+
const target = joinLocation(location, filePart);
|
|
229
|
+
if (seen.has(target))
|
|
230
|
+
continue;
|
|
231
|
+
seen.add(target);
|
|
232
|
+
await loadDoc(target, docCache, options, errors);
|
|
233
|
+
queue.push(target);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
await prefetch();
|
|
238
|
+
const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
|
|
239
|
+
const refCache = /* @__PURE__ */ new Map();
|
|
240
|
+
const hoists = /* @__PURE__ */ new Map();
|
|
241
|
+
const hoistTaken = /* @__PURE__ */ new Set();
|
|
242
|
+
const resolveAt = (node, baseLocation, base) => {
|
|
243
|
+
if (node === null || typeof node !== "object")
|
|
244
|
+
return node;
|
|
245
|
+
if (Array.isArray(node)) {
|
|
246
|
+
return node.map((item) => resolveAt(item, baseLocation, base));
|
|
247
|
+
}
|
|
248
|
+
const obj = node;
|
|
249
|
+
const registry = registryFor(baseLocation);
|
|
250
|
+
const nodeBase = typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
|
|
251
|
+
const reference = readReference(obj);
|
|
252
|
+
if (reference) {
|
|
253
|
+
const { keyword, value } = reference;
|
|
254
|
+
let scoped;
|
|
255
|
+
let targetLocation = baseLocation;
|
|
256
|
+
let fragment = "";
|
|
257
|
+
if (keyword === "$recursiveRef") {
|
|
258
|
+
fragment = value.startsWith("#") ? value.slice(1) : value;
|
|
259
|
+
} else {
|
|
260
|
+
const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
|
|
261
|
+
if (inScope === "external" || inScope === void 0) {
|
|
262
|
+
const parts = splitRef(value);
|
|
263
|
+
fragment = parts.fragment;
|
|
264
|
+
if (inScope === "external" && parts.filePart !== "") {
|
|
265
|
+
targetLocation = joinLocation(baseLocation, parts.filePart);
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
scoped = inScope;
|
|
293
269
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
270
|
+
}
|
|
271
|
+
const cacheKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
|
|
272
|
+
let resolved2;
|
|
273
|
+
let pointer;
|
|
274
|
+
const cached = refCache.get(cacheKey);
|
|
275
|
+
if (cached === CYCLE) {
|
|
276
|
+
let keptRef;
|
|
277
|
+
if (scoped !== void 0 && baseLocation === rootLocation) {
|
|
278
|
+
keptRef = pathToRef(scoped.pointer);
|
|
279
|
+
} else if (scoped === void 0 && targetLocation === rootLocation) {
|
|
280
|
+
keptRef = `#${fragment}`;
|
|
281
|
+
} else {
|
|
282
|
+
let name = hoists.get(cacheKey);
|
|
283
|
+
if (name === void 0) {
|
|
284
|
+
name = hoistName(targetLocation, fragment, hoistTaken);
|
|
285
|
+
hoists.set(cacheKey, name);
|
|
286
|
+
}
|
|
287
|
+
keptRef = `#/$defs/${name}`;
|
|
305
288
|
}
|
|
306
|
-
|
|
307
|
-
// alongside the referenced schema (2020-12) and may carry their own refs.
|
|
289
|
+
const kept = {};
|
|
308
290
|
for (const key of Object.keys(obj)) {
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
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();
|
|
338
|
-
const origins = options.trackOrigins ? new Map() : undefined;
|
|
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));
|
|
291
|
+
if (key === keyword)
|
|
292
|
+
continue;
|
|
293
|
+
assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase));
|
|
358
294
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
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;
|
|
295
|
+
assignKey(kept, "$ref", keptRef);
|
|
296
|
+
return kept;
|
|
297
|
+
}
|
|
298
|
+
if (cached !== void 0) {
|
|
299
|
+
resolved2 = cached.value;
|
|
300
|
+
pointer = cached.pointer;
|
|
301
|
+
} else {
|
|
302
|
+
refCache.set(cacheKey, CYCLE);
|
|
303
|
+
let found;
|
|
304
|
+
let targetBase;
|
|
305
|
+
if (scoped !== void 0) {
|
|
306
|
+
found = scoped;
|
|
307
|
+
targetBase = scoped.base;
|
|
308
|
+
} else {
|
|
309
|
+
const targetRegistry = registryFor(targetLocation);
|
|
310
|
+
const targetRoot = docCache.get(targetLocation) ?? {};
|
|
311
|
+
if (keyword === "$recursiveRef") {
|
|
312
|
+
found = resolveFragment(targetRoot, keyword, fragment);
|
|
313
|
+
targetBase = targetRegistry.rootBase;
|
|
314
|
+
} else {
|
|
315
|
+
const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
|
|
316
|
+
if (scopedFragment !== "external" && scopedFragment !== void 0) {
|
|
317
|
+
found = scopedFragment;
|
|
318
|
+
targetBase = scopedFragment.base;
|
|
319
|
+
} else {
|
|
320
|
+
found = resolveFragment(targetRoot, keyword, fragment);
|
|
321
|
+
targetBase = targetRegistry.rootBase;
|
|
504
322
|
}
|
|
505
|
-
|
|
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;
|
|
323
|
+
}
|
|
513
324
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
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);
|
|
325
|
+
pointer = found?.pointer ?? [];
|
|
326
|
+
resolved2 = resolveAt(found?.value, targetLocation, targetBase);
|
|
327
|
+
refCache.set(cacheKey, { value: resolved2, pointer });
|
|
328
|
+
if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
|
|
329
|
+
origins.set(resolved2, { location: targetLocation, pointer });
|
|
535
330
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
331
|
+
}
|
|
332
|
+
const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
|
|
333
|
+
if (siblingKeys.length === 0)
|
|
334
|
+
return resolved2;
|
|
335
|
+
const siblings = {};
|
|
336
|
+
for (const key of siblingKeys)
|
|
337
|
+
assignKey(siblings, key, resolveAt(obj[key], baseLocation, nodeBase));
|
|
338
|
+
if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
|
|
339
|
+
if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
|
|
340
|
+
const overridden = {};
|
|
341
|
+
for (const key of Object.keys(resolved2)) {
|
|
342
|
+
assignKey(overridden, key, resolved2[key]);
|
|
343
|
+
}
|
|
344
|
+
for (const key of Object.keys(siblings))
|
|
345
|
+
assignKey(overridden, key, siblings[key]);
|
|
346
|
+
if (origins && !origins.has(overridden))
|
|
347
|
+
origins.set(overridden, { location: targetLocation, pointer });
|
|
348
|
+
return overridden;
|
|
541
349
|
}
|
|
350
|
+
return resolved2;
|
|
351
|
+
}
|
|
352
|
+
const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
|
|
353
|
+
const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
|
|
354
|
+
if (origins && !origins.has(merged))
|
|
355
|
+
origins.set(merged, { location: targetLocation, pointer });
|
|
356
|
+
return merged;
|
|
542
357
|
}
|
|
543
|
-
|
|
358
|
+
const result = {};
|
|
359
|
+
for (const key of Object.keys(obj)) {
|
|
360
|
+
assignKey(result, key, resolveAt(obj[key], baseLocation, nodeBase));
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
};
|
|
364
|
+
const rootRegistry = registryFor(rootLocation);
|
|
365
|
+
const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase);
|
|
366
|
+
if (hoists.size > 0) {
|
|
367
|
+
if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
|
|
368
|
+
const container = resolved;
|
|
369
|
+
const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
|
|
370
|
+
for (const [cacheKey, name] of hoists) {
|
|
371
|
+
const cached = refCache.get(cacheKey);
|
|
372
|
+
assignKey(defs, name, cached !== void 0 && cached !== CYCLE ? cached.value ?? {} : {});
|
|
373
|
+
}
|
|
374
|
+
assignKey(container, "$defs", defs);
|
|
375
|
+
} else {
|
|
376
|
+
errors.push({
|
|
377
|
+
message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
|
|
378
|
+
path: []
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
383
|
+
};
|
|
384
|
+
export {
|
|
385
|
+
clearRemoteCache,
|
|
386
|
+
resolveRefsFromFile
|
|
544
387
|
};
|