@amritk/resolve-refs 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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,58 @@ 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` is single-pass: every unique `$ref` string is resolved exactly
101
+ once and memoized, with a sentinel that breaks cycles. The `bench/` suite isolates
102
+ what that memoization buys by pitting it against a naive inliner that re-resolves
103
+ each ref every time it is encountered — same inlined output, the cache is the only
104
+ difference. Representative numbers (Bun 1.3, Linux x64 — your hardware will
105
+ differ, run `bun run bench` yourself):
106
+
107
+ | schema | cached | naive | speedup |
108
+ |:---|---:|---:|---:|
109
+ | reuse-heavy (50 refs → 1 def) | ~35k ops/s | ~6k ops/s | **~5.8×** |
110
+ | chain (40 `$ref` → `$ref` links) | ~5k ops/s | ~0.6k ops/s | **~8.2×** |
111
+ | cyclic tree | ~122k ops/s | ~117k ops/s | ~1.05× |
112
+ | wide-distinct (60 defs, each used once) | ~3.3k ops/s | ~6.1k ops/s | ~0.54× |
113
+
114
+ The cache earns its keep exactly where you'd expect: a `$def` referenced from
115
+ many sites, or a long indirection chain, is resolved once instead of re-walked
116
+ every time. On a document where every ref is distinct — so the cache never hits —
117
+ its bookkeeping is pure overhead and the naive walk is faster; that `wide-distinct`
118
+ row is kept in the table precisely to show the trade honestly. Real API schemas
119
+ lean heavily on shared `$def`s, which is the case the resolver is tuned for.
120
+
121
+ Opting into `trackOrigins` (which records where each inlined value came from) adds
122
+ roughly **5–20%** on top. Both strategies are asserted to produce byte-identical
123
+ output before either is timed.
@@ -68,7 +68,13 @@ const ipv4Octets = (host) => {
68
68
  return [(value >>> 24) & 0xff, (value >>> 16) & 0xff];
69
69
  };
70
70
  export const isPrivateHost = (hostname) => {
71
- const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
71
+ // Strip IPv6 brackets and any trailing dot(s): `localhost.` is the FQDN-root
72
+ // form of `localhost` and resolves to the same loopback address, so it must
73
+ // not slip past the by-name checks below.
74
+ const host = hostname
75
+ .replace(/^\[|\]$/g, '')
76
+ .replace(/\.+$/, '')
77
+ .toLowerCase();
72
78
  if (host === 'localhost' || host.endsWith('.localhost'))
73
79
  return true;
74
80
  if (host.includes(':')) {
@@ -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>;