import { spawnSync } from "node:child_process"; import { access, mkdir, mkdtemp, readFile, rm, symlink, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts"; import { type FixtureBuilds, prepareFixtureBuilds, removeFixtureBuilds, } from "../e2e/support/fixture-builds.ts"; import { ACTIVE_VALUE, turnOnServiceWorker, } from "../e2e/support/service-worker-builds.ts"; /** * 0929/06-01. Step 6 of `scripts/build-frontend.ts`, the Service Worker Vite * build, must not change the app output. Vite copies `public/` into `outDir` * unless the config turns it off, so the worker build replaced the profile * `dist/config.json` from step 4 with `public/config.json` (local, demo auth, * loopback API, root release manifest). The build and `verify-release` passed; * only release admission refused it. * * The defect is in how two Vite runs share `dist`, not in one function, so this * runs the real build over a temp copy with the worker on (one build, ~2s). * A check of `publicDir === false` on the config object would only restate the * fix, and the config cannot load without the inputs step 5 generates. */ const PROFILE = Object.freeze({ APP_PROFILE: "production", VITE_ROUTER_BASE_PATH: "/app/", }); // prepareFixtureBuilds sets VITE_BUILD_ID and RELEASE_ID to `-`. const BUILD_ID = "sw-profile-active"; let builds: FixtureBuilds<"active"> | undefined; beforeAll(async () => { builds = await prepareFixtureBuilds("sw-profile", [ { name: "active", env: PROFILE, edit: turnOnServiceWorker, }, ]); }, 180_000); afterAll(async () => { await removeFixtureBuilds(builds); }); describe("Service Worker build output (0929/06-01, 0929/06-02)", () => { it("keeps the profile runtime config step 4 wrote", async () => { const dist = builds!.dist.active; // The worker build really ran; otherwise nothing below tests step 6. await access(path.join(dist, "service-worker.js")); const shipped: unknown = JSON.parse( await readFile(path.join(dist, "config.json"), "utf8"), ); expect(shipped).toEqual( await generateRuntimeConfig("production", { ...process.env, ...PROFILE, VITE_BUILD_ID: BUILD_ID, RELEASE_ID: BUILD_ID, }), ); }); // 0929/06-02. Under /app/ the worker must precache /app/assets/... and know // /app/config.json; root URLs 404 at install and the worker never installs. it("gives the worker URLs under the router base path", async () => { const generated = (await import( path.join( builds!.root, ".generated/frontend-runtime/service-worker-assets.ts", ) )) as { SERVICE_WORKER_ASSETS: { assets: readonly { url: string }[] } }; const urls = generated.SERVICE_WORKER_ASSETS.assets.map((asset) => asset.url); expect(urls.length).toBeGreaterThan(0); expect(urls.filter((url) => !url.startsWith("/app/assets/"))).toEqual([]); const worker = await readFile( path.join(builds!.dist.active, "service-worker.js"), "utf8", ); // Property names survive minification; the quote style does not. expect( /runtimeConfigUrl:\s*["'`]([^"'`]*)["'`]/u.exec(worker)?.[1], ).toBe("/app/config.json"); }); }); // 0929/06-05. A new worker and the self-unregistering one are the only way to // recover a client without a page. Served from an edge that caches root `.js` // for long, they stay out of reach for that TTL, so a build that ships a // worker has its script's Cache-Control checked like the page's. describe("worker script hosting headers (0929/06-05)", () => { async function verifyHosting(workerCacheControl: string) { const root = builds!.root; await rm(path.join(root, "dist"), { recursive: true, force: true }); await symlink(builds!.dist.active, path.join(root, "dist")); const fixture = JSON.parse( await readFile("tests/fixtures/hosting/response-headers.json", "utf8"), ) as { responses: Record> }; fixture.responses["serviceWorker"]!["cache-control"] = workerCacheControl; await writeFile( path.join(root, "tests/fixtures/hosting/response-headers.json"), JSON.stringify(fixture), ); const env: NodeJS.ProcessEnv = { ...process.env }; delete env["HOSTING_BASE_URL"]; const result = spawnSync(process.execPath, ["scripts/verify-hosting-headers.ts"], { cwd: root, encoding: "utf8", env, }); const record = JSON.parse( await readFile(path.join(root, "artifacts/release/hosting-headers.json"), "utf8"), ) as { results: { surface: string; header: string; passed: boolean }[] }; return { status: result.status, stderr: result.stderr, failed: record.results .filter((entry) => !entry.passed) .map((entry) => `${entry.surface} ${entry.header}`), }; } it("leaves the declared worker headers UNVERIFIED, not failed", async () => { const result = await verifyHosting("no-cache"); expect(result.failed, result.stderr).toEqual([]); expect(result.status).toBe(3); }); it("fails when the worker script is served with a long TTL", async () => { const result = await verifyHosting("public, max-age=31536000, immutable"); expect(result.failed).toEqual(["serviceWorker cache-control"]); expect(result.status).toBe(1); }); }); // 0929/06-04, 0929/11-03. The worker fixtures must also run in a product that // already ships the worker: an inactive selection is turned on, and an ACTIVE // one is kept so the specs exercise that product's own handlers. describe("turnOnServiceWorker (0929/06-04, 0929/11-03)", () => { const productActive = `{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers: ["PWA_STATIC_ASSETS", "OFFLINE_SYNC_WAKEUP"], }`; it.each([ ["null", "null", ACTIVE_VALUE], [ "REMOVE_REGISTRATION", `{ mode: "REMOVE_REGISTRATION", scriptPath: "service-worker.js", }`, ACTIVE_VALUE, ], ["ACTIVE", productActive, productActive], ])("turns a %s selection on", async (_label, value, expected) => { const root = await mkdtemp(path.join(tmpdir(), "sw-select-")); try { const file = path.join( root, "src/features/product-capabilities.ts", ); await mkdir(path.dirname(file), { recursive: true }); const around = (selection: string) => `const WEB_WORKERS = Object.freeze([]);\n\nconst SERVICE_WORKER: InstalledServiceWorkerSelection | null = ${selection};\n\nconst OFFLINE_COMMANDS: X | null = null;\n`; await writeFile(file, around(value)); await turnOnServiceWorker(root); expect(await readFile(file, "utf8")).toBe(around(expected)); } finally { await rm(root, { recursive: true, force: true }); } }); });