mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-19 13:36:48 +00:00
c9dfe9c688
After an update, a tab or a device whose service worker still serves the previous build asks for chunks the update removed. The server answered those requests with index.html and a 200, so the import failed with a MIME error, and everything caching in between was free to keep the HTML as the chunk. A precache install that met a missing file stored it, and Workbox reuses hashed entries by URL, so the device showed "A new version is available" on every load, whatever the reload or the cleared browser cache, and carried the broken entry into every later release that keeps the file's name. The SPA fallback now answers a GET for a build file that is not on disk with a plain 404 (no-store) instead of index.html. A precache install refuses it, so the worker whose cache is complete stays in charge until the new build is. index.html is sent relative to the public dir, which also stops an install living under a dot directory from answering every deep link with a 404. On the client, the reload after a dead chunk (the automatic one and the button on the update screen) no longer goes straight back to the worker that served the broken shell. When that same worker is still in charge and the server answers, its precache and registration are dropped first, so the reload reaches the build the server runs now. Offline, and in offline mode, the shell is kept. Every recovery reload, and the reload of the version handover, asks for the page under a one-off query parameter, so a proxy or CDN that keeps index.html against its headers cannot hand back the stale shell either. A chunk the entry imports statically fails before any of that code runs. shell-guard.js, a small classic script loaded ahead of the entry, watches for exactly that failure and runs the same recovery, once per session. A stylesheet, font or icon that holds a page raises no error at all, so once the app has started and the browser is idle, it looks through the precache for entries that hold a page under a build file's name, fetches each from the server past every cache and puts it back in place. A repaired stylesheet is loaded again, and so are the app's stylesheets when a font was repaired, since the browser does not try a face that failed again in the same document. Only the headers are read, a precache found sound is not looked at again until its entries change, nothing is fetched while nothing is broken, and nothing happens offline, in offline mode or without storage. An answer that is not the file (an auth wall, its login page, a server error) leaves the entry for the next launch. A page the recovery loaded from the network already runs the version the server reports, so the version handover now records it instead of reloading it a second time once the new worker takes over. A page loaded past an older worker that is still in charge, as a hard reload does, still asks for the new worker and records the version only once that has taken over, so the next tab or launch cannot get the old shell without a handover. Dropping the worker ends a Web Push subscription with it, so on such a device the settings card shows push as off until it is switched on again. A missing sw-push.js now fails the worker install with a 404 rather than index.html; the comments that described the old answer say so.
113 lines
4.8 KiB
TypeScript
113 lines
4.8 KiB
TypeScript
/**
|
|
* SPA fallback e2e (#2524). Boots a Nest app with the production static layer and
|
|
* the two global filters wired the way AppModule and bootstrap wire them, then asks
|
|
* over HTTP for a page, for a build file that exists, and for build files an
|
|
* update removed.
|
|
*
|
|
* The last case is the bug: a tab or service worker still on the previous release
|
|
* asks for its chunks, and those requests used to be answered with index.html and a
|
|
* 200, which a precache then kept as the chunk. They must be a plain 404.
|
|
*/
|
|
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import request from 'supertest';
|
|
import type { Server } from 'http';
|
|
import { Module, type INestApplication } from '@nestjs/common';
|
|
import { Test } from '@nestjs/testing';
|
|
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
|
import { SpaFallbackFilter } from '../../src/nest/platform/spa-fallback.filter';
|
|
import { applyPlatformStatic, PUBLIC_DIR } from '../../src/nest/platform/platform.routes';
|
|
|
|
@Module({})
|
|
class NoRoutesModule {}
|
|
|
|
const PRESENT_CHUNK = 'assets/e2e-2524-present-Q1w2E3r4.js';
|
|
const created: string[] = [];
|
|
const createdDirs: string[] = [];
|
|
|
|
/** Writes a file below the served public dir unless the build already put one there. */
|
|
function ensurePublicFile(rel: string, content: string): void {
|
|
const file = path.join(PUBLIC_DIR, rel);
|
|
if (fs.existsSync(file)) return;
|
|
const dir = path.dirname(file);
|
|
if (!fs.existsSync(dir)) {
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
createdDirs.push(dir);
|
|
}
|
|
fs.writeFileSync(file, content);
|
|
created.push(file);
|
|
}
|
|
|
|
describe('SPA fallback e2e: pages get index.html, missing build files a 404 (#2524)', () => {
|
|
const previousEnv = process.env.NODE_ENV;
|
|
let app: INestApplication;
|
|
let server: Server;
|
|
|
|
beforeAll(async () => {
|
|
ensurePublicFile('index.html', '<!DOCTYPE html><html><body><div id="root"></div></body></html>');
|
|
ensurePublicFile(PRESENT_CHUNK, 'export default 1;\n');
|
|
process.env.NODE_ENV = 'production';
|
|
|
|
const moduleRef = await Test.createTestingModule({ imports: [NoRoutesModule] }).compile();
|
|
app = moduleRef.createNestApplication();
|
|
// Before init, like bootstrap.ts: a real file is answered ahead of Nest's router.
|
|
applyPlatformStatic(app.getHttpAdapter().getInstance());
|
|
// Same pair and order as the APP_FILTER providers in AppModule.
|
|
app.useGlobalFilters(new TrekExceptionFilter(), new SpaFallbackFilter());
|
|
await app.init();
|
|
server = app.getHttpServer();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await app?.close();
|
|
for (const file of created) fs.rmSync(file, { force: true });
|
|
for (const dir of createdDirs.reverse()) fs.rmSync(dir, { recursive: true, force: true });
|
|
if (previousEnv === undefined) delete process.env.NODE_ENV;
|
|
else process.env.NODE_ENV = previousEnv;
|
|
});
|
|
|
|
it('answers a page of the app with index.html', async () => {
|
|
const res = await request(server).get('/dashboard');
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers['content-type']).toContain('text/html');
|
|
expect(res.headers['cache-control']).toBe('no-cache, no-store, must-revalidate');
|
|
expect(res.text.toLowerCase()).toContain('<html');
|
|
});
|
|
|
|
it('serves a build file that exists', async () => {
|
|
const res = await request(server).get(`/${PRESENT_CHUNK}`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers['content-type']).toContain('javascript');
|
|
});
|
|
|
|
it('answers a chunk of the previous release with a 404, not index.html', async () => {
|
|
const res = await request(server).get('/assets/DashboardPage-v4ODOTOr.js');
|
|
expect(res.status).toBe(404);
|
|
expect(res.headers['content-type']).toContain('application/json');
|
|
expect(res.headers['cache-control']).toBe('no-store');
|
|
expect(res.body).toEqual({ error: 'Cannot GET /assets/DashboardPage-v4ODOTOr.js' });
|
|
});
|
|
|
|
// The whole answer is asserted, not just the status: a checkout under a dot
|
|
// directory (~/.local) made the old fallback fail with a 404 of its own, which
|
|
// a status check alone would count as the fix.
|
|
it.each([
|
|
['a cache-busted retry of that chunk', '/assets/DashboardPage-v4ODOTOr.js?t=1790358416100'],
|
|
['its stylesheet', '/assets/DashboardPage-v4ODOTOr.css'],
|
|
['a top-level build file', '/manifest-e2e-2524.webmanifest'],
|
|
])('does the same for %s', async (_case, url) => {
|
|
const res = await request(server).get(url);
|
|
expect(res.status).toBe(404);
|
|
expect(res.headers['content-type']).toContain('application/json');
|
|
expect(res.headers['cache-control']).toBe('no-store');
|
|
expect(res.body).toEqual({ error: `Cannot GET ${url}` });
|
|
});
|
|
|
|
it('keeps the JSON envelope for a non-GET miss', async () => {
|
|
const res = await request(server).post('/dashboard').send({});
|
|
expect(res.status).toBe(404);
|
|
expect(res.body).toEqual({ error: 'Cannot POST /dashboard' });
|
|
});
|
|
});
|