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:
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 12-11. One violation line names the rule, the edge and the import specifier
|
||||
* as written, then the rule's `comment` from .dependency-cruiser.json: why the
|
||||
* edge is forbidden and where the code should go instead.
|
||||
*/
|
||||
export function formatArchitectureViolation(
|
||||
violation: Readonly<{ rule: string; source: string; target: string; cycle?: readonly string[] }>,
|
||||
specifiers: readonly string[],
|
||||
comment: string | undefined,
|
||||
): string {
|
||||
const imports = specifiers.length > 0
|
||||
? ` (import ${specifiers.map((specifier) => JSON.stringify(specifier)).join(", ")})`
|
||||
: "";
|
||||
const cycle = violation.cycle ? ` (cycle group: ${violation.cycle.join(", ")})` : "";
|
||||
const why = comment ? ` why: ${comment}\n` : "";
|
||||
return `Architecture violation [${violation.rule}]: ${violation.source} -> ${violation.target}${imports}${cycle}\n${why}`;
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { constants } from "node:fs";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
readFile,
|
||||
readdir,
|
||||
|
||||
@@ -2,12 +2,15 @@ type ViteManifestEntry = Readonly<{
|
||||
file: string;
|
||||
isEntry?: boolean;
|
||||
imports?: readonly string[];
|
||||
dynamicImports?: readonly string[];
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Static imports of an entry are part of initial JavaScript. Every remaining
|
||||
* JavaScript output is governed by the lazy-chunk budget.
|
||||
*
|
||||
* Static imports of an entry are part of initial JavaScript, and so are the
|
||||
* chunks the entry itself imports dynamically: main.tsx only imports the
|
||||
* application graph that way so it can report a graph that fails to evaluate
|
||||
* (09-03). Every remaining JavaScript output is governed by the lazy-chunk
|
||||
* budget.
|
||||
*/
|
||||
export function classifyViteJavascript(
|
||||
manifest: Readonly<Record<string, ViteManifestEntry>>,
|
||||
@@ -31,6 +34,7 @@ export function classifyViteJavascript(
|
||||
}
|
||||
if (entry.file.endsWith(".js")) initialFiles.add(entry.file);
|
||||
pendingKeys.push(...(entry.imports ?? []));
|
||||
if (entry.isEntry) pendingKeys.push(...(entry.dynamicImports ?? []));
|
||||
}
|
||||
|
||||
const allJavaScript = new Set(
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { chmod, readdir, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* 13-02. dist is published as-is to a web server that may run as another OS
|
||||
* user, so every file in it must be readable by others. The validated JSON
|
||||
* writer creates files 0600 on purpose (evidence under artifacts/ stays
|
||||
* private); the build adds read bits to what it publishes instead of loosening
|
||||
* that writer.
|
||||
*/
|
||||
export async function makeDistFilesPublic(directory: string): Promise<void> {
|
||||
for (const entry of await readdir(directory, { recursive: true, withFileTypes: true })) {
|
||||
if (!entry.isFile()) continue;
|
||||
const file = path.join(entry.parentPath, entry.name);
|
||||
const { mode } = await stat(file);
|
||||
if ((mode & 0o004) === 0) await chmod(file, (mode & 0o7777) | 0o444);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import {
|
||||
PROMOTION_VERIFIER_ID,
|
||||
PROMOTION_VERIFIER_VERSION,
|
||||
PROVIDER_FUTURE_SKEW_MS,
|
||||
assertDistinctProviderTrust,
|
||||
evaluatePromotionEvidence,
|
||||
providerVerificationArtifactSchema,
|
||||
@@ -35,6 +36,29 @@ export type ExactPromotionExpectedContext = Readonly<{
|
||||
lockfileSha256?: string;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* 13-04. `current` checks provider evidence against the clock, as a new
|
||||
* promotion must. `archived` re-verifies a release promoted earlier (deploying
|
||||
* it later, or rolling back to it): signatures, digests and members are checked
|
||||
* the same way, but freshness is judged at the promotion's recorded
|
||||
* `verifiedAt`, which may not lie in the future. Promotion itself
|
||||
* (promotion-stager.ts) never passes `archived`.
|
||||
*/
|
||||
export type PromotionFreshness = "current" | "archived";
|
||||
|
||||
export function promotionEvidenceTime(
|
||||
freshness: PromotionFreshness,
|
||||
verifiedAt: string,
|
||||
now: number,
|
||||
): number {
|
||||
if (freshness === "current") return now;
|
||||
const verified = Date.parse(verifiedAt);
|
||||
if (!Number.isFinite(verified) || verified > now + PROVIDER_FUTURE_SKEW_MS) {
|
||||
throw new Error("archived promotion verifiedAt is in the future or invalid");
|
||||
}
|
||||
return verified;
|
||||
}
|
||||
|
||||
export async function verifyExactPromotionBundle(
|
||||
files: ExactPromotionBundle,
|
||||
options: Readonly<{
|
||||
@@ -42,6 +66,7 @@ export async function verifyExactPromotionBundle(
|
||||
provenanceTrust: ProviderTrust;
|
||||
expected: ExactPromotionExpectedContext;
|
||||
nowEpochMs?: () => number;
|
||||
freshness?: PromotionFreshness;
|
||||
}>,
|
||||
): Promise<Readonly<{ status: "PASS" }>> {
|
||||
assertDistinctProviderTrust(options);
|
||||
@@ -286,7 +311,12 @@ export async function verifyExactPromotionBundle(
|
||||
provenanceAttestation: provenance,
|
||||
vulnerabilityTrust: options.vulnerabilityTrust,
|
||||
provenanceTrust: options.provenanceTrust,
|
||||
nowEpochMs: options.nowEpochMs,
|
||||
nowEpochMs: () =>
|
||||
promotionEvidenceTime(
|
||||
options.freshness ?? "current",
|
||||
promotion.verifiedAt,
|
||||
(options.nowEpochMs ?? Date.now)(),
|
||||
),
|
||||
});
|
||||
if (
|
||||
reevaluated.status !== "PASS" ||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { lstat, mkdir, readdir, symlink } from "node:fs/promises";
|
||||
import { copyFile, mkdir, readdir, readFile, stat, symlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
@@ -15,7 +15,32 @@ import path from "node:path";
|
||||
* is an individual symlink. Package resolution is unchanged, but a recursive
|
||||
* delete unlinks the fixture's own symlinks instead of walking through one link
|
||||
* into the shared tree.
|
||||
*
|
||||
* Top-level files are pnpm's install state (`.modules.yaml`,
|
||||
* `.pnpm-workspace-state-v1.json`, ...). pnpm rewrites them in place when it
|
||||
* runs inside the fixture, so they are copied: a link would carry the fixture's
|
||||
* path into the repository's own state and make its next pnpm command
|
||||
* re-verify the install.
|
||||
*
|
||||
* The copied workspace state still names the repository as its validated
|
||||
* project, so pnpm in the fixture would re-verify and start an install through
|
||||
* the linked directories. It is rewritten to name the fixture root instead:
|
||||
* the packages are the repository's own, already validated.
|
||||
*/
|
||||
/**
|
||||
* F-4. The environment for every `pnpm` a linked fixture runs. pnpm verifies
|
||||
* the install before a script and, when the fixture's copied state disagrees
|
||||
* with its own settings (for example `CI=true` against an install made
|
||||
* without it), installs. `.pnpm` and `.bin` are links into the repository's
|
||||
* node_modules, so that install rewrote the shared `.pnpm/lock.yaml` and bin
|
||||
* shims. A fixture started through `pnpm <script>` inherits this setting from
|
||||
* pnpm; one started directly (`node scripts/run-vitest.ts run <file>`) did not.
|
||||
* The fixture uses the repository's packages as they are; it never installs.
|
||||
*/
|
||||
export const FIXTURE_PNPM_ENVIRONMENT = Object.freeze({
|
||||
pnpm_config_verify_deps_before_run: "false",
|
||||
});
|
||||
|
||||
export async function linkFixtureNodeModules(
|
||||
fixtureRoot: string,
|
||||
sourceRoot: string = process.cwd(),
|
||||
@@ -25,7 +50,29 @@ export async function linkFixtureNodeModules(
|
||||
await mkdir(target, { recursive: true });
|
||||
for (const entry of await readdir(source)) {
|
||||
const from = path.join(source, entry);
|
||||
const stats = await lstat(from);
|
||||
await symlink(from, path.join(target, entry), stats.isDirectory() ? "dir" : "file");
|
||||
const to = path.join(target, entry);
|
||||
if ((await stat(from)).isDirectory()) await symlink(from, to, "dir");
|
||||
else await copyFile(from, to);
|
||||
}
|
||||
await retargetWorkspaceState(
|
||||
path.join(target, ".pnpm-workspace-state-v1.json"),
|
||||
fixtureRoot,
|
||||
);
|
||||
}
|
||||
|
||||
async function retargetWorkspaceState(
|
||||
statePath: string,
|
||||
fixtureRoot: string,
|
||||
): Promise<void> {
|
||||
let state: { projects?: Record<string, unknown>; lastValidatedTimestamp?: number };
|
||||
try {
|
||||
state = JSON.parse(await readFile(statePath, "utf8"));
|
||||
} catch {
|
||||
return; // no state file, or not pnpm's JSON: nothing to retarget
|
||||
}
|
||||
const [project] = Object.values(state.projects ?? {});
|
||||
if (project === undefined) return;
|
||||
state.projects = { [fixtureRoot]: project };
|
||||
state.lastValidatedTimestamp = Date.now();
|
||||
await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,62 @@
|
||||
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
|
||||
|
||||
const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
|
||||
|
||||
export type HostingMode = "live" | "invalid-live" | "fixture";
|
||||
export type HostingVerdict = "PASS" | "FAIL" | "UNVERIFIED";
|
||||
|
||||
/**
|
||||
* 13-05 (D-14). The fixture compares the declared headers with a copy of
|
||||
* themselves, so it can only find a contradiction, never prove hosting. Only a
|
||||
* live probe of the deployed release can PASS.
|
||||
*/
|
||||
export function hostingVerdict(mode: HostingMode, passed: boolean): HostingVerdict {
|
||||
if (!passed) return "FAIL";
|
||||
return mode === "live" ? "PASS" : "UNVERIFIED";
|
||||
}
|
||||
|
||||
/**
|
||||
* 13-05. The live probe requests the entry script the served index.html names,
|
||||
* so it checks the release that is deployed rather than the first asset of a
|
||||
* local build, which the deployed release may not contain.
|
||||
*/
|
||||
export function servedEntryScript(indexHtml: string): string | null {
|
||||
for (const tag of indexHtml.match(/<script\b[^>]*>/gu) ?? []) {
|
||||
if (!/\btype=["']module["']/u.test(tag)) continue;
|
||||
const source = /\bsrc=["']([^"']+\.js)["']/u.exec(tag)?.[1];
|
||||
if (source) return source;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const PUBLIC_SERVICE_WORKER = /(?:^|\/)(?:service-worker|sw)(?:[.-][^/]*)?\.js$/i;
|
||||
|
||||
/**
|
||||
* A built `dist` may ship a worker script only when the static selection is
|
||||
* `ACTIVE` or `REMOVE_REGISTRATION` (the self-unregistering worker, 06-03), and
|
||||
* then only the selected script at the app root.
|
||||
*/
|
||||
export function checkPublicServiceWorkers(
|
||||
distFiles: readonly string[],
|
||||
selection: InstalledServiceWorkerSelection | null,
|
||||
) {
|
||||
const found = distFiles.filter((file) => PUBLIC_SERVICE_WORKER.test(file));
|
||||
const allowed: string[] =
|
||||
selection?.mode === "ACTIVE" || selection?.mode === "REMOVE_REGISTRATION"
|
||||
? [selection.scriptPath]
|
||||
: [];
|
||||
const passed =
|
||||
found.length === allowed.length &&
|
||||
found.every((file) => allowed.includes(file));
|
||||
return {
|
||||
surface: "serviceWorker",
|
||||
header: "enabled",
|
||||
expected: allowed.length > 0,
|
||||
observed: found.length > 0,
|
||||
passed,
|
||||
...(passed ? {} : { reason: `dist worker scripts: ${found.join(", ") || "none"}` }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A release gate must not promote a local preview server as live hosting
|
||||
* evidence.
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* 11-07. The pieces of the lab performance gate (`scripts/test-performance.ts`)
|
||||
* that decide what is measured and whether the numbers can be trusted.
|
||||
*/
|
||||
|
||||
export const DEFAULT_LAB_PORT = 4173;
|
||||
export const DEFAULT_LAB_RUNS = 5;
|
||||
|
||||
/**
|
||||
* `vite preview` arguments. Without `--strictPort` vite moved to the next free
|
||||
* port when the requested one was taken, and the gate measured whatever server
|
||||
* already listened there.
|
||||
*/
|
||||
export function previewArguments(port: number): readonly string[] {
|
||||
return [
|
||||
"pnpm",
|
||||
"preview",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
String(port),
|
||||
"--strictPort",
|
||||
];
|
||||
}
|
||||
|
||||
export type SampleSummary = Readonly<{
|
||||
median: number;
|
||||
min: number;
|
||||
max: number;
|
||||
samples: readonly number[];
|
||||
}>;
|
||||
|
||||
export function summarizeSamples(samples: readonly number[]): SampleSummary {
|
||||
if (samples.length === 0) throw new RangeError("no samples to summarize");
|
||||
const sorted = [...samples].sort((left, right) => left - right);
|
||||
const middle = Math.floor(sorted.length / 2);
|
||||
const median =
|
||||
sorted.length % 2 === 1
|
||||
? sorted[middle]!
|
||||
: (sorted[middle - 1]! + sorted[middle]!) / 2;
|
||||
return Object.freeze({
|
||||
median,
|
||||
min: sorted[0]!,
|
||||
max: sorted.at(-1)!,
|
||||
samples: Object.freeze([...samples]),
|
||||
});
|
||||
}
|
||||
|
||||
/** Fails when anything already answers where the preview server will listen. */
|
||||
export async function assertPortUnused(
|
||||
baseUrl: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<void> {
|
||||
let answered = false;
|
||||
try {
|
||||
await fetchImpl(baseUrl, { signal: AbortSignal.timeout(1_000) });
|
||||
answered = true;
|
||||
} catch {
|
||||
// Nothing is listening: the expected state.
|
||||
}
|
||||
if (answered) {
|
||||
throw new Error(
|
||||
`${baseUrl} already answers before the preview server starts; another server holds the port.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the release the server actually serves with the local build that
|
||||
* is being measured, so the numbers belong to that build.
|
||||
*/
|
||||
export async function assertServedRelease(
|
||||
baseUrl: string,
|
||||
expected: Readonly<{ buildId: string; releaseId: string }>,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<void> {
|
||||
const response = await fetchImpl(new URL("/release-manifest.json", baseUrl), {
|
||||
cache: "no-store",
|
||||
});
|
||||
const served = response.ok
|
||||
? ((await response.json()) as Partial<Record<"buildId" | "releaseId", unknown>>)
|
||||
: {};
|
||||
if (served.buildId !== expected.buildId || served.releaseId !== expected.releaseId) {
|
||||
throw new Error(
|
||||
`${baseUrl} serves build ${String(served.buildId)}/${String(served.releaseId)}, ` +
|
||||
`not the measured ${expected.buildId}/${expected.releaseId}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,18 @@
|
||||
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
|
||||
import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts";
|
||||
import { TECH_LOG_ROUTE_REGISTRY } from "../../src/features/tech-log/contracts/tech-log-route-contract.ts";
|
||||
|
||||
/**
|
||||
* Template sync (af3d8e6). The routes this product mounts: the platform's and
|
||||
* TechLog's, the same set `AppRouter` composes. Read from those registries
|
||||
* rather than the installed composition so the CI contract parser
|
||||
* (scripts/contracts/ci-gates.ts), which pins FE-GATE-028 to this scope, does
|
||||
* not depend on the generated feature index; `check:ci` has to stay the
|
||||
* template's canonical command.
|
||||
*/
|
||||
export const MANUAL_A11Y_ROUTE_IDS = Object.freeze(
|
||||
Object.values(ROUTE_REGISTRY).map((route) => route.routeId),
|
||||
Object.values({ ...PLATFORM_ROUTE_REGISTRY, ...TECH_LOG_ROUTE_REGISTRY }).map(
|
||||
(route) => route.routeId,
|
||||
),
|
||||
);
|
||||
|
||||
const REVIEW_FIELDS = Object.freeze([
|
||||
@@ -15,8 +26,20 @@ const REVIEW_FIELDS = Object.freeze([
|
||||
"Screen reader",
|
||||
]);
|
||||
|
||||
export function validateManualA11yEvidence(content: string) {
|
||||
const fields = Object.fromEntries(
|
||||
const IDENTITY_FIELDS = Object.freeze([
|
||||
"Status",
|
||||
"Route ID",
|
||||
"Release ID",
|
||||
"Reviewer",
|
||||
"Reviewed at",
|
||||
"Signature",
|
||||
"Attestation",
|
||||
]);
|
||||
|
||||
const NOT_APPLICABLE = /^not-applicable \(.+\)$/;
|
||||
|
||||
function parseRecordFields(content: string): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
content
|
||||
.split(/\r?\n/)
|
||||
.map((line) => /^([^:]+):\s*(.*)$/.exec(line))
|
||||
@@ -26,6 +49,37 @@ export function validateManualA11yEvidence(content: string) {
|
||||
match[2].trim(),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 08-06. The merge-stage check: the record for `routeId` keeps the template's
|
||||
* fields and vocabulary, whether or not a human has reviewed it yet. A record
|
||||
* that claims `reviewed` must also be complete. Returns the offending fields.
|
||||
*/
|
||||
export function validateManualA11yRecordFormat(content: string, routeId: string): string[] {
|
||||
const fields = parseRecordFields(content);
|
||||
const failures = [...IDENTITY_FIELDS, ...REVIEW_FIELDS].filter(
|
||||
(field) => !(field in fields),
|
||||
);
|
||||
if (fields.Status !== undefined && !["pending-manual-review", "reviewed"].includes(fields.Status)) {
|
||||
failures.push("Status");
|
||||
}
|
||||
if (fields["Route ID"] !== undefined && fields["Route ID"] !== routeId) failures.push("Route ID");
|
||||
if (fields.Attestation !== undefined && !["pending", "accepted"].includes(fields.Attestation)) {
|
||||
failures.push("Attestation");
|
||||
}
|
||||
for (const field of REVIEW_FIELDS) {
|
||||
const verdict = fields[field];
|
||||
if (verdict !== undefined && verdict !== "pass" && verdict !== "pending" && !NOT_APPLICABLE.test(verdict)) {
|
||||
failures.push(field);
|
||||
}
|
||||
}
|
||||
if (fields.Status === "reviewed") failures.push(...validateManualA11yEvidence(content).failures);
|
||||
return [...new Set(failures)];
|
||||
}
|
||||
|
||||
export function validateManualA11yEvidence(content: string) {
|
||||
const fields = parseRecordFields(content);
|
||||
const failures: string[] = [];
|
||||
if (fields.Status !== "reviewed") failures.push("Status");
|
||||
if (!fields["Route ID"]) failures.push("Route ID");
|
||||
@@ -44,7 +98,7 @@ export function validateManualA11yEvidence(content: string) {
|
||||
const result = fields[field];
|
||||
if (
|
||||
result !== "pass" &&
|
||||
!/^not-applicable \(.+\)$/.test(result ?? "")
|
||||
!NOT_APPLICABLE.test(result ?? "")
|
||||
) {
|
||||
failures.push(field);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
/**
|
||||
* Package-script graph for the CI contract (D-12, 12-10). Kept after checking
|
||||
* whether `--ignore-scripts` on the workflow install and `allowBuilds` in
|
||||
* pnpm-workspace.yaml already close the same risks. They do not:
|
||||
*
|
||||
* - Gate commands run installs themselves (`verify:lockfile`, removal
|
||||
* fixtures). `allowBuilds` limits dependency build scripts under pnpm only;
|
||||
* the root project's own install hooks and npm/yarn installs still run
|
||||
* unless the command says `--ignore-scripts`.
|
||||
* - A gate names a root package script. `--prefix`, `--filter`, `-C`, npm
|
||||
* pre/post hooks and `npm_config_*` scope variables can make that name run a
|
||||
* different manifest's script, which no install flag affects.
|
||||
* - `reachablePackageScripts` is also how the ungated-test check (12-04) finds
|
||||
* which Vitest paths a gate runs.
|
||||
*/
|
||||
type PackageManager = "pnpm" | "npm" | "yarn";
|
||||
|
||||
type ManagerParseResult = Readonly<{
|
||||
@@ -182,6 +197,22 @@ export function validatePackageScriptGraph(
|
||||
return [...new Set(failures)];
|
||||
}
|
||||
|
||||
/** Every package script reachable from the entries through manager calls. */
|
||||
export function reachablePackageScripts(
|
||||
scripts: Readonly<Record<string, string>>,
|
||||
entryScripts: readonly string[],
|
||||
): string[] {
|
||||
const visited = new Set<string>();
|
||||
const visit = (scriptName: string): void => {
|
||||
const command = scripts[scriptName];
|
||||
if (visited.has(scriptName) || command === undefined) return;
|
||||
visited.add(scriptName);
|
||||
for (const dependency of parseManagerCommands(command, scripts).dependencies) visit(dependency);
|
||||
};
|
||||
for (const entryScript of entryScripts) visit(entryScript);
|
||||
return [...visited];
|
||||
}
|
||||
|
||||
export function validateInstallScriptPolicy(
|
||||
scripts: Readonly<Record<string, string>>,
|
||||
entryScripts: readonly string[],
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
export type BundleMeasurements = Readonly<{
|
||||
initialJsGzipBytes: number;
|
||||
lazyChunks: readonly Readonly<{ path: string; gzipBytes: number }>[];
|
||||
}>;
|
||||
|
||||
export type BundleThresholds = Readonly<{
|
||||
initialJsGzipBytes: number;
|
||||
lazyChunkGzipBytes: number;
|
||||
}>;
|
||||
|
||||
export function evaluateBundleBudget(
|
||||
measurements: BundleMeasurements,
|
||||
thresholds: BundleThresholds,
|
||||
) {
|
||||
const initialPassed =
|
||||
measurements.initialJsGzipBytes <= thresholds.initialJsGzipBytes;
|
||||
const lazyResults = measurements.lazyChunks.map((chunk) => ({
|
||||
...chunk,
|
||||
threshold: thresholds.lazyChunkGzipBytes,
|
||||
passed: chunk.gzipBytes <= thresholds.lazyChunkGzipBytes,
|
||||
}));
|
||||
return Object.freeze({
|
||||
initialPassed,
|
||||
lazyResults: Object.freeze(lazyResults),
|
||||
passed: initialPassed && lazyResults.every((chunk) => chunk.passed),
|
||||
});
|
||||
}
|
||||
|
||||
export type LabMetrics = Readonly<{
|
||||
lcpMs: number;
|
||||
cls: number;
|
||||
namedInteractionMs: number;
|
||||
}>;
|
||||
|
||||
export function evaluateLabBudget(
|
||||
report: Readonly<{
|
||||
context?: Readonly<Record<string, unknown>>;
|
||||
metrics: LabMetrics;
|
||||
}>,
|
||||
thresholds: LabMetrics,
|
||||
) {
|
||||
const requiredContext = [
|
||||
"runner",
|
||||
"browser",
|
||||
"viewport",
|
||||
"network",
|
||||
"cpu",
|
||||
"cache",
|
||||
"build",
|
||||
];
|
||||
const missingContext = requiredContext.filter(
|
||||
(field) => report.context?.[field] === undefined,
|
||||
);
|
||||
const results = {
|
||||
lcp: report.metrics.lcpMs <= thresholds.lcpMs,
|
||||
cls: report.metrics.cls <= thresholds.cls,
|
||||
namedInteraction:
|
||||
report.metrics.namedInteractionMs <= thresholds.namedInteractionMs,
|
||||
};
|
||||
return Object.freeze({
|
||||
missingContext: Object.freeze(missingContext),
|
||||
results: Object.freeze(results),
|
||||
passed: missingContext.length === 0 && Object.values(results).every(Boolean),
|
||||
});
|
||||
}
|
||||
|
||||
export function percentile75(values: readonly number[]): number | null {
|
||||
if (values.length === 0) return null;
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
return sorted[Math.ceil(sorted.length * 0.75) - 1];
|
||||
}
|
||||
|
||||
export type FieldMetrics = Readonly<{
|
||||
p75LcpMs: number | null;
|
||||
p75Cls: number | null;
|
||||
p75InpMs: number | null;
|
||||
}>;
|
||||
|
||||
export type FieldThresholds = Readonly<{
|
||||
p75LcpMs: number;
|
||||
p75Cls: number;
|
||||
p75InpMs: number;
|
||||
minimumEligibleSamples: number | null;
|
||||
}>;
|
||||
|
||||
export type FieldBudgetResult = Readonly<{
|
||||
status: "PASS" | "FAIL_THRESHOLD" | "FAIL_UNVERIFIED";
|
||||
passed: boolean;
|
||||
}>;
|
||||
|
||||
export function evaluateFieldBudget(
|
||||
report: Readonly<{ metrics: FieldMetrics; eligibleSamples: number }>,
|
||||
thresholds: FieldThresholds,
|
||||
): FieldBudgetResult {
|
||||
if (
|
||||
thresholds.minimumEligibleSamples === null ||
|
||||
report.eligibleSamples < thresholds.minimumEligibleSamples ||
|
||||
Object.values(report.metrics).some((value) => value === null)
|
||||
) {
|
||||
return Object.freeze({
|
||||
status: "FAIL_UNVERIFIED",
|
||||
passed: false,
|
||||
});
|
||||
}
|
||||
const metrics = report.metrics as Readonly<{
|
||||
p75LcpMs: number;
|
||||
p75Cls: number;
|
||||
p75InpMs: number;
|
||||
}>;
|
||||
const passed =
|
||||
metrics.p75LcpMs <= thresholds.p75LcpMs &&
|
||||
metrics.p75Cls <= thresholds.p75Cls &&
|
||||
metrics.p75InpMs <= thresholds.p75InpMs;
|
||||
return Object.freeze({
|
||||
status: passed ? "PASS" : "FAIL_THRESHOLD",
|
||||
passed,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
export const PROMOTION_FORMULA = Object.freeze({
|
||||
MERGE_READY: Object.freeze([
|
||||
"FE-GATE-001",
|
||||
"FE-GATE-002",
|
||||
"FE-GATE-003",
|
||||
"FE-GATE-004",
|
||||
"FE-GATE-005",
|
||||
"FE-GATE-006",
|
||||
"FE-GATE-007",
|
||||
"FE-GATE-008",
|
||||
"FE-GATE-009",
|
||||
"FE-GATE-010",
|
||||
"FE-GATE-011",
|
||||
"FE-GATE-013",
|
||||
"FE-GATE-020",
|
||||
]),
|
||||
RELEASE_READY: Object.freeze([
|
||||
"FE-GATE-012",
|
||||
"FE-GATE-014",
|
||||
"FE-GATE-015",
|
||||
"FE-GATE-026",
|
||||
// FE-GATE-027. A candidate is only release-ready once it has been admitted
|
||||
// to a named environment; coherence alone never proved it belonged there.
|
||||
"FE-GATE-027",
|
||||
// FE-GATE-028 (08-06). The signed human accessibility review belongs to a
|
||||
// release candidate, so it gates release; merge checks the record format.
|
||||
"FE-GATE-028",
|
||||
]),
|
||||
PROD_PROMOTION_READY: Object.freeze([
|
||||
// FE-GATE-019 (13-05, D-14). Live hosting headers of the deployed promoted
|
||||
// release; the declared-header fixture alone is UNVERIFIED, not PASS.
|
||||
"FE-GATE-019",
|
||||
// FE-GATE-016 is retired (D-14): it repeated FE-GATE-025's FE-RB-005 drill.
|
||||
"FE-GATE-021",
|
||||
"FE-GATE-022",
|
||||
"FE-GATE-023",
|
||||
"FE-GATE-024",
|
||||
"FE-GATE-025",
|
||||
]),
|
||||
FIELD_SLO_READY: Object.freeze(["FE-GATE-018"]),
|
||||
DOCUMENTATION_READY: Object.freeze(["FE-GATE-017"]),
|
||||
});
|
||||
|
||||
export type GateResult = "PASS" | "FAIL" | "UNVERIFIED";
|
||||
|
||||
export function evaluatePromotionReadiness(
|
||||
gateResults: Readonly<Record<string, GateResult>>,
|
||||
) {
|
||||
const allPass = (gateIds: readonly string[]) =>
|
||||
gateIds.every((gateId) => gateResults[gateId] === "PASS");
|
||||
|
||||
const mergeReady = allPass(PROMOTION_FORMULA.MERGE_READY);
|
||||
const releaseReady =
|
||||
mergeReady && allPass(PROMOTION_FORMULA.RELEASE_READY);
|
||||
const productionReady =
|
||||
releaseReady && allPass(PROMOTION_FORMULA.PROD_PROMOTION_READY);
|
||||
const fieldReady =
|
||||
productionReady && allPass(PROMOTION_FORMULA.FIELD_SLO_READY);
|
||||
const documentationReady = allPass(PROMOTION_FORMULA.DOCUMENTATION_READY);
|
||||
|
||||
return Object.freeze({
|
||||
MERGE_READY: mergeReady,
|
||||
RELEASE_READY: releaseReady,
|
||||
PROD_PROMOTION_READY: productionReady,
|
||||
FIELD_SLO_READY: fieldReady,
|
||||
DOCUMENTATION_READY: documentationReady,
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
// Importing the realtime or Web Push adapter from the composition root is the
|
||||
// graph rule unselected-realtime-runtime-is-not-composed (12-10). This scan
|
||||
// keeps what an import graph cannot see: native API calls and timers.
|
||||
export type RealtimeBoundaryRuleId =
|
||||
| "NATIVE_REALTIME_API_OUTSIDE_ADAPTER"
|
||||
| "PRESENTATION_INTERVAL_OWNER"
|
||||
| "UNSELECTED_REALTIME_RUNTIME_COMPOSED";
|
||||
| "PRESENTATION_INTERVAL_OWNER";
|
||||
|
||||
export type RealtimeBoundaryViolation = Readonly<{
|
||||
ruleId: RealtimeBoundaryRuleId;
|
||||
@@ -17,8 +19,6 @@ const OWNED_NATIVE_ROOTS = [
|
||||
"src/adapters/realtime/",
|
||||
"src/adapters/web-push/",
|
||||
] as const;
|
||||
const REALTIME_ADAPTER_IMPORT =
|
||||
/(?:from\s*|import\s*\()\s*["'][^"']*\/adapters\/(?:realtime|web-push)(?:\/[^"']*)?["']/gu;
|
||||
const NATIVE_REALTIME_PATTERNS = [
|
||||
/\bnew\s+(?:WebSocket|EventSource|Notification)\s*\(/gu,
|
||||
/\bNotification\s*\.\s*requestPermission\s*\(/gu,
|
||||
@@ -62,9 +62,6 @@ function inspectFile(
|
||||
const presentationOwned =
|
||||
logicalFile.startsWith("src/presentation/") ||
|
||||
/^src\/features\/[^/]+\/presentation\//u.test(logicalFile);
|
||||
const compositionBoundary =
|
||||
logicalFile.startsWith("src/bootstrap/") ||
|
||||
/^src\/features\/installed-feature-/u.test(logicalFile);
|
||||
|
||||
const report = (
|
||||
ruleId: RealtimeBoundaryRuleId,
|
||||
@@ -92,11 +89,6 @@ function inspectFile(
|
||||
report("PRESENTATION_INTERVAL_OWNER", match.index);
|
||||
}
|
||||
}
|
||||
if (compositionBoundary) {
|
||||
for (const match of source.matchAll(REALTIME_ADAPTER_IMPORT)) {
|
||||
report("UNSELECTED_REALTIME_RUNTIME_COMPOSED", match.index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function collectSourceFiles(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
cp,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
readdir,
|
||||
rm,
|
||||
@@ -14,8 +15,12 @@ import {
|
||||
loadCiGateContract,
|
||||
parseCiGateContract,
|
||||
} from "../contracts/ci-gates.ts";
|
||||
import { linkFixtureNodeModules } from "./fixture-node-modules.ts";
|
||||
import {
|
||||
FIXTURE_PNPM_ENVIRONMENT,
|
||||
linkFixtureNodeModules,
|
||||
} from "./fixture-node-modules.ts";
|
||||
import { generateCiWorkflow } from "../generate-ci-workflow.ts";
|
||||
import { updateCiContractBaseline } from "../update-ci-contract-baseline.ts";
|
||||
|
||||
export const REMOVAL_FIXTURE_COPY_TARGETS = Object.freeze([
|
||||
"src", "tests", "recipes", "scripts", "schemas", "config", "public",
|
||||
@@ -159,16 +164,89 @@ function runFixtureGit(root: string, argv: readonly string[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 14-08. A fresh fixture directory per run: two runs, or a run after one that
|
||||
* crashed, no longer share (and overwrite) one fixed path. Callers remove it
|
||||
* in `finally`.
|
||||
*/
|
||||
export async function createRemovalFixtureRoot(name: string): Promise<string> {
|
||||
const parent = path.resolve(".tmp");
|
||||
await mkdir(parent, { recursive: true });
|
||||
return mkdtemp(path.join(parent, `${name}-`));
|
||||
}
|
||||
|
||||
export type RemovalCheck = Readonly<{
|
||||
name: string;
|
||||
passed: boolean;
|
||||
/** Why this check failed; each check names its own cause. */
|
||||
failure?: string;
|
||||
}>;
|
||||
|
||||
export function runRemovalFixtureCheck(
|
||||
name: string,
|
||||
root: string,
|
||||
pnpmCli: string,
|
||||
script: string,
|
||||
extra: readonly string[] = [],
|
||||
): RemovalCheck {
|
||||
const status = spawnSync(process.execPath, [pnpmCli, script, ...extra], {
|
||||
cwd: root,
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT },
|
||||
}).status;
|
||||
return status === 0
|
||||
? { name, passed: true }
|
||||
: {
|
||||
name,
|
||||
passed: false,
|
||||
failure: `corepack pnpm ${[script, ...extra].join(" ")} exited ${status ?? "on a signal"}`,
|
||||
};
|
||||
}
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
}
|
||||
|
||||
/**
|
||||
* 14-08. The report used to say `failures="1"` whatever failed, and put the
|
||||
* residue list into every failed testcase, so a type error read as residue.
|
||||
*/
|
||||
export function renderRemovalJunit(
|
||||
suite: string,
|
||||
checks: readonly RemovalCheck[],
|
||||
): string {
|
||||
const failures = checks.filter((check) => !check.passed).length;
|
||||
const cases = checks
|
||||
.map((check) =>
|
||||
`<testcase name="${escapeXml(check.name)}">${
|
||||
check.passed
|
||||
? ""
|
||||
: `<failure message="${escapeXml(check.failure ?? "failed")}" />`
|
||||
}</testcase>`,
|
||||
)
|
||||
.join("");
|
||||
return (
|
||||
`<?xml version="1.0" encoding="UTF-8"?>\n` +
|
||||
`<testsuite name="${escapeXml(suite)}" tests="${checks.length}" failures="${failures}">` +
|
||||
`${cases}</testsuite>\n`
|
||||
);
|
||||
}
|
||||
|
||||
export function runRemovalFixturePnpm(
|
||||
root: string,
|
||||
pnpmCli: string,
|
||||
script: string,
|
||||
extra: readonly string[] = [],
|
||||
env: Readonly<Record<string, string>> = {},
|
||||
): boolean {
|
||||
return spawnSync(process.execPath, [pnpmCli, script, ...extra], {
|
||||
cwd: root,
|
||||
stdio: "inherit",
|
||||
env: { ...process.env, CI_CONTRACT_MODE: "removal-fixture" },
|
||||
env: { ...process.env, ...FIXTURE_PNPM_ENVIRONMENT, ...env },
|
||||
}).status === 0;
|
||||
}
|
||||
|
||||
@@ -274,7 +352,7 @@ export function pruneScriptOrchestration(
|
||||
}
|
||||
|
||||
export async function regenerateRemovalFixtureWorkflow(root: string): Promise<void> {
|
||||
const contract = await loadCiGateContract(root, { mode: "removal-fixture" });
|
||||
const contract = await loadCiGateContract(root);
|
||||
await generateCiWorkflow({ root, contract, check: false });
|
||||
// Every removal script calls this once, after it has finished mutating the
|
||||
// tree, so it is the one place where the fixture's contents are final.
|
||||
@@ -328,10 +406,6 @@ export async function pruneRemovalFixtureCiContract(options: Readonly<{
|
||||
scripts: Record<string, string>;
|
||||
};
|
||||
for (const script of options.removedScripts) delete packageDocument.scripts[script];
|
||||
packageDocument.scripts["check:ci-workflow"] =
|
||||
"node scripts/generate-ci-workflow.ts --check --reduced-removal-fixture";
|
||||
packageDocument.scripts["check:ci"] =
|
||||
"corepack pnpm check:artifact-schemas && node scripts/check-ci-contract.ts --reduced-removal-fixture && corepack pnpm check:ci-workflow";
|
||||
|
||||
const contract = structuredClone(
|
||||
parseCiGateContract(JSON.parse(await readFile(gatesPath, "utf8"))),
|
||||
@@ -384,9 +458,15 @@ export async function pruneRemovalFixtureCiContract(options: Readonly<{
|
||||
contract.artifactSchemas = contract.artifactSchemas.filter(({ id }) =>
|
||||
referencedSchemaIds.has(id)
|
||||
);
|
||||
const validated = parseCiGateContract(contract, { mode: "removal-fixture" });
|
||||
const validated = parseCiGateContract(contract);
|
||||
await Promise.all([
|
||||
writeFile(packagePath, `${JSON.stringify(packageDocument, null, 2)}\n`),
|
||||
writeFile(gatesPath, `${JSON.stringify(validated, null, 2)}\n`),
|
||||
]);
|
||||
// D-13: the reduced contract is a new baseline, recorded the way a project
|
||||
// that removes the capability records it; canonical check:ci then applies.
|
||||
await updateCiContractBaseline(options.root, {
|
||||
owner: "removal-fixture",
|
||||
reason: `removal fixture pruned ${[...options.removedScripts].join(", ")}`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 06-03 (D-5). The emergency exit for a worker that stops the page from
|
||||
* booting. A `REMOVE_REGISTRATION` release writes this as `service-worker.js`.
|
||||
* The browser's own update check (navigation, `updateViaCache: "none"`) then
|
||||
* installs it over any worker of this scope without a page: it skips waiting,
|
||||
* and on activation unregisters the registration. It has no fetch handler, so
|
||||
* every request goes to the network. Owned caches stay for the
|
||||
* `PURGE_OWNED_RESOURCES` release, as with the page-side removal.
|
||||
*/
|
||||
export const SELF_UNREGISTERING_SERVICE_WORKER = `// Generated by scripts/build-frontend.ts (REMOVE_REGISTRATION).
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(self.skipWaiting());
|
||||
});
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(self.registration.unregister());
|
||||
});
|
||||
`;
|
||||
@@ -29,7 +29,10 @@ export function resolveServiceWorkerBuildInput(input: Readonly<{
|
||||
selection: InstalledServiceWorkerSelection | null;
|
||||
assets: unknown;
|
||||
contractSet: unknown;
|
||||
/** `dist/config.json`, materialized from the build's profile (06-10). */
|
||||
runtimeConfig: unknown;
|
||||
/** The build's `APP_PROFILE`; the runtime document must be for it. */
|
||||
appProfile: string;
|
||||
buildId: string;
|
||||
releaseId: string;
|
||||
}>): ServiceWorkerBuildInput {
|
||||
@@ -70,7 +73,14 @@ export function resolveServiceWorkerBuildInput(input: Readonly<{
|
||||
throw new TypeError("Generated contract set digest is invalid.");
|
||||
}
|
||||
const runtimeConfig = record(input.runtimeConfig);
|
||||
const releaseManifestUrl = runtimeConfig?.RELEASE_MANIFEST_URL;
|
||||
// 06-10 / F-8. `public/config.json` is the local profile; a worker built from
|
||||
// it for another profile would carry that profile's URLs.
|
||||
if (runtimeConfig?.APP_ENV !== input.appProfile) {
|
||||
throw new TypeError(
|
||||
`Service Worker runtime config APP_ENV ${String(runtimeConfig?.APP_ENV)} does not match APP_PROFILE ${input.appProfile}.`,
|
||||
);
|
||||
}
|
||||
const releaseManifestUrl = runtimeConfig.RELEASE_MANIFEST_URL;
|
||||
if (
|
||||
typeof releaseManifestUrl !== "string" ||
|
||||
releaseManifestUrl.length === 0 ||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { reachablePackageScripts } from "./package-script-graph.ts";
|
||||
|
||||
/**
|
||||
* 12-04. A verification package script protects nothing unless a CI gate runs
|
||||
* it. `ungated-tests.ts` covers test files; this covers the scripts. A script
|
||||
* of a verification family is gated when a gate command reaches it through
|
||||
* the package script graph, or when it only re-runs Vitest paths a gate
|
||||
* already runs. Anything else needs a reasoned entry in
|
||||
* config/ci/ungated-scripts.json.
|
||||
*/
|
||||
export const UNGATED_SCRIPTS_PATH = "config/ci/ungated-scripts.json";
|
||||
|
||||
const VERIFICATION_SCRIPT = /^(?:check|verify|test|drill|review):/u;
|
||||
|
||||
const ungatedScriptsSchema = z
|
||||
.object({
|
||||
schemaVersion: z.literal(1),
|
||||
entries: z.array(
|
||||
z
|
||||
.object({
|
||||
script: z.string().regex(VERIFICATION_SCRIPT),
|
||||
reason: z.string().trim().min(1, "exclusion reason is required"),
|
||||
})
|
||||
.strict(),
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type UngatedScriptExclusion = Readonly<{ script: string; reason: string }>;
|
||||
|
||||
export function parseUngatedScriptExclusions(value: unknown): readonly UngatedScriptExclusion[] {
|
||||
return ungatedScriptsSchema.parse(value).entries;
|
||||
}
|
||||
|
||||
/** Every segment is a Vitest run whose paths all lie inside gated paths. */
|
||||
function rerunsGatedTests(command: string, gatedTestPaths: readonly string[]): boolean {
|
||||
const gated = (target: string) =>
|
||||
gatedTestPaths.some((gatedPath) => target === gatedPath || target.startsWith(`${gatedPath}/`));
|
||||
return command.split("&&").every((segment) => {
|
||||
const tokens = segment.trim().split(/\s+/u);
|
||||
const run = tokens.findIndex(
|
||||
(token, index) => token === "run" && /(?:run-vitest\.ts|vitest)$/u.test(tokens[index - 1] ?? ""),
|
||||
);
|
||||
if (run < 0) return false;
|
||||
const paths = tokens.slice(run + 1).filter((token) => !token.startsWith("-"));
|
||||
return paths.length > 0 && paths.every((target) => gated(target.replace(/\/$/u, "")));
|
||||
});
|
||||
}
|
||||
|
||||
export function ungatedScriptFailures(input: Readonly<{
|
||||
scripts: Readonly<Record<string, string>>;
|
||||
entryScripts: readonly string[];
|
||||
gatedTestPaths: readonly string[];
|
||||
exclusions: readonly UngatedScriptExclusion[];
|
||||
}>): string[] {
|
||||
const reached = new Set(reachablePackageScripts(input.scripts, input.entryScripts));
|
||||
const gated = (script: string) =>
|
||||
reached.has(script) || rerunsGatedTests(input.scripts[script] ?? "", input.gatedTestPaths);
|
||||
const excluded = new Set(input.exclusions.map(({ script }) => script));
|
||||
const failures = Object.keys(input.scripts)
|
||||
.filter((script) => VERIFICATION_SCRIPT.test(script) && !gated(script) && !excluded.has(script))
|
||||
.sort()
|
||||
.map((script) =>
|
||||
`verification script is not reached by any CI gate command and is not in ${UNGATED_SCRIPTS_PATH}: ${script}`
|
||||
);
|
||||
// An entry for a script a removal deleted is harmless; one for a script a
|
||||
// gate now reaches would hide the next regression, so it has to go.
|
||||
for (const { script } of input.exclusions) {
|
||||
if (input.scripts[script] !== undefined && gated(script)) {
|
||||
failures.push(`ungated script exclusion is stale; a CI gate reaches it: ${script}`);
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { readdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { SCALE_TIERS, type ScaleTier } from "../scale/run-scale-profile.ts";
|
||||
import { reachablePackageScripts } from "./package-script-graph.ts";
|
||||
|
||||
/**
|
||||
* 12-04. A test file protects nothing unless a CI gate runs it. The gated set
|
||||
* is read from the package scripts the CI contract's commands reach: Vitest
|
||||
* path filters (`run-vitest.ts run <paths>`), the Vitest steps of a scale tier
|
||||
* (`run-scale-profile.ts <tier>`) and Playwright config `testDir`s.
|
||||
* A test outside that set needs a reasoned entry in config/ci/ungated-tests.json.
|
||||
*/
|
||||
export const UNGATED_TESTS_PATH = "config/ci/ungated-tests.json";
|
||||
|
||||
const TEST_FILE = /\.(?:test|spec)\.tsx?$/u;
|
||||
|
||||
const ungatedTestsSchema = z
|
||||
.object({
|
||||
schemaVersion: z.literal(1),
|
||||
entries: z.array(
|
||||
z
|
||||
.object({
|
||||
path: z.string().regex(/^tests\/\S+$/u),
|
||||
reason: z.string().trim().min(1, "exclusion reason is required"),
|
||||
})
|
||||
.strict(),
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type UngatedTestExclusion = Readonly<{ path: string; reason: string }>;
|
||||
|
||||
export function parseUngatedTestExclusions(value: unknown): readonly UngatedTestExclusion[] {
|
||||
return ungatedTestsSchema.parse(value).entries;
|
||||
}
|
||||
|
||||
/** Repository-relative test files below tests/, fixtures excluded. */
|
||||
export async function listTestFiles(root: string): Promise<string[]> {
|
||||
const entries = await readdir(path.join(root, "tests"), { recursive: true, withFileTypes: true });
|
||||
return entries
|
||||
.filter((entry) => entry.isFile() && TEST_FILE.test(entry.name))
|
||||
.map((entry) =>
|
||||
path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join("/"),
|
||||
)
|
||||
.filter((file) => !file.startsWith("tests/fixtures/"))
|
||||
.sort();
|
||||
}
|
||||
|
||||
export function gatedTestPaths(
|
||||
scripts: Readonly<Record<string, string>>,
|
||||
entryScripts: readonly string[],
|
||||
readConfig: (file: string) => string,
|
||||
): string[] {
|
||||
const paths = new Set<string>();
|
||||
const addVitestPaths = (tokens: readonly string[]) => {
|
||||
const vitestRun = tokens.findIndex(
|
||||
(token, index) => token === "run" && /(?:run-vitest\.ts|vitest)$/u.test(tokens[index - 1] ?? ""),
|
||||
);
|
||||
if (vitestRun < 0) return;
|
||||
for (const token of tokens.slice(vitestRun + 1)) {
|
||||
if (!token.startsWith("-")) paths.add(token.replace(/\/$/u, ""));
|
||||
}
|
||||
};
|
||||
for (const script of reachablePackageScripts(scripts, entryScripts)) {
|
||||
for (const segment of scripts[script]!.split("&&")) {
|
||||
const tokens = segment.trim().split(/\s+/u);
|
||||
addVitestPaths(tokens);
|
||||
const scaleProfile = tokens.findIndex((token) => /run-scale-profile\.ts$/u.test(token));
|
||||
if (scaleProfile >= 0) {
|
||||
for (const step of SCALE_TIERS[tokens[scaleProfile + 1] as ScaleTier] ?? []) addVitestPaths(step.command);
|
||||
}
|
||||
const playwrightTest = tokens.findIndex(
|
||||
(token, index) => token === "test" && tokens[index - 1] === "playwright",
|
||||
);
|
||||
if (playwrightTest >= 0) {
|
||||
const configFlag = tokens.indexOf("--config");
|
||||
const config = configFlag >= 0 ? tokens[configFlag + 1]! : "playwright.config.ts";
|
||||
const testDir = /testDir:\s*["']\.?\/?([^"']+)["']/u.exec(readConfig(config))?.[1];
|
||||
if (testDir) paths.add(testDir.replace(/\/$/u, ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...paths].sort();
|
||||
}
|
||||
|
||||
export function ungatedTestFailures(input: Readonly<{
|
||||
testFiles: readonly string[];
|
||||
gatedPaths: readonly string[];
|
||||
exclusions: readonly UngatedTestExclusion[];
|
||||
}>): string[] {
|
||||
const gated = (file: string) =>
|
||||
input.gatedPaths.some((gatedPath) => file === gatedPath || file.startsWith(`${gatedPath}/`));
|
||||
const excluded = new Set(input.exclusions.map(({ path: file }) => file));
|
||||
const failures = input.testFiles
|
||||
.filter((file) => !gated(file) && !excluded.has(file))
|
||||
.map((file) =>
|
||||
`test file is not run by any CI gate command and is not in ${UNGATED_TESTS_PATH}: ${file}`
|
||||
);
|
||||
// An entry for a file a removal deleted is harmless; one for a file a gate
|
||||
// now runs would hide the next regression, so it has to go.
|
||||
for (const { path: file } of input.exclusions) {
|
||||
if (gated(file)) failures.push(`ungated test exclusion is stale; a CI gate runs it: ${file}`);
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import type { Plugin } from "vite";
|
||||
@@ -39,6 +40,7 @@ export function viteModuleInventoryPlugin(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
chunks,
|
||||
packages: bundledPackages(chunks),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
@@ -48,7 +50,41 @@ export function viteModuleInventoryPlugin(
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeModuleId(
|
||||
/**
|
||||
* 13-12. The `name@version` of every package with at least one module in the
|
||||
* emitted bundle: what the public release actually ships, as opposed to the
|
||||
* SBOM, which lists the whole installed graph.
|
||||
*/
|
||||
export function bundledPackages(chunks: readonly ModuleInventoryChunk[]): string[] {
|
||||
const packages = new Set<string>();
|
||||
for (const chunk of chunks) {
|
||||
for (const module of chunk.modules) {
|
||||
const match = /^npm:((?:@[^/]+\/)?[^/@]+@[^/]+)\//u.exec(module);
|
||||
if (match?.[1]) packages.add(match[1]);
|
||||
}
|
||||
}
|
||||
return [...packages].sort();
|
||||
}
|
||||
|
||||
const packageManifests = new Map<string, Readonly<{ name: string; version: string }>>();
|
||||
|
||||
function installedPackage(directory: string): Readonly<{ name: string; version: string }> {
|
||||
let manifest = packageManifests.get(directory);
|
||||
if (!manifest) {
|
||||
const parsed = JSON.parse(readFileSync(path.join(directory, "package.json"), "utf8")) as {
|
||||
name?: unknown;
|
||||
version?: unknown;
|
||||
};
|
||||
if (typeof parsed.name !== "string" || typeof parsed.version !== "string") {
|
||||
throw new TypeError(`bundled package has no name/version: ${directory}`);
|
||||
}
|
||||
manifest = Object.freeze({ name: parsed.name, version: parsed.version });
|
||||
packageManifests.set(directory, manifest);
|
||||
}
|
||||
return manifest;
|
||||
}
|
||||
|
||||
export function normalizeModuleId(
|
||||
moduleId: string,
|
||||
repositoryRoot: string,
|
||||
): string {
|
||||
@@ -56,6 +92,18 @@ function normalizeModuleId(
|
||||
if (!path.isAbsolute(withoutQuery)) {
|
||||
return withoutQuery.replaceAll("\\", "/");
|
||||
}
|
||||
// 13-12: a dependency module keeps its package identity, read from the
|
||||
// package.json of the directory it was resolved into.
|
||||
const file = withoutQuery.replaceAll("\\", "/");
|
||||
const marker = "/node_modules/";
|
||||
const at = file.lastIndexOf(marker);
|
||||
if (at >= 0) {
|
||||
const segments = file.slice(at + marker.length).split("/");
|
||||
const nameLength = segments[0]?.startsWith("@") ? 2 : 1;
|
||||
const directory = file.slice(0, at + marker.length) + segments.slice(0, nameLength).join("/");
|
||||
const { name, version } = installedPackage(directory);
|
||||
return `npm:${name}@${version}/${segments.slice(nameLength).join("/")}`;
|
||||
}
|
||||
const relative = path.relative(repositoryRoot, withoutQuery);
|
||||
return relative.startsWith("..")
|
||||
? `external:${path.basename(withoutQuery)}`
|
||||
|
||||
Reference in New Issue
Block a user