@amritk/resolve-refs 0.7.1 → 0.8.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
@@ -56,7 +56,7 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
56
56
  |:---|:---|:---|
57
57
  | `remote` | `true` | Whether http(s) refs may be fetched at all. |
58
58
  | `localRefs` | `true` | Whether `$ref`s to other files on disk may be read. `false` still reads the root document you named — it refuses everything a ref reaches out to. |
59
- | `allowedRoots` | `[dirname(root)]` | Directories a local `$ref` must resolve inside. The default confines a ref to the folder holding the root document. |
59
+ | `allowedRoots` | `[dirname(root)]` | Directories a local `$ref` must resolve inside. The default confines a ref to the folder holding the root document; for a root loaded from a URL the default is `[]`, so no local file is read at all. |
60
60
  | `allowedHosts` | `[]` | If non-empty, only these hosts may be fetched. Matched case-insensitively; an entry without a port matches any port, one with a port must match it (a URL that omits the port counts as its protocol default). An explicit entry bypasses the private-host and DNS guards. |
61
61
  | `allowPrivateHosts` | `false` | Allow loopback/private/link-local targets. Left off, these are refused as an SSRF guard. |
62
62
  | `verifyDns` | `true` | Resolve each remote host and refuse it when any address it resolves to is non-public. Pass `false` where names resolve at an egress proxy rather than locally. |
@@ -74,7 +74,8 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
74
74
 
75
75
  Errors (a missing file, a refused host, a refused path, a bad URL, a document too
76
76
  deeply nested) are collected on `result.errors` rather than thrown; the
77
- corresponding ref resolves to `{}` so the rest of the document still resolves.
77
+ referencing node is left in place as its `$ref` (nothing is inlined) so the rest
78
+ of the document still resolves.
78
79
  Each error carries the `path` to the reference that caused it — a path in the
79
80
  document you named, ending in the keyword (`['properties', 'pet', '$ref']`) — so
80
81
  a caller can anchor a diagnostic on the `$ref` a reader has to fix. It is empty
@@ -190,15 +191,20 @@ recursive cycles intact, and records a diagnostic for every external ref. The
190
191
  registry, no scoping, no diagnostics — and re-resolves each ref on every
191
192
  encounter, so the gap is the production resolver's *total* per-call cost against
192
193
  the cheapest thing that produces the same inlined shape. Both are asserted to
193
- produce byte-identical output before either is timed. Representative numbers
194
- (Bun 1.4, Linux x64 — your hardware will differ, run `bun run bench` yourself):
194
+ produce byte-identical output before either is timed. Medians of three runs on each runtime, one machine (Linux x64, a 4-vCPU cloud
195
+ box, Bun 1.4.0 and Node 26.8.1 — your hardware will differ, run `bun run bench`
196
+ or `bun run bench:node` yourself):
195
197
 
196
- | schema | cached | naive | speedup |
197
- |:---|---:|---:|---:|
198
- | chain (40 `$ref` → `$ref` links) | ~5.4k ops/s | ~1.2k ops/s | **~4.5×** |
199
- | reuse-heavy (50 refs → 1 def) | ~8.2k ops/s | ~12.6k ops/s | ~0.65× |
200
- | cyclic tree | ~47k ops/s | ~210k ops/s | ~0.22× |
201
- | wide-distinct (60 defs, each used once) | ~3.4k ops/s | ~10.2k ops/s | ~0.34× |
198
+ | schema | Bun: cached | Bun: naive | Bun speedup | Node: cached | Node: naive | Node speedup |
199
+ |:---|---:|---:|---:|---:|---:|---:|
200
+ | 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×** |
201
+ | reuse-heavy (50 refs → 1 def) | ~6.9k ops/s | ~11k ops/s | ~0.62× | ~6.6k ops/s | ~10k ops/s | ~0.66× |
202
+ | cyclic tree | ~50k ops/s | ~183k ops/s | ~0.27× | ~58k ops/s | ~184k ops/s | ~0.31× |
203
+ | 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× |
204
+
205
+ The two engines agree on every row to within a few percent, which is what you
206
+ would expect from a resolver whose cost is one document walk rather than a hot
207
+ inner loop.
202
208
 
