File size: 28,279 Bytes
f119c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Natsu @xiaoxiaojx
*/

"use strict";

const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils");
const { modulesResolveHandler } = require("./ModulesUtils");
const { readJson } = require("./util/fs");
const { PathType: _PathType, isSubPath, normalize } = require("./util/path");

/** @typedef {import("./Resolver")} Resolver */
/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
/** @typedef {import("./AliasUtils").AliasOption} AliasOption */
/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
/** @typedef {import("./Resolver").ResolveContext} ResolveContext */
/** @typedef {import("./Resolver").FileSystem} FileSystem */
/** @typedef {import("./Resolver").TsconfigPathsData} TsconfigPathsData */
/** @typedef {import("./Resolver").TsconfigPathsMap} TsconfigPathsMap */
/** @typedef {import("./ResolverFactory").TsconfigOptions} TsconfigOptions */

// Sentinel stored in `_contextSelectionCache` for `requestPath`s whose
// scan returned `null` ("no context matched"). Using a non-null marker
// lets the cache-hit path be a single `Map.get()` β€” we distinguish
// "cached null" from "not cached yet" without a second `has` lookup.
const NULL_CONTEXT = Symbol("NULL_CONTEXT");

/**
 * Per-`TsconfigPathsMap` memoization of `_selectPathsDataForContext`.
 *
 * Real-world builds resolve hundreds of requests per source file (every
 * import in the file), and webpack-style resolvers walk the same
 * `requestPath` (= source-file directory) for each one. Without this
 * cache every resolve re-scans the full `contextList` even though the
 * answer is invariant for a given `(map, requestPath)` pair.
 *
 * The outer key is the `TsconfigPathsMap` itself β€” rebuilt on every
 * tsconfig change β€” so a `WeakMap` lets the inner map be collected
 * automatically once the map goes away. The inner Map is keyed by
 * `requestPath` (string); a `Symbol` sentinel stands in for "no
 * matching context" so `Map.get` alone distinguishes the three states
 * (cached data / cached null / not cached).
 * @type {WeakMap<TsconfigPathsMap, Map<string, TsconfigPathsData | typeof NULL_CONTEXT>>}
 */
const _contextSelectionCache = new WeakMap();

/**
 * @typedef {object} TsconfigCompilerOptions
 * @property {string=} baseUrl Base URL for resolving paths
 * @property {{ [key: string]: string[] }=} paths TypeScript paths mapping
 */

/**
 * @typedef {object} TsconfigReference
 * @property {string} path Path to the referenced project
 */

/**
 * @typedef {object} Tsconfig
 * @property {TsconfigCompilerOptions=} compilerOptions Compiler options
 * @property {string | string[]=} extends Extended configuration paths
 * @property {TsconfigReference[]=} references Project references
 */

const DEFAULT_CONFIG_FILE = "tsconfig.json";

const READ_JSON_OPTIONS = { stripComments: true };

// Trailing `/*` or `\*` segment of a tsconfig `paths` mapping (e.g.
// `./src/*` β†’ `./src`). Hoisted so we don't allocate a fresh regex per
// path entry on every tsconfig load β€” and so the same regex object can be
// reused for the matching `test` + `replace` pair below.
const WILDCARD_TAIL_RE = /[/\\]\*$/;

/**
 * @param {string} pattern Path pattern
 * @returns {number} Length of the prefix
 */
function getPrefixLength(pattern) {
	const prefixLength = pattern.indexOf("*");
	if (prefixLength === -1) {
		return pattern.length;
	}
	return prefixLength;
}

/**
 * Sort path patterns.
 * If a module name can be matched with multiple patterns then pattern with the longest prefix will be picked.
 * @param {string[]} arr Array of path patterns
 * @returns {string[]} Array of path patterns sorted by longest prefix
 */
function sortByLongestPrefix(arr) {
	return [...arr].sort((a, b) => getPrefixLength(b) - getPrefixLength(a));
}

/**
 * Merge two tsconfig objects
 * @param {Tsconfig | null} base base config
 * @param {Tsconfig | null} config config to merge
 * @returns {Tsconfig} merged config
 */
