From a4d86d2f43b72c2d98e81435808aa69de3df592a Mon Sep 17 00:00:00 2001 From: Liang Date: Tue, 17 Nov 2026 23:06:46 +0800 Subject: [PATCH 1/3] fix(pages): hydrate islands added while the dev server runs --- packages/react/src/plugin-islands.ts | 1 + packages/solid/src/plugin-islands.ts | 1 + packages/svelte/src/plugin-islands.ts | 1 + packages/void/src/pages/islands-plugin.ts | 18 ++++++ packages/vue/src/plugin-islands.ts | 1 + .../island-dev-client-entry.test.ts | 63 +++++++++++++++++++ 6 files changed, 85 insertions(+) create mode 100644 packages/vue/test/integration/island-dev-client-entry.test.ts diff --git a/packages/react/src/plugin-islands.ts b/packages/react/src/plugin-islands.ts index c2e0ff429..298debf50 100644 --- a/packages/react/src/plugin-islands.ts +++ b/packages/react/src/plugin-islands.ts @@ -64,6 +64,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/solid/src/plugin-islands.ts b/packages/solid/src/plugin-islands.ts index 566b1623c..6b6027335 100644 --- a/packages/solid/src/plugin-islands.ts +++ b/packages/solid/src/plugin-islands.ts @@ -85,6 +85,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index 30a17ebec..ff616cc3d 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -79,6 +79,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index a606305e1..863a5c04f 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -84,6 +84,11 @@ export type IslandManifest = { * build may load the islands client entry before their transforms run. */ registerPages(pageScan: PageScanResult, pagesDir: string): void; + /** + * Invalidate the dev islands client entry when a page transform records a + * new island, so the next page load hydrates it without a server restart. + */ + configureServer(server: ViteDevServer): void; }; /** `extensions` are tried, in order, for an island import without one. */ @@ -92,6 +97,7 @@ export function createIslandManifest( extensions: ReadonlyArray, ): IslandManifest { const entries = new Map(); + let server: ViteDevServer | null = null; function register( specifier: string, @@ -103,7 +109,16 @@ export function createIslandManifest( return { absPath, islandId: specifier }; } const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, ''); + const isNew = entries.get(islandId)?.componentPath !== absPath; entries.set(islandId, { componentPath: absPath, islandId, hydrate }); + if (isNew && server) { + for (const env of Object.values(server.environments)) { + const mod = env.moduleGraph.getModuleById('\0' + ISLANDS_CLIENT_ENTRY_ID); + if (mod) { + env.moduleGraph.invalidateModule(mod); + } + } + } return { absPath, islandId }; } @@ -127,6 +142,9 @@ export function createIslandManifest( } } }, + configureServer(devServer) { + server = devServer; + }, }; } diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index 659be890a..6ad123f4a 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -72,6 +72,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/vue/test/integration/island-dev-client-entry.test.ts b/packages/vue/test/integration/island-dev-client-entry.test.ts new file mode 100644 index 000000000..b8d850f46 --- /dev/null +++ b/packages/vue/test/integration/island-dev-client-entry.test.ts @@ -0,0 +1,63 @@ +import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import vue from '@vitejs/plugin-vue'; +import { createServer } from 'vite'; +import { expect, it } from 'vite-plus/test'; +import { islandsPlugin } from '../../src/plugin-islands.ts'; + +const COUNTER = ` + +`; + +it('adds an island imported after the dev server loaded the islands client entry', async () => { + const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_client_entry_')); + const pages = join(root, 'pages'); + mkdirSync(pages); + mkdirSync(join(root, 'components')); + writeFileSync(join(root, 'components/Counter.vue'), COUNTER); + writeFileSync( + join(pages, 'index.island.vue'), + ` + +`, + ); + + const server = await createServer({ + root, + configFile: false, + cacheDir: join(root, '.vite'), + logLevel: 'silent', + plugins: [vue(), ...islandsPlugin(pages)], + server: { ws: false, watch: null }, + }); + try { + const { client, ssr } = server.environments; + const before = await client.transformRequest('virtual:void-islands-client'); + expect(before?.code).toContain('components/Counter'); + expect(before?.code).not.toContain('components/Second'); + + cpSync(join(root, 'components/Counter.vue'), join(root, 'components/Second.vue')); + writeFileSync( + join(pages, 'index.island.vue'), + ` + +`, + ); + // Rendering the edited page registers the new island. + await ssr.transformRequest('/pages/index.island.vue'); + + const after = await client.transformRequest('virtual:void-islands-client'); + expect(after?.code).toContain('components/Second'); + } finally { + await server.close(); + rmSync(root, { recursive: true, force: true }); + } +}); From f308bf4ee86024f0e1a47e1a5b857438ec3e6d19 Mon Sep 17 00:00:00 2001 From: Liang Date: Wed, 18 Nov 2026 21:10:06 +0800 Subject: [PATCH 2/3] fix(pages): prune deleted islands and hydrate a page's first island in dev --- packages/react/src/plugin-islands.ts | 10 +- packages/solid/src/plugin-islands.ts | 10 +- packages/svelte/src/plugin-islands.ts | 10 +- packages/void/src/pages/islands-plugin.ts | 11 +- packages/vue/src/plugin-islands.ts | 10 +- .../island-dev-client-entry.test.ts | 107 ++++++++++++++++++ 6 files changed, 143 insertions(+), 15 deletions(-) diff --git a/packages/react/src/plugin-islands.ts b/packages/react/src/plugin-islands.ts index 298debf50..0ac992193 100644 --- a/packages/react/src/plugin-islands.ts +++ b/packages/react/src/plugin-islands.ts @@ -249,9 +249,13 @@ export async function renderIslandPage(pageObj, assetTags) { ); const html = renderToString(element); + // The rendered islands also count: in dev, the page may have gained its + // first island after this module computed __pagesNeedingClientJS. + const __hasIslands = html.includes("data-island="); + const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") + const __frontmatterScript = __hasIslands ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -261,10 +265,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/solid/src/plugin-islands.ts b/packages/solid/src/plugin-islands.ts index 6b6027335..da8362719 100644 --- a/packages/solid/src/plugin-islands.ts +++ b/packages/solid/src/plugin-islands.ts @@ -292,9 +292,13 @@ export async function renderIslandPage(pageObj, assetTags) { const html = await renderToStringAsync(() => createComponent(ServerApp, {})); + // The rendered islands also count: in dev, the page may have gained its + // first island after this module computed __pagesNeedingClientJS. + const __hasIslands = html.includes("data-island="); + const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") + const __frontmatterScript = __hasIslands ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -304,10 +308,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""} +\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}\${__needsJS ? generateHydrationScript() : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index ff616cc3d..90feb888f 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -342,9 +342,13 @@ export async function renderIslandPage(pageObj, assetTags) { }, }); + // The rendered islands also count: in dev, the page may have gained its + // first island after this module computed __pagesNeedingClientJS. + const __hasIslands = html.includes("data-island="); + const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") + const __frontmatterScript = __hasIslands ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -354,10 +358,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${head}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${head}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index 863a5c04f..3cf3b3ff0 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -396,7 +396,13 @@ export type IslandClientEntryOptions = { export function generateIslandClientEntry(options: IslandClientEntryOptions): string { const uniqueIslands = new Map(); - for (const entry of options.manifest.entries.values()) { + for (const [key, entry] of options.manifest.entries) { + // A dev edit can delete an island the manifest recorded. Importing its + // path would fail the whole entry and stop every other island hydrating. + if (!existsSync(entry.componentPath)) { + options.manifest.entries.delete(key); + continue; + } uniqueIslands.set(entry.islandId, entry.componentPath); } @@ -423,8 +429,7 @@ export function generateIslandClientEntry(options: IslandClientEntryOptions): st // Without islands, no built page gets this script (see // computePagesNeedingClientJS), so the entry only gives the styles a chunk to - // link. Dev keeps the runtime: it does not reload this module when a page - // gains an island. + // link. Dev keeps the runtime so a page that gains its first island hydrates. if (!options.needsRuntime && !options.isDev) { return lines.join('\n'); } diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index 6ad123f4a..fc89087c3 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -280,9 +280,13 @@ export async function renderIslandPage(pageObj, assetTags) { }); const html = await renderToString(app); + // The rendered islands also count: in dev, the page may have gained its + // first island after this module computed __pagesNeedingClientJS. + const __hasIslands = html.includes("data-island="); + const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") + const __frontmatterScript = __hasIslands ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -292,10 +296,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} + \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} \`; } diff --git a/packages/vue/test/integration/island-dev-client-entry.test.ts b/packages/vue/test/integration/island-dev-client-entry.test.ts index b8d850f46..fda7cc7f2 100644 --- a/packages/vue/test/integration/island-dev-client-entry.test.ts +++ b/packages/vue/test/integration/island-dev-client-entry.test.ts @@ -61,3 +61,110 @@ import Second from "../components/Second.vue" with { island: "load" }; rmSync(root, { recursive: true, force: true }); } }); + +it('keeps the islands client entry loading after an island is deleted', async () => { + const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_deleted_')); + const pages = join(root, 'pages'); + mkdirSync(pages); + mkdirSync(join(root, 'components')); + writeFileSync(join(root, 'components/Counter.vue'), COUNTER); + writeFileSync(join(root, 'components/Removed.vue'), COUNTER); + writeFileSync( + join(pages, 'index.island.vue'), + ` + +`, + ); + + const server = await createServer({ + root, + configFile: false, + cacheDir: join(root, '.vite'), + logLevel: 'silent', + plugins: [vue(), ...islandsPlugin(pages)], + server: { ws: false, watch: null }, + }); + try { + const { client, ssr } = server.environments; + await client.transformRequest('virtual:void-islands-client'); + + // Remove an island's import and file, then add another island. + rmSync(join(root, 'components/Removed.vue')); + cpSync(join(root, 'components/Counter.vue'), join(root, 'components/Added.vue')); + writeFileSync( + join(pages, 'index.island.vue'), + ` + +`, + ); + await ssr.transformRequest('/pages/index.island.vue'); + + const after = await client.transformRequest('virtual:void-islands-client'); + expect(after?.code).toContain('components/Counter'); + expect(after?.code).toContain('components/Added'); + expect(after?.code).not.toContain('components/Removed'); + } finally { + await server.close(); + rmSync(root, { recursive: true, force: true }); + } +}); + +it('loads the islands client on a static island page that gains its first island', async () => { + const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_first_island_')); + const pages = join(root, 'pages'); + const page = join(pages, 'index.island.vue'); + mkdirSync(pages); + mkdirSync(join(root, 'components')); + writeFileSync(join(root, 'components/Counter.vue'), COUNTER); + writeFileSync(page, '\n'); + + const server = await createServer({ + root, + configFile: false, + cacheDir: join(root, '.vite'), + logLevel: 'silent', + plugins: [vue(), ...islandsPlugin(pages)], + server: { ws: false, watch: null, port: 0, host: '127.0.0.1' }, + }); + const render = async () => { + const renderer = (await server.ssrLoadModule('virtual:void-islands-renderer')) as { + renderIslandPage( + page: { component: string; props: Record }, + assetTags: { css: string; preloads: string; body: string }, + ): Promise; + }; + return renderer.renderIslandPage( + { component: 'index', props: {} }, + { css: '', preloads: '', body: '' }, + ); + }; + try { + // Listening runs the pages scan. + await server.listen(); + expect(await render()).not.toContain('/islands.js'); + + writeFileSync( + page, + ` + +`, + ); + // What the dev server's watcher does when the page is saved. + server.environments.ssr.moduleGraph.onFileChange(page); + + const html = await render(); + expect(html).toContain('data-island="components/Counter"'); + expect(html).toContain('/islands.js'); + } finally { + await server.close(); + rmSync(root, { recursive: true, force: true }); + } +}); From bcf7622d38d2afc7429ad4b302b279f522ebe1f5 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 25 Nov 2026 17:12:56 +0800 Subject: [PATCH 3/3] fix(pages): refresh dev islands on page edits without scanning HTML - Rebuild the islands renderer when a page or layout changes, so a page that gains its first island gets the client script. This replaces the rendered-HTML `data-island=` check, which also ran in production and matched pages that only show that text. - Skip a missing island file in the client entry without dropping it from the manifest, and rebuild the entry when a recorded island file is deleted or comes back. - Record a Markdown page's islands when it is saved. Markdown pages emit their own wrappers, so no page transform records them. - A page deleted before its islands are read is skipped instead of throwing. - Tests: shared unit coverage in packages/void, fixture dirs from the shared helper, and no `server.listen()` (it started the optimizer). Co-Authored-By: Claude Opus 5.5 --- packages/react/src/plugin-islands.ts | 12 +- packages/solid/src/plugin-islands.ts | 12 +- packages/svelte/src/plugin-islands.ts | 12 +- packages/void/src/pages/islands-plugin.ts | 92 ++++++-- .../test/unit/pages-islands-rescan.test.ts | 116 +++++++++- packages/vue/src/plugin-islands.ts | 12 +- .../island-dev-client-entry.test.ts | 217 ++++++++---------- 7 files changed, 286 insertions(+), 187 deletions(-) diff --git a/packages/react/src/plugin-islands.ts b/packages/react/src/plugin-islands.ts index c11e6f13f..074d37d82 100644 --- a/packages/react/src/plugin-islands.ts +++ b/packages/react/src/plugin-islands.ts @@ -64,7 +64,7 @@ export function islandsPlugin( }, configureServer(server) { - islandManifest.configureServer(server); + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -247,13 +247,9 @@ export async function renderIslandPage(pageObj, assetTags) { ); const html = renderToString(element); - // The rendered islands also count: in dev, the page may have gained its - // first island after this module computed __pagesNeedingClientJS. - const __hasIslands = html.includes("data-island="); - const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __hasIslands + const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -263,10 +259,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""} +\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} + \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} \`; } diff --git a/packages/solid/src/plugin-islands.ts b/packages/solid/src/plugin-islands.ts index bcacb7923..ab1ce002c 100644 --- a/packages/solid/src/plugin-islands.ts +++ b/packages/solid/src/plugin-islands.ts @@ -85,7 +85,7 @@ export function islandsPlugin( }, configureServer(server) { - islandManifest.configureServer(server); + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -293,13 +293,9 @@ export async function renderIslandPage(pageObj, assetTags) { const html = await renderToStringAsync(() => createComponent(ServerApp, {})); - // The rendered islands also count: in dev, the page may have gained its - // first island after this module computed __pagesNeedingClientJS. - const __hasIslands = html.includes("data-island="); - const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __hasIslands + const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -309,10 +305,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""}\${__needsJS ? generateHydrationScript() : ""} +\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""}
\${html}
- \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} + \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} \`; } diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index ae5160aca..a65803b18 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -81,7 +81,7 @@ export function islandsPlugin( }, configureServer(server) { - islandManifest.configureServer(server); + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -346,13 +346,9 @@ export async function renderIslandPage(pageObj, assetTags) { }, }); - // The rendered islands also count: in dev, the page may have gained its - // first island after this module computed __pagesNeedingClientJS. - const __hasIslands = html.includes("data-island="); - const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __hasIslands + const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -362,10 +358,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${head}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""} +\${headHtml}\${head}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} + \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} \`; } diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index eb33ae7c0..226a0034e 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -82,10 +82,12 @@ export type IslandManifest = { */ registerPages(pageScan: PageScanResult, pagesDir: string): void; /** - * Invalidate the dev islands client entry when a page transform records a - * new island, so the next page load hydrates it without a server restart. + * Regenerate the dev islands client entry when an island is recorded, or an + * island file is added or deleted, so the next page load hydrates the + * current islands without a server restart. Markdown pages in `pagesDir` + * are recorded when they are saved. */ - configureServer(server: ViteDevServer): void; + configureServer(server: ViteDevServer, pagesDir: string): void; }; /** `extensions` are tried, in order, for an island import without one. */ @@ -107,16 +109,24 @@ export function createIslandManifest( const isNew = entries.get(islandId)?.componentPath !== absPath; entries.set(islandId, { componentPath: absPath, islandId, hydrate }); if (isNew && server) { - for (const env of Object.values(server.environments)) { - const mod = env.moduleGraph.getModuleById('\0' + ISLANDS_CLIENT_ENTRY_ID); - if (mod) { - env.moduleGraph.invalidateModule(mod); - } - } + invalidateVirtualModule(server, ISLANDS_CLIENT_ENTRY_ID); } return { absPath, islandId }; } + function registerFile(filePath: string): void { + let code: string; + try { + code = readFileSync(filePath, 'utf8'); + } catch { + // Deleted since the scan or watcher event. Its unlink event follows. + return; + } + for (const islandImport of findIslandImports(code, filePath)) { + register(islandImport.specifier, dirname(filePath), islandImport.hydrate); + } + } + return { entries, register, @@ -130,15 +140,36 @@ export function createIslandManifest( if (!entry.island) { continue; } - const filePath = resolve(pagesDir, entry.filePath); - const code = readFileSync(filePath, 'utf8'); - for (const islandImport of findIslandImports(code, filePath)) { - register(islandImport.specifier, dirname(filePath), islandImport.hydrate); - } + registerFile(resolve(pagesDir, entry.filePath)); } }, - configureServer(devServer) { + configureServer(devServer, pagesDir) { server = devServer; + const pagesPrefix = normalizePath(pagesDir) + '/'; + // The entry skips islands whose file is missing. Regenerate it when a + // recorded island file is deleted or comes back. + const onIslandFile = (path: string) => { + for (const entry of entries.values()) { + if (entry.componentPath === path) { + invalidateVirtualModule(devServer, ISLANDS_CLIENT_ENTRY_ID); + return; + } + } + }; + // Markdown pages emit their own island wrappers, so no page transform + // records their islands. Record them before the page reloads. + const onSave = (file: string) => { + const path = normalizePath(file); + if (path.startsWith(pagesPrefix) && path.endsWith('.md')) { + registerFile(path); + } + }; + devServer.watcher.on('add', (file: string) => { + onIslandFile(normalizePath(file)); + onSave(file); + }); + devServer.watcher.on('change', onSave); + devServer.watcher.on('unlink', (file: string) => onIslandFile(normalizePath(file))); }, }; } @@ -405,11 +436,11 @@ export type IslandClientEntryOptions = { export function generateIslandClientEntry(options: IslandClientEntryOptions): string { const uniqueIslands = new Map(); - for (const [key, entry] of options.manifest.entries) { + for (const entry of options.manifest.entries.values()) { // A dev edit can delete an island the manifest recorded. Importing its // path would fail the whole entry and stop every other island hydrating. + // Keep the entry: the file may come back. if (!existsSync(entry.componentPath)) { - options.manifest.entries.delete(key); continue; } uniqueIslands.set(entry.islandId, entry.componentPath); @@ -539,10 +570,21 @@ export function computePagesNeedingClientJS( type PagesRescan = { flush: () => Promise }; +/** Make the dev server load a virtual module again on its next request. */ +function invalidateVirtualModule(server: ViteDevServer, id: string): void { + for (const env of Object.values(server.environments)) { + const mod = env.moduleGraph.getModuleById('\0' + id); + if (mod) { + env.moduleGraph.invalidateModule(mod); + } + } +} + /** * Watch the pages directory for structural changes (add/remove) and .md content * changes (frontmatter layout field) so that new layouts and named layouts are - * picked up without a dev server restart. + * picked up without a dev server restart. Any other page or layout edit + * regenerates the islands renderer, which reads their island imports. * * Returns a `flush()` function that resolves when any pending rescan completes * (useful for tests). @@ -575,12 +617,7 @@ export function watchPagesForRescan( .then( (pageScan) => { onRescan(pageScan); - for (const env of Object.values(server.environments)) { - const mod = env.moduleGraph.getModuleById('\0' + ISLANDS_RENDERER_ID); - if (mod) { - env.moduleGraph.invalidateModule(mod); - } - } + invalidateVirtualModule(server, ISLANDS_RENDERER_ID); }, () => { // The adapter pages plugin runs the same scan on the same events and @@ -596,8 +633,13 @@ export function watchPagesForRescan( server.watcher.on('add', scheduleRescan); server.watcher.on('unlink', scheduleRescan); server.watcher.on('change', (path) => { - if (normalizePath(path).endsWith('.md')) { + const normalizedPath = normalizePath(path); + if (normalizedPath.endsWith('.md')) { scheduleRescan(path); + } else if (normalizedPath.startsWith(normalizedPagesDir + '/')) { + // The renderer decides from the page and layout sources which pages + // need client JavaScript. An edit can add a page's first island. + invalidateVirtualModule(server, ISLANDS_RENDERER_ID); } }); diff --git a/packages/void/test/unit/pages-islands-rescan.test.ts b/packages/void/test/unit/pages-islands-rescan.test.ts index b50c5c02c..a81978ffc 100644 --- a/packages/void/test/unit/pages-islands-rescan.test.ts +++ b/packages/void/test/unit/pages-islands-rescan.test.ts @@ -4,7 +4,15 @@ import { join } from 'node:path'; import type { ViteDevServer } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { packageFixturePath } from '../../../../test/fixture-dir.ts'; -import { hasIslandPages, watchPagesForRescan } from '../../src/pages/islands-plugin.ts'; +import { + createIslandManifest, + generateIslandClientEntry, + hasIslandPages, + ISLANDS_CLIENT_ENTRY_ID, + ISLANDS_RENDERER_ID, + watchPagesForRescan, +} from '../../src/pages/islands-plugin.ts'; +import { scanPages } from '../../src/pages/scan.ts'; import type { PageScanResult } from '../../src/pages/types.ts'; const TMP = packageFixturePath(import.meta.dirname, '__tmp_pages_islands_rescan__'); @@ -17,11 +25,24 @@ function writePage(relativePath: string, source: string): string { return full; } -function setup(onRescan: (scan: PageScanResult) => void) { +/** A dev server with file events and the virtual modules it has loaded. */ +function fakeServer() { const watcher = new EventEmitter(); - const server = { watcher, environments: {} } as unknown as ViteDevServer; + const invalidated: Array = []; + const moduleGraph = { + getModuleById: (id: string) => ({ id }), + invalidateModule: (mod: { id: string }) => invalidated.push(mod.id), + }; + const server = { watcher, environments: { client: { moduleGraph } } } as unknown as ViteDevServer; + return { server, watcher, invalidated }; +} + +function setup(onRescan: (scan: PageScanResult) => void) { + const { server, watcher, invalidated } = fakeServer(); const { flush } = watchPagesForRescan(server, PAGES_DIR, TMP, onRescan); return { + watcher, + invalidated, /** Emit a watcher event, run the debounce timer, and return the scan promise. */ emitAdd(path: string): Promise { watcher.emit('add', path); @@ -73,6 +94,95 @@ describe('watchPagesForRescan', () => { const scan = onRescan.mock.calls[0][0] as PageScanResult; expect(scan.pages.map((page) => page.componentPath)).toEqual(['x.dev.island.tsx']); }); + + it('regenerates the renderer when a page or layout changes', () => { + const page = writePage('index.island.tsx', 'export default () => null;'); + const { watcher, invalidated } = setup(vi.fn()); + + watcher.emit('change', join(TMP, 'components/Counter.tsx')); + expect(invalidated).toEqual([]); + + // The renderer reads the page sources to decide which pages need client JS. + watcher.emit('change', page); + expect(invalidated).toEqual(['\0' + ISLANDS_RENDERER_ID]); + }); +}); + +describe('createIslandManifest in dev', () => { + afterEach(() => { + rmSync(TMP, { recursive: true, force: true }); + }); + + function setupManifest() { + const counter = writePage('../components/Counter.tsx', 'export default () => null;'); + const { server, watcher, invalidated } = fakeServer(); + const manifest = createIslandManifest(TMP, ['.tsx']); + manifest.configureServer(server, PAGES_DIR); + const entry = () => + generateIslandClientEntry({ + manifest, + cssFiles: new Set(), + styles: null, + needsRuntime: true, + isDev: true, + hydrateIsland: '', + }); + return { manifest, watcher, invalidated, counter, entry }; + } + + it('regenerates the client entry only when an island is new', () => { + const { manifest, invalidated } = setupManifest(); + + manifest.register('../components/Counter', PAGES_DIR, 'load'); + expect(invalidated).toEqual(['\0' + ISLANDS_CLIENT_ENTRY_ID]); + + manifest.register('../components/Counter', PAGES_DIR, 'idle'); + expect(invalidated).toHaveLength(1); + }); + + it('skips a deleted island and brings it back with its file', () => { + const { manifest, watcher, invalidated, counter, entry } = setupManifest(); + manifest.register('../components/Counter', PAGES_DIR, 'load'); + invalidated.length = 0; + + watcher.emit('unlink', join(TMP, 'components/Other.tsx')); + expect(invalidated).toEqual([]); + + rmSync(counter); + watcher.emit('unlink', counter); + expect(invalidated).toEqual(['\0' + ISLANDS_CLIENT_ENTRY_ID]); + expect(entry()).not.toContain('components/Counter'); + + writeFileSync(counter, 'export default () => null;'); + watcher.emit('add', counter); + expect(invalidated).toHaveLength(2); + expect(entry()).toContain('components/Counter'); + }); + + it('records the islands of a Markdown page when it is saved', () => { + const { watcher, invalidated, entry } = setupManifest(); + const page = writePage('index.md', '# Home\n'); + watcher.emit('add', page); + expect(invalidated).toEqual([]); + + writePage( + 'index.md', + '\n\n\n', + ); + watcher.emit('change', page); + expect(invalidated).toEqual(['\0' + ISLANDS_CLIENT_ENTRY_ID]); + expect(entry()).toContain('components/Counter'); + }); + + it('skips a page deleted before its islands are read', async () => { + const { manifest, watcher } = setupManifest(); + const page = writePage('index.md', '# Home\n'); + const scan = await scanPages(TMP, { pagesDir: PAGES_DIR, environment: 'dev' }); + rmSync(page); + + expect(() => manifest.registerPages(scan, PAGES_DIR)).not.toThrow(); + expect(() => watcher.emit('change', page)).not.toThrow(); + }); }); describe('hasIslandPages', () => { diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index 568dd8fdc..7a54d402d 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -72,7 +72,7 @@ export function islandsPlugin( }, configureServer(server) { - islandManifest.configureServer(server); + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); @@ -286,13 +286,9 @@ export async function renderIslandPage(pageObj, assetTags) { if (Object.keys(boundaryManifest.plans).length) app.config.errorHandler = error => { renderFailure ??= { error }; }; const html = await renderToString(app); if (renderFailure) throw renderFailure.error; - // The rendered islands also count: in dev, the page may have gained its - // first island after this module computed __pagesNeedingClientJS. - const __hasIslands = html.includes("data-island="); - const __needsJS = __hasIslands || __pagesNeedingClientJS.has(pageObj.component); // Islands hydrate as separate roots. Send the page frontmatter so their // useFrontmatter() returns the same value in the browser. - const __frontmatterScript = __hasIslands + const __frontmatterScript = __pagesNeedingClientJS.has(pageObj.component) && html.includes("data-island=") ? islandFrontmatterScript(__pageModule.frontmatter) : ""; const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : ""; @@ -302,10 +298,10 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${assetTags.css}\${__needsJS ? assetTags.preloads : ""} +\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}
\${html}
- \${__frontmatterScript}\${__needsJS ? assetTags.body : ""} + \${__frontmatterScript}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} \`; } diff --git a/packages/vue/test/integration/island-dev-client-entry.test.ts b/packages/vue/test/integration/island-dev-client-entry.test.ts index fda7cc7f2..4942fe1c2 100644 --- a/packages/vue/test/integration/island-dev-client-entry.test.ts +++ b/packages/vue/test/integration/island-dev-client-entry.test.ts @@ -1,8 +1,10 @@ -import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import vue from '@vitejs/plugin-vue'; import { createServer } from 'vite'; -import { expect, it } from 'vite-plus/test'; +import type { ViteDevServer } from 'vite'; +import { afterEach, expect, it } from 'vite-plus/test'; +import { createPackageFixtureDir } from '../../../../test/fixture-dir.ts'; import { islandsPlugin } from '../../src/plugin-islands.ts'; const COUNTER = `\n\n`; +} + +let root = ''; +let server: ViteDevServer | null = null; + +afterEach(async () => { + await server?.close(); + server = null; + rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }); +}); + +/** Writes `pages/index.island.vue` and the given components, then starts a dev server without file watching. */ +async function startServer(page: string, components: ReadonlyArray) { + root = createPackageFixtureDir(join(import.meta.dirname, '../..'), '__tmp_island_dev_'); const pages = join(root, 'pages'); mkdirSync(pages); mkdirSync(join(root, 'components')); - writeFileSync(join(root, 'components/Counter.vue'), COUNTER); - writeFileSync( - join(pages, 'index.island.vue'), - ` - -`, - ); - - const server = await createServer({ + for (const name of components) { + writeFileSync(join(root, `components/${name}.vue`), COUNTER); + } + writeFileSync(join(pages, 'index.island.vue'), page); + server = await createServer({ root, configFile: false, cacheDir: join(root, '.vite'), logLevel: 'silent', + optimizeDeps: { noDiscovery: true, include: [] }, plugins: [vue(), ...islandsPlugin(pages)], server: { ws: false, watch: null }, }); - try { - const { client, ssr } = server.environments; - const before = await client.transformRequest('virtual:void-islands-client'); - expect(before?.code).toContain('components/Counter'); - expect(before?.code).not.toContain('components/Second'); - - cpSync(join(root, 'components/Counter.vue'), join(root, 'components/Second.vue')); - writeFileSync( - join(pages, 'index.island.vue'), - ` - -`, - ); - // Rendering the edited page registers the new island. - await ssr.transformRequest('/pages/index.island.vue'); - - const after = await client.transformRequest('virtual:void-islands-client'); - expect(after?.code).toContain('components/Second'); - } finally { - await server.close(); - rmSync(root, { recursive: true, force: true }); - } + return { server, page: join(pages, 'index.island.vue') }; +} + +async function clientEntry(devServer: ViteDevServer): Promise { + return (await devServer.environments.client.transformRequest('virtual:void-islands-client'))! + .code; +} + +it('adds an island imported after the dev server loaded the islands client entry', async () => { + const { server, page } = await startServer(islandPage(['Counter']), ['Counter', 'Second']); + const before = await clientEntry(server); + expect(before).toContain('components/Counter'); + expect(before).not.toContain('components/Second'); + + writeFileSync(page, islandPage(['Counter', 'Second'])); + // Rendering the edited page records the new island. + await server.environments.ssr.transformRequest('/pages/index.island.vue'); + + expect(await clientEntry(server)).toContain('components/Second'); }); -it('keeps the islands client entry loading after an island is deleted', async () => { - const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_deleted_')); - const pages = join(root, 'pages'); - mkdirSync(pages); - mkdirSync(join(root, 'components')); - writeFileSync(join(root, 'components/Counter.vue'), COUNTER); - writeFileSync(join(root, 'components/Removed.vue'), COUNTER); +it('adds an island imported by a Markdown page after the dev server started', async () => { + const { server, page } = await startServer(islandPage(['Counter']), ['Counter', 'Note']); + const md = join(page, '../about.md'); + writeFileSync(md, '# About\n'); + server.watcher.emit('add', md); + expect(await clientEntry(server)).not.toContain('components/Note'); + writeFileSync( - join(pages, 'index.island.vue'), - ` - -`, + md, + '\n\n# About\n\n\n', ); + server.watcher.emit('change', md); + expect(await clientEntry(server)).toContain('components/Note'); +}); - const server = await createServer({ - root, - configFile: false, - cacheDir: join(root, '.vite'), - logLevel: 'silent', - plugins: [vue(), ...islandsPlugin(pages)], - server: { ws: false, watch: null }, - }); - try { - const { client, ssr } = server.environments; - await client.transformRequest('virtual:void-islands-client'); - - // Remove an island's import and file, then add another island. - rmSync(join(root, 'components/Removed.vue')); - cpSync(join(root, 'components/Counter.vue'), join(root, 'components/Added.vue')); - writeFileSync( - join(pages, 'index.island.vue'), - ` - -`, - ); - await ssr.transformRequest('/pages/index.island.vue'); - - const after = await client.transformRequest('virtual:void-islands-client'); - expect(after?.code).toContain('components/Counter'); - expect(after?.code).toContain('components/Added'); - expect(after?.code).not.toContain('components/Removed'); - } finally { - await server.close(); - rmSync(root, { recursive: true, force: true }); - } +it('drops a deleted island from the client entry and restores it when the file comes back', async () => { + const { server } = await startServer(islandPage(['Counter', 'Removed']), ['Counter', 'Removed']); + await server.environments.ssr.transformRequest('/pages/index.island.vue'); + expect(await clientEntry(server)).toContain('components/Removed'); + + // A missing import would fail the whole entry, so other islands would not hydrate. + const removed = join(root, 'components/Removed.vue'); + rmSync(removed); + server.watcher.emit('unlink', removed); + const withoutFile = await clientEntry(server); + expect(withoutFile).toContain('components/Counter'); + expect(withoutFile).not.toContain('components/Removed'); + + writeFileSync(removed, COUNTER); + server.watcher.emit('add', removed); + expect(await clientEntry(server)).toContain('components/Removed'); }); it('loads the islands client on a static island page that gains its first island', async () => { - const root = mkdtempSync(join(import.meta.dirname, '__tmp_island_dev_first_island_')); - const pages = join(root, 'pages'); - const page = join(pages, 'index.island.vue'); - mkdirSync(pages); - mkdirSync(join(root, 'components')); - writeFileSync(join(root, 'components/Counter.vue'), COUNTER); - writeFileSync(page, '\n'); - - const server = await createServer({ - root, - configFile: false, - cacheDir: join(root, '.vite'), - logLevel: 'silent', - plugins: [vue(), ...islandsPlugin(pages)], - server: { ws: false, watch: null, port: 0, host: '127.0.0.1' }, - }); + const { server, page } = await startServer('\n', ['Counter']); const render = async () => { const renderer = (await server.ssrLoadModule('virtual:void-islands-renderer')) as { renderIslandPage( @@ -144,27 +117,17 @@ it('loads the islands client on a static island page that gains its first island { css: '', preloads: '', body: '' }, ); }; - try { - // Listening runs the pages scan. - await server.listen(); - expect(await render()).not.toContain('/islands.js'); - - writeFileSync( - page, - ` - -`, - ); - // What the dev server's watcher does when the page is saved. - server.environments.ssr.moduleGraph.onFileChange(page); - - const html = await render(); - expect(html).toContain('data-island="components/Counter"'); - expect(html).toContain('/islands.js'); - } finally { - await server.close(); - rmSync(root, { recursive: true, force: true }); - } + // `server.listen()` runs the pages scan, but also starts the dependency optimizer. + await server.environments.client.pluginContainer.buildStart({}); + expect(await render()).not.toContain('/islands.js'); + + writeFileSync(page, islandPage(['Counter'])); + // What the dev server's watcher reports when the page is saved. Vite's own + // listener invalidates the page asynchronously, so invalidate it here too. + server.watcher.emit('change', page); + server.environments.ssr.moduleGraph.onFileChange(page); + + const html = await render(); + expect(html).toContain('data-island="components/Counter"'); + expect(html).toContain('/islands.js'); });