문제: 빌드는 `dist`, `.generated/frontend-runtime`, `artifacts/release`· `artifacts/quality`에 고정으로 쓰고, 다섯 Playwright 설정은 결과·report· JUnit을 `artifacts/tests/<이름>/`에 고정으로 쓴다. 한 checkout에서 두 번째 e2e 실행이 시작하면 빌드 1단계가 첫 실행의 preview가 서빙 중인 `dist`를 지우고, Playwright가 `outputDir`을 비워 첫 실행의 trace를 지운다. 증거 파일도 늦게 끝난 쪽 것으로 섞인다(1105/12-04). 고른 방법: 변수 두 개로 나눈다(`scripts/lib/run-isolation.ts`). - `TEST_RUN_ID`: Playwright 설정이 읽는다. 값이 있으면 그 실행의 결과· report·JUnit과 서빙할 빌드를 `.tmp/runs/<id>/` 아래 같은 상대 경로에 둔다. 없으면 지금 경로 그대로라 게이트, CI upload, 증거 검사가 읽는 곳이 바뀌지 않는다. - `RUN_OUTPUT_ROOT`: 설정이 web server에만 넘긴다. 빌드 단계 전부 (`build-frontend`, contract set, runtime config, SW asset 목록, SW 빌드, build manifest)와 `vite.config.ts`가 읽어 `dist`·생성 모듈·증거·Vite 캐시를 그 아래에 쓴다. preview는 `--outDir`로 같은 `dist`를 서빙한다. 빌드 코드는 `TEST_RUN_ID`를 읽지 않는다. e2e worker가 저장소 복사본을 빌드할 때(fixture-builds, service-worker-builds) runner 환경을 물려받는데, 그 빌드는 복사본 자기 `dist`에 써야 하기 때문이다. 두 루트는 `.` 또는 `.tmp/` 아래만 받는다. git, Tailwind 소스 스캔(report 안 문자열이 CSS에 들어가지 않게), Vite watcher, vitest, 저장소 복사 helper가 모두 `.tmp`를 건너뛴다. service-worker-builds의 복사 제외 목록에 `.tmp`를 더했다(fixture-builds와 같아짐). build manifest의 경로는 빌드가 쓴 폴더 기준 상대 경로로 둔다. `vite.config.ts`가 새로 가져오는 `scripts/lib/run-isolation.ts`는 저장소 일부를 임시 루트에 복사해 빌드하는 두 목록(초기 JS 측정 `scripts/scale/measure-feature-shape-growth.ts`, `tests/unit/product-feature-selection-build.test.ts`)에도 더한다. Storybook은 run ID가 있으면 `build:storybook`의 두 단계를 다른 `-o`로 돌린다. 같은 단계인지는 단위 테스트가 package script와 대조한다. 버린 대안: 운영 증거 경로(54개 스크립트, `config/ci/gates.json`)까지 run ID로 옮기기. 게이트와 workflow upload가 고정 경로를 읽으므로 이번 범위 밖이다(아래 한계). 실행마다 저장소를 임시 폴더로 복사하기: 매번 수십 MB 복사와 node_modules 링크가 들고, 개발자가 보는 결과 위치가 사라진다. 위험·한계: 포트는 아직 고정이라 이 커밋만으로는 두 실행이 함께 돌지 못한다(다음 커밋). `ci:gate`와 증거 검사(`check:test-evidence`, `verify:browser-capability-evidence`)는 기본 경로만 읽는다. run ID를 준 채 게이트를 돌리면 증거가 기본 경로에 새로 생기지 않아 게이트가 "not freshly produced"로 실패한다(통과로 새지 않는다). Storybook 내부 캐시 (`node_modules/.cache`)는 여전히 공유한다. capability 설정 (`playwright.capabilities.config.ts`)은 test:browser-file-storage-removal이 capability와 함께 지운다. 설정 테스트는 그 파일이 있을 때만 그 설정을 읽고, 경로를 변수로 두어 타입 검사가 그 파일을 요구하지 않는다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/run-isolation.test.ts tests/unit/playwright-run-isolation.test.ts tests/unit/run-output-root-build.test.ts node scripts/run-vitest.ts run tests/unit/feature-shape-growth.test.ts tests/unit/product-feature-selection-build.test.ts corepack pnpm test:browser-file-storage-removal Refs: 1105/12-04
341 lines
12 KiB
TypeScript
341 lines
12 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
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 { pathToFileURL } from "node:url";
|
|
import { gzipSync } from "node:zlib";
|
|
|
|
import { SERVICE_WORKER_ASSETS_OUTPUT } from "../../../scripts/generate-service-worker-assets.ts";
|
|
import { localBuildEnvironment } from "../../../scripts/lib/build-environment.ts";
|
|
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
|
|
import type { StaticAssetManifestV1 } from "../../../src/contracts/service-worker.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 the product-owned
|
|
* `src/features/product-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.
|
|
*
|
|
* 0929/11-03. What the copy relies on, and where to change it when a product
|
|
* changes that code:
|
|
* 1. `src/features/product-capabilities.ts` has one
|
|
* `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = …;`.
|
|
* A selection that is already `ACTIVE` (a product that turned the worker
|
|
* on) is kept as it is; anything else becomes `ACTIVE_VALUE`.
|
|
* 2. `src/bootstrap/register-service-worker.ts` declares
|
|
* `export function createServiceWorkerRuntimeHost(` once (the probe).
|
|
* 3. The build writes its precache list to `SERVICE_WORKER_ASSETS_OUTPUT`.
|
|
* `precached` is read from there, so a product that precaches more than
|
|
* `dist/assets` still compares against what its worker installs.
|
|
* A broken premise fails `prepareServiceWorkerBuilds` with the file and the
|
|
* text it expected.
|
|
*/
|
|
|
|
const repoRoot = path.resolve(import.meta.dirname, "../../..");
|
|
// 1105/12-04. `.tmp` holds other runs' builds and results (.tmp/runs/<id>),
|
|
// which change while this copy is made; fixture-builds.ts skips it too.
|
|
const skipped = new Set([
|
|
"node_modules",
|
|
".git",
|
|
".claude",
|
|
".generated",
|
|
".tmp",
|
|
"dist",
|
|
"artifacts",
|
|
"graphify-out",
|
|
]);
|
|
|
|
export type BuildName = "a" | "b";
|
|
export type ServiceWorkerBuilds = Readonly<{
|
|
root: string;
|
|
dist: Readonly<Record<BuildName, string>>;
|
|
/** Sorted URLs of each build's generated precache list (premise 3). */
|
|
precached: Readonly<Record<BuildName, readonly string[]>>;
|
|
}>;
|
|
|
|
const SELECTION_FILE = "src/features/product-capabilities.ts";
|
|
const SELECTION_DECLARATION =
|
|
/(const SERVICE_WORKER: InstalledServiceWorkerSelection \| null = )([\s\S]*?);\n/gu;
|
|
|
|
export const ACTIVE_VALUE = `{
|
|
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));
|
|
}
|
|
|
|
/**
|
|
* Premise 1. Replaces the value of the one `SERVICE_WORKER` declaration in
|
|
* the temp copy with `next(current)`, whatever the value is now.
|
|
*/
|
|
export async function setServiceWorkerSelection(
|
|
root: string,
|
|
next: (current: string) => string,
|
|
): Promise<void> {
|
|
const file = path.join(root, SELECTION_FILE);
|
|
const source = await readFile(file, "utf8");
|
|
if ([...source.matchAll(SELECTION_DECLARATION)].length !== 1) {
|
|
throw new Error(
|
|
`Expected exactly one "const SERVICE_WORKER: InstalledServiceWorkerSelection | null = …;" in ${file} (premise 1 of tests/e2e/support/service-worker-builds.ts).`,
|
|
);
|
|
}
|
|
await writeFile(
|
|
file,
|
|
source.replace(
|
|
SELECTION_DECLARATION,
|
|
(_declaration, head: string, current: string) =>
|
|
`${head}${next(current)};\n`,
|
|
),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 0929/06-04, 0929/11-03. Turns the copy's worker on whatever the selection is
|
|
* now, but keeps a selection a product already set to `ACTIVE`, so the specs
|
|
* exercise that product's own handlers rather than the template's.
|
|
*/
|
|
export async function turnOnServiceWorker(root: string): Promise<void> {
|
|
await setServiceWorkerSelection(root, (current) =>
|
|
/\bmode:\s*"ACTIVE"/u.test(current) ? current : ACTIVE_VALUE,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Premise 3. The build wrote this list; the worker installs exactly it. A
|
|
* build without an `ACTIVE` worker (06-03's `REMOVE_REGISTRATION` release)
|
|
* writes none and precaches nothing: `scripts/build-frontend.ts` deletes the
|
|
* directory before every build, so a missing file is that build's answer.
|
|
*/
|
|
async function precachedUrls(root: string, name: BuildName): Promise<string[]> {
|
|
const file = path.join(root, SERVICE_WORKER_ASSETS_OUTPUT);
|
|
if (!existsSync(file)) return [];
|
|
const generated = pathToFileURL(file);
|
|
// Both builds write the same file; the query keeps B from reusing A's module.
|
|
generated.search = `build=${name}`;
|
|
const { SERVICE_WORKER_ASSETS } = (await import(generated.href)) as {
|
|
SERVICE_WORKER_ASSETS: StaticAssetManifestV1;
|
|
};
|
|
return SERVICE_WORKER_ASSETS.assets.map((asset) => asset.url).sort();
|
|
}
|
|
|
|
function run(cwd: string, script: string, buildId: string): void {
|
|
const result = spawnSync("node", [script], {
|
|
cwd,
|
|
encoding: "utf8",
|
|
// 1103/11-08. A local build, not the CI job's release build.
|
|
env: { ...localBuildEnvironment(), 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-"));
|
|
try {
|
|
await cp(repoRoot, root, {
|
|
recursive: true,
|
|
filter: (source) =>
|
|
!skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!),
|
|
});
|
|
await linkFixtureNodeModules(root, repoRoot);
|
|
await turnOnServiceWorker(root);
|
|
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") };
|
|
const precached: Record<BuildName, readonly string[]> = { a: [], 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]);
|
|
precached[name] = await precachedUrls(root, name);
|
|
}
|
|
return { root, dist, precached };
|
|
} catch (error) {
|
|
// The spec never receives `root` from a failed setup, so afterAll cannot
|
|
// remove it.
|
|
await rm(root, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
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()));
|
|
},
|
|
};
|
|
}
|