-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
resolver.ts
885 lines (776 loc) · 25.8 KB
/
resolver.ts
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
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable local/prefer-spread-eventually */
import * as path from 'path';
import chalk = require('chalk');
import slash = require('slash');
import type {IModuleMap} from 'jest-haste-map';
import {tryRealpath} from 'jest-util';
import ModuleNotFoundError from './ModuleNotFoundError';
import defaultResolver, {
AsyncResolver,
Resolver as ResolverInterface,
SyncResolver,
} from './defaultResolver';
import {clearFsCache} from './fileWalkers';
import isBuiltinModule from './isBuiltinModule';
import nodeModulesPaths from './nodeModulesPaths';
import shouldLoadAsEsm, {clearCachedLookups} from './shouldLoadAsEsm';
import type {ResolverConfig} from './types';
export type FindNodeModuleConfig = {
basedir: string;
conditions?: Array<string>;
extensions?: Array<string>;
moduleDirectory?: Array<string>;
paths?: Array<string>;
resolver?: string | null;
rootDir?: string;
throwIfNotFound?: boolean;
};
export type ResolveModuleConfig = {
conditions?: Array<string>;
skipNodeResolution?: boolean;
paths?: Array<string>;
};
const NATIVE_PLATFORM = 'native';
// We might be inside a symlink.
const resolvedCwd = tryRealpath(process.cwd());
const {NODE_PATH} = process.env;
const nodePaths = NODE_PATH
? NODE_PATH.split(path.delimiter)
.filter(Boolean)
// The resolver expects absolute paths.
.map(p => path.resolve(resolvedCwd, p))
: undefined;
export default class Resolver {
private readonly _options: ResolverConfig;
private readonly _moduleMap: IModuleMap;
private readonly _moduleIDCache: Map<string, string>;
private readonly _moduleNameCache: Map<string, string>;
private readonly _modulePathCache: Map<string, Array<string>>;
private readonly _supportsNativePlatform: boolean;
constructor(moduleMap: IModuleMap, options: ResolverConfig) {
this._options = {
defaultPlatform: options.defaultPlatform,
extensions: options.extensions,
hasCoreModules:
options.hasCoreModules === undefined ? true : options.hasCoreModules,
moduleDirectories: options.moduleDirectories || ['node_modules'],
moduleNameMapper: options.moduleNameMapper,
modulePaths: options.modulePaths,
platforms: options.platforms,
resolver: options.resolver,
rootDir: options.rootDir,
};
this._supportsNativePlatform = options.platforms
? options.platforms.includes(NATIVE_PLATFORM)
: false;
this._moduleMap = moduleMap;
this._moduleIDCache = new Map();
this._moduleNameCache = new Map();
this._modulePathCache = new Map();
}
static ModuleNotFoundError = ModuleNotFoundError;
static tryCastModuleNotFoundError(
error: unknown,
): ModuleNotFoundError | null {
if (error instanceof ModuleNotFoundError) {
return error;
}
const casted = error as ModuleNotFoundError;
if (casted.code === 'MODULE_NOT_FOUND') {
return ModuleNotFoundError.duckType(casted);
}
return null;
}
static clearDefaultResolverCache(): void {
clearFsCache();
clearCachedLookups();
}
static findNodeModule(
path: string,
options: FindNodeModuleConfig,
): string | null {
const resolverModule = loadResolver(options.resolver);
let resolver: SyncResolver = defaultResolver;
if (typeof resolverModule === 'function') {
resolver = resolverModule;
} else if (typeof resolverModule.sync === 'function') {
resolver = resolverModule.sync;
}
const paths = options.paths;
try {
return resolver(path, {
basedir: options.basedir,
conditions: options.conditions,
defaultResolver,
extensions: options.extensions,
moduleDirectory: options.moduleDirectory,
paths: paths ? (nodePaths || []).concat(paths) : nodePaths,
rootDir: options.rootDir,
});
} catch (e) {
if (options.throwIfNotFound) {
throw e;
}
}
return null;
}
static async findNodeModuleAsync(
path: string,
options: FindNodeModuleConfig,
): Promise<string | null> {
const resolverModule = loadResolver(options.resolver);
let resolver: ResolverInterface = defaultResolver;
if (typeof resolverModule === 'function') {
resolver = resolverModule;
} else if (
typeof resolverModule.async === 'function' ||
typeof resolverModule.sync === 'function'
) {
const asyncOrSync = resolverModule.async || resolverModule.sync;
if (asyncOrSync == null) {
throw new Error(`Unable to load resolver at ${options.resolver}`);
}
resolver = asyncOrSync;
}
const paths = options.paths;
try {
const result = await resolver(path, {
basedir: options.basedir,
conditions: options.conditions,
defaultResolver,
extensions: options.extensions,
moduleDirectory: options.moduleDirectory,
paths: paths ? (nodePaths || []).concat(paths) : nodePaths,
rootDir: options.rootDir,
});
return result;
} catch (e: unknown) {
if (options.throwIfNotFound) {
throw e;
}
}
return null;
}
// unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it
static unstable_shouldLoadAsEsm = shouldLoadAsEsm;
resolveModuleFromDirIfExists(
dirname: string,
moduleName: string,
options?: ResolveModuleConfig,
): string | null {
const {extensions, key, moduleDirectory, paths, skipResolution} =
this._prepareForResolution(dirname, moduleName, options);
let module;
// 1. If we have already resolved this module for this directory name,
// return a value from the cache.
const cacheResult = this._moduleNameCache.get(key);
if (cacheResult) {
return cacheResult;
}
// 2. Check if the module is a haste module.
module = this.getModule(moduleName);
if (module) {
this._moduleNameCache.set(key, module);
return module;
}
// 3. Check if the module is a node module and resolve it based on
// the node module resolution algorithm. If skipNodeResolution is given we
// ignore all modules that look like node modules (ie. are not relative
// requires). This enables us to speed up resolution when we build a
// dependency graph because we don't have to look at modules that may not
// exist and aren't mocked.
const resolveNodeModule = (name: string, throwIfNotFound = false) => {
// Only skip default resolver
if (this.isCoreModule(name) && !this._options.resolver) {
return name;
}
return Resolver.findNodeModule(name, {
basedir: dirname,
conditions: options?.conditions,
extensions,
moduleDirectory,
paths,
resolver: this._options.resolver,
rootDir: this._options.rootDir,
throwIfNotFound,
});
};
if (!skipResolution) {
module = resolveNodeModule(moduleName, Boolean(process.versions.pnp));
if (module) {
this._moduleNameCache.set(key, module);
return module;
}
}
// 4. Resolve "haste packages" which are `package.json` files outside of
// `node_modules` folders anywhere in the file system.
try {
const hasteModulePath = this._getHasteModulePath(moduleName);
if (hasteModulePath) {
// try resolving with custom resolver first to support extensions,
// then fallback to require.resolve
const resolvedModule =
resolveNodeModule(hasteModulePath) ||
require.resolve(hasteModulePath);
this._moduleNameCache.set(key, resolvedModule);
return resolvedModule;
}
} catch {}
return null;
}
async resolveModuleFromDirIfExistsAsync(
dirname: string,
moduleName: string,
options?: ResolveModuleConfig,
): Promise<string | null> {
const {extensions, key, moduleDirectory, paths, skipResolution} =
this._prepareForResolution(dirname, moduleName, options);
let module;
// 1. If we have already resolved this module for this directory name,
// return a value from the cache.
const cacheResult = this._moduleNameCache.get(key);
if (cacheResult) {
return cacheResult;
}
// 2. Check if the module is a haste module.
module = this.getModule(moduleName);
if (module) {
this._moduleNameCache.set(key, module);
return module;
}
// 3. Check if the module is a node module and resolve it based on
// the node module resolution algorithm. If skipNodeResolution is given we
// ignore all modules that look like node modules (ie. are not relative
// requires). This enables us to speed up resolution when we build a
// dependency graph because we don't have to look at modules that may not
// exist and aren't mocked.
const resolveNodeModule = async (name: string, throwIfNotFound = false) => {
// Only skip default resolver
if (this.isCoreModule(name) && !this._options.resolver) {
return name;
}
return Resolver.findNodeModuleAsync(name, {
basedir: dirname,
conditions: options?.conditions,
extensions,
moduleDirectory,
paths,
resolver: this._options.resolver,
rootDir: this._options.rootDir,
throwIfNotFound,
});
};
if (!skipResolution) {
module = await resolveNodeModule(
moduleName,
Boolean(process.versions.pnp),
);
if (module) {
this._moduleNameCache.set(key, module);
return module;
}
}
// 4. Resolve "haste packages" which are `package.json` files outside of
// `node_modules` folders anywhere in the file system.
try {
const hasteModulePath = this._getHasteModulePath(moduleName);
if (hasteModulePath) {
// try resolving with custom resolver first to support extensions,
// then fallback to require.resolve
const resolvedModule =
(await resolveNodeModule(hasteModulePath)) ||
// QUESTION: should this be async?
require.resolve(hasteModulePath);
this._moduleNameCache.set(key, resolvedModule);
return resolvedModule;
}
} catch {}
return null;
}
resolveModule(
from: string,
moduleName: string,
options?: ResolveModuleConfig,
): string {
const dirname = path.dirname(from);
const module =
this.resolveStubModuleName(from, moduleName) ||
this.resolveModuleFromDirIfExists(dirname, moduleName, options);
if (module) return module;
// 5. Throw an error if the module could not be found. `resolve.sync` only
// produces an error based on the dirname but we have the actual current
// module name available.
this._throwModNotFoundError(from, moduleName);
}
async resolveModuleAsync(
from: string,
moduleName: string,
options?: ResolveModuleConfig,
): Promise<string> {
const dirname = path.dirname(from);
const module =
(await this.resolveStubModuleNameAsync(from, moduleName)) ||
(await this.resolveModuleFromDirIfExistsAsync(
dirname,
moduleName,
options,
));
if (module) return module;
// 5. Throw an error if the module could not be found. `resolve` only
// produces an error based on the dirname but we have the actual current
// module name available.
this._throwModNotFoundError(from, moduleName);
}
/**
* _prepareForResolution is shared between the sync and async module resolution
* methods, to try to keep them as DRY as possible.
*/
private _prepareForResolution(
dirname: string,
moduleName: string,
options?: ResolveModuleConfig,
) {
const paths = options?.paths || this._options.modulePaths;
const moduleDirectory = this._options.moduleDirectories;
const stringifiedOptions = options ? JSON.stringify(options) : '';
const key = dirname + path.delimiter + moduleName + stringifiedOptions;
const defaultPlatform = this._options.defaultPlatform;
const extensions = this._options.extensions.slice();
if (this._supportsNativePlatform) {
extensions.unshift(
...this._options.extensions.map(ext => `.${NATIVE_PLATFORM}${ext}`),
);
}
if (defaultPlatform) {
extensions.unshift(
...this._options.extensions.map(ext => `.${defaultPlatform}${ext}`),
);
}
const skipResolution =
options && options.skipNodeResolution && !moduleName.includes(path.sep);
return {extensions, key, moduleDirectory, paths, skipResolution};
}
/**
* _getHasteModulePath attempts to return the path to a haste module.
*/
private _getHasteModulePath(moduleName: string) {
const parts = moduleName.split('/');
const hastePackage = this.getPackage(parts.shift()!);
if (hastePackage) {
return path.join.apply(path, [path.dirname(hastePackage)].concat(parts));
}
return null;
}
private _throwModNotFoundError(from: string, moduleName: string): never {
const relativePath =
slash(path.relative(this._options.rootDir, from)) || '.';
throw new ModuleNotFoundError(
`Cannot find module '${moduleName}' from '${relativePath}'`,
moduleName,
);
}
private _getMapModuleName(matches: RegExpMatchArray | null) {
return matches
? (moduleName: string) =>
moduleName.replace(
/\$([0-9]+)/g,
(_, index) => matches[parseInt(index, 10)],
)
: (moduleName: string) => moduleName;
}
private _isAliasModule(moduleName: string): boolean {
const moduleNameMapper = this._options.moduleNameMapper;
if (!moduleNameMapper) {
return false;
}
return moduleNameMapper.some(({regex}) => regex.test(moduleName));
}
isCoreModule(moduleName: string): boolean {
return (
this._options.hasCoreModules &&
(isBuiltinModule(moduleName) ||
(moduleName.startsWith('node:') &&
isBuiltinModule(moduleName.slice('node:'.length)))) &&
!this._isAliasModule(moduleName)
);
}
getModule(name: string): string | null {
return this._moduleMap.getModule(
name,
this._options.defaultPlatform,
this._supportsNativePlatform,
);
}
getModulePath(from: string, moduleName: string): string {
if (moduleName[0] !== '.' || path.isAbsolute(moduleName)) {
return moduleName;
}
return path.normalize(`${path.dirname(from)}/${moduleName}`);
}
getPackage(name: string): string | null {
return this._moduleMap.getPackage(
name,
this._options.defaultPlatform,
this._supportsNativePlatform,
);
}
getMockModule(from: string, name: string): string | null {
const mock = this._moduleMap.getMockModule(name);
if (mock) {
return mock;
} else {
const moduleName = this.resolveStubModuleName(from, name);
if (moduleName) {
return this.getModule(moduleName) || moduleName;
}
}
return null;
}
async getMockModuleAsync(from: string, name: string): Promise<string | null> {
const mock = this._moduleMap.getMockModule(name);
if (mock) {
return mock;
} else {
const moduleName = await this.resolveStubModuleNameAsync(from, name);
if (moduleName) {
return this.getModule(moduleName) || moduleName;
}
}
return null;
}
getModulePaths(from: string): Array<string> {
const cachedModule = this._modulePathCache.get(from);
if (cachedModule) {
return cachedModule;
}
const moduleDirectory = this._options.moduleDirectories;
const paths = nodeModulesPaths(from, {moduleDirectory});
if (paths[paths.length - 1] === undefined) {
// circumvent node-resolve bug that adds `undefined` as last item.
paths.pop();
}
this._modulePathCache.set(from, paths);
return paths;
}
getModuleID(
virtualMocks: Map<string, boolean>,
from: string,
moduleName = '',
options?: ResolveModuleConfig,
): string {
const stringifiedOptions = options ? JSON.stringify(options) : '';
const key = from + path.delimiter + moduleName + stringifiedOptions;
const cachedModuleID = this._moduleIDCache.get(key);
if (cachedModuleID) {
return cachedModuleID;
}
const moduleType = this._getModuleType(moduleName);
const absolutePath = this._getAbsolutePath(
virtualMocks,
from,
moduleName,
options,
);
const mockPath = this._getMockPath(from, moduleName);
const sep = path.delimiter;
const id =
moduleType +
sep +
(absolutePath ? absolutePath + sep : '') +
(mockPath ? mockPath + sep : '') +
(stringifiedOptions ? stringifiedOptions + sep : '');
this._moduleIDCache.set(key, id);
return id;
}
async getModuleIDAsync(
virtualMocks: Map<string, boolean>,
from: string,
moduleName = '',
options?: ResolveModuleConfig,
): Promise<string> {
const stringifiedOptions = options ? JSON.stringify(options) : '';
const key = from + path.delimiter + moduleName + stringifiedOptions;
const cachedModuleID = this._moduleIDCache.get(key);
if (cachedModuleID) {
return cachedModuleID;
}
if (moduleName.startsWith('data:')) {
return moduleName;
}
const moduleType = this._getModuleType(moduleName);
const absolutePath = await this._getAbsolutePathAsync(
virtualMocks,
from,
moduleName,
options,
);
const mockPath = await this._getMockPathAsync(from, moduleName);
const sep = path.delimiter;
const id =
moduleType +
sep +
(absolutePath ? absolutePath + sep : '') +
(mockPath ? mockPath + sep : '') +
(stringifiedOptions ? stringifiedOptions + sep : '');
this._moduleIDCache.set(key, id);
return id;
}
private _getModuleType(moduleName: string): 'node' | 'user' {
return this.isCoreModule(moduleName) ? 'node' : 'user';
}
private _getAbsolutePath(
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
): string | null {
if (this.isCoreModule(moduleName)) {
return moduleName;
}
if (moduleName.startsWith('data:')) {
return moduleName;
}
return this._isModuleResolved(from, moduleName)
? this.getModule(moduleName)
: this._getVirtualMockPath(virtualMocks, from, moduleName, options);
}
private async _getAbsolutePathAsync(
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
): Promise<string | null> {
if (this.isCoreModule(moduleName)) {
return moduleName;
}
if (moduleName.startsWith('data:')) {
return moduleName;
}
const isModuleResolved = await this._isModuleResolvedAsync(
from,
moduleName,
);
return isModuleResolved
? this.getModule(moduleName)
: this._getVirtualMockPathAsync(virtualMocks, from, moduleName, options);
}
private _getMockPath(from: string, moduleName: string): string | null {
return !this.isCoreModule(moduleName)
? this.getMockModule(from, moduleName)
: null;
}
private async _getMockPathAsync(
from: string,
moduleName: string,
): Promise<string | null> {
return !this.isCoreModule(moduleName)
? this.getMockModuleAsync(from, moduleName)
: null;
}
private _getVirtualMockPath(
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
): string {
const virtualMockPath = this.getModulePath(from, moduleName);
return virtualMocks.get(virtualMockPath)
? virtualMockPath
: moduleName
? this.resolveModule(from, moduleName, options)
: from;
}
private async _getVirtualMockPathAsync(
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
): Promise<string> {
const virtualMockPath = this.getModulePath(from, moduleName);
return virtualMocks.get(virtualMockPath)
? virtualMockPath
: moduleName
? this.resolveModuleAsync(from, moduleName, options)
: from;
}
private _isModuleResolved(from: string, moduleName: string): boolean {
return !!(
this.getModule(moduleName) || this.getMockModule(from, moduleName)
);
}
private async _isModuleResolvedAsync(
from: string,
moduleName: string,
): Promise<boolean> {
return !!(
this.getModule(moduleName) ||
(await this.getMockModuleAsync(from, moduleName))
);
}
resolveStubModuleName(from: string, moduleName: string): string | null {
const dirname = path.dirname(from);
const {extensions, moduleDirectory, paths} = this._prepareForResolution(
dirname,
moduleName,
);
const moduleNameMapper = this._options.moduleNameMapper;
const resolver = this._options.resolver;
if (moduleNameMapper) {
for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) {
if (regex.test(moduleName)) {
// Note: once a moduleNameMapper matches the name, it must result
// in a module, or else an error is thrown.
const matches = moduleName.match(regex);
const mapModuleName = this._getMapModuleName(matches);
const possibleModuleNames = Array.isArray(mappedModuleName)
? mappedModuleName
: [mappedModuleName];
let module: string | null = null;
for (const possibleModuleName of possibleModuleNames) {
const updatedName = mapModuleName(possibleModuleName);
module =
this.getModule(updatedName) ||
Resolver.findNodeModule(updatedName, {
basedir: dirname,
extensions,
moduleDirectory,
paths,
resolver,
rootDir: this._options.rootDir,
});
if (module) {
break;
}
}
if (!module) {
throw createNoMappedModuleFoundError(
moduleName,
mapModuleName,
mappedModuleName,
regex,
resolver,
);
}
return module;
}
}
}
return null;
}
async resolveStubModuleNameAsync(
from: string,
moduleName: string,
): Promise<string | null> {
const dirname = path.dirname(from);
const {extensions, moduleDirectory, paths} = this._prepareForResolution(
dirname,
moduleName,
);
const moduleNameMapper = this._options.moduleNameMapper;
const resolver = this._options.resolver;
if (moduleNameMapper) {
for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) {
if (regex.test(moduleName)) {
// Note: once a moduleNameMapper matches the name, it must result
// in a module, or else an error is thrown.
const matches = moduleName.match(regex);
const mapModuleName = this._getMapModuleName(matches);
const possibleModuleNames = Array.isArray(mappedModuleName)
? mappedModuleName
: [mappedModuleName];
let module: string | null = null;
for (const possibleModuleName of possibleModuleNames) {
const updatedName = mapModuleName(possibleModuleName);
module =
this.getModule(updatedName) ||
(await Resolver.findNodeModuleAsync(updatedName, {
basedir: dirname,
extensions,
moduleDirectory,
paths,
resolver,
rootDir: this._options.rootDir,
}));
if (module) {
break;
}
}
if (!module) {
throw createNoMappedModuleFoundError(
moduleName,
mapModuleName,
mappedModuleName,
regex,
resolver,
);
}
return module;
}
}
}
return null;
}
}
const createNoMappedModuleFoundError = (
moduleName: string,
mapModuleName: (moduleName: string) => string,
mappedModuleName: string | Array<string>,
regex: RegExp,
resolver?: ((...args: Array<unknown>) => unknown) | string | null,
) => {
const mappedAs = Array.isArray(mappedModuleName)
? JSON.stringify(mappedModuleName.map(mapModuleName), null, 2)
: mappedModuleName;
const original = Array.isArray(mappedModuleName)
? `${
JSON.stringify(mappedModuleName, null, 6) // using 6 because of misalignment when nested below
.slice(0, -1) + ' '.repeat(4)
}]` /// align last bracket correctly as well
: mappedModuleName;
const error = new Error(
chalk.red(`${chalk.bold('Configuration error')}:
Could not locate module ${chalk.bold(moduleName)} mapped as:
${chalk.bold(mappedAs)}.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"${regex.toString()}": "${chalk.bold(original)}"
},
"resolver": ${chalk.bold(String(resolver))}
}`),
);
error.name = '';
return error;
};
type ResolverSyncObject = {sync: SyncResolver; async?: AsyncResolver};
type ResolverAsyncObject = {sync?: SyncResolver; async: AsyncResolver};
export type ResolverObject = ResolverSyncObject | ResolverAsyncObject;
function loadResolver(
resolver: string | undefined | null,
): SyncResolver | ResolverObject {
if (resolver == null) {
return defaultResolver;
}
const loadedResolver = require(resolver);
if (loadedResolver == null) {
throw new Error(`Resolver located at ${resolver} does not export anything`);
}
if (typeof loadedResolver === 'function') {
return loadedResolver as SyncResolver;
}
if (
typeof loadedResolver === 'object' &&
(loadedResolver.sync != null || loadedResolver.async != null)
) {
return loadedResolver as ResolverObject;
}
throw new Error(
`Resolver located at ${resolver} does not export a function or an object with "sync" and "async" props`,
);
}