@amritk/resolve-refs 0.9.0 → 0.11.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/AI.md CHANGED
@@ -26,8 +26,8 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
26
26
  ## Gotchas — where agents fail
27
27
 
28
28
  1. **`resolveRefs` is in-memory only.** It does NOT load other files/URLs —
29
- external refs stay in place and are pushed to `errors` (the ref becomes `{}`).
30
- Use `resolveRefsFromFile` for cross-file/remote.
29
+ external refs stay in place and are pushed to `errors` (the `{ $ref }` node is
30
+ kept as written, not inlined). Use `resolveRefsFromFile` for cross-file/remote.
31
31
  2. **Errors are collected, never thrown.** A missing file, refused host, or bad
32
32
  URL lands on `result.errors` while the rest still resolves. Always check it.
33
33
  Each error's `path` is where the offending reference was written in the
@@ -39,7 +39,9 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
39
39
  `169.254.169.254` / metadata hosts by name (`metadata.google.internal`,
40
40
  `*.internal`) are refused unless `allowPrivateHosts: true` or an explicit
41
41
  `allowedHosts` entry. Hostnames are also resolved and refused when they point
42
- at a private address (`verifyDns: false` opts out).
42
+ at a private address, and the connection dials only the addresses that were
43
+ checked, so a DNS-rebinding record cannot slip past (`verifyDns: false` opts
44
+ out; a custom `fetch` gets the check as a pre-flight only).
43
45
  4. **Local `$ref`s are confined to the root document's directory.** A
44
46
  `{"$ref": "../common/schemas.json"}` is refused by default — pass
45
47
  `allowedRoots: ['./specs']` (or whatever contains both files) to allow it.
package/README.md CHANGED
@@ -72,6 +72,7 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
72
72
  | `parse` | `JSON.parse` | Custom content parser (e.g. YAML-aware). |
73
73
  | `rootDocument` | — | The root's already-parsed value. The named file is then neither read nor parsed; its location still anchors relative refs, `allowedRoots`, and `origins`. The value is only read, never written or aliased into the result. |
74
74
  | `trackOrigins` | `false` | Record a per-node origin map on the result. |
75
+ | `bundle` | `false` | Bundle instead of inlining: hoist each target from another document into the root's `$defs` once and point its refs there, keeping refs into the root as written. The output is one document with only internal refs — what a code generator wants, since a shared schema stays one definition instead of a copy at every use. A document with an absolute `$id` is embedded whole with its `$id`, and refs to anything in an embedded resource name it by that URI; a document with a relative `$id` is inlined. |
75
76
 
76
77
  Errors (a missing file, a refused host, a refused path, a bad URL, a document too
77
78
  deeply nested) are collected on `result.errors` rather than thrown; the
@@ -101,20 +102,23 @@ The remote path has always been default-deny; the local path now matches it.
101
102
  planted in the tree cannot be used to escape it. The root document itself is
102
103
  exempt: it is the file you explicitly named.
103
104
  - **The session cache is credential-scoped.** Its key covers the request headers,
104
- the `fetch`/`parse` callbacks, and the transfer limits, so a document fetched
105
+ the `fetch`/`parse` callbacks, the transfer limits, and the host guards
106
+ (`allowPrivateHosts`, `allowedHosts`, `verifyDns`), so a document fetched
105
107
  with one tenant's token is invisible to a call carrying different (or no)
106
108
  credentials — and no caller inherits another's `fetch`. In-flight coalescing
107
109
  uses the same key.
108
110
  - **The SSRF guard runs in two passes.** `isPrivateHost` is synchronous and reads
109
111
  only the URL (every IPv4 encoding, IPv4-in-IPv6 embeddings, ULA/link-local/
110
- site-local IPv6, plus a name denylist for cloud-metadata endpoints).
111
- `assertPublicHost` then resolves the name and refuses it when any address is
112
- non-public. Both run on every redirect hop.
113
- - **Known residual gap: DNS rebinding.** A record that changes between the check
114
- and the connection still wins; closing that requires pinning the socket to the
115
- verified address, which Node's `fetch` does not let us do. What the DNS pass
116
- buys is that a name *statically* pointing at a private address is refused —
117
- which is the case that actually shows up.
112
+ site-local IPv6, plus a name denylist for cloud-metadata endpoints). The name
113
+ is then resolved and refused when any address is non-public. Both run on every
114
+ redirect hop.
115
+ - **The connection dials the addresses that were checked.** The DNS pass runs
116
+ inside the socket's own lookup, so the name is resolved once per connection and
117
+ a rebinding record (public for the check, `127.0.0.1` for the connect) has no
118
+ second answer to give. `Host`, SNI, and certificate checks still use the name.
119
+ A custom `fetch` makes its own connections and cannot be pinned: it gets the
120
+ check as a pre-flight only, which stops a name that statically points at a
121
+ private address but not one that rebinds.
118
122
  - **A resolve is bounded** by `maxDocuments`, `totalTimeoutMs`, and `maxDepth`, so
119
123
  a hostile document cannot use the resolver as an egress amplifier, hold the
120
124
  process for hours, or crash it with nesting.
@@ -192,20 +196,12 @@ recursive cycles intact, and records a diagnostic for every external ref. The
192
196
  registry, no scoping, no diagnostics — and re-resolves each ref on every
193
197
  encounter, so the gap is the production resolver's *total* per-call cost against
194
198
  the cheapest thing that produces the same inlined shape. Both are asserted to
195
- produce byte-identical output before either is timed. Medians of three runs on each runtime, one machine (Linux x64, a 4-vCPU cloud
196
- box, Bun 1.4.0 and Node 26.8.1 — your hardware will differ, run `bun run bench`
197
- or `bun run bench:node` yourself):
198
-
199
- | schema | Bun: cached | Bun: naive | Bun speedup | Node: cached | Node: naive | Node speedup |
200
- |:---|---:|---:|---:|---:|---:|---:|
201
- | chain (40 `$ref` → `$ref` links) | ~4.6k ops/s | ~1.1k ops/s | **~4.1×** | ~4.7k ops/s | ~1.1k ops/s | **~4.1×** |
202
- | reuse-heavy (50 refs → 1 def) | ~6.9k ops/s | ~11k ops/s | ~0.62× | ~6.6k ops/s | ~10k ops/s | ~0.66× |
203
- | cyclic tree | ~50k ops/s | ~183k ops/s | ~0.27× | ~58k ops/s | ~184k ops/s | ~0.31× |
204
- | wide-distinct (60 defs, each used once) | ~3.7k ops/s | ~9.5k ops/s | ~0.39× | ~3.4k ops/s | ~9.0k ops/s | ~0.38× |
205
-
206
- The two engines agree on every row to within a few percent, which is what you
207
- would expect from a resolver whose cost is one document walk rather than a hot
208
- inner loop.
199
+ produce byte-identical output before either is timed. Run it with `bun run bench`
200
+ (Bun) or `bun run bench:node` (Node); the shapes are a long `$ref` → `$ref`
201
+ chain, many refs reusing one definition, a cyclic tree, and many distinct
202
+ definitions each used once. Bun and Node land close together on every shape,
203
+ which is what you would expect from a resolver whose cost is one document walk
204
+ rather than a hot inner loop.
209
205
 
210
206
  Memoization overtakes the naive walk only on the **chain** shape, where a long
211
207
  indirection path is expensive to re-resolve and the cache collapses it to one
@@ -215,10 +211,9 @@ the bare inliner is faster — these are small schemas where that one document w
215
211
  dominates. The takeaway is practical: the resolver's per-call floor is a full
216
212
  document traversal, so in a hot loop resolve a document **once** and reuse the
