vitest 0.34.0 → 0.34.2

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.
Files changed (35) hide show
  1. package/LICENSE.md +28 -0
  2. package/dist/browser.d.ts +1 -1
  3. package/dist/browser.js +1 -1
  4. package/dist/child.js +11 -6
  5. package/dist/{chunk-api-setup.644415c3.js → chunk-api-setup.cc5282f7.js} +25 -15
  6. package/dist/{chunk-install-pkg.dd70081b.js → chunk-install-pkg.7e19b3a0.js} +6 -3
  7. package/dist/{chunk-integrations-globals.877c84db.js → chunk-integrations-globals.522ae1ae.js} +4 -3
  8. package/dist/cli.js +6 -3
  9. package/dist/config.d.ts +1 -1
  10. package/dist/coverage.d.ts +1 -1
  11. package/dist/entry-vm.js +4 -3
  12. package/dist/entry.js +4 -3
  13. package/dist/environments.d.ts +1 -1
  14. package/dist/environments.js +11 -2
  15. package/dist/execute.d.ts +139 -0
  16. package/dist/execute.js +1 -1
  17. package/dist/index.d.ts +10 -9
  18. package/dist/index.js +5 -4
  19. package/dist/loader.js +9 -528
  20. package/dist/node.d.ts +2 -2
  21. package/dist/node.js +6 -3
  22. package/dist/runners.d.ts +1 -1
  23. package/dist/runners.js +3 -2
  24. package/dist/{types-3c7dbfa5.d.ts → types-63abf2e0.d.ts} +63 -2
  25. package/dist/{vendor-environments.443ecd82.js → vendor-environments.37f266a9.js} +13 -6
  26. package/dist/{vendor-execute.9ab1c1a7.js → vendor-execute.4fc8203a.js} +409 -206
  27. package/dist/vendor-index.0b5b3600.js +2062 -0
  28. package/dist/{vendor-index.eff408fd.js → vendor-index.b5efbd68.js} +1 -1
  29. package/dist/{vendor-node.00226ab1.js → vendor-node.7b1bd3c5.js} +196 -122
  30. package/dist/vendor-tasks.f9d75aed.js +14 -0
  31. package/dist/{vendor-vi.271667ef.js → vendor-vi.f8055ff2.js} +2 -1
  32. package/dist/vm.js +14 -6
  33. package/dist/worker.js +12 -6
  34. package/package.json +7 -7
  35. package/dist/vendor-source-map.e6c1997b.js +0 -747
@@ -1,12 +1,12 @@
1
1
  import { pathToFileURL, fileURLToPath } from 'node:url';
2
2
  import vm from 'node:vm';
3
3
  import { ModuleCacheMap, ViteNodeRunner, DEFAULT_REQUEST_STUBS } from 'vite-node/client';
4
- import { isNodeBuiltin, getCachedData, setCacheData, isInternalRequest, isPrimitive } from 'vite-node/utils';
4
+ import { isNodeBuiltin, isPrimitive, toArray, getCachedData, setCacheData, isInternalRequest } from 'vite-node/utils';
5
5
  import { resolve, isAbsolute, dirname, join, basename, extname, normalize, relative } from 'pathe';
6
6
  import { processError } from '@vitest/utils/error';
7
7
  import { d as distDir } from './vendor-paths.84fc7a99.js';
8
8
  import { g as getWorkerState } from './vendor-global.97e4527c.js';
9
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
+ import { existsSync, readdirSync, statSync, readFileSync } from 'node:fs';
10
10
  import { getColors, getType } from '@vitest/utils';
11
11
  import { b as getAllMockableProperties } from './vendor-base.9c08bbd0.js';
12
12
  import { dirname as dirname$1 } from 'node:path';
