Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/react/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server, pagesDir);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down
1 change: 1 addition & 0 deletions packages/solid/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server, pagesDir);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down
1 change: 1 addition & 0 deletions packages/svelte/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server, pagesDir);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down
95 changes: 80 additions & 15 deletions packages/void/src/pages/islands-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ export type IslandManifest = {
* build may load the islands client entry before their transforms run.
*/
registerPages(pageScan: PageScanResult, pagesDir: string): void;
/**
* 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, pagesDir: string): void;
};

/** `extensions` are tried, in order, for an island import without one. */
Expand All @@ -89,6 +96,7 @@ export function createIslandManifest(
extensions: ReadonlyArray<string>,
): IslandManifest {
const entries = new Map<string, IslandEntry>();
let server: ViteDevServer | null = null;

type RegisteredIsland = { absPath: string | null; islandId: string };

Expand All @@ -98,10 +106,27 @@ 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) {
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,
Expand All @@ -115,13 +140,37 @@ 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, 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)));
},
};
}

Expand Down Expand Up @@ -388,6 +437,12 @@ export type IslandClientEntryOptions = {
export function generateIslandClientEntry(options: IslandClientEntryOptions): string {
const uniqueIslands = new Map<string, string>();
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)) {
continue;
}
uniqueIslands.set(entry.islandId, entry.componentPath);
}

Expand All @@ -414,8 +469,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');
}
Expand Down Expand Up @@ -516,10 +570,21 @@ export function computePagesNeedingClientJS(

type PagesRescan = { flush: () => Promise<void> };

/** 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).
Expand Down Expand Up @@ -552,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
Expand All @@ -573,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);
}
});

Expand Down
116 changes: 113 additions & 3 deletions packages/void/test/unit/pages-islands-rescan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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__');
Expand All @@ -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<string> = [];
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<void> {
watcher.emit('add', path);
Expand Down Expand Up @@ -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',
'<script>\nimport Counter from "../components/Counter.tsx" with { island: "load" };\n</script>\n\n<Counter />\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', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/vue/src/plugin-islands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export function islandsPlugin(
},

configureServer(server) {
islandManifest.configureServer(server, pagesDir);
watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => {
pageScan = scan;
});
Expand Down
Loading