diff --git a/packages/plugin-vite/demo/islands/IslandNestedInner.tsx b/packages/plugin-vite/demo/islands/IslandNestedInner.tsx new file mode 100644 index 00000000..3d6312f3 --- /dev/null +++ b/packages/plugin-vite/demo/islands/IslandNestedInner.tsx @@ -0,0 +1,15 @@ +import { useEffect, useState } from "preact/hooks"; + +export function IslandNestedInner() { + const [ready, set] = useState(false); + + useEffect(() => { + set(true); + }, []); + + return ( +
+

Inner

+
+ ); +} diff --git a/packages/plugin-vite/demo/islands/IslandNestedOuter.tsx b/packages/plugin-vite/demo/islands/IslandNestedOuter.tsx new file mode 100644 index 00000000..c91c58d8 --- /dev/null +++ b/packages/plugin-vite/demo/islands/IslandNestedOuter.tsx @@ -0,0 +1,17 @@ +import { useEffect, useState } from "preact/hooks"; +import { IslandNestedInner } from "./IslandNestedInner.tsx"; + +export function IslandNestedOuter() { + const [ready, set] = useState(false); + + useEffect(() => { + set(true); + }, []); + + return ( +
+

Outer

+ +
+ ); +} diff --git a/packages/plugin-vite/demo/islands/tests/JsrIsland.tsx b/packages/plugin-vite/demo/islands/tests/JsrIsland.tsx deleted file mode 100644 index dbecc138..00000000 --- a/packages/plugin-vite/demo/islands/tests/JsrIsland.tsx +++ /dev/null @@ -1 +0,0 @@ -export { RemoteIsland } from "@marvinh-test/fresh-island"; diff --git a/packages/plugin-vite/demo/routes/tests/island_nested.tsx b/packages/plugin-vite/demo/routes/tests/island_nested.tsx new file mode 100644 index 00000000..a86ff4e3 --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/island_nested.tsx @@ -0,0 +1,9 @@ +import { IslandNestedOuter } from "../../islands/IslandNestedOuter.tsx"; + +export default function Page() { + return ( +
+ +
+ ); +} diff --git a/packages/plugin-vite/demo/vite.config.ts b/packages/plugin-vite/demo/vite.config.ts index c52dc3e3..ecb4d370 100644 --- a/packages/plugin-vite/demo/vite.config.ts +++ b/packages/plugin-vite/demo/vite.config.ts @@ -6,7 +6,9 @@ import tailwind from "@tailwindcss/vite"; export default defineConfig({ plugins: [ inspect(), - fresh(), + fresh({ + islandSpecifiers: ["@marvinh-test/fresh-island"], + }), tailwind(), ], }); diff --git a/packages/plugin-vite/src/mod.ts b/packages/plugin-vite/src/mod.ts index 8f2415fe..ffc818ed 100644 --- a/packages/plugin-vite/src/mod.ts +++ b/packages/plugin-vite/src/mod.ts @@ -110,7 +110,6 @@ export function fresh(config?: FreshViteConfig): Plugin[] { preserveEntrySignatures: "strict", input: { "client-entry": "fresh:client-entry", - "client-snapshot": "fresh:client-snapshot", }, }, }, @@ -186,7 +185,7 @@ export function fresh(config?: FreshViteConfig): Plugin[] { patches(), ...serverSnapshot(fConfig), clientEntryPlugin(fConfig), - clientSnapshot(fConfig), + ...clientSnapshot(fConfig), buildIdPlugin(), ...devServer(), prefresh({ diff --git a/packages/plugin-vite/src/plugins/client_snapshot.ts b/packages/plugin-vite/src/plugins/client_snapshot.ts index 9fcf40bb..f555b472 100644 --- a/packages/plugin-vite/src/plugins/client_snapshot.ts +++ b/packages/plugin-vite/src/plugins/client_snapshot.ts @@ -1,94 +1,188 @@ import type { Plugin, ViteDevServer } from "vite"; -import type { ResolvedFreshViteConfig } from "../utils.ts"; -import { crawlFsItem } from "fresh/internal-dev"; +import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts"; +import { crawlFsItem, specToName } from "fresh/internal-dev"; +import * as path from "@std/path"; -export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin { +export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin[] { const modName = "fresh:client-snapshot"; const islands = new Set(); let server: ViteDevServer | undefined; let isDev = false; - return { - name: "fresh:client-snapshot", - applyToEnvironment(env) { - return env.name === "client"; - }, - config(_, env) { - isDev = env.command === "serve"; + const entryToIsland = new Map(); - return { - environments: { - client: { - build: { - rollupOptions: { - input: { - "client-snapshot": "fresh:client-snapshot", + return [ + { + name: "fresh:client-snapshot", + applyToEnvironment(env) { + return env.name === "client"; + }, + + async config(cfg, env) { + isDev = env.command === "serve"; + + const cwd = Deno.cwd(); + + const result = await crawlFsItem({ + islandDir: pathWithRoot(options.islandsDir, cfg.root ?? cwd), + routeDir: pathWithRoot(options.routeDir, cfg.root ?? cwd), + ignore: options.ignore, + }); + + const input: Record = {}; + + if (isDev) { + input["client-snapshot"] = "fresh:client-snapshot"; + } + + for (let i = 0; i < result.islands.length; i++) { + const filePath = result.islands[i]; + islands.add(filePath); + + if (!isDev) { + const specName = specToName(filePath); + const name = options.namer.getUniqueName(specName); + + entryToIsland.set(name, filePath); + input[`fresh-island::${name}`] = `fresh-client-island::${name}`; + } + } + + return { + environments: { + client: { + build: { + rollupOptions: { + input, }, }, }, }, - }, - }; - }, - configResolved() { - options.islandSpecifiers.forEach((_name, spec) => { - islands.add(spec); - }); - }, - async buildStart() { - const result = await crawlFsItem({ - islandDir: options.islandsDir, - routeDir: options.routeDir, - ignore: options.ignore, - }); - - for (let i = 0; i < result.islands.length; i++) { - const filePath = result.islands[i]; - islands.add(filePath); - } - }, - configureServer(devServer) { - server = devServer; - }, - resolveId: { - filter: { - id: /fresh:client-snapshot/, + }; }, - handler(id) { - if (id === modName) { - return `\0${modName}`; + configResolved(cfg) { + for (const [name, spec] of entryToIsland.entries()) { + const full = pathWithRoot(spec, cfg.root); + entryToIsland.set(name, full); } }, - }, - load: { - filter: { - id: /\0fresh:client-snapshot/, - }, - handler() { - const imports = Array.from(islands.keys()).map((file, i) => { - return `export const mod_${i} = await import(${ - JSON.stringify(file) - });`; - }).join("\n"); + options(opts) { + options.islandSpecifiers.forEach((_name, spec) => { + islands.add(spec); - if (isDev && server !== undefined) { - const mod = server.environments.ssr.moduleGraph.getModuleById( - "\0fresh:server-snapshot", - ); - if (mod) { - server.environments.ssr.moduleGraph.invalidateModule(mod); + if (!isDev) { + const specName = specToName(spec); + const name = options.namer.getUniqueName(specName); + entryToIsland.set(name, spec); + + // deno-lint-ignore no-explicit-any + (opts.input as any)[`fresh-island::${name}`] = + `fresh-client-island::${name}`; } - } + }); + }, + configureServer(devServer) { + server = devServer; - return `${imports} + server.watcher.on("add", (filePath) => { + if (!isIslandPath(options, filePath)) return; + + islands.add(filePath); + + invalidateSnapshots(server!); + }); + server.watcher.on("unlink", (filePath) => { + if (!isIslandPath(options, filePath)) return; + + islands.delete(filePath); + + invalidateSnapshots(server!); + }); + }, + resolveId: { + filter: { + id: /fresh:client-snapshot/, + }, + handler(id) { + if (id === modName) { + return `\0${modName}`; + } + }, + }, + load: { + filter: { + id: /\0fresh:client-snapshot/, + }, + handler() { + const imports = Array.from(islands.keys()).map((file, i) => { + return `export const mod_${i} = await import(${ + JSON.stringify(file) + });`; + }).join("\n"); + + if (isDev && server !== undefined) { + const mod = server.environments.ssr.moduleGraph.getModuleById( + "\0fresh:server-snapshot", + ); + if (mod) { + server.environments.ssr.moduleGraph.invalidateModule(mod); + } + } + + return `${imports} if (import.meta.hot) { import.meta.hot.accept(() => { console.log("accepting client-snapshot") }); } `; + }, }, }, - }; + { + name: "fresh:client-island", + resolveId: { + filter: { + id: /^fresh-client-island::/, + }, + handler(id) { + const name = id.slice("fresh-client-island::".length); + const full = entryToIsland.get(name); + return full; + }, + }, + }, + ]; +} + +function isIslandPath( + options: ResolvedFreshViteConfig, + filePath: string, +): boolean { + const relIsland = path.relative(options.islandsDir, filePath); + if (!relIsland.startsWith("..")) return true; + + const relRoutes = path.relative(options.routeDir, filePath); + + if (!relIsland.startsWith("..") && relRoutes.includes("(_islands)")) { + return true; + } + return false; +} + +function invalidateSnapshots(server: ViteDevServer) { + const client = server.environments.client.moduleGraph.getModuleById( + "\0fresh:client-snapshot", + ); + if (client !== undefined) { + server.environments.client.moduleGraph.invalidateModule(client); + } + + const ssr = server.environments.ssr.moduleGraph.getModuleById( + "\0fresh:server-snapshot", + ); + if (ssr !== undefined) { + server.environments.ssr.moduleGraph.invalidateModule(ssr); + } } diff --git a/packages/plugin-vite/src/plugins/server_snapshot.ts b/packages/plugin-vite/src/plugins/server_snapshot.ts index 558cb658..03bcca2b 100644 --- a/packages/plugin-vite/src/plugins/server_snapshot.ts +++ b/packages/plugin-vite/src/plugins/server_snapshot.ts @@ -240,42 +240,36 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] { } } - const namer = new UniqueNamer(); - if (chunk.name === "client-snapshot") { - for (const id of chunk.dynamicImports ?? []) { - const mod = manifest[id]; + if (chunk.name?.startsWith("fresh-island__")) { + const name = chunk.name.slice("fresh-island__".length); + let serverPath = path.join(root, chunk.src ?? chunk.file); + const idx = chunk.src?.indexOf("deno::") ?? -1; - let serverPath = path.join(root, mod.src ?? id); - const idx = mod.src?.indexOf("deno::") ?? -1; - - if (idx > -1 && mod.src) { - const src = mod.src - .slice(idx) - .replace( - /(https?):\/([^/])/, - (_m, protocol, rest) => { - return `${protocol}://${rest}`; - }, - ); - serverPath = resolvedIslandSpecs.get(src)!; - } - - let spec = pathToSpec(clientOutDir, mod.file); - - if (spec.startsWith("./")) { - spec = spec.slice(1); - } - - const chunkCss = mod.css?.map((id) => `/${id}`) ?? []; - - const name = namer.getUniqueName(specToName(id)); - islandMods.push({ - name, - browser: spec, - server: serverPath, - css: chunkCss, - }); + if (idx > -1 && chunk.src) { + const src = chunk.src + .slice(idx) + .replace( + /(https?):\/([^/])/, + (_m, protocol, rest) => { + return `${protocol}://${rest}`; + }, + ); + serverPath = resolvedIslandSpecs.get(src)!; } + + let spec = pathToSpec(clientOutDir, chunk.file); + + if (spec.startsWith("./")) { + spec = spec.slice(1); + } + + const chunkCss = chunk.css?.map((id) => `/${id}`) ?? []; + islandMods.push({ + name, + browser: spec, + server: serverPath, + css: chunkCss, + }); } } diff --git a/packages/plugin-vite/tests/build_test.ts b/packages/plugin-vite/tests/build_test.ts index 8de664eb..5bc45208 100644 --- a/packages/plugin-vite/tests/build_test.ts +++ b/packages/plugin-vite/tests/build_test.ts @@ -83,6 +83,27 @@ Deno.test({ sanitizeResources: false, }); +Deno.test({ + name: "vite build - nested islands", + fn: async () => { + await launchProd( + { cwd: viteResult.tmp }, + async (address) => { + await withBrowser(async (page) => { + await page.goto(`${address}/tests/island_nested`, { + waitUntil: "networkidle2", + }); + + await page.locator(".outer-ready").wait(); + await page.locator(".inner-ready").wait(); + }); + }, + ); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + Deno.test({ name: "vite build - without static/ dir", fn: async () => { diff --git a/packages/plugin-vite/tests/dev_server_test.ts b/packages/plugin-vite/tests/dev_server_test.ts index b961c055..1a0ae9ca 100644 --- a/packages/plugin-vite/tests/dev_server_test.ts +++ b/packages/plugin-vite/tests/dev_server_test.ts @@ -328,6 +328,22 @@ Deno.test({ sanitizeOps: false, }); +Deno.test({ + name: "vite dev - nested islands", + fn: async () => { + await withBrowser(async (page) => { + await page.goto(`${demoServer.address()}/tests/island_nested`, { + waitUntil: "networkidle2", + }); + + await page.locator(".outer-ready").wait(); + await page.locator(".inner-ready").wait(); + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + Deno.test({ name: "vite dev - remote island", fn: async () => {