chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
This commit is contained in:
@@ -39,3 +39,38 @@ test("provides an escape-dismissible mobile navigation", async ({ page }) => {
|
||||
await expect(page.getByRole("navigation", { name: "모바일 주요 탐색" })).toBeHidden();
|
||||
await expect(menu).toBeFocused();
|
||||
});
|
||||
|
||||
// R3-6. A drawer link closes the modal drawer and changes the route in the
|
||||
// same click. The drawer's deferred focus restore must not win over the new
|
||||
// page's heading focus; Escape (no navigation) still returns to the menu.
|
||||
test("moves focus to the new page after a mobile drawer link, not back to the menu", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.goto("/");
|
||||
const menu = page.getByRole("button", { name: "메뉴", exact: true });
|
||||
const navigation = page.getByRole("navigation", { name: "주요 탐색" });
|
||||
|
||||
await menu.click();
|
||||
await navigation.getByRole("link", { name: "화면 상태" }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/examples\/states$/);
|
||||
await expect(menu).toHaveAttribute("aria-expanded", "false");
|
||||
const heading = page.getByRole("heading", { level: 1, name: "화면 상태" });
|
||||
await expect(heading).toBeFocused();
|
||||
// Give any late restore (dialog close timer, lazy route commit) time to run.
|
||||
await page.waitForTimeout(300);
|
||||
expect(
|
||||
await page.evaluate(() => {
|
||||
const active = document.activeElement;
|
||||
return active?.matches("h1, main") === true;
|
||||
}),
|
||||
).toBe(true);
|
||||
await expect(menu).not.toBeFocused();
|
||||
|
||||
await menu.click();
|
||||
await expect(navigation).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(navigation).toBeHidden();
|
||||
await expect(menu).toBeFocused();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { expect, test } from "../support/browser/strict-browser-test.ts";
|
||||
import {
|
||||
editOnce,
|
||||
prepareFixtureBuilds,
|
||||
removeFixtureBuilds,
|
||||
type FixtureBuilds,
|
||||
} from "./support/fixture-builds.ts";
|
||||
import { startBuildServer } from "./support/service-worker-builds.ts";
|
||||
|
||||
/**
|
||||
* 09-03 (F-2). A production build whose application graph throws while its
|
||||
* modules evaluate: the installed features are composed twice, so
|
||||
* `installed-feature-messages.ts` meets every message key a second time and
|
||||
* throws at module top level. The static "loading" shell used to stay up
|
||||
* forever; the boot error shell has to replace it.
|
||||
*/
|
||||
|
||||
let builds: FixtureBuilds<"broken"> | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
test.setTimeout(300_000);
|
||||
builds = await prepareFixtureBuilds("boot-module-failure", [
|
||||
{
|
||||
name: "broken",
|
||||
edit: (root) =>
|
||||
editOnce(
|
||||
path.join(root, "src/features/installed-feature-messages.ts"),
|
||||
"composeInstalledMessageCatalogs(\n INSTALLED_PRODUCT_FEATURE_MODULES,\n)",
|
||||
"composeInstalledMessageCatalogs([\n ...INSTALLED_PRODUCT_FEATURE_MODULES,\n ...INSTALLED_PRODUCT_FEATURE_MODULES,\n])",
|
||||
),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await removeFixtureBuilds(builds);
|
||||
});
|
||||
|
||||
test("shows the boot error shell when a module throws while it evaluates", async ({
|
||||
page,
|
||||
}) => {
|
||||
if (!builds) throw new Error("Fixture build was not prepared.");
|
||||
const broken = builds.dist.broken;
|
||||
const server = await startBuildServer({ a: broken, b: broken });
|
||||
try {
|
||||
await page.goto(`${server.origin}/`);
|
||||
|
||||
const shell = page.getByRole("alert");
|
||||
await expect(shell).toContainText("애플리케이션을 시작할 수 없습니다.");
|
||||
await expect(shell).toContainText("BOOT_UNEXPECTED_FAILURE");
|
||||
await expect(shell).toContainText("TypeError");
|
||||
await expect(shell).toContainText("boot-module-failure-broken");
|
||||
await expect(page.locator("[data-boot-shell]")).toHaveCount(0);
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { appendFile, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
|
||||
import { expect, test } from "../support/browser/strict-browser-test.ts";
|
||||
import {
|
||||
prepareFixtureBuilds,
|
||||
removeFixtureBuilds,
|
||||
type FixtureBuilds,
|
||||
} from "./support/fixture-builds.ts";
|
||||
import { startBuildServer } from "./support/service-worker-builds.ts";
|
||||
|
||||
/**
|
||||
* 11-05. A tab opened on build A, in the default configuration (no Service
|
||||
* Worker), after build B is deployed. B changes two lazy route pages, so their
|
||||
* A chunks no longer exist on the server. The first missing chunk reloads the
|
||||
* tab once, into B. A second missing chunk (the server alternates back to A,
|
||||
* as mismatched replicas do) must not reload again: the tab shows the
|
||||
* recovery failure instead.
|
||||
*/
|
||||
|
||||
// Template sync (af3d8e6). Upstream uses two of its example pages, which this
|
||||
// product deleted; two TechLog primary-navigation pages play the same part.
|
||||
const PLATFORM = ROUTE_REGISTRY.TECH_LOG_EXPLORE;
|
||||
const UI = ROUTE_REGISTRY.TECH_LOG_TOPICS;
|
||||
const PAGES = [
|
||||
"src/features/tech-log/presentation/public/pages/explore-page.tsx",
|
||||
"src/features/tech-log/presentation/public/pages/topics-page.tsx",
|
||||
] as const;
|
||||
|
||||
let builds: FixtureBuilds<"a" | "b"> | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
test.setTimeout(300_000);
|
||||
builds = await prepareFixtureBuilds("chunk-recovery", [
|
||||
{ name: "a" },
|
||||
{
|
||||
name: "b",
|
||||
edit: async (root) => {
|
||||
for (const page of PAGES) {
|
||||
await appendFile(
|
||||
path.join(root, page),
|
||||
'\n(globalThis as Record<string, unknown>).__caFixtureBuild = "b";\n',
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await removeFixtureBuilds(builds);
|
||||
});
|
||||
|
||||
async function routeChunk(dist: string, chunkId: string): Promise<string> {
|
||||
const manifest = JSON.parse(
|
||||
await readFile(path.join(dist, "release-manifest.json"), "utf8"),
|
||||
) as { routeChunks: Record<string, string> };
|
||||
return `/${manifest.routeChunks[chunkId]}`;
|
||||
}
|
||||
|
||||
// Each missing page chunk fails its request and the dynamic import. Chromium
|
||||
// may also log the 404 itself (without its URL), Firefox logs the error
|
||||
// object React caught, and WebKit logs its own import error without the URL.
|
||||
// Nothing else is allowed.
|
||||
const MISSING_PAGE = String.raw`/assets/route-tech-log-(?:explore|topics)-[\w-]+\.js`;
|
||||
test.use({
|
||||
allowedBrowserFailure: new RegExp(
|
||||
[
|
||||
String.raw`^requestfailed:GET:${MISSING_PAGE}:`,
|
||||
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`,
|
||||
String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`,
|
||||
String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`,
|
||||
String.raw`^console:error:JSHandle@object$`,
|
||||
String.raw`^console:error:TypeError: Importing a module script failed\.$`,
|
||||
].join("|"),
|
||||
"u",
|
||||
),
|
||||
});
|
||||
|
||||
test("an old tab reloads once into the new build, then stops reloading", async ({
|
||||
page,
|
||||
}) => {
|
||||
if (!builds) throw new Error("Fixture builds were not prepared.");
|
||||
const aPlatform = await routeChunk(builds.dist.a, PLATFORM.chunkId);
|
||||
const bPlatform = await routeChunk(builds.dist.b, PLATFORM.chunkId);
|
||||
const bUi = await routeChunk(builds.dist.b, UI.chunkId);
|
||||
expect(bPlatform).not.toBe(aPlatform);
|
||||
expect(bUi).not.toBe(await routeChunk(builds.dist.a, UI.chunkId));
|
||||
|
||||
const server = await startBuildServer(builds.dist);
|
||||
try {
|
||||
await page.goto(`${server.origin}/`);
|
||||
await expect(
|
||||
page.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true }),
|
||||
).toBeVisible();
|
||||
let loads = 0;
|
||||
page.on("load", () => {
|
||||
loads += 1;
|
||||
});
|
||||
|
||||
// Build B is deployed while the A tab stays open.
|
||||
server.serve("b");
|
||||
await page
|
||||
.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true })
|
||||
.click();
|
||||
|
||||
await expect(page.getByRole("heading", { name: PLATFORM.title })).toBeVisible();
|
||||
expect(loads).toBe(1);
|
||||
const served = server.served.map((entry) => entry.path);
|
||||
expect(served).not.toContain(aPlatform);
|
||||
expect(served).toContain(bPlatform);
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => (globalThis as Record<string, unknown>).__caFixtureBuild))
|
||||
.toBe("b");
|
||||
|
||||
// The replicas alternate: the B tab now meets A, which lacks B's chunk.
|
||||
server.serve("a");
|
||||
await page.getByRole("link", { name: UI.navigationLabel!, exact: true }).click();
|
||||
|
||||
await expect(page.getByRole("alert")).toContainText(
|
||||
"화면 자산을 복구하지 못했습니다.",
|
||||
);
|
||||
expect(loads).toBe(1);
|
||||
expect(page.url()).toBe(`${server.origin}${UI.path}`);
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
|
||||
|
||||
// 13-08. The Content-Security-Policy in config/hosting/security-headers.json was
|
||||
// declared but never applied in a browser: `vite preview` sends no security
|
||||
// headers. This smoke serves the build with the production headers attached
|
||||
// and fails on any securitypolicyviolation event or console error.
|
||||
const { headers: declaredHeaders } = JSON.parse(
|
||||
readFileSync("config/hosting/security-headers.json", "utf8"),
|
||||
) as { headers: Record<string, string> };
|
||||
// The preview server is plain HTTP on loopback. `upgrade-insecure-requests` is a
|
||||
// no-op for an HTTPS origin, but WebKit applies it to loopback and rewrites
|
||||
// every same-origin request to https, which this server cannot answer. Every
|
||||
// other directive is served exactly as declared.
|
||||
const securityHeaders = {
|
||||
...declaredHeaders,
|
||||
"Content-Security-Policy": declaredHeaders["Content-Security-Policy"]!
|
||||
.split(";")
|
||||
.map((directive) => directive.trim())
|
||||
.filter((directive) => directive !== "upgrade-insecure-requests")
|
||||
.join("; "),
|
||||
};
|
||||
|
||||
// F-7. No zod setup here: the app sets `jitless` in src/contracts/zod.ts before
|
||||
// any schema is built, so zod's `Function("")` probe never reaches the policy.
|
||||
test.beforeEach(async ({ page, baseURL }) => {
|
||||
const origin = new URL(baseURL ?? "http://127.0.0.1:4173").origin;
|
||||
await page.route(
|
||||
(url) => url.origin === origin,
|
||||
async (route) => {
|
||||
const response = await route.fetch();
|
||||
await route.fulfill({
|
||||
response,
|
||||
headers: { ...response.headers(), ...securityHeaders },
|
||||
});
|
||||
},
|
||||
);
|
||||
await page.addInitScript(() => {
|
||||
const violations: string[] = [];
|
||||
Object.defineProperty(window, "__cspViolations", { value: violations });
|
||||
document.addEventListener("securitypolicyviolation", (event) => {
|
||||
violations.push(`${event.effectiveDirective} ${event.blockedURI}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
async function cspViolations(page: Page): Promise<string[]> {
|
||||
return page.evaluate(() => (window as unknown as { __cspViolations: string[] }).__cspViolations);
|
||||
}
|
||||
|
||||
test("boots and changes route under the production security headers", async ({ page }) => {
|
||||
const response = await page.goto("/");
|
||||
expect(response?.headers()["content-security-policy"]).toBe(
|
||||
securityHeaders["Content-Security-Policy"],
|
||||
);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText(
|
||||
"Clean Architecture Frontend",
|
||||
);
|
||||
|
||||
await page
|
||||
.getByRole("navigation", { name: "주요 탐색" })
|
||||
.getByRole("link", { name: "화면 상태" })
|
||||
.click();
|
||||
await expect(
|
||||
page.getByRole("heading", { level: 1, name: "화면 상태" }),
|
||||
).toBeFocused();
|
||||
|
||||
expect(await cspViolations(page)).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
|
||||
|
||||
const scrollY = (page: Page) => page.evaluate(() => Math.round(window.scrollY));
|
||||
|
||||
// 08-08. Back restores where the user was; a new route starts at the top.
|
||||
test("restores the scroll position when navigating back", async ({ page }) => {
|
||||
const heading = page.getByRole("heading", { level: 1 });
|
||||
await page.goto("/examples/ui");
|
||||
await expect(heading).toHaveText("UI 구성요소");
|
||||
await page.evaluate(() => window.scrollTo(0, 900));
|
||||
await expect.poll(() => scrollY(page)).toBe(900);
|
||||
|
||||
await page
|
||||
.getByRole("navigation", { name: "주요 탐색" })
|
||||
.getByRole("link", { name: "화면 상태" })
|
||||
.click();
|
||||
await expect(heading).toHaveText("화면 상태");
|
||||
await expect.poll(() => scrollY(page)).toBe(0);
|
||||
|
||||
await page.goBack();
|
||||
await expect(heading).toHaveText("UI 구성요소");
|
||||
await expect.poll(() => scrollY(page)).toBe(900);
|
||||
});
|
||||
|
||||
test("opens a hash link at its target below the sticky header", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/examples/ui#tokens-title");
|
||||
const target = page.locator("#tokens-title");
|
||||
await expect(target).toBeInViewport();
|
||||
const top = await target.evaluate((element) =>
|
||||
Math.round(element.getBoundingClientRect().top),
|
||||
);
|
||||
const headerBottom = await page
|
||||
.locator(".app-shell__header")
|
||||
.evaluate((element) => Math.round(element.getBoundingClientRect().bottom));
|
||||
expect(top).toBeGreaterThanOrEqual(headerBottom);
|
||||
expect(await scrollY(page)).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
|
||||
import {
|
||||
ACTIVE_SELECTION,
|
||||
prepareServiceWorkerBuilds,
|
||||
removeServiceWorkerBuilds,
|
||||
replaceOnce,
|
||||
startBuildServer,
|
||||
type ServiceWorkerBuilds,
|
||||
} from "./support/service-worker-builds.ts";
|
||||
|
||||
/**
|
||||
* 06-03 (D-5). The emergency exit for a worker that stops the page from
|
||||
* booting. Page code cannot help then: the page never runs. Build A is the
|
||||
* ACTIVE worker with its fetch handler broken (every intercepted request is a
|
||||
* network error, the entry script included). Build B is a
|
||||
* `REMOVE_REGISTRATION` release, which ships the self-unregistering
|
||||
* `service-worker.js` (`scripts/lib/self-unregistering-service-worker.ts`).
|
||||
* The browser's update check alone replaces A with it, and the next load boots
|
||||
* B from the network.
|
||||
*/
|
||||
|
||||
type Probe = typeof globalThis & {
|
||||
__caServiceWorkerTest?: { events: string[] };
|
||||
};
|
||||
|
||||
let builds: ServiceWorkerBuilds | undefined;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
test.setTimeout(180_000);
|
||||
builds = await prepareServiceWorkerBuilds({
|
||||
async beforeBuild(name, root) {
|
||||
if (name === "a") {
|
||||
await replaceOnce(
|
||||
path.join(root, "src/adapters/service-worker/service-worker-entry.ts"),
|
||||
"runtime.onFetch(described).then((cached) => cached ?? fetch(request)),",
|
||||
"Promise.resolve(Response.error()),",
|
||||
);
|
||||
return;
|
||||
}
|
||||
await replaceOnce(
|
||||
path.join(root, "src/features/installed-runtime-capabilities.ts"),
|
||||
ACTIVE_SELECTION,
|
||||
`const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
|
||||
mode: "REMOVE_REGISTRATION",
|
||||
scriptPath: "service-worker.js",
|
||||
};`,
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await removeServiceWorkerBuilds(builds);
|
||||
});
|
||||
|
||||
async function startOutcome(page: Page): Promise<unknown> {
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
|
||||
event.startsWith("start:"),
|
||||
) === true,
|
||||
undefined,
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
const event = await page.evaluate(() =>
|
||||
(globalThis as Probe).__caServiceWorkerTest!.events.find((entry) =>
|
||||
entry.startsWith("start:"),
|
||||
)!,
|
||||
);
|
||||
return JSON.parse(event.slice("start:".length));
|
||||
}
|
||||
|
||||
test("a REMOVE_REGISTRATION release unregisters a worker that blocks boot", async ({
|
||||
browser,
|
||||
browserName,
|
||||
}) => {
|
||||
// Same quarantine as service-worker-update.spec.ts.
|
||||
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
|
||||
test.skip(
|
||||
browserName === "firefox",
|
||||
"Playwright Firefox pages are never controlled by a service worker.",
|
||||
);
|
||||
if (!builds) throw new Error("Service Worker builds were not prepared.");
|
||||
const server = await startBuildServer(builds.dist);
|
||||
// The broken phase fails requests on purpose, so this test drives its own
|
||||
// context instead of the strict `page` fixture and checks the recovered
|
||||
// load for browser errors itself.
|
||||
const context = await browser.newContext();
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.goto(`${server.origin}/`);
|
||||
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
|
||||
await page.evaluate(async () => {
|
||||
await navigator.serviceWorker.ready;
|
||||
});
|
||||
|
||||
// Worker A controls the next load and fails the entry script.
|
||||
await page.goto(`${server.origin}/`);
|
||||
const blocked = await page.evaluate(async () => {
|
||||
const entry = document.querySelector<HTMLScriptElement>(
|
||||
'script[type="module"][src]',
|
||||
);
|
||||
if (!entry) return "no entry script";
|
||||
try {
|
||||
await fetch(entry.src);
|
||||
return "loaded";
|
||||
} catch {
|
||||
return navigator.serviceWorker.controller ? "blocked" : "uncontrolled";
|
||||
}
|
||||
});
|
||||
expect(blocked).toBe("blocked");
|
||||
|
||||
// Release B. Only the browser's update check runs; no code of B does.
|
||||
server.serve("b");
|
||||
await page.evaluate(async () => {
|
||||
await (await navigator.serviceWorker.getRegistration())?.update();
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
page.evaluate(
|
||||
async () =>
|
||||
(await navigator.serviceWorker.getRegistration()) === undefined,
|
||||
),
|
||||
{ timeout: 30_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
|
||||
const failures: string[] = [];
|
||||
page.on("console", (message) => {
|
||||
if (["error", "warning"].includes(message.type())) {
|
||||
failures.push(`console:${message.type()}:${message.text()}`);
|
||||
}
|
||||
});
|
||||
page.on("pageerror", (error) => failures.push(`pageerror:${error.name}`));
|
||||
page.on("requestfailed", (request) =>
|
||||
failures.push(`requestfailed:${new URL(request.url()).pathname}`),
|
||||
);
|
||||
await page.goto(`${server.origin}/`);
|
||||
expect(await startOutcome(page)).toEqual({ kind: "DISABLED" });
|
||||
expect(
|
||||
await page.evaluate(() => navigator.serviceWorker.controller === null),
|
||||
).toBe(true);
|
||||
expect(failures).toEqual([]);
|
||||
} finally {
|
||||
await context.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import { appendFile, readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
|
||||
import {
|
||||
prepareServiceWorkerBuilds,
|
||||
removeServiceWorkerBuilds,
|
||||
startBuildServer,
|
||||
type ServiceWorkerBuilds,
|
||||
} from "./support/service-worker-builds.ts";
|
||||
|
||||
/**
|
||||
* R3-6. Real-browser Service Worker checks, against real production builds.
|
||||
*
|
||||
* How the worker is enabled: the template's default build has
|
||||
* `serviceWorker: null`, and the only supported switch is the static
|
||||
* capability selection in `src/features/installed-runtime-capabilities.ts`
|
||||
* (`{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers:
|
||||
* ["PWA_STATIC_ASSETS"] }`); `scripts/build-frontend.ts` then adds the worker
|
||||
* build. `support/service-worker-builds.ts` applies that selection in a temp
|
||||
* copy of the repo, builds it twice (`VITE_BUILD_ID` sw-e2e-a / sw-e2e-b),
|
||||
* and serves either dist from its own port per test. The copy also records
|
||||
* the worker host's `onUpdateWaiting` / `onReloadRequired` callbacks, which
|
||||
* the app itself does not subscribe to yet.
|
||||
*
|
||||
* The preview server of this suite is not used; each test uses absolute URLs.
|
||||
*/
|
||||
|
||||
type Probe = typeof globalThis & {
|
||||
__caServiceWorkerTest?: {
|
||||
host: { requestActivation(): Promise<unknown> };
|
||||
events: string[];
|
||||
};
|
||||
};
|
||||
|
||||
let builds: ServiceWorkerBuilds | undefined;
|
||||
|
||||
// B changes one route chunk on purpose. Route chunks used to differ only
|
||||
// because they embedded the build ID; since 09-02 they do not, so two builds
|
||||
// of the same source emit the same route chunks. A dynamically imported
|
||||
// module keeps all its exports, so the extra export survives the bundler.
|
||||
const CHANGED_ROUTE_SOURCE =
|
||||
"src/presentation/pages/not-found-page.tsx";
|
||||
|
||||
test.beforeAll(async () => {
|
||||
test.setTimeout(180_000);
|
||||
builds = await prepareServiceWorkerBuilds({
|
||||
beforeBuild: async (name, root) => {
|
||||
if (name !== "b") return;
|
||||
await appendFile(
|
||||
path.join(root, CHANGED_ROUTE_SOURCE),
|
||||
'\nexport const serviceWorkerE2eBuild = "b";\n',
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await removeServiceWorkerBuilds(builds);
|
||||
});
|
||||
|
||||
function requireBuilds(): ServiceWorkerBuilds {
|
||||
if (!builds) throw new Error("Service Worker builds were not prepared.");
|
||||
return builds;
|
||||
}
|
||||
|
||||
async function waitForEvent(page: Page, prefix: string): Promise<string> {
|
||||
await page.waitForFunction(
|
||||
(expected) =>
|
||||
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
|
||||
event.startsWith(expected),
|
||||
) === true,
|
||||
prefix,
|
||||
{ timeout: 60_000 },
|
||||
);
|
||||
const events = await page.evaluate(() => [
|
||||
...((globalThis as Probe).__caServiceWorkerTest?.events ?? []),
|
||||
]);
|
||||
return events.find((event) => event.startsWith(prefix))!;
|
||||
}
|
||||
|
||||
async function startOutcome(page: Page): Promise<unknown> {
|
||||
return JSON.parse((await waitForEvent(page, "start:")).slice("start:".length));
|
||||
}
|
||||
|
||||
async function hashedAssets(dist: string): Promise<string[]> {
|
||||
return (await readdir(path.join(dist, "assets")))
|
||||
.map((file) => `/assets/${file}`)
|
||||
.sort();
|
||||
}
|
||||
|
||||
const headerCases = [
|
||||
{
|
||||
name: "Content-Type: application/javascript",
|
||||
headers: { javascriptContentType: "application/javascript", gzip: false },
|
||||
},
|
||||
{
|
||||
name: "Content-Encoding: gzip with the compressed Content-Length",
|
||||
headers: { javascriptContentType: "text/javascript", gzip: true },
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const { name, headers } of headerCases) {
|
||||
test(`installs the static asset set served with ${name}`, async ({ page }) => {
|
||||
const { dist } = requireBuilds();
|
||||
const server = await startBuildServer(dist, headers);
|
||||
try {
|
||||
await page.goto(`${server.origin}/`);
|
||||
// A failed install (CONTENT_TYPE_INVALID, BYTES_MISMATCH, ...) ends as
|
||||
// FAILED/INSTALL_FAILED; a first install that worked asks for a reload.
|
||||
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
|
||||
const cached = await page.evaluate(async () => {
|
||||
const names = (await caches.keys()).filter((cacheName) =>
|
||||
cacheName.startsWith("ca-static-v1-"),
|
||||
);
|
||||
const cache = await caches.open(names[0] ?? "missing");
|
||||
const paths = (await cache.keys())
|
||||
.map((request) => new URL(request.url))
|
||||
.filter((url) => url.origin === location.origin)
|
||||
.map((url) => url.pathname);
|
||||
return { names, paths };
|
||||
});
|
||||
expect(cached.names).toHaveLength(1);
|
||||
expect(cached.paths.sort()).toEqual(await hashedAssets(dist.a));
|
||||
|
||||
// The server really sent the headers under test.
|
||||
const assets = server.served.filter((response) =>
|
||||
response.path.startsWith("/assets/"),
|
||||
);
|
||||
expect(assets.length).toBeGreaterThan(0);
|
||||
if (headers.gzip) {
|
||||
expect(assets.every((response) => response.contentEncoding === "gzip"))
|
||||
.toBe(true);
|
||||
expect(
|
||||
assets.some(
|
||||
(response) => response.contentLength < response.decodedLength,
|
||||
),
|
||||
).toBe(true);
|
||||
} else {
|
||||
expect(
|
||||
assets
|
||||
.filter((response) => response.path.endsWith(".js"))
|
||||
.every(
|
||||
(response) => response.contentType === "application/javascript",
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type BuildServer = Awaited<ReturnType<typeof startBuildServer>>;
|
||||
|
||||
// Playwright's Firefox never lets a worker control a page: even a trivial
|
||||
// classic worker leaves `navigator.serviceWorker.controller` null after a new
|
||||
// navigation (checked by hand with Playwright 1.62). With no controlled
|
||||
// client, B skips `waiting` and activates by itself (`requestActivation()` then
|
||||
// returns NO_WAITING_WORKER), and the fetch handler is never reached. The
|
||||
// update tests therefore run where a page can be controlled. Not a product
|
||||
// defect.
|
||||
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
|
||||
const NO_CONTROLLED_PAGES =
|
||||
"Playwright Firefox pages are never controlled by a service worker.";
|
||||
|
||||
/**
|
||||
* Loads build A twice (first install, then a normal navigation), switches the
|
||||
* server to B, runs the update check and activates B through the app host.
|
||||
* Returns whether the second load of A was controlled by the worker.
|
||||
*/
|
||||
async function updateFromAToB(
|
||||
page: Page,
|
||||
server: BuildServer,
|
||||
): Promise<{ secondLoad: unknown; controlled: boolean }> {
|
||||
await page.goto(`${server.origin}/`);
|
||||
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
|
||||
await page.evaluate(async () => {
|
||||
await navigator.serviceWorker.ready;
|
||||
});
|
||||
// A normal navigation. (`page.reload()` would not change anything here.)
|
||||
await page.goto(`${server.origin}/`);
|
||||
const secondLoad = await startOutcome(page);
|
||||
const controlled = await page.evaluate(
|
||||
() => navigator.serviceWorker.controller !== null,
|
||||
);
|
||||
|
||||
server.serve("b");
|
||||
await page.evaluate(async () => {
|
||||
await (await navigator.serviceWorker.getRegistration())?.update();
|
||||
});
|
||||
await waitForEvent(page, "update-waiting");
|
||||
const activation = await page.evaluate(() =>
|
||||
(globalThis as Probe).__caServiceWorkerTest!.host.requestActivation(),
|
||||
);
|
||||
expect(activation).toEqual({ kind: "ACTIVATED_RELOAD_REQUIRED" });
|
||||
await waitForEvent(page, "reload-required");
|
||||
return { secondLoad, controlled };
|
||||
}
|
||||
|
||||
test("announces update-waiting and reload-required through the host when build B replaces A", async ({
|
||||
page,
|
||||
browserName,
|
||||
}) => {
|
||||
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
|
||||
const server = await startBuildServer(requireBuilds().dist);
|
||||
try {
|
||||
await updateFromAToB(page, server);
|
||||
const registration = await page.evaluate(async () => {
|
||||
const current = await navigator.serviceWorker.getRegistration();
|
||||
return {
|
||||
active: current?.active?.state ?? null,
|
||||
waiting: current?.waiting ?? null,
|
||||
};
|
||||
});
|
||||
expect(registration).toEqual({ active: "activated", waiting: null });
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("serves A's removed chunk from the previous cache once B controls the page", async ({
|
||||
page,
|
||||
browserName,
|
||||
}) => {
|
||||
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
|
||||
const { dist } = requireBuilds();
|
||||
const routeChunks = Object.values(
|
||||
(
|
||||
JSON.parse(
|
||||
await readFile(path.join(dist.a, "release-manifest.json"), "utf8"),
|
||||
) as { routeChunks: Record<string, string> }
|
||||
).routeChunks,
|
||||
);
|
||||
const inB = new Set(await hashedAssets(dist.b));
|
||||
const removedChunk = routeChunks
|
||||
.map((chunk) => `/${chunk}`)
|
||||
.find((chunk) => !inB.has(chunk));
|
||||
if (!removedChunk) throw new Error("Build B kept every route chunk of A.");
|
||||
|
||||
const server = await startBuildServer(dist);
|
||||
try {
|
||||
const { secondLoad, controlled } = await updateFromAToB(page, server);
|
||||
expect(secondLoad).toEqual({ kind: "ACTIVE", buildId: "sw-e2e-a" });
|
||||
expect(controlled).toBe(true);
|
||||
|
||||
// B's worker now controls the page. The chunk is not in B's manifest and
|
||||
// not on the server any more, so only A's retained cache can answer.
|
||||
const fromWorker = await page.evaluate(async (url) => {
|
||||
const response = await fetch(url);
|
||||
return { status: response.status, body: await response.text() };
|
||||
}, removedChunk);
|
||||
expect(fromWorker).toEqual({
|
||||
status: 200,
|
||||
body: await readFile(path.join(dist.a, removedChunk), "utf8"),
|
||||
});
|
||||
expect((await page.request.get(`${server.origin}${removedChunk}`)).status())
|
||||
.toBe(404);
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
|
||||
// `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default
|
||||
// `bundle` config loader); this pins that both builds emitted the worker.
|
||||
test("builds the ACTIVE worker with the repo's unmodified build script", async () => {
|
||||
const { dist } = requireBuilds();
|
||||
for (const root of [dist.a, dist.b]) {
|
||||
expect(await readdir(root)).toContain("service-worker.js");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { cp, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
|
||||
|
||||
/**
|
||||
* Real production builds of an edited temp copy of the repository, in the
|
||||
* template's default configuration (`serviceWorker: null`). `edit` changes the
|
||||
* copy right before that build runs, and edits persist into later builds. The
|
||||
* working tree and its `dist` (served by the e2e preview server) are never
|
||||
* touched. Serve the result with `startBuildServer` from
|
||||
* `service-worker-builds.ts`.
|
||||
*/
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, "../../..");
|
||||
const skipped = new Set([
|
||||
"node_modules",
|
||||
".git",
|
||||
".claude",
|
||||
".generated",
|
||||
".tmp",
|
||||
"dist",
|
||||
"artifacts",
|
||||
"graphify-out",
|
||||
]);
|
||||
|
||||
export type FixtureBuild<Name extends string> = Readonly<{
|
||||
name: Name;
|
||||
edit?: (root: string) => Promise<void>;
|
||||
}>;
|
||||
|
||||
export type FixtureBuilds<Name extends string> = Readonly<{
|
||||
root: string;
|
||||
dist: Readonly<Record<Name, string>>;
|
||||
}>;
|
||||
|
||||
/** Replaces the one occurrence of `search` in `file` of the copy. */
|
||||
export async function editOnce(
|
||||
file: string,
|
||||
search: string,
|
||||
replacement: string,
|
||||
): Promise<void> {
|
||||
const source = await readFile(file, "utf8");
|
||||
if (source.split(search).length !== 2) {
|
||||
throw new Error(`Expected exactly one "${search}" in ${file}.`);
|
||||
}
|
||||
await writeFile(file, source.replace(search, replacement));
|
||||
}
|
||||
|
||||
function run(cwd: string, script: string, buildId: string): void {
|
||||
const result = spawnSync("node", [script], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, VITE_BUILD_ID: buildId, RELEASE_ID: buildId },
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
`${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareFixtureBuilds<Name extends string>(
|
||||
prefix: string,
|
||||
builds: readonly FixtureBuild<Name>[],
|
||||
): Promise<FixtureBuilds<Name>> {
|
||||
const root = await mkdtemp(path.join(tmpdir(), `${prefix}-`));
|
||||
try {
|
||||
await cp(repoRoot, root, {
|
||||
recursive: true,
|
||||
filter: (source) =>
|
||||
!skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!),
|
||||
});
|
||||
await linkFixtureNodeModules(root, repoRoot);
|
||||
const dist = {} as Record<Name, string>;
|
||||
for (const build of builds) {
|
||||
await build.edit?.(root);
|
||||
const buildId = `${prefix}-${build.name}`;
|
||||
run(root, "scripts/generate-product-feature-index.ts", buildId);
|
||||
run(root, "scripts/build-frontend.ts", buildId);
|
||||
dist[build.name] = path.join(root, `dist-${build.name}`);
|
||||
await rename(path.join(root, "dist"), dist[build.name]);
|
||||
}
|
||||
return { root, dist };
|
||||
} catch (error) {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeFixtureBuilds(
|
||||
builds: Readonly<{ root: string }> | undefined,
|
||||
): Promise<void> {
|
||||
if (builds) await rm(builds.root, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
cp,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rename,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { gzipSync } from "node:zlib";
|
||||
|
||||
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
|
||||
|
||||
/**
|
||||
* R3-6 test helper: two real production builds with the Service Worker on,
|
||||
* and a static server that can switch which one it serves.
|
||||
*
|
||||
* The template ships with `serviceWorker: null`. The supported way to turn the
|
||||
* worker on is the static capability selection in
|
||||
* `src/features/installed-runtime-capabilities.ts` (`mode: "ACTIVE"` with the
|
||||
* `PWA_STATIC_ASSETS` handler); `scripts/build-frontend.ts` then runs the
|
||||
* two-pass worker build. Runtime Config can only disable it. So the helper
|
||||
* copies the repo to a temp dir, edits the selection there, and runs the
|
||||
* repo's own build scripts twice with different `VITE_BUILD_ID`s. The working
|
||||
* tree and its `dist` (served by the e2e preview server) are never touched.
|
||||
*
|
||||
* The app composes the worker host but nothing subscribes to it yet, and it is
|
||||
* not reachable from outside. The copy therefore also wraps
|
||||
* `createServiceWorkerRuntimeHost` so the page records the host's own
|
||||
* `onUpdateWaiting` / `onReloadRequired` callbacks and `start()` outcome on
|
||||
* `globalThis.__caServiceWorkerTest`. Only the temp copy is edited.
|
||||
*/
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, "../../..");
|
||||
const skipped = new Set([
|
||||
"node_modules",
|
||||
".git",
|
||||
".claude",
|
||||
".generated",
|
||||
"dist",
|
||||
"artifacts",
|
||||
"graphify-out",
|
||||
]);
|
||||
|
||||
export type BuildName = "a" | "b";
|
||||
export type ServiceWorkerBuilds = Readonly<{
|
||||
root: string;
|
||||
dist: Readonly<Record<BuildName, string>>;
|
||||
}>;
|
||||
|
||||
export const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
|
||||
mode: "ACTIVE",
|
||||
scriptPath: "service-worker.js",
|
||||
handlers: ["PWA_STATIC_ASSETS"],
|
||||
};`;
|
||||
|
||||
const HOST_PROBE = `
|
||||
export function createServiceWorkerRuntimeHost(
|
||||
input: ServiceWorkerHostInput,
|
||||
): ServiceWorkerRuntimeHost | null {
|
||||
const host = createServiceWorkerRuntimeHostUnobserved(input);
|
||||
if (!host) return host;
|
||||
const events: string[] = [];
|
||||
host.onUpdateWaiting(() => events.push("update-waiting"));
|
||||
host.onReloadRequired(() => events.push("reload-required"));
|
||||
const observed: ServiceWorkerRuntimeHost = Object.freeze({
|
||||
...host,
|
||||
start: async () => {
|
||||
const outcome = await host.start();
|
||||
events.push("start:" + JSON.stringify(outcome));
|
||||
return outcome;
|
||||
},
|
||||
});
|
||||
Object.assign(globalThis, { __caServiceWorkerTest: { host: observed, events } });
|
||||
return observed;
|
||||
}
|
||||
`;
|
||||
|
||||
export async function replaceOnce(
|
||||
file: string,
|
||||
search: string,
|
||||
replacement: string,
|
||||
): Promise<void> {
|
||||
const source = await readFile(file, "utf8");
|
||||
if (source.split(search).length !== 2) {
|
||||
throw new Error(`Expected exactly one "${search}" in ${file}.`);
|
||||
}
|
||||
await writeFile(file, source.replace(search, replacement));
|
||||
}
|
||||
|
||||
function run(cwd: string, script: string, buildId: string): void {
|
||||
const result = spawnSync("node", [script], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, VITE_BUILD_ID: buildId, RELEASE_ID: buildId },
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
`${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `beforeBuild` edits the temp copy right before build `name` (06-03: a
|
||||
* broken worker A, then a `REMOVE_REGISTRATION` release B). Edits persist
|
||||
* into the later build.
|
||||
*/
|
||||
export async function prepareServiceWorkerBuilds(
|
||||
options: Readonly<{
|
||||
beforeBuild?: (name: BuildName, root: string) => Promise<void>;
|
||||
}> = {},
|
||||
): Promise<ServiceWorkerBuilds> {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "ca-sw-builds-"));
|
||||
await cp(repoRoot, root, {
|
||||
recursive: true,
|
||||
filter: (source) =>
|
||||
!skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!),
|
||||
});
|
||||
await linkFixtureNodeModules(root, repoRoot);
|
||||
await replaceOnce(
|
||||
path.join(root, "src/features/installed-runtime-capabilities.ts"),
|
||||
"const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null;",
|
||||
ACTIVE_SELECTION,
|
||||
);
|
||||
const hostFile = path.join(root, "src/bootstrap/register-service-worker.ts");
|
||||
await replaceOnce(
|
||||
hostFile,
|
||||
"export function createServiceWorkerRuntimeHost(",
|
||||
"function createServiceWorkerRuntimeHostUnobserved(",
|
||||
);
|
||||
await writeFile(hostFile, (await readFile(hostFile, "utf8")) + HOST_PROBE);
|
||||
|
||||
const dist = { a: path.join(root, "dist-a"), b: path.join(root, "dist-b") };
|
||||
for (const name of ["a", "b"] as const) {
|
||||
await options.beforeBuild?.(name, root);
|
||||
run(root, "scripts/generate-product-feature-index.ts", `sw-e2e-${name}`);
|
||||
run(root, "scripts/build-frontend.ts", `sw-e2e-${name}`);
|
||||
await rename(path.join(root, "dist"), dist[name]);
|
||||
}
|
||||
return { root, dist };
|
||||
}
|
||||
|
||||
export async function removeServiceWorkerBuilds(
|
||||
builds: ServiceWorkerBuilds | undefined,
|
||||
): Promise<void> {
|
||||
if (builds) await rm(builds.root, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
export type AssetHeaders = Readonly<{
|
||||
/** Sent for every `.js` file, the worker script included. */
|
||||
javascriptContentType: string;
|
||||
/** gzip every `/assets/*` body; Content-Length is the compressed size. */
|
||||
gzip: boolean;
|
||||
}>;
|
||||
|
||||
export type ServedResponse = Readonly<{
|
||||
path: string;
|
||||
contentType: string;
|
||||
contentEncoding: string | null;
|
||||
contentLength: number;
|
||||
decodedLength: number;
|
||||
}>;
|
||||
|
||||
const CONTENT_TYPES: Readonly<Record<string, string>> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".css": "text/css",
|
||||
".json": "application/json",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
".webp": "image/webp",
|
||||
".woff2": "font/woff2",
|
||||
};
|
||||
|
||||
/**
|
||||
* Serves one dist directory at a time from an ephemeral 127.0.0.1 port, so
|
||||
* every test gets its own origin (and its own Service Worker registration).
|
||||
* Paths without an extension get `index.html`; a missing file is a plain 404,
|
||||
* never the SPA fallback, so a chunk that the served build lacks really 404s.
|
||||
*/
|
||||
export async function startBuildServer(
|
||||
dist: Readonly<Record<BuildName, string>>,
|
||||
headers: AssetHeaders = {
|
||||
javascriptContentType: "text/javascript",
|
||||
gzip: false,
|
||||
},
|
||||
) {
|
||||
let current: BuildName = "a";
|
||||
const served: ServedResponse[] = [];
|
||||
const server: Server = createServer((request, response) => {
|
||||
void (async () => {
|
||||
const pathname = decodeURIComponent(
|
||||
new URL(request.url ?? "/", "http://127.0.0.1").pathname,
|
||||
);
|
||||
const root = dist[current];
|
||||
const file = path.extname(pathname)
|
||||
? path.join(root, path.normalize(pathname))
|
||||
: path.join(root, "index.html");
|
||||
let body: Buffer;
|
||||
try {
|
||||
if (!file.startsWith(root + path.sep)) throw new Error("outside root");
|
||||
body = await readFile(file);
|
||||
} catch {
|
||||
response.writeHead(404, { "cache-control": "no-store" }).end();
|
||||
return;
|
||||
}
|
||||
const extension = path.extname(file);
|
||||
const contentType =
|
||||
extension === ".js"
|
||||
? headers.javascriptContentType
|
||||
: (CONTENT_TYPES[extension] ?? "application/octet-stream");
|
||||
const encoded = headers.gzip && pathname.startsWith("/assets/");
|
||||
const payload = encoded ? gzipSync(body) : body;
|
||||
served.push({
|
||||
path: pathname,
|
||||
contentType,
|
||||
contentEncoding: encoded ? "gzip" : null,
|
||||
contentLength: payload.byteLength,
|
||||
decodedLength: body.byteLength,
|
||||
});
|
||||
response
|
||||
.writeHead(200, {
|
||||
"content-type": contentType,
|
||||
"content-length": String(payload.byteLength),
|
||||
"cache-control": "no-cache",
|
||||
...(encoded
|
||||
? { "content-encoding": "gzip", vary: "Accept-Encoding" }
|
||||
: {}),
|
||||
})
|
||||
.end(request.method === "HEAD" ? undefined : payload);
|
||||
})();
|
||||
});
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", () => resolve()),
|
||||
);
|
||||
const { port } = server.address() as AddressInfo;
|
||||
return {
|
||||
origin: `http://127.0.0.1:${port}`,
|
||||
served,
|
||||
serve(name: BuildName) {
|
||||
current = name;
|
||||
},
|
||||
async close() {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user