@@ -334,17 +334,20 @@ ${c.green(`vi.mock("${mockpath}", async () => {
334
334
  }
335
335
  }
336
336
 
337
- const SyntheticModule = vm.SyntheticModule;
338
- const SourceTextModule = vm.SourceTextModule;
339
337
  const _require = createRequire(import.meta.url);
340
- const nativeResolve = import.meta.resolve;
341
- const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
342
- class ExternalModulesExecutor {
338
+ class CommonjsExecutor {
339
+ context;
340
+ requireCache = /* @__PURE__ */ new Map();
341
+ publicRequireCache = this.createProxyCache();
342
+ moduleCache = /* @__PURE__ */ new Map();
343
+ builtinCache = /* @__PURE__ */ Object.create(null);
344
+ extensions = /* @__PURE__ */ Object.create(null);
345
+ fs;
346
+ Module;
343
347
  constructor(options) {
344
- this.options = options;
345
348
  this.context = options.context;
349
+ this.fs = options.fileMap;
346
350
  const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
347
- this.primitives = primitives;
348
351
  const executor = this;
349
352
  this.Module = class Module$1 {
350
353
  exports;
@@ -360,7 +363,7 @@ class ExternalModulesExecutor {
360
363
  constructor(id, parent) {
361
364
  this.exports = primitives.Object.create(Object.prototype);
362
365
  this.require = Module$1.createRequire(id);
363
- this.path = dirname$1(id);
366
+ this.path = dirname(id);
364
367
  this.id = id;
365
368
  this.filename = id;
366
369
  this.loaded = false;
@@ -370,12 +373,12 @@ class ExternalModulesExecutor {
370
373
  const cjsModule = Module$1.wrap(code);
371
374
  const script = new vm.Script(cjsModule, {
372
375
  filename,
373
- importModuleDynamically: executor.importModuleDynamically
376
+ importModuleDynamically: options.importModuleDynamically
374
377
  });
375
378
  script.identifier = filename;
376
379
  const fn = script.runInContext(executor.context);
377
- const __dirname = dirname$1(filename);
378
- executor.requireCache[filename] = this;
380
+ const __dirname = dirname(filename);
381
+ executor.requireCache.set(filename, this);
379
382
  try {
380
383
  fn(this.exports, this.require, this, filename, __dirname);
381
384
  return this.exports;
@@ -427,121 +430,14 @@ class ExternalModulesExecutor {
427
430
  this.extensions[".js"] = this.requireJs;
428
431
  this.extensions[".json"] = this.requireJson;
429
432
  }
430
- requireCache = /* @__PURE__ */ Object.create(null);
431
- builtinCache = /* @__PURE__ */ Object.create(null);
432
- moduleCache = /* @__PURE__ */ new Map();
433
- extensions = /* @__PURE__ */ Object.create(null);
434
- esmLinkMap = /* @__PURE__ */ new WeakMap();
435
- context;
436
- fsCache = /* @__PURE__ */ new Map();
437
- fsBufferCache = /* @__PURE__ */ new Map();
438
- Module;
439
- primitives;
440
433
  requireJs = (m, filename) => {
441
- const content = this.readFile(filename);
434
+ const content = this.fs.readFile(filename);
442
435
  m._compile(content, filename);
443
436
  };
444
437
  requireJson = (m, filename) => {
445
- const code = this.readFile(filename);
438
+ const code = this.fs.readFile(filename);
446
439
  m.exports = JSON.parse(code);
447
440
  };
448
- importModuleDynamically = async (specifier, referencer) => {
449
- const module = await this.resolveModule(specifier, referencer.identifier);
450
- return this.evaluateModule(module);
451
- };
452
- resolveModule = async (specifier, referencer) => {
453
- const identifier = await this.resolveAsync(specifier, referencer);
454
- return await this.createModule(identifier);
455
- };
456
- async resolveAsync(specifier, parent) {
457
- return nativeResolve(specifier, parent);
458
- }
459
- readFile(path) {
460
- const cached = this.fsCache.get(path);
461
- if (cached)
462
- return cached;
463
- const source = readFileSync(path, "utf-8");
464
- this.fsCache.set(path, source);
465
- return source;
466
- }
467
- readBuffer(path) {
468
- const cached = this.fsBufferCache.get(path);
469
- if (cached)
470
- return cached;
471
- const buffer = readFileSync(path);
472
- this.fsBufferCache.set(path, buffer);
473
- return buffer;
474
- }
475
- findNearestPackageData(basedir) {
476
- var _a;
477
- const originalBasedir = basedir;
478
- const packageCache = this.options.packageCache;
479
- while (basedir) {
480
- const cached = getCachedData(packageCache, basedir, originalBasedir);
481
- if (cached)
482
- return cached;
483
- const pkgPath = join(basedir, "package.json");
484
- try {
485
- if ((_a = statSync(pkgPath, { throwIfNoEntry: false })) == null ? void 0 : _a.isFile()) {
486
- const pkgData = JSON.parse(this.readFile(pkgPath));
487
- if (packageCache)
488
- setCacheData(packageCache, pkgData, basedir, originalBasedir);
489
- return pkgData;
490
- }
491
- } catch {
492
- }
493
- const nextBasedir = dirname$1(basedir);
494
- if (nextBasedir === basedir)
495
- break;
496
- basedir = nextBasedir;
497
- }
498
- return null;
499
- }
500
- wrapSynteticModule(identifier, exports) {
501
- const moduleKeys = Object.keys(exports).filter((key) => key !== "default");
502
- const m = new SyntheticModule(
503
- [...moduleKeys, "default"],
504
- () => {
505
- for (const key of moduleKeys)
506
- m.setExport(key, exports[key]);
507
- m.setExport("default", exports);
508
- },
509
- {
510
- context: this.context,
511
- identifier
512
- }
513
- );
514
- return m;
515
- }
516
- async evaluateModule(m) {
517
- if (m.status === "unlinked") {
518
- this.esmLinkMap.set(
519
- m,
520
- m.link(
521
- (identifier, referencer) => this.resolveModule(identifier, referencer.identifier)
522
- )
523
- );
524
- }
525
- await this.esmLinkMap.get(m);
526
- if (m.status === "linked")
527
- await m.evaluate();
528
- return m;
529
- }
530
- findLongestRegisteredExtension(filename) {
531
- const name = basename(filename);
532
- let currentExtension;
533
- let index;
534
- let startIndex = 0;
535
- while ((index = name.indexOf(".", startIndex)) !== -1) {
536
- startIndex = index + 1;
537
- if (index === 0)
538
- continue;
539
- currentExtension = name.slice(index);
540
- if (this.extensions[currentExtension])
541
- return currentExtension;
542
- }
543
- return ".js";
544
- }
545
441
  createRequire = (filename) => {
546
442
  const _require2 = createRequire(filename);
547
443
  const require = (id) => {
@@ -549,7 +445,7 @@ class ExternalModulesExecutor {
549
445
  const ext = extname(resolved);
550
446
  if (ext === ".node" || isNodeBuiltin(resolved))
551
447
  return this.requireCoreModule(resolved);
552
- const module = this.createCommonJSNodeModule(resolved);
448
+ const module = new this.Module(resolved);
553
449
  return this.loadCommonJSModule(module, resolved);
554
450
  };
555
451
  require.resolve = _require2.resolve;
@@ -559,16 +455,29 @@ class ExternalModulesExecutor {
559
455
  },
560
456
  configurable: true
561
457
  });
562
- require.main = _require2.main;
563
- require.cache = this.requireCache;
458
+ require.main = void 0;
459
+ require.cache = this.publicRequireCache;
564
460
  return require;
565
461
  };
566
- createCommonJSNodeModule(filename) {
567
- return new this.Module(filename);
462
+ createProxyCache() {
463
+ return new Proxy(/* @__PURE__ */ Object.create(null), {
464
+ defineProperty: () => true,
465
+ deleteProperty: () => true,
466
+ set: () => true,
467
+ get: (_, key) => this.requireCache.get(key),
468
+ has: (_, key) => this.requireCache.has(key),
469
+ ownKeys: () => Array.from(this.requireCache.keys()),
470
+ getOwnPropertyDescriptor() {
471
+ return {
472
+ configurable: true,
473
+ enumerable: true
474
+ };
475
+ }
476
+ });
568
477
  }
569
478
  // very naive implementation for Node.js require
570
479
  loadCommonJSModule(module, filename) {
571
- const cached = this.requireCache[filename];
480
+ const cached = this.requireCache.get(filename);
572
481
  if (cached)
573
482
  return cached.exports;
574
483
  const extension = this.findLongestRegisteredExtension(filename);
@@ -576,44 +485,106 @@ class ExternalModulesExecutor {
576
485
  loader(module, filename);
577
486
  return module.exports;
578
487
  }
579
- async createEsmModule(fileUrl, code) {
580
- const cached = this.moduleCache.get(fileUrl);
581
- if (cached)
582
- return cached;
583
- const [urlPath] = fileUrl.split("?");
584
- if (CSS_LANGS_RE.test(urlPath) || KNOWN_ASSET_RE.test(urlPath)) {
585
- const path = normalize(urlPath);
586
- let name = path.split("/node_modules/").pop() || "";
587
- if (name == null ? void 0 : name.startsWith("@"))
588
- name = name.split("/").slice(0, 2).join("/");
589
- else
590
- name = name.split("/")[0];
591
- const ext = extname(path);
592
- let error = `[vitest] Cannot import ${fileUrl}. At the moment, importing ${ext} files inside external dependencies is not allowed. `;
593
- if (name) {
594
- const c = getColors();
595
- error += `As a temporary workaround you can try to inline the package by updating your config:
488
+ findLongestRegisteredExtension(filename) {
489
+ const name = basename(filename);
490
+ let currentExtension;
491
+ let index;
492
+ let startIndex = 0;
493
+ while ((index = name.indexOf(".", startIndex)) !== -1) {
494
+ startIndex = index + 1;
495
+ if (index === 0)
496
+ continue;
497
+ currentExtension = name.slice(index);
498
+ if (this.extensions[currentExtension])
499
+ return currentExtension;
500
+ }
501
+ return ".js";
502
+ }
503
+ require(identifier) {
504
+ const ext = extname(identifier);
505
+ if (ext === ".node" || isNodeBuiltin(identifier))
506
+ return this.requireCoreModule(identifier);
507
+ const module = new this.Module(identifier);
508
+ return this.loadCommonJSModule(module, identifier);
509
+ }
510
+ requireCoreModule(identifier) {
511
+ const normalized = identifier.replace(/^node:/, "");
512
+ if (this.builtinCache[normalized])
513
+ return this.builtinCache[normalized].exports;
514
+ const moduleExports = _require(identifier);
515
+ if (identifier === "node:module" || identifier === "module") {
516
+ const module = new this.Module("/module.js");
517
+ module.exports = this.Module;
518
+ this.builtinCache[normalized] = module;
519
+ return module.exports;
520
+ }
521
+ this.builtinCache[normalized] = _require.cache[normalized];
522
+ return moduleExports;
523
+ }
524
+ }
596
525
 
597
- ${c.gray(c.dim("// vitest.config.js"))}
598
- ${c.green(`export default {
599
- test: {
600
- deps: {
601
- optimizer: {
602
- web: {
603
- include: [
604
- ${c.yellow(c.bold(`"${name}"`))}
605
- ]
526
+ function interopCommonJsModule(interopDefault, mod) {
527
+ if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) {
528
+ return {
529
+ keys: [],
530
+ moduleExports: {},
531
+ defaultExport: mod
532
+ };
533
+ }
534
+ if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
535
+ const defaultKets = Object.keys(mod.default);
536
+ const moduleKeys = Object.keys(mod);
537
+ const allKeys = /* @__PURE__ */ new Set([...defaultKets, ...moduleKeys]);
538
+ allKeys.delete("default");
539
+ return {
540
+ keys: Array.from(allKeys),
541
+ moduleExports: new Proxy(mod, {
542
+ get(mod2, prop) {
543
+ var _a;
544
+ return mod2[prop] ?? ((_a = mod2.default) == null ? void 0 : _a[prop]);
606
545
  }
607
- }
608
- }
546
+ }),
547
+ defaultExport: mod
548
+ };
609
549
  }
550
+ return {
551
+ keys: Object.keys(mod).filter((key) => key !== "default"),
552
+ moduleExports: mod,
553
+ defaultExport: mod
554
+ };
610
555
  }
611
- `)}`;
612
- }
613
- throw new this.primitives.Error(error);
556
+ const SyntheticModule$1 = vm.SyntheticModule;
557
+ const SourceTextModule = vm.SourceTextModule;
558
+
559
+ const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
560
+ class EsmExecutor {
561
+ constructor(executor, options) {
562
+ this.executor = executor;
563
+ this.context = options.context;
564
+ }
565
+ moduleCache = /* @__PURE__ */ new Map();
566
+ esmLinkMap = /* @__PURE__ */ new WeakMap();
567
+ context;
568
+ async evaluateModule(m) {
569
+ if (m.status === "unlinked") {
570
+ this.esmLinkMap.set(
571
+ m,
572
+ m.link(
573
+ (identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier)
574
+ )
575
+ );
614
576
  }
577
+ await this.esmLinkMap.get(m);
578
+ if (m.status === "linked")
579
+ await m.evaluate();
580
+ return m;
581
+ }
582
+ async createEsModule(fileUrl, code) {
583
+ const cached = this.moduleCache.get(fileUrl);
584
+ if (cached)
585
+ return cached;
615
586
  if (fileUrl.endsWith(".json")) {
616
- const m2 = new SyntheticModule(
587
+ const m2 = new SyntheticModule$1(
617
588
  ["default"],
618
589
  () => {
619
590
  const result = JSON.parse(code);
@@ -628,11 +599,11 @@ ${c.green(`export default {
628
599
  {
629
600
  identifier: fileUrl,
630
601
  context: this.context,
631
- importModuleDynamically: this.importModuleDynamically,
602
+ importModuleDynamically: this.executor.importModuleDynamically,
632
603
  initializeImportMeta: (meta, mod) => {
633
604
  meta.url = mod.identifier;
634
605
  meta.resolve = (specifier, importer) => {
635
- return nativeResolve(specifier, importer ?? mod.identifier);
606
+ return this.executor.resolve(specifier, importer ?? mod.identifier);
636
607
  };
637
608
  }
638
609
  }
@@ -640,20 +611,6 @@ ${c.green(`export default {
640
611
  this.moduleCache.set(fileUrl, m);
641
612
  return m;
642
613
  }
643
- requireCoreModule(identifier) {
644
- const normalized = identifier.replace(/^node:/, "");
645
- if (this.builtinCache[normalized])
646
- return this.builtinCache[normalized].exports;
647
- const moduleExports = _require(identifier);
648
- if (identifier === "node:module" || identifier === "module") {
649
- const module = new this.Module("/module.js");
650
- module.exports = this.Module;
651
- this.builtinCache[normalized] = module;
652
- return module.exports;
653
- }
654
- this.builtinCache[normalized] = _require.cache[normalized];
655
- return moduleExports;
656
- }
657
614
  async loadWebAssemblyModule(source, identifier) {
658
615
  const cached = this.moduleCache.get(identifier);
659
616
  if (cached)
@@ -664,14 +621,14 @@ ${c.green(`export default {
664
621
  const moduleLookup = {};
665
622
  for (const { module } of imports) {
666
623
  if (moduleLookup[module] === void 0) {
667
- const resolvedModule = await this.resolveModule(
624
+ const resolvedModule = await this.executor.resolveModule(
668
625
  module,
669
626
  identifier
670
627
  );
671
628
  moduleLookup[module] = await this.evaluateModule(resolvedModule);
672
629
  }
673
630
  }
674
- const syntheticModule = new SyntheticModule(
631
+ const syntheticModule = new SyntheticModule$1(
675
632
  exports.map(({ name }) => name),
676
633
  () => {
677
634
  const importsObject = {};
@@ -691,11 +648,16 @@ ${c.green(`export default {
691
648
  );
692
649
  return syntheticModule;
693
650
  }
651
+ cacheModule(identifier, module) {
652
+ this.moduleCache.set(identifier, module);
653
+ }
654
+ resolveCachedModule(identifier) {
655
+ return this.moduleCache.get(identifier);
656
+ }
694
657
  async createDataModule(identifier) {
695
658
  const cached = this.moduleCache.get(identifier);
696
659
  if (cached)
697
660
  return cached;
698
- const Error = this.primitives.Error;
699
661
  const match = identifier.match(dataURIRegex);
700
662
  if (!match || !match.groups)
701
663
  throw new Error("Invalid data URI");
@@ -721,7 +683,7 @@ ${c.green(`export default {
721
683
  else
722
684
  throw new Error(`Invalid data URI encoding: ${encoding}`);
723
685
  if (mime === "application/json") {
724
- const module = new SyntheticModule(
686
+ const module = new SyntheticModule$1(
725
687
  ["default"],
726
688
  () => {
727
689
  const obj = JSON.parse(code);
@@ -732,38 +694,269 @@ ${c.green(`export default {
732
694
  this.moduleCache.set(identifier, module);
733
695
  return module;
734
696
  }
735
- return this.createEsmModule(identifier, code);
697
+ return this.createEsModule(identifier, code);
736
698
  }
737
- async createModule(identifier) {
699
+ }
700
+
701
+ const CLIENT_ID = "/@vite/client";
702
+ const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
703
+ class ViteExecutor {
704
+ constructor(options) {
705
+ this.options = options;
706
+ this.esm = options.esmExecutor;
707
+ }
708
+ esm;
709
+ resolve = (identifier, parent) => {
710
+ if (identifier === CLIENT_ID) {
711
+ if (this.workerState.environment.transformMode === "web")
712
+ return identifier;
713
+ const packageName = this.getPackageName(parent);
714
+ throw new Error(
715
+ `[vitest] Vitest cannot handle ${CLIENT_ID} imported in ${parent} when running in SSR environment. Add "${packageName}" to "ssr.noExternal" if you are using Vite SSR, or to "server.deps.inline" if you are using Vite Node.`
716
+ );
717
+ }
718
+ };
719
+ get workerState() {
720
+ return this.options.context.__vitest_worker__;
721
+ }
722
+ getPackageName(modulePath) {
723
+ const path = normalize(modulePath);
724
+ let name = path.split("/node_modules/").pop() || "";
725
+ if (name == null ? void 0 : name.startsWith("@"))
726
+ name = name.split("/").slice(0, 2).join("/");
727
+ else
728
+ name = name.split("/")[0];
729
+ return name;
730
+ }
731
+ async createViteModule(fileUrl) {
732
+ if (fileUrl === CLIENT_FILE)
733
+ return this.createViteClientModule();
734
+ const cached = this.esm.resolveCachedModule(fileUrl);
735
+ if (cached)
736
+ return cached;
737
+ const result = await this.options.transform(fileUrl, "web");
738
+ if (!result.code)
739
+ throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exists?`);
740
+ return this.esm.createEsModule(fileUrl, result.code);
741
+ }
742
+ createViteClientModule() {
743
+ const identifier = CLIENT_ID;
744
+ const cached = this.esm.resolveCachedModule(identifier);
745
+ if (cached)
746
+ return cached;
747
+ const stub = this.options.viteClientModule;
748
+ const moduleKeys = Object.keys(stub);
749
+ const module = new SyntheticModule$1(
750
+ moduleKeys,
751
+ () => {
752
+ moduleKeys.forEach((key) => {
753
+ module.setExport(key, stub[key]);
754
+ });
755
+ },
756
+ { context: this.options.context, identifier }
757
+ );
758
+ this.esm.cacheModule(identifier, module);
759
+ return module;
760
+ }
761
+ canResolve = (fileUrl) => {
762
+ var _a;
763
+ const transformMode = this.workerState.environment.transformMode;
764
+ if (transformMode !== "web")
765
+ return false;
766
+ if (fileUrl === CLIENT_FILE)
767
+ return true;
768
+ const config = ((_a = this.workerState.config.deps) == null ? void 0 : _a.web) || {};
769
+ const [modulePath] = fileUrl.split("?");
770
+ if (config.transformCss && CSS_LANGS_RE.test(modulePath))
771
+ return true;
772
+ if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath))
773
+ return true;
774
+ if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath)))
775
+ return true;
776
+ return false;
777
+ };
778
+ }
779
+
780
+ const SyntheticModule = vm.SyntheticModule;
781
+ const nativeResolve = import.meta.resolve;
782
+ class ExternalModulesExecutor {
783
+ constructor(options) {
784
+ this.options = options;
785
+ this.context = options.context;
786
+ this.fs = options.fileMap;
787
+ this.esm = new EsmExecutor(this, {
788
+ context: this.context
789
+ });
790
+ this.cjs = new CommonjsExecutor({
791
+ context: this.context,
792
+ importModuleDynamically: this.importModuleDynamically,
793
+ fileMap: options.fileMap
794
+ });
795
+ this.vite = new ViteExecutor({
796
+ esmExecutor: this.esm,
797
+ context: this.context,
798
+ transform: options.transform,
799
+ viteClientModule: options.requestStubs["/@vite/client"]
800
+ });
801
+ this.resolvers = [this.vite.resolve];
802
+ }
803
+ cjs;
804
+ esm;
805
+ vite;
806
+ context;
807
+ fs;
808
+ resolvers = [];
809
+ // dynamic import can be used in both ESM and CJS, so we have it in the executor
810
+ importModuleDynamically = async (specifier, referencer) => {
811
+ const module = await this.resolveModule(specifier, referencer.identifier);
812
+ return this.esm.evaluateModule(module);
813
+ };
814
+ resolveModule = async (specifier, referencer) => {
815
+ const identifier = await this.resolve(specifier, referencer);
816
+ return await this.createModule(identifier);
817
+ };
818
+ async resolve(specifier, parent) {
819
+ for (const resolver of this.resolvers) {
820
+ const id = resolver(specifier, parent);
821
+ if (id)
822
+ return id;
823
+ }
824
+ return nativeResolve(specifier, parent);
825
+ }
826
+ findNearestPackageData(basedir) {
827
+ var _a;
828
+ const originalBasedir = basedir;
829
+ const packageCache = this.options.packageCache;
830
+ while (basedir) {
831
+ const cached = getCachedData(packageCache, basedir, originalBasedir);
832
+ if (cached)
833
+ return cached;
834
+ const pkgPath = join(basedir, "package.json");
835
+ try {
836
+ if ((_a = statSync(pkgPath, { throwIfNoEntry: false })) == null ? void 0 : _a.isFile()) {
837
+ const pkgData = JSON.parse(this.fs.readFile(pkgPath));
838
+ if (packageCache)
839
+ setCacheData(packageCache, pkgData, basedir, originalBasedir);
840
+ return pkgData;
841
+ }
842
+ } catch {
843
+ }
844
+ const nextBasedir = dirname$1(basedir);
845
+ if (nextBasedir === basedir)
846
+ break;
847
+ basedir = nextBasedir;
848
+ }
849
+ return {};
850
+ }
851
+ wrapCoreSynteticModule(identifier, exports) {
852
+ const moduleKeys = Object.keys(exports);
853
+ const m = new SyntheticModule(
854
+ [...moduleKeys, "default"],
855
+ () => {
856
+ for (const key of moduleKeys)
857
+ m.setExport(key, exports[key]);
858
+ m.setExport("default", exports);
859
+ },
860
+ {
861
+ context: this.context,
862
+ identifier
863
+ }
864
+ );
865
+ return m;
866
+ }
867
+ wrapCommonJsSynteticModule(identifier, exports) {
868
+ const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.options.interopDefault, exports);
869
+ const m = new SyntheticModule(
870
+ [...keys, "default"],
871
+ () => {
872
+ for (const key of keys)
873
+ m.setExport(key, moduleExports[key]);
874
+ m.setExport("default", defaultExport);
875
+ },
876
+ {
877
+ context: this.context,
878
+ identifier
879
+ }
880
+ );
881
+ return m;
882
+ }
883
+ getModuleInformation(identifier) {
738
884
  if (identifier.startsWith("data:"))
739
- return this.createDataModule(identifier);
885
+ return { type: "data", url: identifier, path: identifier };
740
886
  const extension = extname(identifier);
741
- if (extension === ".node" || isNodeBuiltin(identifier)) {
742
- const exports2 = this.requireCoreModule(identifier);
743
- return this.wrapSynteticModule(identifier, exports2);
744
- }
887
+ if (extension === ".node" || isNodeBuiltin(identifier))
888
+ return { type: "builtin", url: identifier, path: identifier };
745
889
  const isFileUrl = identifier.startsWith("file://");
746
- const fileUrl = isFileUrl ? identifier : pathToFileURL(identifier).toString();
747
890
  const pathUrl = isFileUrl ? fileURLToPath(identifier.split("?")[0]) : identifier;
748
- if (extension === ".cjs") {
749
- const module2 = this.createCommonJSNodeModule(pathUrl);
750
- const exports2 = this.loadCommonJSModule(module2, pathUrl);
751
- return this.wrapSynteticModule(fileUrl, exports2);
891
+ const fileUrl = isFileUrl ? identifier : pathToFileURL(pathUrl).toString();
892
+ let type;
893
+ if (this.vite.canResolve(fileUrl)) {
894
+ type = "vite";
895
+ } else if (extension === ".mjs") {
896
+ type = "module";
897
+ } else if (extension === ".cjs") {
898
+ type = "commonjs";
899
+ } else {
900
+ const pkgData = this.findNearestPackageData(normalize(pathUrl));
901
+ type = pkgData.type === "module" ? "module" : "commonjs";
902
+ }
903
+ return { type, path: pathUrl, url: fileUrl };
904
+ }
905
+ async createModule(identifier) {
906
+ const { type, url, path } = this.getModuleInformation(identifier);
907
+ switch (type) {
908
+ case "data":
909
+ return this.esm.createDataModule(identifier);
910
+ case "builtin": {
911
+ const exports = this.require(identifier);
912
+ return this.wrapCoreSynteticModule(identifier, exports);
913
+ }
914
+ case "vite":
915
+ return await this.vite.createViteModule(url);
916
+ case "module":
917
+ return await this.esm.createEsModule(url, this.fs.readFile(path));
918
+ case "commonjs": {
919
+ const exports = this.require(path);
920
+ return this.wrapCommonJsSynteticModule(identifier, exports);
921
+ }
922
+ default: {
923
+ const _deadend = type;
924
+ return _deadend;
925
+ }
752
926
  }
753
- if (extension === ".mjs")
754
- return await this.createEsmModule(fileUrl, this.readFile(pathUrl));
755
- const pkgData = this.findNearestPackageData(normalize(pathUrl));
756
- if (pkgData.type === "module")
757
- return await this.createEsmModule(fileUrl, this.readFile(pathUrl));
758
- const module = this.createCommonJSNodeModule(pathUrl);
759
- const exports = this.loadCommonJSModule(module, pathUrl);
760
- return this.wrapSynteticModule(fileUrl, exports);
761
927
  }
762
928
  async import(identifier) {
763
929
  const module = await this.createModule(identifier);
764
- await this.evaluateModule(module);
930
+ await this.esm.evaluateModule(module);
765
931
  return module.namespace;
766
932
  }
933
+ require(identifier) {
934
+ return this.cjs.require(identifier);
935
+ }
936
+ createRequire(identifier) {
937
+ return this.cjs.createRequire(identifier);
938
+ }
939
+ }
940
+
941
+ class FileMap {
942
+ fsCache = /* @__PURE__ */ new Map();
943
+ fsBufferCache = /* @__PURE__ */ new Map();
944
+ readFile(path) {
945
+ const cached = this.fsCache.get(path);
946
+ if (cached)
947
+ return cached;
948
+ const source = readFileSync(path, "utf-8");
949
+ this.fsCache.set(path, source);
950
+ return source;
951
+ }
952
+ readBuffer(path) {
953
+ const cached = this.fsBufferCache.get(path);
954
+ if (cached)
955
+ return cached;
956
+ const buffer = readFileSync(path);
957
+ this.fsBufferCache.set(path, buffer);
958
+ return buffer;
959
+ }
767
960
  }
768
961
 
769
962
  const entryUrl = pathToFileURL(resolve(distDir, "entry.js")).href;
@@ -777,6 +970,7 @@ let _viteNode;
777
970
  const packageCache = /* @__PURE__ */ new Map();
778
971
  const moduleCache = new ModuleCacheMap();
779
972
  const mockMap = /* @__PURE__ */ new Map();
973
+ const fileMap = new FileMap();
780
974
  async function startViteNode(options) {
781
975
  if (_viteNode)
782
976
  return _viteNode;
@@ -818,6 +1012,9 @@ async function startVitestExecutor(options) {
818
1012
  resolveId(id, importer) {
819
1013
  return rpc().resolveId(id, importer, getTransformMode());
820
1014
  },
1015
+ transform(id) {
1016
+ return rpc().transform(id, "web");
1017
+ },
821
1018
  packageCache,
822
1019
  moduleCache,
823
1020
  mockMap,
@@ -860,7 +1057,11 @@ function removeStyle(id) {
860
1057
  }
861
1058
  class VitestExecutor extends ViteNodeRunner {
862
1059
  constructor(options) {
863
- super(options);
1060
+ super({
1061
+ ...options,
1062
+ // interop is done inside the external executor instead
1063
+ interopDefault: options.context ? false : options.interopDefault
1064
+ });
864
1065
  this.options = options;
865
1066
  this.mocker = new VitestMocker(this);
866
1067
  if (!options.context) {
@@ -880,10 +1081,6 @@ class VitestExecutor extends ViteNodeRunner {
880
1081
  Symbol
881
1082
  };
882
1083
  } else {
883
- this.externalModules = new ExternalModulesExecutor({
884
- context: options.context,
885
- packageCache: options.packageCache
886
- });
887
1084
  const clientStub = vm.runInContext(
888
1085
  `(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`,
889
1086
  options.context
@@ -893,6 +1090,12 @@ class VitestExecutor extends ViteNodeRunner {
893
1090
  "@vite/client": clientStub
894
1091
  };
895
1092
  this.primitives = vm.runInContext("({ Object, Reflect, Symbol })", options.context);
1093
+ this.externalModules = new ExternalModulesExecutor({
1094
+ ...options,
1095
+ fileMap,
1096
+ context: options.context,
1097
+ packageCache: options.packageCache
1098
+ });
896
1099
  }
897
1100
  }
898
1101
  mocker;