function mergeTsconfigs(base, config) {
	base = base || {};
	config = config || {};

	return {
		...base,
		...config,
		compilerOptions: {
			.../** @type {TsconfigCompilerOptions} */ (base.compilerOptions),
			.../** @type {TsconfigCompilerOptions} */ (config.compilerOptions),
		},
	};
}

/**
 * Substitute ${configDir} template variable in path
 * @param {string} pathValue the path value
 * @param {string} configDir the config directory
 * @returns {string} the path with substituted template
 */
function substituteConfigDir(pathValue, configDir) {
	// eslint-disable-next-line no-template-curly-in-string
	if (!pathValue.includes("${configDir}")) return pathValue;
	return pathValue.replace(/\$\{configDir\}/g, configDir);
}

/**
 * Convert tsconfig paths to resolver options
 * @param {string} configDir Config file directory
 * @param {{ [key: string]: string[] }} paths TypeScript paths mapping
 * @param {Resolver} resolver resolver instance
 * @param {string=} baseUrl Base URL for resolving paths (relative to configDir)
 * @returns {TsconfigPathsData} the resolver options
 */
function tsconfigPathsToResolveOptions(configDir, paths, resolver, baseUrl) {
	// Calculate absolute base URL
	const absoluteBaseUrl = !baseUrl
		? configDir
		: resolver.join(configDir, baseUrl);

	/** @type {string[]} */
	const sortedKeys = sortByLongestPrefix(Object.keys(paths));
	/** @type {AliasOption[]} */
	const alias = [];
	/** @type {string[]} */
	const modules = [];

	for (const pattern of sortedKeys) {
		const mappings = paths[pattern];
		// Substitute ${configDir} in path mappings
		const absolutePaths = mappings.map((mapping) => {
			const substituted = substituteConfigDir(mapping, configDir);
			return resolver.join(absoluteBaseUrl, substituted);
		});

		if (absolutePaths.length > 0) {
			if (pattern === "*") {
				// Pull `dir/*` entries directly into `modules` with their
				// trailing wildcard stripped, skipping anything else. The
				// previous `.map(...).filter(Boolean)` form allocated two
				// throwaway arrays plus a spread iterator per `*` mapping.
				for (let j = 0; j < absolutePaths.length; j++) {
					const dir = absolutePaths[j];
					if (WILDCARD_TAIL_RE.test(dir)) {
						modules.push(dir.replace(WILDCARD_TAIL_RE, ""));
					}
				}
			} else {
				alias.push({ name: pattern, alias: absolutePaths });
			}
		}
	}

	if (baseUrl && absoluteBaseUrl && !modules.includes(absoluteBaseUrl)) {
		modules.push(absoluteBaseUrl);
	}

	return {
		alias: compileAliasOptions(resolver, alias),
		modules,
	};
}

/**
 * Get the base context for the current project
 * @param {string} context the context
 * @param {Resolver} resolver resolver instance
 * @param {string=} baseUrl base URL for resolving paths
 * @returns {string} the base context
 */
function getAbsoluteBaseUrl(context, resolver, baseUrl) {
	return !baseUrl ? context : resolver.join(context, baseUrl);
}

/**
 * @param {TsconfigPathsData} main main paths data
 * @param {string} mainContext main context
 * @param {{ [baseUrl: string]: TsconfigPathsData }} refs references map
 * @param {Set<string>} fileDependencies file dependencies
 * @returns {TsconfigPathsMap} the tsconfig paths map
 */
function buildTsconfigPathsMap(main, mainContext, refs, fileDependencies) {
	const allContexts = /** @type {{ [context: string]: TsconfigPathsData }} */ ({
		[mainContext]: main,
		...refs,
	});
	// Precompute the key list once per tsconfig load. `_selectPathsDataForContext`
	// runs per resolve and otherwise would call `Object.entries(allContexts)`
	// each time, allocating a fresh [key, value][] array.
	const contextList = Object.keys(allContexts);
	return {
		main,
		mainContext,
		refs,
		allContexts,
		contextList,
		fileDependencies,
	};
}

