@amritk/helpers 0.13.5 → 0.15.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 +13 -5
- package/README.md +4 -1
- package/dist/assert-id-scopes.d.ts +20 -0
- package/dist/assert-id-scopes.js +45 -0
- package/dist/build-anchor-map.d.ts +26 -0
- package/dist/build-anchor-map.js +35 -0
- package/dist/build-dynamic-ref-map.d.ts +8 -0
- package/dist/build-dynamic-ref-map.js +7 -5
- package/dist/build-resource-registry.d.ts +88 -0
- package/dist/build-resource-registry.js +90 -0
- package/dist/escape-regex-pattern.d.ts +27 -0
- package/dist/escape-regex-pattern.js +21 -1
- package/dist/extract-refs.js +6 -4
- package/dist/fold-nullable.d.ts +19 -0
- package/dist/fold-nullable.js +42 -0
- package/dist/generate-index-barrel.js +13 -6
- package/dist/generate-type-definition.d.ts +8 -0
- package/dist/generate-type-definition.js +249 -185
- package/dist/graft-external-schemas.d.ts +83 -0
- package/dist/graft-external-schemas.js +70 -0
- package/dist/max-schema-depth.d.ts +22 -0
- package/dist/max-schema-depth.js +10 -0
- package/dist/mjst-extension.d.ts +4 -2
- package/dist/mjst-extension.js +11 -2
- package/dist/multiple-of-check.d.ts +31 -0
- package/dist/multiple-of-check.js +6 -10
- package/dist/normalize-ref-scopes.d.ts +29 -0
- package/dist/normalize-ref-scopes.js +53 -0
- package/dist/prune-external-schemas.d.ts +16 -0
- package/dist/prune-external-schemas.js +80 -0
- package/dist/ref-to-filename.d.ts +1 -0
- package/dist/ref-to-filename.js +19 -3
- package/dist/ref-to-name.js +7 -4
- package/dist/resolve-dynamic-refs.d.ts +10 -0
- package/dist/resolve-dynamic-refs.js +18 -16
- package/dist/resolve-ref.d.ts +4 -2
- package/dist/resolve-ref.js +32 -6
- package/dist/resolve-scoped-ref.d.ts +35 -0
- package/dist/resolve-scoped-ref.js +35 -0
- package/dist/safe-accessor.d.ts +38 -1
- package/dist/safe-accessor.js +15 -0
- package/dist/string-length-check.d.ts +8 -0
- package/dist/string-length-check.js +23 -0
- package/dist/upgrade-draft07-schema.js +9 -6
- package/dist/walk-ref-graph.d.ts +38 -3
- package/dist/walk-ref-graph.js +173 -18
- package/package.json +16 -3
- package/src/build-dynamic-ref-map.ts +0 -61
- package/src/derive-root-type-name.ts +0 -54
- package/src/escape-regex-pattern.ts +0 -87
- package/src/extract-dynamic-anchor-defs.ts +0 -25
- package/src/extract-refs.ts +0 -73
- package/src/generate-index-barrel.ts +0 -118
- package/src/generate-type-definition.ts +0 -599
- package/src/mjst-extension.ts +0 -81
- package/src/multiple-of-check.ts +0 -32
- package/src/parse-documentation.ts +0 -177
- package/src/quote-js-string.ts +0 -20
- package/src/ref-to-filename.ts +0 -116
- package/src/ref-to-name.ts +0 -54
- package/src/resolve-dynamic-refs.ts +0 -74
- package/src/resolve-ref.ts +0 -82
- package/src/safe-accessor.ts +0 -53
- package/src/schema-guards.ts +0 -234
- package/src/unknown-key-check.ts +0 -68
- package/src/upgrade-draft07-schema.ts +0 -179
- package/src/walk-ref-graph.ts +0 -240
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { resolveUri, SYNTHETIC_BASE } from "./build-resource-registry.js";
|
|
2
|
+
import { refToFilename } from "./ref-to-filename.js";
|
|
3
|
+
const normalizeUri = (uri) => {
|
|
4
|
+
const resolved = resolveUri(uri, SYNTHETIC_BASE);
|
|
5
|
+
if (resolved === void 0)
|
|
6
|
+
return uri;
|
|
7
|
+
const hash = resolved.indexOf("#");
|
|
8
|
+
return hash === -1 ? resolved : resolved.slice(0, hash);
|
|
9
|
+
};
|
|
10
|
+
const planFor = (document, uri) => {
|
|
11
|
+
const id = document["$id"];
|
|
12
|
+
if (typeof id !== "string" || id === "")
|
|
13
|
+
return { kind: "adopt-uri" };
|
|
14
|
+
const resolved = resolveUri(id, uri);
|
|
15
|
+
if (resolved === void 0)
|
|
16
|
+
return { kind: "adopt-uri" };
|
|
17
|
+
const hash = resolved.indexOf("#");
|
|
18
|
+
const bare = hash === -1 ? resolved : resolved.slice(0, hash);
|
|
19
|
+
if (bare === "")
|
|
20
|
+
return { kind: "adopt-uri" };
|
|
21
|
+
return bare === uri ? { kind: "self-identified" } : { kind: "aliased", id: bare };
|
|
22
|
+
};
|
|
23
|
+
const asResource = (document) => {
|
|
24
|
+
if (document === true)
|
|
25
|
+
return {};
|
|
26
|
+
if (document === false)
|
|
27
|
+
return { not: {} };
|
|
28
|
+
if (document === null || typeof document !== "object" || Array.isArray(document))
|
|
29
|
+
return void 0;
|
|
30
|
+
return document;
|
|
31
|
+
};
|
|
32
|
+
const graftExternalSchemas = (root, schemas) => {
|
|
33
|
+
const uris = Object.keys(schemas);
|
|
34
|
+
if (uris.length === 0)
|
|
35
|
+
return { document: root, names: EMPTY_NAMES };
|
|
36
|
+
const existing = root["$defs"];
|
|
37
|
+
const inherited = typeof existing === "object" && existing !== null && !Array.isArray(existing) ? existing : void 0;
|
|
38
|
+
const defs = { ...inherited };
|
|
39
|
+
const claimed = /* @__PURE__ */ new Map();
|
|
40
|
+
const names = /* @__PURE__ */ new Set();
|
|
41
|
+
const claim = (name, uri) => {
|
|
42
|
+
const owner = claimed.get(name);
|
|
43
|
+
if (owner !== void 0) {
|
|
44
|
+
throw new Error(`The registered schemas "${owner}" and "${uri}" both reduce to the definition name "${name}", so only one of them could be embedded and every reference to the other would resolve to the wrong schema. Register one of them under a URI whose last path segment differs.`);
|
|
45
|
+
}
|
|
46
|
+
if (inherited !== void 0 && Object.hasOwn(inherited, name)) {
|
|
47
|
+
throw new Error(`The registered schema "${uri}" reduces to the definition name "${name}", which the root document already declares in $defs. Rename the root definition, or register the schema under a URI whose last path segment differs.`);
|
|
48
|
+
}
|
|
49
|
+
claimed.set(name, uri);
|
|
50
|
+
names.add(name);
|
|
51
|
+
return name;
|
|
52
|
+
};
|
|
53
|
+
for (const key of uris) {
|
|
54
|
+
const resource = asResource(schemas[key]);
|
|
55
|
+
if (resource === void 0)
|
|
56
|
+
continue;
|
|
57
|
+
const uri = normalizeUri(key);
|
|
58
|
+
const plan = planFor(resource, uri);
|
|
59
|
+
const name = claim(refToFilename(uri), uri);
|
|
60
|
+
defs[name] = plan.kind === "adopt-uri" ? { $id: uri, ...resource } : resource;
|
|
61
|
+
if (plan.kind === "aliased") {
|
|
62
|
+
defs[claim(`${name}-retrieved`, uri)] = { $id: uri, $ref: plan.id };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return names.size === 0 ? { document: root, names: EMPTY_NAMES } : { document: { ...root, $defs: defs }, names };
|
|
66
|
+
};
|
|
67
|
+
const EMPTY_NAMES = /* @__PURE__ */ new Set();
|
|
68
|
+
export {
|
|
69
|
+
graftExternalSchemas
|
|
70
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How deep a schema tree may nest before the walkers give up.
|
|
3
|
+
*
|
|
4
|
+
* Every walker in this package is recursive, so a pathologically nested
|
|
5
|
+
* document (a generated fuzz case, or a hand-rolled document that lost a
|
|
6
|
+
* closing brace) used to die with a bare `RangeError: Maximum call stack size
|
|
7
|
+
* exceeded` somewhere inside a `traverse` frame — a stack trace that says
|
|
8
|
+
* nothing about the input that caused it. The cap sits comfortably below the
|
|
9
|
+
* depth at which the stack actually runs out (~5,000 frames in practice) and
|
|
10
|
+
* far above anything a real JSON Schema reaches, so the only documents it
|
|
11
|
+
* rejects are ones that were going to fail anyway — just with a message that
|
|
12
|
+
* names the problem.
|
|
13
|
+
*/
|
|
14
|
+
export declare const MAX_SCHEMA_DEPTH = 2000;
|
|
15
|
+
/**
|
|
16
|
+
* Throws a message naming the nesting limit once a walker passes it.
|
|
17
|
+
*
|
|
18
|
+
* Call this at the top of each recursive step with the *current* depth. The
|
|
19
|
+
* `walker` label is the traversal that hit the limit, so a report points at the
|
|
20
|
+
* pass that failed rather than at whichever helper happened to be deepest.
|
|
21
|
+
*/
|
|
22
|
+
export declare const assertSchemaDepth: (depth: number, walker: string) => void;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const MAX_SCHEMA_DEPTH = 2e3;
|
|
2
|
+
const assertSchemaDepth = (depth, walker) => {
|
|
3
|
+
if (depth > MAX_SCHEMA_DEPTH) {
|
|
4
|
+
throw new Error(`Schema nesting exceeds ${MAX_SCHEMA_DEPTH} levels while running ${walker}. Flatten the document (or split the deepest subschema into a $defs entry and $ref it) and try again.`);
|
|
5
|
+
}
|
|
6
|
+
};
|
|
7
|
+
export {
|
|
8
|
+
MAX_SCHEMA_DEPTH,
|
|
9
|
+
assertSchemaDepth
|
|
10
|
+
};
|
package/dist/mjst-extension.d.ts
CHANGED
|
@@ -27,8 +27,10 @@ export type MjstExtension = {
|
|
|
27
27
|
};
|
|
28
28
|
/**
|
|
29
29
|
* Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
|
|
30
|
-
*
|
|
31
|
-
*
|
|
30
|
+
* names a class the generators actually support (see
|
|
31
|
+
* {@link SUPPORTED_INSTANCE_CLASSES}). Anything else is warned about once and
|
|
32
|
+
* ignored, so callers fall back to ordinary type handling rather than emitting
|
|
33
|
+
* a reference to a class that does not exist.
|
|
32
34
|
*/
|
|
33
35
|
export declare const getMjstInstanceOf: (schema: JSONSchema) => string | undefined;
|
|
34
36
|
/**
|
package/dist/mjst-extension.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { isSchemaObject } from "./schema-guards.js";
|
|
2
2
|
const MJST_EXTENSION_KEY = "x-mjst";
|
|
3
|
-
const
|
|
3
|
+
const SUPPORTED_INSTANCE_CLASSES = /* @__PURE__ */ new Set(["Date"]);
|
|
4
4
|
const SUPPORTED_PRIMITIVES = /* @__PURE__ */ new Set(["bigint"]);
|
|
5
|
+
const warnedInstanceClasses = /* @__PURE__ */ new Set();
|
|
5
6
|
const SAFE_BRAND = /^[\w$ -]+$/;
|
|
6
7
|
const readExtensionString = (schema, field) => {
|
|
7
8
|
if (!isSchemaObject(schema))
|
|
@@ -14,7 +15,15 @@ const readExtensionString = (schema, field) => {
|
|
|
14
15
|
};
|
|
15
16
|
const getMjstInstanceOf = (schema) => {
|
|
16
17
|
const instanceOf = readExtensionString(schema, "instanceOf");
|
|
17
|
-
|
|
18
|
+
if (instanceOf === void 0)
|
|
19
|
+
return void 0;
|
|
20
|
+
if (SUPPORTED_INSTANCE_CLASSES.has(instanceOf))
|
|
21
|
+
return instanceOf;
|
|
22
|
+
if (instanceOf !== "" && !warnedInstanceClasses.has(instanceOf)) {
|
|
23
|
+
warnedInstanceClasses.add(instanceOf);
|
|
24
|
+
console.warn(`Warning: ignoring unsupported x-mjst instanceOf "${instanceOf}". Supported classes: ${[...SUPPORTED_INSTANCE_CLASSES].join(", ")}.`);
|
|
25
|
+
}
|
|
26
|
+
return void 0;
|
|
18
27
|
};
|
|
19
28
|
const getMjstPrimitive = (schema) => {
|
|
20
29
|
const primitive = readExtensionString(schema, "primitive");
|
|
@@ -1,3 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emits code for a JSON Schema `multipleOf` check that agrees with the runtime
|
|
3
|
+
* interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
|
|
4
|
+
*
|
|
5
|
+
* The interpreter answers the keyword in two ways depending on the divisor, and
|
|
6
|
+
* so does this emitter — the two must not diverge, or a generated validator and
|
|
7
|
+
* `@amritk/runtime-validators` return different verdicts for the same document.
|
|
8
|
+
*
|
|
9
|
+
* **Integer divisor.** `%` on doubles is exact for an integer divisor, so the
|
|
10
|
+
* emitted check is the plain one. It accepts huge true multiples (`1e21 % 1` is
|
|
11
|
+
* `0`) that a quotient check would misjudge, and `Number.isInteger` rejects
|
|
12
|
+
* `NaN` / `±Infinity`, which is Ajv's verdict for `multipleOf` on any non-finite
|
|
13
|
+
* value.
|
|
14
|
+
*
|
|
15
|
+
* **Fractional divisor.** The naive `x % m === 0` is float-wrong — IEEE-754
|
|
16
|
+
* makes `0.3 % 0.1` evaluate to `0.0999…`, so `0.3` would spuriously fail
|
|
17
|
+
* `multipleOf: 0.1` — so the check divides and measures the quotient's distance
|
|
18
|
+
* to its nearest integer. The tolerance tracks the actual representation error
|
|
19
|
+
* in the quotient (~`|q|·2⁻⁵²`) rather than a fixed epsilon: a fixed one is both
|
|
20
|
+
* too tight for large values (`1234567.89` against `multipleOf: 0.01`, whose
|
|
21
|
+
* quotient error already exceeds it) and, at the `1e-8·|q|` this used to emit,
|
|
22
|
+
* ~10⁷× too loose — it accepted clear non-multiples like `1000000.005` against
|
|
23
|
+
* `multipleOf: 0.01`. A value whose quotient overflows to `Infinity` yields a
|
|
24
|
+
* `NaN` distance, and `NaN <= tolerance` is `false`, so it fails rather than
|
|
25
|
+
* reading as a clean multiple.
|
|
26
|
+
*
|
|
27
|
+
* `valueExpr` is inlined up to three times, so it must be a side-effect-free
|
|
28
|
+
* expression (a property read or a cached variable — which is all the generators
|
|
29
|
+
* ever pass). Both expressions are self-parenthesized, so a caller can drop
|
|
30
|
+
* either into a `&&` / `||` chain or negate it without re-bracketing.
|
|
31
|
+
*/
|
|
1
32
|
/** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
|
|
2
33
|
export declare const multipleOfPassExpr: (valueExpr: string, divisor: number) => string;
|
|
3
34
|
/** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
|
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
const quotientTolerance = (valueExpr, divisor) => {
|
|
2
|
-
const q = `${valueExpr} / ${divisor}`;
|
|
3
|
-
return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` };
|
|
4
|
-
};
|
|
5
1
|
const multipleOfPassExpr = (valueExpr, divisor) => {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
}
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
return `Math.abs(${q} - Math.round(${q})) > ${tol}`;
|
|
2
|
+
if (Number.isInteger(divisor)) {
|
|
3
|
+
return `(Number.isInteger(${valueExpr}) && ${valueExpr} % ${divisor} === 0)`;
|
|
4
|
+
}
|
|
5
|
+
const q = `${valueExpr} / ${divisor}`;
|
|
6
|
+
return `(Math.abs(${q} - Math.round(${q})) <= 2 * Number.EPSILON * Math.max(1, Math.abs(${q})))`;
|
|
12
7
|
};
|
|
8
|
+
const multipleOfFailExpr = (valueExpr, divisor) => `!${multipleOfPassExpr(valueExpr, divisor)}`;
|
|
13
9
|
export {
|
|
14
10
|
multipleOfFailExpr,
|
|
15
11
|
multipleOfPassExpr
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewrites every `$ref` and `$dynamicRef` in a document to a plain JSON Pointer
|
|
3
|
+
* from the document root, applying the `$id` base URIs in scope on the way.
|
|
4
|
+
*
|
|
5
|
+
* This is the one place `$id` needs to be understood. Everything downstream —
|
|
6
|
+
* the ref-graph walk, the filename and type-name derivation, the import graph
|
|
7
|
+
* the generated code carries, the strict-mode subschema matcher — resolves refs
|
|
8
|
+
* by string against the root document, so handing it a document whose refs are
|
|
9
|
+
* already document-root pointers makes all of it correct at once, with no
|
|
10
|
+
* base-URI awareness of its own.
|
|
11
|
+
*
|
|
12
|
+
* What that buys, concretely: `"list"`, `"http://example.com/b/d.json"`,
|
|
13
|
+
* `"urn:uuid:…#/$defs/bar"`, `"/absref/foobar.json"`, and `"child1#my_anchor"`
|
|
14
|
+
* all become nameable targets instead of refs the walker refuses; and a
|
|
15
|
+
* `"#/$defs/t"` written inside an embedded resource stops silently selecting the
|
|
16
|
+
* document root's `t`.
|
|
17
|
+
*
|
|
18
|
+
* A document that declares no `$id` is returned **by identity** — there is one
|
|
19
|
+
* base URI in play, so its refs already mean what they say and nothing is
|
|
20
|
+
* rewritten or allocated. The same goes for any subtree that comes back
|
|
21
|
+
* unchanged, so the common document pays a single read-only walk.
|
|
22
|
+
*
|
|
23
|
+
* A ref the registry cannot place is left exactly as written. It may name
|
|
24
|
+
* another document (a fetch this package does not do), and leaving it alone
|
|
25
|
+
* keeps the existing behaviour — the walker refuses it, or a consumer drops it —
|
|
26
|
+
* rather than inventing a target. {@link assertIdScopes} is what catches the
|
|
27
|
+
* dangerous subset of those.
|
|
28
|
+
*/
|
|
29
|
+
export declare const normalizeRefScopes: (root: Record<string, unknown>) => Record<string, unknown>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { buildResourceRegistry, DATA_KEYWORDS, escapePointerSegment, resolveUri } from "./build-resource-registry.js";
|
|
2
|
+
import { assertSchemaDepth } from "./max-schema-depth.js";
|
|
3
|
+
import { resolveRef } from "./resolve-ref.js";
|
|
4
|
+
import { resolveScopedRef } from "./resolve-scoped-ref.js";
|
|
5
|
+
const normalizeRefScopes = (root) => {
|
|
6
|
+
const registry = buildResourceRegistry(root);
|
|
7
|
+
if (registry === null)
|
|
8
|
+
return root;
|
|
9
|
+
const normalizedRef = (ref, base) => {
|
|
10
|
+
const target = resolveScopedRef(registry, ref, base);
|
|
11
|
+
if (target === void 0)
|
|
12
|
+
return null;
|
|
13
|
+
const rewritten = `#${target.pointer}`;
|
|
14
|
+
if (rewritten === ref)
|
|
15
|
+
return null;
|
|
16
|
+
return resolveRef(rewritten, root) === void 0 ? null : rewritten;
|
|
17
|
+
};
|
|
18
|
+
const normalizedDynamicRef = (ref, base) => {
|
|
19
|
+
const absolute = resolveUri(ref, base);
|
|
20
|
+
if (absolute === void 0)
|
|
21
|
+
return normalizedRef(ref, base);
|
|
22
|
+
const hash = absolute.indexOf("#");
|
|
23
|
+
const fragment = hash === -1 ? "" : absolute.slice(hash + 1);
|
|
24
|
+
if (fragment !== "" && !fragment.startsWith("/") && registry.dynamicAnchors.has(`${absolute.slice(0, hash)}#${fragment}`)) {
|
|
25
|
+
return `#${fragment}` === ref ? null : `#${fragment}`;
|
|
26
|
+
}
|
|
27
|
+
return normalizedRef(ref, base);
|
|
28
|
+
};
|
|
29
|
+
const rewrite = (node, pointer, enclosing, depth) => {
|
|
30
|
+
assertSchemaDepth(depth, "normalizeRefScopes");
|
|
31
|
+
if (node === null || typeof node !== "object")
|
|
32
|
+
return node;
|
|
33
|
+
if (Array.isArray(node)) {
|
|
34
|
+
const mapped = node.map((item, index) => rewrite(item, `${pointer}/${index}`, enclosing, depth + 1));
|
|
35
|
+
return mapped.some((item, index) => item !== node[index]) ? mapped : node;
|
|
36
|
+
}
|
|
37
|
+
const record = node;
|
|
38
|
+
const base = registry.baseAt.get(pointer) ?? enclosing;
|
|
39
|
+
let changed = false;
|
|
40
|
+
const result = {};
|
|
41
|
+
for (const [key, value] of Object.entries(record)) {
|
|
42
|
+
const next = key === "$ref" && typeof value === "string" ? normalizedRef(value, base) ?? value : key === "$dynamicRef" && typeof value === "string" ? normalizedDynamicRef(value, base) ?? value : DATA_KEYWORDS.has(key) ? value : rewrite(value, `${pointer}/${escapePointerSegment(key)}`, base, depth + 1);
|
|
43
|
+
if (next !== value)
|
|
44
|
+
changed = true;
|
|
45
|
+
result[key] = next;
|
|
46
|
+
}
|
|
47
|
+
return changed ? result : record;
|
|
48
|
+
};
|
|
49
|
+
return rewrite(root, "", registry.rootBase, 0);
|
|
50
|
+
};
|
|
51
|
+
export {
|
|
52
|
+
normalizeRefScopes
|
|
53
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns `document` with every registered definition nothing reaches removed.
|
|
3
|
+
*
|
|
4
|
+
* Reachability starts from the document *without* its registered definitions —
|
|
5
|
+
* so only what the author actually wrote seeds the search — and then follows
|
|
6
|
+
* refs from each registered document that is reached, so a companion pulled in
|
|
7
|
+
* by another companion is kept.
|
|
8
|
+
*
|
|
9
|
+
* The document is returned by identity when nothing needs dropping, which is the
|
|
10
|
+
* case whenever a caller registers exactly what the schema uses.
|
|
11
|
+
*
|
|
12
|
+
* @param document - The grafted document, with every ref already a pointer.
|
|
13
|
+
* @param external - The `$defs` names {@link graftExternalSchemas} added.
|
|
14
|
+
* @returns The document, carrying only the registered definitions it uses.
|
|
15
|
+
*/
|
|
16
|
+
export declare const pruneExternalSchemas: (document: Record<string, unknown>, external: ReadonlySet<string>) => Record<string, unknown>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
|
|
2
|
+
import { assertSchemaDepth } from "./max-schema-depth.js";
|
|
3
|
+
const DEFS_PREFIX = "#/$defs/";
|
|
4
|
+
const unescapeSegment = (segment) => segment.indexOf("~") === -1 ? segment : segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
5
|
+
const externalTarget = (ref, external) => {
|
|
6
|
+
if (!ref.startsWith(DEFS_PREFIX))
|
|
7
|
+
return void 0;
|
|
8
|
+
const rest = ref.slice(DEFS_PREFIX.length);
|
|
9
|
+
const slash = rest.indexOf("/");
|
|
10
|
+
const name = unescapeSegment(slash === -1 ? rest : rest.slice(0, slash));
|
|
11
|
+
return external.has(name) ? name : void 0;
|
|
12
|
+
};
|
|
13
|
+
const referencedFrom = (node, external, dynamicMap, into) => {
|
|
14
|
+
const walk = (value, depth) => {
|
|
15
|
+
assertSchemaDepth(depth, "pruneExternalSchemas");
|
|
16
|
+
if (value === null || typeof value !== "object")
|
|
17
|
+
return;
|
|
18
|
+
if (Array.isArray(value)) {
|
|
19
|
+
for (const item of value)
|
|
20
|
+
walk(item, depth + 1);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const record = value;
|
|
24
|
+
const ref = record["$ref"];
|
|
25
|
+
if (typeof ref === "string") {
|
|
26
|
+
const name = externalTarget(ref, external);
|
|
27
|
+
if (name !== void 0)
|
|
28
|
+
into.add(name);
|
|
29
|
+
}
|
|
30
|
+
const dynamicRef = record["$dynamicRef"];
|
|
31
|
+
if (typeof dynamicRef === "string") {
|
|
32
|
+
const target = dynamicRef.startsWith("#/") ? dynamicRef : dynamicMap[dynamicRef];
|
|
33
|
+
const name = target === void 0 ? void 0 : externalTarget(target, external);
|
|
34
|
+
if (name !== void 0)
|
|
35
|
+
into.add(name);
|
|
36
|
+
}
|
|
37
|
+
for (const key in record)
|
|
38
|
+
walk(record[key], depth + 1);
|
|
39
|
+
};
|
|
40
|
+
walk(node, 0);
|
|
41
|
+
};
|
|
42
|
+
const pruneExternalSchemas = (document, external) => {
|
|
43
|
+
if (external.size === 0)
|
|
44
|
+
return document;
|
|
45
|
+
const defs = document["$defs"];
|
|
46
|
+
if (typeof defs !== "object" || defs === null || Array.isArray(defs))
|
|
47
|
+
return document;
|
|
48
|
+
const definitions = defs;
|
|
49
|
+
const dynamicMap = buildDynamicRefMap(document);
|
|
50
|
+
const authored = {};
|
|
51
|
+
for (const [name, definition] of Object.entries(definitions)) {
|
|
52
|
+
if (!external.has(name))
|
|
53
|
+
authored[name] = definition;
|
|
54
|
+
}
|
|
55
|
+
const seed = { ...document, $defs: authored };
|
|
56
|
+
const reached = /* @__PURE__ */ new Set();
|
|
57
|
+
referencedFrom(seed, external, dynamicMap, reached);
|
|
58
|
+
const queue = [...reached];
|
|
59
|
+
for (let head = 0; head < queue.length; head++) {
|
|
60
|
+
const found = /* @__PURE__ */ new Set();
|
|
61
|
+
referencedFrom(definitions[queue[head]], external, dynamicMap, found);
|
|
62
|
+
for (const name of found) {
|
|
63
|
+
if (reached.has(name))
|
|
64
|
+
continue;
|
|
65
|
+
reached.add(name);
|
|
66
|
+
queue.push(name);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (reached.size === external.size)
|
|
70
|
+
return document;
|
|
71
|
+
const kept = {};
|
|
72
|
+
for (const [name, definition] of Object.entries(definitions)) {
|
|
73
|
+
if (!external.has(name) || reached.has(name))
|
|
74
|
+
kept[name] = definition;
|
|
75
|
+
}
|
|
76
|
+
return { ...document, $defs: kept };
|
|
77
|
+
};
|
|
78
|
+
export {
|
|
79
|
+
pruneExternalSchemas
|
|
80
|
+
};
|
|
@@ -31,6 +31,7 @@ export declare const toKebabCase: (value: string) => string;
|
|
|
31
31
|
* refToFilename('#/definitions/ServerVariable') // 'server-variable'
|
|
32
32
|
* refToFilename('#/definitions/APIKeySecurityScheme') // 'api-key-security-scheme'
|
|
33
33
|
* refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json') // 'channel'
|
|
34
|
+
* refToFilename('#named') // 'named' — a plain `$anchor` ref
|
|
34
35
|
* ```
|
|
35
36
|
*/
|
|
36
37
|
export declare const refToFilename: (ref: string) => string;
|
package/dist/ref-to-filename.js
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
const toKebabCase = (value) => value.replace(/OAuth/g, "Oauth").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase();
|
|
2
|
+
const UNSAFE_FILENAME_CHARS = /[^\p{ID_Continue}.\-]+/gu;
|
|
3
|
+
const stableSuffix = (ref) => {
|
|
4
|
+
let hash = 2166136261;
|
|
5
|
+
for (const char of ref) {
|
|
6
|
+
hash ^= char.codePointAt(0);
|
|
7
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
8
|
+
}
|
|
9
|
+
return hash.toString(36);
|
|
10
|
+
};
|
|
11
|
+
const normalizeFilename = (raw, ref) => {
|
|
12
|
+
const cleaned = raw.replace(UNSAFE_FILENAME_CHARS, "-").replace(/-{2,}/g, "-").replace(/^[.\-]+/, "").replace(/[.\-]+$/, "");
|
|
13
|
+
return cleaned === "" ? `ref-${stableSuffix(ref)}` : cleaned;
|
|
14
|
+
};
|
|
2
15
|
const uriRefToFilename = (uri) => {
|
|
3
16
|
const hashIndex = uri.indexOf("#");
|
|
4
17
|
const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex);
|
|
5
18
|
const fragment = hashIndex === -1 ? "" : uri.slice(hashIndex + 1);
|
|
6
|
-
const
|
|
19
|
+
const parsed = /^https?:\/\/([^/]+)(?:\/(.*))?$/.exec(baseUri);
|
|
20
|
+
const host = parsed?.[1] ?? "";
|
|
21
|
+
const path = parsed?.[2] ?? "";
|
|
22
|
+
const withoutProtocol = parsed ? path === "" ? host : path : baseUri;
|
|
7
23
|
const withoutExt = withoutProtocol.replace(/\.json$/, "");
|
|
8
24
|
const rawSegments = withoutExt.split("/");
|
|
9
25
|
const SKIP_KEYS = /* @__PURE__ */ new Set(["definitions", "$defs"]);
|
|
@@ -28,14 +44,14 @@ const uriRefToFilename = (uri) => {
|
|
|
28
44
|
};
|
|
29
45
|
const refToFilename = (ref) => {
|
|
30
46
|
if (ref.startsWith("http://") || ref.startsWith("https://")) {
|
|
31
|
-
return uriRefToFilename(ref);
|
|
47
|
+
return normalizeFilename(uriRefToFilename(ref), ref);
|
|
32
48
|
}
|
|
33
49
|
const segments = ref.split("/");
|
|
34
50
|
let filename = segments[segments.length - 1];
|
|
35
51
|
if (/[A-Z]/.test(filename)) {
|
|
36
52
|
filename = toKebabCase(filename);
|
|
37
53
|
}
|
|
38
|
-
return filename;
|
|
54
|
+
return normalizeFilename(filename, ref);
|
|
39
55
|
};
|
|
40
56
|
export {
|
|
41
57
|
refToFilename,
|
package/dist/ref-to-name.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { refToFilename } from "./ref-to-filename.js";
|
|
2
|
+
const WORD_SEPARATOR = /[^\p{ID_Continue}]+|_+/u;
|
|
3
|
+
const IDENTIFIER_START = /^[\p{ID_Start}_$]/u;
|
|
2
4
|
const kebabToPascal = (kebab, suffix) => {
|
|
3
|
-
const words = kebab.split(
|
|
5
|
+
const words = kebab.split(WORD_SEPARATOR);
|
|
4
6
|
let pascalCase = "";
|
|
5
7
|
for (const word of words) {
|
|
6
|
-
if (word === "")
|
|
8
|
+
if (word === void 0 || word === "")
|
|
7
9
|
continue;
|
|
8
|
-
|
|
10
|
+
const first = [...word][0];
|
|
11
|
+
pascalCase += first.toUpperCase() + word.slice(first.length);
|
|
9
12
|
}
|
|
10
13
|
if (pascalCase === "")
|
|
11
14
|
pascalCase = "_";
|
|
12
|
-
else if (
|
|
15
|
+
else if (!IDENTIFIER_START.test(pascalCase))
|
|
13
16
|
pascalCase = `_${pascalCase}`;
|
|
14
17
|
return pascalCase + suffix;
|
|
15
18
|
};
|
|
@@ -10,5 +10,15 @@ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
|
|
|
10
10
|
* inside a keyword whose value is an array of subschemas (`allOf`, `anyOf`,
|
|
11
11
|
* `oneOf`, `prefixItems`, …) is rewritten too. The build system generates a
|
|
12
12
|
* separate file per `$def`, so each schema walked here is relatively shallow.
|
|
13
|
+
*
|
|
14
|
+
* A `$dynamicRef` the map cannot place is a hard error. Leaving it in place was
|
|
15
|
+
* the old behaviour, and it was the quiet kind of broken: the type generator
|
|
16
|
+
* then named the type after the anchor itself, emitting a reference to a type
|
|
17
|
+
* no file exports — and for the conventional anchor name `node` that reference
|
|
18
|
+
* resolves against the DOM's `Node` interface under most app tsconfigs, so the
|
|
19
|
+
* build succeeds with the wrong type instead of failing. A pointer form
|
|
20
|
+
* (`$dynamicRef: "#/$defs/x"`) names no anchor at all, so it degrades to a plain
|
|
21
|
+
* `$ref`, matching 2020-12's rule that a dynamic ref with no dynamic anchor to
|
|
22
|
+
* bind to behaves statically.
|
|
13
23
|
*/
|
|
14
24
|
export declare const resolveDynamicRefs: (schema: JSONSchema, dynamicRefMap: Record<string, string>) => JSONSchema;
|
|
@@ -1,44 +1,46 @@
|
|
|
1
|
+
import { assertSchemaDepth } from "./max-schema-depth.js";
|
|
1
2
|
const resolveDynamicRefs = (schema, dynamicRefMap) => {
|
|
2
3
|
if (typeof schema !== "object" || schema === null) {
|
|
3
4
|
return schema;
|
|
4
5
|
}
|
|
5
|
-
if (
|
|
6
|
-
return schema;
|
|
7
|
-
}
|
|
8
|
-
if (!containsDynamicRef(schema)) {
|
|
6
|
+
if (!containsDynamicRef(schema, 0)) {
|
|
9
7
|
return schema;
|
|
10
8
|
}
|
|
11
9
|
const clone = JSON.parse(JSON.stringify(schema));
|
|
12
|
-
const walk = (obj) => {
|
|
10
|
+
const walk = (obj, depth) => {
|
|
11
|
+
assertSchemaDepth(depth, "resolveDynamicRefs");
|
|
13
12
|
if (typeof obj !== "object" || obj === null) {
|
|
14
13
|
return;
|
|
15
14
|
}
|
|
16
15
|
if (Array.isArray(obj)) {
|
|
17
16
|
for (const item of obj)
|
|
18
|
-
walk(item);
|
|
17
|
+
walk(item, depth + 1);
|
|
19
18
|
return;
|
|
20
19
|
}
|
|
21
20
|
const record = obj;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
21
|
+
const dynamicRef = record["$dynamicRef"];
|
|
22
|
+
if (typeof dynamicRef === "string") {
|
|
23
|
+
const resolved = dynamicRefMap[dynamicRef] ?? (dynamicRef.startsWith("#/") ? dynamicRef : void 0);
|
|
24
|
+
if (resolved === void 0) {
|
|
25
|
+
throw new Error(`Unresolvable $dynamicRef "${dynamicRef}": no $dynamicAnchor named "${dynamicRef.replace(/^#/, "")}" is declared anywhere in the document. Declare the anchor, or point a plain $ref at the definition instead.`);
|
|
27
26
|
}
|
|
27
|
+
record["$ref"] = resolved;
|
|
28
|
+
delete record["$dynamicRef"];
|
|
28
29
|
}
|
|
29
30
|
for (const key in record) {
|
|
30
|
-
walk(record[key]);
|
|
31
|
+
walk(record[key], depth + 1);
|
|
31
32
|
}
|
|
32
33
|
};
|
|
33
|
-
walk(clone);
|
|
34
|
+
walk(clone, 0);
|
|
34
35
|
return clone;
|
|
35
36
|
};
|
|
36
|
-
const containsDynamicRef = (value) => {
|
|
37
|
+
const containsDynamicRef = (value, depth) => {
|
|
38
|
+
assertSchemaDepth(depth, "resolveDynamicRefs");
|
|
37
39
|
if (typeof value !== "object" || value === null)
|
|
38
40
|
return false;
|
|
39
41
|
if (Array.isArray(value)) {
|
|
40
42
|
for (const item of value)
|
|
41
|
-
if (containsDynamicRef(item))
|
|
43
|
+
if (containsDynamicRef(item, depth + 1))
|
|
42
44
|
return true;
|
|
43
45
|
return false;
|
|
44
46
|
}
|
|
@@ -46,7 +48,7 @@ const containsDynamicRef = (value) => {
|
|
|
46
48
|
if (typeof record["$dynamicRef"] === "string")
|
|
47
49
|
return true;
|
|
48
50
|
for (const key in record)
|
|
49
|
-
if (containsDynamicRef(record[key]))
|
|
51
|
+
if (containsDynamicRef(record[key], depth + 1))
|
|
50
52
|
return true;
|
|
51
53
|
return false;
|
|
52
54
|
};
|
package/dist/resolve-ref.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Resolves a JSON Schema $ref pointer to the actual schema definition.
|
|
3
3
|
*
|
|
4
|
-
* Supports
|
|
5
|
-
* - Internal: `#/$defs/contact` — navigates the root schema by JSON Pointer
|
|
4
|
+
* Supports four ref forms:
|
|
5
|
+
* - Internal pointer: `#/$defs/contact` — navigates the root schema by JSON Pointer
|
|
6
|
+
* - Internal anchor: `#contact` — resolves against the document's `$anchor` /
|
|
7
|
+
* `$dynamicAnchor` declarations (see {@link buildAnchorMap})
|
|
6
8
|
* - URI key: `http://example.com/foo.json` — looks up the key directly in `$defs`
|
|
7
9
|
* - URI with fragment: `http://example.com/foo.json#/definitions/bar` — looks up
|
|
8
10
|
* the base URI in `$defs`, then navigates the fragment within that definition
|
package/dist/resolve-ref.js
CHANGED
|
@@ -1,10 +1,32 @@
|
|
|
1
|
+
import { buildAnchorMap } from "./build-anchor-map.js";
|
|
2
|
+
const anchorMaps = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
const getAnchorMap = (rootSchema) => {
|
|
4
|
+
const existing = anchorMaps.get(rootSchema);
|
|
5
|
+
if (existing)
|
|
6
|
+
return existing;
|
|
7
|
+
const map = buildAnchorMap(rootSchema);
|
|
8
|
+
anchorMaps.set(rootSchema, map);
|
|
9
|
+
return map;
|
|
10
|
+
};
|
|
11
|
+
const percentDecode = (token) => {
|
|
12
|
+
if (!token.includes("%"))
|
|
13
|
+
return token;
|
|
14
|
+
try {
|
|
15
|
+
return decodeURIComponent(token);
|
|
16
|
+
} catch {
|
|
17
|
+
return token;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
const pointerTokens = (pointer) => {
|
|
21
|
+
if (pointer === "")
|
|
22
|
+
return [];
|
|
23
|
+
return (pointer.startsWith("/") ? pointer.slice(1) : pointer).split("/").map((token) => percentDecode(token).replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
24
|
+
};
|
|
1
25
|
const navigatePointer = (pointer, schema) => {
|
|
2
|
-
const parts = pointer.split("/").filter(Boolean);
|
|
3
26
|
let current = schema;
|
|
4
|
-
for (const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const next = current[decodedPart];
|
|
27
|
+
for (const token of pointerTokens(pointer)) {
|
|
28
|
+
if (current && typeof current === "object" && Object.hasOwn(current, token)) {
|
|
29
|
+
const next = current[token];
|
|
8
30
|
if (typeof next === "object" && next !== null) {
|
|
9
31
|
current = next;
|
|
10
32
|
} else {
|
|
@@ -18,7 +40,11 @@ const navigatePointer = (pointer, schema) => {
|
|
|
18
40
|
};
|
|
19
41
|
const resolveRef = (ref, rootSchema) => {
|
|
20
42
|
if (ref.startsWith("#")) {
|
|
21
|
-
|
|
43
|
+
const fragment2 = ref === "#/" ? "" : ref.slice(1);
|
|
44
|
+
if (fragment2 === "" || fragment2.startsWith("/"))
|
|
45
|
+
return navigatePointer(fragment2, rootSchema);
|
|
46
|
+
const pointer = getAnchorMap(rootSchema)[fragment2];
|
|
47
|
+
return pointer === void 0 ? void 0 : navigatePointer(pointer.slice(1), rootSchema);
|
|
22
48
|
}
|
|
23
49
|
const hashIndex = ref.indexOf("#");
|
|
24
50
|
const baseUri = hashIndex === -1 ? ref : ref.slice(0, hashIndex);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ResourceRegistry } from './build-resource-registry.js';
|
|
2
|
+
/**
|
|
3
|
+
* Where a `$ref` lands once the `$id` base URIs in scope are applied.
|
|
4
|
+
*
|
|
5
|
+
* `pointer` is a JSON Pointer from the *document* root (`''` for the root
|
|
6
|
+
* itself), so `#${pointer}` is a `$ref` every other helper here already
|
|
7
|
+
* understands. `base` is the base URI refs written inside the target resolve
|
|
8
|
+
* against, which a caller that keeps resolving as it walks needs in order to
|
|
9
|
+
* take the next step.
|
|
10
|
+
*/
|
|
11
|
+
export type ScopedRefTarget = {
|
|
12
|
+
readonly pointer: string;
|
|
13
|
+
readonly base: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Resolves `ref` against `base` and locates the result among the document's
|
|
17
|
+
* embedded resources — the half of `$ref` handling that plain pointer navigation
|
|
18
|
+
* deliberately leaves out.
|
|
19
|
+
*
|
|
20
|
+
* Every form a 2020-12 document can write is one call: a relative URI
|
|
21
|
+
* (`"list"`), an absolute one, an absolute path (`"/absref/foobar.json"`), a URN,
|
|
22
|
+
* a pointer into a resource (`"a.json#/$defs/x"`), an anchor in a resource
|
|
23
|
+
* (`"child1#my_anchor"`), and the plain in-document `"#/$defs/x"` — which under
|
|
24
|
+
* an enclosing `$id` means *that resource's* `$defs`, not the document's.
|
|
25
|
+
*
|
|
26
|
+
* Returns `undefined` when the URI names no resource in this document, or when
|
|
27
|
+
* the resource has no such anchor. That is an honest "not here": the target may
|
|
28
|
+
* live in another document, which is a fetch this package does not do.
|
|
29
|
+
*
|
|
30
|
+
* A *pointer* fragment is located, not navigated — the registry holds pointers,
|
|
31
|
+
* not the document — so `"a.json#/$defs/nope"` still comes back as a pointer
|
|
32
|
+
* into `a.json`. Callers that need the subschema itself run the returned pointer
|
|
33
|
+
* through `resolveRef`, which is also how they find out it names nothing.
|
|
34
|
+
*/
|
|
35
|
+
export declare const resolveScopedRef: (registry: ResourceRegistry, ref: string, base: string) => ScopedRefTarget | undefined;
|