@amritk/resolve-refs 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,26 +3,38 @@
3
3
  Resolve and inline JSON Schema / OpenAPI `$ref`s — internal pointers, cross-file
4
4
  refs, and remote (http/https) documents — into a single dereferenced document.
5
5
 
6
- - **One-pass, cached.** Every unique ref is resolved once; cycles are broken with
7
- an empty object so the result is always finite.
8
- - **Anchors + dynamic refs.** Beyond JSON-pointer `$ref`s, plain-name `$anchor`
9
- references (`#node`), `$dynamicRef`/`$dynamicAnchor` (2020-12), and
10
- `$recursiveRef`/`$recursiveAnchor` (2019-09) are dereferenced too. The dynamic
11
- forms bind to their document-global anchor — the single-bundle case; nested
12
- `$id` base-URI re-scoping is not modelled.
6
+ - **One-pass, cached.** Every unique ref is resolved once; the result is always
7
+ finite. At a reference **cycle** the recursive branch is *kept*, not lost: the
8
+ cycle point stays a `$ref` that resolves within the output document (a
9
+ cross-file cycle target is hoisted into the root's `$defs`), so recursive
10
+ schemas survive dereferencing intact.
11
+ - **Anchors + dynamic refs, `$id`-scoped.** Beyond JSON-pointer `$ref`s,
12
+ plain-name `$anchor` references (`#node`), `$dynamicRef`/`$dynamicAnchor`
13
+ (2020-12), and `$recursiveRef`/`$recursiveAnchor` (2019-09) are dereferenced
14
+ too. `$id` base-URI scoping is modelled for the bundled-document case: a ref
15
+ whose URI matches an embedded resource's `$id` resolves to it without
16
+ fetching, and anchors bind within the resource that declares them (falling
17
+ back to a document-global search). See *`$id` scoping* below for the exact
18
+ subset.
13
19
  - **Cross-file + remote.** Relative refs resolve against the document they appear
14
20
  in (a ref inside a remote doc stays remote, one inside a local file stays
15
21
  local). Fetched remote documents are cached for the lifetime of the process.
16
22
  - **Default-deny SSRF guard.** Remote refs to loopback, private, link-local, and
17
23
  cloud-metadata (`169.254.169.254`) hosts are refused unless you opt in.
24
+ - **OpenAPI Reference Objects.** A `$ref` whose only siblings are `summary` /
25
+ `description` inlines the target with those annotations overriding — matching
26
+ OpenAPI 3.1 Reference Object semantics, where an `allOf` wrapper would be
27
+ invalid. Any other sibling keyword keeps the spec-correct `allOf` combination.
18
28
 
19
29
  ## Usage
20
30
 
21
31
  ```ts
22
32
  import { resolveRefs, resolveRefsFromFile } from '@amritk/resolve-refs'
23
33
 
24
- // In-memory, internal (#/...) refs only:
25
- const { resolved } = resolveRefs(myDocument)
34
+ // In-memory, internal (#/...) refs only. External refs (another file or an
35
+ // http(s) URL) are left in place and reported on `errors`, since this resolver
36
+ // can't load other documents — use resolveRefsFromFile for those:
37
+ const { resolved, errors } = resolveRefs(myDocument)
26
38
 
27
39
  // From disk or a URL, including cross-file and remote refs:
28
40
  const result = await resolveRefsFromFile('./schema.json')
@@ -38,6 +50,14 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
38
50
  | `remote` | `true` | Whether http(s) refs may be fetched at all. |
39
51
  | `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. An explicit entry bypasses the private-host guard. |
40
52
  | `allowPrivateHosts` | `false` | Allow loopback/private/link-local targets. Left off, these are refused as an SSRF guard. |
53
+ | `headers` | — | Extra headers for remote requests (record, or `(url) => headers` for per-host credentials). Never sent across a cross-origin redirect. |
54
+ | `fetch` | global `fetch` | Custom fetch implementation. The SSRF guard still evaluates every hop before it is called. |
55
+ | `timeoutMs` | `30_000` | Abort an unresponsive remote fetch after this many milliseconds. |
56
+ | `maxRedirects` | `5` | Redirect hops to follow per remote document (each hop re-runs the SSRF guard). |
57
+ | `maxBytes` | `16` MiB | Refuse to buffer a remote document larger than this. |
58
+ | `cache` | `true` | Pass `false` to bypass the process-wide session cache for this call — everything is re-fetched, nothing is stored. |
59
+ | `parse` | `JSON.parse` | Custom content parser (e.g. YAML-aware). |
60
+ | `trackOrigins` | `false` | Record a per-node origin map on the result. |
41
61
 
42
62
  Errors (a missing file, a refused host, a bad URL) are collected on
43
63
  `result.errors` rather than thrown; the corresponding ref resolves to `{}` so the
@@ -46,8 +66,66 @@ rest of the document still resolves.
46
66
  `clearRemoteCache()` drops every cached remote document — useful in tests or
47
67
  long-lived sessions where remote schemas may change.
48
68
 
69
+ ## `$id` scoping
70
+
71
+ The supported subset, chosen for the bundled-document reality rather than the
72
+ full spec:
73
+
74
+ - A subschema with `$id` is an **embedded resource**: its `$id` (resolved
75
+ against the enclosing base) becomes the base URI for everything inside it.
76
+ - A ref whose URI — resolved against the enclosing base — **matches an embedded
77
+ resource's `$id`** resolves to that resource without fetching. A pointer or
78
+ anchor fragment on such a ref applies *within* that resource.
79
+ - **Anchors** bind within the resource that declares them first; an anchor not
80
+ found in scope falls back to a document-global search (compatibility with
81
+ documents that reference across sibling resources).
82
+ - A plain `#/pointer` fragment stays **document-root-relative** — the behavior
83
+ bundled real-world documents rely on — even inside an embedded resource.
84
+ - `$dynamicRef` prefers a `$dynamicAnchor` in scope, then degrades to `$ref`
85
+ semantics. The full dynamic-scope algorithm (outermost anchor along the
86
+ runtime reference chain) is not modelled.
87
+ - Document **retrieval is unaffected**: which file/URL an external ref loads
88
+ from is derived from the referencing document's *location*, never its `$id` —
89
+ a root `$id` naming a remote URL cannot turn a local sibling-file ref into a
90
+ network fetch.
91
+
49
92
  ## Documents
50
93
 
51
94
  Every document — local file or remote — is parsed as **JSON**. mjst works with
52
95
  JSON Schema documents only, so this resolver stays JSON-only and dependency-free.
53
96
  (The Loupe linter's sibling resolver additionally accepts YAML.)
97
+
98
+ ## Benchmarks
99
+
100
+ `resolveRefs` memoizes: every unique `$ref` string is resolved once per scope,
101
+ with a sentinel that breaks cycles by keeping the reference node in place. But it
102
+ is no longer *only* a memoized inliner — before resolving anything it walks the
103
+ whole document once to build a resource registry (`$id`/`$anchor` scoping), keeps
104
+ recursive cycles intact, and records a diagnostic for every external ref. The
105
+ `bench/` suite pits it against a bare naive inliner that does none of that — no
106
+ registry, no scoping, no diagnostics — and re-resolves each ref on every
107
+ encounter, so the gap is the production resolver's *total* per-call cost against
108
+ the cheapest thing that produces the same inlined shape. Both are asserted to
109
+ produce byte-identical output before either is timed. Representative numbers
110
+ (Bun 1.3, Linux x64 — your hardware will differ, run `bun run bench` yourself):
111
+
112
+ | schema | cached | naive | speedup |
113
+ |:---|---:|---:|---:|
114
+ | chain (40 `$ref` → `$ref` links) | ~2.6k ops/s | ~0.8k ops/s | **~3.2×** |
115
+ | reuse-heavy (50 refs → 1 def) | ~4.5k ops/s | ~8k ops/s | ~0.5× |
116
+ | cyclic tree | ~27k ops/s | ~74k ops/s | ~0.37× |
117
+ | wide-distinct (60 defs, each used once) | ~2.3k ops/s | ~7.3k ops/s | ~0.32× |
118
+
119
+ Memoization overtakes the naive walk only on the **chain** shape, where a long
120
+ indirection path is expensive to re-resolve and the cache collapses it to one
121
+ pass. On every other shape here the fixed cost of the up-front registry walk (paid
122
+ once per call, no matter how the refs reuse) outweighs what memoization saves, and
123
+ the bare inliner is faster — these are small schemas where that one document walk
124
+ dominates. The takeaway is practical: the resolver's per-call floor is a full
125
+ document traversal, so in a hot loop resolve a document **once** and reuse the
126
+ result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct`
127
+ rows are kept in the table precisely to show that trade honestly rather than
128
+ cherry-picking the one shape the cache wins.
129
+
130
+ Opting into `trackOrigins` (which records where each inlined value came from) adds
131
+ roughly **0–20%** on top, within run-to-run noise on these small schemas.
@@ -67,8 +67,72 @@ const ipv4Octets = (host) => {
67
67
  return null;
68
68
  return [(value >>> 24) & 0xff, (value >>> 16) & 0xff];
69
69
  };
70
+ /**
71
+ * Expands a hex IPv6 literal (no dotted-IPv4 tail — that is handled separately)
72
+ * into its eight 16-bit groups, resolving `::` zero-compression. Returns null if
73
+ * the string is not a well-formed hex IPv6 address.
74
+ */
75
+ const expandHexIpv6 = (host) => {
76
+ const halves = host.split('::');
77
+ if (halves.length > 2)
78
+ return null;
79
+ const toGroups = (part) => {
80
+ if (part === '')
81
+ return [];
82
+ const groups = [];
83
+ for (const g of part.split(':')) {
84
+ if (!/^[0-9a-f]{1,4}$/.test(g))
85
+ return null;
86
+ groups.push(Number.parseInt(g, 16));
87
+ }
88
+ return groups;
89
+ };
90
+ const head = toGroups(halves[0]);
91
+ if (head === null)
92
+ return null;
93
+ if (halves.length === 1)
94
+ return head.length === 8 ? head : null;
95
+ const tail = toGroups(halves[1]);
96
+ if (tail === null)
97
+ return null;
98
+ const fill = 8 - head.length - tail.length;
99
+ if (fill < 0)
100
+ return null;
101
+ return [...head, ...new Array(fill).fill(0), ...tail];
102
+ };
103
+ /**
104
+ * When an expanded IPv6 address embeds an IPv4 address in its low 32 bits,
105
+ * returns that IPv4 as a 32-bit number; otherwise null. Covers every embedding
106
+ * the WHATWG URL parser can hand us as bare hex — the `ffff:`-only regex this
107
+ * replaced let `::7f00:1` (`::127.0.0.1`) and `::a9fe:a9fe` (`::169.254.169.254`)
108
+ * through, since those normalize away the `ffff:` marker:
109
+ * - `::/96` compatible (`::X:Y`, also covers `::`/`::1`),
110
+ * - IPv4-mapped (`::ffff:X:Y`),
111
+ * - IPv4-translated (`::ffff:0:X:Y`),
112
+ * - NAT64 (`64:ff9b::/96`).
113
+ */
114
+ const ipv4EmbeddedInIpv6 = (g) => {
115
+ const [a, b, c, d, e, f, hi, lo] = g;
116
+ const embedded = (hi * 0x10000 + lo) >>> 0;
117
+ const zeros4 = a === 0 && b === 0 && c === 0 && d === 0;
118
+ if (zeros4 && e === 0 && f === 0)
119
+ return embedded; // ::/96 compatible
120
+ if (zeros4 && e === 0 && f === 0xffff)
121
+ return embedded; // ::ffff:X:Y mapped
122
+ if (zeros4 && e === 0xffff && f === 0)
123
+ return embedded; // ::ffff:0:X:Y translated
124
+ if (a === 0x64 && b === 0xff9b && c === 0 && d === 0 && e === 0 && f === 0)
125
+ return embedded; // 64:ff9b::/96 NAT64
126
+ return null;
127
+ };
70
128
  export const isPrivateHost = (hostname) => {
71
- const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
129
+ // Strip IPv6 brackets and any trailing dot(s): `localhost.` is the FQDN-root
130
+ // form of `localhost` and resolves to the same loopback address, so it must
131
+ // not slip past the by-name checks below.
132
+ const host = hostname
133
+ .replace(/^\[|\]$/g, '')
134
+ .replace(/\.+$/, '')
135
+ .toLowerCase();
72
136
  if (host === 'localhost' || host.endsWith('.localhost'))
73
137
  return true;
74
138
  if (host.includes(':')) {
@@ -80,19 +144,23 @@ export const isPrivateHost = (hostname) => {
80
144
  return true;
81
145
  if (host.startsWith('fc') || host.startsWith('fd'))
82
146
  return true; // fc00::/7 unique-local
83
- // IPv4-mapped/compatible, dotted (`::ffff:127.0.0.1`) — the URL parser
84
- // rewrites this to hex, but a direct caller may pass the dotted form.
147
+ // IPv4-mapped/compatible, dotted (`::ffff:127.0.0.1`, `::127.0.0.1`) — the URL
148
+ // parser rewrites these to hex, but a direct caller may pass the dotted form.
85
149
  const dotted = /:((?:\d{1,3}\.){3}\d{1,3})$/.exec(host);
86
150
  if (dotted?.[1]) {
87
151
  const oct = ipv4Octets(dotted[1]);
88
152
  if (oct)
89
153
  return isPrivateIpv4(oct[0], oct[1]);
90
154
  }
91
- // IPv4-mapped, hex (`::ffff:7f00:1`) — what `new URL()` produces.
92
- const hex = /:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);
93
- if (hex?.[1] && hex[2]) {
94
- const hi = Number.parseInt(hex[1], 16);
95
- return isPrivateIpv4((hi >> 8) & 0xff, hi & 0xff);
155
+ // Every hex IPv4-in-IPv6 embedding `new URL()` can produce (mapped,
156
+ // compatible, translated, NAT64) — via a full expansion rather than a
157
+ // single-form regex, which missed `::7f00:1` / `::a9fe:a9fe`. This also
158
+ // catches the fully-expanded loopback `0:0:0:0:0:0:0:1`.
159
+ const groups = expandHexIpv6(host);
160
+ if (groups) {
161
+ const embedded = ipv4EmbeddedInIpv6(groups);
162
+ if (embedded !== null)
163
+ return isPrivateIpv4((embedded >>> 24) & 0xff, (embedded >>> 16) & 0xff);
96
164
  }
97
165
  return false;
98
166
  }
@@ -34,9 +34,9 @@ export type ResolvedTarget = {
34
34
  * none (2019-09).
35
35
  *
36
36
  * Anchor search is document-global: we bind to the single matching anchor in
37
- * `root` rather than walking the dynamic scope. For one bundled document — what a
38
- * linter dereferences — there is exactly one anchor per name, so this agrees with
39
- * the full dynamic-scope algorithm. Nested `$id` base-URI re-scoping is not
40
- * modelled (the common bundled case does not rely on it).
37
+ * `root` rather than walking the dynamic scope. This is the *fallback* path —
38
+ * the resolvers first try `$id`-scoped resolution via `resource-registry.ts`,
39
+ * which binds duplicate anchor names to the resource they are declared in, and
40
+ * only land here for anchors declared outside any registered scope.
41
41
  */
42
42
  export declare const resolveFragment: (root: unknown, keyword: RefKeyword, fragment: string) => ResolvedTarget | undefined;
package/dist/reference.js CHANGED
@@ -59,10 +59,10 @@ const search = (root, predicate) => {
59
59
  * none (2019-09).
60
60
  *
61
61
  * Anchor search is document-global: we bind to the single matching anchor in
62
- * `root` rather than walking the dynamic scope. For one bundled document — what a
63
- * linter dereferences — there is exactly one anchor per name, so this agrees with
64
- * the full dynamic-scope algorithm. Nested `$id` base-URI re-scoping is not
65
- * modelled (the common bundled case does not rely on it).
62
+ * `root` rather than walking the dynamic scope. This is the *fallback* path —
63
+ * the resolvers first try `$id`-scoped resolution via `resource-registry.ts`,
64
+ * which binds duplicate anchor names to the resource they are declared in, and
65
+ * only land here for anchors declared outside any registered scope.
66
66
  */
67
67
  export const resolveFragment = (root, keyword, fragment) => {
68
68
  if (keyword === '$recursiveRef') {
@@ -4,6 +4,8 @@ export declare const clearRemoteCache: () => void;
4
4
  /**
5
5
  * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
6
6
  * and remote refs. Remote documents are fetched on the fly and cached in memory
7
- * for the session; `options` governs whether/which remote hosts are allowed.
7
+ * for the session; `options` governs whether/which remote hosts are allowed,
8
+ * how they are fetched (`headers`, `fetch`, `timeoutMs`, `maxRedirects`,
9
+ * `maxBytes`), and whether the session cache is used (`cache`).
8
10
  */
9
11
  export declare const resolveRefsFromFile: (filename: string, options?: ResolveOptions) => Promise<ResolveResult>;