@hey-api/json-schema-ref-parser 0.0.0-next-20260212230650

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/src/bundle.ts ADDED
@@ -0,0 +1,743 @@
1
+ import type { $RefParser } from '.';
2
+ import type { ParserOptions } from './options';
3
+ import Pointer from './pointer';
4
+ import $Ref from './ref';
5
+ import type $Refs from './refs';
6
+ import type { JSONSchema } from './types';
7
+ import * as url from './util/url';
8
+
9
+ const DEBUG_PERFORMANCE =
10
+ process.env.DEBUG === 'true' ||
11
+ (typeof globalThis !== 'undefined' && (globalThis as any).DEBUG_BUNDLE_PERFORMANCE === true);
12
+
13
+ const perf = {
14
+ log: (message: string, ...args: any[]) =>
15
+ DEBUG_PERFORMANCE && console.log('[PERF] ' + message, ...args),
16
+ mark: (name: string) => DEBUG_PERFORMANCE && performance.mark(name),
17
+ measure: (name: string, start: string, end: string) =>
18
+ DEBUG_PERFORMANCE && performance.measure(name, start, end),
19
+ warn: (message: string, ...args: any[]) =>
20
+ DEBUG_PERFORMANCE && console.warn('[PERF] ' + message, ...args),
21
+ };
22
+
23
+ export interface InventoryEntry {
24
+ $ref: any;
25
+ circular: any;
26
+ depth: any;
27
+ extended: any;
28
+ external: any;
29
+ file: any;
30
+ hash: any;
31
+ indirections: any;
32
+ key: any;
33
+ originalContainerType?: 'schemas' | 'parameters' | 'requestBodies' | 'responses' | 'headers';
34
+ parent: any;
35
+ pathFromRoot: any;
36
+ value: any;
37
+ }
38
+
39
+ /**
40
+ * Fast lookup using Map instead of linear search with deep equality
41
+ */
42
+ const createInventoryLookup = () => {
43
+ const lookup = new Map<string, InventoryEntry>();
44
+ const objectIds = new WeakMap<object, string>(); // Use WeakMap to avoid polluting objects
45
+ let idCounter = 0;
46
+ let lookupCount = 0;
47
+ let addCount = 0;
48
+
49
+ const getObjectId = (obj: any) => {
50
+ if (!objectIds.has(obj)) {
51
+ objectIds.set(obj, `obj_${++idCounter}`);
52
+ }
53
+ return objectIds.get(obj)!;
54
+ };
55
+
56
+ const createInventoryKey = ($refParent: any, $refKey: any) =>
57
+ // Use WeakMap-based lookup to avoid polluting the actual schema objects
58
+ `${getObjectId($refParent)}_${$refKey}`;
59
+
60
+ return {
61
+ add: (entry: InventoryEntry) => {
62
+ addCount++;
63
+ const key = createInventoryKey(entry.parent, entry.key);
64
+ lookup.set(key, entry);
65
+ if (addCount % 100 === 0) {
66
+ perf.log(`Inventory lookup: Added ${addCount} entries, map size: ${lookup.size}`);
67
+ }
68
+ },
69
+ find: ($refParent: any, $refKey: any) => {
70
+ lookupCount++;
71
+ const key = createInventoryKey($refParent, $refKey);
72
+ const result = lookup.get(key);
73
+ if (lookupCount % 100 === 0) {
74
+ perf.log(`Inventory lookup: ${lookupCount} lookups performed`);
75
+ }
76
+ return result;
77
+ },
78
+ getStats: () => ({ addCount, lookupCount, mapSize: lookup.size }),
79
+ remove: (entry: InventoryEntry) => {
80
+ const key = createInventoryKey(entry.parent, entry.key);
81
+ lookup.delete(key);
82
+ },
83
+ };
84
+ };
85
+
86
+ /**
87
+ * Determine the container type from a JSON Pointer path.
88
+ * Analyzes the path tokens to identify the appropriate OpenAPI component container.
89
+ *
90
+ * @param path - The JSON Pointer path to analyze
91
+ * @returns The container type: "schemas", "parameters", "requestBodies", "responses", or "headers"
92
+ */
93
+ const getContainerTypeFromPath = (
94
+ path: string,
95
+ ): 'schemas' | 'parameters' | 'requestBodies' | 'responses' | 'headers' => {
96
+ const tokens = Pointer.parse(path);
97
+ const has = (t: string) => tokens.includes(t);
98
+ // Prefer more specific containers first
99
+ if (has('parameters')) {
100
+ return 'parameters';
101
+ }
102
+ if (has('requestBody')) {
103
+ return 'requestBodies';
104
+ }
105
+ if (has('headers')) {
106
+ return 'headers';
107
+ }
108
+ if (has('responses')) {
109
+ return 'responses';
110
+ }
111
+ if (has('schema')) {
112
+ return 'schemas';
113
+ }
114
+ // default: treat as schema-like
115
+ return 'schemas';
116
+ };
117
+
118
+ /**
119
+ * Inventories the given JSON Reference (i.e. records detailed information about it so we can
120
+ * optimize all $refs in the schema), and then crawls the resolved value.
121
+ */
122
+ const inventory$Ref = <S extends object = JSONSchema>({
123
+ $refKey,
124
+ $refParent,
125
+ $refs,
126
+ indirections,
127
+ inventory,
128
+ inventoryLookup,
129
+ options,
130
+ path,
131
+ pathFromRoot,
132
+ resolvedRefs = new Map(),
133
+ visitedObjects = new WeakSet(),
134
+ }: {
135
+ /**
136
+ * The key in `$refParent` that is a JSON Reference
137
+ */
138
+ $refKey: string | null;
139
+ /**
140
+ * The object that contains a JSON Reference as one of its keys
141
+ */
142
+ $refParent: any;
143
+ $refs: $Refs<S>;
144
+ /**
145
+ * unknown
146
+ */
147
+ indirections: number;
148
+ /**
149
+ * An array of already-inventoried $ref pointers
150
+ */
151
+ inventory: Array<InventoryEntry>;
152
+ /**
153
+ * Fast lookup for inventory entries
154
+ */
155
+ inventoryLookup: ReturnType<typeof createInventoryLookup>;
156
+ options: ParserOptions;
157
+ /**
158
+ * The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash
159
+ */
160
+ path: string;
161
+ /**
162
+ * The path of the JSON Reference at `$refKey`, from the schema root
163
+ */
164
+ pathFromRoot: string;
165
+ /**
166
+ * Cache for resolved $ref targets to avoid redundant resolution
167
+ */
168
+ resolvedRefs?: Map<string, any>;
169
+ /**
170
+ * Set of already visited objects to avoid infinite loops and redundant processing
171
+ */
172
+ visitedObjects?: WeakSet<object>;
173
+ }) => {
174
+ perf.mark('inventory-ref-start');
175
+ const $ref = $refKey === null ? $refParent : $refParent[$refKey];
176
+ const $refPath = url.resolve(path, $ref.$ref);
177
+
178
+ // Check cache first to avoid redundant resolution
179
+ let pointer = resolvedRefs.get($refPath);
180
+ if (!pointer) {
181
+ perf.mark('resolve-start');
182
+ pointer = $refs._resolve($refPath, pathFromRoot, options);
183
+ perf.mark('resolve-end');
184
+ perf.measure('resolve-time', 'resolve-start', 'resolve-end');
185
+
186
+ if (pointer) {
187
+ resolvedRefs.set($refPath, pointer);
188
+ perf.log(`Cached resolved $ref: ${$refPath}`);
189
+ }
190
+ }
191
+
192
+ if (pointer === null) {
193
+ perf.mark('inventory-ref-end');
194
+ perf.measure('inventory-ref-time', 'inventory-ref-start', 'inventory-ref-end');
195
+ return;
196
+ }
197
+
198
+ const parsed = Pointer.parse(pathFromRoot);
199
+ const depth = parsed.length;
200
+ const file = url.stripHash(pointer.path);
201
+ const hash = url.getHash(pointer.path);
202
+ const external = file !== $refs._root$Ref.path;
203
+ const extended = $Ref.isExtended$Ref($ref);
204
+ indirections += pointer.indirections;
205
+
206
+ // Check if this exact location (parent + key + pathFromRoot) has already been inventoried
207
+ perf.mark('lookup-start');
208
+ const existingEntry = inventoryLookup.find($refParent, $refKey);
209
+ perf.mark('lookup-end');
210
+ perf.measure('lookup-time', 'lookup-start', 'lookup-end');
211
+
212
+ if (existingEntry && existingEntry.pathFromRoot === pathFromRoot) {
213
+ // This exact location has already been inventoried, so we don't need to process it again
214
+ if (depth < existingEntry.depth || indirections < existingEntry.indirections) {
215
+ removeFromInventory(inventory, existingEntry);
216
+ inventoryLookup.remove(existingEntry);
217
+ } else {
218
+ perf.mark('inventory-ref-end');
219
+ perf.measure('inventory-ref-time', 'inventory-ref-start', 'inventory-ref-end');
220
+ return;
221
+ }
222
+ }
223
+
224
+ const newEntry: InventoryEntry = {
225
+ $ref, // The JSON Reference (e.g. {$ref: string})
226
+ circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)
227
+ depth, // How far from the JSON Schema root is this $ref pointer?
228
+ extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref")
229
+ external, // Does this $ref pointer point to a file other than the main JSON Schema file?
230
+ file, // The file that the $ref pointer resolves to
231
+ hash, // The hash within `file` that the $ref pointer resolves to
232
+ indirections, // The number of indirect references that were traversed to resolve the value
233
+ key: $refKey,
234
+ // The resolved value of the $ref pointer
235
+ originalContainerType: external ? getContainerTypeFromPath(pointer.path) : undefined,
236
+
237
+ // The key in `parent` that is the $ref pointer
238
+ parent: $refParent,
239
+
240
+ // The object that contains this $ref pointer
241
+ pathFromRoot,
242
+ // The path to the $ref pointer, from the JSON Schema root
243
+ value: pointer.value, // The original container type in the external file
244
+ };
245
+
246
+ inventory.push(newEntry);
247
+ inventoryLookup.add(newEntry);
248
+
249
+ perf.log(
250
+ `Inventoried $ref: ${$ref.$ref} -> ${file}${hash} (external: ${external}, depth: ${depth})`,
251
+ );
252
+
253
+ // Recursively crawl the resolved value
254
+ if (!existingEntry || external) {
255
+ perf.mark('crawl-recursive-start');
256
+ crawl({
257
+ $refs,
258
+ indirections: indirections + 1,
259
+ inventory,
260
+ inventoryLookup,
261
+ key: null,
262
+ options,
263
+ parent: pointer.value,
264
+ path: pointer.path,
265
+ pathFromRoot,
266
+ resolvedRefs,
267
+ visitedObjects,
268
+ });
269
+ perf.mark('crawl-recursive-end');
270
+ perf.measure('crawl-recursive-time', 'crawl-recursive-start', 'crawl-recursive-end');
271
+ }
272
+
273
+ perf.mark('inventory-ref-end');
274
+ perf.measure('inventory-ref-time', 'inventory-ref-start', 'inventory-ref-end');
275
+ };
276
+
277
+ /**
278
+ * Recursively crawls the given value, and inventories all JSON references.
279
+ */
280
+ const crawl = <S extends object = JSONSchema>({
281
+ $refs,
282
+ indirections,
283
+ inventory,
284
+ inventoryLookup,
285
+ key,
286
+ options,
287
+ parent,
288
+ path,
289
+ pathFromRoot,
290
+ resolvedRefs = new Map(),
291
+ visitedObjects = new WeakSet(),
292
+ }: {
293
+ $refs: $Refs<S>;
294
+ indirections: number;
295
+ /**
296
+ * An array of already-inventoried $ref pointers
297
+ */
298
+ inventory: Array<InventoryEntry>;
299
+ /**
300
+ * Fast lookup for inventory entries
301
+ */
302
+ inventoryLookup: ReturnType<typeof createInventoryLookup>;
303
+ /**
304
+ * The property key of `parent` to be crawled
305
+ */
306
+ key: string | null;
307
+ options: ParserOptions;
308
+ /**
309
+ * The object containing the value to crawl. If the value is not an object or array, it will be ignored.
310
+ */
311
+ parent: object | $RefParser;
312
+ /**
313
+ * The full path of the property being crawled, possibly with a JSON Pointer in the hash
314
+ */
315
+ path: string;
316
+ /**
317
+ * The path of the property being crawled, from the schema root
318
+ */
319
+ pathFromRoot: string;
320
+ /**
321
+ * Cache for resolved $ref targets to avoid redundant resolution
322
+ */
323
+ resolvedRefs?: Map<string, any>;
324
+ /**
325
+ * Set of already visited objects to avoid infinite loops and redundant processing
326
+ */
327
+ visitedObjects?: WeakSet<object>;
328
+ }) => {
329
+ const obj = key === null ? parent : parent[key as keyof typeof parent];
330
+
331
+ if (obj && typeof obj === 'object' && !ArrayBuffer.isView(obj)) {
332
+ // Early exit if we've already processed this exact object
333
+ if (visitedObjects.has(obj)) {
334
+ perf.log(`Skipping already visited object at ${pathFromRoot}`);
335
+ return;
336
+ }
337
+
338
+ if ($Ref.isAllowed$Ref(obj)) {
339
+ perf.log(`Found $ref at ${pathFromRoot}: ${(obj as any).$ref}`);
340
+ inventory$Ref({
341
+ $refKey: key,
342
+ $refParent: parent,
343
+ $refs,
344
+ indirections,
345
+ inventory,
346
+ inventoryLookup,
347
+ options,
348
+ path,
349
+ pathFromRoot,
350
+ resolvedRefs,
351
+ visitedObjects,
352
+ });
353
+ } else {
354
+ // Mark this object as visited BEFORE processing its children
355
+ visitedObjects.add(obj);
356
+
357
+ // Crawl the object in a specific order that's optimized for bundling.
358
+ // This is important because it determines how `pathFromRoot` gets built,
359
+ // which later determines which keys get dereferenced and which ones get remapped
360
+ const keys = Object.keys(obj).sort((a, b) => {
361
+ // Most people will expect references to be bundled into the "definitions" property,
362
+ // so we always crawl that property first, if it exists.
363
+ if (a === 'definitions') {
364
+ return -1;
365
+ } else if (b === 'definitions') {
366
+ return 1;
367
+ } else {
368
+ // Otherwise, crawl the keys based on their length.
369
+ // This produces the shortest possible bundled references
370
+ return a.length - b.length;
371
+ }
372
+ }) as (keyof typeof obj)[];
373
+
374
+ for (const key of keys) {
375
+ const keyPath = Pointer.join(path, key);
376
+ const keyPathFromRoot = Pointer.join(pathFromRoot, key);
377
+ const value = obj[key];
378
+
379
+ if ($Ref.isAllowed$Ref(value)) {
380
+ inventory$Ref({
381
+ $refKey: key,
382
+ $refParent: obj,
383
+ $refs,
384
+ indirections,
385
+ inventory,
386
+ inventoryLookup,
387
+ options,
388
+ path,
389
+ pathFromRoot: keyPathFromRoot,
390
+ resolvedRefs,
391
+ visitedObjects,
392
+ });
393
+ } else {
394
+ crawl({
395
+ $refs,
396
+ indirections,
397
+ inventory,
398
+ inventoryLookup,
399
+ key,
400
+ options,
401
+ parent: obj,
402
+ path: keyPath,
403
+ pathFromRoot: keyPathFromRoot,
404
+ resolvedRefs,
405
+ visitedObjects,
406
+ });
407
+ }
408
+ }
409
+ }
410
+ }
411
+ };
412
+
413
+ /**
414
+ * Remap external refs by hoisting resolved values into a shared container in the root schema
415
+ * and pointing all occurrences to those internal definitions. Internal refs remain internal.
416
+ */
417
+ function remap(parser: $RefParser, inventory: InventoryEntry[]) {
418
+ perf.log(`Starting remap with ${inventory.length} inventory entries`);
419
+ perf.mark('remap-start');
420
+ const root = parser.schema as any;
421
+
422
+ // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them
423
+ perf.mark('sort-inventory-start');
424
+ inventory.sort((a: InventoryEntry, b: InventoryEntry) => {
425
+ if (a.file !== b.file) {
426
+ // Group all the $refs that point to the same file
427
+ return a.file < b.file ? -1 : +1;
428
+ } else if (a.hash !== b.hash) {
429
+ // Group all the $refs that point to the same part of the file
430
+ return a.hash < b.hash ? -1 : +1;
431
+ } else if (a.circular !== b.circular) {
432
+ // If the $ref points to itself, then sort it higher than other $refs that point to this $ref
433
+ return a.circular ? -1 : +1;
434
+ } else if (a.extended !== b.extended) {
435
+ // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value
436
+ return a.extended ? +1 : -1;
437
+ } else if (a.indirections !== b.indirections) {
438
+ // Sort direct references higher than indirect references
439
+ return a.indirections - b.indirections;
440
+ } else if (a.depth !== b.depth) {
441
+ // Sort $refs by how close they are to the JSON Schema root
442
+ return a.depth - b.depth;
443
+ } else {
444
+ // Determine how far each $ref is from the "definitions" property.
445
+ // Most people will expect references to be bundled into the the "definitions" property if possible.
446
+ const aDefinitionsIndex = a.pathFromRoot.lastIndexOf('/definitions');
447
+ const bDefinitionsIndex = b.pathFromRoot.lastIndexOf('/definitions');
448
+ if (aDefinitionsIndex !== bDefinitionsIndex) {
449
+ // Give higher priority to the $ref that's closer to the "definitions" property
450
+ return bDefinitionsIndex - aDefinitionsIndex;
451
+ } else {
452
+ // All else is equal, so use the shorter path, which will produce the shortest possible reference
453
+ return a.pathFromRoot.length - b.pathFromRoot.length;
454
+ }
455
+ }
456
+ });
457
+
458
+ perf.mark('sort-inventory-end');
459
+ perf.measure('sort-inventory-time', 'sort-inventory-start', 'sort-inventory-end');
460
+
461
+ perf.log(`Sorted ${inventory.length} inventory entries`);
462
+
463
+ // Ensure or return a container by component type. Prefer OpenAPI-aware placement;
464
+ // otherwise use existing root containers; otherwise create components/*.
465
+ const ensureContainer = (
466
+ type: 'schemas' | 'parameters' | 'requestBodies' | 'responses' | 'headers',
467
+ ) => {
468
+ const isOas3 = !!(root && typeof root === 'object' && typeof root.openapi === 'string');
469
+ const isOas2 = !!(root && typeof root === 'object' && typeof root.swagger === 'string');
470
+
471
+ if (isOas3) {
472
+ if (!root.components || typeof root.components !== 'object') {
473
+ root.components = {};
474
+ }
475
+ if (!root.components[type] || typeof root.components[type] !== 'object') {
476
+ root.components[type] = {};
477
+ }
478
+ return { obj: root.components[type], prefix: `#/components/${type}` } as const;
479
+ }
480
+
481
+ if (isOas2) {
482
+ if (type === 'schemas') {
483
+ if (!root.definitions || typeof root.definitions !== 'object') {
484
+ root.definitions = {};
485
+ }
486
+ return { obj: root.definitions, prefix: '#/definitions' } as const;
487
+ }
488
+ if (type === 'parameters') {
489
+ if (!root.parameters || typeof root.parameters !== 'object') {
490
+ root.parameters = {};
491
+ }
492
+ return { obj: root.parameters, prefix: '#/parameters' } as const;
493
+ }
494
+ if (type === 'responses') {
495
+ if (!root.responses || typeof root.responses !== 'object') {
496
+ root.responses = {};
497
+ }
498
+ return { obj: root.responses, prefix: '#/responses' } as const;
499
+ }
500
+ // requestBodies/headers don't exist as reusable containers in OAS2; fallback to definitions
501
+ if (!root.definitions || typeof root.definitions !== 'object') {
502
+ root.definitions = {};
503
+ }
504
+ return { obj: root.definitions, prefix: '#/definitions' } as const;
505
+ }
506
+
507
+ // No explicit version: prefer existing containers
508
+ if (root && typeof root === 'object') {
509
+ if (root.components && typeof root.components === 'object') {
510
+ if (!root.components[type] || typeof root.components[type] !== 'object') {
511
+ root.components[type] = {};
512
+ }
513
+ return { obj: root.components[type], prefix: `#/components/${type}` } as const;
514
+ }
515
+ if (root.definitions && typeof root.definitions === 'object') {
516
+ return { obj: root.definitions, prefix: '#/definitions' } as const;
517
+ }
518
+ // Create components/* by default if nothing exists
519
+ if (!root.components || typeof root.components !== 'object') {
520
+ root.components = {};
521
+ }
522
+ if (!root.components[type] || typeof root.components[type] !== 'object') {
523
+ root.components[type] = {};
524
+ }
525
+ return { obj: root.components[type], prefix: `#/components/${type}` } as const;
526
+ }
527
+
528
+ // Fallback
529
+ root.definitions = root.definitions || {};
530
+ return { obj: root.definitions, prefix: '#/definitions' } as const;
531
+ };
532
+
533
+ /**
534
+ * Choose the appropriate component container for bundling.
535
+ * Prioritizes the original container type from external files over usage location.
536
+ *
537
+ * @param entry - The inventory entry containing reference information
538
+ * @returns The container type to use for bundling
539
+ */
540
+ const chooseComponent = (entry: InventoryEntry) => {
541
+ // If we have the original container type from the external file, use it
542
+ if (entry.originalContainerType) {
543
+ return entry.originalContainerType;
544
+ }
545
+
546
+ // Fallback to usage path for internal references or when original type is not available
547
+ return getContainerTypeFromPath(entry.pathFromRoot);
548
+ };
549
+
550
+ // Track names per (container prefix) and per target
551
+ const targetToNameByPrefix = new Map<string, Map<string, string>>();
552
+ const usedNamesByObj = new Map<any, Set<string>>();
553
+
554
+ const sanitize = (name: string) => name.replace(/[^A-Za-z0-9_-]/g, '_');
555
+ const baseName = (filePath: string) => {
556
+ try {
557
+ const withoutHash = filePath.split('#')[0]!;
558
+ const parts = withoutHash.split('/');
559
+ const filename = parts[parts.length - 1] || 'schema';
560
+ const dot = filename.lastIndexOf('.');
561
+ return sanitize(dot > 0 ? filename.substring(0, dot) : filename);
562
+ } catch {
563
+ return 'schema';
564
+ }
565
+ };
566
+ const lastToken = (hash: string) => {
567
+ if (!hash || hash === '#') {
568
+ return 'root';
569
+ }
570
+ const tokens = hash.replace(/^#\//, '').split('/');
571
+ return sanitize(tokens[tokens.length - 1] || 'root');
572
+ };
573
+ const uniqueName = (containerObj: any, proposed: string) => {
574
+ if (!usedNamesByObj.has(containerObj)) {
575
+ usedNamesByObj.set(containerObj, new Set<string>(Object.keys(containerObj || {})));
576
+ }
577
+ const used = usedNamesByObj.get(containerObj)!;
578
+ let name = proposed;
579
+ let i = 2;
580
+ while (used.has(name)) {
581
+ name = `${proposed}_${i++}`;
582
+ }
583
+ used.add(name);
584
+ return name;
585
+ };
586
+ perf.mark('remap-loop-start');
587
+ for (const entry of inventory) {
588
+ // Safety check: ensure entry and entry.$ref are valid objects
589
+ if (!entry || !entry.$ref || typeof entry.$ref !== 'object') {
590
+ perf.warn(`Skipping invalid inventory entry:`, entry);
591
+ continue;
592
+ }
593
+
594
+ // Keep internal refs internal. However, if the $ref extends the resolved value
595
+ // (i.e. it has additional properties in addition to "$ref"), then we must
596
+ // preserve the original $ref rather than rewriting it to the resolved hash.
597
+ if (!entry.external) {
598
+ if (!entry.extended && entry.$ref && typeof entry.$ref === 'object') {
599
+ entry.$ref.$ref = entry.hash;
600
+ }
601
+ continue;
602
+ }
603
+
604
+ // Avoid changing direct self-references; keep them internal
605
+ if (entry.circular) {
606
+ if (entry.$ref && typeof entry.$ref === 'object') {
607
+ entry.$ref.$ref = entry.pathFromRoot;
608
+ }
609
+ continue;
610
+ }
611
+
612
+ // Choose appropriate container based on original location in external file
613
+ const component = chooseComponent(entry);
614
+ const { obj: container, prefix } = ensureContainer(component);
615
+
616
+ const targetKey = `${entry.file}::${entry.hash}`;
617
+ if (!targetToNameByPrefix.has(prefix)) {
618
+ targetToNameByPrefix.set(prefix, new Map<string, string>());
619
+ }
620
+ const namesForPrefix = targetToNameByPrefix.get(prefix)!;
621
+
622
+ let defName = namesForPrefix.get(targetKey);
623
+ if (!defName) {
624
+ // If the external file is one of the original input sources, prefer its assigned prefix
625
+ let proposedBase = baseName(entry.file);
626
+ try {
627
+ const parserAny: any = parser as any;
628
+ if (
629
+ parserAny &&
630
+ parserAny.sourcePathToPrefix &&
631
+ typeof parserAny.sourcePathToPrefix.get === 'function'
632
+ ) {
633
+ const withoutHash = (entry.file || '').split('#')[0];
634
+ const mapped = parserAny.sourcePathToPrefix.get(withoutHash);
635
+ if (mapped && typeof mapped === 'string') {
636
+ proposedBase = mapped;
637
+ }
638
+ }
639
+ } catch {
640
+ // Ignore errors
641
+ }
642
+ const proposed = `${proposedBase}_${lastToken(entry.hash)}`;
643
+ defName = uniqueName(container, proposed);
644
+ namesForPrefix.set(targetKey, defName);
645
+ // Store the resolved value under the container
646
+ container[defName] = entry.value;
647
+ }
648
+
649
+ // Point the occurrence to the internal definition, preserving extensions
650
+ const refPath = `${prefix}/${defName}`;
651
+ if (entry.extended && entry.$ref && typeof entry.$ref === 'object') {
652
+ entry.$ref.$ref = refPath;
653
+ } else {
654
+ entry.parent[entry.key] = { $ref: refPath };
655
+ }
656
+ }
657
+ perf.mark('remap-loop-end');
658
+ perf.measure('remap-loop-time', 'remap-loop-start', 'remap-loop-end');
659
+
660
+ perf.mark('remap-end');
661
+ perf.measure('remap-total-time', 'remap-start', 'remap-end');
662
+
663
+ perf.log(`Completed remap of ${inventory.length} entries`);
664
+ }
665
+
666
+ function removeFromInventory(inventory: InventoryEntry[], entry: any) {
667
+ const index = inventory.indexOf(entry);
668
+ inventory.splice(index, 1);
669
+ }
670
+
671
+ /**
672
+ * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that
673
+ * only has *internal* references, not any *external* references.
674
+ * This method mutates the JSON schema object, adding new references and re-mapping existing ones.
675
+ *
676
+ * @param parser
677
+ * @param options
678
+ */
679
+ export const bundle = (parser: $RefParser, options: ParserOptions) => {
680
+ // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);
681
+ perf.mark('bundle-start');
682
+
683
+ // Build an inventory of all $ref pointers in the JSON Schema
684
+ const inventory: InventoryEntry[] = [];
685
+ const inventoryLookup = createInventoryLookup();
686
+
687
+ perf.log('Starting crawl phase');
688
+ perf.mark('crawl-phase-start');
689
+
690
+ const visitedObjects = new WeakSet<object>();
691
+ const resolvedRefs = new Map<string, any>(); // Cache for resolved $ref targets
692
+
693
+ crawl<JSONSchema>({
694
+ $refs: parser.$refs,
695
+ indirections: 0,
696
+ inventory,
697
+ inventoryLookup,
698
+ key: 'schema',
699
+ options,
700
+ parent: parser,
701
+ path: parser.$refs._root$Ref.path + '#',
702
+ pathFromRoot: '#',
703
+ resolvedRefs,
704
+ visitedObjects,
705
+ });
706
+
707
+ perf.mark('crawl-phase-end');
708
+ perf.measure('crawl-phase-time', 'crawl-phase-start', 'crawl-phase-end');
709
+
710
+ const stats = inventoryLookup.getStats();
711
+ perf.log(`Crawl phase complete. Found ${inventory.length} $refs. Lookup stats:`, stats);
712
+
713
+ // Remap all $ref pointers
714
+ perf.log('Starting remap phase');
715
+ perf.mark('remap-phase-start');
716
+ remap(parser, inventory);
717
+ perf.mark('remap-phase-end');
718
+ perf.measure('remap-phase-time', 'remap-phase-start', 'remap-phase-end');
719
+
720
+ perf.mark('bundle-end');
721
+ perf.measure('bundle-total-time', 'bundle-start', 'bundle-end');
722
+
723
+ perf.log('Bundle complete. Performance summary:');
724
+
725
+ // Log final stats
726
+ const finalStats = inventoryLookup.getStats();
727
+ perf.log(`Final inventory stats:`, finalStats);
728
+ perf.log(`Resolved refs cache size: ${resolvedRefs.size}`);
729
+
730
+ if (DEBUG_PERFORMANCE) {
731
+ // Log all performance measures
732
+ const measures = performance.getEntriesByType('measure');
733
+ measures.forEach((measure) => {
734
+ if (measure.name.includes('time')) {
735
+ console.log(`${measure.name}: ${measure.duration.toFixed(2)}ms`);
736
+ }
737
+ });
738
+
739
+ // Clear performance marks and measures for next run
740
+ performance.clearMarks();
741
+ performance.clearMeasures();
742
+ }
743
+ };