@storm-stack/core
Version:
A build toolkit and runtime used by Storm Software in TypeScript applications
109 lines (106 loc) • 3.31 kB
JavaScript
import { __name } from './chunk-IRPJW6HH.js';
import { declare } from '@babel/helper-plugin-utils';
import * as t from '@babel/types';
function resolveModulePath(nodePath, state) {
if (!t.isStringLiteral(nodePath.node)) {
return;
}
const sourcePath = nodePath.node.value;
const resolvedPath = state.context?.vfs.resolvePath(sourcePath);
if (resolvedPath) {
nodePath.replaceWith(t.stringLiteral(
// Remove the file extension if it exists
resolvedPath.replace(/\.(?:ts|mts|cts)x?$/, "")
));
}
}
__name(resolveModulePath, "resolveModulePath");
var TRANSFORM_FUNCTIONS = [
"require",
"require.resolve",
"System.import",
// Jest methods
"jest.genMockFromModule",
"jest.mock",
"jest.unmock",
"jest.doMock",
// eslint-disable-next-line @cspell/spellchecker
"jest.dontMock",
"jest.setMock",
"jest.requireActual",
"jest.requireMock",
// Older Jest methods
"require.requireActual",
"require.requireMock"
];
function matchesPattern(state, calleePath, pattern) {
const { node } = calleePath;
if (t.isMemberExpression(node)) {
return calleePath.matchesPattern(pattern);
}
if (!t.isIdentifier(node) || pattern.includes(".")) {
return false;
}
const name = pattern.split(".")[0];
return node.name === name;
}
__name(matchesPattern, "matchesPattern");
var importVisitors = {
CallExpression: /* @__PURE__ */ __name((nodePath, state) => {
if (state.moduleResolverVisited.has(nodePath)) {
return;
}
const calleePath = nodePath.get("callee");
if (calleePath && TRANSFORM_FUNCTIONS.some((pattern) => matchesPattern(state, calleePath, pattern)) || t.isImport(nodePath.node.callee)) {
state.moduleResolverVisited.add(nodePath);
resolveModulePath(nodePath.get("arguments.0"), state);
}
}, "CallExpression"),
// eslint-disable-next-line ts/naming-convention
"ImportDeclaration|ExportDeclaration|ExportAllDeclaration": /* @__PURE__ */ __name((nodePath, state) => {
if (!nodePath || !nodePath.get("source") || state.moduleResolverVisited.has(nodePath)) {
return;
}
state.moduleResolverVisited.add(nodePath);
resolveModulePath(nodePath.get("source"), state);
}, "ImportDeclaration|ExportDeclaration|ExportAllDeclaration")
};
function ModuleResolverPlugin(context) {
return declare(/* @__PURE__ */ __name(function builder(api) {
let moduleResolverVisited = /* @__PURE__ */ new Set();
return {
name: "storm-stack:module-resolver",
manipulateOptions(opts) {
opts.filename ??= "unknown";
},
pre() {
moduleResolverVisited = /* @__PURE__ */ new Set();
},
visitor: {
Program: {
enter(programPath, state) {
programPath.traverse(importVisitors, {
...state,
context,
moduleResolverVisited,
api
});
},
exit(programPath, state) {
programPath.traverse(importVisitors, {
...state,
context,
moduleResolverVisited,
api
});
}
}
},
post() {
moduleResolverVisited.clear();
}
};
}, "builder"));
}
__name(ModuleResolverPlugin, "ModuleResolverPlugin");
export { ModuleResolverPlugin };