203
209
  Memoization overtakes the naive walk only on the **chain** shape, where a long
204
210
  indirection path is expensive to re-resolve and the cache collapses it to one
@@ -212,5 +218,6 @@ rows are kept in the table precisely to show that trade honestly rather than
212
218
  cherry-picking the one shape the cache wins.
213
219
 
214
220
  Opting into `trackOrigins` (which records where each inlined value came from)
215
- costs nothing measurable on these small schemas: the four rows land between −24%
216
- and +16%, straddling zero, which is run-to-run noise rather than a price.
221
+ costs nothing measurable on these small schemas, on either runtime: the four
222
+ rows land between −9% and +7% on Bun and between −3% and +1% on Node, straddling
223
+ zero in both cases, which is run-to-run noise rather than a price.
@@ -1,4 +1,6 @@
1
1
  const decodeSegment = (segment) => {
2
+ if (!segment.includes("%") && !segment.includes("~"))
3
+ return segment;
2
4
  let decoded = segment;
3
5
  try {
4
6
  decoded = decodeURIComponent(segment);
@@ -11,9 +13,10 @@ const pointerToPath = (pointer) => {
11
13
  return [];
12
14
  return pointer.replace(/^\//, "").split("/").map((segment) => {
13
15
  const decoded = decodeSegment(segment);
14
- return /^(0|[1-9]\d*)$/.test(decoded) ? Number(decoded) : decoded;
16
+ return ARRAY_INDEX.test(decoded) ? Number(decoded) : decoded;
15
17
  });
16
18
  };
19
+ const ARRAY_INDEX = /^(0|[1-9]\d*)$/;
17
20
  const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
18
21
  const getByPointer = (root, pointer) => {
19
22
  if (pointer === "" || pointer === "/")
@@ -23,6 +26,8 @@ const getByPointer = (root, pointer) => {
23
26
  for (const segment of segments) {
24
27
  if (current === null || typeof current !== "object")
25
28
  return void 0;
29
+ if (Array.isArray(current) && !ARRAY_INDEX.test(segment))
30
+ return void 0;
26
31
  const key = Array.isArray(current) ? Number(segment) : segment;
27
32
  if (!Object.hasOwn(current, key))
28
33
  return void 0;
package/dist/reference.js CHANGED
@@ -13,31 +13,36 @@ const readReference = (obj) => {
13
13
  };
14
14
  const search = (root, predicate) => {
15
15
  const seen = /* @__PURE__ */ new Set();
16
- const walk = (node, pointer, depth, role) => {
16
+ const path = [];
17
+ const walk = (node, depth, role) => {
17
18
  if (node === null || typeof node !== "object" || seen.has(node) || depth > DEFAULT_MAX_DEPTH)
18
19
  return void 0;
19
20
  if (role === "value")
20
21
  return void 0;
21
22
  seen.add(node);
22
23
  if (!Array.isArray(node) && role !== "schemaMap" && predicate(node)) {
23
- return { value: node, pointer };
24
+ return { value: node, pointer: path.slice() };
24
25
  }
25
26
  if (Array.isArray(node)) {
26
27
  for (let i = 0; i < node.length; i++) {
27
- const found = walk(node[i], [...pointer, i], depth + 1, childRole(role, i));
28
+ path.push(i);
29
+ const found = walk(node[i], depth + 1, childRole(role, i));
30
+ path.pop();
28
31
  if (found)
29
32
  return found;
30
33
  }
31
34
  } else {
32
35
  for (const key of Object.keys(node)) {
33
- const found = walk(node[key], [...pointer, key], depth + 1, childRole(role, key));
36
+ path.push(key);
37
+ const found = walk(node[key], depth + 1, childRole(role, key));
38
+ path.pop();
34
39
  if (found)
35
40
  return found;
36
41
  }
37
42
  }
38
43
  return void 0;
39
44
  };
40
- return walk(root, [], 0, "schema");
45
+ return walk(root, 0, "schema");
41
46
  };
42
47
  const resolveFragment = (root, keyword, fragment) => {
43
48
  if (keyword === "$recursiveRef") {
@@ -47,28 +47,10 @@ const resolveNode = (node, base, depth, role, context) => {
47
47
  });
48
48
  return obj;
49
49
  };
50
- let found;
51
- let targetBase = nodeBase;
52
- if (keyword === "$recursiveRef") {
53
- found = resolveFragment(root, keyword, ref.startsWith("#") ? ref.slice(1) : ref);
54
- targetBase = registry.rootBase;
55
- } else {
56
- const scoped = resolveRefInScope(registry, keyword, ref, nodeBase);
57
- if (scoped === "external")
58
- return externalRef();
59
- if (scoped !== void 0) {
60
- found = scoped;
61
- targetBase = scoped.base;
62
- } else if (ref.startsWith("#")) {
63
- found = resolveFragment(root, keyword, ref.slice(1));
64
- targetBase = registry.rootBase;
65
- } else {
66
- return externalRef();
67
- }
68
- }
69
50
  const cacheKey = `${keyword} ${nodeBase} ${ref}`;
70
51
  let target;
71
52
  let pointer;
53
+ let targetBase;
72
54
  const cached = cache.get(cacheKey);
73
55
  if (cached === MISSING)
74
56
  return obj;
@@ -78,7 +60,27 @@ const resolveNode = (node, base, depth, role, context) => {
78
60
  if (cached !== void 0) {
79
61
  target = cached.target;
80
62
  pointer = cached.pointer;
63
+ targetBase = cached.base;
81
64
  } else {
65
+ let found;
66
+ targetBase = nodeBase;
67
+ if (keyword === "$recursiveRef") {
68
+ found = resolveFragment(root, keyword, ref.startsWith("#") ? ref.slice(1) : ref);
69
+ targetBase = registry.rootBase;
70
+ } else {
71
+ const scoped = resolveRefInScope(registry, keyword, ref, nodeBase);
72
+ if (scoped === "external")
73
+ return externalRef();
74
+ if (scoped !== void 0) {
75
+ found = scoped;
76
+ targetBase = scoped.base;
77
+ } else if (ref.startsWith("#")) {
78
+ found = resolveFragment(root, keyword, ref.slice(1));
79
+ targetBase = registry.rootBase;
80
+ } else {
81
+ return externalRef();
82
+ }
83
+ }
82
84
  cache.set(cacheKey, CYCLE);
83
85
  if (found === void 0) {
84
86
  errors.push({
@@ -90,7 +92,7 @@ const resolveNode = (node, base, depth, role, context) => {
90
92
  }
91
93
  pointer = found.pointer;
92
94
  target = resolveNode(found.value, targetBase, depth + 1, roleAtPath(pointer), context);
93
- cache.set(cacheKey, { target, pointer });
95
+ cache.set(cacheKey, { target, pointer, base: targetBase });
94
96
  if (origins && target !== null && typeof target === "object" && !origins.has(target)) {
95
97
  origins.set(target, { location: "", pointer });
96
98
  }
@@ -37,45 +37,51 @@ const buildResourceRegistry = (root, documentBase = SYNTHETIC_BASE, maxDepth = D
37
37
  if (typeof anchor === "string") {
38
38
  const key = `${base}#${anchor}`;
39
39
  if (!staticAnchors.has(key))
40
- staticAnchors.set(key, { value: node, pointer });
40
+ staticAnchors.set(key, { value: node, pointer: pointer.slice() });
41
41
  }
42
42
  const dynamicAnchor = node["$dynamicAnchor"];
43
43
  if (typeof dynamicAnchor === "string") {
44
44
  dynamicAnchorCounts.set(dynamicAnchor, (dynamicAnchorCounts.get(dynamicAnchor) ?? 0) + 1);
45
45
  const key = `${base}#${dynamicAnchor}`;
46
46
  if (!dynamicAnchors.has(key))
47
- dynamicAnchors.set(key, { value: node, pointer });
47
+ dynamicAnchors.set(key, { value: node, pointer: pointer.slice() });
48
48
  if (!staticAnchors.has(key))
49
- staticAnchors.set(key, { value: node, pointer });
49
+ staticAnchors.set(key, { value: node, pointer: pointer.slice() });
50
50
  }
51
51
  };
52
- const walk = (node, base, pointer, depth, role) => {
52
+ const path = [];
53
+ const walk = (node, base, depth, role) => {
53
54
  if (node === null || typeof node !== "object" || depth > maxDepth || role === "value")
54
55
  return;
55
56
  if (Array.isArray(node)) {
56
- for (let i = 0; i < node.length; i++)
57
- walk(node[i], base, [...pointer, i], depth + 1, childRole(role, i));
57
+ for (let i = 0; i < node.length; i++) {
58
+ path.push(i);
59
+ walk(node[i], base, depth + 1, childRole(role, i));
60
+ path.pop();
61
+ }
58
62
  return;
59
63
  }
60
64
  const record = node;
61
65
  const nodeBase = role === "schemaMap" ? base : baseAfterId(record, base);
62
66
  if (nodeBase !== base) {
63
67
  if (!resources.has(nodeBase))
64
- resources.set(nodeBase, { value: node, pointer });
68
+ resources.set(nodeBase, { value: node, pointer: path.slice() });
65
69
  if (!bases.has(node))
66
70
  bases.set(node, nodeBase);
67
71
  }
68
72
  if (role !== "schemaMap")
69
- registerAnchors(record, nodeBase, pointer);
73
+ registerAnchors(record, nodeBase, path);
70
74
  for (const key of Object.keys(record)) {
71
- walk(record[key], nodeBase, [...pointer, key], depth + 1, childRole(role, key));
75
+ path.push(key);
76
+ walk(record[key], nodeBase, depth + 1, childRole(role, key));
77
+ path.pop();
72
78
  }
73
79
  };
74
80
  if (rootBase !== initialBase)
75
81
  resources.set(rootBase, { value: root, pointer: [] });
76
82
  if (!resources.has(initialBase))
77
83
  resources.set(initialBase, { value: root, pointer: [] });
78
- walk(root, initialBase, [], 0, "schema");
84
+ walk(root, initialBase, 0, "schema");
79
85
  const ambiguousDynamicAnchors = /* @__PURE__ */ new Set();
80
86
  for (const [name, count] of dynamicAnchorCounts) {
81
87
  if (count > 1)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.7.1",
3
+ "version": "0.8.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",
@@ -43,7 +43,10 @@
43
43
  "prepublishOnly": "node ../../scripts/check-publishable.mjs",
44
44
  "types:check": "tsgo -p . --noEmit",
45
45
  "test": "NODE_ENV=production vitest run --root ../.. resolve-refs",
46
- "bench": "bun run ./bench/run.ts"
46
+ "prebench": "bun run build",
47
+ "bench": "bun run ./bench/run.ts",
48
+ "prebench:node": "bun run build",
49
+ "bench:node": "node ./bench/run.ts"
47
50
  },
48
51
  "exports": {
49
52
  ".": {
@@ -52,6 +55,6 @@
52
55
  }
53
56
  },
54
57
  "devDependencies": {
55
- "@amritk/runtime-validators": "^0.12.0"
58
+ "@amritk/runtime-validators": "^0.15.1"
56
59
  }
57
60
  }