@amritk/helpers 0.13.1 → 0.13.3

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.
@@ -1,160 +1,97 @@
1
- /**
2
- * Upgrades a JSON Schema draft-07 document to be compatible with the
3
- * draft 2020-12 conventions used by the build pipeline.
4
- *
5
- * Draft-07 schemas differ from 2020-12 in two ways that affect our pipeline:
6
- * - They use `definitions` instead of `$defs`
7
- * - Their `definitions` keys (and `$ref` values) may be full URIs
8
- * (e.g. `http://asyncapi.com/definitions/3.1.0/channel.json`) rather than
9
- * short names (e.g. `channel`)
10
- *
11
- * This function:
12
- * 1. Renames `definitions` → `$defs` at the root level only
13
- * 2. Hoists any nested `$defs` (originally `definitions` inside sub-schemas)
14
- * up to the root `$defs` with a prefixed name, rewriting internal refs
15
- * so they resolve correctly from the root
16
- * 3. Rewrites bare `$ref: "#"` self-references within each definition to
17
- * point back to that definition's root-level `$defs` entry
18
- *
19
- * Only applied when the schema declares `$schema: http://json-schema.org/draft-07/schema`.
20
- */
21
- import { refToFilename, toKebabCase } from './ref-to-filename.js';
22
- /**
23
- * Returns true if the schema is a draft-07 document that needs upgrading.
24
- */
25
- export const isDraft07Schema = (schema) => typeof schema['$schema'] === 'string' && schema['$schema'].includes('draft-07');
26
- /**
27
- * Rewrites `$ref` values in a schema tree using an explicit string→string map.
28
- * Also rewrites bare `$ref: "#"` to the given `selfRef` path when provided.
29
- */
1
+ import { refToFilename, toKebabCase } from "./ref-to-filename.js";
2
+ const isDraft07Schema = (schema) => typeof schema["$schema"] === "string" && schema["$schema"].includes("draft-07");
30
3
  const rewriteRefs = (obj, refMap, selfRef) => {
31
- if (typeof obj !== 'object' || obj === null)
32
- return obj;
33
- if (Array.isArray(obj))
34
- return obj.map((item) => rewriteRefs(item, refMap, selfRef));
35
- const record = obj;
36
- const result = {};
37
- for (const [key, value] of Object.entries(record)) {
38
- if (key === '$ref' && typeof value === 'string') {
39
- if (refMap.has(value)) {
40
- result[key] = refMap.get(value);
41
- }
42
- else if (value === '#' && selfRef) {
43
- result[key] = selfRef;
44
- }
45
- else {
46
- result[key] = value;
47
- }
48
- }
49
- else {
50
- result[key] = rewriteRefs(value, refMap, selfRef);
51
- }
4
+ if (typeof obj !== "object" || obj === null)
5
+ return obj;
6
+ if (Array.isArray(obj))
7
+ return obj.map((item) => rewriteRefs(item, refMap, selfRef));
8
+ const record = obj;
9
+ const result = {};
10
+ for (const [key, value] of Object.entries(record)) {
11
+ if (key === "$ref" && typeof value === "string") {
12
+ if (refMap.has(value)) {
13
+ result[key] = refMap.get(value);
14
+ } else if (value === "#" && selfRef) {
15
+ result[key] = selfRef;
16
+ } else {
17
+ result[key] = value;
18
+ }
19
+ } else {
20
+ result[key] = rewriteRefs(value, refMap, selfRef);
52
21
  }
53
- return result;
22
+ }
23
+ return result;
54
24
  };
55
- /**
56
- * Hoists nested `$defs` from each root-level definition up to the root `$defs`.
57
- *
58
- * When a definition contains its own `$defs` (originally `definitions` in draft-07,
59
- * e.g. the json-schema meta-schema or avro schema), those nested defs are moved to
60
- * the root with a `parentName-childName` prefix. All internal `#/$defs/X` refs
61
- * within the parent and its nested defs are rewritten to `#/$defs/parentName-X`.
62
- * Bare `$ref: "#"` within nested defs is rewritten to `#/$defs/parentName`.
63
- */
64
25
  const hoistNestedDefs = (defs) => {
65
- const hoisted = {};
66
- for (const [parentName, parentSchema] of Object.entries(defs)) {
67
- if (typeof parentSchema !== 'object' || parentSchema === null) {
68
- hoisted[parentName] = parentSchema;
69
- continue;
70
- }
71
- const parentObj = parentSchema;
72
- const nestedDefs = parentObj['$defs'];
73
- if (!nestedDefs || typeof nestedDefs !== 'object') {
74
- hoisted[parentName] = parentSchema;
75
- continue;
76
- }
77
- // Derive a short kebab-case prefix from the parent name (which may be a URI)
78
- const parentPrefix = parentName.startsWith('http://') || parentName.startsWith('https://') ? refToFilename(parentName) : parentName;
79
- // Build a map from local ref → hoisted ref for every nested def
80
- const localToHoisted = new Map();
81
- for (const localName of Object.keys(nestedDefs)) {
82
- const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`;
83
- localToHoisted.set(`#/$defs/${localName}`, `#/$defs/${hoistedName}`);
84
- }
85
- const selfRef = `#/$defs/${parentPrefix}`;
86
- // Rewrite refs in the parent. Keep the nested $defs in place so that
87
- // URI-with-fragment refs (e.g. "http://foo.json#/$defs/queue") can still
88
- // navigate into the parent's nested defs after resolution.
89
- const rewrittenParent = rewriteRefs(parentObj, localToHoisted, selfRef);
90
- hoisted[parentName] = rewrittenParent;
91
- // Hoist each nested def, rewriting its internal refs too
92
- for (const [localName, localSchema] of Object.entries(nestedDefs)) {
93
- const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`;
94
- hoisted[hoistedName] = rewriteRefs(localSchema, localToHoisted, selfRef);
95
- }
26
+ const hoisted = {};
27
+ for (const [parentName, parentSchema] of Object.entries(defs)) {
28
+ if (typeof parentSchema !== "object" || parentSchema === null) {
29
+ hoisted[parentName] = parentSchema;
30
+ continue;
96
31
  }
97
- return hoisted;
98
- };
99
- /**
100
- * Upgrades a draft-07 schema so it is compatible with the build pipeline.
101
- * If the schema is not draft-07, it is returned unchanged.
102
- *
103
- * @param schema - The raw JSON Schema (any draft)
104
- * @returns The schema with `definitions` renamed to `$defs` at the root,
105
- * nested defs hoisted to the root, and internal refs rewritten
106
- */
107
- export const upgradeDraft07Schema = (schema) => {
108
- if (!isDraft07Schema(schema))
109
- return schema;
110
- // Rename root-level `definitions` to `$defs` (keep all other keys as-is)
111
- const { definitions, $schema: _, ...rest } = schema;
112
- const rawDefs = (definitions ?? {});
113
- // Recursively rename `definitions` → `$defs` inside each definition's body
114
- // so nested defs are accessible before hoisting
115
- const renamedDefs = {};
116
- for (const [key, value] of Object.entries(rawDefs)) {
117
- renamedDefs[key] = renameNestedDefs(value);
32
+ const parentObj = parentSchema;
33
+ const nestedDefs = parentObj["$defs"];
34
+ if (!nestedDefs || typeof nestedDefs !== "object") {
35
+ hoisted[parentName] = parentSchema;
36
+ continue;
37
+ }
38
+ const parentPrefix = parentName.startsWith("http://") || parentName.startsWith("https://") ? refToFilename(parentName) : parentName;
39
+ const localToHoisted = /* @__PURE__ */ new Map();
40
+ for (const localName of Object.keys(nestedDefs)) {
41
+ const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`;
42
+ localToHoisted.set(`#/$defs/${localName}`, `#/$defs/${hoistedName}`);
118
43
  }
119
- // Hoist nested $defs up to root so the pipeline can resolve all refs flatly
120
- const hoistedDefs = hoistNestedDefs(renamedDefs);
121
- // Add short-name aliases for URI-keyed definitions so that internal refs
122
- // like `#/$defs/draft-07-schema` (produced by self-ref rewriting in hoistNestedDefs)
123
- // resolve correctly alongside the original URI key lookups.
124
- for (const key of Object.keys(hoistedDefs)) {
125
- if (key.startsWith('http://') || key.startsWith('https://')) {
126
- const shortName = refToFilename(key);
127
- if (shortName && !(shortName in hoistedDefs)) {
128
- hoistedDefs[shortName] = hoistedDefs[key];
129
- }
130
- }
44
+ const selfRef = `#/$defs/${parentPrefix}`;
45
+ const rewrittenParent = rewriteRefs(parentObj, localToHoisted, selfRef);
46
+ hoisted[parentName] = rewrittenParent;
47
+ for (const [localName, localSchema] of Object.entries(nestedDefs)) {
48
+ const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`;
49
+ hoisted[hoistedName] = rewriteRefs(localSchema, localToHoisted, selfRef);
131
50
  }
132
- return {
133
- ...rest,
134
- $defs: hoistedDefs,
135
- };
51
+ }
52
+ return hoisted;
53
+ };
54
+ const upgradeDraft07Schema = (schema) => {
55
+ if (!isDraft07Schema(schema))
56
+ return schema;
57
+ const { definitions, $schema: _, ...rest } = schema;
58
+ const rawDefs = definitions ?? {};
59
+ const renamedDefs = {};
60
+ for (const [key, value] of Object.entries(rawDefs)) {
61
+ renamedDefs[key] = renameNestedDefs(value);
62
+ }
63
+ const hoistedDefs = hoistNestedDefs(renamedDefs);
64
+ for (const key of Object.keys(hoistedDefs)) {
65
+ if (key.startsWith("http://") || key.startsWith("https://")) {
66
+ const shortName = refToFilename(key);
67
+ if (shortName && !(shortName in hoistedDefs)) {
68
+ hoistedDefs[shortName] = hoistedDefs[key];
69
+ }
70
+ }
71
+ }
72
+ return {
73
+ ...rest,
74
+ $defs: hoistedDefs
75
+ };
136
76
  };
137
- /**
138
- * Recursively renames `definitions` → `$defs` within a schema value and
139
- * rewrites `$ref: "#/definitions/X"` to `$ref: "#/$defs/X"` so that
140
- * `hoistNestedDefs` can map them to their hoisted root-level equivalents.
141
- * Does NOT hoist — hoisting is done separately at the root level.
142
- */
143
77
  const renameNestedDefs = (obj) => {
144
- if (typeof obj !== 'object' || obj === null)
145
- return obj;
146
- if (Array.isArray(obj))
147
- return obj.map(renameNestedDefs);
148
- const record = obj;
149
- const result = {};
150
- for (const [key, value] of Object.entries(record)) {
151
- if (key === '$ref' && typeof value === 'string' && value.startsWith('#/definitions/')) {
152
- result[key] = value.replace('#/definitions/', '#/$defs/');
153
- }
154
- else {
155
- const outKey = key === 'definitions' ? '$defs' : key;
156
- result[outKey] = renameNestedDefs(value);
157
- }
78
+ if (typeof obj !== "object" || obj === null)
79
+ return obj;
80
+ if (Array.isArray(obj))
81
+ return obj.map(renameNestedDefs);
82
+ const record = obj;
83
+ const result = {};
84
+ for (const [key, value] of Object.entries(record)) {
85
+ if (key === "$ref" && typeof value === "string" && value.startsWith("#/definitions/")) {
86
+ result[key] = value.replace("#/definitions/", "#/$defs/");
87
+ } else {
88
+ const outKey = key === "definitions" ? "$defs" : key;
89
+ result[outKey] = renameNestedDefs(value);
158
90
  }
159
- return result;
91
+ }
92
+ return result;
93
+ };
94
+ export {
95
+ isDraft07Schema,
96
+ upgradeDraft07Schema
160
97
  };
@@ -1,33 +1,22 @@
1
- /**
2
- * Parses the items of an array with a parser function.
3
- *
4
- * When every element parses to the very same reference — the parser found it
5
- * already valid and handed it back, as the generated item sub-parsers do for
6
- * clean values — the input array itself is returned and nothing is allocated.
7
- * The result array is only materialized (lazily, on the first element the
8
- * parser actually replaced) when something was coerced or stripped, so the
9
- * common all-clean parse costs no allocation at all. Callers already share
10
- * element references either way; sharing the container mirrors the generated
11
- * fast paths, which return the input array by reference too.
12
- */
13
- export const validateArray = (input, parser) => {
14
- if (!Array.isArray(input)) {
15
- return [];
1
+ const validateArray = (input, parser) => {
2
+ if (!Array.isArray(input)) {
3
+ return [];
4
+ }
5
+ const len = input.length;
6
+ let result = null;
7
+ for (let i = 0; i < len; i++) {
8
+ const parsed = parser(input[i]);
9
+ if (result !== null) {
10
+ result[i] = parsed;
11
+ } else if (parsed !== input[i]) {
12
+ result = new Array(len);
13
+ for (let j = 0; j < i; j++)
14
+ result[j] = input[j];
15
+ result[i] = parsed;
16
16
  }
17
- const len = input.length;
18
- let result = null;
19
- for (let i = 0; i < len; i++) {
20
- const parsed = parser(input[i]);
21
- if (result !== null) {
22
- result[i] = parsed;
23
- }
24
- else if (parsed !== input[i]) {
25
- // First replaced element: materialize the copy and backfill the prefix.
26
- result = new Array(len);
27
- for (let j = 0; j < i; j++)
28
- result[j] = input[j];
29
- result[i] = parsed;
30
- }
31
- }
32
- return result ?? input;
17
+ }
18
+ return result ?? input;
19
+ };
20
+ export {
21
+ validateArray
33
22
  };
@@ -1,26 +1,20 @@
1
- import { isObject } from './is-object.js';
2
- /**
3
- * Parses the values of a record with a parser function.
4
- * Uses for...in instead of Object.entries() to avoid allocating an intermediate array.
5
- */
6
- export const validateRecord = (input, parser) => {
7
- if (!isObject(input)) {
8
- return {};
1
+ import { isObject } from "./is-object.js";
2
+ const validateRecord = (input, parser) => {
3
+ if (!isObject(input)) {
4
+ return {};
5
+ }
6
+ const record = input;
7
+ const result = {};
8
+ for (const key in record) {
9
+ const value = parser(record[key]);
10
+ if (key === "__proto__") {
11
+ Object.defineProperty(result, key, { value, writable: true, enumerable: true, configurable: true });
12
+ } else {
13
+ result[key] = value;
9
14
  }
10
- const record = input;
11
- const result = {};
12
- for (const key in record) {
13
- const value = parser(record[key]);
14
- // A plain assignment of `__proto__` invokes the prototype setter and
15
- // corrupts `result`'s prototype (a prototype-pollution vector for untrusted
16
- // input). Define it as an own data property instead so it round-trips as a
17
- // normal key, matching every other property.
18
- if (key === '__proto__') {
19
- Object.defineProperty(result, key, { value, writable: true, enumerable: true, configurable: true });
20
- }
21
- else {
22
- result[key] = value;
23
- }
24
- }
25
- return result;
15
+ }
16
+ return result;
17
+ };
18
+ export {
19
+ validateRecord
26
20
  };
@@ -1,172 +1,127 @@
1
- import { buildDynamicRefMap } from './build-dynamic-ref-map.js';
2
- import { extractRefs } from './extract-refs.js';
3
- import { refToFilename } from './ref-to-filename.js';
4
- import { refToName } from './ref-to-name.js';
5
- import { resolveDynamicRefs } from './resolve-dynamic-refs.js';
6
- import { resolveRef } from './resolve-ref.js';
7
- import { upgradeDraft07Schema } from './upgrade-draft07-schema.js';
8
- const rootCaches = new WeakMap();
9
- /**
10
- * Keywords that give a schema a shape of its own. A root carrying any of these
11
- * next to its `$ref` is a real composition, not a pure alias, and keeps the
12
- * default root handling.
13
- */
1
+ import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
2
+ import { extractRefs } from "./extract-refs.js";
3
+ import { refToFilename } from "./ref-to-filename.js";
4
+ import { refToName } from "./ref-to-name.js";
5
+ import { resolveDynamicRefs } from "./resolve-dynamic-refs.js";
6
+ import { resolveRef } from "./resolve-ref.js";
7
+ import { upgradeDraft07Schema } from "./upgrade-draft07-schema.js";
8
+ const rootCaches = /* @__PURE__ */ new WeakMap();
14
9
  const SHAPE_KEYWORDS = [
15
- 'properties',
16
- 'type',
17
- 'oneOf',
18
- 'anyOf',
19
- 'allOf',
20
- 'patternProperties',
21
- 'additionalProperties',
22
- 'enum',
23
- 'const',
24
- 'items',
25
- 'prefixItems',
26
- 'required',
27
- 'if',
28
- 'then',
29
- 'else',
30
- 'not',
10
+ "properties",
11
+ "type",
12
+ "oneOf",
13
+ "anyOf",
14
+ "allOf",
15
+ "patternProperties",
16
+ "additionalProperties",
17
+ "enum",
18
+ "const",
19
+ "items",
20
+ "prefixItems",
21
+ "required",
22
+ "if",
23
+ "then",
24
+ "else",
25
+ "not"
31
26
  ];
32
- /** The `$ref` of a pure-alias root document (only `$ref` + metadata keys), or null. */
33
27
  const getAliasRootRef = (schema) => {
34
- if (typeof schema !== 'object' || schema === null)
35
- return null;
36
- const record = schema;
37
- if (typeof record['$ref'] !== 'string')
38
- return null;
39
- return SHAPE_KEYWORDS.some((key) => key in record) ? null : record['$ref'];
28
+ if (typeof schema !== "object" || schema === null)
29
+ return null;
30
+ const record = schema;
31
+ if (typeof record["$ref"] !== "string")
32
+ return null;
33
+ return SHAPE_KEYWORDS.some((key) => key in record) ? null : record["$ref"];
40
34
  };
41
35
  const getRootCache = (rootSchema) => {
42
- // Only object roots can key a WeakMap. A boolean root has no refs to walk and
43
- // the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
44
- if (typeof rootSchema !== 'object' || rootSchema === null) {
45
- const upgraded = rootSchema;
46
- return { upgraded, dynamicRefMap: {}, resolveRefCache: new Map(), extractRefsCache: new WeakMap() };
47
- }
48
- const existing = rootCaches.get(rootSchema);
49
- if (existing)
50
- return existing;
51
- const upgraded = upgradeDraft07Schema(rootSchema);
52
- const cache = {
53
- upgraded,
54
- dynamicRefMap: buildDynamicRefMap(upgraded),
55
- resolveRefCache: new Map(),
56
- extractRefsCache: new WeakMap(),
57
- };
58
- rootCaches.set(rootSchema, cache);
59
- return cache;
36
+ if (typeof rootSchema !== "object" || rootSchema === null) {
37
+ const upgraded2 = rootSchema;
38
+ return { upgraded: upgraded2, dynamicRefMap: {}, resolveRefCache: /* @__PURE__ */ new Map(), extractRefsCache: /* @__PURE__ */ new WeakMap() };
39
+ }
40
+ const existing = rootCaches.get(rootSchema);
41
+ if (existing)
42
+ return existing;
43
+ const upgraded = upgradeDraft07Schema(rootSchema);
44
+ const cache = {
45
+ upgraded,
46
+ dynamicRefMap: buildDynamicRefMap(upgraded),
47
+ resolveRefCache: /* @__PURE__ */ new Map(),
48
+ extractRefsCache: /* @__PURE__ */ new WeakMap()
49
+ };
50
+ rootCaches.set(rootSchema, cache);
51
+ return cache;
60
52
  };
61
- /** Memoized `resolveRef` keyed by ref string within a single root document. */
62
53
  const cachedResolveRef = (cache, ref) => {
63
- if (cache.resolveRefCache.has(ref))
64
- return cache.resolveRefCache.get(ref);
65
- const resolved = resolveRef(ref, cache.upgraded);
66
- cache.resolveRefCache.set(ref, resolved);
67
- return resolved;
54
+ if (cache.resolveRefCache.has(ref))
55
+ return cache.resolveRefCache.get(ref);
56
+ const resolved = resolveRef(ref, cache.upgraded);
57
+ cache.resolveRefCache.set(ref, resolved);
58
+ return resolved;
68
59
  };
69
- /** Memoized `extractRefs` keyed by the (stable) resolved subschema identity. */
70
60
  const cachedExtractRefs = (cache, schema) => {
71
- if (typeof schema !== 'object' || schema === null)
72
- return extractRefs(schema);
73
- const existing = cache.extractRefsCache.get(schema);
74
- if (existing)
75
- return existing;
76
- const refs = extractRefs(schema);
77
- cache.extractRefsCache.set(schema, refs);
78
- return refs;
61
+ if (typeof schema !== "object" || schema === null)
62
+ return extractRefs(schema);
63
+ const existing = cache.extractRefsCache.get(schema);
64
+ if (existing)
65
+ return existing;
66
+ const refs = extractRefs(schema);
67
+ cache.extractRefsCache.set(schema, refs);
68
+ return refs;
79
69
  };
80
- /**
81
- * Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
82
- * `visit` once per distinct output file: first the root, then every reachable
83
- * definition (breadth-first). This is the single, shared traversal the parser,
84
- * validator, and example generators were each re-implementing.
85
- *
86
- * For every node the walker has already upgraded draft-07 inputs, resolved the
87
- * ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
88
- * callers only have to turn `node.schema` into file content. Definitions
89
- * reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
90
- * code imports goes ungenerated. A ref that fails to resolve is reported via
91
- * `console.warn` and skipped, matching the generators' prior behavior.
92
- *
93
- * Resolution work is memoized per root document (see {@link RootCache}), so
94
- * running several generators over the same loaded schema does the expensive
95
- * walking once.
96
- *
97
- * @param rootSchema - The root JSON Schema to walk.
98
- * @param rootTypeName - The name for the root type (e.g. `'Document'`).
99
- * @param options - Naming options ({@link WalkRefGraphOptions}).
100
- * @param visit - Called once per output file with a fully prepared {@link RefNode}.
101
- */
102
- export const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
103
- const typeSuffix = options.typeSuffix ?? '';
104
- const cache = getRootCache(rootSchema);
105
- const { upgraded, dynamicRefMap } = cache;
106
- const processedRefs = new Set();
107
- const processedFilenames = new Set();
108
- // Root node first — its filename reserves a slot so a later ref that maps to
109
- // the same name does not emit a duplicate file.
110
- const rootFilename = rootTypeName.toLowerCase();
111
- processedFilenames.add(rootFilename);
112
- // An alias root (a document that is just `$ref: '#/$defs/x'`) whose derived
113
- // filename equals its target's would reserve the filename for a wrapper that
114
- // re-exports the target — and the target, mapping to the same file, would
115
- // then never be generated, leaving a file that imports itself. Generate the
116
- // *target's* schema under the root's name instead, carrying the ref so
117
- // generators can exclude the self-import.
118
- let rootNodeSchema = upgraded;
119
- let rootNodeRef;
120
- const aliasRef = getAliasRootRef(upgraded);
121
- if (aliasRef && refToFilename(aliasRef) === rootFilename) {
122
- const resolved = cachedResolveRef(cache, aliasRef);
123
- if (resolved) {
124
- rootNodeSchema = resolved;
125
- rootNodeRef = aliasRef;
126
- }
70
+ const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
71
+ const typeSuffix = options.typeSuffix ?? "";
72
+ const cache = getRootCache(rootSchema);
73
+ const { upgraded, dynamicRefMap } = cache;
74
+ const processedRefs = /* @__PURE__ */ new Set();
75
+ const processedFilenames = /* @__PURE__ */ new Set();
76
+ const rootFilename = rootTypeName.toLowerCase();
77
+ processedFilenames.add(rootFilename);
78
+ let rootNodeSchema = upgraded;
79
+ let rootNodeRef;
80
+ const aliasRef = getAliasRootRef(upgraded);
81
+ if (aliasRef && refToFilename(aliasRef) === rootFilename) {
82
+ const resolved = cachedResolveRef(cache, aliasRef);
83
+ if (resolved) {
84
+ rootNodeSchema = resolved;
85
+ rootNodeRef = aliasRef;
86
+ }
87
+ }
88
+ visit({
89
+ ref: rootNodeRef,
90
+ typeName: rootTypeName,
91
+ filename: rootFilename,
92
+ schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
93
+ rootSchema: upgraded,
94
+ isRoot: true
95
+ });
96
+ const queue = [...cachedExtractRefs(cache, upgraded), ...Object.values(dynamicRefMap)];
97
+ for (let head = 0; head < queue.length; head++) {
98
+ const ref = queue[head];
99
+ if (!ref || processedRefs.has(ref))
100
+ continue;
101
+ processedRefs.add(ref);
102
+ const resolved = cachedResolveRef(cache, ref);
103
+ if (!resolved) {
104
+ console.warn(`Warning: Could not resolve ref: ${ref}`);
105
+ continue;
127
106
  }
128
- visit({
129
- ref: rootNodeRef,
130
- typeName: rootTypeName,
131
- filename: rootFilename,
132
- schema: resolveDynamicRefs(rootNodeSchema, dynamicRefMap),
107
+ const filename = refToFilename(ref);
108
+ if (!processedFilenames.has(filename)) {
109
+ processedFilenames.add(filename);
110
+ visit({
111
+ ref,
112
+ typeName: refToName(ref, typeSuffix),
113
+ filename,
114
+ schema: resolveDynamicRefs(resolved, dynamicRefMap),
133
115
  rootSchema: upgraded,
134
- isRoot: true,
135
- });
136
- // Seed dynamic-anchor targets from the memoized map instead of calling
137
- // extractDynamicAnchorDefs (which would re-walk the whole document — the map
138
- // already holds exactly those refs as its values).
139
- const queue = [...cachedExtractRefs(cache, upgraded), ...Object.values(dynamicRefMap)];
140
- // Advance a read cursor instead of `queue.shift()`, whose O(n) element move
141
- // makes draining a large ref graph quadratic.
142
- for (let head = 0; head < queue.length; head++) {
143
- const ref = queue[head];
144
- if (!ref || processedRefs.has(ref))
145
- continue;
146
- processedRefs.add(ref);
147
- const resolved = cachedResolveRef(cache, ref);
148
- if (!resolved) {
149
- console.warn(`Warning: Could not resolve ref: ${ref}`);
150
- continue;
151
- }
152
- const filename = refToFilename(ref);
153
- if (!processedFilenames.has(filename)) {
154
- processedFilenames.add(filename);
155
- visit({
156
- ref,
157
- typeName: refToName(ref, typeSuffix),
158
- filename,
159
- schema: resolveDynamicRefs(resolved, dynamicRefMap),
160
- rootSchema: upgraded,
161
- isRoot: false,
162
- });
163
- }
164
- // Always queue nested refs from the resolved schema, even when its file was
165
- // a duplicate: two ref strings can share a filename yet reach different
166
- // sub-definitions (e.g. a URI key and its short-name alias).
167
- for (const nested of cachedExtractRefs(cache, resolved)) {
168
- if (!processedRefs.has(nested))
169
- queue.push(nested);
170
- }
116
+ isRoot: false
117
+ });
171
118
  }
119
+ for (const nested of cachedExtractRefs(cache, resolved)) {
120
+ if (!processedRefs.has(nested))
121
+ queue.push(nested);
122
+ }
123
+ }
124
+ };
125
+ export {
126
+ walkRefGraph
172
127
  };