Files
vibemake/tests/cad/engine-updates.browser.mjs
T
2026-11-06 15:54:55 +08:00

177 lines
10 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { chromium } from 'playwright';
import { cadWorker } from '../../scripts/cad-engine.mjs';
const root = new URL('../../', import.meta.url);
const html = `<!doctype html><button hidden>Refresh</button><script type="module">
import { loadEngine, prepareEngineRefresh } from '/js/cad/engine.js';
window.notices = 0;
window.manifestChecks = 0;
const nativeFetch = window.fetch;
window.fetch = async (...args) => {
const response = await nativeFetch(...args);
if (args[0] === '/cad/engine.json') {
const json = response.json.bind(response);
response.json = async () => { const value = await json(); window.manifestChecks++; return value; };
}
return response;
};
const button = document.querySelector('button');
addEventListener('vm:cad:update', () => { window.notices++; button.hidden = false; });
button.onclick = async () => {
button.disabled = true;
try { await prepareEngineRefresh(); location.reload(); }
catch { window.refreshFailed = true; button.disabled = false; }
};
await loadEngine(); window.engineReady = true;
</script>`;
// Exact lifecycle behaviour of packages shipped before explicit activation existed.
const legacyWorker = (manifest) => `
const FILES=new Set(${JSON.stringify(manifest.files.map((f) => f.path))});
const CACHE='vm.cad.static.${manifest.buildId}';
self.addEventListener('install',()=>{});
self.addEventListener('activate',()=>{});
self.addEventListener('fetch',event=>{const u=new URL(event.request.url);if(event.request.method!=='GET'||u.origin!==self.location.origin||u.search||!FILES.has(u.pathname))return;event.respondWith((async()=>{const cache=await caches.open(CACHE);const hit=await cache.match(event.request);if(hit)return hit;const response=await fetch(event.request);if(response.ok)await cache.put(event.request,response.clone());return response;})());});
`;
test('CAD engine updates complete without clearing browser data', async (t) => {
let buildId = 'v1', legacy = false, workerUnavailable = false;
const manifest = () => ({
bridgeVersion: 1, buildId,
js: `/cad/_assets/${buildId}/engine.js`, wasm: `/cad/_assets/${buildId}/engine.wasm`, chineseFont: `/cad/_assets/${buildId}/font.otf`,
files: ['engine.js', 'engine.wasm', 'font.otf'].map((name) => ({ path: `/cad/_assets/${buildId}/${name}` })),
});
const server = createServer(async (req, res) => {
const path = new URL(req.url, 'http://localhost').pathname;
res.setHeader('Cache-Control', 'no-store');
if (path === '/cad/editor/') res.writeHead(200, { 'Content-Type': 'text/html' }).end(html);
else if (path === '/cad/seed/') res.writeHead(200, { 'Content-Type': 'text/html' }).end('<!doctype html><title>Previous editor</title>');
else if (path === '/cad/worker.js') res.writeHead(workerUnavailable ? 503 : 200, { 'Content-Type': 'text/javascript' }).end(await readFile(new URL('cad/worker.js', root)));
else if (path === '/cad/engine.json') res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(manifest()));
else if (path === '/cad/sw.js') res.writeHead(workerUnavailable ? 503 : 200, { 'Content-Type': 'text/javascript' }).end(legacy ? legacyWorker(manifest()) : cadWorker(manifest()));
else if (path === '/other/sw.js') res.writeHead(200, { 'Content-Type': 'text/javascript' }).end("self.addEventListener('install',()=>{});");
else if (/^\/cad\/_assets\/[^/]+\/engine.js$/.test(path)) {
const version = path.split('/')[3];
res.writeHead(200, { 'Content-Type': 'text/javascript' }).end(`export default async function() { window.engineBuild=${JSON.stringify(version)}; window.vibemakeCad={ready:async()=>({})}; }`);
} else if (path.startsWith('/cad/_assets/')) res.writeHead(200).end('asset');
else if (path.startsWith('/js/')) {
try { res.writeHead(200, { 'Content-Type': 'text/javascript' }).end(await readFile(new URL(path.slice(1), root))); }
catch { res.writeHead(404).end(); }
} else res.writeHead(404).end();
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch({ headless: true });
t.after(async () => { await browser.close(); server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); });
const loaded = (page, expected) => page.waitForFunction((version) => window.engineReady && window.engineBuild === version, expected);
const open = async (context) => {
const page = await context.newPage();
await page.goto(`${base}/cad/editor/`);
await loaded(page, buildId);
await page.evaluate(() => navigator.serviceWorker.ready);
await page.reload();
await loaded(page, buildId);
await page.waitForFunction(() => !!navigator.serviceWorker.controller);
return page;
};
const publish = async (page) => {
await page.evaluate(async () => { await (await navigator.serviceWorker.getRegistration('/cad/')).update(); });
await page.waitForFunction(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting);
};
const preserveData = async (page) => page.evaluate(async () => {
localStorage.setItem('vm.auth', 'preserved-login');
const { DraftStore } = await import('/js/cad/drafts.js');
const store = new DraftStore();
await store.put('owner', 'project', 'session', 'draft', { snapshotId: 'keep-draft', bytes: new Uint8Array([1, 2, 3]) });
await (await caches.open('unrelated-cache')).put('/keep', new Response('keep'));
await navigator.serviceWorker.register('/other/sw.js', { scope: '/other/' });
});
const assertData = async (page) => {
const data = await page.evaluate(async () => {
const { DraftStore } = await import('/js/cad/drafts.js');
const drafts = await new DraftStore().list('owner', 'project', 'draft');
return { auth: localStorage.getItem('vm.auth'), draft: [...drafts[0].bytes], cache: await (await caches.match('/keep')).text(), otherWorker: !!await navigator.serviceWorker.getRegistration('/other/') };
});
assert.deepEqual(data, { auth: 'preserved-login', draft: [1, 2, 3], cache: 'keep', otherWorker: true });
};
await t.test('activates the new worker before refresh and leaves other editor tabs intact', async () => {
buildId = 'v1'; legacy = false;
const context = await browser.newContext();
try {
const first = await open(context), second = await open(context);
await second.evaluate(() => { window.unsavedDesign = 'keep editing'; });
await preserveData(first);
buildId = 'v2';
await publish(first);
await first.waitForFunction(() => window.notices === 1);
assert.equal(await first.evaluate(() => window.engineBuild), 'v1');
await first.getByRole('button', { name: 'Refresh' }).click();
await loaded(first, 'v2');
assert.equal(await first.evaluate(() => window.notices), 0);
assert.equal(await first.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting), false);
assert.deepEqual(await second.evaluate(() => ({ build: window.engineBuild, design: window.unsavedDesign })), { build: 'v1', design: 'keep editing' });
await assertData(first);
await first.reload(); await loaded(first, 'v2');
assert.equal(await first.evaluate(() => window.notices), 0);
} finally { await context.close(); }
});
await t.test('recovers from a legacy waiting worker without clearing auth, drafts or other scopes', async () => {
buildId = 'legacy-v1'; legacy = true;
const context = await browser.newContext();
try {
const previous = await context.newPage();
await previous.goto(`${base}/cad/seed/`);
await previous.evaluate(async () => {
await navigator.serviceWorker.register('/cad/sw.js', { scope: '/cad/', updateViaCache: 'none' });
await navigator.serviceWorker.ready;
});
const page = await open(context), other = await open(context);
await preserveData(page);
buildId = 'legacy-v2'; await publish(page);
await page.waitForFunction(() => window.notices === 1);
await page.getByRole('button', { name: 'Refresh' }).click();
await loaded(page, 'legacy-v2');
await page.evaluate(() => navigator.serviceWorker.ready);
assert.equal(await page.evaluate(() => window.notices), 0);
assert.equal(await page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting), false);
assert.equal(await other.evaluate(() => window.engineBuild), 'legacy-v1');
await assertData(page);
} finally { await context.close(); }
});
await t.test('a fresh engine does not show an update merely because a cache worker is waiting', async () => {
buildId = 'same-v1'; legacy = true;
const context = await browser.newContext();
try {
const page = await open(context), other = await open(context);
buildId = 'same-v2'; await publish(page);
await page.reload(); await loaded(page, 'same-v2');
await page.waitForFunction(() => window.manifestChecks === 2);
assert.equal(await page.evaluate(() => window.notices), 0);
assert.equal(await page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('/cad/')).waiting), true);
assert.equal(await other.evaluate(() => window.engineBuild), 'same-v1');
} finally { await context.close(); }
});
await t.test('failed worker checks keep the editor open for retry', async () => {
buildId = 'offline-v1'; legacy = false;
const context = await browser.newContext();
try {
const page = await open(context);
buildId = 'offline-v2'; await publish(page);
await page.waitForFunction(() => window.notices === 1);
workerUnavailable = true;
await page.getByRole('button', { name: 'Refresh' }).click();
await page.waitForFunction(() => window.refreshFailed);
assert.equal(await page.evaluate(() => window.engineBuild), 'offline-v1');
assert.equal(await page.getByRole('button', { name: 'Refresh' }).isEnabled(), true);
} finally { workerUnavailable = false; await context.close(); }
});
});