@amritk/resolve-refs 0.4.5 → 0.7.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 +17 -7
- package/README.md +93 -16
- package/dist/assert-public-host.d.ts +39 -0
- package/dist/assert-public-host.js +28 -0
- package/dist/child-role.d.ts +43 -0
- package/dist/child-role.js +45 -0
- package/dist/dynamic-scope.d.ts +70 -0
- package/dist/dynamic-scope.js +25 -0
- package/dist/get-by-pointer.d.ts +6 -0
- package/dist/get-by-pointer.js +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/is-contained-path.d.ts +12 -0
- package/dist/is-contained-path.js +32 -0
- package/dist/is-private-host.d.ts +11 -4
- package/dist/is-private-host.js +24 -10
- package/dist/max-depth.d.ts +24 -0
- package/dist/max-depth.js +9 -0
- package/dist/reference.js +11 -6
- package/dist/resolve-refs-from-file.d.ts +22 -3
- package/dist/resolve-refs-from-file.js +414 -43
- package/dist/resolve-refs.d.ts +31 -3
- package/dist/resolve-refs.js +55 -14
- package/dist/resource-registry.d.ts +15 -4
- package/dist/resource-registry.js +26 -12
- package/dist/role-at-path.d.ts +17 -0
- package/dist/role-at-path.js +5 -0
- package/dist/types.d.ts +75 -1
- package/package.json +7 -1
package/dist/resolve-refs.d.ts
CHANGED
|
@@ -8,15 +8,43 @@ export type ResolveRefsOptions = {
|
|
|
8
8
|
* Defaults to `false`.
|
|
9
9
|
*/
|
|
10
10
|
trackOrigins?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* How deep the resolver walks before leaving a subtree unresolved and
|
|
13
|
+
* recording an error. Defaults to `512`. The walk is recursive, so a
|
|
14
|
+
* pathologically nested document would otherwise unwind the stack with a
|
|
15
|
+
* `RangeError` — a thrown error this package promises never to throw.
|
|
16
|
+
*/
|
|
17
|
+
maxDepth?: number;
|
|
11
18
|
};
|
|
12
19
|
/**
|
|
13
20
|
* Resolves all internal `$ref`s in an in-memory document — plain `#/...`
|
|
14
21
|
* pointers, `$anchor`/`$dynamicAnchor` names (scoped by `$id`), and refs whose
|
|
15
22
|
* URI matches an embedded resource's `$id` — inlining each target. Refs to
|
|
16
23
|
* other files/URLs are left in place and reported on `errors` (this resolver
|
|
17
|
-
* can't load other documents — use `resolveRefsFromFile` for those).
|
|
18
|
-
*
|
|
19
|
-
*
|
|
24
|
+
* can't load other documents — use `resolveRefsFromFile` for those).
|
|
25
|
+
*
|
|
26
|
+
* Only references in *schema* positions are inlined: a `$ref`-shaped object
|
|
27
|
+
* inside `enum`, `const`, `default` or `examples` is instance data and is kept
|
|
28
|
+
* verbatim (see `child-role.ts`).
|
|
29
|
+
*
|
|
30
|
+
* **Not every reference can be inlined, and the ones that cannot are kept.** The
|
|
31
|
+
* output is a dereferenced document with two documented exceptions, both of
|
|
32
|
+
* which resolve *within* the output:
|
|
33
|
+
*
|
|
34
|
+
* - a **cycle** keeps its reference node, so a recursive schema keeps its
|
|
35
|
+
* recursive branch instead of collapsing to `{}`;
|
|
36
|
+
* - a **`$dynamicRef` that binds at evaluation time** keeps its keyword, along
|
|
37
|
+
* with the `$dynamicAnchor`s it may bind to and the `$id`s scoping them.
|
|
38
|
+
* Inlining one target would be a guess, and a wrong guess changes what the
|
|
39
|
+
* document accepts; a reference kept in place does not (see
|
|
40
|
+
* `dynamic-scope.ts`). A `$ref` whose target carries that scaffolding is kept
|
|
41
|
+
* for the same reason when inlining it would move the scaffolding out of the
|
|
42
|
+
* resource that scopes it.
|
|
43
|
+
*
|
|
44
|
+
* Neither is an error — nothing failed — so neither appears on `errors`, and
|
|
45
|
+
* neither is inlined, so neither is stamped in `origins`. A consumer walking the
|
|
46
|
+
* output should treat a leftover `$ref`/`$dynamicRef` the way it treats one in
|
|
47
|
+
* the input.
|
|
20
48
|
*
|
|
21
49
|
* @example
|
|
22
50
|
* ```ts
|
package/dist/resolve-refs.js
CHANGED
|
@@ -1,21 +1,48 @@
|
|
|
1
|
+
import { childRole } from "./child-role.js";
|
|
2
|
+
import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
|
|
1
3
|
import { pointerToPath } from "./get-by-pointer.js";
|
|
4
|
+
import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
|
|
2
5
|
import { readReference, resolveFragment } from "./reference.js";
|
|
3
6
|
import { baseOfNode, buildResourceRegistry, resolveRefInScope } from "./resource-registry.js";
|
|
7
|
+
import { roleAtPath } from "./role-at-path.js";
|
|
4
8
|
import { assignKey } from "./safe-assign.js";
|
|
5
9
|
const CYCLE = /* @__PURE__ */ Symbol("cycle");
|
|
6
10
|
const MISSING = /* @__PURE__ */ Symbol("missing");
|
|
7
11
|
const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
|
|
8
|
-
const resolveInternal = (node, root, registry, base, cache, origins, errors) => {
|
|
12
|
+
const resolveInternal = (node, root, registry, base, cache, origins, errors, limits, depth, role, sensitive) => {
|
|
9
13
|
if (node === null || typeof node !== "object")
|
|
10
14
|
return node;
|
|
15
|
+
if (role === "value")
|
|
16
|
+
return node;
|
|
17
|
+
if (depth > limits.maxDepth) {
|
|
18
|
+
if (!limits.reported) {
|
|
19
|
+
limits.reported = true;
|
|
20
|
+
errors.push(depthLimitError(limits.maxDepth));
|
|
21
|
+
}
|
|
22
|
+
return node;
|
|
23
|
+
}
|
|
11
24
|
if (Array.isArray(node)) {
|
|
12
|
-
|
|
25
|
+
const items = node.map((item, index) => resolveInternal(item, root, registry, base, cache, origins, errors, limits, depth + 1, childRole(role, index), sensitive));
|
|
26
|
+
if (items.some((item) => isScopeSensitive(sensitive, item)))
|
|
27
|
+
sensitive.add(items);
|
|
28
|
+
return items;
|
|
13
29
|
}
|
|
14
30
|
const obj = node;
|
|
15
|
-
const
|
|
16
|
-
const
|
|
31
|
+
const isSchema = role !== "schemaMap";
|
|
32
|
+
const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
|
|
33
|
+
const reference = isSchema ? readReference(obj) : void 0;
|
|
17
34
|
if (reference) {
|
|
18
35
|
const { keyword, value: ref } = reference;
|
|
36
|
+
const keepReference = () => {
|
|
37
|
+
const kept = {};
|
|
38
|
+
for (const key of Object.keys(obj)) {
|
|
39
|
+
assignKey(kept, key, key === keyword ? obj[key] : resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors, limits, depth + 1, childRole(role, key), sensitive));
|
|
40
|
+
}
|
|
41
|
+
sensitive.add(kept);
|
|
42
|
+
return kept;
|
|
43
|
+
};
|
|
44
|
+
if (bindsAtEvaluationTime(keyword, ref, registry.ambiguousDynamicAnchors))
|
|
45
|
+
return keepReference();
|
|
19
46
|
const externalRef = () => {
|
|
20
47
|
errors.push({
|
|
21
48
|
message: `Cannot resolve external ${keyword} "${ref}": external ref requires resolveRefsFromFile`,
|
|
@@ -49,11 +76,7 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors) =>
|
|
|
49
76
|
if (cached === MISSING)
|
|
50
77
|
return obj;
|
|
51
78
|
if (cached === CYCLE) {
|
|
52
|
-
|
|
53
|
-
for (const key of Object.keys(obj)) {
|
|
54
|
-
assignKey(kept, key, key === keyword ? obj[key] : resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors));
|
|
55
|
-
}
|
|
56
|
-
return kept;
|
|
79
|
+
return keepReference();
|
|
57
80
|
}
|
|
58
81
|
if (cached !== void 0) {
|
|
59
82
|
target = cached.target;
|
|
@@ -70,19 +93,27 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors) =>
|
|
|
70
93
|
return obj;
|
|
71
94
|
}
|
|
72
95
|
pointer = found.pointer;
|
|
73
|
-
target = resolveInternal(found.value, root, registry, targetBase, cache, origins, errors);
|
|
96
|
+
target = resolveInternal(found.value, root, registry, targetBase, cache, origins, errors, limits, depth + 1, roleAtPath(pointer), sensitive);
|
|
74
97
|
cache.set(cacheKey, { target, pointer });
|
|
75
98
|
if (origins && target !== null && typeof target === "object" && !origins.has(target)) {
|
|
76
99
|
origins.set(target, { location: "", pointer });
|
|
77
100
|
}
|
|
78
101
|
}
|
|
102
|
+
if (isScopeSensitive(sensitive, target) && !inliningKeepsScope(target, nodeBase, targetBase)) {
|
|
103
|
+
return keepReference();
|
|
104
|
+
}
|
|
79
105
|
const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
|
|
80
106
|
if (siblingKeys.length === 0)
|
|
81
107
|
return target;
|
|
82
108
|
const siblings = {};
|
|
109
|
+
let siblingIsSensitive = false;
|
|
83
110
|
for (const key of siblingKeys) {
|
|
84
|
-
|
|
111
|
+
const child = resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors, limits, depth + 1, childRole(role, key), sensitive);
|
|
112
|
+
assignKey(siblings, key, child);
|
|
113
|
+
if (isScopeSensitive(sensitive, child))
|
|
114
|
+
siblingIsSensitive = true;
|
|
85
115
|
}
|
|
116
|
+
const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, target) || declaresAmbiguousAnchor(obj, registry.ambiguousDynamicAnchors);
|
|
86
117
|
if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
|
|
87
118
|
if (target !== null && typeof target === "object" && !Array.isArray(target)) {
|
|
88
119
|
const overridden = {};
|
|
@@ -92,6 +123,8 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors) =>
|
|
|
92
123
|
assignKey(overridden, key, siblings[key]);
|
|
93
124
|
if (origins && !origins.has(overridden))
|
|
94
125
|
origins.set(overridden, { location: "", pointer });
|
|
126
|
+
if (inlineIsSensitive)
|
|
127
|
+
sensitive.add(overridden);
|
|
95
128
|
return overridden;
|
|
96
129
|
}
|
|
97
130
|
return target;
|
|
@@ -100,19 +133,27 @@ const resolveInternal = (node, root, registry, base, cache, origins, errors) =>
|
|
|
100
133
|
const merged = { ...siblings, allOf: [...existingAllOf, target] };
|
|
101
134
|
if (origins && !origins.has(merged))
|
|
102
135
|
origins.set(merged, { location: "", pointer });
|
|
136
|
+
if (inlineIsSensitive)
|
|
137
|
+
sensitive.add(merged);
|
|
103
138
|
return merged;
|
|
104
139
|
}
|
|
105
140
|
const result = {};
|
|
106
141
|
for (const key of Object.keys(obj)) {
|
|
107
|
-
|
|
142
|
+
const child = resolveInternal(obj[key], root, registry, nodeBase, cache, origins, errors, limits, depth + 1, childRole(role, key), sensitive);
|
|
143
|
+
assignKey(result, key, child);
|
|
144
|
+
if (isScopeSensitive(sensitive, child))
|
|
145
|
+
sensitive.add(result);
|
|
108
146
|
}
|
|
147
|
+
if (isSchema && declaresAmbiguousAnchor(obj, registry.ambiguousDynamicAnchors))
|
|
148
|
+
sensitive.add(result);
|
|
109
149
|
return result;
|
|
110
150
|
};
|
|
111
151
|
const resolveRefs = (data, options = {}) => {
|
|
112
152
|
const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
|
|
113
153
|
const errors = [];
|
|
114
|
-
const
|
|
115
|
-
const
|
|
154
|
+
const limits = { maxDepth: options.maxDepth ?? DEFAULT_MAX_DEPTH, reported: false };
|
|
155
|
+
const registry = buildResourceRegistry(data, void 0, limits.maxDepth);
|
|
156
|
+
const resolved = resolveInternal(data, data, registry, registry.rootBase, /* @__PURE__ */ new Map(), origins, errors, limits, 0, "schema", /* @__PURE__ */ new WeakSet());
|
|
116
157
|
return origins ? { resolved, errors, origins } : { resolved, errors };
|
|
117
158
|
};
|
|
118
159
|
export {
|
|
@@ -18,9 +18,10 @@ import type { JsonPath } from './types.js';
|
|
|
18
18
|
* - A ref whose URI (resolved against the enclosing base) matches an embedded
|
|
19
19
|
* resource's `$id` resolves to that resource without any fetching; a pointer
|
|
20
20
|
* or anchor fragment on such a ref applies *within* that resource.
|
|
21
|
-
* - A
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* - A `#/pointer` fragment resolves **within the resource it appears in**, per
|
|
22
|
+
* the spec: a nested `$id` re-bases the pointers inside it. A pointer that
|
|
23
|
+
* matches nothing there falls back to the document root, because bundled
|
|
24
|
+
* documents in the wild point at the root from inside an `$id` scope.
|
|
24
25
|
* - `$dynamicRef` prefers a `$dynamicAnchor` in scope, then degrades to `$ref`
|
|
25
26
|
* semantics. The full dynamic-scope algorithm (outermost anchor along the
|
|
26
27
|
* *runtime* reference chain) is not modelled — for the single bundled
|
|
@@ -54,6 +55,14 @@ export type ResourceRegistry = {
|
|
|
54
55
|
value: unknown;
|
|
55
56
|
pointer: JsonPath;
|
|
56
57
|
}>;
|
|
58
|
+
/**
|
|
59
|
+
* `$dynamicAnchor` names the document declares more than once — the names a
|
|
60
|
+
* `$dynamicRef` cannot be bound to statically, because which declaration wins
|
|
61
|
+
* is decided by the dynamic scope at evaluation time. A name declared once (or
|
|
62
|
+
* not at all) is absent from this set and stays inlinable; see
|
|
63
|
+
* `dynamic-scope.ts` for what the resolver does with the rest.
|
|
64
|
+
*/
|
|
65
|
+
ambiguousDynamicAnchors: Set<string>;
|
|
57
66
|
/** The document root's base URI (its root `$id` resolved, or the initial base). */
|
|
58
67
|
rootBase: string;
|
|
59
68
|
/** The document root value, for root-relative pointer lookups. */
|
|
@@ -73,12 +82,14 @@ export declare const splitFragment: (ref: string) => {
|
|
|
73
82
|
uriPart: string;
|
|
74
83
|
fragment: string;
|
|
75
84
|
};
|
|
85
|
+
/** The base URI a subschema establishes via `$id`, or the enclosing base. */
|
|
86
|
+
export declare const baseAfterId: (node: Record<string, unknown>, enclosingBase: string) => string;
|
|
76
87
|
/**
|
|
77
88
|
* Walks the document once, registering every embedded resource (`$id`) and
|
|
78
89
|
* every anchor under the base URI it is scoped to. First declaration wins on
|
|
79
90
|
* a duplicate URI or anchor name, matching document order.
|
|
80
91
|
*/
|
|
81
|
-
export declare const buildResourceRegistry: (root: unknown, initialBase?: string) => ResourceRegistry;
|
|
92
|
+
export declare const buildResourceRegistry: (root: unknown, initialBase?: string, maxDepth?: number) => ResourceRegistry;
|
|
82
93
|
/**
|
|
83
94
|
* The base URI `node` establishes via its `$id`, as assigned during the
|
|
84
95
|
* registry walk (identity lookup), or `enclosing` when it declares none that
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { childRole } from "./child-role.js";
|
|
1
2
|
import { getByPointer, pointerToPath } from "./get-by-pointer.js";
|
|
3
|
+
import { DEFAULT_MAX_DEPTH } from "./max-depth.js";
|
|
2
4
|
const SYNTHETIC_BASE = "https://mjst-internal.invalid/document";
|
|
3
|
-
const NON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
|
|
4
5
|
const resolveUri = (ref, base) => {
|
|
5
6
|
try {
|
|
6
7
|
return new URL(ref, base).href;
|
|
@@ -29,10 +30,11 @@ const baseAfterId = (node, enclosingBase) => {
|
|
|
29
30
|
const bare = withoutFragment(resolved);
|
|
30
31
|
return bare === "" ? enclosingBase : bare;
|
|
31
32
|
};
|
|
32
|
-
const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE) => {
|
|
33
|
+
const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE, maxDepth = DEFAULT_MAX_DEPTH) => {
|
|
33
34
|
const resources = /* @__PURE__ */ new Map();
|
|
34
35
|
const staticAnchors = /* @__PURE__ */ new Map();
|
|
35
36
|
const dynamicAnchors = /* @__PURE__ */ new Map();
|
|
37
|
+
const dynamicAnchorCounts = /* @__PURE__ */ new Map();
|
|
36
38
|
const rootBase = root !== null && typeof root === "object" && !Array.isArray(root) ? baseAfterId(root, initialBase) : initialBase;
|
|
37
39
|
const registerAnchors = (node, base, pointer) => {
|
|
38
40
|
const anchor = node["$anchor"];
|
|
@@ -43,6 +45,7 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE) => {
|
|
|
43
45
|
}
|
|
44
46
|
const dynamicAnchor = node["$dynamicAnchor"];
|
|
45
47
|
if (typeof dynamicAnchor === "string") {
|
|
48
|
+
dynamicAnchorCounts.set(dynamicAnchor, (dynamicAnchorCounts.get(dynamicAnchor) ?? 0) + 1);
|
|
46
49
|
const key = `${base}#${dynamicAnchor}`;
|
|
47
50
|
if (!dynamicAnchors.has(key))
|
|
48
51
|
dynamicAnchors.set(key, { value: node, pointer });
|
|
@@ -50,23 +53,22 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE) => {
|
|
|
50
53
|
staticAnchors.set(key, { value: node, pointer });
|
|
51
54
|
}
|
|
52
55
|
};
|
|
53
|
-
const walk = (node, base, pointer) => {
|
|
54
|
-
if (node === null || typeof node !== "object")
|
|
56
|
+
const walk = (node, base, pointer, depth, role) => {
|
|
57
|
+
if (node === null || typeof node !== "object" || depth > maxDepth || role === "value")
|
|
55
58
|
return;
|
|
56
59
|
if (Array.isArray(node)) {
|
|
57
60
|
for (let i = 0; i < node.length; i++)
|
|
58
|
-
walk(node[i], base, [...pointer, i]);
|
|
61
|
+
walk(node[i], base, [...pointer, i], depth + 1, childRole(role, i));
|
|
59
62
|
return;
|
|
60
63
|
}
|
|
61
64
|
const record = node;
|
|
62
|
-
const nodeBase = baseAfterId(record, base);
|
|
65
|
+
const nodeBase = role === "schemaMap" ? base : baseAfterId(record, base);
|
|
63
66
|
if (nodeBase !== base && !resources.has(nodeBase))
|
|
64
67
|
resources.set(nodeBase, { value: node, pointer });
|
|
65
|
-
|
|
68
|
+
if (role !== "schemaMap")
|
|
69
|
+
registerAnchors(record, nodeBase, pointer);
|
|
66
70
|
for (const key of Object.keys(record)) {
|
|
67
|
-
|
|
68
|
-
continue;
|
|
69
|
-
walk(record[key], nodeBase, [...pointer, key]);
|
|
71
|
+
walk(record[key], nodeBase, [...pointer, key], depth + 1, childRole(role, key));
|
|
70
72
|
}
|
|
71
73
|
};
|
|
72
74
|
if (rootBase !== initialBase)
|
|
@@ -74,8 +76,13 @@ const buildResourceRegistry = (root, initialBase = SYNTHETIC_BASE) => {
|
|
|
74
76
|
if (!resources.has(withoutFragment(initialBase))) {
|
|
75
77
|
resources.set(withoutFragment(initialBase), { value: root, pointer: [] });
|
|
76
78
|
}
|
|
77
|
-
walk(root, initialBase, []);
|
|
78
|
-
|
|
79
|
+
walk(root, initialBase, [], 0, "schema");
|
|
80
|
+
const ambiguousDynamicAnchors = /* @__PURE__ */ new Set();
|
|
81
|
+
for (const [name, count] of dynamicAnchorCounts) {
|
|
82
|
+
if (count > 1)
|
|
83
|
+
ambiguousDynamicAnchors.add(name);
|
|
84
|
+
}
|
|
85
|
+
return { resources, staticAnchors, dynamicAnchors, ambiguousDynamicAnchors, rootBase, root };
|
|
79
86
|
};
|
|
80
87
|
const getByPointerWithBase = (start, startBase, startPointer, fragment) => {
|
|
81
88
|
const value = getByPointer(start, fragment);
|
|
@@ -113,6 +120,12 @@ const resolveRefInScope = (registry, keyword, ref, currentBase) => {
|
|
|
113
120
|
const { uriPart, fragment } = splitFragment(ref);
|
|
114
121
|
if (uriPart === "") {
|
|
115
122
|
if (isPointerFragment(fragment)) {
|
|
123
|
+
const resource2 = registry.resources.get(currentBase);
|
|
124
|
+
if (resource2 !== void 0) {
|
|
125
|
+
const scoped = getByPointerWithBase(resource2.value, currentBase, resource2.pointer, fragment);
|
|
126
|
+
if (scoped !== void 0)
|
|
127
|
+
return scoped;
|
|
128
|
+
}
|
|
116
129
|
return getByPointerWithBase(registry.root, registry.rootBase, [], fragment);
|
|
117
130
|
}
|
|
118
131
|
const anchored2 = lookupAnchor(registry, keyword, currentBase, fragment);
|
|
@@ -133,6 +146,7 @@ const resolveRefInScope = (registry, keyword, ref, currentBase) => {
|
|
|
133
146
|
};
|
|
134
147
|
export {
|
|
135
148
|
SYNTHETIC_BASE,
|
|
149
|
+
baseAfterId,
|
|
136
150
|
baseOfNode,
|
|
137
151
|
buildResourceRegistry,
|
|
138
152
|
resolveRefInScope,
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type NodeRole } from './child-role.js';
|
|
2
|
+
import type { JsonPath } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* The role of the node a document path leads to, starting from the document
|
|
5
|
+
* root (which is a schema).
|
|
6
|
+
*
|
|
7
|
+
* A reference is inlined by resolving its *target*, so the target has to be
|
|
8
|
+
* walked with the role it has where it is defined, not the role of the node
|
|
9
|
+
* pointing at it. `#/$defs/a` lands in a schema whichever keyword the reference
|
|
10
|
+
* sat under, and `#/components/schemas/Foo` lands outside the vocabulary either
|
|
11
|
+
* way — so resolution of a given target does not depend on who referenced it,
|
|
12
|
+
* and the resolvers can keep memoizing per unique ref.
|
|
13
|
+
*
|
|
14
|
+
* The path segments alone are enough: no part of the classification depends on
|
|
15
|
+
* the values in the document.
|
|
16
|
+
*/
|
|
17
|
+
export declare const roleAtPath: (pointer: JsonPath) => NodeRole;
|
package/dist/types.d.ts
CHANGED
|
@@ -43,10 +43,42 @@ export type ResolveOptions = {
|
|
|
43
43
|
* Whether http(s) `$ref`s may be fetched. Defaults to `true`.
|
|
44
44
|
*/
|
|
45
45
|
remote?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Whether `$ref`s to other files on disk may be read. Defaults to `true`.
|
|
48
|
+
* Pass `false` for a document from an untrusted source: the root document
|
|
49
|
+
* you named is still read (it is what you asked for), but every cross-file
|
|
50
|
+
* `$ref` out of it is refused. Internal `#/...` refs are unaffected.
|
|
51
|
+
*/
|
|
52
|
+
localRefs?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Directories a local `$ref` must resolve inside. Defaults to
|
|
55
|
+
* `[dirname(rootLocation)]` — the folder holding the document being resolved
|
|
56
|
+
* — so a `$ref` cannot walk out of the document tree it belongs to
|
|
57
|
+
* (`{"$ref": "../../../etc/passwd"}`, or an absolute `/etc/passwd`).
|
|
58
|
+
*
|
|
59
|
+
* Set it explicitly for the common split-spec layout where a document refers
|
|
60
|
+
* to shared schemas in a sibling folder:
|
|
61
|
+
*
|
|
62
|
+
* ```ts
|
|
63
|
+
* resolveRefsFromFile('./specs/v2/api.json', { allowedRoots: ['./specs'] })
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* Entries are resolved against the current working directory. Both the
|
|
67
|
+
* lexical and the symlink-resolved path must land inside a root, so a symlink
|
|
68
|
+
* planted in the tree cannot be used to escape it.
|
|
69
|
+
*/
|
|
70
|
+
allowedRoots?: string[];
|
|
46
71
|
/**
|
|
47
72
|
* If non-empty, only these hosts (e.g. `api.example.com`) may be fetched for
|
|
48
73
|
* remote `$ref`s. An empty/undefined list allows any host (subject to
|
|
49
|
-
* `remote`). An explicit entry here always bypasses the private-host guard
|
|
74
|
+
* `remote`). An explicit entry here always bypasses the private-host guard
|
|
75
|
+
* (including the DNS check — see `verifyDns`).
|
|
76
|
+
*
|
|
77
|
+
* Matching is case-insensitive. An entry with **no port** (`example.com`)
|
|
78
|
+
* matches the host on any port; an entry **with** a port
|
|
79
|
+
* (`example.com:8443`) must match the URL's port exactly, where a URL that
|
|
80
|
+
* omits the port counts as its protocol default (`443` for https, `80` for
|
|
81
|
+
* http).
|
|
50
82
|
*/
|
|
51
83
|
allowedHosts?: string[];
|
|
52
84
|
/**
|
|
@@ -56,6 +88,19 @@ export type ResolveOptions = {
|
|
|
56
88
|
* endpoint). An explicit `allowedHosts` entry always bypasses this guard.
|
|
57
89
|
*/
|
|
58
90
|
allowPrivateHosts?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Resolve each remote host and refuse it when any address it resolves to is
|
|
93
|
+
* non-public. Defaults to `true`, which is what stops a public-looking name
|
|
94
|
+
* that points at a private address (`127.0.0.1.nip.io`) — the URL-only guard
|
|
95
|
+
* cannot see those. Pass `false` where names are resolved somewhere else
|
|
96
|
+
* (behind an egress proxy) and a local lookup would fail; allow-listed hosts
|
|
97
|
+
* skip the check either way.
|
|
98
|
+
*
|
|
99
|
+
* This narrows DNS rebinding rather than closing it: the record can still
|
|
100
|
+
* change between the check and the connection, which would take pinning the
|
|
101
|
+
* socket to the verified address to prevent.
|
|
102
|
+
*/
|
|
103
|
+
verifyDns?: boolean;
|
|
59
104
|
/**
|
|
60
105
|
* Custom content parser. Receives the raw text of every loaded document and
|
|
61
106
|
* its absolute location (file path or URL). Defaults to `JSON.parse`.
|
|
@@ -103,15 +148,44 @@ export type ResolveOptions = {
|
|
|
103
148
|
}) => Promise<Response>;
|
|
104
149
|
/** Milliseconds before an unresponsive remote fetch is aborted. Defaults to `30_000`. */
|
|
105
150
|
timeoutMs?: number;
|
|
151
|
+
/**
|
|
152
|
+
* Milliseconds the whole resolve may take, across every document. Defaults to
|
|
153
|
+
* `60_000`. `timeoutMs` bounds one hop; without an aggregate budget a document
|
|
154
|
+
* with hundreds of `$ref`s could hold the process for hours by paying the
|
|
155
|
+
* per-hop timeout over and over. Once it elapses, no further document is
|
|
156
|
+
* loaded and the overrun is reported on `errors`.
|
|
157
|
+
*/
|
|
158
|
+
totalTimeoutMs?: number;
|
|
106
159
|
/** Maximum redirect hops to follow per remote document. Defaults to `5`. */
|
|
107
160
|
maxRedirects?: number;
|
|
161
|
+
/**
|
|
162
|
+
* Maximum number of documents (root included) a single resolve may load.
|
|
163
|
+
* Defaults to `500`. A hostile document listing hundreds of distinct URLs
|
|
164
|
+
* otherwise turns this resolver into an egress amplifier — and each fetched
|
|
165
|
+
* document can add more refs of its own. Once the cap is hit, loading stops
|
|
166
|
+
* and the remaining refs degrade like any unresolvable ref.
|
|
167
|
+
*/
|
|
168
|
+
maxDocuments?: number;
|
|
108
169
|
/** Maximum bytes buffered per remote document. Defaults to `16` MiB. */
|
|
109
170
|
maxBytes?: number;
|
|
171
|
+
/**
|
|
172
|
+
* How deep the resolver walks before leaving a subtree unresolved and
|
|
173
|
+
* recording an error. Defaults to `512`. Guards the recursive walk against a
|
|
174
|
+
* pathologically nested document, which would otherwise blow the call stack
|
|
175
|
+
* with a `RangeError` — a thrown error this package promises never to throw.
|
|
176
|
+
*/
|
|
177
|
+
maxDepth?: number;
|
|
110
178
|
/**
|
|
111
179
|
* Whether fetched remote documents may be served from (and stored into) the
|
|
112
180
|
* process-wide session cache. Pass `false` to bypass it for one call: every
|
|
113
181
|
* remote document is re-fetched and nothing new is cached — useful when a
|
|
114
182
|
* remote schema is known to have changed mid-session. Defaults to `true`.
|
|
183
|
+
*
|
|
184
|
+
* The cache is keyed by URL **and** by the credentials/transport it was
|
|
185
|
+
* fetched with (`headers`, `fetch`, `parse`, and the limits), so a call
|
|
186
|
+
* carrying one tenant's token can never serve its document to a call carrying
|
|
187
|
+
* different (or no) credentials. It is bounded in both size and age; see
|
|
188
|
+
* `clearRemoteCache`.
|
|
115
189
|
*/
|
|
116
190
|
cache?: boolean;
|
|
117
191
|
};
|
package/package.json
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amritk/resolve-refs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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
|
+
"main": "./dist/index.js",
|
|
5
6
|
"module": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
6
8
|
"type": "module",
|
|
7
9
|
"sideEffects": false,
|
|
8
10
|
"engines": {
|
|
@@ -38,6 +40,7 @@
|
|
|
38
40
|
},
|
|
39
41
|
"scripts": {
|
|
40
42
|
"build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f && node ../../scripts/strip-comments.mjs",
|
|
43
|
+
"prepublishOnly": "node ../../scripts/check-publishable.mjs",
|
|
41
44
|
"types:check": "tsgo -p . --noEmit",
|
|
42
45
|
"test": "NODE_ENV=production vitest run --root ../.. resolve-refs",
|
|
43
46
|
"bench": "bun run ./bench/run.ts"
|
|
@@ -47,5 +50,8 @@
|
|
|
47
50
|
"types": "./dist/index.d.ts",
|
|
48
51
|
"default": "./dist/index.js"
|
|
49
52
|
}
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@amritk/runtime-validators": "^0.11.0"
|
|
50
56
|
}
|
|
51
57
|
}
|