module.exports = class TsconfigPathsPlugin {
	/**
	 * @param {true | string | TsconfigOptions} configFileOrOptions tsconfig file path or options object
	 */
	constructor(configFileOrOptions) {
		if (
			typeof configFileOrOptions === "object" &&
			configFileOrOptions !== null
		) {
			// Options object format
			const { configFile } = configFileOrOptions;
			/** @type {boolean} */
			this.isAutoConfigFile = typeof configFile !== "string";
			/** @type {string} */
			this.configFile = this.isAutoConfigFile
				? DEFAULT_CONFIG_FILE
				: /** @type {string} */ (configFile);
			/** @type {string[] | "auto"} */
			if (Array.isArray(configFileOrOptions.references)) {
				/** @type {TsconfigReference[] | "auto"} */
				this.references = configFileOrOptions.references.map((ref) => ({
					path: ref,
				}));
			} else if (configFileOrOptions.references === "auto") {
				this.references = "auto";
			} else {
				this.references = [];
			}
			/** @type {string | undefined} */
			this.baseUrl = configFileOrOptions.baseUrl;
		} else {
			/** @type {boolean} */
			this.isAutoConfigFile = configFileOrOptions === true;
			/** @type {string} */
			this.configFile = this.isAutoConfigFile
				? DEFAULT_CONFIG_FILE
				: /** @type {string} */ (configFileOrOptions);
			/** @type {TsconfigReference[] | "auto"} */
			this.references = [];
			/** @type {string | undefined} */
			this.baseUrl = undefined;
		}
	}

	/**
	 * @param {Resolver} resolver the resolver
	 * @returns {void}
	 */
	apply(resolver) {
		const aliasTarget = resolver.ensureHook("internal-resolve");
		const moduleTarget = resolver.ensureHook("module");

		resolver
			.getHook("raw-resolve")
			.tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => {
				this._getTsconfigPathsMap(
					resolver,
					request,
					resolveContext,
					(err, tsconfigPathsMap) => {
						if (err) return callback(err);
						if (!tsconfigPathsMap) return callback();

						const selectedData = this._selectPathsDataForContext(
							request.path,
							tsconfigPathsMap,
						);

						if (!selectedData) return callback();

						aliasResolveHandler(
							resolver,
							selectedData.alias,
							aliasTarget,
							request,
							resolveContext,
							(err, result) => {
								if (err) return callback(err);
								if (result) return callback(null, result);
								// https://github.com/webpack/webpack/issues/20944
								// Unlike resolve.alias, tsconfig paths should fall through
								// when a pattern matches but the mapped path does not exist
								// (matching TypeScript's native resolution behavior).
								return callback();
							},
						);
					},
				);
			});

		resolver
			.getHook("raw-module")
			.tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => {
				this._getTsconfigPathsMap(
					resolver,
					request,
					resolveContext,
					(err, tsconfigPathsMap) => {
						if (err) return callback(err);
						if (!tsconfigPathsMap) return callback();

						const selectedData = this._selectPathsDataForContext(
							request.path,
							tsconfigPathsMap,
						);

						if (!selectedData) return callback();

						modulesResolveHandler(
							resolver,
							selectedData.modules,
							moduleTarget,
							request,
							resolveContext,
							callback,
						);
					},
				);
			});
	}

	/**
	 * Get TsconfigPathsMap for the request (with caching)
	 * @param {Resolver} resolver the resolver
	 * @param {ResolveRequest} request the request
	 * @param {ResolveContext} resolveContext the resolve context
	 * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback
	 * @returns {void}
	 */
	_getTsconfigPathsMap(resolver, request, resolveContext, callback) {
		if (typeof request.tsconfigPathsMap !== "undefined") {
			const cached = request.tsconfigPathsMap;
			if (!cached) return callback(null, null);
			if (resolveContext.fileDependencies) {
				for (const fileDependency of cached.fileDependencies) {
					resolveContext.fileDependencies.add(fileDependency);
				}
			}
			return callback(null, cached);
		}

		if (this.isAutoConfigFile) {
			this._findTsconfigUpward(
				resolver,
				request.path || process.cwd(),
				(err, result) => {
					if (err) {
						request.tsconfigPathsMap = null;
						return callback(err);
					}
					if (!result) {
						request.tsconfigPathsMap = null;
						return callback(null, null);
					}
					const map = /** @type {TsconfigPathsMap} */ (result);
					request.tsconfigPathsMap = map;
					if (resolveContext.fileDependencies) {
						for (const fileDependency of map.fileDependencies) {
							resolveContext.fileDependencies.add(fileDependency);
						}
					}
					callback(null, map);
				},
			);
			return;
		}

		const absTsconfigPath = resolver.join(
			request.path || process.cwd(),
			this.configFile,
		);
		this._loadTsconfigPathsMap(resolver, absTsconfigPath, (err, result) => {
			if (err) {
				request.tsconfigPathsMap = null;
				return callback(err);
			}

			const map = /** @type {TsconfigPathsMap} */ (result);
			request.tsconfigPathsMap = map;
			if (resolveContext.fileDependencies) {
				for (const fileDependency of map.fileDependencies) {
					resolveContext.fileDependencies.add(fileDependency);
				}
			}
			callback(null, map);
		});
	}

	/**
	 * Walk up from startDir to the filesystem root looking for tsconfig.json.
	 * Like TypeScript's own `findConfigFile` / `forEachAncestorDirectory`.
	 * @param {Resolver} resolver the resolver
	 * @param {string} startDir the directory to start searching from
	 * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback
	 * @returns {void}
	 */
	_findTsconfigUpward(resolver, startDir, callback) {
		const { fileSystem } = resolver;
		const configFileName = this.configFile;

		/**
		 * @param {string} dir current directory
		 * @returns {void}
		 */
		const check = (dir) => {
			const candidate = resolver.join(dir, configFileName);
			fileSystem.stat(candidate, (statErr) => {
				if (!statErr) {
					// Found β€” load it
					this._loadTsconfigPathsMap(resolver, candidate, (loadErr, result) => {
						if (loadErr) {
							// Auto mode: soft-fail silently.
							return callback(null, null);
						}
						callback(null, result);
					});
					return;
				}
				// Not found β€” move to parent
				const parentDir = resolver.dirname(dir);
				if (parentDir === dir) {
					// Reached filesystem root, no tsconfig.json found
					return callback(null, null);
				}
				check(parentDir);
			});
		};

		check(startDir);
	}

	/**
	 * Load tsconfig.json and build complete TsconfigPathsMap
	 * Includes main project paths and all referenced projects
	 * @param {Resolver} resolver the resolver
	 * @param {string} absTsconfigPath absolute path to tsconfig.json
	 * @param {(err: Error | null, result?: TsconfigPathsMap) => void} callback the callback
	 * @returns {void}
	 */
	_loadTsconfigPathsMap(resolver, absTsconfigPath, callback) {
		/** @type {Set<string>} */
		const fileDependencies = new Set();

		this._loadTsconfig(
			resolver,
			absTsconfigPath,
			fileDependencies,
			undefined,
			(err, config) => {
				if (err) return callback(err);

				const cfg = /** @type {Tsconfig} */ (config);
				const compilerOptions = cfg.compilerOptions || {};
				const mainContext = resolver.dirname(absTsconfigPath);

				const baseUrl =
					this.baseUrl !== undefined ? this.baseUrl : compilerOptions.baseUrl;

				const main = tsconfigPathsToResolveOptions(
					mainContext,
					compilerOptions.paths || {},
					resolver,
					baseUrl,
				);
				/** @type {{ [baseUrl: string]: TsconfigPathsData }} */
				const refs = {};

				let referencesToUse = null;
				if (this.references === "auto") {
					referencesToUse = cfg.references;
				} else if (Array.isArray(this.references)) {
					referencesToUse = this.references;
				}

				if (!Array.isArray(referencesToUse)) {
					return callback(
						null,
						buildTsconfigPathsMap(main, mainContext, refs, fileDependencies),
					);
				}

				this._loadTsconfigReferences(
					resolver,
					mainContext,
					referencesToUse,
					fileDependencies,
					refs,
					(refErr) => {
						if (refErr) return callback(refErr);
						callback(
							null,
							buildTsconfigPathsMap(main, mainContext, refs, fileDependencies),
						);
					},
				);
			},
		);
	}

	/**
	 * Select the correct TsconfigPathsData based on request.path (context-aware)
	 * Matches the behavior of tsconfig-paths-webpack-plugin
	 * @param {string | false} requestPath the request path
	 * @param {TsconfigPathsMap} tsconfigPathsMap the tsconfig paths map
	 * @returns {TsconfigPathsData | null} the selected paths data
	 */
	_selectPathsDataForContext(requestPath, tsconfigPathsMap) {
		const { main, allContexts, contextList } = tsconfigPathsMap;
		if (!requestPath) {
			return main;
		}
		// Single-context tsconfigs (no project references) hit the loop
		// below at most once; in that case the cache lookup costs more
		// than the loop itself. Only memoize when there are 2+ contexts
		// β€” that's the monorepo / project-references shape where the
		// scan actually walks multiple entries per resolve and the
		// `(map, requestPath)` answer can be reused.
		/** @type {Map<string, TsconfigPathsData | typeof NULL_CONTEXT> | undefined} */
		let perMap;
		if (contextList.length >= 2) {
			perMap = _contextSelectionCache.get(tsconfigPathsMap);
			if (perMap !== undefined) {
				const cached = perMap.get(requestPath);
				if (cached !== undefined) {
					return cached === NULL_CONTEXT
						? null
						: /** @type {TsconfigPathsData} */ (cached);
				}
			} else {
				perMap = new Map();
				_contextSelectionCache.set(tsconfigPathsMap, perMap);
			}
		}
		let longestMatchContext = null;
		let longestMatchLength = 0;
		// Iterate the pre-computed key list (the previous
		// `Object.entries(allContexts)` form allocated a fresh
		// `[key, value][]` per resolve). Defer the `allContexts[context]`
		// lookup to after we know the context actually matches β€” non-matches
		// are the common case and don't need the property access.
		for (let i = 0; i < contextList.length; i++) {
			const context = contextList[i];
			if (context === requestPath) {
				const exact = allContexts[context];
				if (perMap !== undefined) perMap.set(requestPath, exact);
				return exact;
			}
			// Cheap integer-compare gate first: a context can only beat the
			// current longest match if its own length is strictly greater.
			// Skipping `isSubPath` (a `startsWith` + char-code probe) when the
			// length already disqualifies the candidate avoids the per-resolve
			// scan over every shorter context.
			if (
				context.length > longestMatchLength &&
				isSubPath(context, requestPath)
			) {
				longestMatchContext = context;
				longestMatchLength = context.length;
			}
		}
		const result =
			longestMatchContext === null ? null : allContexts[longestMatchContext];
		if (perMap !== undefined) {
			perMap.set(requestPath, result === null ? NULL_CONTEXT : result);
		}
		return result;
	}

	/**
	 * Load tsconfig from extends path
	 * @param {Resolver} resolver the resolver
	 * @param {string} configFilePath current config file path
	 * @param {string} extendedConfigValue extends value
	 * @param {Set<string>} fileDependencies the file dependencies
	 * @param {Set<string>} visitedConfigPaths config paths being loaded (for circular extends detection)
	 * @param {(err: Error | null, result?: Tsconfig) => void} callback callback
	 * @returns {void}
	 */
	_loadTsconfigFromExtends(
		resolver,
		configFilePath,
		extendedConfigValue,
		fileDependencies,
		visitedConfigPaths,
		callback,
	) {
		const { fileSystem } = resolver;
		const currentDir = resolver.dirname(configFilePath);

		// Substitute ${configDir} in extends path
		extendedConfigValue = substituteConfigDir(extendedConfigValue, currentDir);

		// Remember the original value before potentially appending .json
		const originalExtendedConfigValue = extendedConfigValue;

		if (
			typeof extendedConfigValue === "string" &&
			!extendedConfigValue.includes(".json")
		) {
			extendedConfigValue += ".json";
		}

		const initialExtendedConfigPath = resolver.join(
			currentDir,
			extendedConfigValue,
		);

		/**
		 * @param {string} extendedConfigPath resolved config path to load
		 */
		const loadExtended = (extendedConfigPath) => {
			this._loadTsconfig(
				resolver,
				extendedConfigPath,
				fileDependencies,
				visitedConfigPaths,
				(err, config) => {
					if (err) return callback(err);

					const cfg = /** @type {Tsconfig} */ (config);
					const compilerOptions = cfg.compilerOptions || {
						baseUrl: undefined,
					};

					if (compilerOptions.baseUrl) {
						const extendedConfigDir = resolver.dirname(extendedConfigPath);
						compilerOptions.baseUrl = getAbsoluteBaseUrl(
							extendedConfigDir,
							resolver,
							compilerOptions.baseUrl,
						);
					}

					delete cfg.references;

					callback(null, cfg);
				},
			);
		};

		fileSystem.stat(initialExtendedConfigPath, (existsErr) => {
			if (!existsErr) return loadExtended(initialExtendedConfigPath);

			// The relative form does not exist β€” treat the value as a package
			// specifier and compute its `node_modules/<...>` sub-path.
			let nodeModulesSubPath = null;
			if (
				typeof originalExtendedConfigValue === "string" &&
				originalExtendedConfigValue.startsWith("@") &&
				originalExtendedConfigValue.split("/").length === 2
			) {
				// Scoped package, no sub-path ("@scope/name") β†’
				// node_modules/@scope/name/tsconfig.json (not @scope/name.json).
				// See: test/fixtures/tsconfig-paths/extends-pkg-entry/
				nodeModulesSubPath = `${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`;
			} else if (
				extendedConfigValue.includes("/") &&
				!originalExtendedConfigValue.startsWith(".") &&
				!originalExtendedConfigValue.startsWith("/")
			) {
				// Package sub-path ("react/tsconfig", "@scope/name/tsconfig") β†’
				// node_modules/react/tsconfig.json.
				// See: test/fixtures/tsconfig-paths/extends-npm/
				nodeModulesSubPath = extendedConfigValue;
			} else if (
				!originalExtendedConfigValue.startsWith(".") &&
				!originalExtendedConfigValue.startsWith("/")
			) {
				// Unscoped package, no sub-path ("my-base-config") β†’
				// node_modules/my-base-config/tsconfig.json.
				nodeModulesSubPath = `${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`;
			}

			// Not a package specifier (relative/absolute) β€” load the missing
			// path anyway so the read surfaces its own ENOENT.
			if (nodeModulesSubPath === null) {
				return loadExtended(initialExtendedConfigPath);
			}

			// Walk ancestor node_modules like Node.js/TypeScript so a package
			// hoisted to a parent workspace directory is found. #21457
			const subPath = normalize(`node_modules/${nodeModulesSubPath}`);
			this._findExtendsInNodeModules(resolver, currentDir, subPath, (found) => {
				loadExtended(found || resolver.join(currentDir, subPath));
			});
		});
	}

	/**
	 * Walk up from startDir looking for `<dir>/<subPath>` (a
	 * `node_modules/...` sub-path), matching Node.js module resolution so a
	 * package hoisted to a parent workspace's node_modules is found.
	 * @param {Resolver} resolver the resolver
	 * @param {string} startDir directory to start searching from
	 * @param {string} subPath node_modules-relative sub-path to look for
	 * @param {(found: string | null) => void} callback receives the found path or null
	 * @returns {void}
	 */
	_findExtendsInNodeModules(resolver, startDir, subPath, callback) {
		const { fileSystem } = resolver;

		/**
		 * @param {string} dir current directory
		 */
		const check = (dir) => {
			const candidate = resolver.join(dir, subPath);
			fileSystem.stat(candidate, (statErr) => {
				if (!statErr) return callback(candidate);
				const parentDir = resolver.dirname(dir);
				if (parentDir === dir) return callback(null);
				check(parentDir);
			});
		};

		check(startDir);
	}

	/**
	 * Load referenced tsconfig projects and store in referenceMatchMap
	 * Simple implementation matching tsconfig-paths-webpack-plugin:
	 * Just load each reference and store independently
	 * @param {Resolver} resolver the resolver
	 * @param {string} context the context
	 * @param {TsconfigReference[]} references array of references
	 * @param {Set<string>} fileDependencies the file dependencies
	 * @param {{ [baseUrl: string]: TsconfigPathsData }} referenceMatchMap the map to populate
	 * @param {(err: Error | null) => void} callback callback
	 * @param {Set<string>=} visitedRefPaths visited reference config paths (for circular reference detection)
	 * @returns {void}
	 */
	_loadTsconfigReferences(
		resolver,
		context,
		references,
		fileDependencies,
		referenceMatchMap,
		callback,
		visitedRefPaths,
	) {
		if (references.length === 0) return callback(null);

		const visited = visitedRefPaths || new Set();
		let pending = references.length;
		const finishOne = () => {
			if (--pending === 0) callback(null);
		};

		for (const ref of references) {
			const refPath = substituteConfigDir(ref.path, context);
			const refConfigPath = resolver.join(
				resolver.join(context, refPath),
				DEFAULT_CONFIG_FILE,
			);

			if (visited.has(refConfigPath)) {
				finishOne();
				continue;
			}
			visited.add(refConfigPath);

			this._loadTsconfig(
				resolver,
				refConfigPath,
				fileDependencies,
				undefined,
				(err, refConfig) => {
					// Failures are swallowed to match tsconfig-paths-webpack-plugin:
					// a broken reference must not abort the main project's resolution.
					if (err) return finishOne();

					const cfg = /** @type {Tsconfig} */ (refConfig);
					if (cfg.compilerOptions && cfg.compilerOptions.paths) {
						const refContext = resolver.dirname(refConfigPath);

						referenceMatchMap[refContext] = tsconfigPathsToResolveOptions(
							refContext,
							cfg.compilerOptions.paths || {},
							resolver,
							cfg.compilerOptions.baseUrl,
						);
					}

					if (this.references === "auto" && Array.isArray(cfg.references)) {
						this._loadTsconfigReferences(
							resolver,
							resolver.dirname(refConfigPath),
							cfg.references,
							fileDependencies,
							referenceMatchMap,
							finishOne,
							visited,
						);
					} else {
						finishOne();
					}
				},
			);
		}
	}

	/**
	 * Load tsconfig.json with extends support
	 * @param {Resolver} resolver the resolver
	 * @param {string} configFilePath absolute path to tsconfig.json
	 * @param {Set<string>} fileDependencies the file dependencies
	 * @param {Set<string> | undefined} visitedConfigPaths config paths being loaded (for circular extends detection)
	 * @param {(err: Error | null, result?: Tsconfig) => void} callback callback
	 * @returns {void}
	 */
	_loadTsconfig(
		resolver,
		configFilePath,
		fileDependencies,
		visitedConfigPaths,
		callback,
	) {
		const visited = visitedConfigPaths || new Set();

		if (visited.has(configFilePath)) {
			return callback(null, /** @type {Tsconfig} */ ({}));
		}
		visited.add(configFilePath);

		readJson(
			resolver.fileSystem,
			configFilePath,
			READ_JSON_OPTIONS,
			(err, parsed) => {
				if (err) return callback(/** @type {Error} */ (err));

				const config = /** @type {Tsconfig} */ (parsed);
				fileDependencies.add(configFilePath);

				const extendedConfig = config.extends;
				if (!extendedConfig) return callback(null, config);

				if (!Array.isArray(extendedConfig)) {
					this._loadTsconfigFromExtends(
						resolver,
						configFilePath,
						extendedConfig,
						fileDependencies,
						visited,
						(extErr, extendedTsconfig) => {
							if (extErr) return callback(extErr);
							callback(
								null,
								mergeTsconfigs(
									/** @type {Tsconfig} */ (extendedTsconfig),
									config,
								),
							);
						},
					);
					return;
				}

				/** @type {Tsconfig} */
				let base = {};
				let i = 0;
				const next = () => {
					if (i >= extendedConfig.length) {
						return callback(null, mergeTsconfigs(base, config));
					}
					this._loadTsconfigFromExtends(
						resolver,
						configFilePath,
						extendedConfig[i++],
						fileDependencies,
						visited,
						(extErr, extendedTsconfig) => {
							if (extErr) return callback(extErr);
							base = mergeTsconfigs(
								base,
								/** @type {Tsconfig} */ (extendedTsconfig),
							);
							next();
						},
					);
				};
				next();
			},
		);
	}
};