From 84576bd84817079ea73a4d8ad9d57a7b91dc411f Mon Sep 17 00:00:00 2001
From: fry69 <142489379+fry69@users.noreply.github.com>
Date: Sun, 5 Oct 2025 10:53:55 +0200
Subject: [PATCH] fix: prevent island names from shadowing JavaScript globals
(#3522)
fix #3521
Generated PR message below
---
## Problem
Island files named after JavaScript global objects (e.g., Map.tsx,
`Set.tsx`, `Array.tsx`, `Promise.tsx`) cause runtime errors. The
generated boot code uses object shorthand syntax that resolves to the
global constructor instead of the imported component:
```javascript
import Map from "/islands/Map.tsx";
boot({Map}, props); // {Map} resolves to global Map constructor
```
This results in `TypeError: Map is not a constructor` when the runtime
attempts to instantiate islands.
## Solution
Generate safe prefixed variable names (`__FRSH_ISLAND_N`) for island
imports and use explicit object property syntax to preserve the original
island names:
```javascript
import __FRSH_ISLAND_0 from "/islands/Map.tsx";
boot({"Map":__FRSH_ISLAND_0}, props);
```
This approach:
- Eliminates variable shadowing in all contexts (no scope collisions)
- Preserves original island names in HTML markers, error messages, and
runtime registry
- Allows any valid filename without restrictions
- Follows existing Fresh conventions for generated identifiers
## Changes
- preact_hooks.ts: Updated client-side boot script generation
- dev_build_cache.ts: Updated server-side snapshot generation
- Added integration tests for both Builder and Vite build systems
- Added documentation comment explaining why globals aren't in
`JS_RESERVED`
## Testing
Both tests verify that islands named after globals build successfully
and use safe variable names in generated code. Tests confirm the bug is
detected when fixes are reverted.
---
packages/fresh/src/dev/builder_test.ts | 67 +++++++++++++
packages/fresh/src/utils.ts | 94 +++++++++++++++++++
packages/plugin-vite/tests/build_test.ts | 24 +++++
.../fixtures/island_global_name/deno.json | 8 ++
.../island_global_name/islands/Map.tsx | 24 +++++
.../tests/fixtures/island_global_name/main.ts | 3 +
.../island_global_name/routes/index.tsx | 5 +
.../island_global_name/vite.config.ts | 6 ++
8 files changed, 231 insertions(+)
create mode 100644 packages/plugin-vite/tests/fixtures/island_global_name/deno.json
create mode 100644 packages/plugin-vite/tests/fixtures/island_global_name/islands/Map.tsx
create mode 100644 packages/plugin-vite/tests/fixtures/island_global_name/main.ts
create mode 100644 packages/plugin-vite/tests/fixtures/island_global_name/routes/index.tsx
create mode 100644 packages/plugin-vite/tests/fixtures/island_global_name/vite.config.ts
diff --git a/packages/fresh/src/dev/builder_test.ts b/packages/fresh/src/dev/builder_test.ts
index cd973646..fb921114 100644
--- a/packages/fresh/src/dev/builder_test.ts
+++ b/packages/fresh/src/dev/builder_test.ts
@@ -838,3 +838,70 @@ Deno.test("specToName", () => {
expect(specToName("/islands/_bar-baz-...-$.tsx")).toEqual("_bar_baz_$");
expect(specToName("/islands/1_hello.tsx")).toEqual("_hello");
});
+
+Deno.test({
+ name: "Builder - island named after global object (Map)",
+ fn: async () => {
+ const root = path.join(import.meta.dirname!, "..", "..");
+ await using _tmp = await withTmpDir({ dir: root, prefix: "tmp_builder_" });
+ const tmp = _tmp.dir;
+
+ await writeFiles(tmp, {
+ "islands/Map.tsx": `import { useSignal } from "@preact/signals";
+import { useEffect } from "preact/hooks";
+
+export default function Map() {
+ const ready = useSignal(false);
+ const count = useSignal(0);
+
+ useEffect(() => {
+ ready.value = true;
+ }, []);
+
+ return (
+
+
{count.value}
+
+
+ );
+}`,
+ "routes/index.tsx": `import Map from "../islands/Map.tsx";
+export default () => ;`,
+ "main.ts": `import { App } from "fresh";
+export const app = new App().fsRoutes();`,
+ });
+
+ const builder = new Builder({
+ root: tmp,
+ outDir: path.join(tmp, "dist"),
+ });
+
+ // Register the island manually
+ const islandPath = path.join(tmp, "islands", "Map.tsx");
+ builder.registerIsland(path.toFileUrl(islandPath).href);
+
+ await builder.build();
+
+ await withChildProcessServer(
+ { cwd: tmp, args: ["serve", "-A", "dist/server.js"] },
+ async (address) => {
+ const res = await fetch(address);
+ const html = await res.text();
+
+ // Verify the fix: UniqueNamer prefixes "Map" with underscore to prevent shadowing
+ // Without the fix: import Map from "..." and boot({Map}, ...) - shadows global Map
+ // With the fix: import _Map_N from "..." and boot({_Map_N}, ...) - no shadowing
+ expect(html).toMatch(/import\s+_Map_\d+\s+from/);
+ expect(html).toMatch(/boot\(\s*\{\s*_Map_\d+\s*\}/);
+ },
+ );
+ },
+ sanitizeOps: false,
+ sanitizeResources: false,
+});
diff --git a/packages/fresh/src/utils.ts b/packages/fresh/src/utils.ts
index ee2ebf64..96952e34 100644
--- a/packages/fresh/src/utils.ts
+++ b/packages/fresh/src/utils.ts
@@ -76,7 +76,9 @@ export class UniqueNamer {
}
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
+// Includes JavaScript reserved keywords and global objects to prevent variable shadowing
const JS_RESERVED = new Set([
+ // Reserved keywords
"break",
"case",
"catch",
@@ -147,6 +149,98 @@ const JS_RESERVED = new Set([
"get",
"of",
"set",
+ // JavaScript built-in objects that could cause shadowing bugs
+ "Array",
+ "ArrayBuffer",
+ "Boolean",
+ "DataView",
+ "Date",
+ "Error",
+ "EvalError",
+ "Float32Array",
+ "Float64Array",
+ "Function",
+ "Infinity",
+ "Int8Array",
+ "Int16Array",
+ "Int32Array",
+ "Intl",
+ "JSON",
+ "Map",
+ "Math",
+ "NaN",
+ "Number",
+ "Object",
+ "Promise",
+ "Proxy",
+ "RangeError",
+ "ReferenceError",
+ "Reflect",
+ "RegExp",
+ "Set",
+ "String",
+ "Symbol",
+ "SyntaxError",
+ "TypeError",
+ "Uint8Array",
+ "Uint8ClampedArray",
+ "Uint16Array",
+ "Uint32Array",
+ "URIError",
+ "WeakMap",
+ "WeakSet",
+ "BigInt",
+ "BigInt64Array",
+ "BigUint64Array",
+ // Web APIs commonly used in islands
+ "console",
+ "fetch",
+ "Request",
+ "Response",
+ "Headers",
+ "URL",
+ "URLSearchParams",
+ "Event",
+ "EventTarget",
+ "AbortController",
+ "AbortSignal",
+ "FormData",
+ "Blob",
+ "File",
+ "FileReader",
+ "TextEncoder",
+ "TextDecoder",
+ "ReadableStream",
+ "WritableStream",
+ "TransformStream",
+ "WebSocket",
+ "Worker",
+ "MessageChannel",
+ "MessagePort",
+ "BroadcastChannel",
+ "crypto",
+ "atob",
+ "btoa",
+ "setTimeout",
+ "setInterval",
+ "clearTimeout",
+ "clearInterval",
+ "queueMicrotask",
+ "structuredClone",
+ // Browser-specific globals
+ "document",
+ "window",
+ "navigator",
+ "location",
+ "history",
+ "localStorage",
+ "sessionStorage",
+ // Deno-specific globals
+ "Deno",
+ // Node.js compatibility globals (for Deno's Node compat mode)
+ "process",
+ "global",
+ "Buffer",
]);
const PATH_TO_SPEC = /[\\/]+/g;
diff --git a/packages/plugin-vite/tests/build_test.ts b/packages/plugin-vite/tests/build_test.ts
index 5bc45208..b538037c 100644
--- a/packages/plugin-vite/tests/build_test.ts
+++ b/packages/plugin-vite/tests/build_test.ts
@@ -542,3 +542,27 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
});
+
+Deno.test({
+ name: "vite build - island named after global object (Map)",
+ fn: async () => {
+ const fixture = path.join(FIXTURE_DIR, "island_global_name");
+ await using res = await buildVite(fixture);
+
+ await launchProd(
+ { cwd: res.tmp },
+ async (address) => {
+ const response = await fetch(address);
+ const html = await response.text();
+
+ // Verify the fix: UniqueNamer prefixes "Map" with underscore to prevent shadowing
+ // Without the fix: import Map from "..." and boot({Map}, ...) - shadows global Map
+ // With the fix: import _Map_N from "..." and boot({_Map_N}, ...) - no shadowing
+ expect(html).toMatch(/import.*_Map(_\d+)?.*from/);
+ expect(html).toMatch(/boot\(\s*\{\s*_Map(_\d+)?\s*\}/);
+ },
+ );
+ },
+ sanitizeOps: false,
+ sanitizeResources: false,
+});
diff --git a/packages/plugin-vite/tests/fixtures/island_global_name/deno.json b/packages/plugin-vite/tests/fixtures/island_global_name/deno.json
new file mode 100644
index 00000000..54cc5dbc
--- /dev/null
+++ b/packages/plugin-vite/tests/fixtures/island_global_name/deno.json
@@ -0,0 +1,8 @@
+{
+ "imports": {
+ "fresh": "jsr:@fresh/core",
+ "@preact/signals": "npm:@preact/signals@^1.3.0",
+ "preact": "npm:preact@^10.26.1",
+ "preact/": "npm:/preact@^10.26.1/"
+ }
+}
diff --git a/packages/plugin-vite/tests/fixtures/island_global_name/islands/Map.tsx b/packages/plugin-vite/tests/fixtures/island_global_name/islands/Map.tsx
new file mode 100644
index 00000000..a7f15654
--- /dev/null
+++ b/packages/plugin-vite/tests/fixtures/island_global_name/islands/Map.tsx
@@ -0,0 +1,24 @@
+import { useSignal } from "@preact/signals";
+import { useEffect } from "preact/hooks";
+
+export default function Map() {
+ const ready = useSignal(false);
+ const count = useSignal(0);
+
+ useEffect(() => {
+ ready.value = true;
+ }, []);
+
+ return (
+
+
{count.value}
+
+
+ );
+}
diff --git a/packages/plugin-vite/tests/fixtures/island_global_name/main.ts b/packages/plugin-vite/tests/fixtures/island_global_name/main.ts
new file mode 100644
index 00000000..287ca00a
--- /dev/null
+++ b/packages/plugin-vite/tests/fixtures/island_global_name/main.ts
@@ -0,0 +1,3 @@
+import { App } from "fresh";
+
+export const app = new App().fsRoutes();
diff --git a/packages/plugin-vite/tests/fixtures/island_global_name/routes/index.tsx b/packages/plugin-vite/tests/fixtures/island_global_name/routes/index.tsx
new file mode 100644
index 00000000..27058dc2
--- /dev/null
+++ b/packages/plugin-vite/tests/fixtures/island_global_name/routes/index.tsx
@@ -0,0 +1,5 @@
+import Map from "../islands/Map.tsx";
+
+export default function Page() {
+ return ;
+}
diff --git a/packages/plugin-vite/tests/fixtures/island_global_name/vite.config.ts b/packages/plugin-vite/tests/fixtures/island_global_name/vite.config.ts
new file mode 100644
index 00000000..727d49a2
--- /dev/null
+++ b/packages/plugin-vite/tests/fixtures/island_global_name/vite.config.ts
@@ -0,0 +1,6 @@
+import { defineConfig } from "vite";
+import { fresh } from "@fresh/plugin-vite";
+
+export default defineConfig({
+ plugins: [fresh()],
+});