formacao
This commit is contained in:
+2
@@ -1,5 +1,7 @@
|
||||
# @vitest/mocker
|
||||
|
||||
[](https://npmx.dev/package/@vitest/mocker)
|
||||
|
||||
Vitest's module mocker implementation.
|
||||
|
||||
[GitHub](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/mocker/EXPORTS.md)
|
||||
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
import { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
|
||||
import { registerModuleMocker } from './register.js';
|
||||
import './chunk-mocker.js';
|
||||
import './chunk-helpers.js';
|
||||
import './index.js';
|
||||
import './chunk-registry.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
+1
@@ -5,6 +5,7 @@ interface AutomockOptions {
|
||||
* @default "__vitest_mocker__"
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
id?: string;
|
||||
}
|
||||
declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString;
|
||||
|
||||
|
||||
+5
@@ -1,3 +1,8 @@
|
||||
import 'node:fs';
|
||||
import 'node:url';
|
||||
import 'magic-string';
|
||||
export { a as automockModule } from './chunk-automock.js';
|
||||
import 'estree-walker';
|
||||
import 'node:module';
|
||||
import 'node:path';
|
||||
import './chunk-helpers.js';
|
||||
|
||||
+4
-4
@@ -1,9 +1,9 @@
|
||||
import { M as ModuleMockerInterceptor } from './mocker.d-TnKRhz7N.js';
|
||||
export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, d as ModuleMockerConfig, e as ModuleMockerRPC, R as ResolveIdResult, f as ResolveMockResult, c as createCompilerHints } from './mocker.d-TnKRhz7N.js';
|
||||
import { M as ModuleMockerInterceptor } from './mocker.d-QEntlm6J.js';
|
||||
export { C as CompilerHintsOptions, b as ModuleMocker, a as ModuleMockerCompilerHints, c as ModuleMockerConfig, d as ModuleMockerRPC, R as ResolveIdResult, e as ResolveMockResult, f as createCompilerHints } from './mocker.d-QEntlm6J.js';
|
||||
import { StartOptions, SetupWorker } from 'msw/browser';
|
||||
import { M as MockerRegistry, a as MockedModule } from './types.d-B8CCKmHt.js';
|
||||
import { M as MockerRegistry, a as MockedModule } from './types.d-BjI5eAwu.js';
|
||||
import '@vitest/spy';
|
||||
import './index.d-C-sLYZi-.js';
|
||||
import './index.d-B41z0AuW.js';
|
||||
|
||||
interface ModuleMockerMSWInterceptorOptions {
|
||||
/**
|
||||
|
||||
+1
@@ -2,6 +2,7 @@ export { M as ModuleMocker, c as createCompilerHints } from './chunk-mocker.js';
|
||||
import { M as MockerRegistry } from './chunk-registry.js';
|
||||
import { c as createManualModuleSource, a as cleanUrl } from './chunk-utils.js';
|
||||
export { M as ModuleMockerServerInterceptor } from './chunk-interceptor-native.js';
|
||||
import './chunk-helpers.js';
|
||||
import './index.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
|
||||
+187
-15
File diff suppressed because one or more lines are too long
+44
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Get original stacktrace without source map support the most performant way.
|
||||
* - Create only 1 stack frame.
|
||||
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
|
||||
*/
|
||||
function createSimpleStackTrace(options) {
|
||||
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
|
||||
const limit = Error.stackTraceLimit;
|
||||
const prepareStackTrace = Error.prepareStackTrace;
|
||||
Error.stackTraceLimit = stackTraceLimit;
|
||||
Error.prepareStackTrace = (e) => e.stack;
|
||||
const err = new Error(message);
|
||||
const stackTrace = err.stack || "";
|
||||
Error.prepareStackTrace = prepareStackTrace;
|
||||
Error.stackTraceLimit = limit;
|
||||
return stackTrace;
|
||||
}
|
||||
function filterOutComments(s) {
|
||||
const result = [];
|
||||
let commentState = "none";
|
||||
for (let i = 0; i < s.length; ++i) {
|
||||
if (commentState === "singleline") {
|
||||
if (s[i] === "\n") {
|
||||
commentState = "none";
|
||||
}
|
||||
} else if (commentState === "multiline") {
|
||||
if (s[i - 1] === "*" && s[i] === "/") {
|
||||
commentState = "none";
|
||||
}
|
||||
} else if (commentState === "none") {
|
||||
if (s[i] === "/" && s[i + 1] === "/") {
|
||||
commentState = "singleline";
|
||||
} else if (s[i] === "/" && s[i + 1] === "*") {
|
||||
commentState = "multiline";
|
||||
i += 2;
|
||||
} else {
|
||||
result.push(s[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result.join("");
|
||||
}
|
||||
|
||||
export { createSimpleStackTrace as c, filterOutComments as f };
|
||||
+665
@@ -0,0 +1,665 @@
|
||||
import MagicString from 'magic-string';
|
||||
import { e as esmWalker } from './chunk-automock.js';
|
||||
|
||||
// AST walker module for ESTree compatible trees
|
||||
|
||||
|
||||
function makeTest(test) {
|
||||
if (typeof test === "string")
|
||||
{ return function (type) { return type === test; } }
|
||||
else if (!test)
|
||||
{ return function () { return true; } }
|
||||
else
|
||||
{ return test }
|
||||
}
|
||||
|
||||
var Found = function Found(node, state) { this.node = node; this.state = state; };
|
||||
|
||||
// Find the innermost node of a given type that contains the given
|
||||
// position. Interface similar to findNodeAt.
|
||||
function findNodeAround(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if (node.start > pos || node.end < pos) { return }
|
||||
visitNode(baseVisitor, type, node, st, c);
|
||||
if (test(type, node)) { throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
function skipThrough(node, st, c) { c(node, st); }
|
||||
function ignore(_node, _st, _c) {}
|
||||
|
||||
function visitNode(baseVisitor, type, node, st, c) {
|
||||
if (baseVisitor[type] == null) { throw new Error(("No walker function defined for node type " + type)) }
|
||||
baseVisitor[type](node, st, c);
|
||||
}
|
||||
|
||||
// Node walkers.
|
||||
|
||||
var base = {};
|
||||
|
||||
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var stmt = list[i];
|
||||
|
||||
c(stmt, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.Statement = skipThrough;
|
||||
base.EmptyStatement = ignore;
|
||||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
|
||||
function (node, st, c) { return c(node.expression, st, "Expression"); };
|
||||
base.IfStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Statement");
|
||||
if (node.alternate) { c(node.alternate, st, "Statement"); }
|
||||
};
|
||||
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
||||
base.BreakStatement = base.ContinueStatement = ignore;
|
||||
base.WithStatement = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.SwitchStatement = function (node, st, c) {
|
||||
c(node.discriminant, st, "Expression");
|
||||
for (var i = 0, list = node.cases; i < list.length; i += 1) {
|
||||
var cs = list[i];
|
||||
|
||||
c(cs, st);
|
||||
}
|
||||
};
|
||||
base.SwitchCase = function (node, st, c) {
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
|
||||
if (node.argument) { c(node.argument, st, "Expression"); }
|
||||
};
|
||||
base.ThrowStatement = base.SpreadElement =
|
||||
function (node, st, c) { return c(node.argument, st, "Expression"); };
|
||||
base.TryStatement = function (node, st, c) {
|
||||
c(node.block, st, "Statement");
|
||||
if (node.handler) { c(node.handler, st); }
|
||||
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
||||
};
|
||||
base.CatchClause = function (node, st, c) {
|
||||
if (node.param) { c(node.param, st, "Pattern"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForStatement = function (node, st, c) {
|
||||
if (node.init) { c(node.init, st, "ForInit"); }
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
if (node.update) { c(node.update, st, "Expression"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
|
||||
c(node.left, st, "ForInit");
|
||||
c(node.right, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInit = function (node, st, c) {
|
||||
if (node.type === "VariableDeclaration") { c(node, st); }
|
||||
else { c(node, st, "Expression"); }
|
||||
};
|
||||
base.DebuggerStatement = ignore;
|
||||
|
||||
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
||||
base.VariableDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
||||
{
|
||||
var decl = list[i];
|
||||
|
||||
c(decl, st);
|
||||
}
|
||||
};
|
||||
base.VariableDeclarator = function (node, st, c) {
|
||||
c(node.id, st, "Pattern");
|
||||
if (node.init) { c(node.init, st, "Expression"); }
|
||||
};
|
||||
|
||||
base.Function = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
for (var i = 0, list = node.params; i < list.length; i += 1)
|
||||
{
|
||||
var param = list[i];
|
||||
|
||||
c(param, st, "Pattern");
|
||||
}
|
||||
c(node.body, st, node.expression ? "Expression" : "Statement");
|
||||
};
|
||||
|
||||
base.Pattern = function (node, st, c) {
|
||||
if (node.type === "Identifier")
|
||||
{ c(node, st, "VariablePattern"); }
|
||||
else if (node.type === "MemberExpression")
|
||||
{ c(node, st, "MemberPattern"); }
|
||||
else
|
||||
{ c(node, st); }
|
||||
};
|
||||
base.VariablePattern = ignore;
|
||||
base.MemberPattern = skipThrough;
|
||||
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
||||
base.ArrayPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Pattern"); }
|
||||
}
|
||||
};
|
||||
base.ObjectPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
||||
var prop = list[i];
|
||||
|
||||
if (prop.type === "Property") {
|
||||
if (prop.computed) { c(prop.key, st, "Expression"); }
|
||||
c(prop.value, st, "Pattern");
|
||||
} else if (prop.type === "RestElement") {
|
||||
c(prop.argument, st, "Pattern");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
base.Expression = skipThrough;
|
||||
base.ThisExpression = base.Super = base.MetaProperty = ignore;
|
||||
base.ArrayExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Expression"); }
|
||||
}
|
||||
};
|
||||
base.ObjectExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1)
|
||||
{
|
||||
var prop = list[i];
|
||||
|
||||
c(prop, st);
|
||||
}
|
||||
};
|
||||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
|
||||
base.SequenceExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
||||
{
|
||||
var expr = list[i];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateLiteral = function (node, st, c) {
|
||||
for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
||||
{
|
||||
var quasi = list[i];
|
||||
|
||||
c(quasi, st);
|
||||
}
|
||||
|
||||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
||||
{
|
||||
var expr = list$1[i$1];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateElement = ignore;
|
||||
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
|
||||
c(node.argument, st, "Expression");
|
||||
};
|
||||
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
|
||||
c(node.left, st, "Expression");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
|
||||
c(node.left, st, "Pattern");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.ConditionalExpression = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Expression");
|
||||
c(node.alternate, st, "Expression");
|
||||
};
|
||||
base.NewExpression = base.CallExpression = function (node, st, c) {
|
||||
c(node.callee, st, "Expression");
|
||||
if (node.arguments)
|
||||
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
||||
{
|
||||
var arg = list[i];
|
||||
|
||||
c(arg, st, "Expression");
|
||||
} }
|
||||
};
|
||||
base.MemberExpression = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
if (node.computed) { c(node.property, st, "Expression"); }
|
||||
};
|
||||
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
|
||||
if (node.declaration)
|
||||
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
||||
if (node.source) { c(node.source, st, "Expression"); }
|
||||
if (node.attributes)
|
||||
{ for (var i = 0, list = node.attributes; i < list.length; i += 1)
|
||||
{
|
||||
var attr = list[i];
|
||||
|
||||
c(attr, st);
|
||||
} }
|
||||
};
|
||||
base.ExportAllDeclaration = function (node, st, c) {
|
||||
if (node.exported)
|
||||
{ c(node.exported, st); }
|
||||
c(node.source, st, "Expression");
|
||||
if (node.attributes)
|
||||
{ for (var i = 0, list = node.attributes; i < list.length; i += 1)
|
||||
{
|
||||
var attr = list[i];
|
||||
|
||||
c(attr, st);
|
||||
} }
|
||||
};
|
||||
base.ImportAttribute = function (node, st, c) {
|
||||
c(node.value, st, "Expression");
|
||||
};
|
||||
base.ImportDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
||||
{
|
||||
var spec = list[i];
|
||||
|
||||
c(spec, st);
|
||||
}
|
||||
c(node.source, st, "Expression");
|
||||
if (node.attributes)
|
||||
{ for (var i$1 = 0, list$1 = node.attributes; i$1 < list$1.length; i$1 += 1)
|
||||
{
|
||||
var attr = list$1[i$1];
|
||||
|
||||
c(attr, st);
|
||||
} }
|
||||
};
|
||||
base.ImportExpression = function (node, st, c) {
|
||||
c(node.source, st, "Expression");
|
||||
if (node.options) { c(node.options, st, "Expression"); }
|
||||
};
|
||||
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
|
||||
|
||||
base.TaggedTemplateExpression = function (node, st, c) {
|
||||
c(node.tag, st, "Expression");
|
||||
c(node.quasi, st, "Expression");
|
||||
};
|
||||
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
||||
base.Class = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
if (node.superClass) { c(node.superClass, st, "Expression"); }
|
||||
c(node.body, st);
|
||||
};
|
||||
base.ClassBody = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var elt = list[i];
|
||||
|
||||
c(elt, st);
|
||||
}
|
||||
};
|
||||
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
|
||||
if (node.computed) { c(node.key, st, "Expression"); }
|
||||
if (node.value) { c(node.value, st, "Expression"); }
|
||||
};
|
||||
|
||||
const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
|
||||
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
|
||||
To fix this issue you can either:
|
||||
- import the mocks API directly from 'vitest'
|
||||
- enable the 'globals' option`;
|
||||
function API_NOT_FOUND_CHECK(names) {
|
||||
return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
|
||||
}
|
||||
function isIdentifier(node) {
|
||||
return node.type === "Identifier";
|
||||
}
|
||||
function getNodeTail(code, node) {
|
||||
let end = node.end;
|
||||
if (code[node.end] === ";") {
|
||||
end += 1;
|
||||
}
|
||||
if (code[node.end] === "\n") {
|
||||
return end + 1;
|
||||
}
|
||||
if (code[node.end + 1] === "\n") {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
|
||||
const hashbangRE = /^#!.*\n/;
|
||||
// Public redistributions of Vitest that re-export its mocking API (`vi`)
|
||||
// verbatim under their own specifier. Imports from these are treated as the
|
||||
// hoisted module so `vi.mock()` is hoisted for e.g.
|
||||
// `import { vi } from 'vite-plus/test'`, exactly as it is for `vitest`.
|
||||
const REDISTRIBUTED_HOISTED_MODULES = ["vite-plus/test"];
|
||||
// this is a fork of Vite SSR transform
|
||||
function hoistMocks(code, id, parse, options = {}) {
|
||||
const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
|
||||
if (!needHoisting) {
|
||||
return;
|
||||
}
|
||||
const s = options.magicString?.() || new MagicString(code);
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(code);
|
||||
} catch (err) {
|
||||
console.error(`Cannot parse ${id}:\n${err.message}.`);
|
||||
return;
|
||||
}
|
||||
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
|
||||
"mock",
|
||||
"unmock",
|
||||
"doMock",
|
||||
"doUnmock"
|
||||
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
|
||||
// hoist at the start of the file, after the hashbang
|
||||
const hashbangEnd = hashbangRE.exec(code)?.[0].length ?? 0;
|
||||
let hoistIndex = hashbangEnd;
|
||||
let hoistedModuleImported = false;
|
||||
let uid = 0;
|
||||
const idToImportMap = new Map();
|
||||
const imports = [];
|
||||
// this will transform import statements into dynamic ones, if there are imports
|
||||
// it will keep the import as is, if we don't need to mock anything
|
||||
// in browser environment it will wrap the module value with "vitest_wrap_module" function
|
||||
// that returns a proxy to the module so that named exports can be mocked
|
||||
function defineImport(importNode) {
|
||||
const source = importNode.source.value;
|
||||
// always hoist vitest import to top of the file, so
|
||||
// "vi" helpers can access it. Vitest redistributions that re-export the
|
||||
// mocking API under their own specifier are recognized the same way.
|
||||
if (hoistedModule === source || REDISTRIBUTED_HOISTED_MODULES.includes(source)) {
|
||||
hoistedModuleImported = true;
|
||||
return;
|
||||
}
|
||||
const importId = `__vi_import_${uid++}__`;
|
||||
imports.push({
|
||||
id: importId,
|
||||
node: importNode
|
||||
});
|
||||
return importId;
|
||||
}
|
||||
// 1. check all import statements and record id -> importName map
|
||||
for (const node of ast.body) {
|
||||
// import foo from 'foo' --> foo -> __import_foo__.default
|
||||
// import { baz } from 'foo' --> baz -> __import_foo__.baz
|
||||
// import * as ok from 'foo' --> ok -> __import_foo__
|
||||
if (node.type === "ImportDeclaration") {
|
||||
const importId = defineImport(node);
|
||||
if (!importId) {
|
||||
continue;
|
||||
}
|
||||
for (const spec of node.specifiers) {
|
||||
if (spec.type === "ImportSpecifier") {
|
||||
if (spec.imported.type === "Identifier") {
|
||||
idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
|
||||
} else {
|
||||
idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
|
||||
}
|
||||
} else if (spec.type === "ImportDefaultSpecifier") {
|
||||
idToImportMap.set(spec.local.name, `${importId}.default`);
|
||||
} else {
|
||||
// namespace specifier
|
||||
idToImportMap.set(spec.local.name, importId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const declaredConst = new Set();
|
||||
const hoistedNodes = new Set();
|
||||
function createSyntaxError(node, message) {
|
||||
const _error = new SyntaxError(message);
|
||||
Error.captureStackTrace(_error, createSyntaxError);
|
||||
const serializedError = {
|
||||
name: "SyntaxError",
|
||||
message: _error.message,
|
||||
stack: _error.stack
|
||||
};
|
||||
if (options.codeFrameGenerator) {
|
||||
serializedError.frame = options.codeFrameGenerator(node, id, code);
|
||||
}
|
||||
return serializedError;
|
||||
}
|
||||
function assertNotDefaultExport(node, error) {
|
||||
const defaultExport = findNodeAround(ast, node.start, "ExportDefaultDeclaration")?.node;
|
||||
if (defaultExport?.declaration === node || defaultExport?.declaration.type === "AwaitExpression" && defaultExport.declaration.argument === node) {
|
||||
throw createSyntaxError(defaultExport, error);
|
||||
}
|
||||
}
|
||||
function assertNotNamedExport(node, error) {
|
||||
const nodeExported = findNodeAround(ast, node.start, "ExportNamedDeclaration")?.node;
|
||||
if (nodeExported?.declaration === node) {
|
||||
throw createSyntaxError(nodeExported, error);
|
||||
}
|
||||
}
|
||||
function getVariableDeclaration(node) {
|
||||
const declarationNode = findNodeAround(ast, node.start, "VariableDeclaration")?.node;
|
||||
const init = declarationNode?.declarations[0]?.init;
|
||||
if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
|
||||
return declarationNode;
|
||||
}
|
||||
}
|
||||
const usedUtilityExports = new Set();
|
||||
let hasImportMetaVitest = false;
|
||||
esmWalker(ast, {
|
||||
onImportMeta(node) {
|
||||
const property = code.slice(node.end, node.end + 7);
|
||||
if (property === ".vitest") {
|
||||
hasImportMetaVitest = true;
|
||||
}
|
||||
},
|
||||
onIdentifier(id, info, parentStack) {
|
||||
const binding = idToImportMap.get(id.name);
|
||||
if (!binding) {
|
||||
return;
|
||||
}
|
||||
if (info.hasBindingShortcut) {
|
||||
s.appendLeft(id.end, `: ${binding}`);
|
||||
} else if (info.classDeclaration) {
|
||||
if (!declaredConst.has(id.name)) {
|
||||
declaredConst.add(id.name);
|
||||
// locate the top-most node containing the class declaration
|
||||
const topNode = parentStack[parentStack.length - 2];
|
||||
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
|
||||
}
|
||||
} else if (!info.classExpression) {
|
||||
s.update(id.start, id.end, binding);
|
||||
}
|
||||
},
|
||||
onDynamicImport(_node) {
|
||||
// TODO: vi.mock(import) breaks it, and vi.mock('', () => import) also does,
|
||||
// only move imports that are outside of vi.mock
|
||||
// backwards compat, don't do if not passed
|
||||
// if (!options.globalThisAccessor) {
|
||||
// return
|
||||
// }
|
||||
// const globalThisAccessor = options.globalThisAccessor
|
||||
// const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`
|
||||
// const importSubstring = code.substring(node.start, node.end)
|
||||
// const hasIgnore = importSubstring.includes('/* @vite-ignore */')
|
||||
// s.overwrite(
|
||||
// node.start,
|
||||
// (node.source as Positioned<Expression>).start,
|
||||
// replaceString + (hasIgnore ? '/* @vite-ignore */ ' : ''),
|
||||
// )
|
||||
// s.overwrite(node.end - 1, node.end, '))')
|
||||
},
|
||||
onCallExpression(node) {
|
||||
if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
|
||||
const methodName = node.callee.property.name;
|
||||
usedUtilityExports.add(node.callee.object.name);
|
||||
if (hoistableMockMethodNames.includes(methodName)) {
|
||||
const method = `${node.callee.object.name}.${methodName}`;
|
||||
assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
|
||||
const declarationNode = getVariableDeclaration(node);
|
||||
if (declarationNode) {
|
||||
assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
|
||||
}
|
||||
// rewrite vi.mock(import('..')) into vi.mock('..')
|
||||
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
|
||||
const moduleInfo = node.arguments[0];
|
||||
// vi.mock(import('./path')) -> vi.mock('./path')
|
||||
if (moduleInfo.type === "ImportExpression") {
|
||||
const source = moduleInfo.source;
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
// vi.mock(await import('./path')) -> vi.mock('./path')
|
||||
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
|
||||
const source = moduleInfo.argument.source;
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
}
|
||||
hoistedNodes.add(node);
|
||||
} else if (dynamicImportMockMethodNames.includes(methodName)) {
|
||||
const moduleInfo = node.arguments[0];
|
||||
let source = null;
|
||||
if (moduleInfo.type === "ImportExpression") {
|
||||
source = moduleInfo.source;
|
||||
}
|
||||
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
|
||||
source = moduleInfo.argument.source;
|
||||
}
|
||||
if (source) {
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
}
|
||||
if (hoistedMethodNames.includes(methodName)) {
|
||||
assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
|
||||
const declarationNode = getVariableDeclaration(node);
|
||||
if (declarationNode) {
|
||||
assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
|
||||
// hoist "const variable = vi.hoisted(() => {})"
|
||||
hoistedNodes.add(declarationNode);
|
||||
} else {
|
||||
const awaitedExpression = findNodeAround(ast, node.start, "AwaitExpression")?.node;
|
||||
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
|
||||
const moveNode = awaitedExpression?.argument === node ? awaitedExpression : node;
|
||||
hoistedNodes.add(moveNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
function getNodeName(node) {
|
||||
const callee = node.callee || {};
|
||||
if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
|
||||
const argument = node.arguments[0];
|
||||
const argStr = argument.type === "Literal" || argument.type === "ImportExpression" ? code.slice(argument.start, argument.end) : "";
|
||||
return `${callee.object.name}.${callee.property.name}(${argStr})`;
|
||||
}
|
||||
return "\"hoisted method\"";
|
||||
}
|
||||
function getNodeCall(node) {
|
||||
if (node.type === "CallExpression") {
|
||||
return node;
|
||||
}
|
||||
if (node.type === "VariableDeclaration") {
|
||||
const { declarations } = node;
|
||||
const init = declarations[0].init;
|
||||
if (init) {
|
||||
return getNodeCall(init);
|
||||
}
|
||||
}
|
||||
if (node.type === "AwaitExpression") {
|
||||
const { argument } = node;
|
||||
if (argument.type === "CallExpression") {
|
||||
return getNodeCall(argument);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function createError(outsideNode, insideNode) {
|
||||
const outsideCall = getNodeCall(outsideNode);
|
||||
const insideCall = getNodeCall(insideNode);
|
||||
throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
|
||||
}
|
||||
// validate hoistedNodes doesn't have nodes inside other nodes
|
||||
const arrayNodes = Array.from(hoistedNodes);
|
||||
for (let i = 0; i < arrayNodes.length; i++) {
|
||||
const node = arrayNodes[i];
|
||||
for (let j = i + 1; j < arrayNodes.length; j++) {
|
||||
const otherNode = arrayNodes[j];
|
||||
if (node.start >= otherNode.start && node.end <= otherNode.end) {
|
||||
throw createError(otherNode, node);
|
||||
}
|
||||
if (otherNode.start >= node.start && otherNode.end <= node.end) {
|
||||
throw createError(node, otherNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
// validate that hoisted nodes are defined on the top level
|
||||
// ignore `import.meta.vitest` because it needs to be inside an IfStatement
|
||||
// and it can be used anywhere in the code (inside methods too)
|
||||
if (!hasImportMetaVitest) {
|
||||
for (const node of ast.body) {
|
||||
hoistedNodes.delete(node);
|
||||
if (node.type === "ExpressionStatement") {
|
||||
hoistedNodes.delete(node.expression);
|
||||
}
|
||||
}
|
||||
for (const invalidNode of hoistedNodes) {
|
||||
console.warn(`Warning: A ${getNodeName(getNodeCall(invalidNode))} call in "${id}" is not at the top level of the module. ` + `Although it appears nested, it will be hoisted and executed before any tests run. ` + `Move it to the top level to reflect its actual execution order. This will become an error in a future version.\n` + `See: https://vitest.dev/guide/mocking/modules#how-it-works`);
|
||||
}
|
||||
}
|
||||
// hoist vi.mock/vi.hoisted
|
||||
for (const node of arrayNodes) {
|
||||
const end = getNodeTail(code, node);
|
||||
// don't hoist into itself if it's already at the top
|
||||
if (hoistIndex === end || hoistIndex === node.start) {
|
||||
hoistIndex = end;
|
||||
} else {
|
||||
s.move(node.start, end, hoistIndex);
|
||||
}
|
||||
}
|
||||
// hoist actual dynamic imports last so they are inserted after all hoisted mocks
|
||||
for (const { node: importNode, id: importId } of imports) {
|
||||
const source = importNode.source.value;
|
||||
const sourceString = JSON.stringify(source);
|
||||
let importLine = `const ${importId} = await `;
|
||||
if (options.globalThisAccessor) {
|
||||
importLine += `globalThis[${options.globalThisAccessor}].wrapDynamicImport(() => import(${sourceString}));\n`;
|
||||
} else {
|
||||
importLine += `import(${sourceString});\n`;
|
||||
}
|
||||
s.update(importNode.start, importNode.end, importLine);
|
||||
if (importNode.start === hoistIndex) {
|
||||
// no need to hoist, but update hoistIndex to keep the order
|
||||
hoistIndex = importNode.end;
|
||||
} else {
|
||||
// There will be an error if the module is called before it is imported,
|
||||
// so the module import statement is hoisted to the top
|
||||
s.move(importNode.start, importNode.end, hoistIndex);
|
||||
}
|
||||
}
|
||||
if (!hoistedModuleImported && arrayNodes.length > 0) {
|
||||
const utilityImports = [...usedUtilityExports];
|
||||
// "vi" or "vitest" is imported from a module other than "vitest"
|
||||
if (utilityImports.some((name) => idToImportMap.has(name))) {
|
||||
s.appendLeft(hashbangEnd, API_NOT_FOUND_CHECK(utilityImports));
|
||||
} else if (utilityImports.length) {
|
||||
s.appendLeft(hashbangEnd, `import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export { hoistMocks as h };
|
||||
+41
-30
@@ -1,25 +1,8 @@
|
||||
import { c as createSimpleStackTrace } from './chunk-helpers.js';
|
||||
import { mockObject } from './index.js';
|
||||
import { M as MockerRegistry, R as RedirectedModule, A as AutomockedModule } from './chunk-registry.js';
|
||||
import { e as extname, j as join } from './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
/**
|
||||
* Get original stacktrace without source map support the most performant way.
|
||||
* - Create only 1 stack frame.
|
||||
* - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
|
||||
*/
|
||||
function createSimpleStackTrace(options) {
|
||||
const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
|
||||
const limit = Error.stackTraceLimit;
|
||||
const prepareStackTrace = Error.prepareStackTrace;
|
||||
Error.stackTraceLimit = stackTraceLimit;
|
||||
Error.prepareStackTrace = (e) => e.stack;
|
||||
const err = new Error(message);
|
||||
const stackTrace = err.stack || "";
|
||||
Error.prepareStackTrace = prepareStackTrace;
|
||||
Error.stackTraceLimit = limit;
|
||||
return stackTrace;
|
||||
}
|
||||
|
||||
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input) {
|
||||
@@ -126,6 +109,8 @@ for (let i = 0; i < chars.length; i++) {
|
||||
}
|
||||
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
|
||||
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
|
||||
const NOW_LENGTH = Date.now().toString().length;
|
||||
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
|
||||
function extractLocation(urlLike) {
|
||||
// Fail-fast but return locations like "(native)"
|
||||
if (!urlLike.includes(":")) {
|
||||
@@ -150,6 +135,9 @@ function extractLocation(urlLike) {
|
||||
const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
|
||||
url = url.slice(isWindows ? 5 : 4);
|
||||
}
|
||||
if (url.includes("vitest=")) {
|
||||
url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
|
||||
}
|
||||
return [
|
||||
url,
|
||||
parts[2] || undefined,
|
||||
@@ -243,7 +231,7 @@ function parseSingleV8Stack(raw) {
|
||||
// normalize Windows path (\ -> /)
|
||||
file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
|
||||
if (method) {
|
||||
method = method.replace(/__vite_ssr_import_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
|
||||
method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
|
||||
}
|
||||
return {
|
||||
method,
|
||||
@@ -254,7 +242,7 @@ function parseSingleV8Stack(raw) {
|
||||
}
|
||||
|
||||
function createCompilerHints(options) {
|
||||
const globalThisAccessor = (options === null || options === void 0 ? void 0 : options.globalThisKey) || "__vitest_mocker__";
|
||||
const globalThisAccessor = options?.globalThisKey || "__vitest_mocker__";
|
||||
function _mocker() {
|
||||
// @ts-expect-error injected by the plugin
|
||||
return typeof globalThis[globalThisAccessor] !== "undefined" ? globalThis[globalThisAccessor] : new Proxy({}, { get(_, name) {
|
||||
@@ -310,7 +298,7 @@ function getImporter(name) {
|
||||
return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`);
|
||||
});
|
||||
const stack = /* @__PURE__ */ parseSingleStack(stackArray[importerStackIndex + 1]);
|
||||
return (stack === null || stack === void 0 ? void 0 : stack.file) || "";
|
||||
return stack?.file || "";
|
||||
}
|
||||
|
||||
const hot = import.meta.hot || {
|
||||
@@ -385,7 +373,7 @@ class ModuleMocker {
|
||||
throw new Error(`[vitest] Cannot resolve "${id}" imported from "${importer}"`);
|
||||
}
|
||||
const ext = extname(resolved.id);
|
||||
const url = new URL(resolved.url, location.href);
|
||||
const url = new URL(resolved.url, this.getBaseUrl());
|
||||
const query = `_vitest_original&ext${ext}`;
|
||||
const actualUrl = `${url.pathname}${url.search ? `${url.search}&${query}` : `?${query}`}${url.hash}`;
|
||||
return this.wrapDynamicImport(() => import(
|
||||
@@ -397,12 +385,15 @@ class ModuleMocker {
|
||||
}
|
||||
// vite injects this helper for optimized modules, so we try to follow the same behavior
|
||||
const m = mod.default;
|
||||
return (m === null || m === void 0 ? void 0 : m.__esModule) ? m : {
|
||||
return m?.__esModule ? m : {
|
||||
...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
|
||||
default: m
|
||||
};
|
||||
});
|
||||
}
|
||||
getBaseUrl() {
|
||||
return location.href;
|
||||
}
|
||||
async importMock(rawId, importer) {
|
||||
await this.prepare();
|
||||
const { resolvedId, resolvedUrl, redirectUrl } = await this.rpc.resolveMock(rawId, importer, { mock: "auto" });
|
||||
@@ -410,7 +401,7 @@ class ModuleMocker {
|
||||
let mock = this.registry.get(mockUrl);
|
||||
if (!mock) {
|
||||
if (redirectUrl) {
|
||||
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString();
|
||||
const resolvedRedirect = new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString();
|
||||
mock = new RedirectedModule(rawId, resolvedId, mockUrl, resolvedRedirect);
|
||||
} else {
|
||||
mock = new AutomockedModule(rawId, resolvedId, mockUrl);
|
||||
@@ -420,7 +411,7 @@ class ModuleMocker {
|
||||
return await mock.resolve();
|
||||
}
|
||||
if (mock.type === "automock" || mock.type === "autospy") {
|
||||
const url = new URL(`/@id/${resolvedId}`, location.href);
|
||||
const url = new URL(`/@id/${resolvedId}`, this.getBaseUrl());
|
||||
const query = url.search ? `${url.search}&t=${now()}` : `?t=${now()}`;
|
||||
const moduleObject = await import(
|
||||
/* @vite-ignore */
|
||||
@@ -433,8 +424,16 @@ class ModuleMocker {
|
||||
mock.redirect
|
||||
);
|
||||
}
|
||||
mockObject(object, moduleType = "automock") {
|
||||
return mockObject({
|
||||
mockObject(object, mockExportsOrModuleType, moduleType) {
|
||||
let mockExports;
|
||||
if (mockExportsOrModuleType === "automock" || mockExportsOrModuleType === "autospy") {
|
||||
moduleType = mockExportsOrModuleType;
|
||||
mockExports = undefined;
|
||||
} else {
|
||||
mockExports = mockExportsOrModuleType;
|
||||
}
|
||||
moduleType ??= "automock";
|
||||
const result = mockObject({
|
||||
globalConstructors: {
|
||||
Object,
|
||||
Function,
|
||||
@@ -444,10 +443,14 @@ class ModuleMocker {
|
||||
},
|
||||
createMockInstance: this.createMockInstance,
|
||||
type: moduleType
|
||||
}, object);
|
||||
}, object, mockExports);
|
||||
return result;
|
||||
}
|
||||
getMockContext() {
|
||||
return { callstack: null };
|
||||
}
|
||||
queueMock(rawId, importer, factoryOrOptions) {
|
||||
const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : (factoryOrOptions === null || factoryOrOptions === void 0 ? void 0 : factoryOrOptions.spy) ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
|
||||
const promise = this.rpc.resolveMock(rawId, importer, { mock: typeof factoryOrOptions === "function" ? "factory" : factoryOrOptions?.spy ? "spy" : "auto" }).then(async ({ redirectUrl, resolvedId, resolvedUrl, needsInterop, mockType }) => {
|
||||
const mockUrl = this.resolveMockPath(cleanVersion(resolvedUrl));
|
||||
this.mockedIds.add(resolvedId);
|
||||
const factory = typeof factoryOrOptions === "function" ? async () => {
|
||||
@@ -456,7 +459,7 @@ class ModuleMocker {
|
||||
// merges all exports from default into the module object
|
||||
return needsInterop ? { default: data } : data;
|
||||
} : undefined;
|
||||
const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), location.href).toString() : null;
|
||||
const mockRedirect = typeof redirectUrl === "string" ? new URL(this.resolveMockPath(cleanVersion(redirectUrl)), this.getBaseUrl()).toString() : null;
|
||||
let module;
|
||||
if (mockType === "manual") {
|
||||
module = this.registry.register("manual", rawId, resolvedId, mockUrl, factory);
|
||||
@@ -500,6 +503,14 @@ class ModuleMocker {
|
||||
}
|
||||
return moduleFactory;
|
||||
}
|
||||
getMockedModuleById(id) {
|
||||
return this.registry.getById(id);
|
||||
}
|
||||
reset() {
|
||||
this.registry.clear();
|
||||
this.mockedIds.clear();
|
||||
this.queue.clear();
|
||||
}
|
||||
resolveMockPath(path) {
|
||||
const config = this.config;
|
||||
const fsRoot = join("/@fs/", config.root);
|
||||
|
||||
+21
-7
@@ -152,21 +152,25 @@ class ManualMockedModule {
|
||||
this.url = url;
|
||||
this.factory = factory;
|
||||
}
|
||||
async resolve() {
|
||||
resolve() {
|
||||
if (this.cache) {
|
||||
return this.cache;
|
||||
}
|
||||
let exports$1;
|
||||
try {
|
||||
exports$1 = await this.factory();
|
||||
exports$1 = this.factory();
|
||||
} catch (err) {
|
||||
const vitestError = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock");
|
||||
vitestError.cause = err;
|
||||
throw vitestError;
|
||||
throw createHelpfulError(err);
|
||||
}
|
||||
if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
|
||||
throw new TypeError(`[vitest] vi.mock("${this.raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
|
||||
if (typeof exports$1 === "object" && typeof exports$1?.then === "function") {
|
||||
return exports$1.then((result) => {
|
||||
assertValidExports(this.raw, result);
|
||||
return this.cache = result;
|
||||
}, (error) => {
|
||||
throw createHelpfulError(error);
|
||||
});
|
||||
}
|
||||
assertValidExports(this.raw, exports$1);
|
||||
return this.cache = exports$1;
|
||||
}
|
||||
static fromJSON(data, factory) {
|
||||
@@ -181,5 +185,15 @@ class ManualMockedModule {
|
||||
};
|
||||
}
|
||||
}
|
||||
function createHelpfulError(cause) {
|
||||
const error = new Error("[vitest] There was an error when mocking a module. " + "If you are using \"vi.mock\" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. " + "Read more: https://vitest.dev/api/vi.html#vi-mock");
|
||||
error.cause = cause;
|
||||
return error;
|
||||
}
|
||||
function assertValidExports(raw, exports$1) {
|
||||
if (exports$1 === null || typeof exports$1 !== "object" || Array.isArray(exports$1)) {
|
||||
throw new TypeError(`[vitest] vi.mock("${raw}", factory?: () => unknown) is not returning an object. Did you mean to return an object with a "default" key?`);
|
||||
}
|
||||
}
|
||||
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, ManualMockedModule as a, AutospiedModule as b };
|
||||
|
||||
+18
-7
@@ -3,14 +3,25 @@ function cleanUrl(url) {
|
||||
return url.replace(postfixRE, "");
|
||||
}
|
||||
function createManualModuleSource(moduleUrl, exports$1, globalAccessor = "\"__vitest_mocker__\"") {
|
||||
const source = `const module = globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");`;
|
||||
const keys = exports$1.map((name) => {
|
||||
if (name === "default") {
|
||||
return `export default module["default"];`;
|
||||
}
|
||||
return `export const ${name} = module["${name}"];`;
|
||||
const source = `
|
||||
const __factoryModule__ = await globalThis[${globalAccessor}].getFactoryModule("${moduleUrl}");
|
||||
`;
|
||||
const keys = exports$1.map((name, index) => {
|
||||
return `let __${index} = __factoryModule__["${name}"]
|
||||
export { __${index} as "${name}" }`;
|
||||
}).join("\n");
|
||||
return `${source}\n${keys}`;
|
||||
let code = `${source}\n${keys}`;
|
||||
// this prevents recursion
|
||||
code += `
|
||||
if (__factoryModule__.__factoryPromise != null) {
|
||||
__factoryModule__.__factoryPromise.then((resolvedModule) => {
|
||||
${exports$1.map((name, index) => {
|
||||
return `__${index} = resolvedModule["${name}"];`;
|
||||
}).join("\n")}
|
||||
})
|
||||
}
|
||||
`;
|
||||
return code;
|
||||
}
|
||||
|
||||
export { cleanUrl as a, createManualModuleSource as c };
|
||||
|
||||
+739
@@ -0,0 +1,739 @@
|
||||
import MagicString from 'magic-string';
|
||||
|
||||
declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string;
|
||||
|
||||
// This definition file follows a somewhat unusual format. ESTree allows
|
||||
// runtime type checks based on the `type` parameter. In order to explain this
|
||||
// to typescript we want to use discriminated union types:
|
||||
// https://github.com/Microsoft/TypeScript/pull/9163
|
||||
//
|
||||
// For ESTree this is a bit tricky because the high level interfaces like
|
||||
// Node or Function are pulling double duty. We want to pass common fields down
|
||||
// to the interfaces that extend them (like Identifier or
|
||||
// ArrowFunctionExpression), but you can't extend a type union or enforce
|
||||
// common fields on them. So we've split the high level interfaces into two
|
||||
// types, a base type which passes down inherited fields, and a type union of
|
||||
// all types which extend the base type. Only the type union is exported, and
|
||||
// the union is how other types refer to the collection of inheriting types.
|
||||
//
|
||||
// This makes the definitions file here somewhat more difficult to maintain,
|
||||
// but it has the notable advantage of making ESTree much easier to use as
|
||||
// an end user.
|
||||
|
||||
interface BaseNodeWithoutComments {
|
||||
// Every leaf interface that extends BaseNode must specify a type property.
|
||||
// The type property should be a string literal. For example, Identifier
|
||||
// has: `type: "Identifier"`
|
||||
type: string;
|
||||
loc?: SourceLocation | null | undefined;
|
||||
range?: [number, number] | undefined;
|
||||
}
|
||||
|
||||
interface BaseNode extends BaseNodeWithoutComments {
|
||||
leadingComments?: Comment[] | undefined;
|
||||
trailingComments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface NodeMap {
|
||||
AssignmentProperty: AssignmentProperty;
|
||||
CatchClause: CatchClause;
|
||||
Class: Class;
|
||||
ClassBody: ClassBody;
|
||||
Expression: Expression;
|
||||
Function: Function;
|
||||
Identifier: Identifier;
|
||||
Literal: Literal;
|
||||
MethodDefinition: MethodDefinition;
|
||||
ModuleDeclaration: ModuleDeclaration;
|
||||
ModuleSpecifier: ModuleSpecifier;
|
||||
Pattern: Pattern;
|
||||
PrivateIdentifier: PrivateIdentifier;
|
||||
Program: Program;
|
||||
Property: Property;
|
||||
PropertyDefinition: PropertyDefinition;
|
||||
SpreadElement: SpreadElement;
|
||||
Statement: Statement;
|
||||
Super: Super;
|
||||
SwitchCase: SwitchCase;
|
||||
TemplateElement: TemplateElement;
|
||||
VariableDeclarator: VariableDeclarator;
|
||||
}
|
||||
|
||||
type Node$1 = NodeMap[keyof NodeMap];
|
||||
|
||||
interface Comment extends BaseNodeWithoutComments {
|
||||
type: "Line" | "Block";
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface SourceLocation {
|
||||
source?: string | null | undefined;
|
||||
start: Position;
|
||||
end: Position;
|
||||
}
|
||||
|
||||
interface Position {
|
||||
/** >= 1 */
|
||||
line: number;
|
||||
/** >= 0 */
|
||||
column: number;
|
||||
}
|
||||
|
||||
interface Program extends BaseNode {
|
||||
type: "Program";
|
||||
sourceType: "script" | "module";
|
||||
body: Array<Directive | Statement | ModuleDeclaration>;
|
||||
comments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface Directive extends BaseNode {
|
||||
type: "ExpressionStatement";
|
||||
expression: Literal;
|
||||
directive: string;
|
||||
}
|
||||
|
||||
interface BaseFunction extends BaseNode {
|
||||
params: Pattern[];
|
||||
generator?: boolean | undefined;
|
||||
async?: boolean | undefined;
|
||||
// The body is either BlockStatement or Expression because arrow functions
|
||||
// can have a body that's either. FunctionDeclarations and
|
||||
// FunctionExpressions have only BlockStatement bodies.
|
||||
body: BlockStatement | Expression;
|
||||
}
|
||||
|
||||
type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
|
||||
|
||||
type Statement =
|
||||
| ExpressionStatement
|
||||
| BlockStatement
|
||||
| StaticBlock
|
||||
| EmptyStatement
|
||||
| DebuggerStatement
|
||||
| WithStatement
|
||||
| ReturnStatement
|
||||
| LabeledStatement
|
||||
| BreakStatement
|
||||
| ContinueStatement
|
||||
| IfStatement
|
||||
| SwitchStatement
|
||||
| ThrowStatement
|
||||
| TryStatement
|
||||
| WhileStatement
|
||||
| DoWhileStatement
|
||||
| ForStatement
|
||||
| ForInStatement
|
||||
| ForOfStatement
|
||||
| Declaration;
|
||||
|
||||
interface BaseStatement extends BaseNode {}
|
||||
|
||||
interface EmptyStatement extends BaseStatement {
|
||||
type: "EmptyStatement";
|
||||
}
|
||||
|
||||
interface BlockStatement extends BaseStatement {
|
||||
type: "BlockStatement";
|
||||
body: Statement[];
|
||||
innerComments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface StaticBlock extends Omit<BlockStatement, "type"> {
|
||||
type: "StaticBlock";
|
||||
}
|
||||
|
||||
interface ExpressionStatement extends BaseStatement {
|
||||
type: "ExpressionStatement";
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
interface IfStatement extends BaseStatement {
|
||||
type: "IfStatement";
|
||||
test: Expression;
|
||||
consequent: Statement;
|
||||
alternate?: Statement | null | undefined;
|
||||
}
|
||||
|
||||
interface LabeledStatement extends BaseStatement {
|
||||
type: "LabeledStatement";
|
||||
label: Identifier;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface BreakStatement extends BaseStatement {
|
||||
type: "BreakStatement";
|
||||
label?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface ContinueStatement extends BaseStatement {
|
||||
type: "ContinueStatement";
|
||||
label?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface WithStatement extends BaseStatement {
|
||||
type: "WithStatement";
|
||||
object: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface SwitchStatement extends BaseStatement {
|
||||
type: "SwitchStatement";
|
||||
discriminant: Expression;
|
||||
cases: SwitchCase[];
|
||||
}
|
||||
|
||||
interface ReturnStatement extends BaseStatement {
|
||||
type: "ReturnStatement";
|
||||
argument?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ThrowStatement extends BaseStatement {
|
||||
type: "ThrowStatement";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface TryStatement extends BaseStatement {
|
||||
type: "TryStatement";
|
||||
block: BlockStatement;
|
||||
handler?: CatchClause | null | undefined;
|
||||
finalizer?: BlockStatement | null | undefined;
|
||||
}
|
||||
|
||||
interface WhileStatement extends BaseStatement {
|
||||
type: "WhileStatement";
|
||||
test: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface DoWhileStatement extends BaseStatement {
|
||||
type: "DoWhileStatement";
|
||||
body: Statement;
|
||||
test: Expression;
|
||||
}
|
||||
|
||||
interface ForStatement extends BaseStatement {
|
||||
type: "ForStatement";
|
||||
init?: VariableDeclaration | Expression | null | undefined;
|
||||
test?: Expression | null | undefined;
|
||||
update?: Expression | null | undefined;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface BaseForXStatement extends BaseStatement {
|
||||
left: VariableDeclaration | Pattern;
|
||||
right: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface ForInStatement extends BaseForXStatement {
|
||||
type: "ForInStatement";
|
||||
}
|
||||
|
||||
interface DebuggerStatement extends BaseStatement {
|
||||
type: "DebuggerStatement";
|
||||
}
|
||||
|
||||
type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
|
||||
|
||||
interface BaseDeclaration extends BaseStatement {}
|
||||
|
||||
interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
|
||||
type: "FunctionDeclaration";
|
||||
/** It is null when a function declaration is a part of the `export default function` statement */
|
||||
id: Identifier | null;
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
|
||||
id: Identifier;
|
||||
}
|
||||
|
||||
interface VariableDeclaration extends BaseDeclaration {
|
||||
type: "VariableDeclaration";
|
||||
declarations: VariableDeclarator[];
|
||||
kind: "var" | "let" | "const" | "using" | "await using";
|
||||
}
|
||||
|
||||
interface VariableDeclarator extends BaseNode {
|
||||
type: "VariableDeclarator";
|
||||
id: Pattern;
|
||||
init?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ExpressionMap {
|
||||
ArrayExpression: ArrayExpression;
|
||||
ArrowFunctionExpression: ArrowFunctionExpression;
|
||||
AssignmentExpression: AssignmentExpression;
|
||||
AwaitExpression: AwaitExpression;
|
||||
BinaryExpression: BinaryExpression;
|
||||
CallExpression: CallExpression;
|
||||
ChainExpression: ChainExpression;
|
||||
ClassExpression: ClassExpression;
|
||||
ConditionalExpression: ConditionalExpression;
|
||||
FunctionExpression: FunctionExpression;
|
||||
Identifier: Identifier;
|
||||
ImportExpression: ImportExpression;
|
||||
Literal: Literal;
|
||||
LogicalExpression: LogicalExpression;
|
||||
MemberExpression: MemberExpression;
|
||||
MetaProperty: MetaProperty;
|
||||
NewExpression: NewExpression;
|
||||
ObjectExpression: ObjectExpression;
|
||||
SequenceExpression: SequenceExpression;
|
||||
TaggedTemplateExpression: TaggedTemplateExpression;
|
||||
TemplateLiteral: TemplateLiteral;
|
||||
ThisExpression: ThisExpression;
|
||||
UnaryExpression: UnaryExpression;
|
||||
UpdateExpression: UpdateExpression;
|
||||
YieldExpression: YieldExpression;
|
||||
}
|
||||
|
||||
type Expression = ExpressionMap[keyof ExpressionMap];
|
||||
|
||||
interface BaseExpression extends BaseNode {}
|
||||
|
||||
type ChainElement = SimpleCallExpression | MemberExpression;
|
||||
|
||||
interface ChainExpression extends BaseExpression {
|
||||
type: "ChainExpression";
|
||||
expression: ChainElement;
|
||||
}
|
||||
|
||||
interface ThisExpression extends BaseExpression {
|
||||
type: "ThisExpression";
|
||||
}
|
||||
|
||||
interface ArrayExpression extends BaseExpression {
|
||||
type: "ArrayExpression";
|
||||
elements: Array<Expression | SpreadElement | null>;
|
||||
}
|
||||
|
||||
interface ObjectExpression extends BaseExpression {
|
||||
type: "ObjectExpression";
|
||||
properties: Array<Property | SpreadElement>;
|
||||
}
|
||||
|
||||
interface PrivateIdentifier extends BaseNode {
|
||||
type: "PrivateIdentifier";
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Property extends BaseNode {
|
||||
type: "Property";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value: Expression | Pattern; // Could be an AssignmentProperty
|
||||
kind: "init" | "get" | "set";
|
||||
method: boolean;
|
||||
shorthand: boolean;
|
||||
computed: boolean;
|
||||
}
|
||||
|
||||
interface PropertyDefinition extends BaseNode {
|
||||
type: "PropertyDefinition";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value?: Expression | null | undefined;
|
||||
computed: boolean;
|
||||
static: boolean;
|
||||
}
|
||||
|
||||
interface FunctionExpression extends BaseFunction, BaseExpression {
|
||||
id?: Identifier | null | undefined;
|
||||
type: "FunctionExpression";
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface SequenceExpression extends BaseExpression {
|
||||
type: "SequenceExpression";
|
||||
expressions: Expression[];
|
||||
}
|
||||
|
||||
interface UnaryExpression extends BaseExpression {
|
||||
type: "UnaryExpression";
|
||||
operator: UnaryOperator;
|
||||
prefix: true;
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface BinaryExpression extends BaseExpression {
|
||||
type: "BinaryExpression";
|
||||
operator: BinaryOperator;
|
||||
left: Expression | PrivateIdentifier;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface AssignmentExpression extends BaseExpression {
|
||||
type: "AssignmentExpression";
|
||||
operator: AssignmentOperator;
|
||||
left: Pattern | MemberExpression;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface UpdateExpression extends BaseExpression {
|
||||
type: "UpdateExpression";
|
||||
operator: UpdateOperator;
|
||||
argument: Expression;
|
||||
prefix: boolean;
|
||||
}
|
||||
|
||||
interface LogicalExpression extends BaseExpression {
|
||||
type: "LogicalExpression";
|
||||
operator: LogicalOperator;
|
||||
left: Expression;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface ConditionalExpression extends BaseExpression {
|
||||
type: "ConditionalExpression";
|
||||
test: Expression;
|
||||
alternate: Expression;
|
||||
consequent: Expression;
|
||||
}
|
||||
|
||||
interface BaseCallExpression extends BaseExpression {
|
||||
callee: Expression | Super;
|
||||
arguments: Array<Expression | SpreadElement>;
|
||||
}
|
||||
type CallExpression = SimpleCallExpression | NewExpression;
|
||||
|
||||
interface SimpleCallExpression extends BaseCallExpression {
|
||||
type: "CallExpression";
|
||||
optional: boolean;
|
||||
}
|
||||
|
||||
interface NewExpression extends BaseCallExpression {
|
||||
type: "NewExpression";
|
||||
}
|
||||
|
||||
interface MemberExpression extends BaseExpression, BasePattern {
|
||||
type: "MemberExpression";
|
||||
object: Expression | Super;
|
||||
property: Expression | PrivateIdentifier;
|
||||
computed: boolean;
|
||||
optional: boolean;
|
||||
}
|
||||
|
||||
type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
|
||||
|
||||
interface BasePattern extends BaseNode {}
|
||||
|
||||
interface SwitchCase extends BaseNode {
|
||||
type: "SwitchCase";
|
||||
test?: Expression | null | undefined;
|
||||
consequent: Statement[];
|
||||
}
|
||||
|
||||
interface CatchClause extends BaseNode {
|
||||
type: "CatchClause";
|
||||
param: Pattern | null;
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface Identifier extends BaseNode, BaseExpression, BasePattern {
|
||||
type: "Identifier";
|
||||
name: string;
|
||||
}
|
||||
|
||||
type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
|
||||
|
||||
interface SimpleLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value: string | boolean | number | null;
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
interface RegExpLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value?: RegExp | null | undefined;
|
||||
regex: {
|
||||
pattern: string;
|
||||
flags: string;
|
||||
};
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
interface BigIntLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value?: bigint | null | undefined;
|
||||
bigint: string;
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
|
||||
|
||||
type BinaryOperator =
|
||||
| "=="
|
||||
| "!="
|
||||
| "==="
|
||||
| "!=="
|
||||
| "<"
|
||||
| "<="
|
||||
| ">"
|
||||
| ">="
|
||||
| "<<"
|
||||
| ">>"
|
||||
| ">>>"
|
||||
| "+"
|
||||
| "-"
|
||||
| "*"
|
||||
| "/"
|
||||
| "%"
|
||||
| "**"
|
||||
| "|"
|
||||
| "^"
|
||||
| "&"
|
||||
| "in"
|
||||
| "instanceof";
|
||||
|
||||
type LogicalOperator = "||" | "&&" | "??";
|
||||
|
||||
type AssignmentOperator =
|
||||
| "="
|
||||
| "+="
|
||||
| "-="
|
||||
| "*="
|
||||
| "/="
|
||||
| "%="
|
||||
| "**="
|
||||
| "<<="
|
||||
| ">>="
|
||||
| ">>>="
|
||||
| "|="
|
||||
| "^="
|
||||
| "&="
|
||||
| "||="
|
||||
| "&&="
|
||||
| "??=";
|
||||
|
||||
type UpdateOperator = "++" | "--";
|
||||
|
||||
interface ForOfStatement extends BaseForXStatement {
|
||||
type: "ForOfStatement";
|
||||
await: boolean;
|
||||
}
|
||||
|
||||
interface Super extends BaseNode {
|
||||
type: "Super";
|
||||
}
|
||||
|
||||
interface SpreadElement extends BaseNode {
|
||||
type: "SpreadElement";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
|
||||
type: "ArrowFunctionExpression";
|
||||
expression: boolean;
|
||||
body: BlockStatement | Expression;
|
||||
}
|
||||
|
||||
interface YieldExpression extends BaseExpression {
|
||||
type: "YieldExpression";
|
||||
argument?: Expression | null | undefined;
|
||||
delegate: boolean;
|
||||
}
|
||||
|
||||
interface TemplateLiteral extends BaseExpression {
|
||||
type: "TemplateLiteral";
|
||||
quasis: TemplateElement[];
|
||||
expressions: Expression[];
|
||||
}
|
||||
|
||||
interface TaggedTemplateExpression extends BaseExpression {
|
||||
type: "TaggedTemplateExpression";
|
||||
tag: Expression;
|
||||
quasi: TemplateLiteral;
|
||||
}
|
||||
|
||||
interface TemplateElement extends BaseNode {
|
||||
type: "TemplateElement";
|
||||
tail: boolean;
|
||||
value: {
|
||||
/** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
|
||||
cooked?: string | null | undefined;
|
||||
raw: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AssignmentProperty extends Property {
|
||||
value: Pattern;
|
||||
kind: "init";
|
||||
method: boolean; // false
|
||||
}
|
||||
|
||||
interface ObjectPattern extends BasePattern {
|
||||
type: "ObjectPattern";
|
||||
properties: Array<AssignmentProperty | RestElement>;
|
||||
}
|
||||
|
||||
interface ArrayPattern extends BasePattern {
|
||||
type: "ArrayPattern";
|
||||
elements: Array<Pattern | null>;
|
||||
}
|
||||
|
||||
interface RestElement extends BasePattern {
|
||||
type: "RestElement";
|
||||
argument: Pattern;
|
||||
}
|
||||
|
||||
interface AssignmentPattern extends BasePattern {
|
||||
type: "AssignmentPattern";
|
||||
left: Pattern;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
type Class = ClassDeclaration | ClassExpression;
|
||||
interface BaseClass extends BaseNode {
|
||||
superClass?: Expression | null | undefined;
|
||||
body: ClassBody;
|
||||
}
|
||||
|
||||
interface ClassBody extends BaseNode {
|
||||
type: "ClassBody";
|
||||
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>;
|
||||
}
|
||||
|
||||
interface MethodDefinition extends BaseNode {
|
||||
type: "MethodDefinition";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value: FunctionExpression;
|
||||
kind: "constructor" | "method" | "get" | "set";
|
||||
computed: boolean;
|
||||
static: boolean;
|
||||
}
|
||||
|
||||
interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
|
||||
type: "ClassDeclaration";
|
||||
/** It is null when a class declaration is a part of the `export default class` statement */
|
||||
id: Identifier | null;
|
||||
}
|
||||
|
||||
interface ClassDeclaration extends MaybeNamedClassDeclaration {
|
||||
id: Identifier;
|
||||
}
|
||||
|
||||
interface ClassExpression extends BaseClass, BaseExpression {
|
||||
type: "ClassExpression";
|
||||
id?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface MetaProperty extends BaseExpression {
|
||||
type: "MetaProperty";
|
||||
meta: Identifier;
|
||||
property: Identifier;
|
||||
}
|
||||
|
||||
type ModuleDeclaration =
|
||||
| ImportDeclaration
|
||||
| ExportNamedDeclaration
|
||||
| ExportDefaultDeclaration
|
||||
| ExportAllDeclaration;
|
||||
interface BaseModuleDeclaration extends BaseNode {}
|
||||
|
||||
type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
|
||||
interface BaseModuleSpecifier extends BaseNode {
|
||||
local: Identifier;
|
||||
}
|
||||
|
||||
interface ImportDeclaration extends BaseModuleDeclaration {
|
||||
type: "ImportDeclaration";
|
||||
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>;
|
||||
attributes: ImportAttribute[];
|
||||
source: Literal;
|
||||
}
|
||||
|
||||
interface ImportSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportSpecifier";
|
||||
imported: Identifier | Literal;
|
||||
}
|
||||
|
||||
interface ImportAttribute extends BaseNode {
|
||||
type: "ImportAttribute";
|
||||
key: Identifier | Literal;
|
||||
value: Literal;
|
||||
}
|
||||
|
||||
interface ImportExpression extends BaseExpression {
|
||||
type: "ImportExpression";
|
||||
source: Expression;
|
||||
options?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ImportDefaultSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportDefaultSpecifier";
|
||||
}
|
||||
|
||||
interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportNamespaceSpecifier";
|
||||
}
|
||||
|
||||
interface ExportNamedDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportNamedDeclaration";
|
||||
declaration?: Declaration | null | undefined;
|
||||
specifiers: ExportSpecifier[];
|
||||
attributes: ImportAttribute[];
|
||||
source?: Literal | null | undefined;
|
||||
}
|
||||
|
||||
interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> {
|
||||
type: "ExportSpecifier";
|
||||
local: Identifier | Literal;
|
||||
exported: Identifier | Literal;
|
||||
}
|
||||
|
||||
interface ExportDefaultDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportDefaultDeclaration";
|
||||
declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
|
||||
}
|
||||
|
||||
interface ExportAllDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportAllDeclaration";
|
||||
exported: Identifier | Literal | null;
|
||||
attributes: ImportAttribute[];
|
||||
source: Literal;
|
||||
}
|
||||
|
||||
interface AwaitExpression extends BaseExpression {
|
||||
type: "AwaitExpression";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
type Positioned<T> = T & {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
type Node = Positioned<Node$1>;
|
||||
|
||||
interface HoistMocksOptions {
|
||||
/**
|
||||
* List of modules that should always be imported before compiler hints.
|
||||
* @default 'vitest'
|
||||
*/
|
||||
hoistedModule?: string;
|
||||
/**
|
||||
* @default ["vi", "vitest"]
|
||||
*/
|
||||
utilsObjectNames?: string[];
|
||||
/**
|
||||
* @default ["mock", "unmock"]
|
||||
*/
|
||||
hoistableMockMethodNames?: string[];
|
||||
/**
|
||||
* @default ["mock", "unmock", "doMock", "doUnmock"]
|
||||
*/
|
||||
dynamicImportMockMethodNames?: string[];
|
||||
/**
|
||||
* @default ["hoisted"]
|
||||
*/
|
||||
hoistedMethodNames?: string[];
|
||||
globalThisAccessor?: string;
|
||||
regexpHoistable?: RegExp;
|
||||
codeFrameGenerator?: CodeFrameGenerator;
|
||||
magicString?: () => MagicString;
|
||||
}
|
||||
declare function hoistMocks(code: string, id: string, parse: (code: string) => any, options?: HoistMocksOptions): MagicString | undefined;
|
||||
interface CodeFrameGenerator {
|
||||
(node: Positioned<Node>, id: string, code: string): string;
|
||||
}
|
||||
|
||||
export { createManualModuleSource as c, hoistMocks as h };
|
||||
export type { HoistMocksOptions as H };
|
||||
Generated
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
||||
import './types.d-B8CCKmHt.js';
|
||||
import './types.d-BjI5eAwu.js';
|
||||
|
||||
type Key = string | symbol;
|
||||
type CreateMockInstanceProcedure = (options?: {
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-C-sLYZi-.js';
|
||||
export { A as AutomockedModule, h as AutomockedModuleSerialized, f as AutospiedModule, i as AutospiedModuleSerialized, g as ManualMockedModule, j as ManualMockedModuleSerialized, a as MockedModule, k as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, l as RedirectedModuleSerialized, e as ServerIdResolution, S as ServerMockResolution } from './types.d-B8CCKmHt.js';
|
||||
export { G as GlobalConstructors, M as MockObjectOptions, m as mockObject } from './index.d-B41z0AuW.js';
|
||||
export { A as AutomockedModule, g as AutomockedModuleSerialized, h as AutospiedModule, i as AutospiedModuleSerialized, j as ManualMockedModule, k as ManualMockedModuleSerialized, a as MockedModule, l as MockedModuleSerialized, d as MockedModuleType, M as MockerRegistry, e as ModuleMockContext, m as ModuleMockFactory, c as ModuleMockFactoryWithHelper, b as ModuleMockOptions, R as RedirectedModule, n as RedirectedModuleSerialized, f as ServerIdResolution, S as ServerMockResolution, T as TestModuleMocker } from './types.d-BjI5eAwu.js';
|
||||
|
||||
+18
-3
@@ -81,9 +81,24 @@ function mockObject(options, object, mockExports = {}) {
|
||||
define(newContainer, property, value);
|
||||
continue;
|
||||
}
|
||||
// Sometimes this assignment fails for some unknown reason. If it does,
|
||||
// just move along.
|
||||
if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
|
||||
if (options.type === "autospy" && type === "Module") {
|
||||
// Replace with clean object to recursively autospy exported module objects:
|
||||
// export * as ns from "./ns"
|
||||
// or
|
||||
// import * as ns from "./ns"
|
||||
// export { ns }
|
||||
const exports$1 = Object.create(null);
|
||||
Object.defineProperty(exports$1, Symbol.toStringTag, {
|
||||
value: "Module",
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
try {
|
||||
newContainer[property] = exports$1;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
} else if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
|
||||
continue;
|
||||
}
|
||||
if (isFunction) {
|
||||
|
||||
Generated
Vendored
+10
-5
@@ -1,6 +1,6 @@
|
||||
import { MaybeMockedDeep } from '@vitest/spy';
|
||||
import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, M as MockerRegistry, d as MockedModuleType } from './types.d-B8CCKmHt.js';
|
||||
import { C as CreateMockInstanceProcedure } from './index.d-C-sLYZi-.js';
|
||||
import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, T as TestModuleMocker, M as MockerRegistry, d as MockedModuleType, e as ModuleMockContext } from './types.d-BjI5eAwu.js';
|
||||
import { C as CreateMockInstanceProcedure } from './index.d-B41z0AuW.js';
|
||||
|
||||
interface CompilerHintsOptions {
|
||||
/**
|
||||
@@ -33,7 +33,7 @@ interface ModuleMockerInterceptor {
|
||||
invalidate: () => Promise<void>;
|
||||
}
|
||||
|
||||
declare class ModuleMocker {
|
||||
declare class ModuleMocker implements TestModuleMocker {
|
||||
private interceptor;
|
||||
private rpc;
|
||||
private createMockInstance;
|
||||
@@ -47,11 +47,16 @@ declare class ModuleMocker {
|
||||
getFactoryModule(id: string): any;
|
||||
invalidate(): Promise<void>;
|
||||
importActual<T>(id: string, importer: string): Promise<T>;
|
||||
protected getBaseUrl(): string;
|
||||
importMock<T>(rawId: string, importer: string): Promise<T>;
|
||||
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
getMockContext(): ModuleMockContext;
|
||||
queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void;
|
||||
queueUnmock(id: string, importer: string): void;
|
||||
wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>;
|
||||
getMockedModuleById(id: string): MockedModule | undefined;
|
||||
reset(): void;
|
||||
private resolveMockPath;
|
||||
}
|
||||
interface ResolveIdResult {
|
||||
@@ -77,5 +82,5 @@ interface ModuleMockerConfig {
|
||||
root: string;
|
||||
}
|
||||
|
||||
export { ModuleMocker as b, createCompilerHints as c };
|
||||
export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as d, ModuleMockerRPC as e, ResolveMockResult as f };
|
||||
export { ModuleMocker as b, createCompilerHints as f };
|
||||
export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as c, ModuleMockerRPC as d, ResolveMockResult as e };
|
||||
+5
-734
@@ -1,12 +1,12 @@
|
||||
import { H as HoistMocksOptions } from './hoistMocks.d-w2ILr1dG.js';
|
||||
export { c as createManualModuleSource } from './hoistMocks.d-w2ILr1dG.js';
|
||||
import { AutomockOptions } from './automock.js';
|
||||
export { automockModule } from './automock.js';
|
||||
import { Plugin, Rollup, ViteDevServer } from 'vite';
|
||||
import { SourceMap } from 'magic-string';
|
||||
import { M as MockerRegistry, S as ServerMockResolution, e as ServerIdResolution } from './types.d-B8CCKmHt.js';
|
||||
import { M as MockerRegistry, S as ServerMockResolution, f as ServerIdResolution } from './types.d-BjI5eAwu.js';
|
||||
export { findMockRedirect } from './redirect.js';
|
||||
|
||||
declare function createManualModuleSource(moduleUrl: string, exports: string[], globalAccessor?: string): string;
|
||||
|
||||
declare function automockPlugin(options?: AutomockOptions): Plugin;
|
||||
|
||||
interface DynamicImportPluginOptions {
|
||||
@@ -18,732 +18,6 @@ interface DynamicImportPluginOptions {
|
||||
}
|
||||
declare function dynamicImportPlugin(options?: DynamicImportPluginOptions): Plugin;
|
||||
|
||||
// This definition file follows a somewhat unusual format. ESTree allows
|
||||
// runtime type checks based on the `type` parameter. In order to explain this
|
||||
// to typescript we want to use discriminated union types:
|
||||
// https://github.com/Microsoft/TypeScript/pull/9163
|
||||
//
|
||||
// For ESTree this is a bit tricky because the high level interfaces like
|
||||
// Node or Function are pulling double duty. We want to pass common fields down
|
||||
// to the interfaces that extend them (like Identifier or
|
||||
// ArrowFunctionExpression), but you can't extend a type union or enforce
|
||||
// common fields on them. So we've split the high level interfaces into two
|
||||
// types, a base type which passes down inherited fields, and a type union of
|
||||
// all types which extend the base type. Only the type union is exported, and
|
||||
// the union is how other types refer to the collection of inheriting types.
|
||||
//
|
||||
// This makes the definitions file here somewhat more difficult to maintain,
|
||||
// but it has the notable advantage of making ESTree much easier to use as
|
||||
// an end user.
|
||||
|
||||
interface BaseNodeWithoutComments {
|
||||
// Every leaf interface that extends BaseNode must specify a type property.
|
||||
// The type property should be a string literal. For example, Identifier
|
||||
// has: `type: "Identifier"`
|
||||
type: string;
|
||||
loc?: SourceLocation | null | undefined;
|
||||
range?: [number, number] | undefined;
|
||||
}
|
||||
|
||||
interface BaseNode extends BaseNodeWithoutComments {
|
||||
leadingComments?: Comment[] | undefined;
|
||||
trailingComments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface NodeMap {
|
||||
AssignmentProperty: AssignmentProperty;
|
||||
CatchClause: CatchClause;
|
||||
Class: Class;
|
||||
ClassBody: ClassBody;
|
||||
Expression: Expression;
|
||||
Function: Function;
|
||||
Identifier: Identifier;
|
||||
Literal: Literal;
|
||||
MethodDefinition: MethodDefinition;
|
||||
ModuleDeclaration: ModuleDeclaration;
|
||||
ModuleSpecifier: ModuleSpecifier;
|
||||
Pattern: Pattern;
|
||||
PrivateIdentifier: PrivateIdentifier;
|
||||
Program: Program;
|
||||
Property: Property;
|
||||
PropertyDefinition: PropertyDefinition;
|
||||
SpreadElement: SpreadElement;
|
||||
Statement: Statement;
|
||||
Super: Super;
|
||||
SwitchCase: SwitchCase;
|
||||
TemplateElement: TemplateElement;
|
||||
VariableDeclarator: VariableDeclarator;
|
||||
}
|
||||
|
||||
type Node$1 = NodeMap[keyof NodeMap];
|
||||
|
||||
interface Comment extends BaseNodeWithoutComments {
|
||||
type: "Line" | "Block";
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface SourceLocation {
|
||||
source?: string | null | undefined;
|
||||
start: Position;
|
||||
end: Position;
|
||||
}
|
||||
|
||||
interface Position {
|
||||
/** >= 1 */
|
||||
line: number;
|
||||
/** >= 0 */
|
||||
column: number;
|
||||
}
|
||||
|
||||
interface Program extends BaseNode {
|
||||
type: "Program";
|
||||
sourceType: "script" | "module";
|
||||
body: Array<Directive | Statement | ModuleDeclaration>;
|
||||
comments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface Directive extends BaseNode {
|
||||
type: "ExpressionStatement";
|
||||
expression: Literal;
|
||||
directive: string;
|
||||
}
|
||||
|
||||
interface BaseFunction extends BaseNode {
|
||||
params: Pattern[];
|
||||
generator?: boolean | undefined;
|
||||
async?: boolean | undefined;
|
||||
// The body is either BlockStatement or Expression because arrow functions
|
||||
// can have a body that's either. FunctionDeclarations and
|
||||
// FunctionExpressions have only BlockStatement bodies.
|
||||
body: BlockStatement | Expression;
|
||||
}
|
||||
|
||||
type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression;
|
||||
|
||||
type Statement =
|
||||
| ExpressionStatement
|
||||
| BlockStatement
|
||||
| StaticBlock
|
||||
| EmptyStatement
|
||||
| DebuggerStatement
|
||||
| WithStatement
|
||||
| ReturnStatement
|
||||
| LabeledStatement
|
||||
| BreakStatement
|
||||
| ContinueStatement
|
||||
| IfStatement
|
||||
| SwitchStatement
|
||||
| ThrowStatement
|
||||
| TryStatement
|
||||
| WhileStatement
|
||||
| DoWhileStatement
|
||||
| ForStatement
|
||||
| ForInStatement
|
||||
| ForOfStatement
|
||||
| Declaration;
|
||||
|
||||
interface BaseStatement extends BaseNode {}
|
||||
|
||||
interface EmptyStatement extends BaseStatement {
|
||||
type: "EmptyStatement";
|
||||
}
|
||||
|
||||
interface BlockStatement extends BaseStatement {
|
||||
type: "BlockStatement";
|
||||
body: Statement[];
|
||||
innerComments?: Comment[] | undefined;
|
||||
}
|
||||
|
||||
interface StaticBlock extends Omit<BlockStatement, "type"> {
|
||||
type: "StaticBlock";
|
||||
}
|
||||
|
||||
interface ExpressionStatement extends BaseStatement {
|
||||
type: "ExpressionStatement";
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
interface IfStatement extends BaseStatement {
|
||||
type: "IfStatement";
|
||||
test: Expression;
|
||||
consequent: Statement;
|
||||
alternate?: Statement | null | undefined;
|
||||
}
|
||||
|
||||
interface LabeledStatement extends BaseStatement {
|
||||
type: "LabeledStatement";
|
||||
label: Identifier;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface BreakStatement extends BaseStatement {
|
||||
type: "BreakStatement";
|
||||
label?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface ContinueStatement extends BaseStatement {
|
||||
type: "ContinueStatement";
|
||||
label?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface WithStatement extends BaseStatement {
|
||||
type: "WithStatement";
|
||||
object: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface SwitchStatement extends BaseStatement {
|
||||
type: "SwitchStatement";
|
||||
discriminant: Expression;
|
||||
cases: SwitchCase[];
|
||||
}
|
||||
|
||||
interface ReturnStatement extends BaseStatement {
|
||||
type: "ReturnStatement";
|
||||
argument?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ThrowStatement extends BaseStatement {
|
||||
type: "ThrowStatement";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface TryStatement extends BaseStatement {
|
||||
type: "TryStatement";
|
||||
block: BlockStatement;
|
||||
handler?: CatchClause | null | undefined;
|
||||
finalizer?: BlockStatement | null | undefined;
|
||||
}
|
||||
|
||||
interface WhileStatement extends BaseStatement {
|
||||
type: "WhileStatement";
|
||||
test: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface DoWhileStatement extends BaseStatement {
|
||||
type: "DoWhileStatement";
|
||||
body: Statement;
|
||||
test: Expression;
|
||||
}
|
||||
|
||||
interface ForStatement extends BaseStatement {
|
||||
type: "ForStatement";
|
||||
init?: VariableDeclaration | Expression | null | undefined;
|
||||
test?: Expression | null | undefined;
|
||||
update?: Expression | null | undefined;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface BaseForXStatement extends BaseStatement {
|
||||
left: VariableDeclaration | Pattern;
|
||||
right: Expression;
|
||||
body: Statement;
|
||||
}
|
||||
|
||||
interface ForInStatement extends BaseForXStatement {
|
||||
type: "ForInStatement";
|
||||
}
|
||||
|
||||
interface DebuggerStatement extends BaseStatement {
|
||||
type: "DebuggerStatement";
|
||||
}
|
||||
|
||||
type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration;
|
||||
|
||||
interface BaseDeclaration extends BaseStatement {}
|
||||
|
||||
interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration {
|
||||
type: "FunctionDeclaration";
|
||||
/** It is null when a function declaration is a part of the `export default function` statement */
|
||||
id: Identifier | null;
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface FunctionDeclaration extends MaybeNamedFunctionDeclaration {
|
||||
id: Identifier;
|
||||
}
|
||||
|
||||
interface VariableDeclaration extends BaseDeclaration {
|
||||
type: "VariableDeclaration";
|
||||
declarations: VariableDeclarator[];
|
||||
kind: "var" | "let" | "const" | "using" | "await using";
|
||||
}
|
||||
|
||||
interface VariableDeclarator extends BaseNode {
|
||||
type: "VariableDeclarator";
|
||||
id: Pattern;
|
||||
init?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ExpressionMap {
|
||||
ArrayExpression: ArrayExpression;
|
||||
ArrowFunctionExpression: ArrowFunctionExpression;
|
||||
AssignmentExpression: AssignmentExpression;
|
||||
AwaitExpression: AwaitExpression;
|
||||
BinaryExpression: BinaryExpression;
|
||||
CallExpression: CallExpression;
|
||||
ChainExpression: ChainExpression;
|
||||
ClassExpression: ClassExpression;
|
||||
ConditionalExpression: ConditionalExpression;
|
||||
FunctionExpression: FunctionExpression;
|
||||
Identifier: Identifier;
|
||||
ImportExpression: ImportExpression;
|
||||
Literal: Literal;
|
||||
LogicalExpression: LogicalExpression;
|
||||
MemberExpression: MemberExpression;
|
||||
MetaProperty: MetaProperty;
|
||||
NewExpression: NewExpression;
|
||||
ObjectExpression: ObjectExpression;
|
||||
SequenceExpression: SequenceExpression;
|
||||
TaggedTemplateExpression: TaggedTemplateExpression;
|
||||
TemplateLiteral: TemplateLiteral;
|
||||
ThisExpression: ThisExpression;
|
||||
UnaryExpression: UnaryExpression;
|
||||
UpdateExpression: UpdateExpression;
|
||||
YieldExpression: YieldExpression;
|
||||
}
|
||||
|
||||
type Expression = ExpressionMap[keyof ExpressionMap];
|
||||
|
||||
interface BaseExpression extends BaseNode {}
|
||||
|
||||
type ChainElement = SimpleCallExpression | MemberExpression;
|
||||
|
||||
interface ChainExpression extends BaseExpression {
|
||||
type: "ChainExpression";
|
||||
expression: ChainElement;
|
||||
}
|
||||
|
||||
interface ThisExpression extends BaseExpression {
|
||||
type: "ThisExpression";
|
||||
}
|
||||
|
||||
interface ArrayExpression extends BaseExpression {
|
||||
type: "ArrayExpression";
|
||||
elements: Array<Expression | SpreadElement | null>;
|
||||
}
|
||||
|
||||
interface ObjectExpression extends BaseExpression {
|
||||
type: "ObjectExpression";
|
||||
properties: Array<Property | SpreadElement>;
|
||||
}
|
||||
|
||||
interface PrivateIdentifier extends BaseNode {
|
||||
type: "PrivateIdentifier";
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Property extends BaseNode {
|
||||
type: "Property";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value: Expression | Pattern; // Could be an AssignmentProperty
|
||||
kind: "init" | "get" | "set";
|
||||
method: boolean;
|
||||
shorthand: boolean;
|
||||
computed: boolean;
|
||||
}
|
||||
|
||||
interface PropertyDefinition extends BaseNode {
|
||||
type: "PropertyDefinition";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value?: Expression | null | undefined;
|
||||
computed: boolean;
|
||||
static: boolean;
|
||||
}
|
||||
|
||||
interface FunctionExpression extends BaseFunction, BaseExpression {
|
||||
id?: Identifier | null | undefined;
|
||||
type: "FunctionExpression";
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface SequenceExpression extends BaseExpression {
|
||||
type: "SequenceExpression";
|
||||
expressions: Expression[];
|
||||
}
|
||||
|
||||
interface UnaryExpression extends BaseExpression {
|
||||
type: "UnaryExpression";
|
||||
operator: UnaryOperator;
|
||||
prefix: true;
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface BinaryExpression extends BaseExpression {
|
||||
type: "BinaryExpression";
|
||||
operator: BinaryOperator;
|
||||
left: Expression | PrivateIdentifier;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface AssignmentExpression extends BaseExpression {
|
||||
type: "AssignmentExpression";
|
||||
operator: AssignmentOperator;
|
||||
left: Pattern | MemberExpression;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface UpdateExpression extends BaseExpression {
|
||||
type: "UpdateExpression";
|
||||
operator: UpdateOperator;
|
||||
argument: Expression;
|
||||
prefix: boolean;
|
||||
}
|
||||
|
||||
interface LogicalExpression extends BaseExpression {
|
||||
type: "LogicalExpression";
|
||||
operator: LogicalOperator;
|
||||
left: Expression;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
interface ConditionalExpression extends BaseExpression {
|
||||
type: "ConditionalExpression";
|
||||
test: Expression;
|
||||
alternate: Expression;
|
||||
consequent: Expression;
|
||||
}
|
||||
|
||||
interface BaseCallExpression extends BaseExpression {
|
||||
callee: Expression | Super;
|
||||
arguments: Array<Expression | SpreadElement>;
|
||||
}
|
||||
type CallExpression = SimpleCallExpression | NewExpression;
|
||||
|
||||
interface SimpleCallExpression extends BaseCallExpression {
|
||||
type: "CallExpression";
|
||||
optional: boolean;
|
||||
}
|
||||
|
||||
interface NewExpression extends BaseCallExpression {
|
||||
type: "NewExpression";
|
||||
}
|
||||
|
||||
interface MemberExpression extends BaseExpression, BasePattern {
|
||||
type: "MemberExpression";
|
||||
object: Expression | Super;
|
||||
property: Expression | PrivateIdentifier;
|
||||
computed: boolean;
|
||||
optional: boolean;
|
||||
}
|
||||
|
||||
type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression;
|
||||
|
||||
interface BasePattern extends BaseNode {}
|
||||
|
||||
interface SwitchCase extends BaseNode {
|
||||
type: "SwitchCase";
|
||||
test?: Expression | null | undefined;
|
||||
consequent: Statement[];
|
||||
}
|
||||
|
||||
interface CatchClause extends BaseNode {
|
||||
type: "CatchClause";
|
||||
param: Pattern | null;
|
||||
body: BlockStatement;
|
||||
}
|
||||
|
||||
interface Identifier extends BaseNode, BaseExpression, BasePattern {
|
||||
type: "Identifier";
|
||||
name: string;
|
||||
}
|
||||
|
||||
type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral;
|
||||
|
||||
interface SimpleLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value: string | boolean | number | null;
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
interface RegExpLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value?: RegExp | null | undefined;
|
||||
regex: {
|
||||
pattern: string;
|
||||
flags: string;
|
||||
};
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
interface BigIntLiteral extends BaseNode, BaseExpression {
|
||||
type: "Literal";
|
||||
value?: bigint | null | undefined;
|
||||
bigint: string;
|
||||
raw?: string | undefined;
|
||||
}
|
||||
|
||||
type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
|
||||
|
||||
type BinaryOperator =
|
||||
| "=="
|
||||
| "!="
|
||||
| "==="
|
||||
| "!=="
|
||||
| "<"
|
||||
| "<="
|
||||
| ">"
|
||||
| ">="
|
||||
| "<<"
|
||||
| ">>"
|
||||
| ">>>"
|
||||
| "+"
|
||||
| "-"
|
||||
| "*"
|
||||
| "/"
|
||||
| "%"
|
||||
| "**"
|
||||
| "|"
|
||||
| "^"
|
||||
| "&"
|
||||
| "in"
|
||||
| "instanceof";
|
||||
|
||||
type LogicalOperator = "||" | "&&" | "??";
|
||||
|
||||
type AssignmentOperator =
|
||||
| "="
|
||||
| "+="
|
||||
| "-="
|
||||
| "*="
|
||||
| "/="
|
||||
| "%="
|
||||
| "**="
|
||||
| "<<="
|
||||
| ">>="
|
||||
| ">>>="
|
||||
| "|="
|
||||
| "^="
|
||||
| "&="
|
||||
| "||="
|
||||
| "&&="
|
||||
| "??=";
|
||||
|
||||
type UpdateOperator = "++" | "--";
|
||||
|
||||
interface ForOfStatement extends BaseForXStatement {
|
||||
type: "ForOfStatement";
|
||||
await: boolean;
|
||||
}
|
||||
|
||||
interface Super extends BaseNode {
|
||||
type: "Super";
|
||||
}
|
||||
|
||||
interface SpreadElement extends BaseNode {
|
||||
type: "SpreadElement";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
interface ArrowFunctionExpression extends BaseExpression, BaseFunction {
|
||||
type: "ArrowFunctionExpression";
|
||||
expression: boolean;
|
||||
body: BlockStatement | Expression;
|
||||
}
|
||||
|
||||
interface YieldExpression extends BaseExpression {
|
||||
type: "YieldExpression";
|
||||
argument?: Expression | null | undefined;
|
||||
delegate: boolean;
|
||||
}
|
||||
|
||||
interface TemplateLiteral extends BaseExpression {
|
||||
type: "TemplateLiteral";
|
||||
quasis: TemplateElement[];
|
||||
expressions: Expression[];
|
||||
}
|
||||
|
||||
interface TaggedTemplateExpression extends BaseExpression {
|
||||
type: "TaggedTemplateExpression";
|
||||
tag: Expression;
|
||||
quasi: TemplateLiteral;
|
||||
}
|
||||
|
||||
interface TemplateElement extends BaseNode {
|
||||
type: "TemplateElement";
|
||||
tail: boolean;
|
||||
value: {
|
||||
/** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */
|
||||
cooked?: string | null | undefined;
|
||||
raw: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AssignmentProperty extends Property {
|
||||
value: Pattern;
|
||||
kind: "init";
|
||||
method: boolean; // false
|
||||
}
|
||||
|
||||
interface ObjectPattern extends BasePattern {
|
||||
type: "ObjectPattern";
|
||||
properties: Array<AssignmentProperty | RestElement>;
|
||||
}
|
||||
|
||||
interface ArrayPattern extends BasePattern {
|
||||
type: "ArrayPattern";
|
||||
elements: Array<Pattern | null>;
|
||||
}
|
||||
|
||||
interface RestElement extends BasePattern {
|
||||
type: "RestElement";
|
||||
argument: Pattern;
|
||||
}
|
||||
|
||||
interface AssignmentPattern extends BasePattern {
|
||||
type: "AssignmentPattern";
|
||||
left: Pattern;
|
||||
right: Expression;
|
||||
}
|
||||
|
||||
type Class = ClassDeclaration | ClassExpression;
|
||||
interface BaseClass extends BaseNode {
|
||||
superClass?: Expression | null | undefined;
|
||||
body: ClassBody;
|
||||
}
|
||||
|
||||
interface ClassBody extends BaseNode {
|
||||
type: "ClassBody";
|
||||
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>;
|
||||
}
|
||||
|
||||
interface MethodDefinition extends BaseNode {
|
||||
type: "MethodDefinition";
|
||||
key: Expression | PrivateIdentifier;
|
||||
value: FunctionExpression;
|
||||
kind: "constructor" | "method" | "get" | "set";
|
||||
computed: boolean;
|
||||
static: boolean;
|
||||
}
|
||||
|
||||
interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration {
|
||||
type: "ClassDeclaration";
|
||||
/** It is null when a class declaration is a part of the `export default class` statement */
|
||||
id: Identifier | null;
|
||||
}
|
||||
|
||||
interface ClassDeclaration extends MaybeNamedClassDeclaration {
|
||||
id: Identifier;
|
||||
}
|
||||
|
||||
interface ClassExpression extends BaseClass, BaseExpression {
|
||||
type: "ClassExpression";
|
||||
id?: Identifier | null | undefined;
|
||||
}
|
||||
|
||||
interface MetaProperty extends BaseExpression {
|
||||
type: "MetaProperty";
|
||||
meta: Identifier;
|
||||
property: Identifier;
|
||||
}
|
||||
|
||||
type ModuleDeclaration =
|
||||
| ImportDeclaration
|
||||
| ExportNamedDeclaration
|
||||
| ExportDefaultDeclaration
|
||||
| ExportAllDeclaration;
|
||||
interface BaseModuleDeclaration extends BaseNode {}
|
||||
|
||||
type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier;
|
||||
interface BaseModuleSpecifier extends BaseNode {
|
||||
local: Identifier;
|
||||
}
|
||||
|
||||
interface ImportDeclaration extends BaseModuleDeclaration {
|
||||
type: "ImportDeclaration";
|
||||
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>;
|
||||
attributes: ImportAttribute[];
|
||||
source: Literal;
|
||||
}
|
||||
|
||||
interface ImportSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportSpecifier";
|
||||
imported: Identifier | Literal;
|
||||
}
|
||||
|
||||
interface ImportAttribute extends BaseNode {
|
||||
type: "ImportAttribute";
|
||||
key: Identifier | Literal;
|
||||
value: Literal;
|
||||
}
|
||||
|
||||
interface ImportExpression extends BaseExpression {
|
||||
type: "ImportExpression";
|
||||
source: Expression;
|
||||
options?: Expression | null | undefined;
|
||||
}
|
||||
|
||||
interface ImportDefaultSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportDefaultSpecifier";
|
||||
}
|
||||
|
||||
interface ImportNamespaceSpecifier extends BaseModuleSpecifier {
|
||||
type: "ImportNamespaceSpecifier";
|
||||
}
|
||||
|
||||
interface ExportNamedDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportNamedDeclaration";
|
||||
declaration?: Declaration | null | undefined;
|
||||
specifiers: ExportSpecifier[];
|
||||
attributes: ImportAttribute[];
|
||||
source?: Literal | null | undefined;
|
||||
}
|
||||
|
||||
interface ExportSpecifier extends Omit<BaseModuleSpecifier, "local"> {
|
||||
type: "ExportSpecifier";
|
||||
local: Identifier | Literal;
|
||||
exported: Identifier | Literal;
|
||||
}
|
||||
|
||||
interface ExportDefaultDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportDefaultDeclaration";
|
||||
declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression;
|
||||
}
|
||||
|
||||
interface ExportAllDeclaration extends BaseModuleDeclaration {
|
||||
type: "ExportAllDeclaration";
|
||||
exported: Identifier | Literal | null;
|
||||
attributes: ImportAttribute[];
|
||||
source: Literal;
|
||||
}
|
||||
|
||||
interface AwaitExpression extends BaseExpression {
|
||||
type: "AwaitExpression";
|
||||
argument: Expression;
|
||||
}
|
||||
|
||||
type Positioned<T> = T & {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
type Node = Positioned<Node$1>;
|
||||
|
||||
interface HoistMocksOptions {
|
||||
/**
|
||||
* List of modules that should always be imported before compiler hints.
|
||||
* @default 'vitest'
|
||||
*/
|
||||
hoistedModule?: string;
|
||||
/**
|
||||
* @default ["vi", "vitest"]
|
||||
*/
|
||||
utilsObjectNames?: string[];
|
||||
/**
|
||||
* @default ["mock", "unmock"]
|
||||
*/
|
||||
hoistableMockMethodNames?: string[];
|
||||
/**
|
||||
* @default ["mock", "unmock", "doMock", "doUnmock"]
|
||||
*/
|
||||
dynamicImportMockMethodNames?: string[];
|
||||
/**
|
||||
* @default ["hoisted"]
|
||||
*/
|
||||
hoistedMethodNames?: string[];
|
||||
regexpHoistable?: RegExp;
|
||||
codeFrameGenerator?: CodeFrameGenerator;
|
||||
}
|
||||
interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistable"> {
|
||||
include?: string | RegExp | (string | RegExp)[];
|
||||
exclude?: string | RegExp | (string | RegExp)[];
|
||||
@@ -753,14 +27,11 @@ interface HoistMocksPluginOptions extends Omit<HoistMocksOptions, "regexpHoistab
|
||||
filter?: (id: string) => boolean;
|
||||
}
|
||||
declare function hoistMocksPlugin(options?: HoistMocksPluginOptions): Plugin;
|
||||
declare function hoistMockAndResolve(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined;
|
||||
interface HoistMocksResult {
|
||||
code: string;
|
||||
map: SourceMap;
|
||||
}
|
||||
interface CodeFrameGenerator {
|
||||
(node: Positioned<Node>, id: string, code: string): string;
|
||||
}
|
||||
declare function hoistMocks(code: string, id: string, parse: Rollup.PluginContext["parse"], options?: HoistMocksOptions): HoistMocksResult | undefined;
|
||||
|
||||
interface InterceptorPluginOptions {
|
||||
/**
|
||||
@@ -796,5 +67,5 @@ declare class ServerMockResolver {
|
||||
private resolveModule;
|
||||
}
|
||||
|
||||
export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, createManualModuleSource, dynamicImportPlugin, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
export { AutomockOptions as AutomockPluginOptions, ServerMockResolver, automockPlugin, dynamicImportPlugin, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
export type { HoistMocksPluginOptions, HoistMocksResult, InterceptorPluginOptions, ServerResolverOptions };
|
||||
|
||||
+29
-587
@@ -2,6 +2,7 @@ import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js';
|
||||
import { a as automockModule, e as esmWalker } from './chunk-automock.js';
|
||||
import MagicString from 'magic-string';
|
||||
import { createFilter } from 'vite';
|
||||
import { h as hoistMocks } from './chunk-hoistMocks.js';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path/posix';
|
||||
import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
|
||||
@@ -11,6 +12,8 @@ import { findMockRedirect } from './redirect.js';
|
||||
import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js';
|
||||
import 'estree-walker';
|
||||
import 'node:module';
|
||||
import 'node:path';
|
||||
import './chunk-helpers.js';
|
||||
|
||||
function automockPlugin(options = {}) {
|
||||
return {
|
||||
@@ -50,6 +53,9 @@ function dynamicImportPlugin(options = {}) {
|
||||
};
|
||||
}
|
||||
function injectDynamicImport(code, id, parse, options = {}) {
|
||||
if (code.includes("wrapDynamicImport")) {
|
||||
return;
|
||||
}
|
||||
const s = new MagicString(code);
|
||||
let ast;
|
||||
try {
|
||||
@@ -81,295 +87,6 @@ function injectDynamicImport(code, id, parse, options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// AST walker module for ESTree compatible trees
|
||||
|
||||
|
||||
function makeTest(test) {
|
||||
if (typeof test === "string")
|
||||
{ return function (type) { return type === test; } }
|
||||
else if (!test)
|
||||
{ return function () { return true; } }
|
||||
else
|
||||
{ return test }
|
||||
}
|
||||
|
||||
var Found = function Found(node, state) { this.node = node; this.state = state; };
|
||||
|
||||
// Find the innermost node of a given type that contains the given
|
||||
// position. Interface similar to findNodeAt.
|
||||
function findNodeAround(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if (node.start > pos || node.end < pos) { return }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (test(type, node)) { throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
function skipThrough(node, st, c) { c(node, st); }
|
||||
function ignore(_node, _st, _c) {}
|
||||
|
||||
// Node walkers.
|
||||
|
||||
var base = {};
|
||||
|
||||
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var stmt = list[i];
|
||||
|
||||
c(stmt, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.Statement = skipThrough;
|
||||
base.EmptyStatement = ignore;
|
||||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
|
||||
function (node, st, c) { return c(node.expression, st, "Expression"); };
|
||||
base.IfStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Statement");
|
||||
if (node.alternate) { c(node.alternate, st, "Statement"); }
|
||||
};
|
||||
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
||||
base.BreakStatement = base.ContinueStatement = ignore;
|
||||
base.WithStatement = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.SwitchStatement = function (node, st, c) {
|
||||
c(node.discriminant, st, "Expression");
|
||||
for (var i = 0, list = node.cases; i < list.length; i += 1) {
|
||||
var cs = list[i];
|
||||
|
||||
c(cs, st);
|
||||
}
|
||||
};
|
||||
base.SwitchCase = function (node, st, c) {
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
|
||||
if (node.argument) { c(node.argument, st, "Expression"); }
|
||||
};
|
||||
base.ThrowStatement = base.SpreadElement =
|
||||
function (node, st, c) { return c(node.argument, st, "Expression"); };
|
||||
base.TryStatement = function (node, st, c) {
|
||||
c(node.block, st, "Statement");
|
||||
if (node.handler) { c(node.handler, st); }
|
||||
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
||||
};
|
||||
base.CatchClause = function (node, st, c) {
|
||||
if (node.param) { c(node.param, st, "Pattern"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForStatement = function (node, st, c) {
|
||||
if (node.init) { c(node.init, st, "ForInit"); }
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
if (node.update) { c(node.update, st, "Expression"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
|
||||
c(node.left, st, "ForInit");
|
||||
c(node.right, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInit = function (node, st, c) {
|
||||
if (node.type === "VariableDeclaration") { c(node, st); }
|
||||
else { c(node, st, "Expression"); }
|
||||
};
|
||||
base.DebuggerStatement = ignore;
|
||||
|
||||
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
||||
base.VariableDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
||||
{
|
||||
var decl = list[i];
|
||||
|
||||
c(decl, st);
|
||||
}
|
||||
};
|
||||
base.VariableDeclarator = function (node, st, c) {
|
||||
c(node.id, st, "Pattern");
|
||||
if (node.init) { c(node.init, st, "Expression"); }
|
||||
};
|
||||
|
||||
base.Function = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
for (var i = 0, list = node.params; i < list.length; i += 1)
|
||||
{
|
||||
var param = list[i];
|
||||
|
||||
c(param, st, "Pattern");
|
||||
}
|
||||
c(node.body, st, node.expression ? "Expression" : "Statement");
|
||||
};
|
||||
|
||||
base.Pattern = function (node, st, c) {
|
||||
if (node.type === "Identifier")
|
||||
{ c(node, st, "VariablePattern"); }
|
||||
else if (node.type === "MemberExpression")
|
||||
{ c(node, st, "MemberPattern"); }
|
||||
else
|
||||
{ c(node, st); }
|
||||
};
|
||||
base.VariablePattern = ignore;
|
||||
base.MemberPattern = skipThrough;
|
||||
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
||||
base.ArrayPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Pattern"); }
|
||||
}
|
||||
};
|
||||
base.ObjectPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
||||
var prop = list[i];
|
||||
|
||||
if (prop.type === "Property") {
|
||||
if (prop.computed) { c(prop.key, st, "Expression"); }
|
||||
c(prop.value, st, "Pattern");
|
||||
} else if (prop.type === "RestElement") {
|
||||
c(prop.argument, st, "Pattern");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
base.Expression = skipThrough;
|
||||
base.ThisExpression = base.Super = base.MetaProperty = ignore;
|
||||
base.ArrayExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Expression"); }
|
||||
}
|
||||
};
|
||||
base.ObjectExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1)
|
||||
{
|
||||
var prop = list[i];
|
||||
|
||||
c(prop, st);
|
||||
}
|
||||
};
|
||||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
|
||||
base.SequenceExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
||||
{
|
||||
var expr = list[i];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateLiteral = function (node, st, c) {
|
||||
for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
||||
{
|
||||
var quasi = list[i];
|
||||
|
||||
c(quasi, st);
|
||||
}
|
||||
|
||||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
||||
{
|
||||
var expr = list$1[i$1];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateElement = ignore;
|
||||
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
|
||||
c(node.argument, st, "Expression");
|
||||
};
|
||||
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
|
||||
c(node.left, st, "Expression");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
|
||||
c(node.left, st, "Pattern");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.ConditionalExpression = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Expression");
|
||||
c(node.alternate, st, "Expression");
|
||||
};
|
||||
base.NewExpression = base.CallExpression = function (node, st, c) {
|
||||
c(node.callee, st, "Expression");
|
||||
if (node.arguments)
|
||||
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
||||
{
|
||||
var arg = list[i];
|
||||
|
||||
c(arg, st, "Expression");
|
||||
} }
|
||||
};
|
||||
base.MemberExpression = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
if (node.computed) { c(node.property, st, "Expression"); }
|
||||
};
|
||||
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
|
||||
if (node.declaration)
|
||||
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
||||
if (node.source) { c(node.source, st, "Expression"); }
|
||||
};
|
||||
base.ExportAllDeclaration = function (node, st, c) {
|
||||
if (node.exported)
|
||||
{ c(node.exported, st); }
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
||||
{
|
||||
var spec = list[i];
|
||||
|
||||
c(spec, st);
|
||||
}
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportExpression = function (node, st, c) {
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
|
||||
|
||||
base.TaggedTemplateExpression = function (node, st, c) {
|
||||
c(node.tag, st, "Expression");
|
||||
c(node.quasi, st, "Expression");
|
||||
};
|
||||
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
||||
base.Class = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
if (node.superClass) { c(node.superClass, st, "Expression"); }
|
||||
c(node.body, st);
|
||||
};
|
||||
base.ClassBody = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var elt = list[i];
|
||||
|
||||
c(elt, st);
|
||||
}
|
||||
};
|
||||
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
|
||||
if (node.computed) { c(node.key, st, "Expression"); }
|
||||
if (node.value) { c(node.value, st, "Expression"); }
|
||||
};
|
||||
|
||||
function hoistMocksPlugin(options = {}) {
|
||||
const filter = options.filter || createFilter(options.include, options.exclude);
|
||||
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
|
||||
@@ -391,7 +108,7 @@ function hoistMocksPlugin(options = {}) {
|
||||
if (!filter(id)) {
|
||||
return;
|
||||
}
|
||||
return hoistMocks(code, id, this.parse, {
|
||||
const s = hoistMocks(code, id, this.parse, {
|
||||
regexpHoistable,
|
||||
hoistableMockMethodNames,
|
||||
hoistedMethodNames,
|
||||
@@ -399,304 +116,30 @@ function hoistMocksPlugin(options = {}) {
|
||||
dynamicImportMockMethodNames,
|
||||
...options
|
||||
});
|
||||
if (s) {
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({
|
||||
hires: "boundary",
|
||||
source: cleanUrl(id)
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
|
||||
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
|
||||
To fix this issue you can either:
|
||||
- import the mocks API directly from 'vitest'
|
||||
- enable the 'globals' options`;
|
||||
function API_NOT_FOUND_CHECK(names) {
|
||||
return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
|
||||
}
|
||||
function isIdentifier(node) {
|
||||
return node.type === "Identifier";
|
||||
}
|
||||
function getNodeTail(code, node) {
|
||||
let end = node.end;
|
||||
if (code[node.end] === ";") {
|
||||
end += 1;
|
||||
}
|
||||
if (code[node.end] === "\n") {
|
||||
return end + 1;
|
||||
}
|
||||
if (code[node.end + 1] === "\n") {
|
||||
end += 1;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
|
||||
const hashbangRE = /^#!.*\n/;
|
||||
// this is a fork of Vite SSR transform
|
||||
function hoistMocks(code, id, parse, options = {}) {
|
||||
var _hashbangRE$exec;
|
||||
const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
|
||||
if (!needHoisting) {
|
||||
return;
|
||||
}
|
||||
const s = new MagicString(code);
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(code);
|
||||
} catch (err) {
|
||||
console.error(`Cannot parse ${id}:\n${err.message}.`);
|
||||
return;
|
||||
}
|
||||
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
|
||||
"mock",
|
||||
"unmock",
|
||||
"doMock",
|
||||
"doUnmock"
|
||||
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
|
||||
// hoist at the start of the file, after the hashbang
|
||||
let hoistIndex = ((_hashbangRE$exec = hashbangRE.exec(code)) === null || _hashbangRE$exec === void 0 ? void 0 : _hashbangRE$exec[0].length) ?? 0;
|
||||
let hoistedModuleImported = false;
|
||||
let uid = 0;
|
||||
const idToImportMap = new Map();
|
||||
const imports = [];
|
||||
// this will transform import statements into dynamic ones, if there are imports
|
||||
// it will keep the import as is, if we don't need to mock anything
|
||||
// in browser environment it will wrap the module value with "vitest_wrap_module" function
|
||||
// that returns a proxy to the module so that named exports can be mocked
|
||||
function defineImport(importNode) {
|
||||
const source = importNode.source.value;
|
||||
// always hoist vitest import to top of the file, so
|
||||
// "vi" helpers can access it
|
||||
if (hoistedModule === source) {
|
||||
hoistedModuleImported = true;
|
||||
return;
|
||||
}
|
||||
const importId = `__vi_import_${uid++}__`;
|
||||
imports.push({
|
||||
id: importId,
|
||||
node: importNode
|
||||
});
|
||||
return importId;
|
||||
}
|
||||
// 1. check all import statements and record id -> importName map
|
||||
for (const node of ast.body) {
|
||||
// import foo from 'foo' --> foo -> __import_foo__.default
|
||||
// import { baz } from 'foo' --> baz -> __import_foo__.baz
|
||||
// import * as ok from 'foo' --> ok -> __import_foo__
|
||||
if (node.type === "ImportDeclaration") {
|
||||
const importId = defineImport(node);
|
||||
if (!importId) {
|
||||
continue;
|
||||
}
|
||||
for (const spec of node.specifiers) {
|
||||
if (spec.type === "ImportSpecifier") {
|
||||
if (spec.imported.type === "Identifier") {
|
||||
idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
|
||||
} else {
|
||||
idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
|
||||
}
|
||||
} else if (spec.type === "ImportDefaultSpecifier") {
|
||||
idToImportMap.set(spec.local.name, `${importId}.default`);
|
||||
} else {
|
||||
// namespace specifier
|
||||
idToImportMap.set(spec.local.name, importId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const declaredConst = new Set();
|
||||
const hoistedNodes = [];
|
||||
function createSyntaxError(node, message) {
|
||||
const _error = new SyntaxError(message);
|
||||
Error.captureStackTrace(_error, createSyntaxError);
|
||||
const serializedError = {
|
||||
name: "SyntaxError",
|
||||
message: _error.message,
|
||||
stack: _error.stack
|
||||
// to keeb backwards compat
|
||||
function hoistMockAndResolve(code, id, parse, options = {}) {
|
||||
const s = hoistMocks(code, id, parse, options);
|
||||
if (s) {
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({
|
||||
hires: "boundary",
|
||||
source: cleanUrl(id)
|
||||
})
|
||||
};
|
||||
if (options.codeFrameGenerator) {
|
||||
serializedError.frame = options.codeFrameGenerator(node, id, code);
|
||||
}
|
||||
return serializedError;
|
||||
}
|
||||
function assertNotDefaultExport(node, error) {
|
||||
var _findNodeAround;
|
||||
const defaultExport = (_findNodeAround = findNodeAround(ast, node.start, "ExportDefaultDeclaration")) === null || _findNodeAround === void 0 ? void 0 : _findNodeAround.node;
|
||||
if ((defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration) === node || (defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport.declaration.type) === "AwaitExpression" && defaultExport.declaration.argument === node) {
|
||||
throw createSyntaxError(defaultExport, error);
|
||||
}
|
||||
}
|
||||
function assertNotNamedExport(node, error) {
|
||||
var _findNodeAround2;
|
||||
const nodeExported = (_findNodeAround2 = findNodeAround(ast, node.start, "ExportNamedDeclaration")) === null || _findNodeAround2 === void 0 ? void 0 : _findNodeAround2.node;
|
||||
if ((nodeExported === null || nodeExported === void 0 ? void 0 : nodeExported.declaration) === node) {
|
||||
throw createSyntaxError(nodeExported, error);
|
||||
}
|
||||
}
|
||||
function getVariableDeclaration(node) {
|
||||
var _findNodeAround3, _declarationNode$decl;
|
||||
const declarationNode = (_findNodeAround3 = findNodeAround(ast, node.start, "VariableDeclaration")) === null || _findNodeAround3 === void 0 ? void 0 : _findNodeAround3.node;
|
||||
const init = declarationNode === null || declarationNode === void 0 || (_declarationNode$decl = declarationNode.declarations[0]) === null || _declarationNode$decl === void 0 ? void 0 : _declarationNode$decl.init;
|
||||
if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
|
||||
return declarationNode;
|
||||
}
|
||||
}
|
||||
const usedUtilityExports = new Set();
|
||||
esmWalker(ast, {
|
||||
onIdentifier(id, info, parentStack) {
|
||||
const binding = idToImportMap.get(id.name);
|
||||
if (!binding) {
|
||||
return;
|
||||
}
|
||||
if (info.hasBindingShortcut) {
|
||||
s.appendLeft(id.end, `: ${binding}`);
|
||||
} else if (info.classDeclaration) {
|
||||
if (!declaredConst.has(id.name)) {
|
||||
declaredConst.add(id.name);
|
||||
// locate the top-most node containing the class declaration
|
||||
const topNode = parentStack[parentStack.length - 2];
|
||||
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
|
||||
}
|
||||
} else if (!info.classExpression) {
|
||||
s.update(id.start, id.end, binding);
|
||||
}
|
||||
},
|
||||
onCallExpression(node) {
|
||||
if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
|
||||
const methodName = node.callee.property.name;
|
||||
usedUtilityExports.add(node.callee.object.name);
|
||||
if (hoistableMockMethodNames.includes(methodName)) {
|
||||
const method = `${node.callee.object.name}.${methodName}`;
|
||||
assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
|
||||
const declarationNode = getVariableDeclaration(node);
|
||||
if (declarationNode) {
|
||||
assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
|
||||
}
|
||||
// rewrite vi.mock(import('..')) into vi.mock('..')
|
||||
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
|
||||
const moduleInfo = node.arguments[0];
|
||||
// vi.mock(import('./path')) -> vi.mock('./path')
|
||||
if (moduleInfo.type === "ImportExpression") {
|
||||
const source = moduleInfo.source;
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
// vi.mock(await import('./path')) -> vi.mock('./path')
|
||||
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
|
||||
const source = moduleInfo.argument.source;
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
}
|
||||
hoistedNodes.push(node);
|
||||
} else if (dynamicImportMockMethodNames.includes(methodName)) {
|
||||
const moduleInfo = node.arguments[0];
|
||||
let source = null;
|
||||
if (moduleInfo.type === "ImportExpression") {
|
||||
source = moduleInfo.source;
|
||||
}
|
||||
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
|
||||
source = moduleInfo.argument.source;
|
||||
}
|
||||
if (source) {
|
||||
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
|
||||
}
|
||||
}
|
||||
if (hoistedMethodNames.includes(methodName)) {
|
||||
assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
|
||||
const declarationNode = getVariableDeclaration(node);
|
||||
if (declarationNode) {
|
||||
assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
|
||||
// hoist "const variable = vi.hoisted(() => {})"
|
||||
hoistedNodes.push(declarationNode);
|
||||
} else {
|
||||
var _findNodeAround4;
|
||||
const awaitedExpression = (_findNodeAround4 = findNodeAround(ast, node.start, "AwaitExpression")) === null || _findNodeAround4 === void 0 ? void 0 : _findNodeAround4.node;
|
||||
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
|
||||
const moveNode = (awaitedExpression === null || awaitedExpression === void 0 ? void 0 : awaitedExpression.argument) === node ? awaitedExpression : node;
|
||||
hoistedNodes.push(moveNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
function getNodeName(node) {
|
||||
const callee = node.callee || {};
|
||||
if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
|
||||
return `${callee.object.name}.${callee.property.name}()`;
|
||||
}
|
||||
return "\"hoisted method\"";
|
||||
}
|
||||
function getNodeCall(node) {
|
||||
if (node.type === "CallExpression") {
|
||||
return node;
|
||||
}
|
||||
if (node.type === "VariableDeclaration") {
|
||||
const { declarations } = node;
|
||||
const init = declarations[0].init;
|
||||
if (init) {
|
||||
return getNodeCall(init);
|
||||
}
|
||||
}
|
||||
if (node.type === "AwaitExpression") {
|
||||
const { argument } = node;
|
||||
if (argument.type === "CallExpression") {
|
||||
return getNodeCall(argument);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function createError(outsideNode, insideNode) {
|
||||
const outsideCall = getNodeCall(outsideNode);
|
||||
const insideCall = getNodeCall(insideNode);
|
||||
throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
|
||||
}
|
||||
// validate hoistedNodes doesn't have nodes inside other nodes
|
||||
for (let i = 0; i < hoistedNodes.length; i++) {
|
||||
const node = hoistedNodes[i];
|
||||
for (let j = i + 1; j < hoistedNodes.length; j++) {
|
||||
const otherNode = hoistedNodes[j];
|
||||
if (node.start >= otherNode.start && node.end <= otherNode.end) {
|
||||
throw createError(otherNode, node);
|
||||
}
|
||||
if (otherNode.start >= node.start && otherNode.end <= node.end) {
|
||||
throw createError(node, otherNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
// hoist vi.mock/vi.hoisted
|
||||
for (const node of hoistedNodes) {
|
||||
const end = getNodeTail(code, node);
|
||||
// don't hoist into itself if it's already at the top
|
||||
if (hoistIndex === end || hoistIndex === node.start) {
|
||||
hoistIndex = end;
|
||||
} else {
|
||||
s.move(node.start, end, hoistIndex);
|
||||
}
|
||||
}
|
||||
// hoist actual dynamic imports last so they are inserted after all hoisted mocks
|
||||
for (const { node: importNode, id: importId } of imports) {
|
||||
const source = importNode.source.value;
|
||||
s.update(importNode.start, importNode.end, `const ${importId} = await import(${JSON.stringify(source)});\n`);
|
||||
if (importNode.start === hoistIndex) {
|
||||
// no need to hoist, but update hoistIndex to keep the order
|
||||
hoistIndex = importNode.end;
|
||||
} else {
|
||||
// There will be an error if the module is called before it is imported,
|
||||
// so the module import statement is hoisted to the top
|
||||
s.move(importNode.start, importNode.end, hoistIndex);
|
||||
}
|
||||
}
|
||||
if (!hoistedModuleImported && hoistedNodes.length) {
|
||||
const utilityImports = [...usedUtilityExports];
|
||||
// "vi" or "vitest" is imported from a module other than "vitest"
|
||||
if (utilityImports.some((name) => idToImportMap.has(name))) {
|
||||
s.prepend(API_NOT_FOUND_CHECK(utilityImports));
|
||||
} else if (utilityImports.length) {
|
||||
s.prepend(`import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({
|
||||
hires: "boundary",
|
||||
source: id
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function interceptorPlugin(options = {}) {
|
||||
@@ -794,9 +237,8 @@ class ServerMockResolver {
|
||||
const { id, fsPath, external } = await this.resolveMockId(rawId, importer);
|
||||
const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url;
|
||||
if (options.mock === "factory") {
|
||||
var _manifest$fsPath;
|
||||
const manifest = getViteDepsManifest(this.server.config);
|
||||
const needsInterop = (manifest === null || manifest === void 0 || (_manifest$fsPath = manifest[fsPath]) === null || _manifest$fsPath === void 0 ? void 0 : _manifest$fsPath.needsInterop) ?? false;
|
||||
const needsInterop = manifest?.[fsPath]?.needsInterop ?? false;
|
||||
return {
|
||||
mockType: "manual",
|
||||
resolvedId: id,
|
||||
@@ -865,7 +307,7 @@ class ServerMockResolver {
|
||||
return this.resolveModule(rawId, resolved);
|
||||
}
|
||||
resolveModule(rawId, resolved) {
|
||||
const id = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || rawId;
|
||||
const id = resolved?.id || rawId;
|
||||
const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
|
||||
return {
|
||||
id,
|
||||
@@ -964,4 +406,4 @@ function mockerPlugin(options = {}) {
|
||||
];
|
||||
}
|
||||
|
||||
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
|
||||
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
import fs from 'node:fs';
|
||||
import nodeModule from 'node:module';
|
||||
import module$1 from 'node:module';
|
||||
import { d as dirname, j as join, b as basename, r as resolve, e as extname } from './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
const { existsSync, readdirSync, statSync } = fs;
|
||||
@@ -42,7 +42,7 @@ function findMockRedirect(root, mockPath, external) {
|
||||
return existsSync(fullPath) ? fullPath : null;
|
||||
}
|
||||
const builtins = new Set([
|
||||
...nodeModule.builtinModules,
|
||||
...module$1.builtinModules,
|
||||
"assert/strict",
|
||||
"diagnostics_channel",
|
||||
"dns/promises",
|
||||
@@ -67,8 +67,8 @@ const prefixedBuiltins = new Set([
|
||||
const NODE_BUILTIN_NAMESPACE = "node:";
|
||||
function isNodeBuiltin(id) {
|
||||
// Added in v18.6.0
|
||||
if (nodeModule.isBuiltin) {
|
||||
return nodeModule.isBuiltin(id);
|
||||
if (module$1.isBuiltin) {
|
||||
return module$1.isBuiltin(id);
|
||||
}
|
||||
if (prefixedBuiltins.has(id)) {
|
||||
return true;
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-TnKRhz7N.js';
|
||||
import { M as ModuleMockerInterceptor, a as ModuleMockerCompilerHints, b as ModuleMocker } from './mocker.d-QEntlm6J.js';
|
||||
import '@vitest/spy';
|
||||
import './types.d-B8CCKmHt.js';
|
||||
import './index.d-C-sLYZi-.js';
|
||||
import './types.d-BjI5eAwu.js';
|
||||
import './index.d-B41z0AuW.js';
|
||||
|
||||
declare function registerModuleMocker(interceptor: (accessor: string) => ModuleMockerInterceptor): ModuleMockerCompilerHints;
|
||||
declare function registerNativeFactoryResolver(mocker: ModuleMocker): void;
|
||||
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
import { createMockInstance } from '@vitest/spy';
|
||||
import { M as ModuleMocker, r as rpc, c as createCompilerHints, h as hot } from './chunk-mocker.js';
|
||||
import './chunk-helpers.js';
|
||||
import './index.js';
|
||||
import './chunk-registry.js';
|
||||
import './chunk-pathe.M-eThtNZ.js';
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
export { c as createManualModuleSource, h as hoistMocks } from './hoistMocks.d-w2ILr1dG.js';
|
||||
export { automockModule } from './automock.js';
|
||||
import 'magic-string';
|
||||
|
||||
declare function initSyntaxLexers(): Promise<void>;
|
||||
declare function collectModuleExports(filename: string, code: string, format: "module" | "commonjs", exports?: string[]): string[];
|
||||
|
||||
export { collectModuleExports, initSyntaxLexers };
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export { c as createManualModuleSource } from './chunk-utils.js';
|
||||
export { a as automockModule, c as collectModuleExports, i as initSyntaxLexers } from './chunk-automock.js';
|
||||
export { h as hoistMocks } from './chunk-hoistMocks.js';
|
||||
import 'node:fs';
|
||||
import 'node:url';
|
||||
import 'magic-string';
|
||||
import 'estree-walker';
|
||||
import 'node:module';
|
||||
import 'node:path';
|
||||
import './chunk-helpers.js';
|
||||
Generated
Vendored
+23
-7
@@ -65,15 +65,15 @@ interface RedirectedModuleSerialized {
|
||||
raw: string;
|
||||
redirect: string;
|
||||
}
|
||||
declare class ManualMockedModule {
|
||||
declare class ManualMockedModule<T = any> {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
factory: () => any;
|
||||
cache: Record<string | symbol, any> | undefined;
|
||||
factory: () => T;
|
||||
cache: T | undefined;
|
||||
readonly type = "manual";
|
||||
constructor(raw: string, id: string, url: string, factory: () => any);
|
||||
resolve(): Promise<Record<string | symbol, any>>;
|
||||
constructor(raw: string, id: string, url: string, factory: () => T);
|
||||
resolve(): T;
|
||||
static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule;
|
||||
toJSON(): ManualMockedModuleSerialized;
|
||||
}
|
||||
@@ -102,6 +102,22 @@ interface ServerIdResolution {
|
||||
url: string;
|
||||
optimized: boolean;
|
||||
}
|
||||
interface ModuleMockContext {
|
||||
/**
|
||||
* When mocking with a factory, this refers to the module that imported the mock.
|
||||
*/
|
||||
callstack: null | string[];
|
||||
}
|
||||
interface TestModuleMocker {
|
||||
queueMock(id: string, importer: string, factoryOrOptions?: ModuleMockFactory | ModuleMockOptions): void;
|
||||
queueUnmock(id: string, importer: string): void;
|
||||
importActual<T>(rawId: string, importer: string, callstack?: string[] | null): Promise<T>;
|
||||
importMock(rawId: string, importer: string): Promise<any>;
|
||||
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
getMockContext(): ModuleMockContext;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as f, ManualMockedModule as g };
|
||||
export type { ServerMockResolution as S, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ServerIdResolution as e, AutomockedModuleSerialized as h, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as j, MockedModuleSerialized as k, RedirectedModuleSerialized as l, ModuleMockFactory as m };
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as h, ManualMockedModule as j };
|
||||
export type { ServerMockResolution as S, TestModuleMocker as T, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ModuleMockContext as e, ServerIdResolution as f, AutomockedModuleSerialized as g, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as k, MockedModuleSerialized as l, ModuleMockFactory as m, RedirectedModuleSerialized as n };
|
||||
+20
-9
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "@vitest/mocker",
|
||||
"type": "module",
|
||||
"version": "4.0.18",
|
||||
"version": "4.1.9",
|
||||
"description": "Vitest module mocker implementation",
|
||||
"license": "MIT",
|
||||
"funding": "https://opencollective.com/vitest",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker#readme",
|
||||
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/mocker",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vitest-dev/vitest.git",
|
||||
@@ -14,6 +14,11 @@
|
||||
"bugs": {
|
||||
"url": "https://github.com/vitest-dev/vitest/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"vitest",
|
||||
"test",
|
||||
"mock"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
@@ -44,7 +49,11 @@
|
||||
"types": "./dist/register.d.ts",
|
||||
"default": "./dist/register.js"
|
||||
},
|
||||
"./*": "./*"
|
||||
"./transforms": {
|
||||
"types": "./dist/transforms.d.ts",
|
||||
"default": "./dist/transforms.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
@@ -55,7 +64,7 @@
|
||||
],
|
||||
"peerDependencies": {
|
||||
"msw": "^2.4.9",
|
||||
"vite": "^6.0.0 || ^7.0.0-0"
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"msw": {
|
||||
@@ -68,16 +77,18 @@
|
||||
"dependencies": {
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^0.30.21",
|
||||
"@vitest/spy": "4.0.18"
|
||||
"@vitest/spy": "4.1.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/estree": "^1.0.8",
|
||||
"acorn-walk": "^8.3.4",
|
||||
"msw": "^2.12.3",
|
||||
"acorn-walk": "^8.3.5",
|
||||
"cjs-module-lexer": "^2.2.0",
|
||||
"es-module-lexer": "^2.0.0",
|
||||
"msw": "^2.12.10",
|
||||
"pathe": "^2.0.3",
|
||||
"vite": "^6.3.5",
|
||||
"@vitest/spy": "4.0.18",
|
||||
"@vitest/utils": "4.0.18"
|
||||
"@vitest/spy": "4.1.9",
|
||||
"@vitest/utils": "4.1.9"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "premove dist && rollup -c",
|
||||
|
||||
Reference in New Issue
Block a user