217
213
  result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct`
218
- rows are kept in the table precisely to show that trade honestly rather than
214
+ shapes are kept in the bench precisely to show that trade honestly rather than
219
215
  cherry-picking the one shape the cache wins.
220
216
 
221
217
  Opting into `trackOrigins` (which records where each inlined value came from)
222
- costs nothing measurable on these small schemas, on either runtime: the four
223
- rows land between −9% and +7% on Bun and between −3% and +1% on Node, straddling
224
- zero in both cases, which is run-to-run noise rather than a price.
218
+ costs nothing measurable on these small schemas, on either runtime: the
219
+ differences straddle zero, which is run-to-run noise rather than a price.
@@ -1,18 +1,10 @@
1
- /**
2
- * Resolves a hostname to the addresses it points at. Only the `address` is used
3
- * — the shape matches `dns.lookup(host, { all: true })` so the real resolver
4
- * drops straight in. Exposed as a parameter so the guard can be exercised
5
- * against known records without a live resolver, and so a caller that resolves
6
- * names some other way (a custom DoH client) can supply it.
7
- */
8
- export type HostLookup = (hostname: string) => Promise<{
9
- address: string;
10
- }[]>;
1
+ import { type HostLookup } from './resolve-public-host.js';
2
+ export type { HostLookup } from './resolve-public-host.js';
11
3
  /**
12
4
  * The name-resolving half of the SSRF guard: resolves `hostname` and rejects if
13
5
  * **any** address it resolves to is non-public. {@link isPrivateHost} only reads
14
6
  * the URL, so `127.0.0.1.nip.io` — a public-looking name whose A record is
15
- * `127.0.0.1` — sails past it. This closes that hole for the fetch path.
7
+ * `127.0.0.1` — sails past it.
16
8
  *
17
9
  * It is deliberately a separate async function rather than a change to
18
10
  * `isPrivateHost`: that predicate is synchronous, pure, and exported (the CLI
@@ -25,13 +17,11 @@ export type HostLookup = (hostname: string) => Promise<{
25
17
  * the resolving (so names do not resolve locally) should allow-list the host or
26
18
  * pass `verifyDns: false`.
27
19
  *
28
- * **Residual gap — DNS rebinding is narrowed, not closed.** Between this check
29
- * and the connection, the record can change to a private address (the classic
30
- * TOCTOU rebind). Truly closing it means pinning the socket to the address we
31
- * just verified, and Node's `fetch` offers no seam for that. What this does buy:
32
- * a name that *statically* points at a private address — the overwhelmingly
33
- * common case, every `nip.io`-style trick included — is refused, and an attacker
34
- * is pushed to a short-TTL rebinding record instead of a plain A record.
20
+ * **A check on its own does not stop DNS rebinding.** Anything that resolves the
21
+ * name again before connecting can be handed a different, private answer.
22
+ * `resolveRefsFromFile` does not rely on this function for its own fetches: it
23
+ * dials the very addresses it verified. Use this as a pre-check only where the
24
+ * connection is made by code you cannot pin, and treat it as advisory there.
35
25
  *
36
26
  * Rejects with an `Error` explaining the refusal; resolves when the host looks
37
27
  * public.
@@ -1,27 +1,6 @@
1
- import { lookup } from "node:dns/promises";
2
- import { isPrivateHost } from "./is-private-host.js";
3
- const defaultLookup = (hostname) => lookup(hostname, { all: true, verbatim: true });
4
- const assertPublicHost = async (hostname, lookupHost = defaultLookup) => {
5
- const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase();
6
- if (host === "")
7
- throw new Error("host is empty");
8
- if (isPrivateHost(host)) {
9
- throw new Error(`host "${hostname}" is a private or loopback address (set allowPrivateHosts to permit)`);
10
- }
11
- let addresses;
12
- try {
13
- addresses = await lookupHost(host);
14
- } catch (err) {
15
- throw new Error(`cannot verify that host "${hostname}" is public: DNS lookup failed (${String(err)}) (allow-list the host or set verifyDns: false to skip this check)`);
16
- }
17
- if (addresses.length === 0) {
18
- throw new Error(`cannot verify that host "${hostname}" is public: DNS returned no addresses (allow-list the host or set verifyDns: false to skip this check)`);
19
- }
20
- for (const { address } of addresses) {
21
- if (isPrivateHost(address)) {
22
- throw new Error(`host "${hostname}" resolves to the non-public address ${address} (set allowPrivateHosts to permit)`);
23
- }
24
- }
1
+ import { resolvePublicHost } from "./resolve-public-host.js";
2
+ const assertPublicHost = async (hostname, lookupHost) => {
3
+ await resolvePublicHost(hostname, lookupHost);
25
4
  };
26
5
  export {
27
6
  assertPublicHost
@@ -0,0 +1,30 @@
1
+ import type { PublicAddress } from './resolve-public-host.js';
2
+ /** The subset of `fetch`'s `init` that remote `$ref` resolution sends. */
3
+ export type PinnedFetchInit = {
4
+ redirect: 'manual';
5
+ signal: AbortSignal;
6
+ headers?: Record<string, string>;
7
+ };
8
+ /** Resolves a hostname to the only addresses the connection may dial. */
9
+ export type ResolveHost = (hostname: string) => Promise<PublicAddress[]>;
10
+ /**
11
+ * A `fetch` for remote `$ref`s that dials only the addresses `resolveHost`
12
+ * returns, closing the DNS-rebinding hole a check-then-`fetch` guard leaves.
13
+ *
14
+ * Checking a name and then calling `fetch` resolves it twice: once for the
15
+ * check and again inside the socket. A record with a short TTL can answer the
16
+ * first with a public address and the second with `127.0.0.1` or
17
+ * `169.254.169.254`. Node's `fetch` offers no seam to pin the address, but
18
+ * `http.request` does: its `lookup` option *is* the socket's resolver, so
19
+ * running the guard there makes the verified addresses the dialed ones. The
20
+ * host name itself is still what goes on the wire, so `Host`, SNI, and
21
+ * certificate verification are unchanged.
22
+ *
23
+ * `agent: false` gives every request its own socket. A shared agent could hand
24
+ * back a keep-alive socket some other code opened to the same `host:port`
25
+ * without this guard — connected to wherever the name pointed then.
26
+ *
27
+ * Bodies are requested uncompressed (`accept-encoding: identity`) because,
28
+ * unlike `fetch`, `http.request` does not decode them.
29
+ */
30
+ export declare const createPinnedFetch: (resolveHost: ResolveHost) => (url: string, init: PinnedFetchInit) => Promise<Response>;
@@ -0,0 +1,76 @@
1
+ import { request as httpRequest } from "node:http";
2
+ import { request as httpsRequest } from "node:https";
3
+ import { Readable } from "node:stream";
4
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([101, 204, 205, 304]);
5
+ const wantedFamily = (family) => {
6
+ if (family === 4 || family === "IPv4")
7
+ return 4;
8
+ if (family === 6 || family === "IPv6")
9
+ return 6;
10
+ return void 0;
11
+ };
12
+ const toResponse = (message) => {
13
+ const headers = new Headers();
14
+ for (let i = 0; i + 1 < message.rawHeaders.length; i += 2) {
15
+ headers.append(message.rawHeaders[i], message.rawHeaders[i + 1]);
16
+ }
17
+ const status = message.statusCode ?? 0;
18
+ if (NULL_BODY_STATUSES.has(status)) {
19
+ message.resume();
20
+ return new Response(null, { status, statusText: message.statusMessage ?? "", headers });
21
+ }
22
+ return new Response(Readable.toWeb(message), {
23
+ status,
24
+ statusText: message.statusMessage ?? "",
25
+ headers
26
+ });
27
+ };
28
+ const createPinnedFetch = (resolveHost) => (url, init) => {
29
+ const target = new URL(url);
30
+ if (target.username !== "" || target.password !== "") {
31
+ return Promise.reject(new TypeError(`refusing a URL that includes credentials: ${target.host}`));
32
+ }
33
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
34
+ const lookup = (hostname, options, callback) => {
35
+ resolveHost(hostname).then((addresses) => {
36
+ const family = wantedFamily(options.family);
37
+ const usable = family === void 0 ? addresses : addresses.filter((entry) => entry.family === family);
38
+ const first = usable[0];
39
+ if (first === void 0) {
40
+ callback(new Error(`host "${hostname}" has no IPv${family} address`), "", 0);
41
+ return;
42
+ }
43
+ if (options.all)
44
+ callback(null, usable);
45
+ else
46
+ callback(null, first.address, first.family);
47
+ }, (err) => callback(err instanceof Error ? err : new Error(String(err)), "", 0));
48
+ };
49
+ return new Promise((resolve, reject) => {
50
+ const request = send({
51
+ protocol: target.protocol,
52
+ // IP literals never reach `lookup` (the socket dials them directly);
53
+ // `denialReason` has already vetted those by syntax.
54
+ host: target.hostname.replace(/^\[|\]$/g, ""),
55
+ port: target.port === "" ? void 0 : target.port,
56
+ path: `${target.pathname}${target.search}`,
57
+ method: "GET",
58
+ headers: { accept: "*/*", ...init.headers, "accept-encoding": "identity" },
59
+ lookup,
60
+ agent: false,
61
+ signal: init.signal
62
+ }, (message) => {
63
+ try {
64
+ resolve(toResponse(message));
65
+ } catch (err) {
66
+ message.destroy();
67
+ reject(err);
68
+ }
69
+ });
70
+ request.on("error", reject);
71
+ request.end();
72
+ });
73
+ };
74
+ export {
75
+ createPinnedFetch
76
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Resolves a hostname to the addresses it points at. Only the `address` is used
3
+ * — the shape matches `dns.lookup(host, { all: true })` so the real resolver
4
+ * drops straight in. Exposed as a parameter so the guard can be exercised
5
+ * against known records without a live resolver, and so a caller that resolves
6
+ * names some other way (a custom DoH client) can supply it.
7
+ */
8
+ export type HostLookup = (hostname: string) => Promise<{
9
+ address: string;
10
+ }[]>;
11
+ /** An address that passed the guard, with the family a socket needs to dial it. */
12
+ export type PublicAddress = {
13
+ address: string;
14
+ family: 4 | 6;
15
+ };
16
+ /**
17
+ * Resolves `hostname` once and returns its addresses, rejecting if **any** of
18
+ * them is non-public. Returning the addresses (rather than a yes/no) is the
19
+ * point: a caller that dials exactly these — see `pinned-fetch` — closes the
20
+ * DNS-rebinding window, because there is no second lookup for the record to
21
+ * change under.
22
+ *
23
+ * {@link isPrivateHost} runs first so an IP literal or a denied name never
24
+ * costs a resolver round-trip, and so the refusal reads the same either way.
25
+ *
26
+ * **Fails closed.** A lookup that errors, returns nothing, or returns something
27
+ * that is not an IP address is rejected: we cannot show the host is public.
28
+ */
29
+ export declare const resolvePublicHost: (hostname: string, lookupHost?: HostLookup) => Promise<PublicAddress[]>;
@@ -0,0 +1,34 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+ import { isPrivateHost } from "./is-private-host.js";
4
+ const defaultLookup = (hostname) => lookup(hostname, { all: true, verbatim: true });
5
+ const resolvePublicHost = async (hostname, lookupHost = defaultLookup) => {
6
+ const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "").toLowerCase();
7
+ if (host === "")
8
+ throw new Error("host is empty");
9
+ if (isPrivateHost(host)) {
10
+ throw new Error(`host "${hostname}" is a private or loopback address (set allowPrivateHosts to permit)`);
11
+ }
12
+ let answers;
13
+ try {
14
+ answers = await lookupHost(host);
15
+ } catch (err) {
16
+ throw new Error(`cannot verify that host "${hostname}" is public: DNS lookup failed (${String(err)}) (allow-list the host or set verifyDns: false to skip this check)`);
17
+ }
18
+ if (answers.length === 0) {
19
+ throw new Error(`cannot verify that host "${hostname}" is public: DNS returned no addresses (allow-list the host or set verifyDns: false to skip this check)`);
20
+ }
21
+ return answers.map(({ address }) => {
22
+ const family = isIP(address);
23
+ if (family !== 4 && family !== 6) {
24
+ throw new Error(`cannot verify that host "${hostname}" is public: DNS returned "${address}", not an IP address`);
25
+ }
26
+ if (isPrivateHost(address)) {
27
+ throw new Error(`host "${hostname}" resolves to the non-public address ${address} (set allowPrivateHosts to permit)`);
28
+ }
29
+ return { address, family };
30
+ });
31
+ };
32
+ export {
33
+ resolvePublicHost
34
+ };
@@ -4,11 +4,14 @@ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "
4
4
  import { assertPublicHost } from "./assert-public-host.js";
5
5
  import { childRole } from "./child-role.js";
6
6
  import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
7
+ import { getByPointer } from "./get-by-pointer.js";
7
8
  import { isContainedPath } from "./is-contained-path.js";
8
9
  import { isPrivateHost } from "./is-private-host.js";
9
10
  import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
11
+ import { createPinnedFetch } from "./pinned-fetch.js";
10
12
  import { refPathIndex } from "./ref-path-index.js";
11
13
  import { ANNOTATION_ONLY_SIBLINGS, readReference, resolveFragment } from "./reference.js";
14
+ import { resolvePublicHost } from "./resolve-public-host.js";
12
15
  import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE } from "./resource-registry.js";
13
16
  import { roleAtPath } from "./role-at-path.js";
14
17
  import { assignKey } from "./safe-assign.js";
@@ -131,18 +134,20 @@ const fetchScope = (location, options) => [
131
134
  [...options.allowedHosts ?? []].sort().join(",")
132
135
  ].join("|");
133
136
  const cacheKeyFor = (location, options) => `${fetchScope(location, options)}${SCOPE_SEPARATOR}${location}`;
137
+ const pinnedPublicFetch = createPinnedFetch((hostname) => resolvePublicHost(hostname));
134
138
  const fetchRemote = async (location, options, deadline) => {
135
139
  const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
136
140
  const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
137
141
  const maxBytes = options.maxBytes ?? MAX_REMOTE_BYTES;
138
- const doFetch = options.fetch ?? fetch;
142
+ const verifyDns = needsDnsVerification(options);
143
+ const doFetch = options.fetch ?? (verifyDns ? pinnedPublicFetch : fetch);
139
144
  const origin = new URL(location).origin;
140
145
  let current = location;
141
146
  for (let hop = 0; hop <= maxRedirects; hop++) {
142
147
  const reason = denialReason(current, options);
143
148
  if (reason !== null)
144
149
  throw new Error(`refusing to follow redirect (${reason}): ${current}`);
145
- if (needsDnsVerification(options))
150
+ if (verifyDns && options.fetch !== void 0)
146
151
  await assertPublicHost(new URL(current).hostname);
147
152
  const headers = new URL(current).origin === origin ? headersFor(location, options) : void 0;
148
153
  const response = await doFetch(current, {
@@ -155,13 +160,16 @@ const fetchRemote = async (location, options, deadline) => {
155
160
  });
156
161
  if (response.status >= 300 && response.status < 400) {
157
162
  const next = response.headers.get("location");
163
+ await response.body?.cancel();
158
164
  if (!next)
159
165
  throw new Error(`HTTP ${response.status} redirect with no Location header`);
160
166
  current = new URL(next, current).href;
161
167
  continue;
162
168
  }
163
- if (!response.ok)
169
+ if (!response.ok) {
170
+ await response.body?.cancel();
164
171
  throw new Error(`HTTP ${response.status} ${response.statusText}`);
172
+ }
165
173
  return parseDocument(await readCapped(response, maxBytes), location, options);
166
174
  }
167
175
  throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
@@ -387,15 +395,72 @@ const rebaseKeptRefs = (node, from, root, role) => {
387
395
  return node;
388
396
  };
389
397
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
390
- const hoistName = (targetLocation, fragment, taken) => {
398
+ const DEFINITION_CONTAINERS = [["$defs"], ["definitions"], ["components", "schemas"]];
399
+ const enclosingDefinitionLength = (pointer) => {
400
+ for (const container of DEFINITION_CONTAINERS) {
401
+ const length = container.length + 1;
402
+ if (pointer.length > length && container.every((key, index) => pointer[index] === key))
403
+ return length;
404
+ }
405
+ return 0;
406
+ };
407
+ const asWritten = (name) => name;
408
+ const asFilename = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
409
+ const NAME_CONTAINERS = ["$defs", "definitions"];
410
+ const POINTER_NAME_CONTAINERS = /* @__PURE__ */ new Set(["$defs", "definitions", "properties"]);
411
+ const generatedName = (pointer) => {
412
+ const segments = pointer.split("/").filter((segment) => segment !== "");
413
+ const named = segments.map((segment, index) => ({
414
+ segment,
415
+ nested: index > 0 && POINTER_NAME_CONTAINERS.has(segments[index - 1])
416
+ })).filter(({ segment }) => !POINTER_NAME_CONTAINERS.has(segment));
417
+ return named.filter((part, index) => part.nested || index === named.length - 1).map(({ segment }) => segment).join("-");
418
+ };
419
+ const internalPointers = (root) => {
420
+ const pointers = /* @__PURE__ */ new Set();
421
+ const seen = /* @__PURE__ */ new WeakSet();
422
+ const stack = [{ value: root, depth: 0 }];
423
+ while (stack.length > 0) {
424
+ const { value, depth } = stack.pop();
425
+ if (value === null || typeof value !== "object" || seen.has(value) || depth > DEFAULT_MAX_DEPTH)
426
+ continue;
427
+ seen.add(value);
428
+ const ref = value.$ref;
429
+ if (typeof ref === "string" && ref.startsWith("#/"))
430
+ pointers.add(ref.slice(1));
431
+ for (const member of Object.values(value))
432
+ stack.push({ value: member, depth: depth + 1 });
433
+ }
434
+ return pointers;
435
+ };
436
+ const nestedDefinitionNames = (map) => {
437
+ const names = [];
438
+ const seen = /* @__PURE__ */ new WeakSet();
439
+ const stack = [{ prefix: "", map, depth: 0 }];
440
+ while (stack.length > 0) {
441
+ const { prefix: parent, map: current, depth } = stack.pop();
442
+ if (seen.has(current) || depth > DEFAULT_MAX_DEPTH)
443
+ continue;
444
+ seen.add(current);
445
+ for (const [key, value] of Object.entries(current)) {
446
+ const name = parent === "" ? key : `${parent}-${key}`;
447
+ names.push(name);
448
+ for (const nested of containedNameMaps(value))
449
+ stack.push({ prefix: name, map: nested, depth: depth + 1 });
450
+ }
451
+ }
452
+ return names;
453
+ };
454
+ const containedNameMaps = (schema) => schema === null || typeof schema !== "object" || Array.isArray(schema) ? [] : NAME_CONTAINERS.map((container) => schema[container]).filter((map) => map !== null && typeof map === "object" && !Array.isArray(map));
455
+ const hoistName = (targetLocation, fragment, taken, keyOf = asWritten) => {
391
456
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
392
457
  const locationTail = targetLocation.split("/").filter(Boolean).pop()?.replace(/\.[a-z0-9]+$/i, "");
393
458
  const raw = fragmentTail || locationTail || "cycle";
394
459
  const sanitized = raw.replace(/[^A-Za-z0-9_.-]/g, "-") || "cycle";
395
460
  let name = sanitized;
396
- for (let n = 2; taken.has(name); n++)
461
+ for (let n = 2; taken.has(keyOf(name)); n++)
397
462
  name = `${sanitized}-${n}`;
398
- taken.add(name);
463
+ taken.add(keyOf(name));
399
464
  return name;
400
465
  };
401
466
  const MAX_DOCUMENTS = 500;
@@ -525,245 +590,452 @@ const resolveRefsFromFile = async (filename, options = {}) => {
525
590
  }
526
591
  };
527
592
  await prefetch();
528
- const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
529
- const refCache = /* @__PURE__ */ new Map();
530
- const sensitive = /* @__PURE__ */ new WeakSet();
531
- const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
532
- const hoists = /* @__PURE__ */ new Map();
533
- const rootDoc = docCache.get(rootLocation);
534
- const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
535
- const hoistTaken = new Set(rootDefs !== null && typeof rootDefs === "object" && !Array.isArray(rootDefs) ? Object.keys(rootDefs) : []);
536
- const hoistRefSites = /* @__PURE__ */ new Map();
537
- const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
538
- const kept = {};
539
- for (const key of Object.keys(obj)) {
540
- const value = obj[key];
541
- assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
542
- }
543
- return kept;
544
- };
545
- const resolveAt = (node, baseLocation, base, depth, role) => {
546
- if (node === null || typeof node !== "object")
547
- return node;
548
- if (role === "value")
549
- return detach(node);
550
- if (depth > maxDepth) {
551
- reportDepthLimit();
552
- return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
553
- }
554
- if (Array.isArray(node)) {
555
- const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
556
- if (items.some((item) => isScopeSensitive(sensitive, item)))
557
- sensitive.add(items);
558
- return items;
559
- }
560
- const obj = node;
561
- const registry = registryFor(baseLocation);
562
- const isSchema = role !== "schemaMap";
563
- const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
564
- const reference = isSchema ? readReference(obj) : void 0;
565
- if (reference) {
566
- const { keyword, value } = reference;
567
- if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
568
- const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
569
- sensitive.add(kept);
570
- return kept;
593
+ const errorsBeforeResolve = errors.length;
594
+ const depthReportedBeforeResolve = depthLimitReported;
595
+ const resolvePass = (inlineOnly) => {
596
+ const unplaceable = /* @__PURE__ */ new Set();
597
+ const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
598
+ const refCache = /* @__PURE__ */ new Map();
599
+ const sensitive = /* @__PURE__ */ new WeakSet();
600
+ const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
601
+ const hoists = /* @__PURE__ */ new Map();
602
+ const rootDoc = docCache.get(rootLocation);
603
+ const nameKey = options.bundle === true ? asFilename : asWritten;
604
+ const definitionNames = (root) => (options.bundle === true ? DEFINITION_CONTAINERS : [["$defs"]]).flatMap((container) => {
605
+ const map = getByPointer(root, `/${container.join("/")}`);
606
+ if (map === null || typeof map !== "object" || Array.isArray(map))
607
+ return [];
608
+ return options.bundle === true ? nestedDefinitionNames(map) : Object.keys(map);
609
+ });
610
+ const rootRefNames = (root) => options.bundle === true ? [...internalPointers(root)].map(generatedName) : [];
611
+ const rootNames = [...definitionNames(rootDoc), ...rootRefNames(rootDoc)];
612
+ const hoistTaken = new Set(rootNames.map(nameKey));
613
+ const hoistRefSites = /* @__PURE__ */ new Map();
614
+ const hoistRefSuffixes = /* @__PURE__ */ new Map();
615
+ const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
616
+ const kept = {};
617
+ for (const key of Object.keys(obj)) {
618
+ const value = obj[key];
619
+ assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
571
620
  }
572
- let scoped;
573
- let targetLocation = baseLocation;
574
- let fragment = "";
621
+ return kept;
622
+ };
623
+ const lookupTarget = (scoped, keyword, targetLocation, fragment) => {
624
+ if (scoped !== void 0)
625
+ return { found: scoped, base: scoped.base };
626
+ const targetRegistry = registryFor(targetLocation);
627
+ const targetRoot = docCache.get(targetLocation) ?? {};
575
628
  if (keyword === "$recursiveRef") {
576
- fragment = value.startsWith("#") ? value.slice(1) : value;
577
- } else {
578
- const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
579
- if (inScope === "external" || inScope === void 0) {
580
- const parts = splitRef(value);
581
- fragment = parts.fragment;
582
- if (inScope === "external" && parts.uriPart !== "") {
583
- const target = joinLocation(baseLocation, parts.uriPart);
584
- if (target === void 0)
585
- return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
586
- targetLocation = target;
587
- }
588
- } else {
589
- scoped = inScope;
629
+ return { found: resolveFragment(targetRoot, keyword, fragment), base: targetRegistry.rootBase };
630
+ }
631
+ const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
632
+ if (scopedFragment !== "external" && scopedFragment !== void 0) {
633
+ return { found: scopedFragment, base: scopedFragment.base };
634
+ }
635
+ return { found: resolveFragment(targetRoot, keyword, fragment), base: targetRegistry.rootBase };
636
+ };
637
+ const placements = [];
638
+ const embeddedIds = /* @__PURE__ */ new Map();
639
+ const contestedIds = /* @__PURE__ */ new Set();
640
+ const uriRefSites = /* @__PURE__ */ new Map();
641
+ const hoistTargets = /* @__PURE__ */ new Map();
642
+ const declaresRootId = (location) => {
643
+ const root = docCache.get(location);
644
+ return root !== null && typeof root === "object" && !Array.isArray(root) && typeof root.$id === "string";
645
+ };
646
+ const absoluteRootId = (location) => {
647
+ const root = docCache.get(location);
648
+ if (root === null || typeof root !== "object" || Array.isArray(root))
649
+ return void 0;
650
+ const id = root["$id"];
651
+ if (typeof id !== "string" || !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(id))
652
+ return void 0;
653
+ return registryFor(location).rootBase;
654
+ };
655
+ const uriFor = (location, base, pointer) => {
656
+ if (base.startsWith(SYNTHETIC_BASE))
657
+ return void 0;
658
+ const registry = registryFor(location);
659
+ const declared = base === registry.rootBase ? absoluteRootId(location) === base : registry.resources.has(base);
660
+ if (!declared)
661
+ return void 0;
662
+ const resourcePointer = base === registry.rootBase ? [] : registry.resources.get(base)?.pointer;
663
+ if (resourcePointer === void 0 || resourcePointer.some((segment, index) => pointer[index] !== segment)) {
664
+ return void 0;
665
+ }
666
+ const inner = pointer.slice(resourcePointer.length);
667
+ return inner.length === 0 ? base : `${base}${pathToRef(inner)}`;
668
+ };
669
+ const cycleTargetUri = (scoped, keyword, targetLocation, fragment) => {
670
+ const { found, base } = lookupTarget(scoped, keyword, targetLocation, fragment);
671
+ return found === void 0 ? void 0 : uriFor(targetLocation, base, found.pointer);
672
+ };
673
+ const hoistFor = (targetLocation, found, targetBase, plain, depth) => {
674
+ const wholeHoisted = plain && hoists.has(`$ref ${targetLocation}#`);
675
+ const split = plain && !wholeHoisted ? enclosingDefinitionLength(found.pointer) : 0;
676
+ const pointer = plain && !wholeHoisted ? split > 0 ? found.pointer.slice(0, split) : found.pointer : [];
677
+ const key = `$ref ${targetLocation}${pathToRef(pointer)}`;
678
+ const name = hoists.get(key) ?? hoistName(targetLocation, pathToRef(pointer).slice(1), hoistTaken, nameKey);
679
+ hoists.set(key, name);
680
+ hoistTargets.set(key, { location: targetLocation, pointer });
681
+ if (!refCache.has(key)) {
682
+ refCache.set(key, CYCLE);
683
+ const whole = pointer.length === found.pointer.length;
684
+ const value = whole ? found.value : getByPointer(docCache.get(targetLocation), pathToRef(pointer).slice(1));
685
+ const base = whole ? targetBase : registryFor(targetLocation).rootBase;
686
+ const resolved2 = resolveAt(value, targetLocation, base, depth + 1, roleAtPath(pointer));
687
+ refCache.set(key, { value: resolved2, pointer, base });
688
+ if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
689
+ origins.set(resolved2, { location: targetLocation, pointer });
590
690
  }
