Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/runtime/plugins.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ The second argument to `onResolve()` is a callback that runs for each module imp

The callback receives the _path_ to the matching module and can return a _new path_ for it. Bun reads the contents of the _new path_ and parses it as a module.

At runtime, the callback runs once for each `import` or `require()` as it executes. A _new path_ without a `namespace` is resolved from the importing module like any other import, without running `onResolve()` callbacks on it: it can be relative, leave out its extension, or name a package. If nothing is found there, the _new path_ is used as it is when an [`onLoad()`](#onload) callback matches it, so it does not have to exist on disk.
At runtime, the callback runs once for each `import` or `require()` as it executes. A _new path_ without a `namespace` is resolved from the importing module like any other import, without running `onResolve()` callbacks on it: it can be relative, leave out its extension, or name a package. If nothing is found there, the _new path_ is used as it is when an [`onLoad()`](#onload) callback matches it, so it does not have to exist on disk. Such a path is never [auto-installed](/runtime/auto-install).

For example, redirecting all imports to `images/` to `./public/images/`:

Expand Down
2 changes: 1 addition & 1 deletion packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6393,7 +6393,7 @@ declare module "bun" {
* In a runtime plugin, a path without a `namespace` is resolved from the
* importing module like any other import, without running `onResolve`
* callbacks on it. If nothing is found there, it is used as it is when an
* `onLoad` callback matches it.
* `onLoad` callback matches it, and such a path is never auto-installed.
*/
path: string;
/**
Expand Down
15 changes: 13 additions & 2 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5035,6 +5035,7 @@ impl VirtualMachine {
source: &[u8],
is_esm: bool,
is_a_file_path: bool,
global_cache: bun_resolver::GlobalCache,
) -> crate::CrateResult<()> {
use bun_js_parser::Macro;
use bun_resolver::{ResultUnion, node_fallbacks};
Expand Down Expand Up @@ -5124,7 +5125,6 @@ impl VirtualMachine {
} else {
bun_ast::ImportKind::Require
};
let global_cache = self.transpiler.resolver.opts.global_cache;
match self.transpiler.resolver.resolve_and_auto_install(
source_to_use,
normalized_specifier,
Expand Down Expand Up @@ -5226,15 +5226,23 @@ impl VirtualMachine {
if let Some(name) = global.resolve_virtual_module(&answer, source) {
return Ok(Ok(name));
}
let has_on_load = global.has_on_load(&answer.to_utf8())?;
// The plugin's own name for a module may be a package's in the registry.
let global_cache = if has_on_load || answer.eql(specifier) {
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
bun_resolver::GlobalCache::disable
} else {
global.bun_vm().transpiler.resolver.opts.global_cache
};
let resolved = Self::resolve_without_on_resolve::<IS_A_FILE_PATH>(
global,
&answer,
source,
query_string,
mode,
global_cache,
)?;
// Not on disk, for an `onLoad` to serve.
if resolved.is_err() && global.has_on_load(&answer.to_utf8())? {
if resolved.is_err() && has_on_load {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return Ok(Ok(answer));
}
return Ok(resolved);
Expand All @@ -5247,6 +5255,7 @@ impl VirtualMachine {
source,
query_string,
mode,
global.bun_vm().transpiler.resolver.opts.global_cache,
)
}

Expand All @@ -5256,6 +5265,7 @@ impl VirtualMachine {
source: &bun_core::String,
query_string: Option<&mut bun_core::String>,
mode: ResolveMode,
global_cache: bun_resolver::GlobalCache,
) -> JsResult<Result<bun_core::String, JSValue>> {
const MAX_LEN: usize = (bun_paths::MAX_PATH_BYTES as f64 * 1.5) as usize;
// `data:` URLs carry the module source inline and never touch the
Expand Down Expand Up @@ -5401,6 +5411,7 @@ impl VirtualMachine {
normalize_source(source_utf8.slice()),
mode.is_esm(),
IS_A_FILE_PATH,
global_cache,
);
if let Err(err_) = resolve_result {
let err = err_;
Expand Down
106 changes: 106 additions & 0 deletions test/js/bun/plugin/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1313,6 +1313,112 @@ describe.concurrent("what onResolve answers without a namespace", () => {
});
});

// Without a node_modules directory, Bun installs the package it does not find.
describe.concurrent("the registry is not asked for what a plugin serves or onResolve answers with itself", () => {
it.each([
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
[
"an import statement",
"entry.mjs",
`import a from "served.ask"; import b from "itself-served.js"; console.log(a, b);`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
[
"import()",
"entry.mjs",
`console.log((await import("served.ask")).default, (await import("itself-served.js")).default);`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
[
"require()",
"entry.cjs",
`console.log(require("served.ask").default, require("itself-served.js").default);`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
[
"require.resolve()",
"entry.cjs",
`console.log(require.resolve("served.ask"), require.resolve("itself-served.js"));
for (const specifier of ["package.ask", "itself-not-served.js"])
try { require.resolve(specifier); } catch (error) { console.log(error.message.split("\\n")[0]); }`,
"virtual.js itself-served.js\nCannot find module 'a-package'\nCannot find module 'itself-not-served.js'\n",
// The name of a package is not the plugin's.
["/a-package", "/not-answered"],
],
[
"import.meta.require()",
"entry.mjs",
`console.log(import.meta.require("served.ask").default, import.meta.require("itself-served.js").default);`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
[
"import.meta.resolve()",
"entry.mjs",
`console.log(import.meta.resolve("served.ask"), import.meta.resolve("itself-served.js"));`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
[
"Bun.resolveSync()",
"entry.mjs",
`console.log(Bun.resolveSync("served.ask", import.meta.dir), Bun.resolveSync("itself-served.js", import.meta.dir));`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
[
"Bun.resolve()",
"entry.mjs",
`console.log(await Bun.resolve("served.ask", import.meta.dir), await Bun.resolve("itself-served.js", import.meta.dir));`,
"virtual.js itself-served.js\n",
["/not-answered"],
],
])("by %s", async (_, name, source, stdout, expected) => {
const asked: string[] = [];
using registry = Bun.serve({
port: 0,
fetch(request) {
asked.push(new URL(request.url).pathname);
return new Response("{}", { status: 404 });
},
});
using dir = tempDir("plugin-onresolve-registry", {
"plugin.ts": `
const answers = { "served.ask": "virtual.js", "package.ask": "a-package" };
Bun.plugin({
name: "answers",
setup(build) {
build.onResolve({ filter: /\\.ask$/ }, ({ path }) => ({ path: answers[path] }));
build.onResolve({ filter: /^itself-/ }, ({ path }) => ({ path }));
build.onLoad({ filter: /^(virtual|itself-served)\\.js$/ }, ({ path }) => ({
contents: "export default " + JSON.stringify(path),
loader: "js",
}));
},
});
`,
// The last line is what no plugin answers about, which is asked of the registry.
[name]: source + `\nimport("not-answered").catch(() => {});`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "--preload", "./plugin.ts", name],
cwd: String(dir),
env: {
...bunEnv,
BUN_CONFIG_REGISTRY: registry.url.href,
NPM_CONFIG_REGISTRY: registry.url.href,
BUN_INSTALL_CACHE_DIR: resolve(String(dir), ".cache"),
},
stdout: "pipe",
stderr: "pipe",
});
const [out, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect({ stdout: out, stderr, exitCode, asked }).toEqual({ stdout, stderr: "", exitCode: 0, asked: expected });
});
});

it.concurrent("an onLoad in the namespace of builtins leaves their aliases alone", async () => {
const source = `
Bun.plugin({ name: "node", setup(build) { build.onLoad({ filter: /^never$/, namespace: "node" }, () => {}); } });
Expand Down
Loading