-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
index.ts
2591 lines (2257 loc) · 78.5 KB
/
index.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
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import nativeModule = require('module');
import * as path from 'path';
import {URL, fileURLToPath, pathToFileURL} from 'url';
import {
Script,
// @ts-expect-error: experimental, not added to the types
SourceTextModule,
// @ts-expect-error: experimental, not added to the types
SyntheticModule,
type Context as VMContext,
// @ts-expect-error: experimental, not added to the types
type Module as VMModule,
} from 'vm';
import {parse as parseCjs} from 'cjs-module-lexer';
import {CoverageInstrumenter, type V8Coverage} from 'collect-v8-coverage';
import * as fs from 'graceful-fs';
import slash = require('slash');
import stripBOM = require('strip-bom');
import type {
Jest,
JestEnvironment,
JestImportMeta,
Module,
ModuleWrapper,
} from '@jest/environment';
import type {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
import type {expect, jest} from '@jest/globals';
import type {SourceMapRegistry} from '@jest/source-map';
import type {
RuntimeTransformResult,
TestContext,
V8CoverageResult,
} from '@jest/test-result';
import {
type CallerTransformOptions,
type ScriptTransformer,
type ShouldInstrumentOptions,
type TransformationOptions,
handlePotentialSyntaxError,
shouldInstrument,
} from '@jest/transform';
import type {Config, Global} from '@jest/types';
import HasteMap, {type IHasteMap, type IModuleMap} from 'jest-haste-map';
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
import type {MockMetadata, ModuleMocker} from 'jest-mock';
import {escapePathForRegex} from 'jest-regex-util';
import Resolver, {type ResolveModuleConfig} from 'jest-resolve';
import {EXTENSION as SnapshotExtension} from 'jest-snapshot';
import {
createDirectory,
deepCyclicCopy,
invariant,
isNonNullable,
} from 'jest-util';
import {
createOutsideJestVmPath,
decodePossibleOutsideJestVmPath,
findSiblingsWithFileExtension,
} from './helpers';
const esmIsAvailable = typeof SourceTextModule === 'function';
const dataURIRegex =
/^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
interface JestGlobals extends Global.TestFrameworkGlobals {
expect: typeof expect;
}
interface JestGlobalsWithJest extends JestGlobals {
jest: typeof jest;
}
type HasteMapOptions = {
console?: Console;
maxWorkers: number;
resetCache: boolean;
watch?: boolean;
watchman: boolean;
workerThreads?: boolean;
};
interface InternalModuleOptions extends Required<CallerTransformOptions> {
isInternalModule: boolean;
}
const defaultTransformOptions: InternalModuleOptions = {
isInternalModule: false,
supportsDynamicImport: esmIsAvailable,
supportsExportNamespaceFrom: false,
supportsStaticESM: false,
supportsTopLevelAwait: false,
};
type InitialModule = Omit<Module, 'require' | 'parent' | 'paths'>;
type ModuleRegistry = Map<string, InitialModule | Module>;
// These are modules that we know
// * are safe to require from the outside (not stateful, not prone to errors passing in instances from different realms), and
// * take sufficiently long to require to warrant an optimization.
// When required from the outside, they use the worker's require cache and are thus
// only loaded once per worker, not once per test file.
// Use /benchmarks/test-file-overhead to measure the impact.
// Note that this only applies when they are required in an internal context;
// users who require one of these modules in their tests will still get the module from inside the VM.
// Prefer listing a module here only if it is impractical to use the jest-resolve-outside-vm-option where it is required,
// e.g. because there are many require sites spread across the dependency graph.
const INTERNAL_MODULE_REQUIRE_OUTSIDE_OPTIMIZED_MODULES = new Set(['chalk']);
const JEST_RESOLVE_OUTSIDE_VM_OPTION = Symbol.for(
'jest-resolve-outside-vm-option',
);
type ResolveOptions = Parameters<typeof require.resolve>[1] & {
[JEST_RESOLVE_OUTSIDE_VM_OPTION]?: true;
};
const testTimeoutSymbol = Symbol.for('TEST_TIMEOUT_SYMBOL');
const retryTimesSymbol = Symbol.for('RETRY_TIMES');
const waitBeforeRetrySymbol = Symbol.for('WAIT_BEFORE_RETRY');
const retryImmediatelySybmbol = Symbol.for('RETRY_IMMEDIATELY');
const logErrorsBeforeRetrySymbol = Symbol.for('LOG_ERRORS_BEFORE_RETRY');
const NODE_MODULES = `${path.sep}node_modules${path.sep}`;
const getModuleNameMapper = (config: Config.ProjectConfig) => {
if (
Array.isArray(config.moduleNameMapper) &&
config.moduleNameMapper.length > 0
) {
return config.moduleNameMapper.map(([regex, moduleName]) => ({
moduleName,
regex: new RegExp(regex),
}));
}
return null;
};
const isWasm = (modulePath: string): boolean => modulePath.endsWith('.wasm');
const unmockRegExpCache = new WeakMap();
const EVAL_RESULT_VARIABLE = 'Object.<anonymous>';
type RunScriptEvalResult = {[EVAL_RESULT_VARIABLE]: ModuleWrapper};
const runtimeSupportsVmModules = typeof SyntheticModule === 'function';
const supportsNodeColonModulePrefixInRequire = (() => {
try {
require('node:fs');
return true;
} catch {
return false;
}
})();
export default class Runtime {
private readonly _cacheFS: Map<string, string>;
private readonly _cacheFSBuffer = new Map<string, Buffer>();
private readonly _config: Config.ProjectConfig;
private readonly _globalConfig: Config.GlobalConfig;
private readonly _coverageOptions: ShouldInstrumentOptions;
private _currentlyExecutingModulePath: string;
private readonly _environment: JestEnvironment;
private readonly _explicitShouldMock: Map<string, boolean>;
private readonly _explicitShouldMockModule: Map<string, boolean>;
private _fakeTimersImplementation:
| LegacyFakeTimers<unknown>
| ModernFakeTimers
| null;
private readonly _internalModuleRegistry: ModuleRegistry;
private _isCurrentlyExecutingManualMock: string | null;
private _mainModule: Module | null;
private readonly _mockFactories: Map<string, () => unknown>;
private readonly _mockMetaDataCache: Map<string, MockMetadata<any>>;
private _mockRegistry: Map<string, any>;
private _isolatedMockRegistry: Map<string, any> | null;
private readonly _moduleMockRegistry: Map<string, VMModule>;
private readonly _moduleMockFactories: Map<string, () => unknown>;
private readonly _moduleMocker: ModuleMocker;
private _isolatedModuleRegistry: ModuleRegistry | null;
private _moduleRegistry: ModuleRegistry;
private readonly _esmoduleRegistry: Map<string, VMModule>;
private readonly _cjsNamedExports: Map<string, Set<string>>;
private readonly _esmModuleLinkingMap: WeakMap<VMModule, Promise<unknown>>;
private readonly _testPath: string;
private readonly _resolver: Resolver;
private _shouldAutoMock: boolean;
private readonly _shouldMockModuleCache: Map<string, boolean>;
private readonly _shouldUnmockTransitiveDependenciesCache: Map<
string,
boolean
>;
private readonly _sourceMapRegistry: SourceMapRegistry;
private readonly _scriptTransformer: ScriptTransformer;
private readonly _fileTransforms: Map<string, RuntimeTransformResult>;
private readonly _fileTransformsMutex: Map<string, Promise<void>>;
private _v8CoverageInstrumenter: CoverageInstrumenter | undefined;
private _v8CoverageResult: V8Coverage | undefined;
private _v8CoverageSources: Map<string, RuntimeTransformResult> | undefined;
private readonly _transitiveShouldMock: Map<string, boolean>;
private _unmockList: RegExp | undefined;
private readonly _virtualMocks: Map<string, boolean>;
private readonly _virtualModuleMocks: Map<string, boolean>;
private _moduleImplementation?: typeof nativeModule.Module;
private readonly jestObjectCaches: Map<string, Jest>;
private jestGlobals?: JestGlobals;
private readonly esmConditions: Array<string>;
private readonly cjsConditions: Array<string>;
private isTornDown = false;
private isInsideTestCode: boolean | undefined;
constructor(
config: Config.ProjectConfig,
environment: JestEnvironment,
resolver: Resolver,
transformer: ScriptTransformer,
cacheFS: Map<string, string>,
coverageOptions: ShouldInstrumentOptions,
testPath: string,
globalConfig: Config.GlobalConfig,
) {
this._cacheFS = cacheFS;
this._config = config;
this._coverageOptions = coverageOptions;
this._currentlyExecutingModulePath = '';
this._environment = environment;
this._globalConfig = globalConfig;
this._explicitShouldMock = new Map();
this._explicitShouldMockModule = new Map();
this._internalModuleRegistry = new Map();
this._isCurrentlyExecutingManualMock = null;
this._mainModule = null;
this._mockFactories = new Map();
this._mockRegistry = new Map();
this._moduleMockRegistry = new Map();
this._moduleMockFactories = new Map();
invariant(
this._environment.moduleMocker,
'`moduleMocker` must be set on an environment when created',
);
this._moduleMocker = this._environment.moduleMocker;
this._isolatedModuleRegistry = null;
this._isolatedMockRegistry = null;
this._moduleRegistry = new Map();
this._esmoduleRegistry = new Map();
this._cjsNamedExports = new Map();
this._esmModuleLinkingMap = new WeakMap();
this._testPath = testPath;
this._resolver = resolver;
this._scriptTransformer = transformer;
this._shouldAutoMock = config.automock;
this._sourceMapRegistry = new Map();
this._fileTransforms = new Map();
this._fileTransformsMutex = new Map();
this._virtualMocks = new Map();
this._virtualModuleMocks = new Map();
this.jestObjectCaches = new Map();
this._mockMetaDataCache = new Map();
this._shouldMockModuleCache = new Map();
this._shouldUnmockTransitiveDependenciesCache = new Map();
this._transitiveShouldMock = new Map();
this._fakeTimersImplementation = config.fakeTimers.legacyFakeTimers
? this._environment.fakeTimers
: this._environment.fakeTimersModern;
this._unmockList = unmockRegExpCache.get(config);
if (!this._unmockList && config.unmockedModulePathPatterns) {
this._unmockList = new RegExp(
config.unmockedModulePathPatterns.join('|'),
);
unmockRegExpCache.set(config, this._unmockList);
}
const envExportConditions = this._environment.exportConditions?.() ?? [];
this.esmConditions = [
...new Set(['import', 'default', ...envExportConditions]),
];
this.cjsConditions = [
...new Set(['require', 'default', ...envExportConditions]),
];
if (config.automock) {
for (const filePath of config.setupFiles) {
if (filePath.includes(NODE_MODULES)) {
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
filePath,
undefined,
// shouldn't really matter, but in theory this will make sure the caching is correct
{
conditions: this.unstable_shouldLoadAsEsm(filePath)
? this.esmConditions
: this.cjsConditions,
},
);
this._transitiveShouldMock.set(moduleID, false);
}
}
}
this.resetModules();
}
static shouldInstrument = shouldInstrument;
static async createContext(
config: Config.ProjectConfig,
options: {
console?: Console;
maxWorkers: number;
watch?: boolean;
watchman: boolean;
},
): Promise<TestContext> {
createDirectory(config.cacheDirectory);
const instance = await Runtime.createHasteMap(config, {
console: options.console,
maxWorkers: options.maxWorkers,
resetCache: !config.cache,
watch: options.watch,
watchman: options.watchman,
});
const hasteMap = await instance.build();
return {
config,
hasteFS: hasteMap.hasteFS,
moduleMap: hasteMap.moduleMap,
resolver: Runtime.createResolver(config, hasteMap.moduleMap),
};
}
static createHasteMap(
config: Config.ProjectConfig,
options?: HasteMapOptions,
): Promise<IHasteMap> {
const ignorePatternParts = [
...config.modulePathIgnorePatterns,
...(options && options.watch ? config.watchPathIgnorePatterns : []),
config.cacheDirectory.startsWith(config.rootDir + path.sep) &&
config.cacheDirectory,
].filter(Boolean);
const ignorePattern =
ignorePatternParts.length > 0
? new RegExp(ignorePatternParts.join('|'))
: undefined;
return HasteMap.create({
cacheDirectory: config.cacheDirectory,
computeSha1: config.haste.computeSha1,
console: options?.console,
dependencyExtractor: config.dependencyExtractor,
enableSymlinks: config.haste.enableSymlinks,
extensions: [SnapshotExtension, ...config.moduleFileExtensions],
forceNodeFilesystemAPI: config.haste.forceNodeFilesystemAPI,
hasteImplModulePath: config.haste.hasteImplModulePath,
hasteMapModulePath: config.haste.hasteMapModulePath,
id: config.id,
ignorePattern,
maxWorkers: options?.maxWorkers || 1,
mocksPattern: escapePathForRegex(`${path.sep}__mocks__${path.sep}`),
platforms: config.haste.platforms || ['ios', 'android'],
resetCache: options?.resetCache,
retainAllFiles: config.haste.retainAllFiles || false,
rootDir: config.rootDir,
roots: config.roots,
throwOnModuleCollision: config.haste.throwOnModuleCollision,
useWatchman: options?.watchman,
watch: options?.watch,
workerThreads: options?.workerThreads,
});
}
static createResolver(
config: Config.ProjectConfig,
moduleMap: IModuleMap,
): Resolver {
return new Resolver(moduleMap, {
defaultPlatform: config.haste.defaultPlatform,
extensions: config.moduleFileExtensions.map(extension => `.${extension}`),
hasCoreModules: true,
moduleDirectories: config.moduleDirectories,
moduleNameMapper: getModuleNameMapper(config),
modulePaths: config.modulePaths,
platforms: config.haste.platforms,
resolver: config.resolver,
rootDir: config.rootDir,
});
}
static async runCLI(): Promise<never> {
throw new Error('The jest-runtime CLI has been moved into jest-repl');
}
static getCLIOptions(): never {
throw new Error('The jest-runtime CLI has been moved into jest-repl');
}
// unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it
unstable_shouldLoadAsEsm(modulePath: string): boolean {
return (
isWasm(modulePath) ||
Resolver.unstable_shouldLoadAsEsm(
modulePath,
this._config.extensionsToTreatAsEsm,
)
);
}
private async loadEsmModule(
modulePath: string,
query = '',
): Promise<VMModule> {
const cacheKey = modulePath + query;
const registry = this._isolatedModuleRegistry ?? this._esmoduleRegistry;
if (this._fileTransformsMutex.has(cacheKey)) {
await this._fileTransformsMutex.get(cacheKey);
}
if (!registry.has(cacheKey)) {
invariant(
typeof this._environment.getVmContext === 'function',
'ES Modules are only supported if your test environment has the `getVmContext` function',
);
const context = this._environment.getVmContext();
invariant(context, 'Test environment has been torn down');
let transformResolve: () => void;
let transformReject: (error?: unknown) => void;
this._fileTransformsMutex.set(
cacheKey,
new Promise((resolve, reject) => {
transformResolve = resolve;
transformReject = reject;
}),
);
invariant(
transformResolve! && transformReject!,
'Promise initialization should be sync - please report this bug to Jest!',
);
if (isWasm(modulePath)) {
const wasm = this._importWasmModule(
this.readFileBuffer(modulePath),
modulePath,
context,
);
registry.set(cacheKey, wasm);
transformResolve();
return wasm;
}
if (this._resolver.isCoreModule(modulePath)) {
const core = this._importCoreModule(modulePath, context);
registry.set(cacheKey, core);
transformResolve();
return core;
}
const transformedCode = await this.transformFileAsync(modulePath, {
isInternalModule: false,
supportsDynamicImport: true,
supportsExportNamespaceFrom: true,
supportsStaticESM: true,
supportsTopLevelAwait: true,
});
try {
let module;
if (modulePath.endsWith('.json')) {
module = new SyntheticModule(
['default'],
function () {
const obj = JSON.parse(transformedCode);
// @ts-expect-error: TS doesn't know what `this` is
this.setExport('default', obj);
},
{context, identifier: modulePath},
);
} else {
module = new SourceTextModule(transformedCode, {
context,
identifier: modulePath,
importModuleDynamically: async (
specifier: string,
referencingModule: VMModule,
) => {
invariant(
runtimeSupportsVmModules,
'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules',
);
const module = await this.resolveModule(
specifier,
referencingModule.identifier,
referencingModule.context,
);
return this.linkAndEvaluateModule(module);
},
initializeImportMeta: (meta: JestImportMeta) => {
const metaUrl = pathToFileURL(modulePath).href;
meta.url = metaUrl;
// @ts-expect-error Jest uses @types/node@16. Will be fixed when updated to @types/[email protected]
meta.filename = modulePath;
// @ts-expect-error Jest uses @types/node@16. Will be fixed when updated to @types/[email protected]
meta.dirname = path.dirname(modulePath);
meta.resolve = (specifier, parent = metaUrl) => {
const parentPath = fileURLToPath(parent);
const resolvedPath = this._resolver.resolveModule(
parentPath,
specifier,
{conditions: this.esmConditions},
);
return pathToFileURL(resolvedPath).href;
};
let jest = this.jestObjectCaches.get(modulePath);
if (!jest) {
jest = this._createJestObjectFor(modulePath);
this.jestObjectCaches.set(modulePath, jest);
}
meta.jest = jest;
},
});
}
invariant(
!registry.has(cacheKey),
`Module cache already has entry ${cacheKey}. This is a bug in Jest, please report it!`,
);
registry.set(cacheKey, module);
transformResolve();
} catch (error) {
transformReject(error);
throw error;
}
}
const module = registry.get(cacheKey);
invariant(
module,
'Module cache does not contain module. This is a bug in Jest, please open up an issue',
);
return module;
}
private async resolveModule<T = unknown>(
specifier: string,
referencingIdentifier: string,
context: VMContext,
): Promise<T> {
if (this.isTornDown) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
// @ts-expect-error - exiting
return;
}
if (this.isInsideTestCode === false) {
throw new ReferenceError(
'You are trying to `import` a file outside of the scope of the test code.',
);
}
const registry = this._isolatedModuleRegistry ?? this._esmoduleRegistry;
if (specifier === '@jest/globals') {
const fromCache = registry.get('@jest/globals');
if (fromCache) {
return fromCache;
}
const globals = this.getGlobalsForEsm(referencingIdentifier, context);
registry.set('@jest/globals', globals);
return globals;
}
if (specifier.startsWith('data:')) {
if (
await this._shouldMockModule(
referencingIdentifier,
specifier,
this._explicitShouldMockModule,
)
) {
return this.importMock(referencingIdentifier, specifier, context);
}
const fromCache = registry.get(specifier);
if (fromCache) {
return fromCache;
}
const match = specifier.match(dataURIRegex);
if (!match || !match.groups) {
throw new Error('Invalid data URI');
}
const mime = match.groups.mime;
const encoding = match.groups.encoding;
let module;
if (mime === 'application/wasm') {
if (!encoding) {
throw new Error('Missing data URI encoding');
}
if (encoding !== 'base64') {
throw new Error(`Invalid data URI encoding: ${encoding}`);
}
module = await this._importWasmModule(
Buffer.from(match.groups.code, 'base64'),
specifier,
context,
);
} else {
let code = match.groups.code;
if (!encoding || encoding === 'charset=utf-8') {
code = decodeURIComponent(code);
} else if (encoding === 'base64') {
code = Buffer.from(code, 'base64').toString();
} else {
throw new Error(`Invalid data URI encoding: ${encoding}`);
}
if (mime === 'application/json') {
module = new SyntheticModule(
['default'],
function () {
const obj = JSON.parse(code);
// @ts-expect-error: TS doesn't know what `this` is
this.setExport('default', obj);
},
{context, identifier: specifier},
);
} else {
module = new SourceTextModule(code, {
context,
identifier: specifier,
importModuleDynamically: async (
specifier: string,
referencingModule: VMModule,
) => {
invariant(
runtimeSupportsVmModules,
'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules',
);
const module = await this.resolveModule(
specifier,
referencingModule.identifier,
referencingModule.context,
);
return this.linkAndEvaluateModule(module);
},
initializeImportMeta(meta: ImportMeta) {
// no `jest` here as it's not loaded in a file
meta.url = specifier;
if (meta.url.startsWith('file://')) {
// @ts-expect-error Jest uses @types/node@16. Will be fixed when updated to @types/[email protected]
meta.filename = fileURLToPath(meta.url);
// @ts-expect-error Jest uses @types/node@16. Will be fixed when updated to @types/[email protected]
meta.dirname = path.dirname(meta.filename);
}
},
});
}
}
registry.set(specifier, module);
return module;
}
if (specifier.startsWith('file://')) {
specifier = fileURLToPath(specifier);
}
const [specifierPath, query] = specifier.split('?');
if (
await this._shouldMockModule(
referencingIdentifier,
specifierPath,
this._explicitShouldMockModule,
)
) {
return this.importMock(referencingIdentifier, specifierPath, context);
}
const resolved = await this._resolveModule(
referencingIdentifier,
specifierPath,
);
if (
// json files are modules when imported in modules
resolved.endsWith('.json') ||
this._resolver.isCoreModule(resolved) ||
this.unstable_shouldLoadAsEsm(resolved)
) {
return this.loadEsmModule(resolved, query);
}
return this.loadCjsAsEsm(referencingIdentifier, resolved, context);
}
private async linkAndEvaluateModule(
module: VMModule,
): Promise<VMModule | void> {
if (this.isTornDown) {
this._logFormattedReferenceError(
'You are trying to `import` a file after the Jest environment has been torn down.',
);
process.exitCode = 1;
return;
}
if (this.isInsideTestCode === false) {
throw new ReferenceError(
'You are trying to `import` a file outside of the scope of the test code.',
);
}
if (module.status === 'unlinked') {
// since we might attempt to link the same module in parallel, stick the promise in a weak map so every call to
// this method can await it
this._esmModuleLinkingMap.set(
module,
module.link((specifier: string, referencingModule: VMModule) =>
this.resolveModule(
specifier,
referencingModule.identifier,
referencingModule.context,
),
),
);
}
await this._esmModuleLinkingMap.get(module);
if (module.status === 'linked') {
await module.evaluate();
}
return module;
}
async unstable_importModule(
from: string,
moduleName?: string,
): Promise<unknown | void> {
invariant(
runtimeSupportsVmModules,
'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules',
);
const [path, query] = (moduleName ?? '').split('?');
const modulePath = await this._resolveModule(from, path);
const module = await this.loadEsmModule(modulePath, query);
return this.linkAndEvaluateModule(module);
}
private loadCjsAsEsm(from: string, modulePath: string, context: VMContext) {
// CJS loaded via `import` should share cache with other CJS: https://github.com/nodejs/modules/issues/503
const cjs = this.requireModuleOrMock(from, modulePath);
const parsedExports = this.getExportsOfCjs(modulePath);
const cjsExports = [...parsedExports].filter(exportName => {
// we don't wanna respect any exports _named_ default as a named export
if (exportName === 'default') {
return false;
}
return Object.hasOwnProperty.call(cjs, exportName);
});
const module = new SyntheticModule(
[...cjsExports, 'default'],
function () {
for (const exportName of cjsExports) {
// @ts-expect-error: TS doesn't know what `this` is
this.setExport(exportName, cjs[exportName]);
}
// @ts-expect-error: TS doesn't know what `this` is
this.setExport('default', cjs);
},
{context, identifier: modulePath},
);
return evaluateSyntheticModule(module);
}
private async importMock<T = unknown>(
from: string,
moduleName: string,
context: VMContext,
): Promise<T> {
const moduleID = await this._resolver.getModuleIDAsync(
this._virtualModuleMocks,
from,
moduleName,
{conditions: this.esmConditions},
);
if (this._moduleMockRegistry.has(moduleID)) {
return this._moduleMockRegistry.get(moduleID);
}
if (this._moduleMockFactories.has(moduleID)) {
const invokedFactory: any = await this._moduleMockFactories.get(
moduleID,
// has check above makes this ok
)!();
const module = new SyntheticModule(
Object.keys(invokedFactory),
function () {
for (const [key, value] of Object.entries(invokedFactory)) {
// @ts-expect-error: TS doesn't know what `this` is
this.setExport(key, value);
}
},
{context, identifier: moduleName},
);
this._moduleMockRegistry.set(moduleID, module);
return evaluateSyntheticModule(module);
}
throw new Error('Attempting to import a mock without a factory');
}
private getExportsOfCjs(modulePath: string) {
const cachedNamedExports = this._cjsNamedExports.get(modulePath);
if (cachedNamedExports) {
return cachedNamedExports;
}
if (path.extname(modulePath) === '.node') {
const nativeModule = this.requireModuleOrMock('', modulePath);
const namedExports = new Set(
Object.keys(nativeModule as Record<string, unknown>),
);
this._cjsNamedExports.set(modulePath, namedExports);
return namedExports;
}
const transformedCode =
this._fileTransforms.get(modulePath)?.code ?? this.readFile(modulePath);
const {exports, reexports} = parseCjs(transformedCode);
const namedExports = new Set(exports);
for (const reexport of reexports) {
if (this._resolver.isCoreModule(reexport)) {
const exports = this.requireModule(modulePath, reexport);
if (exports !== null && typeof exports === 'object') {
for (const e of Object.keys(exports)) namedExports.add(e);
}
} else {
const resolved = this._resolveCjsModule(modulePath, reexport);
const exports = this.getExportsOfCjs(resolved);
for (const e of exports) namedExports.add(e);
}
}
this._cjsNamedExports.set(modulePath, namedExports);
return namedExports;
}
requireModule<T = unknown>(
from: string,
moduleName?: string,
options?: InternalModuleOptions,
isRequireActual = false,
): T {
const isInternal = options?.isInternalModule ?? false;
const moduleID = this._resolver.getModuleID(
this._virtualMocks,
from,
moduleName,
{conditions: this.cjsConditions},
);
let modulePath: string | undefined;
// Some old tests rely on this mocking behavior. Ideally we'll change this
// to be more explicit.
const moduleResource = moduleName && this._resolver.getModule(moduleName);
const manualMock =
moduleName && this._resolver.getMockModule(from, moduleName);
if (
!options?.isInternalModule &&
!isRequireActual &&
!moduleResource &&
manualMock &&
manualMock !== this._isCurrentlyExecutingManualMock &&
this._explicitShouldMock.get(moduleID) !== false
) {
modulePath = manualMock;
}
if (moduleName && this._resolver.isCoreModule(moduleName)) {
return this._requireCoreModule(
moduleName,
supportsNodeColonModulePrefixInRequire,
);
}
if (!modulePath) {
modulePath = this._resolveCjsModule(from, moduleName);
}
if (this.unstable_shouldLoadAsEsm(modulePath)) {
// Node includes more info in the message
const error: NodeJS.ErrnoException = new Error(
`Must use import to load ES Module: ${modulePath}`,
);
error.code = 'ERR_REQUIRE_ESM';
throw error;
}
let moduleRegistry;
if (isInternal) {
moduleRegistry = this._internalModuleRegistry;
} else if (this._isolatedModuleRegistry) {
moduleRegistry = this._isolatedModuleRegistry;
} else {
moduleRegistry = this._moduleRegistry;
}
const module = moduleRegistry.get(modulePath);
if (module) {
return module.exports;
}
// We must register the pre-allocated module object first so that any
// circular dependencies that may arise while evaluating the module can
// be satisfied.
const localModule: InitialModule = {
children: [],
exports: {},
filename: modulePath,
id: modulePath,
isPreloading: false,
loaded: false,
path: path.dirname(modulePath),
};
moduleRegistry.set(modulePath, localModule);
try {
this._loadModule(