591
691
  }
592
- const cacheKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
593
- let resolved2;
594
- let pointer;
595
- let targetBase = nodeBase;
596
- const cached = refCache.get(cacheKey);
597
- if (cached === CYCLE) {
598
- let keptRef;
599
- let hoisted = false;
600
- if (scoped !== void 0 && baseLocation === rootLocation) {
601
- keptRef = pathToRef(scoped.pointer);
602
- } else if (scoped === void 0 && targetLocation === rootLocation) {
603
- keptRef = `#${fragment}`;
604
- } else {
605
- let name = hoists.get(cacheKey);
606
- if (name === void 0) {
607
- name = hoistName(targetLocation, fragment, hoistTaken);
608
- hoists.set(cacheKey, name);
609
- }
610
- hoisted = true;
611
- keptRef = `#/$defs/${name}`;
692
+ return { key, name, pointer };
693
+ };
694
+ const bundleReference = (obj, value, scoped, targetLocation, fragment, cacheKey, refKey, baseLocation, nodeBase, depth, role) => {
695
+ const placedIn = placements.at(-1);
696
+ const siteInRoot = placedIn === void 0 && nodeBase === registryFor(baseLocation).rootBase;
697
+ const intoRoot = scoped !== void 0 ? baseLocation === rootLocation : targetLocation === rootLocation;
698
+ const plain = !intoRoot && registryFor(targetLocation).bases.size === 0 && !declaresRootId(targetLocation);
699
+ const embeddedId = intoRoot || plain ? void 0 : absoluteRootId(targetLocation);
700
+ if (!intoRoot && !plain) {
701
+ if (embeddedId === void 0 || inlineOnly.has(targetLocation))
702
+ return void 0;
703
+ const claimedBy = embeddedIds.get(embeddedId);
704
+ if (registryFor(rootLocation).resources.has(embeddedId) || (claimedBy ?? targetLocation) !== targetLocation) {
705
+ if (claimedBy !== void 0 && claimedBy !== targetLocation)
706
+ contestedIds.add(embeddedId);
707
+ return void 0;
612
708
  }
613
- const kept = {};
614
- for (const key of Object.keys(obj)) {
615
- if (key === keyword)
616
- continue;
617
- assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
709
+ }
710
+ if (plain && !siteInRoot)
711
+ return void 0;
712
+ if (refCache.get(cacheKey) === MISSING || refCache.get(refKey) === MISSING)
713
+ return keepScopedReference(obj, "$ref", baseLocation, nodeBase, depth, role);
714
+ const { found, base: targetBase } = lookupTarget(scoped, "$ref", targetLocation, fragment);
715
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
716
+ if (found === void 0 || !targetLoaded) {
717
+ if (targetLoaded) {
718
+ errors.push({
719
+ message: `Cannot resolve $ref "${value}"`,
720
+ path: baseLocation === rootLocation ? refPathAt("$ref", value) : []
721
+ });
618
722
  }
619
- assignKey(kept, "$ref", keptRef);
620
- if (hoisted)
621
- hoistRefSites.set(kept, cacheKey);
622
- return kept;
723
+ refCache.set(cacheKey, MISSING);
724
+ refCache.set(refKey, MISSING);
725
+ return keepScopedReference(obj, "$ref", baseLocation, nodeBase, depth, role);
623
726
  }
624
- if (cached === MISSING)
625
- return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
626
- if (cached !== void 0) {
627
- resolved2 = cached.value;
628
- pointer = cached.pointer;
629
- targetBase = cached.base;
630
- } else {
631
- refCache.set(cacheKey, CYCLE);
632
- let found;
633
- if (scoped !== void 0) {
634
- found = scoped;
635
- targetBase = scoped.base;
727
+ const sameResource = placedIn !== void 0 && placedIn === nodeBase && nodeBase === targetBase && baseLocation === targetLocation && (scoped !== void 0 || splitRef(value).uriPart === "");
728
+ const byUri = !sameResource && (!siteInRoot || embeddedId !== void 0);
729
+ const uri = byUri ? uriFor(targetLocation, targetBase, found.pointer) : void 0;
730
+ if (byUri && uri === void 0)
731
+ return void 0;
732
+ if (embeddedId !== void 0)
733
+ embeddedIds.set(embeddedId, targetLocation);
734
+ const hoist = intoRoot ? void 0 : hoistFor(targetLocation, found, targetBase, plain, depth);
735
+ const named = hoist !== void 0 && plain && siteInRoot;
736
+ const suffix = named ? pathToRef(found.pointer.slice(hoist.pointer.length)).slice(1) : "";
737
+ const target = uri ?? (sameResource ? value : named ? `#/$defs/${hoist.name}${suffix}` : scoped !== void 0 || value.startsWith("#") ? value : pathToRef(found.pointer));
738
+ const kept = {};
739
+ for (const key of Object.keys(obj)) {
740
+ assignKey(kept, key, key === "$ref" ? target : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
741
+ }
742
+ if (named) {
743
+ hoistRefSites.set(kept, hoist.key);
744
+ if (suffix !== "")
745
+ hoistRefSuffixes.set(kept, suffix);
746
+ }
747
+ if (siteInRoot && hoist !== void 0 && embeddedId !== void 0) {
748
+ uriRefSites.set(kept, { key: hoist.key, id: embeddedId, suffix: pathToRef(found.pointer).slice(1) });
749
+ }
750
+ if (Object.values(kept).some((child) => isScopeSensitive(sensitive, child)) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors)) {
751
+ sensitive.add(kept);
752
+ }
753
+ return kept;
754
+ };
755
+ const resolveAt = (node, baseLocation, base, depth, role) => {
756
+ const entersResource = options.bundle === true && role !== "value" && role !== "schemaMap" && node !== null && typeof node === "object" && !Array.isArray(node) && typeof node["$id"] === "string" && // Draft-07's `#Foo` names a location, not a resource, wherever it lands.
757
+ splitRef(node["$id"]).uriPart !== "" && !(depth === 0 && baseLocation === rootLocation);
758
+ const nodeBase = entersResource ? baseOfNode(registryFor(baseLocation), node, base) : base;
759
+ if (!entersResource || nodeBase === (placements.at(-1) ?? registryFor(rootLocation).rootBase)) {
760
+ return resolveNode(node, baseLocation, base, depth, role);
761
+ }
762
+ placements.push(nodeBase);
763
+ try {
764
+ return resolveNode(node, baseLocation, base, depth, role);
765
+ } finally {
766
+ placements.pop();
767
+ }
768
+ };
769
+ const resolveNode = (node, baseLocation, base, depth, role) => {
770
+ if (node === null || typeof node !== "object")
771
+ return node;
772
+ if (role === "value")
773
+ return detach(node);
774
+ if (depth > maxDepth) {
775
+ reportDepthLimit();
776
+ return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
777
+ }
778
+ if (Array.isArray(node)) {
779
+ const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
780
+ if (items.some((item) => isScopeSensitive(sensitive, item)))
781
+ sensitive.add(items);
782
+ return items;
783
+ }
784
+ const obj = node;
785
+ const registry = registryFor(baseLocation);
786
+ const isSchema = role !== "schemaMap";
787
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
788
+ const reference = isSchema ? readReference(obj) : void 0;
789
+ if (reference) {
790
+ const { keyword, value } = reference;
791
+ if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
792
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
793
+ sensitive.add(kept);
794
+ return kept;
795
+ }
796
+ let scoped;
797
+ let targetLocation = baseLocation;
798
+ let fragment = "";
799
+ if (keyword === "$recursiveRef") {
800
+ fragment = value.startsWith("#") ? value.slice(1) : value;
636
801
  } else {
637
- const targetRegistry = registryFor(targetLocation);
638
- const targetRoot = docCache.get(targetLocation) ?? {};
639
- if (keyword === "$recursiveRef") {
640
- found = resolveFragment(targetRoot, keyword, fragment);
641
- targetBase = targetRegistry.rootBase;
642
- } else {
643
- const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
644
- if (scopedFragment !== "external" && scopedFragment !== void 0) {
645
- found = scopedFragment;
646
- targetBase = scopedFragment.base;
647
- } else {
648
- found = resolveFragment(targetRoot, keyword, fragment);
649
- targetBase = targetRegistry.rootBase;
802
+ const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
803
+ if (inScope === "external" || inScope === void 0) {
804
+ const parts = splitRef(value);
805
+ fragment = parts.fragment;
806
+ if (inScope === "external" && parts.uriPart !== "") {
807
+ const target = joinLocation(baseLocation, parts.uriPart);
808
+ if (target === void 0)
809
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
810
+ targetLocation = target;
650
811
  }
812
+ } else {
813
+ scoped = inScope;
651
814
  }
652
815
  }
653
- const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
654
- if (found === void 0 || !targetLoaded) {
655
- if (targetLoaded) {
656
- errors.push({
657
- message: `Cannot resolve ${keyword} "${value}"`,
658
- // `refPathAt` indexes the *root* document only, so it can only
659
- // speak for a ref that lives there. Called unguarded it answered
660
- // for a ref in a sub-document by handing back the position of an
661
- // identical ref in the root — pointing a diagnostic at a line
662
- // that is not the offending one. The prefetch loop above already
663
- // guards this the same way; an empty path means "no position to
664
- // give", which is honest.
665
- path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
666
- });
816
+ const refKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
817
+ const placedIn = options.bundle === true ? placements.at(-1) : void 0;
818
+ const cacheKey = placedIn === void 0 ? refKey : `${refKey} (in ${placedIn})`;
819
+ if (options.bundle === true && keyword === "$ref") {
820
+ const bundled = bundleReference(obj, value, scoped, targetLocation, fragment, cacheKey, refKey, baseLocation, nodeBase, depth, role);
821
+ if (bundled !== void 0)
822
+ return bundled;
823
+ }
824
+ let resolved2;
825
+ let pointer;
826
+ let targetBase = nodeBase;
827
+ const cached = refCache.get(cacheKey) ?? (refCache.get(refKey) === MISSING ? MISSING : void 0);
828
+ if (cached === CYCLE) {
829
+ const cycleUri = placedIn === void 0 ? void 0 : cycleTargetUri(scoped, keyword, targetLocation, fragment);
830
+ if (placedIn !== void 0 && cycleUri === void 0) {
831
+ const innermost = placements.findLast((base2) => embeddedIds.has(base2));
832
+ if (innermost !== void 0)
833
+ unplaceable.add(embeddedIds.get(innermost));
834
+ }
835
+ let keptRef;
836
+ let hoisted = false;
837
+ if (cycleUri !== void 0) {
838
+ keptRef = cycleUri;
839
+ } else if (scoped !== void 0 && baseLocation === rootLocation) {
840
+ keptRef = pathToRef(scoped.pointer);
841
+ } else if (scoped === void 0 && targetLocation === rootLocation) {
842
+ keptRef = `#${fragment}`;
843
+ } else {
844
+ let name = hoists.get(cacheKey);
845
+ if (name === void 0) {
846
+ name = hoistName(targetLocation, fragment, hoistTaken, nameKey);
847
+ hoists.set(cacheKey, name);
848
+ }
849
+ hoisted = true;
850
+ keptRef = `#/$defs/${name}`;
667
851
  }
668
- refCache.set(cacheKey, MISSING);
852
+ const kept = {};
853
+ for (const key of Object.keys(obj)) {
854
+ if (key === keyword)
855
+ continue;
856
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
857
+ }
858
+ assignKey(kept, "$ref", keptRef);
859
+ if (hoisted)
860
+ hoistRefSites.set(kept, cacheKey);
861
+ return kept;
862
+ }
863
+ if (cached === MISSING)
669
864
  return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
865
+ if (cached !== void 0) {
866
+ resolved2 = cached.value;
867
+ pointer = cached.pointer;
868
+ targetBase = cached.base;
869
+ } else {
870
+ refCache.set(cacheKey, CYCLE);
871
+ const lookup = lookupTarget(scoped, keyword, targetLocation, fragment);
872
+ const found = lookup.found;
873
+ targetBase = lookup.base;
874
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
875
+ if (found === void 0 || !targetLoaded) {
876
+ if (targetLoaded) {
877
+ errors.push({
878
+ message: `Cannot resolve ${keyword} "${value}"`,
879
+ // `refPathAt` indexes the *root* document only, so it can only
880
+ // speak for a ref that lives there. Called unguarded it answered
881
+ // for a ref in a sub-document by handing back the position of an
882
+ // identical ref in the root — pointing a diagnostic at a line
883
+ // that is not the offending one. The prefetch loop above already
884
+ // guards this the same way; an empty path means "no position to
885
+ // give", which is honest.
886
+ path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
887
+ });
888
+ }
889
+ refCache.set(cacheKey, MISSING);
890
+ refCache.set(refKey, MISSING);
891
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
892
+ }
893
+ pointer = found?.pointer ?? [];
894
+ resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
895
+ refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
896
+ if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
897
+ origins.set(resolved2, { location: targetLocation, pointer });
898
+ }
670
899
  }
671
- pointer = found?.pointer ?? [];
672
- resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
673
- refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
674
- if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
675
- origins.set(resolved2, { location: targetLocation, pointer });
900
+ if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
901
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
902
+ sensitive.add(kept);
903
+ return kept;
676
904
  }
905
+ const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
906
+ if (siblingKeys.length === 0)
907
+ return resolved2;
908
+ const siblings = {};
909
+ let siblingIsSensitive = false;
910
+ for (const key of siblingKeys) {
911
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
912
+ assignKey(siblings, key, child);
913
+ if (isScopeSensitive(sensitive, child))
914
+ siblingIsSensitive = true;
915
+ }
916
+ const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
917
+ if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
918
+ if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
919
+ const overridden = {};
920
+ for (const key of Object.keys(resolved2)) {
921
+ assignKey(overridden, key, resolved2[key]);
922
+ }
923
+ for (const key of Object.keys(siblings))
924
+ assignKey(overridden, key, siblings[key]);
925
+ const hoistOf = hoistRefSites.get(resolved2);
926
+ if (hoistOf !== void 0)
927
+ hoistRefSites.set(overridden, hoistOf);
928
+ const suffixOf = hoistRefSuffixes.get(resolved2);
929
+ if (suffixOf !== void 0)
930
+ hoistRefSuffixes.set(overridden, suffixOf);
931
+ const uriSite = uriRefSites.get(resolved2);
932
+ if (uriSite !== void 0)
933
+ uriRefSites.set(overridden, uriSite);
934
+ if (origins && !origins.has(overridden))
935
+ origins.set(overridden, { location: targetLocation, pointer });
936
+ if (inlineIsSensitive)
937
+ sensitive.add(overridden);
938
+ return overridden;
939
+ }
940
+ return resolved2;
941
+ }
942
+ const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
943
+ const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
944
+ if (origins && !origins.has(merged))
945
+ origins.set(merged, { location: targetLocation, pointer });
946
+ if (inlineIsSensitive)
947
+ sensitive.add(merged);
948
+ return merged;
677
949
  }
678
- if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
679
- const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
680
- sensitive.add(kept);
681
- return kept;
682
- }
683
- const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
684
- if (siblingKeys.length === 0)
685
- return resolved2;
686
- const siblings = {};
687
- let siblingIsSensitive = false;
688
- for (const key of siblingKeys) {
950
+ const result = {};
951
+ for (const key of Object.keys(obj)) {
689
952
  const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
690
- assignKey(siblings, key, child);
953
+ assignKey(result, key, child);
691
954
  if (isScopeSensitive(sensitive, child))
692
- siblingIsSensitive = true;
955
+ sensitive.add(result);
693
956
  }
694
- const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
695
- if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
696
- if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
697
- const overridden = {};
698
- for (const key of Object.keys(resolved2)) {
699
- assignKey(overridden, key, resolved2[key]);
700
- }
701
- for (const key of Object.keys(siblings))
702
- assignKey(overridden, key, siblings[key]);
703
- const hoistOf = hoistRefSites.get(resolved2);
704
- if (hoistOf !== void 0)
705
- hoistRefSites.set(overridden, hoistOf);
706
- if (origins && !origins.has(overridden))
707
- origins.set(overridden, { location: targetLocation, pointer });
708
- if (inlineIsSensitive)
709
- sensitive.add(overridden);
710
- return overridden;
957
+ if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
958
+ sensitive.add(result);
959
+ return result;
960
+ };
961
+ const rootRegistry = registryFor(rootLocation);
962
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
963
+ if (hoists.size > 0) {
964
+ if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
965
+ const container = resolved;
966
+ const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
967
+ const insideWhole = /* @__PURE__ */ new Map();
968
+ for (const [key, { location, pointer }] of hoistTargets) {
969
+ const whole = `$ref ${location}#`;
970
+ if (pointer.length > 0 && hoists.has(whole))
971
+ insideWhole.set(key, { whole, suffix: pathToRef(pointer).slice(1) });
972
+ }
973
+ const taken = new Set([...Object.keys(defs), ...definitionNames(container), ...rootNames].map(nameKey));
974
+ const usedSuffixes = /* @__PURE__ */ new Map();
975
+ for (const [node, cacheKey] of hoistRefSites) {
976
+ const redirect = insideWhole.get(cacheKey);
977
+ const key = redirect?.whole ?? cacheKey;
978
+ const suffix = `${redirect?.suffix ?? ""}${hoistRefSuffixes.get(node) ?? ""}`;
979
+ if (suffix !== "")
980
+ usedSuffixes.set(key, (usedSuffixes.get(key) ?? /* @__PURE__ */ new Set()).add(suffix));
981
+ }
982
+ const finalNames = /* @__PURE__ */ new Map();
983
+ for (const [cacheKey, name] of hoists) {
984
+ if (insideWhole.has(cacheKey))
985
+ continue;
986
+ const cached = refCache.get(cacheKey);
987
+ const value = cached !== void 0 && cached !== CYCLE && cached !== MISSING ? cached.value : void 0;
988
+ const nested = options.bundle === true ? containedNameMaps(value).flatMap((map) => nestedDefinitionNames(map)) : [];
989
+ const claims = (candidate) => [
990
+ candidate,
991
+ ...options.bundle === true ? [
992
+ ...nested.map((name2) => `${candidate}-${name2}`),
993
+ ...[...usedSuffixes.get(cacheKey) ?? []].map((suffix) => generatedName(`/$defs/${candidate}${suffix}`))
994
+ ] : []
995
+ ].map(nameKey);
996
+ let unique = name;
997
+ for (let n = 2; claims(unique).some((claim) => taken.has(claim)); n++)
998
+ unique = `${name}-${n}`;
999
+ for (const claim of claims(unique))
1000
+ taken.add(claim);
1001
+ finalNames.set(cacheKey, unique);
1002
+ }
1003
+ for (const [node, { key, id, suffix }] of uriRefSites) {
1004
+ if (contestedIds.has(id))
1005
+ assignKey(node, "$ref", `#/$defs/${finalNames.get(key)}${suffix}`);
1006
+ }
1007
+ for (const [node, cacheKey] of hoistRefSites) {
1008
+ const redirect = insideWhole.get(cacheKey);
1009
+ const name = finalNames.get(redirect?.whole ?? cacheKey);
1010
+ assignKey(node, "$ref", `#/$defs/${name}${redirect?.suffix ?? ""}${hoistRefSuffixes.get(node) ?? ""}`);
711
1011
  }
712
- return resolved2;
1012
+ for (const [cacheKey] of hoists) {
1013
+ if (insideWhole.has(cacheKey))
1014
+ continue;
1015
+ const cached = refCache.get(cacheKey);
1016
+ const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
1017
+ assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
1018
+ }
1019
+ assignKey(container, "$defs", defs);
1020
+ } else {
1021
+ errors.push({
1022
+ message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
1023
+ path: []
1024
+ });
713
1025
  }
714
- const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
715
- const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
716
- if (origins && !origins.has(merged))
717
- origins.set(merged, { location: targetLocation, pointer });
718
- if (inlineIsSensitive)
719
- sensitive.add(merged);
720
- return merged;
721
- }
722
- const result = {};
723
- for (const key of Object.keys(obj)) {
724
- const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
725
- assignKey(result, key, child);
726
- if (isScopeSensitive(sensitive, child))
727
- sensitive.add(result);
728
1026
  }
729
- if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
730
- sensitive.add(result);
731
- return result;
1027
+ return { result: origins ? { resolved, errors, origins } : { resolved, errors }, unplaceable };
732
1028
  };
733
- const rootRegistry = registryFor(rootLocation);
734
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
735
- if (hoists.size > 0) {
736
- if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
737
- const container = resolved;
738
- const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
739
- const taken = new Set(Object.keys(defs));
740
- const finalNames = /* @__PURE__ */ new Map();
741
- for (const [cacheKey, name] of hoists) {
742
- let unique = name;
743
- for (let n = 2; taken.has(unique); n++)
744
- unique = `${name}-${n}`;
745
- taken.add(unique);
746
- finalNames.set(cacheKey, unique);
747
- }
748
- for (const [node, cacheKey] of hoistRefSites) {
749
- const name = finalNames.get(cacheKey);
750
- if (name !== void 0)
751
- assignKey(node, "$ref", `#/$defs/${name}`);
752
- }
753
- for (const [cacheKey] of hoists) {
754
- const cached = refCache.get(cacheKey);
755
- const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
756
- assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
757
- }
758
- assignKey(container, "$defs", defs);
759
- } else {
760
- errors.push({
761
- message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
762
- path: []
763
- });
764
- }
765
- }
766
- return origins ? { resolved, errors, origins } : { resolved, errors };
1029
+ const settle = (inlineOnly) => {
1030
+ const { result, unplaceable } = resolvePass(inlineOnly);
1031
+ const more = [...unplaceable].filter((location) => !inlineOnly.has(location));
1032
+ if (more.length === 0)
1033
+ return result;
1034
+ errors.length = errorsBeforeResolve;
1035
+ depthLimitReported = depthReportedBeforeResolve;
1036
+ return settle(/* @__PURE__ */ new Set([...inlineOnly, ...more]));
1037
+ };
1038
+ return settle(/* @__PURE__ */ new Set());
767
1039
  };
