Fix hosting destructured decl with movable initializer (#17468)

This commit is contained in:
pfg
2025-02-19 20:21:52 -08:00
committed by GitHub
parent 6b2486a95d
commit 92a91ef2fd
4 changed files with 17 additions and 8 deletions

View File

@@ -13131,7 +13131,6 @@ pub const LinkerContext = struct {
const ExportHoist = struct {
decls: std.ArrayListUnmanaged(G.Decl),
allocator: std.mem.Allocator,
next_value: ?Expr = null,
pub fn wrapIdentifier(w: *@This(), loc: Logger.Loc, ref: Ref) Expr {
w.decls.append(
@@ -13144,7 +13143,7 @@ pub const LinkerContext = struct {
},
loc,
),
.value = w.next_value,
.value = null,
},
) catch bun.outOfMemory();
@@ -13170,16 +13169,20 @@ pub const LinkerContext = struct {
for (local.decls.slice()) |*decl| {
if (decl.value) |initializer| {
const can_be_moved = initializer.canBeMoved();
hoist.next_value = if (can_be_moved) initializer else null;
const binding = decl.binding.toExpr(&hoist);
if (!can_be_moved) {
if (can_be_moved) {
// if the value can be moved, move the decl directly to preserve destructuring
// ie `const { main } = class { static main() {} }` => `var {main} = class { static main() {} }`
hoist.decls.append(hoist.allocator, decl.*) catch bun.outOfMemory();
} else {
// if the value cannot be moved, add every destructuring key seperately
// ie `var { append } = { append() {} }` => `var append; __esm(() => ({ append } = { append() {} }))`
const binding = decl.binding.toExpr(&hoist);
value = value.joinWithComma(
binding.assign(initializer),
temp_allocator,
);
}
} else {
hoist.next_value = null;
_ = decl.binding.toExpr(&hoist);
}
}
@@ -13200,8 +13203,6 @@ pub const LinkerContext = struct {
continue;
}
hoist.next_value = null;
break :stmt Stmt.allocateExpr(
temp_allocator,
Expr.assign(hoist.wrapIdentifier(

View File

@@ -0,0 +1,5 @@
import { $ } from "bun";
test("destructure string does not become string", async () => {
const result = await $`bun build --target=node f2.ts | bun -`.cwd(import.meta.dir).text();
expect(result).toBe("[Function: replace]\n");
});

View File

@@ -0,0 +1,2 @@
const contents_esm = await import("./repro");
console.log(contents_esm.replace);

View File

@@ -0,0 +1 @@
export const { replace } = "error!";