Skip to content

Commit 30ef3cb

Browse files
astro-factory[bot]factory[bot]matthewp
authored
fix: invalidate prerender environment in invalidateDataStore (#17991) (#17999)
When an adapter enables a separate prerender environment (e.g. @astrojs/cloudflare with prerenderEnvironment: 'node'), prerendered pages are served by that environment's own module runner and route cache. invalidateDataStore() only invalidated the ssr environment, leaving the prerender environment serving stale content after edits. Iterate over both ssr and prerender environments, following the same pattern already used by the routes plugin. Co-authored-by: factory[bot] <factory[bot]@users.noreply.github.com> Co-authored-by: Matthew Phillips <[email protected]>
1 parent 74098b6 commit 30ef3cb

3 files changed

Lines changed: 103 additions & 40 deletions

File tree

‎.changeset/tasty-eyes-leave.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Fixes content collection HMR not updating prerendered pages when an adapter enables a separate prerender environment (e.g. `@astrojs/cloudflare` with `prerenderEnvironment: 'node'`)

‎packages/astro/src/content/vite-plugin-content-virtual-mod.ts‎

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -58,29 +58,41 @@ function invalidateAssetImports(viteServer: ViteDevServer, filePath: string) {
5858
}
5959

6060
function invalidateDataStore(viteServer: ViteDevServer, { notifyClient = true } = {}) {
61-
const environment = viteServer.environments[ASTRO_VITE_ENVIRONMENT_NAMES.ssr];
62-
const module = environment.moduleGraph.getModuleById(RESOLVED_DATA_STORE_VIRTUAL_ID);
63-
if (module) {
64-
const timestamp = Date.now();
65-
// Pass `true` to mark this as HMR invalidation so Vite drops cached SSR results.
66-
environment.moduleGraph.invalidateModule(module, undefined, timestamp, true);
67-
}
68-
// Also invalidate the module in the SSR module runner's evaluation cache.
69-
// Server-side invalidation only clears `transformResult`, but the runner
70-
// may still hold a stale evaluated result. When the runner's `fetchModule`
71-
// call triggers a fresh server transform, the transform re-populates
72-
// `transformResult` before the runner checks it, causing a false cache hit.
73-
if (isRunnableDevEnvironment(environment)) {
74-
const runnerModule = environment.runner.evaluatedModules.getModuleById(
75-
RESOLVED_DATA_STORE_VIRTUAL_ID,
76-
);
77-
if (runnerModule) {
78-
environment.runner.evaluatedModules.invalidateModule(runnerModule);
61+
const timestamp = Date.now();
62+
// Invalidate both the ssr and prerender environments. When an adapter
63+
// enables a separate prerender environment (e.g. Cloudflare with
64+
// `prerenderEnvironment: 'node'`), prerendered pages are served by that
65+
// environment's own module runner and route cache. Skipping it would
66+
// leave the prerender environment serving stale content after edits.
67+
for (const name of [
68+
ASTRO_VITE_ENVIRONMENT_NAMES.ssr,
69+
ASTRO_VITE_ENVIRONMENT_NAMES.prerender,
70+
] as const) {
71+
const environment = viteServer.environments[name];
72+
if (!environment) continue;
73+
74+
const module = environment.moduleGraph.getModuleById(RESOLVED_DATA_STORE_VIRTUAL_ID);
75+
if (module) {
76+
// Pass `true` to mark this as HMR invalidation so Vite drops cached SSR results.
77+
environment.moduleGraph.invalidateModule(module, undefined, timestamp, true);
78+
}
79+
// Also invalidate the module in the runner's evaluation cache.
80+
// Server-side invalidation only clears `transformResult`, but the runner
81+
// may still hold a stale evaluated result. When the runner's `fetchModule`
82+
// call triggers a fresh server transform, the transform re-populates
83+
// `transformResult` before the runner checks it, causing a false cache hit.
84+
if (isRunnableDevEnvironment(environment)) {
85+
const runnerModule = environment.runner.evaluatedModules.getModuleById(
86+
RESOLVED_DATA_STORE_VIRTUAL_ID,
87+
);
88+
if (runnerModule) {
89+
environment.runner.evaluatedModules.invalidateModule(runnerModule);
90+
}
7991
}
92+
// Signal the runner to clear its route cache so that getStaticPaths()
93+
// is re-evaluated with the updated content collection data.
94+
environment.hot.send('astro:content-changed', {});
8095
}
81-
// Signal the SSR runner to clear its route cache so that getStaticPaths()
82-
// is re-evaluated with the updated content collection data.
83-
environment.hot.send('astro:content-changed', {});
8496
// Only notify the client to reload when data has actually changed at runtime.
8597
// During initial startup (buildStart), no client has loaded content yet, so
8698
// sending a full-reload would just cause a spurious page reload for the first

‎packages/astro/test/units/content-layer/content-virtual-mod.test.ts‎

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,33 +21,41 @@ function createMockModuleGraph() {
2121
};
2222
}
2323

24+
/**
25+
* Creates a mock environment with a module graph and HMR channel.
26+
*/
27+
function createMockEnvironment(name: string, sentMessages: Array<Record<string, unknown>>) {
28+
return {
29+
moduleGraph: createMockModuleGraph(),
30+
hot: {
31+
send: (...args: unknown[]) => {
32+
if (typeof args[0] === 'string') {
33+
sentMessages.push({ channel: name, type: args[0], data: args[1] });
34+
} else {
35+
sentMessages.push({ channel: name, ...(args[0] as Record<string, unknown>) });
36+
}
37+
},
38+
},
39+
};
40+
}
41+
2442
/**
2543
* Creates a minimal mock ViteDevServer with just enough structure for
2644
* the content virtual mod plugin's buildStart hook.
2745
*/
28-
function createMockViteDevServer() {
46+
function createMockViteDevServer({ includePrerender = false } = {}) {
2947
const sentMessages: Array<Record<string, unknown>> = [];
3048
const watcherListeners = new Map<string, Array<(path: string) => void>>();
49+
const environments: Record<string, ReturnType<typeof createMockEnvironment>> = {
50+
ssr: createMockEnvironment('ssr', sentMessages),
51+
client: createMockEnvironment('client', sentMessages),
52+
};
53+
if (includePrerender) {
54+
environments.prerender = createMockEnvironment('prerender', sentMessages);
55+
}
3156
return {
3257
sentMessages,
33-
environments: {
34-
ssr: {
35-
moduleGraph: createMockModuleGraph(),
36-
hot: {
37-
send: (type: unknown, data: unknown) => {
38-
sentMessages.push({ channel: 'ssr', type, data });
39-
},
40-
},
41-
},
42-
client: {
43-
moduleGraph: createMockModuleGraph(),
44-
hot: {
45-
send: (payload: Record<string, unknown>) => {
46-
sentMessages.push({ channel: 'client', ...payload });
47-
},
48-
},
49-
},
50-
},
58+
environments,
5159
watcher: {
5260
add: () => {},
5361
on: (event: string, listener: (path: string) => void) => {
@@ -236,4 +244,42 @@ describe('attachDataStoreInvalidation', () => {
236244
mockServer.watcher.emit('change', dataStorePath);
237245
assert.equal(countClientReloads(mockServer), 2, 'a later external change should reload');
238246
});
247+
248+
it('invalidates the prerender environment when it exists (#17991)', async (t) => {
249+
const root = createTempDir('content-data-store-prerender-invalidation-test-');
250+
const settings = createMinimalSettings(root, { config: { legacy: {} } });
251+
const dataStoreFile = getDataStoreFile(settings, true);
252+
await nodeFs.promises.mkdir(settings.dotAstroDir, { recursive: true });
253+
254+
t.mock.timers.enable({ apis: ['Date'], now: 10_000 });
255+
t.after(() => mock.timers.reset());
256+
257+
const mockServer = createMockViteDevServer({ includePrerender: true });
258+
const plugin = astroContentVirtualModPlugin({ settings, fs: nodeFs });
259+
// @ts-expect-error - mock args are sufficient for this test
260+
plugin.config?.({}, { command: 'serve' });
261+
// @ts-expect-error - mock server has enough structure for this test
262+
plugin.configureServer?.(mockServer);
263+
264+
const store = await MutableDataStore.fromFile(dataStoreFile);
265+
// @ts-expect-error - mock server has enough structure for this test
266+
attachDataStoreInvalidation(store, mockServer, settings);
267+
268+
store.set('dogs', 'poodle', { id: 'poodle', data: { breed: 'Poodle' } });
269+
await store.waitUntilSaveComplete();
270+
271+
const prerenderChanged = mockServer.sentMessages.filter(
272+
(msg) => msg.channel === 'prerender' && msg.type === 'astro:content-changed',
273+
);
274+
assert.equal(
275+
prerenderChanged.length,
276+
1,
277+
'the prerender environment should receive astro:content-changed',
278+
);
279+
280+
const ssrChanged = mockServer.sentMessages.filter(
281+
(msg) => msg.channel === 'ssr' && msg.type === 'astro:content-changed',
282+
);
283+
assert.equal(ssrChanged.length, 1, 'the SSR environment should also receive the signal');
284+
});
239285
});

0 commit comments

Comments
 (0)