@amritk/resolve-refs 0.7.0 → 0.7.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/AI.md +5 -0
- package/README.md +13 -7
- package/dist/dynamic-scope.js +3 -2
- package/dist/get-by-pointer.d.ts +6 -0
- package/dist/get-by-pointer.js +2 -0
- package/dist/is-private-host.js +2 -0
- package/dist/ref-path-index.d.ts +22 -0
- package/dist/ref-path-index.js +53 -0
- package/dist/reference.d.ts +9 -0
- package/dist/reference.js +4 -2
- package/dist/resolve-refs-from-file.js +56 -45
- package/dist/resolve-refs.js +32 -20
- package/dist/resource-registry.d.ts +18 -9
- package/dist/resource-registry.js +22 -28
- package/dist/split-ref.d.ts +14 -0
- package/dist/split-ref.js +10 -0
- package/dist/types.d.ts +12 -2
- package/package.json +2 -2
package/AI.md
CHANGED
|
@@ -30,6 +30,11 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
|
|
|
30
30
|
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
|
+
Each error's `path` is where the offending reference was written in the
|
|
34
|
+
document you passed in, ending in the keyword (`['properties','p','$ref']`),
|
|
35
|
+
so you can point a diagnostic straight at it. It is empty when there is
|
|
36
|
+
nowhere to point — a budget the whole resolve overran, or a reference living
|
|
37
|
+
in some other document.
|
|
33
38
|
3. **Default-deny SSRF guard.** Remote refs to loopback / private / link-local /
|
|
34
39
|
`169.254.169.254` / metadata hosts by name (`metadata.google.internal`,
|
|
35
40
|
`*.internal`) are refused unless `allowPrivateHosts: true` or an explicit
|
package/README.md
CHANGED
|
@@ -75,6 +75,11 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
|
|
|
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
77
|
corresponding ref resolves to `{}` so the rest of the document still resolves.
|
|
78
|
+
Each error carries the `path` to the reference that caused it — a path in the
|
|
79
|
+
document you named, ending in the keyword (`['properties', 'pet', '$ref']`) — so
|
|
80
|
+
a caller can anchor a diagnostic on the `$ref` a reader has to fix. It is empty
|
|
81
|
+
when there is nowhere to point: a budget the resolve as a whole overran, or a
|
|
82
|
+
reference written in some other document.
|
|
78
83
|
|
|
79
84
|
`clearRemoteCache()` drops every cached remote document — useful in tests or
|
|
80
85
|
long-lived sessions where remote schemas may change. Pass a URL
|
|
@@ -186,14 +191,14 @@ registry, no scoping, no diagnostics — and re-resolves each ref on every
|
|
|
186
191
|
encounter, so the gap is the production resolver's *total* per-call cost against
|
|
187
192
|
the cheapest thing that produces the same inlined shape. Both are asserted to
|
|
188
193
|
produce byte-identical output before either is timed. Representative numbers
|
|
189
|
-
(Bun 1.
|
|
194
|
+
(Bun 1.4, Linux x64 — your hardware will differ, run `bun run bench` yourself):
|
|
190
195
|
|
|
191
196
|
| schema | cached | naive | speedup |
|
|
192
197
|
|:---|---:|---:|---:|
|
|
193
|
-
| chain (40 `$ref` → `$ref` links) | ~
|
|
194
|
-
| reuse-heavy (50 refs → 1 def) | ~
|
|
195
|
-
| cyclic tree | ~
|
|
196
|
-
| wide-distinct (60 defs, each used once) | ~
|
|
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× |
|
|
197
202
|
|
|
198
203
|
Memoization overtakes the naive walk only on the **chain** shape, where a long
|
|
199
204
|
indirection path is expensive to re-resolve and the cache collapses it to one
|
|
@@ -206,5 +211,6 @@ result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct
|
|
|
206
211
|
rows are kept in the table precisely to show that trade honestly rather than
|
|
207
212
|
cherry-picking the one shape the cache wins.
|
|
208
213
|
|
|
209
|
-
Opting into `trackOrigins` (which records where each inlined value came from)
|
|
210
|
-
|
|
214
|
+
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.
|
package/dist/dynamic-scope.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { baseAfterId
|
|
1
|
+
import { baseAfterId } from "./resource-registry.js";
|
|
2
|
+
import { splitRef } from "./split-ref.js";
|
|
2
3
|
const bindsAtEvaluationTime = (keyword, ref, ambiguousAnchors) => {
|
|
3
4
|
if (keyword !== "$dynamicRef")
|
|
4
5
|
return false;
|
|
5
|
-
const { fragment } =
|
|
6
|
+
const { fragment } = splitRef(ref);
|
|
6
7
|
if (fragment === "" || fragment.startsWith("/"))
|
|
7
8
|
return false;
|
|
8
9
|
return ambiguousAnchors.has(fragment);
|
package/dist/get-by-pointer.d.ts
CHANGED
|
@@ -9,6 +9,12 @@ import type { JsonPath } from './types.js';
|
|
|
9
9
|
* not `obj[1]`). A bare `''` or `'/'` is the empty path.
|
|
10
10
|
*/
|
|
11
11
|
export declare const pointerToPath: (pointer: string) => JsonPath;
|
|
12
|
+
/**
|
|
13
|
+
* Whether a reference fragment is a JSON Pointer rather than a plain-name
|
|
14
|
+
* anchor. RFC 6901 pointers are empty or start with `/`; anything else names an
|
|
15
|
+
* `$anchor`.
|
|
16
|
+
*/
|
|
17
|
+
export declare const isPointerFragment: (fragment: string) => boolean;
|
|
12
18
|
/**
|
|
13
19
|
* Walks a JSON Pointer string (RFC 6901) to the value it points to within
|
|
14
20
|
* `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
|
package/dist/get-by-pointer.js
CHANGED
|
@@ -14,6 +14,7 @@ const pointerToPath = (pointer) => {
|
|
|
14
14
|
return /^(0|[1-9]\d*)$/.test(decoded) ? Number(decoded) : decoded;
|
|
15
15
|
});
|
|
16
16
|
};
|
|
17
|
+
const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
|
|
17
18
|
const getByPointer = (root, pointer) => {
|
|
18
19
|
if (pointer === "" || pointer === "/")
|
|
19
20
|
return root;
|
|
@@ -31,5 +32,6 @@ const getByPointer = (root, pointer) => {
|
|
|
31
32
|
};
|
|
32
33
|
export {
|
|
33
34
|
getByPointer,
|
|
35
|
+
isPointerFragment,
|
|
34
36
|
pointerToPath
|
|
35
37
|
};
|
package/dist/is-private-host.js
CHANGED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type RefKeyword } from './reference.js';
|
|
2
|
+
import type { JsonPath } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A lookup from a reference to where it was written in `root`, or `[]` when it
|
|
5
|
+
* was not written there at all.
|
|
6
|
+
*
|
|
7
|
+
* Every {@link ResolveError} carries the path to the reference that failed, and
|
|
8
|
+
* every one of them used to be either empty or — worse — the path to the target
|
|
9
|
+
* the reference *should* have found, which by definition is a node the document
|
|
10
|
+
* does not contain. A consumer anchoring a diagnostic on it (the CLI does) sent
|
|
11
|
+
* the reader to the top of the file, or to whichever node sat nearest the hole.
|
|
12
|
+
*
|
|
13
|
+
* The index is built on the first lookup and never on a resolve that has
|
|
14
|
+
* nothing to report, which is what keeps this off the happy path — and building
|
|
15
|
+
* it *once* is what keeps a document full of broken references linear rather
|
|
16
|
+
* than paying a fresh document walk per error.
|
|
17
|
+
*
|
|
18
|
+
* The paths are paths **in `root`**, which is what a consumer can map back to a
|
|
19
|
+
* position. A reference living in some other document is simply not indexed,
|
|
20
|
+
* and an empty path says "no position" the way it always has.
|
|
21
|
+
*/
|
|
22
|
+
export declare const refPathIndex: (root: unknown, maxDepth?: number) => ((keyword: RefKeyword, ref: string) => JsonPath);
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { childRole } from "./child-role.js";
|
|
2
|
+
import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
|
|
3
|
+
import { REF_KEYWORDS } from "./reference.js";
|
|
4
|
+
const refKey = (keyword, ref) => `${keyword} ${ref}`;
|
|
5
|
+
const buildIndex = (root, maxDepth) => {
|
|
6
|
+
const index = /* @__PURE__ */ new Map();
|
|
7
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8
|
+
const stack = [{ node: root, path: [], role: "schema" }];
|
|
9
|
+
while (stack.length > 0) {
|
|
10
|
+
const frame = stack.pop();
|
|
11
|
+
if (frame === void 0)
|
|
12
|
+
break;
|
|
13
|
+
const { node, path, role } = frame;
|
|
14
|
+
if (node === null || typeof node !== "object" || role === "value")
|
|
15
|
+
continue;
|
|
16
|
+
if (path.length > maxDepth || seen.has(node))
|
|
17
|
+
continue;
|
|
18
|
+
seen.add(node);
|
|
19
|
+
if (Array.isArray(node)) {
|
|
20
|
+
for (let at = node.length - 1; at >= 0; at--) {
|
|
21
|
+
stack.push({ node: node[at], path: [...path, at], role: childRole(role, at) });
|
|
22
|
+
}
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const obj = node;
|
|
26
|
+
const keys = Object.keys(obj);
|
|
27
|
+
if (role !== "schemaMap") {
|
|
28
|
+
for (const keyword of REF_KEYWORDS) {
|
|
29
|
+
const value = obj[keyword];
|
|
30
|
+
if (typeof value !== "string")
|
|
31
|
+
continue;
|
|
32
|
+
const entry = refKey(keyword, value);
|
|
33
|
+
if (!index.has(entry))
|
|
34
|
+
index.set(entry, [...path, keyword]);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
for (let at = keys.length - 1; at >= 0; at--) {
|
|
38
|
+
const key = keys[at];
|
|
39
|
+
stack.push({ node: obj[key], path: [...path, key], role: childRole(role, key) });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return index;
|
|
43
|
+
};
|
|
44
|
+
const refPathIndex = (root, maxDepth = DEFAULT_MAX_DEPTH) => {
|
|
45
|
+
let index;
|
|
46
|
+
return (keyword, ref) => {
|
|
47
|
+
index ??= buildIndex(root, maxDepth);
|
|
48
|
+
return index.get(refKey(keyword, ref)) ?? [];
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export {
|
|
52
|
+
refPathIndex
|
|
53
|
+
};
|
package/dist/reference.d.ts
CHANGED
|
@@ -7,6 +7,15 @@ import type { JsonPath } from './types.js';
|
|
|
7
7
|
* anchor (see {@link resolveFragment}).
|
|
8
8
|
*/
|
|
9
9
|
export type RefKeyword = '$ref' | '$dynamicRef' | '$recursiveRef';
|
|
10
|
+
export declare const REF_KEYWORDS: readonly RefKeyword[];
|
|
11
|
+
/**
|
|
12
|
+
* OpenAPI 3.1 Reference Objects allow only these annotation keywords beside a
|
|
13
|
+
* `$ref`, and they *override* the target's — an `allOf` wrapper is not valid in
|
|
14
|
+
* those positions (Path Item, Response, Parameter references). They carry no
|
|
15
|
+
* validation semantics in plain JSON Schema either, so overriding is safe there
|
|
16
|
+
* too; every other sibling keyword keeps the spec-correct `allOf` combination.
|
|
17
|
+
*/
|
|
18
|
+
export declare const ANNOTATION_ONLY_SIBLINGS: Set<string>;
|
|
10
19
|
/** A reference carried by an object: which keyword, and its string value. */
|
|
11
20
|
export type Reference = {
|
|
12
21
|
keyword: RefKeyword;
|
package/dist/reference.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { childRole } from "./child-role.js";
|
|
2
|
-
import { getByPointer, pointerToPath } from "./get-by-pointer.js";
|
|
2
|
+
import { getByPointer, isPointerFragment, pointerToPath } from "./get-by-pointer.js";
|
|
3
3
|
import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
|
|
4
4
|
const REF_KEYWORDS = ["$ref", "$dynamicRef", "$recursiveRef"];
|
|
5
|
+
const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
|
|
5
6
|
const readReference = (obj) => {
|
|
6
7
|
for (const keyword of REF_KEYWORDS) {
|
|
7
8
|
const value = obj[keyword];
|
|
@@ -10,7 +11,6 @@ const readReference = (obj) => {
|
|
|
10
11
|
}
|
|
11
12
|
return void 0;
|
|
12
13
|
};
|
|
13
|
-
const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
|
|
14
14
|
const search = (root, predicate) => {
|
|
15
15
|
const seen = /* @__PURE__ */ new Set();
|
|
16
16
|
const walk = (node, pointer, depth, role) => {
|
|
@@ -54,6 +54,8 @@ const resolveFragment = (root, keyword, fragment) => {
|
|
|
54
54
|
return search(root, (obj) => obj["$anchor"] === fragment || obj["$dynamicAnchor"] === fragment);
|
|
55
55
|
};
|
|
56
56
|
export {
|
|
57
|
+
ANNOTATION_ONLY_SIBLINGS,
|
|
58
|
+
REF_KEYWORDS,
|
|
57
59
|
readReference,
|
|
58
60
|
resolveFragment
|
|
59
61
|
};
|
|
@@ -4,32 +4,30 @@ 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 { pointerToPath } from "./get-by-pointer.js";
|
|
8
7
|
import { isContainedPath } from "./is-contained-path.js";
|
|
9
8
|
import { isPrivateHost } from "./is-private-host.js";
|
|
10
9
|
import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
|
|
11
|
-
import {
|
|
10
|
+
import { refPathIndex } from "./ref-path-index.js";
|
|
11
|
+
import { ANNOTATION_ONLY_SIBLINGS, readReference, resolveFragment } from "./reference.js";
|
|
12
12
|
import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE } from "./resource-registry.js";
|
|
13
13
|
import { roleAtPath } from "./role-at-path.js";
|
|
14
14
|
import { assignKey } from "./safe-assign.js";
|
|
15
|
+
import { splitRef } from "./split-ref.js";
|
|
15
16
|
const CYCLE = /* @__PURE__ */ Symbol("cycle");
|
|
16
17
|
const MISSING = /* @__PURE__ */ Symbol("missing");
|
|
17
|
-
const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
|
|
18
18
|
const isRemote = (location) => /^https?:\/\//i.test(location);
|
|
19
19
|
const joinLocation = (base, ref) => {
|
|
20
20
|
if (isRemote(ref))
|
|
21
21
|
return ref;
|
|
22
|
-
if (isRemote(base))
|
|
23
|
-
|
|
22
|
+
if (isRemote(base)) {
|
|
23
|
+
try {
|
|
24
|
+
return new URL(ref, base).href;
|
|
25
|
+
} catch {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
24
29
|
return resolvePath(dirname(base), ref);
|
|
25
30
|
};
|
|
26
|
-
const splitRef = (ref) => {
|
|
27
|
-
const hashIdx = ref.indexOf("#");
|
|
28
|
-
return {
|
|
29
|
-
filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
|
|
30
|
-
fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
|
|
31
|
-
};
|
|
32
|
-
};
|
|
33
31
|
const REMOTE_CACHE_TTL_MS = 10 * 6e4;
|
|
34
32
|
const REMOTE_CACHE_MAX_ENTRIES = 256;
|
|
35
33
|
const remoteCache = /* @__PURE__ */ new Map();
|
|
@@ -90,6 +88,10 @@ const readCapped = async (response, maxBytes) => {
|
|
|
90
88
|
}
|
|
91
89
|
return text + decoder.decode();
|
|
92
90
|
};
|
|
91
|
+
const parseDocument = (content, location, options) => {
|
|
92
|
+
const text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
93
|
+
return options.parse === void 0 ? JSON.parse(text) : options.parse(text, location);
|
|
94
|
+
};
|
|
93
95
|
const headersFor = (url, options) => {
|
|
94
96
|
if (options.headers === void 0)
|
|
95
97
|
return void 0;
|
|
@@ -160,8 +162,7 @@ const fetchRemote = async (location, options, deadline) => {
|
|
|
160
162
|
}
|
|
161
163
|
if (!response.ok)
|
|
162
164
|
throw new Error(`HTTP ${response.status} ${response.statusText}`);
|
|
163
|
-
|
|
164
|
-
return parse(await readCapped(response, maxBytes), location);
|
|
165
|
+
return parseDocument(await readCapped(response, maxBytes), location, options);
|
|
165
166
|
}
|
|
166
167
|
throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
|
|
167
168
|
};
|
|
@@ -204,13 +205,13 @@ const needsDnsVerification = (options) => {
|
|
|
204
205
|
return false;
|
|
205
206
|
return true;
|
|
206
207
|
};
|
|
207
|
-
const loadDoc = async (location, docCache, options, errors, deadline) => {
|
|
208
|
+
const loadDoc = async (location, docCache, options, errors, deadline, refPath) => {
|
|
208
209
|
if (docCache.has(location))
|
|
209
210
|
return true;
|
|
210
211
|
if (isRemote(location)) {
|
|
211
212
|
const reason = denialReason(location, options);
|
|
212
213
|
if (reason !== null) {
|
|
213
|
-
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path:
|
|
214
|
+
errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: refPath });
|
|
214
215
|
docCache.set(location, {});
|
|
215
216
|
return false;
|
|
216
217
|
}
|
|
@@ -229,7 +230,7 @@ const loadDoc = async (location, docCache, options, errors, deadline) => {
|
|
|
229
230
|
docCache.set(location, doc);
|
|
230
231
|
return true;
|
|
231
232
|
} catch (err) {
|
|
232
|
-
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path:
|
|
233
|
+
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: refPath });
|
|
233
234
|
docCache.set(location, {});
|
|
234
235
|
return false;
|
|
235
236
|
}
|
|
@@ -246,7 +247,7 @@ const loadDoc = async (location, docCache, options, errors, deadline) => {
|
|
|
246
247
|
docCache.set(location, doc);
|
|
247
248
|
return true;
|
|
248
249
|
} catch (err) {
|
|
249
|
-
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path:
|
|
250
|
+
errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: refPath });
|
|
250
251
|
docCache.set(location, {});
|
|
251
252
|
return false;
|
|
252
253
|
} finally {
|
|
@@ -255,11 +256,10 @@ const loadDoc = async (location, docCache, options, errors, deadline) => {
|
|
|
255
256
|
}
|
|
256
257
|
}
|
|
257
258
|
try {
|
|
258
|
-
|
|
259
|
-
docCache.set(location, parse(readFileSync(location, "utf8"), location));
|
|
259
|
+
docCache.set(location, parseDocument(readFileSync(location, "utf8"), location, options));
|
|
260
260
|
return true;
|
|
261
261
|
} catch (err) {
|
|
262
|
-
errors.push({ message: String(err), path:
|
|
262
|
+
errors.push({ message: String(err), path: refPath });
|
|
263
263
|
docCache.set(location, {});
|
|
264
264
|
return false;
|
|
265
265
|
}
|
|
@@ -331,12 +331,14 @@ const detach = (node) => {
|
|
|
331
331
|
const rebaseKeptRef = (value, from, root) => {
|
|
332
332
|
if (from === root)
|
|
333
333
|
return value;
|
|
334
|
-
const { filePart, fragment } = splitRef(value);
|
|
334
|
+
const { uriPart: filePart, fragment } = splitRef(value);
|
|
335
335
|
if (filePart === "")
|
|
336
336
|
return `${renderLocation(from, root)}${value}`;
|
|
337
337
|
if (/^[a-zA-Z][a-zA-Z0-9+.-]+:/.test(filePart))
|
|
338
338
|
return value;
|
|
339
339
|
const target = joinLocation(from, filePart);
|
|
340
|
+
if (target === void 0)
|
|
341
|
+
return value;
|
|
340
342
|
const suffix = value.includes("#") ? `#${fragment}` : "";
|
|
341
343
|
return `${renderLocation(target, root)}${suffix}`;
|
|
342
344
|
};
|
|
@@ -417,7 +419,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
417
419
|
return null;
|
|
418
420
|
return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
|
|
419
421
|
};
|
|
420
|
-
if (!await loadDoc(rootLocation, docCache, options, errors, deadline)) {
|
|
422
|
+
if (!await loadDoc(rootLocation, docCache, options, errors, deadline, [])) {
|
|
421
423
|
return { resolved: {}, errors };
|
|
422
424
|
}
|
|
423
425
|
const registries = /* @__PURE__ */ new Map();
|
|
@@ -429,6 +431,7 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
429
431
|
}
|
|
430
432
|
return registry;
|
|
431
433
|
};
|
|
434
|
+
const refPathAt = refPathIndex(docCache.get(rootLocation), maxDepth);
|
|
432
435
|
let depthLimitReported = false;
|
|
433
436
|
const reportDepthLimit = () => {
|
|
434
437
|
if (depthLimitReported)
|
|
@@ -457,9 +460,9 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
457
460
|
if (reference && reference.keyword !== "$recursiveRef") {
|
|
458
461
|
const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
|
|
459
462
|
if (scoped === "external") {
|
|
460
|
-
const { filePart } = splitRef(reference.value);
|
|
461
|
-
if (filePart !== "")
|
|
462
|
-
out.
|
|
463
|
+
const { uriPart: filePart } = splitRef(reference.value);
|
|
464
|
+
if (filePart !== "" && !out.has(filePart))
|
|
465
|
+
out.set(filePart, reference);
|
|
463
466
|
}
|
|
464
467
|
}
|
|
465
468
|
for (const key of Object.keys(obj)) {
|
|
@@ -474,10 +477,18 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
474
477
|
let loaded = 1;
|
|
475
478
|
while (queue.length > 0) {
|
|
476
479
|
const location = queue.shift();
|
|
477
|
-
const out = /* @__PURE__ */ new
|
|
480
|
+
const out = /* @__PURE__ */ new Map();
|
|
478
481
|
collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out, 0, "schema");
|
|
479
|
-
for (const filePart of out) {
|
|
482
|
+
for (const [filePart, reference] of out) {
|
|
483
|
+
const refPath = location === rootLocation ? refPathAt(reference.keyword, reference.value) : [];
|
|
480
484
|
const target = joinLocation(location, filePart);
|
|
485
|
+
if (target === void 0) {
|
|
486
|
+
errors.push({
|
|
487
|
+
message: `Refusing to load $ref "${filePart}": it does not name a valid location`,
|
|
488
|
+
path: refPath
|
|
489
|
+
});
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
481
492
|
if (seen.has(target))
|
|
482
493
|
continue;
|
|
483
494
|
seen.add(target);
|
|
@@ -498,14 +509,14 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
498
509
|
if (!isRemote(target)) {
|
|
499
510
|
const reason = localDenialReason(target);
|
|
500
511
|
if (reason !== null) {
|
|
501
|
-
errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path:
|
|
512
|
+
errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path: refPath });
|
|
502
513
|
docCache.set(target, {});
|
|
503
514
|
unloadable.add(target);
|
|
504
515
|
continue;
|
|
505
516
|
}
|
|
506
517
|
}
|
|
507
518
|
loaded++;
|
|
508
|
-
if (!await loadDoc(target, docCache, options, errors, deadline))
|
|
519
|
+
if (!await loadDoc(target, docCache, options, errors, deadline, refPath))
|
|
509
520
|
unloadable.add(target);
|
|
510
521
|
queue.push(target);
|
|
511
522
|
}
|
|
@@ -566,8 +577,11 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
566
577
|
if (inScope === "external" || inScope === void 0) {
|
|
567
578
|
const parts = splitRef(value);
|
|
568
579
|
fragment = parts.fragment;
|
|
569
|
-
if (inScope === "external" && parts.
|
|
570
|
-
|
|
580
|
+
if (inScope === "external" && parts.uriPart !== "") {
|
|
581
|
+
const target = joinLocation(baseLocation, parts.uriPart);
|
|
582
|
+
if (target === void 0)
|
|
583
|
+
return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
|
|
584
|
+
targetLocation = target;
|
|
571
585
|
}
|
|
572
586
|
} else {
|
|
573
587
|
scoped = inScope;
|
|
@@ -605,18 +619,8 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
605
619
|
hoistRefSites.set(kept, cacheKey);
|
|
606
620
|
return kept;
|
|
607
621
|
}
|
|
608
|
-
const keepUnresolved = () => {
|
|
609
|
-
const kept = {};
|
|
610
|
-
for (const key of Object.keys(obj)) {
|
|
611
|
-
if (key === keyword)
|
|
612
|
-
continue;
|
|
613
|
-
assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
|
|
614
|
-
}
|
|
615
|
-
assignKey(kept, keyword, keyword === "$ref" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
|
|
616
|
-
return kept;
|
|
617
|
-
};
|
|
618
622
|
if (cached === MISSING)
|
|
619
|
-
return
|
|
623
|
+
return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
|
|
620
624
|
if (cached !== void 0) {
|
|
621
625
|
resolved2 = cached.value;
|
|
622
626
|
pointer = cached.pointer;
|
|
@@ -649,11 +653,18 @@ const resolveRefsFromFile = async (filename, options = {}) => {
|
|
|
649
653
|
if (targetLoaded) {
|
|
650
654
|
errors.push({
|
|
651
655
|
message: `Cannot resolve ${keyword} "${value}"`,
|
|
652
|
-
|
|
656
|
+
// `refPathAt` indexes the *root* document only, so it can only
|
|
657
|
+
// speak for a ref that lives there. Called unguarded it answered
|
|
658
|
+
// for a ref in a sub-document by handing back the position of an
|
|
659
|
+
// identical ref in the root — pointing a diagnostic at a line
|
|
660
|
+
// that is not the offending one. The prefetch loop above already
|
|
661
|
+
// guards this the same way; an empty path means "no position to
|
|
662
|
+
// give", which is honest.
|
|
663
|
+
path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
|
|
653
664
|
});
|
|
654
665
|
}
|
|
655
666
|
refCache.set(cacheKey, MISSING);
|
|
656
|
-
return
|
|
667
|
+
return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
|
|
657
668
|
}
|
|
658
669
|
pointer = found?.pointer ?? [];
|
|
659
670
|
resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
|
package/dist/resolve-refs.js
CHANGED
|
@@ -1,28 +1,25 @@
|
|
|
1
1
|
import { childRole } from "./child-role.js";
|
|
2
2
|
import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
|
|
3
|
-
import { pointerToPath } from "./get-by-pointer.js";
|
|
4
3
|
import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
|
|
5
|
-
import {
|
|
4
|
+
import { refPathIndex } from "./ref-path-index.js";
|
|
5
|
+
import { ANNOTATION_ONLY_SIBLINGS, readReference, resolveFragment } from "./reference.js";
|
|
6
6
|
import { baseOfNode, buildResourceRegistry, resolveRefInScope } from "./resource-registry.js";
|
|
7
7
|
import { roleAtPath } from "./role-at-path.js";
|
|
8
8
|
import { assignKey } from "./safe-assign.js";
|
|
9
9
|
const CYCLE = /* @__PURE__ */ Symbol("cycle");
|
|
10
10
|
const MISSING = /* @__PURE__ */ Symbol("missing");
|
|
11
|
-
const
|
|
12
|
-
const
|
|
11
|
+
const resolveNode = (node, base, depth, role, context) => {
|
|
12
|
+
const { root, registry, cache, origins, errors, sensitive, maxDepth, refPathAt, reportDepthLimit } = context;
|
|
13
13
|
if (node === null || typeof node !== "object")
|
|
14
14
|
return node;
|
|
15
15
|
if (role === "value")
|
|
16
16
|
return node;
|
|
17
|
-
if (depth >
|
|
18
|
-
|
|
19
|
-
limits.reported = true;
|
|
20
|
-
errors.push(depthLimitError(limits.maxDepth));
|
|
21
|
-
}
|
|
17
|
+
if (depth > maxDepth) {
|
|
18
|
+
reportDepthLimit();
|
|
22
19
|
return node;
|
|
23
20
|
}
|
|
24
21
|
if (Array.isArray(node)) {
|
|
25
|
-
const items = node.map((item, index) =>
|
|
22
|
+
const items = node.map((item, index) => resolveNode(item, base, depth + 1, childRole(role, index), context));
|
|
26
23
|
if (items.some((item) => isScopeSensitive(sensitive, item)))
|
|
27
24
|
sensitive.add(items);
|
|
28
25
|
return items;
|
|
@@ -36,7 +33,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
36
33
|
const keepReference = () => {
|
|
37
34
|
const kept = {};
|
|
38
35
|
for (const key of Object.keys(obj)) {
|
|
39
|
-
assignKey(kept, key, key === keyword ? obj[key] :
|
|
36
|
+
assignKey(kept, key, key === keyword ? obj[key] : resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context));
|
|
40
37
|
}
|
|
41
38
|
sensitive.add(kept);
|
|
42
39
|
return kept;
|
|
@@ -46,7 +43,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
46
43
|
const externalRef = () => {
|
|
47
44
|
errors.push({
|
|
48
45
|
message: `Cannot resolve external ${keyword} "${ref}": external ref requires resolveRefsFromFile`,
|
|
49
|
-
path:
|
|
46
|
+
path: refPathAt(keyword, ref)
|
|
50
47
|
});
|
|
51
48
|
return obj;
|
|
52
49
|
};
|
|
@@ -84,16 +81,15 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
84
81
|
} else {
|
|
85
82
|
cache.set(cacheKey, CYCLE);
|
|
86
83
|
if (found === void 0) {
|
|
87
|
-
const fragment = ref.startsWith("#") ? ref.slice(1) : ref;
|
|
88
84
|
errors.push({
|
|
89
85
|
message: `Cannot resolve internal ${keyword} "${ref}"`,
|
|
90
|
-
path:
|
|
86
|
+
path: refPathAt(keyword, ref)
|
|
91
87
|
});
|
|
92
88
|
cache.set(cacheKey, MISSING);
|
|
93
89
|
return obj;
|
|
94
90
|
}
|
|
95
91
|
pointer = found.pointer;
|
|
96
|
-
target =
|
|
92
|
+
target = resolveNode(found.value, targetBase, depth + 1, roleAtPath(pointer), context);
|
|
97
93
|
cache.set(cacheKey, { target, pointer });
|
|
98
94
|
if (origins && target !== null && typeof target === "object" && !origins.has(target)) {
|
|
99
95
|
origins.set(target, { location: "", pointer });
|
|
@@ -108,7 +104,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
108
104
|
const siblings = {};
|
|
109
105
|
let siblingIsSensitive = false;
|
|
110
106
|
for (const key of siblingKeys) {
|
|
111
|
-
const child =
|
|
107
|
+
const child = resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context);
|
|
112
108
|
assignKey(siblings, key, child);
|
|
113
109
|
if (isScopeSensitive(sensitive, child))
|
|
114
110
|
siblingIsSensitive = true;
|
|
@@ -139,7 +135,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
139
135
|
}
|
|
140
136
|
const result = {};
|
|
141
137
|
for (const key of Object.keys(obj)) {
|
|
142
|
-
const child =
|
|
138
|
+
const child = resolveNode(obj[key], nodeBase, depth + 1, childRole(role, key), context);
|
|
143
139
|
assignKey(result, key, child);
|
|
144
140
|
if (isScopeSensitive(sensitive, child))
|
|
145
141
|
sensitive.add(result);
|
|
@@ -151,9 +147,25 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors, lim
|
|
|
151
147
|
const resolveRefs = (data, options = {}) => {
|
|
152
148
|
const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
|
|
153
149
|
const errors = [];
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
const
|
|
150
|
+
const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
151
|
+
let depthLimitReported = false;
|
|
152
|
+
const context = {
|
|
153
|
+
root: data,
|
|
154
|
+
registry: buildResourceRegistry(data, void 0, maxDepth),
|
|
155
|
+
cache: /* @__PURE__ */ new Map(),
|
|
156
|
+
origins,
|
|
157
|
+
errors,
|
|
158
|
+
sensitive: /* @__PURE__ */ new WeakSet(),
|
|
159
|
+
maxDepth,
|
|
160
|
+
refPathAt: refPathIndex(data, maxDepth),
|
|
161
|
+
reportDepthLimit: () => {
|
|
162
|
+
if (depthLimitReported)
|
|
163
|
+
return;
|
|
164
|
+
depthLimitReported = true;
|
|
165
|
+
errors.push(depthLimitError(maxDepth));
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const resolved = resolveNode(data, context.registry.rootBase, 0, "schema", context);
|
|
157
169
|
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
158
170
|
};
|
|
159
171
|
export {
|
|
@@ -45,6 +45,20 @@ export type ResourceRegistry = {
|
|
|
45
45
|
value: unknown;
|
|
46
46
|
pointer: JsonPath;
|
|
47
47
|
}>;
|
|
48
|
+
/**
|
|
49
|
+
* Embedded-resource root → the base URI its `$id` established, by node
|
|
50
|
+
* identity. This is the inverse of {@link ResourceRegistry.resources}, kept
|
|
51
|
+
* because that is the direction the resolvers ask in: they hold a node and
|
|
52
|
+
* want its base. Scanning `resources` for it made every `$id` node cost a
|
|
53
|
+
* pass over every resource in the document, which is quadratic on exactly the
|
|
54
|
+
* bundled schemas that declare an `$id` per definition.
|
|
55
|
+
*
|
|
56
|
+
* It also answers for a node `resources` never took — a second `$id`
|
|
57
|
+
* resolving to a URI already claimed — where the scan fell back to the
|
|
58
|
+
* enclosing base and disagreed with the base this walk registered that node's
|
|
59
|
+
* own anchors under.
|
|
60
|
+
*/
|
|
61
|
+
bases: Map<object, string>;
|
|
48
62
|
/** `${base}#${name}` → target, for `$anchor` and `$dynamicAnchor` alike. */
|
|
49
63
|
staticAnchors: Map<string, {
|
|
50
64
|
value: unknown;
|
|
@@ -77,11 +91,6 @@ export type ResourceRegistry = {
|
|
|
77
91
|
export declare const SYNTHETIC_BASE = "https://mjst-internal.invalid/document";
|
|
78
92
|
/** `new URL(ref, base).href`, or `undefined` when the pair does not parse. */
|
|
79
93
|
export declare const resolveUri: (ref: string, base: string) => string | undefined;
|
|
80
|
-
/** Splits a ref string into its URI part and its fragment (pointer or anchor name). */
|
|
81
|
-
export declare const splitFragment: (ref: string) => {
|
|
82
|
-
uriPart: string;
|
|
83
|
-
fragment: string;
|
|
84
|
-
};
|
|
85
94
|
/** The base URI a subschema establishes via `$id`, or the enclosing base. */
|
|
86
95
|
export declare const baseAfterId: (node: Record<string, unknown>, enclosingBase: string) => string;
|
|
87
96
|
/**
|
|
@@ -89,12 +98,12 @@ export declare const baseAfterId: (node: Record<string, unknown>, enclosingBase:
|
|
|
89
98
|
* every anchor under the base URI it is scoped to. First declaration wins on
|
|
90
99
|
* a duplicate URI or anchor name, matching document order.
|
|
91
100
|
*/
|
|
92
|
-
export declare const buildResourceRegistry: (root: unknown,
|
|
101
|
+
export declare const buildResourceRegistry: (root: unknown, documentBase?: string, maxDepth?: number) => ResourceRegistry;
|
|
93
102
|
/**
|
|
94
103
|
* The base URI `node` establishes via its `$id`, as assigned during the
|
|
95
|
-
* registry walk
|
|
96
|
-
*
|
|
97
|
-
* resource resolve against the right base.
|
|
104
|
+
* registry walk, or `enclosing` when its `$id` established none (a draft-07
|
|
105
|
+
* `$id: "#name"`, or one that does not parse). Resolvers call this while
|
|
106
|
+
* walking so refs inside an embedded resource resolve against the right base.
|
|
98
107
|
*/
|
|
99
108
|
export declare const baseOfNode: (registry: ResourceRegistry, node: Record<string, unknown>, enclosing: string) => string;
|
|
100
109
|
/**
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { childRole } from "./child-role.js";
|
|
2
|
-
import { getByPointer, pointerToPath } from "./get-by-pointer.js";
|
|
2
|
+
import { getByPointer, isPointerFragment, pointerToPath } from "./get-by-pointer.js";
|
|
3
3
|
import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
|
|
4
|
+
import { splitRef } from "./split-ref.js";
|
|
4
5
|
const SYNTHETIC_BASE = "https://mjst-internal.invalid/document";
|
|
5
6
|
const resolveUri = (ref, base) => {
|
|
6
7
|
try {
|
|
@@ -13,13 +14,6 @@ const withoutFragment = (uri) => {
|
|
|
13
14
|
const hashIdx = uri.indexOf("#");
|
|
14
15
|
return hashIdx === -1 ? uri : uri.slice(0, hashIdx);
|
|
15
16
|
};
|
|
16
|
-
const splitFragment = (ref) => {
|
|
17
|
-
const hashIdx = ref.indexOf("#");
|
|
18
|
-
return {
|
|
19
|
-
uriPart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
|
|
20
|
-
fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
|
|
21
|
-
};
|
|
22
|
-
};
|
|
23
17
|
const baseAfterId = (node, enclosingBase) => {
|
|
24
18
|
const id = node["$id"];
|
|
25
19
|
if (typeof id !== "string" || id === "")
|
|
@@ -30,8 +24,10 @@ const baseAfterId = (node, enclosingBase) => {
|
|
|
30
24
|
const bare = withoutFragment(resolved);
|
|
31
25
|
return bare === "" ? enclosingBase : bare;
|
|
32
26
|
};
|
|
33
|
-
const buildResourceRegistry = (root,
|
|
27
|
+
const buildResourceRegistry = (root, documentBase = SYNTHETIC_BASE, maxDepth = DEFAULT_MAX_DEPTH) => {
|
|
28
|
+
const initialBase = withoutFragment(documentBase);
|
|
34
29
|
const resources = /* @__PURE__ */ new Map();
|
|
30
|
+
const bases = /* @__PURE__ */ new Map();
|
|
35
31
|
const staticAnchors = /* @__PURE__ */ new Map();
|
|
36
32
|
const dynamicAnchors = /* @__PURE__ */ new Map();
|
|
37
33
|
const dynamicAnchorCounts = /* @__PURE__ */ new Map();
|
|
@@ -63,8 +59,12 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DE
|
|
|
63
59
|
}
|
|
64
60
|
const record = node;
|
|
65
61
|
const nodeBase = role === "schemaMap" ? base : baseAfterId(record, base);
|
|
66
|
-
if (nodeBase !== base
|
|
67
|
-
resources.
|
|
62
|
+
if (nodeBase !== base) {
|
|
63
|
+
if (!resources.has(nodeBase))
|
|
64
|
+
resources.set(nodeBase, { value: node, pointer });
|
|
65
|
+
if (!bases.has(node))
|
|
66
|
+
bases.set(node, nodeBase);
|
|
67
|
+
}
|
|
68
68
|
if (role !== "schemaMap")
|
|
69
69
|
registerAnchors(record, nodeBase, pointer);
|
|
70
70
|
for (const key of Object.keys(record)) {
|
|
@@ -73,43 +73,38 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DE
|
|
|
73
73
|
};
|
|
74
74
|
if (rootBase !== initialBase)
|
|
75
75
|
resources.set(rootBase, { value: root, pointer: [] });
|
|
76
|
-
if (!resources.has(
|
|
77
|
-
resources.set(
|
|
78
|
-
}
|
|
76
|
+
if (!resources.has(initialBase))
|
|
77
|
+
resources.set(initialBase, { value: root, pointer: [] });
|
|
79
78
|
walk(root, initialBase, [], 0, "schema");
|
|
80
79
|
const ambiguousDynamicAnchors = /* @__PURE__ */ new Set();
|
|
81
80
|
for (const [name, count] of dynamicAnchorCounts) {
|
|
82
81
|
if (count > 1)
|
|
83
82
|
ambiguousDynamicAnchors.add(name);
|
|
84
83
|
}
|
|
85
|
-
return { resources, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
|
|
84
|
+
return { resources, bases, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
|
|
86
85
|
};
|
|
87
86
|
const getByPointerWithBase = (start, startBase, startPointer, fragment) => {
|
|
88
87
|
const value = getByPointer(start, fragment);
|
|
89
88
|
if (value === void 0)
|
|
90
89
|
return void 0;
|
|
90
|
+
const path = pointerToPath(fragment);
|
|
91
91
|
let base = startBase;
|
|
92
92
|
let current = start;
|
|
93
|
-
for (const segment of
|
|
93
|
+
for (const segment of path) {
|
|
94
94
|
if (current === null || typeof current !== "object")
|
|
95
95
|
break;
|
|
96
96
|
if (!Array.isArray(current))
|
|
97
97
|
base = baseAfterId(current, base);
|
|
98
|
+
if (!Object.hasOwn(current, segment))
|
|
99
|
+
break;
|
|
98
100
|
current = current[segment];
|
|
99
101
|
}
|
|
100
102
|
if (current !== null && typeof current === "object" && !Array.isArray(current)) {
|
|
101
103
|
base = baseAfterId(current, base);
|
|
102
104
|
}
|
|
103
|
-
return { value, pointer: [...startPointer, ...
|
|
104
|
-
};
|
|
105
|
-
const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
|
|
106
|
-
const baseOfNode = (registry, node, enclosing) => {
|
|
107
|
-
for (const [uri, resource] of registry.resources) {
|
|
108
|
-
if (resource.value === node)
|
|
109
|
-
return uri;
|
|
110
|
-
}
|
|
111
|
-
return enclosing;
|
|
105
|
+
return { value, pointer: [...startPointer, ...path], base };
|
|
112
106
|
};
|
|
107
|
+
const baseOfNode = (registry, node, enclosing) => registry.bases.get(node) ?? enclosing;
|
|
113
108
|
const lookupAnchor = (registry, keyword, base, name) => {
|
|
114
109
|
const key = `${base}#${name}`;
|
|
115
110
|
if (keyword === "$dynamicRef")
|
|
@@ -117,7 +112,7 @@ const lookupAnchor = (registry, keyword, base, name) => {
|
|
|
117
112
|
return registry.staticAnchors.get(key);
|
|
118
113
|
};
|
|
119
114
|
const resolveRefInScope = (registry, keyword, ref, currentBase) => {
|
|
120
|
-
const { uriPart, fragment } =
|
|
115
|
+
const { uriPart, fragment } = splitRef(ref);
|
|
121
116
|
if (uriPart === "") {
|
|
122
117
|
if (isPointerFragment(fragment)) {
|
|
123
118
|
const resource2 = registry.resources.get(currentBase);
|
|
@@ -150,6 +145,5 @@ export {
|
|
|
150
145
|
baseOfNode,
|
|
151
146
|
buildResourceRegistry,
|
|
152
147
|
resolveRefInScope,
|
|
153
|
-
resolveUri
|
|
154
|
-
splitFragment
|
|
148
|
+
resolveUri
|
|
155
149
|
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a reference string into the part naming a document and the fragment
|
|
3
|
+
* that addresses something inside it (a JSON Pointer, or a plain-name anchor).
|
|
4
|
+
*
|
|
5
|
+
* Everything before the first `#` is the document part. What that part *means*
|
|
6
|
+
* depends on who is asking — `resource-registry.ts` resolves it as a URI
|
|
7
|
+
* against the enclosing `$id` base, `resolve-refs-from-file.ts` as a file path
|
|
8
|
+
* or URL relative to the referencing document's location — but the split itself
|
|
9
|
+
* is the same one, which is why it lives here rather than in both.
|
|
10
|
+
*/
|
|
11
|
+
export declare const splitRef: (ref: string) => {
|
|
12
|
+
uriPart: string;
|
|
13
|
+
fragment: string;
|
|
14
|
+
};
|
package/dist/types.d.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A path into a JSON document: object keys and array indices, in order.
|
|
3
|
-
* report the location of the offending `$ref` with one of these.
|
|
2
|
+
* A path into a JSON document: object keys and array indices, in order.
|
|
4
3
|
*/
|
|
5
4
|
export type JsonPath = (string | number)[];
|
|
6
5
|
/** A single `$ref` resolution failure (a missing file, a bad URL, a refusal). */
|
|
7
6
|
export type ResolveError = {
|
|
8
7
|
message: string;
|
|
8
|
+
/**
|
|
9
|
+
* Where the reference that failed was written, as a path in the document you
|
|
10
|
+
* asked to resolve — ending in the reference keyword, so it points at the
|
|
11
|
+
* `$ref` line itself rather than at the schema around it. Anchor a diagnostic
|
|
12
|
+
* on it and the reader lands on the reference they have to fix.
|
|
13
|
+
*
|
|
14
|
+
* Empty when there is nowhere to point: a failure that belongs to the resolve
|
|
15
|
+
* as a whole (a depth or document budget), or a reference written in some
|
|
16
|
+
* other document rather than in the one you named. A reference used in
|
|
17
|
+
* several places is reported once, at the first.
|
|
18
|
+
*/
|
|
9
19
|
path: JsonPath;
|
|
10
20
|
};
|
|
11
21
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/resolve-refs",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
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",
|
|
@@ -52,6 +52,6 @@
|
|
|
52
52
|
}
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
-
"@amritk/runtime-validators": "^0.
|
|
55
|
+
"@amritk/runtime-validators": "^0.12.0"
|
|
56
56
|
}
|
|
57
57
|
}
|