fix(natives): detect compiled-binary mode via embedded-addon presence

Standalone Bun binaries on WSL (and any host where the user moves the
binary away from the build-host's checkout) failed to load
pi_natives.<platform>-<arch>*.node. The loader's isCompiledBinary
detection relied on two signals that are both false in shipped binaries:
process.env.PI_COMPILED (bun --define PI_COMPILED=true substitutes the
bare identifier, not property accesses on process.env) and
__filename.includes("$bunfs") (Bun retains the build-host absolute path
in __filename for required CJS modules — only import.meta.url is
rewritten). Detection therefore returned false, embedded-addon
extraction was skipped, and the only candidates probed were the
build-host nativeDir and execDir.

Make embedded-addon presence the authoritative compiled-mode signal
(it is null in the post-build --reset stub, populated when embed:native
ran for the standalone build), eagerly require the manifest, and
extract candidate-path computation into a pure helper covered by a
host-platform-agnostic unit test. Also fix the build-time --define so
process.env.PI_COMPILED is genuinely set at runtime as a defensive
fallback.

Fixes #823
This commit is contained in:
can1357
2026-04-30 04:39:38 +02:00
parent d731e57513
commit e39d3d9c76
9 changed files with 283 additions and 65 deletions
-27
View File
@@ -129,32 +129,6 @@ async function installBinary(src: string, dest: string): Promise<void> {
}
}
}
async function patchGeneratedIndexLoader(): Promise<void> {
const indexPath = path.join(nativeDir, "index.js");
let content = await Bun.file(indexPath).text();
const embeddedLoadPatch = "let embeddedAddon = null;\n";
if (!content.includes(embeddedLoadPatch)) {
content = content.replace(/const \{ embeddedAddon \} = require\("\.\/embedded-addon"\);\n/, embeddedLoadPatch);
}
const lazyLoadPatch = [
"if (isCompiledBinary) {",
"\ttry {",
'\t\t({ embeddedAddon } = require("./embedded-addon"));',
"\t} catch {",
"\t\tembeddedAddon = null;",
"\t}",
"}",
"",
].join("\n");
if (!content.includes(lazyLoadPatch)) {
content = content.replace(
/(const isCompiledBinary =[\s\S]*?__filename\.includes\("%7EBUN"\);\n)/,
`$1\n${lazyLoadPatch}`,
);
}
await Bun.write(indexPath, content);
}
async function resolveBuiltAddonPath(outputDir: string, canonicalFilename: string): Promise<string> {
// napi-rs 3.x emits `${binaryName}.${platformArchABI}.node` where
// platformArchABI is e.g. `darwin-x64`, `linux-x64-gnu`, `win32-x64-msvc`,
@@ -308,7 +282,6 @@ try {
await installGeneratedBindings(buildOutputDir);
await generateEnumExports();
await patchGeneratedIndexLoader();
console.log("Build complete.");
} finally {