768
1040
  export {
769
1041
  clearRemoteCache,
package/dist/types.d.ts CHANGED
@@ -106,9 +106,10 @@ export type ResolveOptions = {
106
106
  * (behind an egress proxy) and a local lookup would fail; allow-listed hosts
107
107
  * skip the check either way.
108
108
  *
109
- * This narrows DNS rebinding rather than closing it: the record can still
110
- * change between the check and the connection, which would take pinning the
111
- * socket to the verified address to prevent.
109
+ * The default client verifies inside the connection's own lookup and dials
110
+ * only the addresses it verified, so a rebinding record cannot answer the
111
+ * check and the connection differently. A custom `fetch` cannot be pinned
112
+ * that way and gets the check as a pre-flight only.
112
113
  */
113
114
  verifyDns?: boolean;
114
115
  /**
@@ -152,6 +153,36 @@ export type ResolveOptions = {
152
153
  * to their source without re-walking the `$ref` chain. Defaults to `false`.
153
154
  */
154
155
  trackOrigins?: boolean;
156
+ /**
157
+ * Bundle instead of inlining: pull every other document a `$ref` reaches into
158
+ * the root's `$defs` and point the ref there, so the output is one
159
+ * self-contained document whose `$ref`s are all internal. A ref into the root
160
+ * document is kept as written, and each target is hoisted once however many
161
+ * refs name it. A code generator wants this: a shared schema stays one named
162
+ * definition rather than an inline copy at every use, which on schemas that
163
+ * reference each other in layers is exponential in the output's size.
164
+ *
165
+ * A document that declares an absolute `$id` at its root is embedded whole
166
+ * under the root's `$defs` with that `$id` kept — how JSON Schema bundles a
167
+ * resource — so the `#/...` pointers written inside it still read against it,
168
+ * and every ref to something in it names it by that URI: a `#/...` pointer from
169
+ * the root into a resource with its own `$id` is one JSON Schema does not
170
+ * promise to resolve. (When a second document claims the same `$id`, refs from
171
+ * the root's own resource fall back to the hoist's pointer, which names one.)
172
+ * Inside any embedded resource `#` names that resource, so a ref there is kept
173
+ * as written when it is a `#...` pointer (or resolves by `$id`) to a target in
174
+ * the same resource, names its target by absolute URI otherwise, and is
175
+ * inlined when the target has no URI (a document without an `$id`). A target
176
+ * with no URI that is part of a cycle cannot be inlined, and has no name that
177
+ * reads the same from inside the resource, so a document whose resource meets
178
+ * one is inlined instead, as without this option. (A resource nested in the
179
+ * root document cannot be inlined; there the ref is the root-relative pointer
180
+ * inlining has always written.) A document whose `$id` is relative, or whose
181
+ * `$id` another bundled document already claims, is inlined.
182
+ * `$dynamicRef` and `$recursiveRef` are resolved as without this option.
183
+ * Defaults to `false`.
184
+ */
185
+ bundle?: boolean;
155
186
  /**
156
187
  * Extra HTTP headers sent with remote `$ref` requests (e.g. an `Authorization`
157
188
  * token for a private schema registry) — a static record, or a function
@@ -166,7 +197,13 @@ export type ResolveOptions = {
166
197
  * proxy-aware one, a test stub). Called once per redirect hop with
167
198
  * `redirect: 'manual'` and a timeout signal. The SSRF guard still evaluates
168
199
  * every hop before this is called — a custom fetch widens *how* documents are
169
- * fetched, never *which* hosts may be. Defaults to the global `fetch`.
200
+ * fetched, never *which* hosts may be.
201
+ *
202
+ * Defaults to a built-in client that pins each connection to the addresses
203
+ * the DNS check verified (see `verifyDns`), or to the global `fetch` when that
204
+ * check is off. A custom fetch resolves names itself, so for it the DNS check
205
+ * is a pre-flight that a rebinding record can still answer differently from
206
+ * the connection: pin the address yourself if that matters.
170
207
  */
171
208
  fetch?: (url: string, init: {
172
209
  redirect: 'manual';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.9.0",
3
+ "version": "0.11.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
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -55,6 +55,6 @@
55
55
  }
56
56
  },
57
57
  "devDependencies": {
58
- "@amritk/runtime-validators": "^0.15.1"
58
+ "@amritk/runtime-validators": "^0.15.2"
59
59
  }
60
60
  }