Skip to content

Commit

Permalink
Smarter path handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Gerrit0 committed Oct 18, 2024
1 parent f06401f commit ab8f4eb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
26 changes: 19 additions & 7 deletions src/lib/utils/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,25 @@ export async function loadPlugins(
const pluginDisplay = getPluginDisplayName(plugin);

try {
// On Windows, we need to ensure this path is a file path.
// Or we'll get ERR_UNSUPPORTED_ESM_URL_SCHEME
const esmPath = isAbsolute(plugin)
? pathToFileURL(plugin).toString()
: plugin;
let instance: any = await import(esmPath);
const initFunction = instance.load || instance.default?.load;
let instance: any;
// Try importing first to avoid warnings about requiring ESM being experimental.
// If that fails due to importing a directory, fall back to require.
try {
// On Windows, we need to ensure this path is a file path.
// Or we'll get ERR_UNSUPPORTED_ESM_URL_SCHEME
const esmPath = isAbsolute(plugin)
? pathToFileURL(plugin).toString()
: plugin;
instance = await import(esmPath);
} catch (error: any) {
if (error.code === "ERR_UNSUPPORTED_DIR_IMPORT") {
// eslint-disable-next-line @typescript-eslint/no-require-imports
instance = require(plugin);
} else {
throw error;
}
}
const initFunction = instance.load;

if (typeof initFunction === "function") {
await initFunction(app);
Expand Down
18 changes: 17 additions & 1 deletion src/test/utils/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe("loadPlugins", () => {
logger = fakeApp.logger = new TestLogger();
});

it("Should support loading a basic plugin", async () => {
it("Should support loading a CJS plugin with directory target", async () => {
using project = tempdirProject();
project.addJsonFile("package.json", {
type: "commonjs",
Expand All @@ -28,6 +28,22 @@ describe("loadPlugins", () => {
logger.expectMessage(`info: Loaded plugin ${plugin}`);
});

it("Should support loading a CJS plugin with full path", async () => {
using project = tempdirProject();
project.addJsonFile("package.json", {
type: "commonjs",
main: "index.js",
});
const plugin = project.addFile(
"index.js",
"exports.load = function load() {}",
).path;
project.write();

await loadPlugins(fakeApp, [plugin]);
logger.expectMessage(`info: Loaded plugin ${plugin}`);
});

it("Should support loading a ESM plugin", async () => {
using project = tempdirProject();
project.addJsonFile("package.json", {
Expand Down

0 comments on commit ab8f4eb

Please sign in to comment.