chore(review): 1103 release·CI·성능 조치 브랜치를 합친다
Refs: docs/reviews/2026-11-03-maturity-review/README.md 12-07 13-01~13-03 13-05 15-02~15-07 # Conflicts: # docs/manual/03-outside-feature-folder.md # docs/operations/performance-evidence.md # scripts/lib/hosting-probe.ts
This commit is contained in:
@@ -43,7 +43,7 @@ Build and deploy variables, lowest precedence first:
|
||||
| `APP_PROFILE` | which `config/runtime/<profile>.json` is used | `local`; an empty value fails the build |
|
||||
| `RUNTIME_API_BASE_URL` | `API_BASE_URL`, overriding the profile; the CI workflow cannot pass it (see below) | the profile value |
|
||||
| `RUNTIME_TELEMETRY_ENDPOINT` | `TELEMETRY_ENDPOINT`, overriding the profile; the CI workflow cannot pass it (see below) | the profile value |
|
||||
| `VITE_BUILD_ID` | `BUILD_ID` in the runtime config and the release manifest | `local-build` |
|
||||
| `VITE_BUILD_ID` | `BUILD_ID` in the runtime config and the release manifest | `local-build` for `local` and `development`; a `staging` or `production` build fails without it |
|
||||
| `RELEASE_ID` | `RELEASE_ID` in the runtime config and the release manifest | `local-release` |
|
||||
| `RELEASE_TARGET` | the environment FE-GATE-027 admits the build to; must equal `APP_PROFILE` | none; admission refuses without it |
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"owner": "frontend-platform",
|
||||
"reason": "U7: FE-GATE-020 runs test:feature-scaffold, which creates a feature with create:feature in a copy and runs the merge gates on it",
|
||||
"owner": "DongHyeonka",
|
||||
"reason": "1103/13-03: FE-GATE-027 also runs scan:dependency-advisories, a non-blocking release-stage advisory signal",
|
||||
"gates": 27,
|
||||
"commands": 99,
|
||||
"commandReferences": 103,
|
||||
"commands": 100,
|
||||
"commandReferences": 104,
|
||||
"artifacts": 110,
|
||||
"stages": 5,
|
||||
"gateShapeSha256": "02e87e35b87fbc5114af7e1b1ce1ec030062c60ae8bd03c151f1ec9538f2db3b"
|
||||
"gateShapeSha256": "6225494d6447a2065d921a34597a744d180a7a68e601119e32f8fc42e18eb1c1"
|
||||
}
|
||||
|
||||
@@ -595,6 +595,11 @@
|
||||
"id": "check-release-admission",
|
||||
"script": "check:release-admission",
|
||||
"expect": "pass"
|
||||
},
|
||||
{
|
||||
"id": "scan-dependency-advisories",
|
||||
"script": "scan:dependency-advisories",
|
||||
"expect": "pass"
|
||||
}
|
||||
],
|
||||
"artifactSchemas": [
|
||||
@@ -2200,7 +2205,8 @@
|
||||
"id": "FE-GATE-027",
|
||||
"name": "release-admission",
|
||||
"commandIds": [
|
||||
"check-release-admission"
|
||||
"check-release-admission",
|
||||
"scan-dependency-advisories"
|
||||
],
|
||||
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-027-txt",
|
||||
"evidenceArtifactIds": [
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"deployment": null,
|
||||
"mergeGates": []
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"transport": {
|
||||
"alpnProtocols": ["h2"]
|
||||
},
|
||||
"surfaces": {
|
||||
"index": {
|
||||
"path": "/",
|
||||
@@ -23,6 +26,7 @@
|
||||
"pathPattern": "/assets/*",
|
||||
"cacheControl": "public, max-age=31536000, immutable",
|
||||
"contentTypes": ["text/javascript", "application/javascript"],
|
||||
"contentEncodings": ["br", "gzip", "zstd"],
|
||||
"securityHeaders": false
|
||||
},
|
||||
"sourceMap": {
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
},
|
||||
"hashedAsset": {
|
||||
"cache-control": "public, max-age=31536000, immutable",
|
||||
"content-type": "text/javascript; charset=utf-8"
|
||||
"content-type": "text/javascript; charset=utf-8",
|
||||
"content-encoding": "gzip"
|
||||
},
|
||||
"appRoute": {
|
||||
"cache-control": "no-cache",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"schemaVersion": 1,
|
||||
"bundle": {
|
||||
"initialJsGzipBytes": 204800,
|
||||
"initialJsFiles": 25,
|
||||
"lazyChunkGzipBytes": 122880
|
||||
},
|
||||
"lab": {
|
||||
|
||||
@@ -21,9 +21,9 @@
|
||||
},
|
||||
{
|
||||
"axis": "Initial JavaScript",
|
||||
"verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes. Baseline: 203,816 B with no copy, about 610-630 B and no extra file per copy (219,508 B at 25, 264,841 B at 100; before 15-01: +3,922 B per copy). tests/unit/feature-shape-growth.test.ts keeps one copy at or under 1 KiB",
|
||||
"verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes, and a copy adds no initial file. initialJavascript below is the current template build, what one more feature in an existing context adds (perFeatureGzipBytes) and what a new context adds (perContextGzipBytes); tests/unit/feature-shape-growth.test.ts measures them on every unit run, bounds a feature at 1 KiB and a context at 512 B, and fails when the record no longer matches the build. The 25- and 100-copy runs are in the baseline at its source commit (before 15-01: +3,922 B per copy)",
|
||||
"condition": "Same; the feature-declarations and feature-platform chunk groups in vite.config.ts",
|
||||
"notVerified": "The initial budget (204,800 B, config/performance/budgets.json) leaves 2,291 B over the baseline's 202,509 B, so about three more reference-shaped features fit at about 610 B each: the platform itself is 98.9% of it"
|
||||
"notVerified": "How many more features fit: the initial budget (config/performance/budgets.json) minus initialJavascript.gzipBytes, divided by perFeatureGzipBytes (plus perContextGzipBytes per new context). The platform itself takes most of the budget"
|
||||
},
|
||||
{
|
||||
"axis": "Lazy JavaScript",
|
||||
@@ -37,5 +37,11 @@
|
||||
"condition": "Same",
|
||||
"notVerified": "Router matching cost at runtime"
|
||||
}
|
||||
]
|
||||
],
|
||||
"initialJavascript": {
|
||||
"gzipBytes": 200939,
|
||||
"files": 25,
|
||||
"perFeatureGzipBytes": 765,
|
||||
"perContextGzipBytes": 214
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"snapshotDigest": "ce4fa9b7944f27553067228bd6c9e73e7dc05875c283255b50d7eb3ad2923f6d",
|
||||
"owner": "frontend-platform",
|
||||
"reason": "RP-11-initial-transitive-inventory",
|
||||
"approvedAt": "2026-07-26T08:27:17.874Z"
|
||||
"snapshotDigest": "1be535686bed2315cc986f51b991b269c359ce1dca34d47faee6d35b0d57cfd3",
|
||||
"owner": "DongHyeonka",
|
||||
"reason": "1103/13-03 dev-only advisory fixes: vite 8.1.6, vitest and coverage-v8 4.1.12, storybook 10.6.5, in-range updates of undici, brace-expansion, nanoid, source-map-js, postcss",
|
||||
"approvedAt": "2026-11-04T13:27:48.076Z"
|
||||
}
|
||||
|
||||
+1294
-1292
File diff suppressed because it is too large
Load Diff
@@ -40,8 +40,10 @@ that the host serves that release; while the slot is empty FE-GATE-019 is
|
||||
Rollback changes the active pointer only after confirming that the prior
|
||||
immutable release has a coherent HTML/assets/config/API/manifest tuple.
|
||||
|
||||
Serve the app over HTTP/2 or later. The entry preloads about 26 initial
|
||||
JavaScript files in parallel. Over HTTP/1.1 they queue for six connections per
|
||||
Serve the app over HTTP/2 or later. The entry preloads every initial
|
||||
JavaScript file in parallel (`initialJsFiles` in
|
||||
`config/performance/budgets.json` bounds how many; the current count is
|
||||
`initialJavascript.files` in `config/scale/feature-shape-ceilings.json`). Over HTTP/1.1 they queue for six connections per
|
||||
host, and the first screen on Fast 3G came about one second later than with the
|
||||
initial chunks grouped (2026-11-03). Over HTTP/2 the difference was under
|
||||
100 ms, so the template keeps the chunks split. A product that can only serve
|
||||
@@ -49,3 +51,12 @@ HTTP/1.1 groups its initial chunks in `vite.config.ts` and measures again
|
||||
whenever the shell changes ("초기 청크 수와 HTTP/1.1" in
|
||||
[`performance-evidence.md`](../operations/performance-evidence.md), review
|
||||
1101/14.4).
|
||||
|
||||
Serve JavaScript compressed (gzip, brotli or zstd). The bundle budget counts
|
||||
gzip bytes; uncompressed, the initial JavaScript is about three times larger.
|
||||
Both premises are declared in `config/hosting/cache-policy.json`
|
||||
(`transport.alpnProtocols`, `hashedAsset.contentEncodings`), and the live probe
|
||||
of FE-GATE-019 fails a host that does not meet them (review 1103/13-02). The
|
||||
nginx example in
|
||||
[`release-cache-rollback.md`](../operations/release-cache-rollback.md) turns
|
||||
both on.
|
||||
|
||||
@@ -114,6 +114,7 @@ release admission refused for staging:
|
||||
- FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다.
|
||||
- `config/runtime/<profile>.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`).
|
||||
- `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다.
|
||||
- `config/ci/product-gates.json`: 배포 job(`deployment`)을 채우거나 제품 전용 merge 검사(`PRODUCT-GATE-NNN`)를 더할 때. 템플릿 파일 `config/ci/gates.json`은 고치지 않는다. 형식은 [`ci-quality-gates.md`](../operations/ci-quality-gates.md)에 있다.
|
||||
- `package.json`, lockfile, `config/security/dependency-change-evidence.json`: 계약 패키지를 더할 때(B절).
|
||||
|
||||
정본 표에 없는 것:
|
||||
|
||||
@@ -335,17 +335,60 @@ contract rejects a production gate command that builds or omits the release root
|
||||
The hosting gate FE-GATE-019 also reads `.release/promoted-release`: it checks
|
||||
that archive's `dist` and requires the live host to serve a
|
||||
`release-manifest.json` with the candidate's `buildId` and `releaseId`, so a
|
||||
host still serving an earlier release fails (1101/13-01). The workflow deploys
|
||||
host still serving an earlier release fails (1101/13-01). Because a rebuild in
|
||||
the same run shares those names, the served `config.json` must also equal the
|
||||
candidate's outside the two emergency switches and the served `index.html` must
|
||||
name the candidate's entry script (1103/13-01). The workflow deploys
|
||||
nothing itself. Between `promotion` and `production_gate` sits the `deployment`
|
||||
job, the project's deployment slot. It is empty by default: it reports
|
||||
`deployed=false`, FE-GATE-019 does not probe the host and ends `UNVERIFIED`
|
||||
(exit 3), and the production stage stays open. To fill it, edit the
|
||||
`deployment` job in `config/ci/gates.json` and run `corepack pnpm
|
||||
generate:ci-workflow`. The contract allows the steps `checkout`, `setup-node`,
|
||||
(exit 3), and the production stage stays open. To fill it, set `deployment`
|
||||
in the product-owned `config/ci/product-gates.json` and run `corepack pnpm
|
||||
generate:ci-workflow` (1103/12-07):
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"deployment": {
|
||||
"script": "deploy:desktop",
|
||||
"environment": [
|
||||
{ "name": "DEPLOY_HOST", "value": "${{ vars.DEPLOY_HOST }}" },
|
||||
{ "name": "DEPLOY_SSH_KEY", "value": "${{ secrets.DEPLOY_SSH_KEY }}" }
|
||||
]
|
||||
},
|
||||
"mergeGates": []
|
||||
}
|
||||
```
|
||||
|
||||
The template renders the rest of the slot: it downloads the `promoted-release`
|
||||
transfer, extracts it to `.release/promoted-release` against the candidate
|
||||
digest, then runs the script, which deploys `.release/promoted-release/dist`.
|
||||
`environment` takes only `vars.*` and `secrets.*` values. The template ships
|
||||
this file empty and never changes it, so a template sync does not meet it;
|
||||
`config/ci/gates.json` stays the template's, and its contract baseline counts
|
||||
the template contract only. A slot filled in both files is refused.
|
||||
|
||||
`mergeGates` adds the product's own checks, such as a contract check against
|
||||
the paired backend: `{ "id": "PRODUCT-GATE-001", "name": "backend-contract",
|
||||
"script": "check:backend-contract" }`. Ids are `PRODUCT-GATE-NNN`; the
|
||||
`FE-GATE-NNN` ids, their commands, artifacts and readiness formula stay the
|
||||
template's. Each runs as `corepack pnpm <script>` in the `product_merge_gate`
|
||||
job, on the same condition as `merge_gate`, without browsers and without the
|
||||
gate log and evidence artifacts of `ci:gate`. Make that job a required check
|
||||
of the branch where it has to block a merge. `check:ci` refuses a script that
|
||||
`package.json` does not define and counts these scripts as gated.
|
||||
|
||||
The slot as stored in `config/ci/gates.json` still follows the same contract
|
||||
rules. The contract allows the steps `checkout`, `setup-node`,
|
||||
`frozen-install`, `download` (the `promoted-release` transfer), `extract`, and
|
||||
one final `deploy` step whose `script` names a package script. Its variables
|
||||
may only be the `CANDIDATE_ARCHIVE_SHA256` digest of `immutable_build` and
|
||||
`vars.*` or `secrets.*` values. The `deploy` step writes `deployed=true` only
|
||||
`vars.*` or `secrets.*` values. A slot with a deploy script must download only
|
||||
the `promoted-release` transfer, extract its `release-candidate.tar.gz` and
|
||||
bind the digest, so the script deploys the promoted candidate rather than a
|
||||
rebuild (1103/13-01). `secrets.*` values are rendered on the `deploy` step
|
||||
alone, not on the job, so checkout, setup-node and the download action never
|
||||
see them (1103/13-05). The `deploy` step writes `deployed=true` only
|
||||
after the script succeeds. The job owns no gate, so filling it changes neither
|
||||
gate ownership nor the contract baseline. Browser boot, live API traffic, smoke after a provider
|
||||
switch, and anything the runbook marks as needing provider verification are
|
||||
@@ -433,6 +476,18 @@ Repository variables required by higher tiers:
|
||||
job runs FE-GATE-015 and then FE-GATE-027, and FE-GATE-027 refuses the
|
||||
candidate when `APP_PROFILE` is set and differs from `RELEASE_TARGET`. Both are
|
||||
repository-wide variables, so set them together for each release.
|
||||
FE-GATE-027 then runs `scan:dependency-advisories` (1103/13-03). It applies
|
||||
`config/security/vulnerability-policy.json` and its exceptions to the
|
||||
registry's advisory report for the lockfile (pnpm's audit command with
|
||||
`--json`) and writes the result to the gate log
|
||||
and `artifacts/security/dependency-advisories.json`: `PASS`,
|
||||
`POLICY_VIOLATION` (what the production promotion would refuse, with the
|
||||
findings) or `UNVERIFIED` (no registry). It never fails the gate, because an
|
||||
advisory database that changes under unchanged code would break releases;
|
||||
the signed verdict of the vulnerability provider still decides promotion.
|
||||
`renovate.json` opens security update PRs once a Renovate runner is attached;
|
||||
a dependency update re-approves the dependency baseline in the same change
|
||||
(`update:dependency-baseline`).
|
||||
- `FIELD_WEB_VITALS_INPUT` for the privacy-approved field sample document
|
||||
- `MIN_ELIGIBLE_SAMPLES` after the baseline decision
|
||||
- `VULNERABILITY_PROVIDER_COMMAND` and `PROVENANCE_PROVIDER_COMMAND` for the
|
||||
@@ -441,6 +496,17 @@ Repository variables required by higher tiers:
|
||||
`PROVENANCE_PUBLIC_KEY_PATH`, and `PROVENANCE_KEY_ID` for separately managed
|
||||
trusted Ed25519 verification material
|
||||
|
||||
Advisories at or above the policy's `high` that `scan:dependency-advisories`
|
||||
reports for this lockfile, checked 2026-11-04 (review 1103/13-03). Check again
|
||||
by 2026-12-04 or when the update below is made. The development-only ones
|
||||
(storybook, vite, vitest, undici, brace-expansion, nanoid, source-map-js) were
|
||||
updated within their declared ranges and are gone.
|
||||
|
||||
| Advisory | Package | Fixed in | Why it is not updated yet |
|
||||
|---|---|---|---|
|
||||
| GHSA-mrhx-c7xc-m3w5 (high) | `zod` 4.4.3 (production) | 4.6.6 | A direct production upgrade needs a `config/security/dependency-change-evidence.json` entry whose reviewer is not its owner. 4.6.7 also adds about 7 KB gzip of initial JavaScript, over the bundle budget, so the update needs a budget decision as well. The app reads HTTP bodies with a byte limit, which narrows the large-collection input the advisory needs (review estimate) |
|
||||
| GHSA-qwww-vcr4-c8h2 (high) | `react-router` 7.18.1, through `react-router-dom` (production) | 7.18.2 | Same evidence rule. The advisory concerns RSC mode, which this browser-router SPA does not use (review estimate, not verified). 7.18.5 adds about 470 B of initial JavaScript |
|
||||
|
||||
두 provider role은 서로 다른 key ID뿐 아니라 canonical DER-SPKI public-key bytes도
|
||||
사용해야 한다. 동일 key를 서로 다른 ID로 재등록한 구성도 finalizer가 거절한다.
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
Performance evidence is deliberately split by measurement context:
|
||||
|
||||
- `bundle.json` records production build output and enforces initial JavaScript
|
||||
at 200 KiB gzip and every lazy chunk at 120 KiB gzip.
|
||||
at 200 KiB gzip, the number of initial JavaScript files (`initialJsFiles`),
|
||||
and every lazy chunk at 120 KiB gzip. A failure names each exceeded limit,
|
||||
the measured value and the excess (1103/15-03).
|
||||
- `lab.json` records Chromium/runner/viewport/network/CPU/cache/build context and
|
||||
enforces LCP 2.5 s, CLS 0.10, and the named route interaction at 200 ms.
|
||||
- `field-web-vitals.json` records consent-filtered, route-ID aggregated,
|
||||
@@ -12,23 +14,33 @@ Performance evidence is deliberately split by measurement context:
|
||||
|
||||
## 번들 예산의 기준선과 여유
|
||||
|
||||
리뷰 0925/13-14, 1101/15-02. 예산은 `config/performance/budgets.json`에 있고
|
||||
`scripts/check-bundle.ts`(FE-GATE-012, merge 단계)가 강제한다. 템플릿 기본
|
||||
화면만으로 초기 JS 예산의 98.9%를 쓴다. 첫 기능을 추가하기 전에 아래 숫자를
|
||||
리뷰 0925/13-14, 1101/15-02, 1103/15-02. 예산은 `config/performance/budgets.json`에
|
||||
있고 `scripts/check-bundle.ts`(FE-GATE-012, merge 단계)가 강제한다. 템플릿 기본
|
||||
화면만으로 초기 JS 예산의 대부분을 쓴다. 첫 기능을 추가하기 전에 아래 기록을
|
||||
보고 예산을 정한다.
|
||||
|
||||
| 항목 | 값 |
|
||||
기준선 숫자는 이 문서에 적지 않는다. 손으로 적은 숫자는 두 번 낡았다. 기록은
|
||||
`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다.
|
||||
|
||||
| 칸 | 뜻 |
|
||||
|---|---|
|
||||
| 초기 JS 예산 | 204,800 gzip bytes(200 KiB) |
|
||||
| 템플릿 기준선(2026-11-01, 커밋 `298201f`) | 202,509~202,522 gzip bytes, 16개 파일. local 프로필, `VITE_BUILD_ID`가 `local-build`일 때와 CI 모양(`gitea-<run>-<attempt>`)일 때다. 빌드 ID가 번들에 들어가므로 빌드마다 수십~수백 바이트 다르다 |
|
||||
| 여유 | 약 2,280 bytes(1.1%) |
|
||||
| 기능 하나를 더할 때 | 참조 기능 모양 복사본 하나에 약 +650~750 bytes(`298201f` 측정, 상한은 참조 기능과 함께 지워지는 tests/unit/feature-shape-growth.test.ts의 1 KiB). 기능 실행부(`feature-runtime.ts`)는 라우트에 들어갈 때 받는 lazy chunk다 |
|
||||
| lazy chunk 예산 | 파일마다 122,880 gzip bytes(120 KiB). 기준선의 lazy JS는 17개, 합계 28,204 bytes이고 가장 큰 것은 `use-reference-feature` 8,386 bytes다 |
|
||||
| `gzipBytes`, `files` | 템플릿 그대로의 초기 JS gzip bytes와 파일 수(entry 포함) |
|
||||
| `perFeatureGzipBytes` | 있는 context에 참조 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB |
|
||||
| `perContextGzipBytes` | 새 context를 하나 더할 때 느는 초기 JS. 상한 512 B |
|
||||
|
||||
- `tests/unit/feature-shape-growth.test.ts`(unit, merge 단계)가 매번 빌드해 이
|
||||
값을 재고, 상한을 넘거나 기록과 다르면(합계 1% 초과, 파일 수 불일치, 기능·
|
||||
context 비용 10% 초과) 실패한다. 실패 메시지에 잰 값이 나온다.
|
||||
- 기록을 고칠 때는 `node scripts/scale/measure-feature-shape-growth.ts
|
||||
--initial-baseline --write`를 돌리고 같은 변경에 넣는다.
|
||||
- 여유는 예산에서 `gzipBytes`를 뺀 값이다. 그것을 `perFeatureGzipBytes`로 나누면
|
||||
더 넣을 수 있는 기능 수다. 새 context마다 `perContextGzipBytes`가 더 든다.
|
||||
- 기능 실행부(`feature-runtime.ts`)는 라우트에 들어갈 때 받는 lazy chunk다.
|
||||
lazy chunk 예산은 파일마다 120 KiB(`lazyChunkGzipBytes`)다.
|
||||
|
||||
청크 이름으로 크기를 판단하지 않는다. rolldown은 공용 청크에 안에 든 모듈
|
||||
하나의 이름을 붙인다. 예를 들어 `render-boot-failure` 청크(58.6 KB)의 대부분은
|
||||
react-dom이고, `design-system` 청크(48.2 KB)에는 react-router가 들어 있다.
|
||||
아래는 출처별 크기다. sourcemap 빌드에서 minify된 바이트를 원래 모듈에 나눠
|
||||
하나의 이름을 붙인다. 아래는 2026-11-01(`298201f`)에 잰 출처별 크기다. 지금
|
||||
빌드와는 조금 다르다. sourcemap 빌드에서 minify된 바이트를 원래 모듈에 나눠
|
||||
붙이고 묶음마다 따로 gzip했다. 따로 압축하므로 합은 실제 합계와 조금 다르다.
|
||||
|
||||
| 출처 | minify bytes | 단독 gzip bytes |
|
||||
@@ -52,8 +64,7 @@ react-dom이고, `design-system` 청크(48.2 KB)에는 react-router가 들어
|
||||
(`scripts/lib/classify-vite-bundle.ts`). entry는 앱 그래프의 평가 실패를
|
||||
보고하려고 그 둘을 dynamic import로 읽을 뿐이고, 첫 화면에 항상 필요하다
|
||||
(0925/09-03). 그 밖의 dynamic import chunk는 lazy다.
|
||||
- 합계는 JavaScript만 센다. CSS(`index-*.css`, 8.6 KB gzip)는 예산에 들어가지
|
||||
않는다.
|
||||
- 합계는 JavaScript만 센다. CSS(`index-*.css`)는 예산에 들어가지 않는다.
|
||||
- gzip은 Node `zlib.gzipSync` 기본 수준(6)으로 잰다
|
||||
(`scripts/lib/release-candidate.ts`). 호스팅이 brotli로 보내면 전송 크기는 더
|
||||
작다. 예산은 gzip 기준 그대로 둔다.
|
||||
@@ -102,12 +113,12 @@ the example can never serve as production evidence.
|
||||
리뷰 1101/14.4. 08-08은 초기 JS 바이트를 줄이는 대신 초기 파일 수를 늘렸다
|
||||
(`vite.config.ts`의 `moduleSideEffects` 주석). HTTP/1.1에서 브라우저는 한
|
||||
호스트에 연결을 6개까지만 연다. 파일이 많으면 요청이 줄을 서서 왕복이 는다.
|
||||
그래서 지금 빌드와 작은 초기 청크를 하나로 묶은 빌드를 쟀다(2026-11-03,
|
||||
커밋 `ec7435c`).
|
||||
그래서 그때 빌드와 작은 초기 청크를 하나로 묶은 빌드를 쟀다(2026-11-03,
|
||||
커밋 `ec7435c`). 아래 두 표의 파일 수와 바이트는 그 커밋의 값이다.
|
||||
|
||||
| 빌드 | 초기 JS 파일(entry 포함) | 초기 JS gzip(B) | 첫 화면까지 JS 요청 | Fast 3G 첫 화면 | Fast 4G 첫 화면 |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| 지금 | 26 | 202,782 | 27 | 5,887 ms | 1,874 ms |
|
||||
| `ec7435c` | 26 | 202,782 | 27 | 5,887 ms | 1,874 ms |
|
||||
| (가) 08-08이 나눈 초기 primitive 청크 4개(`field`·`button`·`select`·`page-templates`)를 하나로 | 23 | 201,818 | 24 | 5,426 ms | 1,764 ms |
|
||||
| (나) 묶을 수 있는 초기 청크 14개를 하나로 | 13 | 198,673 | 14 | 4,930 ms | 1,535 ms |
|
||||
|
||||
@@ -116,7 +127,7 @@ the example can never serve as production evidence.
|
||||
|
||||
| 빌드 | Fast 3G 첫 화면 | Fast 4G 첫 화면 |
|
||||
|---|---:|---:|
|
||||
| 지금 | 4,793 ms | 1,444 ms |
|
||||
| `ec7435c` | 4,793 ms | 1,444 ms |
|
||||
| (가) | 4,769 ms | 1,440 ms |
|
||||
| (나) | 4,708 ms | 1,422 ms |
|
||||
|
||||
@@ -128,7 +139,7 @@ the example can never serve as production evidence.
|
||||
- 매번 새 browser context에서 캐시 없이 `/`를 연다. 첫 화면은 boot 셸이
|
||||
사라지고 `#main-content h1[data-route-heading]`가 DOM에 들어온 시각이다
|
||||
(`performance.now()`).
|
||||
- 세 빌드를 번갈아 7번씩 재고 중앙값을 적었다. 7번의 범위는 지금 5,866~6,077 ms,
|
||||
- 세 빌드를 번갈아 7번씩 재고 중앙값을 적었다. 7번의 범위는 `ec7435c` 5,866~6,077 ms,
|
||||
(가) 5,384~5,652 ms, (나) 4,891~5,032 ms다(Fast 3G). loadavg는 HTTP/1.1
|
||||
측정 때 6~20, HTTP/2 측정 때 3~6이었다. 그래서 두 표끼리는 비교하지 않는다.
|
||||
- CDP 지연은 요청마다 붙는다. 연결 수립(TCP·TLS) 비용은 따로 재지 않았다.
|
||||
@@ -154,6 +165,34 @@ the example can never serve as production evidence.
|
||||
버렸다.
|
||||
- HTTP/2에서는 (나)도 Fast 3G 85 ms, Fast 4G 22 ms 차이다(위 둘째 표).
|
||||
|
||||
그래서 템플릿은 HTTP/2 이상으로 서빙한다고 본다. HTTP/1.1로만 서빙해야 하는
|
||||
그래서 템플릿은 HTTP/2 이상으로 서빙한다고 본다. 초기 파일 수는
|
||||
`config/performance/budgets.json`의 `initialJsFiles`가 막는다(1103/15-05). 초기
|
||||
파일을 늘리는 변경은 그 값을 같이 고치고, 이유를 같은 변경에 적는다. HTTP/1.1로만 서빙해야 하는
|
||||
제품은 (나)처럼 초기 청크를 묶는 그룹을 `vite.config.ts`에 넣는다. 그 목록은
|
||||
셸을 바꿀 때마다 위 방법으로 다시 잰다.
|
||||
|
||||
## build id와 재방문 캐시
|
||||
|
||||
리뷰 1103/15-06(1101 O1, 0929/13-03). build id는 부트 실패 화면이 보여 주므로
|
||||
그 청크에 들어간다. 해시 자산은 1년 `immutable`로 캐시되지만, build id가 든
|
||||
청크와 그 청크를 import하는 청크는 release마다 이름이 바뀐다. react-dom이 그
|
||||
청크 안에 있을 때는 코드가 같아도 release마다 초기 JS의 절반을 다시 받았다.
|
||||
|
||||
판단: react-dom과 scheduler를 자기 청크(`vite.config.ts`의 `react-dom` 그룹)로
|
||||
뺀다. 2026-11-04 `VITE_BUILD_ID`만 다른 두 빌드(`gitea-101-1`, `gitea-102-1`)를
|
||||
비교했다.
|
||||
|
||||
| 빌드 | 이름이 바뀐 초기 파일 | 바뀐 초기 JS gzip(B) | 초기 JS gzip(B) | 초기 파일 |
|
||||
|---|---|---:|---:|---:|
|
||||
| 분리 전 | `boot`, `index`, `render-boot-failure` | 99,785 (49.4%) | 201,857 | 25 |
|
||||
| 분리 뒤 | `boot`, `index`, `render-boot-failure` | 44,297 (22.0%) | 201,552 | 25 |
|
||||
|
||||
- lazy 파일은 두 경우 모두 0 B 바뀐다.
|
||||
- 초기 파일 수는 그대로다. react-dom의 작은 진입 모듈(1.3 KB)이 같은 청크로
|
||||
합쳐졌다.
|
||||
- `boot`는 build id로 설정 문서를 대조하므로 계속 바뀐다. build id를 JS에 넣지
|
||||
않고 `release-manifest.json`에서만 읽으면 더 줄지만, 부트 실패 화면이 build
|
||||
id를 보여 주는 계약을 바꿔야 해서 하지 않았다.
|
||||
- 부트 실패 화면은 여전히 앱 그래프의 모듈 없이 그려진다(09-03,
|
||||
`tests/e2e/boot-module-failure.spec.ts`). 이름이 유지되는지는
|
||||
`tests/unit/build-environment-bundle.test.ts`가 본다.
|
||||
|
||||
@@ -85,6 +85,24 @@ evidence for this one (review 1101/13-01). That release is
|
||||
`<release-root>/dist` with `-- --release-root <extracted archive>` (FE-GATE-019
|
||||
passes the promoted archive), otherwise the local `dist`.
|
||||
|
||||
Those two names come from the CI run, so a release rebuilt in the same run
|
||||
carries them as well. The served `config.json` must therefore equal the
|
||||
release's `dist/config.json`, the document release admission (FE-GATE-027)
|
||||
admitted, in every field except the two emergency switches
|
||||
`CAPABILITY_OVERRIDES` and `FEATURE_OVERRIDES` (FE-RB-001), and the served
|
||||
`index.html` must name the release's entry script (review 1103/13-01).
|
||||
|
||||
The probe also checks the two serving premises the bundle budget and the split
|
||||
initial chunks rest on (review 1103/13-02): the entry script arrives with a
|
||||
`Content-Encoding` from `hashedAsset.contentEncodings` (the budget counts gzip
|
||||
bytes; uncompressed, the initial JavaScript is about three times larger), and
|
||||
the TLS handshake negotiates a protocol from `transport.alpnProtocols` (`h2`;
|
||||
over HTTP/1.1 the initial files queue for six connections). A host that cannot
|
||||
meet them fails FE-GATE-019; a product that has to serve that way changes the
|
||||
declaration in `config/hosting/cache-policy.json` in the same change that
|
||||
groups its initial chunks ("초기 청크 수와 HTTP/1.1" in
|
||||
[`performance-evidence.md`](performance-evidence.md)).
|
||||
|
||||
### Example: nginx on a single server
|
||||
|
||||
Written by hand for the default base path `/`; nothing in CI runs it. The live
|
||||
@@ -105,9 +123,18 @@ add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
# nginx 1.25.1 and later; before it, `listen 443 ssl http2;`.
|
||||
http2 on;
|
||||
server_name app.example.com;
|
||||
# ssl_certificate / ssl_certificate_key ...
|
||||
|
||||
# The bundle budget counts gzip bytes, and FE-GATE-019 fails an
|
||||
# uncompressed entry script (cache-policy.json `hashedAsset`). nginx
|
||||
# compresses only text/html unless gzip_types names the rest.
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_types text/javascript application/javascript application/json text/css image/svg+xml;
|
||||
|
||||
# The active release directory. Switch it with an atomic symlink rename.
|
||||
root /srv/frontend/current;
|
||||
|
||||
|
||||
+7
-6
@@ -23,6 +23,7 @@
|
||||
"check:backend-contract-drift": "node scripts/check-backend-contract-drift.ts",
|
||||
"check:remediation-ledger": "node scripts/check-remediation-ledger.ts",
|
||||
"check:release-admission": "node scripts/generate-product-feature-index.ts && node scripts/check-release-admission.ts",
|
||||
"scan:dependency-advisories": "node scripts/scan-dependency-advisories.ts",
|
||||
"check:diagnostics": "node scripts/generate-product-feature-index.ts && node scripts/check-diagnostics.ts",
|
||||
"check:diagnostics:fixture": "node scripts/generate-product-feature-index.ts && node scripts/check-diagnostics.ts --fixture",
|
||||
"check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test && corepack pnpm check:types:recipes && corepack pnpm check:types:web-worker && corepack pnpm check:types:service-worker",
|
||||
@@ -167,8 +168,8 @@
|
||||
"@babel/plugin-syntax-typescript": "8.0.3",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@playwright/test": "1.62.0",
|
||||
"@storybook/addon-a11y": "10.5.4",
|
||||
"@storybook/react-vite": "10.5.4",
|
||||
"@storybook/addon-a11y": "10.6.5",
|
||||
"@storybook/react-vite": "10.6.5",
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
"@testing-library/jest-dom": "7.0.0",
|
||||
"@testing-library/react": "16.3.2",
|
||||
@@ -177,17 +178,17 @@
|
||||
"@types/react": "19.2.8",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-react": "6.0.4",
|
||||
"@vitest/coverage-v8": "4.1.10",
|
||||
"@vitest/coverage-v8": "4.1.12",
|
||||
"dependency-cruiser": "18.1.0",
|
||||
"eslint": "10.8.0",
|
||||
"eslint-plugin-react-hooks": "7.1.1",
|
||||
"globals": "17.7.0",
|
||||
"jsdom": "29.1.1",
|
||||
"msw": "2.15.0",
|
||||
"storybook": "10.5.4",
|
||||
"storybook": "10.6.5",
|
||||
"tailwindcss": "4.3.3",
|
||||
"typescript": "7.0.2",
|
||||
"vite": "8.1.5",
|
||||
"vitest": "4.1.10"
|
||||
"vite": "8.1.6",
|
||||
"vitest": "4.1.12"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+272
-298
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"description": [
|
||||
"Review 1103/13-03: dependency security updates. The template had no update automation, so a known advisory stayed in every copy until someone ran pnpm audit by hand.",
|
||||
"Inert until a Renovate runner is attached to the Gitea instance; the release-stage signal is `corepack pnpm scan:dependency-advisories` (FE-GATE-027).",
|
||||
"Renovate regenerates pnpm-lock.yaml. A maintainer re-approves the dependency baseline in the same PR (`DEPENDENCY_BASELINE_OWNER=... DEPENDENCY_BASELINE_REASON=... corepack pnpm update:dependency-baseline`) and reviews the inventory diff before the PR can merge.",
|
||||
"Versions stay exact (pnpm-workspace.yaml saveExact) and a release must be a day old, the pnpm minimumReleaseAge default."
|
||||
],
|
||||
"extends": [
|
||||
"config:recommended",
|
||||
"security:only-security-updates"
|
||||
],
|
||||
"rangeStrategy": "pin",
|
||||
"minimumReleaseAge": "1 day",
|
||||
"vulnerabilityAlerts": {
|
||||
"description": "A vulnerability alert opens a security PR at once, ignoring the schedule.",
|
||||
"enabled": true,
|
||||
"labels": [
|
||||
"security",
|
||||
"dependencies"
|
||||
]
|
||||
},
|
||||
"osvVulnerabilityAlerts": true,
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "Every update is reviewed and merged by a person after the merge gates pass.",
|
||||
"matchUpdateTypes": [
|
||||
"patch",
|
||||
"pin",
|
||||
"digest",
|
||||
"minor",
|
||||
"major"
|
||||
],
|
||||
"automerge": false
|
||||
}
|
||||
]
|
||||
}
|
||||
+48
-9
@@ -1,6 +1,9 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { evaluateBundleBudget } from "./lib/performance-budgets.ts";
|
||||
import {
|
||||
describeBundleBudgetFailures,
|
||||
evaluateBundleBudget,
|
||||
} from "./lib/performance-budgets.ts";
|
||||
import {
|
||||
bundleOutputInventoryArtifactSchema,
|
||||
bundlePerformanceArtifactSchema,
|
||||
@@ -14,6 +17,7 @@ type ViteManifest = Record<
|
||||
>;
|
||||
type BundleBudgets = {
|
||||
initialJsGzipBytes: number;
|
||||
initialJsFiles: number;
|
||||
lazyChunkGzipBytes: number;
|
||||
};
|
||||
|
||||
@@ -43,7 +47,11 @@ const missingOutputs = [
|
||||
...classification.initialFiles,
|
||||
...classification.lazyFiles,
|
||||
].filter((file) => !outputByPath.has(file));
|
||||
const measurements = { initialJsGzipBytes, lazyChunks };
|
||||
const measurements = {
|
||||
initialJsGzipBytes,
|
||||
initialJsFiles: classification.initialFiles.length,
|
||||
lazyChunks,
|
||||
};
|
||||
const result = evaluateBundleBudget(measurements, budgets);
|
||||
const fixtures = [
|
||||
{
|
||||
@@ -52,6 +60,7 @@ const fixtures = [
|
||||
!evaluateBundleBudget(
|
||||
{
|
||||
initialJsGzipBytes: budgets.initialJsGzipBytes + 1,
|
||||
initialJsFiles: 0,
|
||||
lazyChunks: [],
|
||||
},
|
||||
budgets,
|
||||
@@ -63,6 +72,7 @@ const fixtures = [
|
||||
!evaluateBundleBudget(
|
||||
{
|
||||
initialJsGzipBytes: 0,
|
||||
initialJsFiles: 0,
|
||||
lazyChunks: [
|
||||
{
|
||||
path: "fixture.js",
|
||||
@@ -73,6 +83,18 @@ const fixtures = [
|
||||
budgets,
|
||||
).passed,
|
||||
},
|
||||
{
|
||||
name: "initial-files-over-budget",
|
||||
passed:
|
||||
!evaluateBundleBudget(
|
||||
{
|
||||
initialJsGzipBytes: 0,
|
||||
initialJsFiles: budgets.initialJsFiles + 1,
|
||||
lazyChunks: [],
|
||||
},
|
||||
budgets,
|
||||
).passed,
|
||||
},
|
||||
];
|
||||
const passed =
|
||||
result.passed &&
|
||||
@@ -95,15 +117,32 @@ await writeValidatedJsonArtifact({
|
||||
schema: bundlePerformanceArtifactSchema,
|
||||
value: completedReport,
|
||||
});
|
||||
// 1103/15-03. The budget and the manifest integrity fail for different
|
||||
// reasons, so each says what failed and by how much.
|
||||
if (!passed) {
|
||||
process.stderr.write(
|
||||
`Bundle budget or manifest integrity failed: ${[
|
||||
...classification.missingImports,
|
||||
...missingOutputs,
|
||||
].join(", ")}\n`,
|
||||
);
|
||||
const budgetFailures = describeBundleBudgetFailures(measurements, budgets);
|
||||
if (budgetFailures.length > 0) {
|
||||
process.stderr.write(
|
||||
`Bundle budget failed (config/performance/budgets.json):\n${budgetFailures
|
||||
.map((line) => ` ${line}\n`)
|
||||
.join("")}`,
|
||||
);
|
||||
}
|
||||
const integrityFailures = [
|
||||
...classification.missingImports.map((key) => `manifest import without an entry: ${key}`),
|
||||
...missingOutputs.map((file) => `output missing from the inventory: ${file}`),
|
||||
...fixtures
|
||||
.filter((fixture) => !fixture.passed)
|
||||
.map((fixture) => `budget self-check did not fail: ${fixture.name}`),
|
||||
];
|
||||
if (integrityFailures.length > 0) {
|
||||
process.stderr.write(
|
||||
`Bundle manifest integrity failed:\n${integrityFailures.map((line) => ` ${line}\n`).join("")}`,
|
||||
);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
process.stdout.write(
|
||||
`Bundle budget: PASS (initial JS ${initialJsGzipBytes} / ${budgets.initialJsGzipBytes} gzip bytes)\n`,
|
||||
`Bundle budget: PASS (initial JS ${initialJsGzipBytes} / ${budgets.initialJsGzipBytes} gzip bytes, ` +
|
||||
`${measurements.initialJsFiles} / ${budgets.initialJsFiles} files)\n`,
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
renderCiWorkflow,
|
||||
workflowGateExecutionFailures,
|
||||
} from "./generate-ci-workflow.ts";
|
||||
import { loadProductCiOverlay } from "./contracts/product-ci-overlay.ts";
|
||||
import {
|
||||
ciContractReportSchema,
|
||||
} from "./lib/ci-contract-report.ts";
|
||||
@@ -40,6 +41,9 @@ import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
|
||||
const contract = await loadCiGateContract(process.cwd());
|
||||
const index = indexCiGateContract(contract);
|
||||
// 1103/12-07. The product's merge gates are entry scripts of CI as well.
|
||||
const { mergeGates: productGates } = await loadProductCiOverlay(process.cwd());
|
||||
const productGateScripts = productGates.map(({ script }) => script);
|
||||
const [packageDocument, nodeVersion] = await Promise.all([
|
||||
readFile("package.json", "utf8").then((value) => JSON.parse(value) as { scripts?: Record<string, string> }),
|
||||
readFile(".nvmrc", "utf8").then((value) => value.trim()),
|
||||
@@ -85,7 +89,7 @@ try {
|
||||
testFiles: await listTestFiles(process.cwd()),
|
||||
gatedPaths: gatedTestPaths(
|
||||
packageScripts,
|
||||
contract.commands.map(({ script }) => script),
|
||||
[...contract.commands.map(({ script }) => script), ...productGateScripts],
|
||||
(file) => readFileSync(file, "utf8"),
|
||||
),
|
||||
exclusions: parseUngatedTestExclusions(
|
||||
@@ -100,7 +104,7 @@ try {
|
||||
// 12-04: every verification package script is reached by a gate, or
|
||||
// config/ci/ungated-scripts.json says why not.
|
||||
try {
|
||||
const entryScripts = contract.commands.map(({ script }) => script);
|
||||
const entryScripts = [...contract.commands.map(({ script }) => script), ...productGateScripts];
|
||||
failures.push(
|
||||
...ungatedScriptFailures({
|
||||
scripts: packageScripts,
|
||||
@@ -148,10 +152,11 @@ for (const readiness of Object.keys(PROMOTION_FORMULA) as Array<keyof typeof PRO
|
||||
}
|
||||
if (!Object.values(allPass).every(Boolean)) failures.push("all-PASS formula did not produce every readiness state");
|
||||
|
||||
const renderedWorkflow = renderCiWorkflow(contract);
|
||||
const renderedWorkflow = renderCiWorkflow(contract, productGates);
|
||||
const workflowCheck = await generateCiWorkflow({
|
||||
root: process.cwd(),
|
||||
contract,
|
||||
productGates,
|
||||
check: true,
|
||||
});
|
||||
if (!workflowCheck.matches) {
|
||||
@@ -165,7 +170,9 @@ try {
|
||||
} catch (error) {
|
||||
failures.push(`generated workflow is unreadable: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
failures.push(...workflowGateExecutionFailures(contract, checkedWorkflowBytes.toString("utf8")));
|
||||
failures.push(
|
||||
...workflowGateExecutionFailures(contract, checkedWorkflowBytes.toString("utf8"), productGates),
|
||||
);
|
||||
const report = ciContractReportSchema.parse({
|
||||
schemaVersion: 2,
|
||||
nodeVersion,
|
||||
|
||||
@@ -12,6 +12,10 @@ import { unknownProductFeatureOverrides } from "../src/contracts/product-feature
|
||||
import { parseRuntimeConfigArtifact } from "../src/contracts/release-artifacts.ts";
|
||||
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts";
|
||||
import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-manifest.ts";
|
||||
import {
|
||||
changedRuntimeConfigBuildFields,
|
||||
RUNTIME_CONFIG_EMERGENCY_SWITCHES,
|
||||
} from "./lib/runtime-config-switches.ts";
|
||||
|
||||
/**
|
||||
* §6.4 / FE-GATE-027. Refuses to admit an artifact to an environment it was not
|
||||
@@ -30,17 +34,7 @@ import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-
|
||||
|
||||
const RUNTIME_CONFIG_PATH = "dist/config.json";
|
||||
const RECORD_PATH = "artifacts/release/deployment-admission.json";
|
||||
|
||||
/**
|
||||
* 1101/13-05. The only fields an operator may change in a deployed config.json
|
||||
* without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to
|
||||
* the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and
|
||||
* release manifest, or every boot stops with CONFIG_BUILD_MISMATCH.
|
||||
*/
|
||||
const EMERGENCY_SWITCHES: ReadonlySet<string> = new Set([
|
||||
"CAPABILITY_OVERRIDES",
|
||||
"FEATURE_OVERRIDES",
|
||||
]);
|
||||
const EMERGENCY_SWITCHES = RUNTIME_CONFIG_EMERGENCY_SWITCHES;
|
||||
|
||||
function refuse(reason: string): void {
|
||||
process.stderr.write(`release admission refused: ${reason}\n`);
|
||||
@@ -67,18 +61,6 @@ async function readRuntimeConfig(file: string): Promise<AdmissionInput | null> {
|
||||
}
|
||||
}
|
||||
|
||||
function changedBuildFields(original: object, edited: object): string[] {
|
||||
const before = new Map(Object.entries(original));
|
||||
const after = new Map(Object.entries(edited));
|
||||
return [...new Set([...before.keys(), ...after.keys()])]
|
||||
.filter(
|
||||
(field) =>
|
||||
!EMERGENCY_SWITCHES.has(field) &&
|
||||
JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)),
|
||||
)
|
||||
.sort();
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
// `pnpm check:release-admission -- --config …` may pass the separator through.
|
||||
const argv = process.argv.slice(2);
|
||||
@@ -127,7 +109,7 @@ async function main(): Promise<void> {
|
||||
if (options.original !== undefined) {
|
||||
const original = await readRuntimeConfig(options.original);
|
||||
if (original === null) return;
|
||||
const changed = changedBuildFields(original, config);
|
||||
const changed = changedRuntimeConfigBuildFields(original, config);
|
||||
if (changed.length > 0) {
|
||||
refuse(
|
||||
`${configPath} changes ${changed.join(", ")}; without a rebuild only ` +
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
validateNpmScopeEnvironment,
|
||||
validatePackageScriptGraph,
|
||||
} from "../lib/package-script-graph.ts";
|
||||
import { loadProductCiOverlay, withProductDeployment } from "./product-ci-overlay.ts";
|
||||
import { PROMOTED_UPLOAD_PATHS } from "./promotion-artifacts.ts";
|
||||
|
||||
const ciActionRegistrationSchema = z
|
||||
@@ -583,20 +584,30 @@ export function parseCiGateContract(value: unknown): CiGateContract {
|
||||
export async function loadCiGateContract(
|
||||
root = process.cwd(),
|
||||
): Promise<CiGateContract> {
|
||||
const [rawContract, rawPackage] = await Promise.all([
|
||||
const [rawContract, rawPackage, overlay] = await Promise.all([
|
||||
readFile(path.join(root, "config/ci/gates.json"), "utf8"),
|
||||
readFile(path.join(root, "package.json"), "utf8"),
|
||||
loadProductCiOverlay(root),
|
||||
]);
|
||||
const contract = parseCiGateContract(JSON.parse(rawContract));
|
||||
const template = parseCiGateContract(JSON.parse(rawContract));
|
||||
// 1103/12-07. The product fills the deployment slot in its own overlay; the
|
||||
// filled contract is parsed again, so the template's slot rules hold.
|
||||
const contract = overlay.deployment === null
|
||||
? template
|
||||
: parseCiGateContract(withProductDeployment(JSON.parse(rawContract), overlay.deployment));
|
||||
const packageDocument = z
|
||||
.object({ scripts: z.record(z.string(), z.string()).default({}) })
|
||||
.passthrough()
|
||||
.parse(JSON.parse(rawPackage));
|
||||
// 1101/13-01. A filled deployment slot runs a package script in CI, under the
|
||||
// same existence and script-graph rules as a gate command.
|
||||
const deployScripts = contract.jobs.flatMap(({ steps }) =>
|
||||
steps.flatMap((step) => (step.kind === "deploy" && step.script ? [step.script] : [])),
|
||||
);
|
||||
// same existence and script-graph rules as a gate command. So does a
|
||||
// product merge gate (1103/12-07).
|
||||
const deployScripts = [
|
||||
...contract.jobs.flatMap(({ steps }) =>
|
||||
steps.flatMap((step) => (step.kind === "deploy" && step.script ? [step.script] : [])),
|
||||
),
|
||||
...overlay.mergeGates.map(({ script }) => script),
|
||||
];
|
||||
const missing = [...contract.commands.map((command) => command.script), ...deployScripts]
|
||||
.filter((script, index, scripts) => scripts.indexOf(script) === index)
|
||||
.filter((script) => !packageDocument.scripts[script]);
|
||||
@@ -643,7 +654,8 @@ export async function loadCiGateContract(
|
||||
`CI package script install policy invalid:\n${installPolicyFailures.join("\n")}`,
|
||||
);
|
||||
}
|
||||
await assertCiContractBaseline(root, contract);
|
||||
// The baseline describes the template contract; the overlay is the product's.
|
||||
await assertCiContractBaseline(root, template);
|
||||
return contract;
|
||||
}
|
||||
|
||||
@@ -1027,6 +1039,7 @@ function validateContractSemantics(
|
||||
if (duplicate || foreign.length > 0) {
|
||||
issue(`deployment slot binding must be the candidate digest or a vars.* or secrets.* value: ${job.id}`);
|
||||
}
|
||||
for (const failure of deploymentSlotInputFailures(job)) issue(failure);
|
||||
} else if (duplicate || JSON.stringify(job.environment) !== JSON.stringify(expectedEnvironmentBindings[job.id])) {
|
||||
issue(`job environment binding drift: ${job.id}`);
|
||||
}
|
||||
@@ -1244,6 +1257,47 @@ function validateCanonicalStepFields(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/13-01. A slot that runs a deploy script deploys the promoted candidate:
|
||||
* it downloads the promoted-release transfer and extracts its
|
||||
* release-candidate.tar.gz, checked against the digest immutable_build
|
||||
* recorded, before the script runs. A slot that rebuilt instead passed the
|
||||
* contract under the name deploy-promoted-release, and FE-GATE-019 could not
|
||||
* tell the rebuild from the candidate.
|
||||
*/
|
||||
function deploymentSlotInputFailures(job: z.infer<typeof jobSchema>): string[] {
|
||||
const deploy = job.steps.find((step) => step.kind === "deploy");
|
||||
if (deploy?.kind !== "deploy" || deploy.script === undefined) return [];
|
||||
const failures: string[] = [];
|
||||
const downloads = job.steps.filter((step) => step.kind === "download");
|
||||
const download = downloads[0];
|
||||
const extract = job.steps.find((step) => step.kind === "extract");
|
||||
if (
|
||||
downloads.length !== 1 ||
|
||||
download?.kind !== "download" ||
|
||||
download.transferId !== "promoted-release" ||
|
||||
extract?.kind !== "extract" ||
|
||||
extract.archivePath !== `${download.path}/release-candidate.tar.gz` ||
|
||||
job.steps.indexOf(download) > job.steps.indexOf(extract)
|
||||
) {
|
||||
failures.push(
|
||||
`deployment slot with a deploy script must download only the promoted-release transfer and extract its release-candidate.tar.gz before deploying: ${job.id}`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!job.environment.some(
|
||||
({ name, value }) =>
|
||||
name === "CANDIDATE_ARCHIVE_SHA256" &&
|
||||
value === "${{ needs.immutable_build.outputs.archive_sha256 }}",
|
||||
)
|
||||
) {
|
||||
failures.push(
|
||||
`deployment slot with a deploy script must bind CANDIDATE_ARCHIVE_SHA256 so its extract step checks the promoted archive: ${job.id}`,
|
||||
);
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
function validateJobStepKinds(
|
||||
job: z.infer<typeof jobSchema>,
|
||||
issue: (message: string, path?: PropertyKey[]) => void,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* 1103/12-07. The product's own part of CI, kept out of the template-owned
|
||||
* config/ci/gates.json so a template sync never meets it. The template ships
|
||||
* this file empty and does not change it. It may hold only:
|
||||
*
|
||||
* - `deployment`: the package script that deploys the promoted release, and
|
||||
* its `vars.*` / `secrets.*` bindings. The template renders the rest of the
|
||||
* slot (download the promoted-release transfer, extract it against the
|
||||
* candidate digest, then run the script); secrets reach the deploy step only
|
||||
* (1103/13-05).
|
||||
* - `mergeGates`: product checks that run on every merge-stage run, in a job
|
||||
* of their own (`product_merge_gate`). Their ids are `PRODUCT-GATE-NNN`, so
|
||||
* they never take or change a template gate (`FE-GATE-NNN`), its commands,
|
||||
* artifacts or readiness formula. The template contract baseline counts
|
||||
* only the template contract.
|
||||
*/
|
||||
export const PRODUCT_CI_OVERLAY_PATH = "config/ci/product-gates.json";
|
||||
|
||||
const scriptName = z
|
||||
.string()
|
||||
.max(128)
|
||||
.regex(/^[A-Za-z0-9:_-]+$/u, "a product script is a package script name ([A-Za-z0-9:_-])");
|
||||
const binding = z
|
||||
.object({
|
||||
name: z.string().regex(/^[A-Z][A-Z0-9_]*$/u),
|
||||
value: z
|
||||
.string()
|
||||
.regex(
|
||||
/^\$\{\{ (?:vars|secrets)\.[A-Za-z_][A-Za-z0-9_]* \}\}$/u,
|
||||
"a product binding must be a vars.* or secrets.* value",
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
const productGate = z
|
||||
.object({
|
||||
id: z
|
||||
.string()
|
||||
.regex(/^PRODUCT-GATE-\d{3}$/u, "product gate ids are PRODUCT-GATE-NNN; FE-GATE-NNN ids belong to the template"),
|
||||
name: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/u),
|
||||
script: scriptName,
|
||||
})
|
||||
.strict();
|
||||
|
||||
const productCiOverlaySchema = z
|
||||
.object({
|
||||
schemaVersion: z.literal(1),
|
||||
deployment: z
|
||||
.object({ script: scriptName, environment: z.array(binding).max(32) })
|
||||
.strict()
|
||||
.nullable(),
|
||||
mergeGates: z.array(productGate).max(32),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((overlay, context) => {
|
||||
const issue = (message: string) => context.addIssue({ code: "custom", message });
|
||||
const names = overlay.deployment?.environment.map(({ name }) => name) ?? [];
|
||||
if (new Set(names).size !== names.length) issue("duplicate deployment binding name");
|
||||
if (names.includes("CANDIDATE_ARCHIVE_SHA256")) {
|
||||
issue("CANDIDATE_ARCHIVE_SHA256 is bound by the template to the immutable_build digest");
|
||||
}
|
||||
for (const field of ["id", "name"] as const) {
|
||||
const values = overlay.mergeGates.map((gate) => gate[field]);
|
||||
if (new Set(values).size !== values.length) issue(`duplicate product gate ${field}`);
|
||||
}
|
||||
});
|
||||
|
||||
export type ProductCiOverlay = z.infer<typeof productCiOverlaySchema>;
|
||||
export type ProductDeployment = NonNullable<ProductCiOverlay["deployment"]>;
|
||||
export type ProductGate = ProductCiOverlay["mergeGates"][number];
|
||||
|
||||
const EMPTY_PRODUCT_CI_OVERLAY: ProductCiOverlay = Object.freeze({
|
||||
schemaVersion: 1,
|
||||
deployment: null,
|
||||
mergeGates: [],
|
||||
});
|
||||
|
||||
export function parseProductCiOverlay(value: unknown): ProductCiOverlay {
|
||||
const result = productCiOverlaySchema.safeParse(value);
|
||||
if (!result.success) {
|
||||
throw new TypeError(
|
||||
`${PRODUCT_CI_OVERLAY_PATH} invalid:\n${result.error.issues
|
||||
.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`)
|
||||
.join("\n")}`,
|
||||
);
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
/** The overlay of `root`; a checkout without the file (synced before it existed) has none. */
|
||||
export async function loadProductCiOverlay(root: string): Promise<ProductCiOverlay> {
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(path.join(root, PRODUCT_CI_OVERLAY_PATH), "utf8");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return EMPTY_PRODUCT_CI_OVERLAY;
|
||||
throw error;
|
||||
}
|
||||
return parseProductCiOverlay(JSON.parse(text));
|
||||
}
|
||||
|
||||
const PROMOTED_DOWNLOAD_PATH = ".release/deployment";
|
||||
/** Where the slot extracts the promoted archive; the deploy script uploads `<this>/dist`. */
|
||||
export const PROMOTED_RELEASE_ROOT = ".release/promoted-release";
|
||||
|
||||
/**
|
||||
* The template contract document with its empty deployment slot filled from
|
||||
* the overlay. The caller parses the result, so the slot rules of the
|
||||
* template contract still apply. A slot the template contract already
|
||||
* filled is refused: the slot has one owner.
|
||||
*/
|
||||
export function withProductDeployment(contract: unknown, deployment: ProductDeployment): unknown {
|
||||
const document = structuredClone(contract) as { jobs?: { id?: unknown; steps?: unknown; environment?: unknown }[] };
|
||||
const slot = document.jobs?.find(({ id }) => id === "deployment");
|
||||
if (
|
||||
!slot ||
|
||||
JSON.stringify(slot.steps) !== JSON.stringify([{ kind: "deploy" }]) ||
|
||||
JSON.stringify(slot.environment) !== "[]"
|
||||
) {
|
||||
throw new TypeError(
|
||||
`the deployment slot is filled in config/ci/gates.json and in ${PRODUCT_CI_OVERLAY_PATH}; ` +
|
||||
`keep the template slot empty and fill ${PRODUCT_CI_OVERLAY_PATH}`,
|
||||
);
|
||||
}
|
||||
slot.environment = [
|
||||
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
||||
...deployment.environment,
|
||||
];
|
||||
slot.steps = [
|
||||
{ kind: "checkout" },
|
||||
{ kind: "setup-node" },
|
||||
{ kind: "frozen-install" },
|
||||
{ kind: "download", transferId: "promoted-release", path: PROMOTED_DOWNLOAD_PATH },
|
||||
{
|
||||
kind: "extract",
|
||||
archivePath: `${PROMOTED_DOWNLOAD_PATH}/release-candidate.tar.gz`,
|
||||
targetRoot: PROMOTED_RELEASE_ROOT,
|
||||
},
|
||||
{ kind: "deploy", script: deployment.script },
|
||||
];
|
||||
return document;
|
||||
}
|
||||
@@ -364,12 +364,14 @@ const bundleClassificationSchema = z
|
||||
const bundleThresholdsSchema = z
|
||||
.object({
|
||||
initialJsGzipBytes: z.int().positive(),
|
||||
initialJsFiles: z.int().positive(),
|
||||
lazyChunkGzipBytes: z.int().positive(),
|
||||
})
|
||||
.strict();
|
||||
const bundleBudgetResultSchema = z
|
||||
.object({
|
||||
initialPassed: z.boolean(),
|
||||
initialFilesPassed: z.boolean(),
|
||||
lazyResults: z.array(
|
||||
bundleMeasurementSchema.extend({
|
||||
threshold: z.int().positive(),
|
||||
@@ -386,6 +388,7 @@ export const bundlePerformanceArtifactSchema = z
|
||||
measurements: z
|
||||
.object({
|
||||
initialJsGzipBytes: z.int().nonnegative(),
|
||||
initialJsFiles: z.int().nonnegative(),
|
||||
lazyChunks: z.array(bundleMeasurementSchema),
|
||||
})
|
||||
.strict(),
|
||||
@@ -396,6 +399,7 @@ export const bundlePerformanceArtifactSchema = z
|
||||
fixtures: z.tuple([
|
||||
z.object({ name: z.literal("initial-js-over-budget"), passed: z.boolean() }).strict(),
|
||||
z.object({ name: z.literal("lazy-chunk-over-budget"), passed: z.boolean() }).strict(),
|
||||
z.object({ name: z.literal("initial-files-over-budget"), passed: z.boolean() }).strict(),
|
||||
]),
|
||||
passed: z.boolean(),
|
||||
})
|
||||
@@ -441,6 +445,9 @@ export const bundlePerformanceArtifactSchema = z
|
||||
if (artifact.measurements.initialJsGzipBytes !== expectedInitialBytes) {
|
||||
issue(["measurements", "initialJsGzipBytes"], "must equal classified initial output bytes");
|
||||
}
|
||||
if (artifact.measurements.initialJsFiles !== artifact.classification.initialFiles.length) {
|
||||
issue(["measurements", "initialJsFiles"], "must equal the classified initial file count");
|
||||
}
|
||||
const expectedLazyChunks = artifact.classification.lazyFiles.map((file) => ({
|
||||
path: file,
|
||||
gzipBytes: outputs.get(file)?.gzipBytes ?? 0,
|
||||
@@ -453,6 +460,11 @@ export const bundlePerformanceArtifactSchema = z
|
||||
if (artifact.results.initialPassed !== expectedInitialPassed) {
|
||||
issue(["results", "initialPassed"], "must agree with initial threshold");
|
||||
}
|
||||
const expectedInitialFilesPassed =
|
||||
artifact.measurements.initialJsFiles <= artifact.thresholds.initialJsFiles;
|
||||
if (artifact.results.initialFilesPassed !== expectedInitialFilesPassed) {
|
||||
issue(["results", "initialFilesPassed"], "must agree with the initial file threshold");
|
||||
}
|
||||
const expectedLazyResults = artifact.measurements.lazyChunks.map((chunk) => ({
|
||||
...chunk,
|
||||
threshold: artifact.thresholds.lazyChunkGzipBytes,
|
||||
@@ -462,7 +474,9 @@ export const bundlePerformanceArtifactSchema = z
|
||||
issue(["results", "lazyResults"], "must agree with lazy measurements and threshold");
|
||||
}
|
||||
const expectedBudgetPassed =
|
||||
expectedInitialPassed && expectedLazyResults.every(({ passed }) => passed);
|
||||
expectedInitialPassed &&
|
||||
expectedInitialFilesPassed &&
|
||||
expectedLazyResults.every(({ passed }) => passed);
|
||||
if (artifact.results.passed !== expectedBudgetPassed) {
|
||||
issue(["results", "passed"], "must agree with budget results");
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type CiWorkflowJob,
|
||||
type CiWorkflowStep,
|
||||
} from "./contracts/ci-gates.ts";
|
||||
import { loadProductCiOverlay, type ProductGate } from "./contracts/product-ci-overlay.ts";
|
||||
import {
|
||||
assertSafeExistingPublishPath,
|
||||
assertSafePublishLeaf,
|
||||
@@ -28,6 +29,8 @@ import { VISUAL_TEST_FONT_INSTALL_ARGUMENTS } from "./lib/visual-test-fonts.ts";
|
||||
export type GenerateCiWorkflowOptions = Readonly<{
|
||||
root: string;
|
||||
contract?: CiGateContract;
|
||||
/** Product merge gates; read from the root's config/ci/product-gates.json when omitted. */
|
||||
productGates?: readonly ProductGate[];
|
||||
check: boolean;
|
||||
}>;
|
||||
|
||||
@@ -62,7 +65,10 @@ const defaultFileSystem: CiWorkflowFileSystem = Object.freeze({
|
||||
rm: async (target) => rm(target, { force: true }),
|
||||
});
|
||||
|
||||
export function renderCiWorkflow(contract: CiGateContract): string {
|
||||
export function renderCiWorkflow(
|
||||
contract: CiGateContract,
|
||||
productGates: readonly ProductGate[] = [],
|
||||
): string {
|
||||
const index = indexCiGateContract(contract);
|
||||
const transfers = new Map<string, { name: string }>();
|
||||
for (const job of contract.jobs) {
|
||||
@@ -109,9 +115,48 @@ export function renderCiWorkflow(contract: CiGateContract): string {
|
||||
if (jobIndex > 0) lines.push("");
|
||||
lines.push(...renderJob(job, index, transfers));
|
||||
}
|
||||
if (productGates.length > 0) lines.push("", ...renderProductGateJob(productGates));
|
||||
return `${lines.join("\n").replace(/\n+$/u, "")}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/12-07. The product's merge gates (config/ci/product-gates.json) run in
|
||||
* a job after every template job, on the same merge condition. A product gate
|
||||
* is one package script; it has no log artifact or evidence of the template
|
||||
* gate contract and is not part of its readiness formula, so the product makes
|
||||
* this job a required check where it wants it to block a merge.
|
||||
*/
|
||||
function renderProductGateJob(productGates: readonly ProductGate[]): string[] {
|
||||
return [
|
||||
" product_merge_gate:",
|
||||
` name: ${yamlScalar("${{ matrix.gate }} / ${{ matrix.name }}")}`,
|
||||
` if: ${renderCondition("merge")}`,
|
||||
" runs-on: ubuntu-latest",
|
||||
" timeout-minutes: 45",
|
||||
" strategy:",
|
||||
" fail-fast: false",
|
||||
" matrix:",
|
||||
" include:",
|
||||
...productGates.map(
|
||||
(gate) => ` - { gate: ${gate.id}, name: ${gate.name}, script: ${yamlScalar(gate.script)} }`,
|
||||
),
|
||||
" steps:",
|
||||
` - uses: ${requiredStepActionUses("checkout")}`,
|
||||
" with:",
|
||||
" persist-credentials: false",
|
||||
` - uses: ${requiredStepActionUses("setup-node")}`,
|
||||
" with:",
|
||||
" node-version-file: .nvmrc",
|
||||
" - name: Frozen install",
|
||||
" run: |",
|
||||
" corepack enable",
|
||||
" corepack pnpm install --frozen-lockfile --ignore-scripts",
|
||||
// The overlay limits the script to [A-Za-z0-9:_-], a plain shell word.
|
||||
" - name: Run product gate",
|
||||
" run: corepack pnpm ${{ matrix.script }}",
|
||||
];
|
||||
}
|
||||
|
||||
function renderJob(
|
||||
job: CiWorkflowJob,
|
||||
index: ReturnType<typeof indexCiGateContract>,
|
||||
@@ -145,9 +190,10 @@ function renderJob(
|
||||
if (job.kind === "deployment") {
|
||||
lines.push(" outputs:", " deployed: ${{ steps.deploy.outputs.deployed }}");
|
||||
}
|
||||
if (job.environment.length > 0) {
|
||||
const jobEnvironment = job.environment.filter((binding) => !isStepScopedSecret(job, binding));
|
||||
if (jobEnvironment.length > 0) {
|
||||
lines.push(" env:");
|
||||
for (const binding of job.environment) {
|
||||
for (const binding of jobEnvironment) {
|
||||
lines.push(` ${binding.name}: ${yamlScalar(binding.value)}`);
|
||||
}
|
||||
}
|
||||
@@ -282,11 +328,15 @@ function renderStep(
|
||||
];
|
||||
// 1101/13-01. `run` fails on the first failing command, so deployed=true
|
||||
// is written only after the project's script succeeded.
|
||||
case "deploy":
|
||||
case "deploy": {
|
||||
const secrets = job.environment.filter((binding) => isStepScopedSecret(job, binding));
|
||||
return step.script
|
||||
? [
|
||||
" - name: Deploy the promoted release",
|
||||
" id: deploy",
|
||||
...(secrets.length > 0
|
||||
? [" env:", ...secrets.map((binding) => ` ${binding.name}: ${yamlScalar(binding.value)}`)]
|
||||
: []),
|
||||
" run: |",
|
||||
// The contract limits the name to [A-Za-z0-9:_-], a plain shell word.
|
||||
` corepack pnpm ${step.script}`,
|
||||
@@ -297,6 +347,7 @@ function renderStep(
|
||||
" id: deploy",
|
||||
' run: echo "deployed=false" >> "$GITHUB_OUTPUT"',
|
||||
];
|
||||
}
|
||||
case "upload": {
|
||||
const lines = [
|
||||
` - name: Upload ${humanize(step.transferId)}`,
|
||||
@@ -316,6 +367,16 @@ function renderStep(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/13-05. Job env reaches every step of the job: checkout, setup-node and
|
||||
* the third-party download action as well. In the deployment slot a
|
||||
* `secrets.*` binding is rendered on the deploy step instead, the one step
|
||||
* that uses it.
|
||||
*/
|
||||
function isStepScopedSecret(job: CiWorkflowJob, binding: CiWorkflowJob["environment"][number]): boolean {
|
||||
return job.kind === "deployment" && /^\$\{\{ secrets\./u.test(binding.value);
|
||||
}
|
||||
|
||||
function requiredStepActionUses(stepKind: string): string {
|
||||
const uses = resolveCiStepActionUses(stepKind);
|
||||
if (!uses) throw new TypeError(`workflow step has no registered CI action: ${stepKind}`);
|
||||
@@ -393,9 +454,22 @@ function runGateStepName(jobId: string, gateId: string): string {
|
||||
export function workflowGateExecutionFailures(
|
||||
contract: CiGateContract,
|
||||
workflow: string,
|
||||
productGates: readonly ProductGate[] = [],
|
||||
): string[] {
|
||||
const executed = new Set<string>();
|
||||
for (const job of workflow.split(/^(?= {2}[a-z_]+:$)/mu)) {
|
||||
const jobs = workflow.split(/^(?= {2}[a-z_]+:$)/mu);
|
||||
const productJob = jobs.find((job) => job.startsWith(" product_merge_gate:\n")) ?? "";
|
||||
const productRuns = /^ {8}run: corepack pnpm \$\{\{ matrix\.script \}\}$/mu.test(productJob);
|
||||
const productFailures = productGates
|
||||
.filter(
|
||||
(gate) =>
|
||||
!productRuns ||
|
||||
!productJob.includes(
|
||||
` - { gate: ${gate.id}, name: ${gate.name}, script: ${yamlScalar(gate.script)} }\n`,
|
||||
),
|
||||
)
|
||||
.map(({ id }) => `product gate is not executed by the product_merge_gate job: ${id}`);
|
||||
for (const job of jobs) {
|
||||
for (const match of job.matchAll(/^ +run: corepack pnpm ci:gate -- (FE-GATE-\d{3})$/gmu)) {
|
||||
executed.add(match[1]!);
|
||||
}
|
||||
@@ -405,9 +479,12 @@ export function workflowGateExecutionFailures(
|
||||
}
|
||||
}
|
||||
}
|
||||
return contract.gates
|
||||
.filter(({ id }) => !executed.has(id))
|
||||
.map(({ id }) => `gate is not executed by any workflow run step: ${id}`);
|
||||
return [
|
||||
...contract.gates
|
||||
.filter(({ id }) => !executed.has(id))
|
||||
.map(({ id }) => `gate is not executed by any workflow run step: ${id}`),
|
||||
...productFailures,
|
||||
];
|
||||
}
|
||||
|
||||
function humanize(value: string): string {
|
||||
@@ -429,7 +506,8 @@ export function createCiWorkflowGenerator(
|
||||
if (path.relative(root, target).startsWith("..") || path.relative(root, target) === "") {
|
||||
throw new TypeError(`workflow target escapes repository root: ${contract.providerAdapter}`);
|
||||
}
|
||||
const expected = Buffer.from(renderCiWorkflow(contract), "utf8");
|
||||
const productGates = options.productGates ?? (await loadProductCiOverlay(root)).mergeGates;
|
||||
const expected = Buffer.from(renderCiWorkflow(contract, productGates), "utf8");
|
||||
let actual: Buffer | null = null;
|
||||
const existingPathIsSafe =
|
||||
fileSystem === defaultFileSystem
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { validateVulnerabilityReport } from "./supply-chain.ts";
|
||||
|
||||
/**
|
||||
* 1103/13-03. The vulnerability verdict belongs to the external provider of
|
||||
* the production promotion (signed, independent of the build). Without a
|
||||
* provider nothing told the project that its lockfile already broke the
|
||||
* template's own policy (high and above, no exception). This summary is the
|
||||
* early signal: it reads `pnpm audit --json` and applies that policy, so it
|
||||
* names what the promotion would refuse. It does not replace the provider and
|
||||
* blocks nothing.
|
||||
*/
|
||||
export type AdvisoryStatus = "PASS" | "POLICY_VIOLATION" | "UNVERIFIED";
|
||||
type Severity = "critical" | "high" | "moderate" | "low" | "info";
|
||||
type SeverityCounts = Record<Severity, number>;
|
||||
|
||||
export type DependencyAdvisorySummary = Readonly<{
|
||||
status: AdvisoryStatus;
|
||||
reason: string | null;
|
||||
counts: Readonly<{ production: SeverityCounts; development: SeverityCounts }>;
|
||||
/** Findings the vulnerability policy would block at promotion: `id:package@version:severity`. */
|
||||
blocking: readonly string[];
|
||||
advisories: readonly Readonly<{
|
||||
id: string;
|
||||
packageName: string;
|
||||
versions: readonly string[];
|
||||
severity: string;
|
||||
development: boolean;
|
||||
patchedVersions: string;
|
||||
}>[];
|
||||
}>;
|
||||
|
||||
const SEVERITIES: readonly Severity[] = ["critical", "high", "moderate", "low", "info"];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function emptyCounts(): SeverityCounts {
|
||||
return { critical: 0, high: 0, moderate: 0, low: 0, info: 0 };
|
||||
}
|
||||
|
||||
export function summarizeDependencyAdvisories(
|
||||
audit: unknown,
|
||||
policy: Readonly<Record<string, unknown>>,
|
||||
exceptions: Readonly<Record<string, unknown>>,
|
||||
lockfileSha256: string,
|
||||
now: Date = new Date(),
|
||||
): DependencyAdvisorySummary {
|
||||
const counts = { production: emptyCounts(), development: emptyCounts() };
|
||||
if (!isRecord(audit) || !isRecord(audit["advisories"]) || !isRecord(audit["metadata"])) {
|
||||
return {
|
||||
status: "UNVERIFIED",
|
||||
reason: "pnpm audit returned no advisory report (network or registry unavailable)",
|
||||
counts,
|
||||
blocking: [],
|
||||
advisories: [],
|
||||
};
|
||||
}
|
||||
const advisories = Object.values(audit["advisories"]).filter(isRecord).map((advisory) => {
|
||||
const findings = Array.isArray(advisory["findings"]) ? advisory["findings"].filter(isRecord) : [];
|
||||
return {
|
||||
id: String(advisory["github_advisory_id"] ?? advisory["id"] ?? "unknown"),
|
||||
packageName: String(advisory["module_name"] ?? "unknown"),
|
||||
versions: findings.map((finding) => String(finding["version"] ?? "unknown")),
|
||||
severity: String(advisory["severity"] ?? "unknown").toLowerCase(),
|
||||
// A package reached only through development dependencies never ships.
|
||||
development: findings.length > 0 && findings.every((finding) => finding["dev"] === true),
|
||||
patchedVersions: String(advisory["patched_versions"] ?? ""),
|
||||
};
|
||||
});
|
||||
for (const advisory of advisories) {
|
||||
const scope = advisory.development ? counts.development : counts.production;
|
||||
if ((SEVERITIES as readonly string[]).includes(advisory.severity)) scope[advisory.severity as Severity] += 1;
|
||||
}
|
||||
const verdict = validateVulnerabilityReport(
|
||||
{
|
||||
provider: "pnpm-audit (local, not the promotion provider)",
|
||||
scannedLockfileSha256: lockfileSha256,
|
||||
findings: advisories.flatMap((advisory) =>
|
||||
advisory.versions.map((version) => ({
|
||||
id: advisory.id,
|
||||
packageName: advisory.packageName,
|
||||
version,
|
||||
severity: advisory.severity,
|
||||
})),
|
||||
),
|
||||
},
|
||||
policy,
|
||||
exceptions,
|
||||
lockfileSha256,
|
||||
now,
|
||||
);
|
||||
return {
|
||||
status: verdict.blocking.length > 0 ? "POLICY_VIOLATION" : "PASS",
|
||||
reason: null,
|
||||
counts,
|
||||
blocking: verdict.blocking,
|
||||
advisories,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { isIP } from "node:net";
|
||||
import path from "node:path";
|
||||
import { connect } from "node:tls";
|
||||
|
||||
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
|
||||
import { CACHEABLE_ASSET_CONTENT_TYPES } from "../../src/contracts/service-worker-static-manifest.ts";
|
||||
import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts";
|
||||
|
||||
const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
|
||||
|
||||
@@ -42,6 +45,49 @@ export type ProbeResult = Readonly<{
|
||||
export type ResponseHeaders = Record<string, Record<string, string>>;
|
||||
export type HostingFetcher = (url: URL) => Promise<Response>;
|
||||
export type ReleaseIdentity = Readonly<{ buildId: string; releaseId: string }>;
|
||||
/** The promoted candidate: its manifest names and the texts of its dist/config.json and dist/index.html. */
|
||||
export type CandidateRelease = ReleaseIdentity & Readonly<{ runtimeConfig: string; indexHtml: string }>;
|
||||
export type ProbeTransport = Readonly<{
|
||||
fetcher?: HostingFetcher;
|
||||
/** The ALPN protocol the host negotiates over TLS, or null when none. */
|
||||
negotiateAlpn?: (base: URL) => Promise<string | null>;
|
||||
/** Accepted protocols (`transport.alpnProtocols` in config/hosting/cache-policy.json); empty skips the check. */
|
||||
alpnProtocols?: readonly string[];
|
||||
}>;
|
||||
|
||||
/**
|
||||
* 1103/13-02. Node's fetch speaks HTTP/1.1 even to a host that offers h2, so
|
||||
* the protocol a browser gets is read from the TLS handshake instead: the
|
||||
* client offers h2 and http/1.1 and the host picks one. The certificate is
|
||||
* verified as fetch verifies it.
|
||||
*/
|
||||
export function negotiatedAlpnProtocol(base: URL, timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const host = base.hostname.replace(/^\[|\]$/gu, "");
|
||||
const socket = connect({
|
||||
host,
|
||||
port: Number(base.port || 443),
|
||||
...(isIP(host) === 0 ? { servername: host } : {}),
|
||||
ALPNProtocols: ["h2", "http/1.1"],
|
||||
});
|
||||
socket.setTimeout(timeoutMs, () => socket.destroy(new Error("TLS handshake timed out")));
|
||||
socket.once("secureConnect", () => {
|
||||
const protocol = socket.alpnProtocol;
|
||||
socket.end();
|
||||
resolve(typeof protocol === "string" ? protocol : null);
|
||||
});
|
||||
socket.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function parsedJsonObject(text: string | null): object | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(text ?? "");
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** `buildId` and `releaseId` of a release-manifest.json text, or null. */
|
||||
export function releaseIdentity(manifest: string | null): ReleaseIdentity | null {
|
||||
@@ -67,13 +113,24 @@ export function releaseIdentity(manifest: string | null): ReleaseIdentity | null
|
||||
*
|
||||
* 1101/13-01. The served release manifest must name the candidate's build and
|
||||
* release. Correct headers on an earlier release are not evidence for this one.
|
||||
*
|
||||
* 1103/13-01. Those names come from the CI run, so a release rebuilt in the
|
||||
* same run (say with the local profile) carries them too. The served
|
||||
* config.json must equal the candidate's, the one release admission
|
||||
* (FE-GATE-027) admitted, except for the two emergency switches FE-RB-001 may
|
||||
* change; and the served index.html must name the candidate's entry script.
|
||||
*
|
||||
* 1103/13-02. The host must negotiate a declared protocol (HTTP/2): the
|
||||
* template splits its initial chunks on that premise.
|
||||
*/
|
||||
export async function probeLiveRelease(
|
||||
base: URL,
|
||||
paths: Readonly<Record<string, string>>,
|
||||
candidate: ReleaseIdentity,
|
||||
fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }),
|
||||
candidate: CandidateRelease,
|
||||
transport: ProbeTransport = {},
|
||||
): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> {
|
||||
const fetcher = transport.fetcher ?? ((url: URL) => fetch(url, { redirect: "follow" }));
|
||||
const negotiateAlpn = transport.negotiateAlpn ?? negotiatedAlpnProtocol;
|
||||
const responses: ResponseHeaders = {};
|
||||
const results: ProbeResult[] = [];
|
||||
const probe = async (surface: string, pathname: string): Promise<string | null> => {
|
||||
@@ -148,6 +205,50 @@ export async function probeLiveRelease(
|
||||
passed: entryScript !== null && observed === entryScript,
|
||||
});
|
||||
}
|
||||
const candidateEntryScript = servedEntryScript(candidate.indexHtml);
|
||||
results.push({
|
||||
surface: "index",
|
||||
header: "candidate-entry-script",
|
||||
expected: candidateEntryScript,
|
||||
observed: entryScript,
|
||||
passed: candidateEntryScript !== null && entryScript === candidateEntryScript,
|
||||
});
|
||||
if ("runtimeConfig" in paths) {
|
||||
const served = parsedJsonObject(bodies["runtimeConfig"] ?? null);
|
||||
const admitted = parsedJsonObject(candidate.runtimeConfig);
|
||||
const changed = served && admitted ? changedRuntimeConfigBuildFields(admitted, served) : null;
|
||||
results.push({
|
||||
surface: "runtimeConfig",
|
||||
header: "build-fields",
|
||||
expected: [],
|
||||
observed: changed ?? "unreadable",
|
||||
...(changed === null
|
||||
? { reason: "the served or the candidate config.json is not a JSON object" }
|
||||
: changed.length > 0
|
||||
? { reason: "differs from the candidate's config.json beyond the emergency switches" }
|
||||
: {}),
|
||||
passed: changed !== null && changed.length === 0,
|
||||
});
|
||||
}
|
||||
const alpnProtocols = transport.alpnProtocols ?? [];
|
||||
if (alpnProtocols.length > 0) {
|
||||
let observed: string | null;
|
||||
try {
|
||||
observed = await negotiateAlpn(base);
|
||||
} catch (error: unknown) {
|
||||
observed = error instanceof Error ? error.name : "UnknownError";
|
||||
}
|
||||
results.push({
|
||||
surface: "transport",
|
||||
header: "alpn",
|
||||
expected: alpnProtocols,
|
||||
observed,
|
||||
...(observed !== null && alpnProtocols.includes(observed)
|
||||
? {}
|
||||
: { reason: "the split initial chunks assume HTTP/2 (docs/architecture/static-delivery.md)" }),
|
||||
passed: observed !== null && alpnProtocols.includes(observed),
|
||||
});
|
||||
}
|
||||
return { responses, results };
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ export async function measureOptionalRecipeBundle(input: Readonly<{
|
||||
copyPublicDir: false,
|
||||
cssCodeSplit: false,
|
||||
reportCompressedSize: false,
|
||||
rollupOptions: {
|
||||
rolldownOptions: {
|
||||
input: virtualEntry,
|
||||
// Budget the complete selected runtime, including internal fail-closed
|
||||
// guards that a synthetic consumer cannot predict it will exercise.
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
export type BundleMeasurements = Readonly<{
|
||||
initialJsGzipBytes: number;
|
||||
initialJsFiles: number;
|
||||
lazyChunks: readonly Readonly<{ path: string; gzipBytes: number }>[];
|
||||
}>;
|
||||
|
||||
/**
|
||||
* 1103/15-05. `initialJsFiles` bounds the number of initial JavaScript files
|
||||
* (entry included). The entry preloads them in parallel, which costs no round
|
||||
* trip over HTTP/2 and queues them six at a time over HTTP/1.1
|
||||
* (docs/operations/performance-evidence.md, "초기 청크 수와 HTTP/1.1").
|
||||
*/
|
||||
export type BundleThresholds = Readonly<{
|
||||
initialJsGzipBytes: number;
|
||||
initialJsFiles: number;
|
||||
lazyChunkGzipBytes: number;
|
||||
}>;
|
||||
|
||||
@@ -14,6 +22,7 @@ export function evaluateBundleBudget(
|
||||
) {
|
||||
const initialPassed =
|
||||
measurements.initialJsGzipBytes <= thresholds.initialJsGzipBytes;
|
||||
const initialFilesPassed = measurements.initialJsFiles <= thresholds.initialJsFiles;
|
||||
const lazyResults = measurements.lazyChunks.map((chunk) => ({
|
||||
...chunk,
|
||||
threshold: thresholds.lazyChunkGzipBytes,
|
||||
@@ -21,11 +30,38 @@ export function evaluateBundleBudget(
|
||||
}));
|
||||
return Object.freeze({
|
||||
initialPassed,
|
||||
initialFilesPassed,
|
||||
lazyResults: Object.freeze(lazyResults),
|
||||
passed: initialPassed && lazyResults.every((chunk) => chunk.passed),
|
||||
passed: initialPassed && initialFilesPassed && lazyResults.every((chunk) => chunk.passed),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/15-03. One line per exceeded limit with the measured value, the limit
|
||||
* and the excess, so a failed check:bundle says what to cut without opening
|
||||
* artifacts/performance/bundle.json.
|
||||
*/
|
||||
export function describeBundleBudgetFailures(
|
||||
measurements: BundleMeasurements,
|
||||
thresholds: BundleThresholds,
|
||||
): string[] {
|
||||
const over = (label: string, measured: number, limit: number, unit = " gzip bytes") =>
|
||||
`${label} ${measured}${unit} > budget ${limit} (over by ${measured - limit})`;
|
||||
const lines: string[] = [];
|
||||
if (measurements.initialJsGzipBytes > thresholds.initialJsGzipBytes) {
|
||||
lines.push(over("initial JavaScript", measurements.initialJsGzipBytes, thresholds.initialJsGzipBytes));
|
||||
}
|
||||
if (measurements.initialJsFiles > thresholds.initialJsFiles) {
|
||||
lines.push(over("initial JavaScript files", measurements.initialJsFiles, thresholds.initialJsFiles, ""));
|
||||
}
|
||||
for (const chunk of measurements.lazyChunks) {
|
||||
if (chunk.gzipBytes > thresholds.lazyChunkGzipBytes) {
|
||||
lines.push(over(`lazy chunk ${chunk.path}`, chunk.gzipBytes, thresholds.lazyChunkGzipBytes));
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export type LabMetrics = Readonly<{
|
||||
lcpMs: number;
|
||||
cls: number;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 1101/13-05. The only fields an operator may change in a deployed config.json
|
||||
* without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to
|
||||
* the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and
|
||||
* release manifest, or every boot stops with CONFIG_BUILD_MISMATCH.
|
||||
*
|
||||
* 1103/13-01. The live hosting probe (FE-GATE-019) compares the served
|
||||
* config.json with the promoted candidate's by the same rule, so the release
|
||||
* admission and the probe agree on what an edited document may change.
|
||||
*/
|
||||
export const RUNTIME_CONFIG_EMERGENCY_SWITCHES: ReadonlySet<string> = new Set([
|
||||
"CAPABILITY_OVERRIDES",
|
||||
"FEATURE_OVERRIDES",
|
||||
]);
|
||||
|
||||
/** Fields other than the emergency switches whose values differ, sorted. */
|
||||
export function changedRuntimeConfigBuildFields(original: object, edited: object): string[] {
|
||||
const before = new Map(Object.entries(original));
|
||||
const after = new Map(Object.entries(edited));
|
||||
return [...new Set([...before.keys(), ...after.keys()])]
|
||||
.filter(
|
||||
(field) =>
|
||||
!RUNTIME_CONFIG_EMERGENCY_SWITCHES.has(field) &&
|
||||
JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)),
|
||||
)
|
||||
.sort();
|
||||
}
|
||||
@@ -25,8 +25,11 @@ import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc-
|
||||
* to represent) is recorded as a result with its first error.
|
||||
*
|
||||
* node scripts/scale/measure-feature-shape-growth.ts [--sizes=0,25,100] [--repeats=2] [--write]
|
||||
* node scripts/scale/measure-feature-shape-growth.ts --initial-baseline [--write]
|
||||
*
|
||||
* `--write` stores the result as config/scale/feature-shape-growth.json.
|
||||
* `--write` stores the result as config/scale/feature-shape-growth.json, or
|
||||
* with `--initial-baseline` the initial JavaScript record in
|
||||
* config/scale/feature-shape-ceilings.json.
|
||||
*/
|
||||
export const FEATURE_SHAPE_BASELINE_PATH = "config/scale/feature-shape-growth.json";
|
||||
/** What the declared ceilings rest on, derived by hand from the baseline. */
|
||||
@@ -143,10 +146,15 @@ function run(
|
||||
cwd: string,
|
||||
options: Readonly<{ allowFailure?: boolean }> = {},
|
||||
) {
|
||||
// 1103/15-02. Vitest sets NODE_ENV=test, and a vite build that inherits it
|
||||
// bundles React's development build: the unit test measured 264 KB where
|
||||
// the production build is 201 KB. Every command here measures production.
|
||||
const { NODE_ENV: _inherited, ...environment } = process.env;
|
||||
const started = performance.now();
|
||||
const result = spawnSync(command, args, {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
env: environment,
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
const ms = Math.round(performance.now() - started);
|
||||
@@ -167,23 +175,77 @@ async function javascriptGzipBytes(root: string, files: readonly string[]) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 15-01. Initial JavaScript gzip bytes of the app with `features` reference
|
||||
* copies added: the generator and `vite build` only, no typecheck. The unit
|
||||
* suite (merge stage) bounds what one more feature adds to the initial chunk
|
||||
* with it, so the growth is caught on the PR instead of at the next release.
|
||||
* 15-01. Initial JavaScript of the app with `features` reference copies
|
||||
* added: the generator and `vite build` only, no typecheck. The unit suite
|
||||
* (merge stage) bounds what one more feature adds to the initial chunk with
|
||||
* it, so the growth is caught on the PR instead of at the next release.
|
||||
*/
|
||||
export async function measureInitialJavascriptGzipBytes(features: number): Promise<number> {
|
||||
async function measureInitialJavascript(
|
||||
features: number,
|
||||
): Promise<Readonly<{ gzipBytes: number; files: number }>> {
|
||||
const root = await createFixture(features);
|
||||
try {
|
||||
run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root);
|
||||
run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root);
|
||||
const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8"));
|
||||
return await javascriptGzipBytes(root, classifyViteJavascript(manifest).initialFiles);
|
||||
const { initialFiles } = classifyViteJavascript(manifest);
|
||||
return { gzipBytes: await javascriptGzipBytes(root, initialFiles), files: initialFiles.length };
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/15-02, 15-04. The template's initial JavaScript and what one more
|
||||
* feature and one more context add to it. The first copy lands in a new
|
||||
* context (shape-context-0) and the second in the same one, so the second
|
||||
* copy is a feature alone and the rest of the first is the context.
|
||||
* `initialJavascript` in config/scale/feature-shape-ceilings.json records
|
||||
* these numbers; tests/unit/feature-shape-growth.test.ts compares them with
|
||||
* the build on every unit run.
|
||||
*/
|
||||
export type InitialJavascriptCosts = Readonly<{
|
||||
gzipBytes: number;
|
||||
files: number;
|
||||
perFeatureGzipBytes: number;
|
||||
perContextGzipBytes: number;
|
||||
}>;
|
||||
|
||||
export async function measureInitialJavascriptCosts(): Promise<InitialJavascriptCosts> {
|
||||
const none = await measureInitialJavascript(0);
|
||||
const one = await measureInitialJavascript(1);
|
||||
const two = await measureInitialJavascript(2);
|
||||
const perFeatureGzipBytes = two.gzipBytes - one.gzipBytes;
|
||||
return {
|
||||
gzipBytes: none.gzipBytes,
|
||||
files: none.files,
|
||||
perFeatureGzipBytes,
|
||||
perContextGzipBytes: one.gzipBytes - none.gzipBytes - perFeatureGzipBytes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fields of the record that no longer describe the build. The total moves
|
||||
* by tens of bytes with the build id (CI and local builds differ), so it may
|
||||
* be 1% off; the per-feature and per-context costs are differences of builds
|
||||
* with the same id but only a few hundred bytes, so 10%; the file count is
|
||||
* exact.
|
||||
*/
|
||||
export function initialJavascriptRecordDrift(
|
||||
measured: InitialJavascriptCosts,
|
||||
record: InitialJavascriptCosts,
|
||||
): string[] {
|
||||
const tolerance: Readonly<Record<keyof InitialJavascriptCosts, number>> = {
|
||||
gzipBytes: 0.01,
|
||||
files: 0,
|
||||
perFeatureGzipBytes: 0.1,
|
||||
perContextGzipBytes: 0.1,
|
||||
};
|
||||
return (Object.keys(tolerance) as (keyof InitialJavascriptCosts)[])
|
||||
.filter((field) => Math.abs(record[field] - measured[field]) > Math.abs(measured[field]) * tolerance[field])
|
||||
.map((field) => `${field}: record ${record[field]}, build ${measured[field]}`);
|
||||
}
|
||||
|
||||
async function measureOnce(root: string, features: number) {
|
||||
const loadBefore = load();
|
||||
run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root);
|
||||
@@ -262,7 +324,27 @@ function version(bin: string): string {
|
||||
return (result.stdout ?? "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/15-02. `--initial-baseline` measures the record the documents cite and,
|
||||
* with `--write`, stores it as `initialJavascript` in
|
||||
* config/scale/feature-shape-ceilings.json. Run it in the change that moves
|
||||
* the initial JavaScript.
|
||||
*/
|
||||
async function writeInitialBaseline(): Promise<void> {
|
||||
const measured = await measureInitialJavascriptCosts();
|
||||
process.stdout.write(`initial JavaScript: ${JSON.stringify(measured)}\n`);
|
||||
if (!process.argv.includes("--write")) return;
|
||||
const ceilings = JSON.parse(await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8")) as Record<string, unknown>;
|
||||
ceilings["initialJavascript"] = measured;
|
||||
await writeFile(FEATURE_SHAPE_CEILINGS_PATH, `${JSON.stringify(ceilings, null, 2)}\n`);
|
||||
process.stdout.write(`feature-shape initial baseline: ${FEATURE_SHAPE_CEILINGS_PATH}\n`);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
if (process.argv.includes("--initial-baseline")) {
|
||||
await writeInitialBaseline();
|
||||
return;
|
||||
}
|
||||
const argument = (name: string) =>
|
||||
process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3);
|
||||
const sizes = (argument("sizes") ?? "0,25,100").split(",").map(Number);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
|
||||
import { summarizeDependencyAdvisories } from "./lib/dependency-advisories.ts";
|
||||
|
||||
/**
|
||||
* 1103/13-03. Release-stage signal for known dependency advisories
|
||||
* (FE-GATE-027, next to the release admission of the candidate). It runs
|
||||
* `pnpm audit --json` over the lockfile and applies
|
||||
* config/security/vulnerability-policy.json with its exceptions, the policy the
|
||||
* production promotion provider is held to. The result is a line in the gate
|
||||
* log and artifacts/security/dependency-advisories.json.
|
||||
*
|
||||
* It never fails the gate. An advisory database that changes under unchanged
|
||||
* code would otherwise break a release run, and without the registry the
|
||||
* result is UNVERIFIED, not PASS. The signed verdict of the vulnerability
|
||||
* provider stays the only one that decides a promotion.
|
||||
*/
|
||||
const RECORD_PATH = "artifacts/security/dependency-advisories.json";
|
||||
|
||||
const [policy, exceptions, lockfile] = await Promise.all([
|
||||
readFile("config/security/vulnerability-policy.json", "utf8").then((text) => JSON.parse(text) as Record<string, unknown>),
|
||||
readFile("config/security/vulnerability-exceptions.json", "utf8").then((text) => JSON.parse(text) as Record<string, unknown>),
|
||||
readFile("pnpm-lock.yaml"),
|
||||
]);
|
||||
const lockfileSha256 = createHash("sha256").update(lockfile).digest("hex");
|
||||
|
||||
// pnpm audit exits 1 when it finds advisories; the JSON on stdout is the result.
|
||||
const run = spawnSync("corepack", ["pnpm", "audit", "--json"], {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
timeout: 120_000,
|
||||
});
|
||||
let audit: unknown;
|
||||
try {
|
||||
audit = JSON.parse(run.stdout ?? "");
|
||||
} catch {
|
||||
audit = null;
|
||||
}
|
||||
const summary = summarizeDependencyAdvisories(audit, policy, exceptions, lockfileSha256);
|
||||
|
||||
await mkdir("artifacts/security", { recursive: true });
|
||||
await writeFile(
|
||||
RECORD_PATH,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
generatedAt: new Date().toISOString(),
|
||||
source: "pnpm audit --json",
|
||||
authoritative: false,
|
||||
lockfileSha256,
|
||||
blockAtSeverity: policy["blockAtSeverity"] ?? null,
|
||||
...summary,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
|
||||
const count = (scope: Readonly<Record<string, number>>) =>
|
||||
`critical ${scope["critical"]}, high ${scope["high"]}, moderate ${scope["moderate"]}, low ${scope["low"]}`;
|
||||
process.stdout.write(
|
||||
`Dependency advisories: ${summary.status} (production: ${count(summary.counts.production)}; ` +
|
||||
`development: ${count(summary.counts.development)}); record at ${RECORD_PATH}. ` +
|
||||
"Not blocking: the production promotion provider decides.\n",
|
||||
);
|
||||
if (summary.status === "POLICY_VIOLATION") {
|
||||
process.stderr.write(
|
||||
`WARNING: the vulnerability policy (block at ${String(policy["blockAtSeverity"])}) would refuse this lockfile at production promotion:\n` +
|
||||
summary.blocking.map((finding) => ` ${finding}\n`).join("") +
|
||||
"Update the dependency or record a reviewed exception in config/security/vulnerability-exceptions.json.\n",
|
||||
);
|
||||
}
|
||||
if (summary.status === "UNVERIFIED") {
|
||||
process.stderr.write(`WARNING: dependency advisories UNVERIFIED: ${summary.reason}\n`);
|
||||
}
|
||||
@@ -100,11 +100,20 @@ if (liveTarget?.passed && !slotEmpty) {
|
||||
),
|
||||
);
|
||||
const candidateManifest = await readFile(path.join(distRoot, "release-manifest.json"), "utf8").catch(() => null);
|
||||
const candidate = releaseIdentity(candidateManifest);
|
||||
if (!candidate) {
|
||||
const identity = releaseIdentity(candidateManifest);
|
||||
if (!identity) {
|
||||
throw new Error(`${distRoot}/release-manifest.json does not name a buildId and releaseId`);
|
||||
}
|
||||
const probed = await probeLiveRelease(liveTarget.url, paths, candidate);
|
||||
// 1103/13-01. The served config.json and index.html are compared with the
|
||||
// candidate's, not only the manifest names a rebuild in the same run shares.
|
||||
const candidate = {
|
||||
...identity,
|
||||
runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"),
|
||||
indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"),
|
||||
};
|
||||
const probed = await probeLiveRelease(liveTarget.url, paths, candidate, {
|
||||
alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols),
|
||||
});
|
||||
responses = probed.responses;
|
||||
probeResults.push(...probed.results);
|
||||
// 1103/06-03. The worker needs every precached asset kind typed exactly.
|
||||
@@ -151,6 +160,19 @@ for (const [surface, policy] of requiredSurfaces) {
|
||||
observed: observedContentType,
|
||||
passed: observedMime !== undefined && contentTypes.includes(observedMime),
|
||||
});
|
||||
// 1103/13-02. The bundle budget counts gzip bytes. The probe's fetch offers
|
||||
// br and gzip, so an uncompressed answer is the host's choice.
|
||||
const contentEncodings = strings(policy.contentEncodings);
|
||||
if (contentEncodings.length > 0) {
|
||||
const observedEncoding = responses[surface]?.["content-encoding"];
|
||||
results.push({
|
||||
surface,
|
||||
header: "content-encoding",
|
||||
expected: contentEncodings,
|
||||
observed: observedEncoding,
|
||||
passed: observedEncoding !== undefined && contentEncodings.includes(observedEncoding.trim().toLowerCase()),
|
||||
});
|
||||
}
|
||||
if (policy.securityHeaders === true) {
|
||||
for (const [header, expected] of Object.entries(securityHeaders)) {
|
||||
const observedSecurity = responses[surface]?.[header.toLowerCase()];
|
||||
@@ -207,7 +229,7 @@ if (status === "FAIL") {
|
||||
}
|
||||
if (status === "UNVERIFIED" && slotEmpty) {
|
||||
process.stderr.write(
|
||||
"Hosting header contract: UNVERIFIED (the deployment slot is empty: nothing deployed this release, so the host was not probed; fill the deployment job in config/ci/gates.json)\n",
|
||||
"Hosting header contract: UNVERIFIED (the deployment slot is empty: nothing deployed this release, so the host was not probed; fill deployment in config/ci/product-gates.json)\n",
|
||||
);
|
||||
process.exit(3);
|
||||
}
|
||||
|
||||
@@ -78,6 +78,26 @@ describe("build variables in the bundle (13-06)", () => {
|
||||
const firstChunks = designSystem(first);
|
||||
expect(firstChunks).toHaveLength(1);
|
||||
expect(designSystem(second)).toEqual(firstChunks);
|
||||
|
||||
// 1103/15-06. react-dom is about 56 KB of the initial JavaScript. It sat
|
||||
// in the boot-failure chunk with the build id, so every release renamed
|
||||
// it and returning visitors downloaded it again. Its own chunk keeps the
|
||||
// name while only the build id changes.
|
||||
const reactDom = ({ contents }: Awaited<ReturnType<typeof build>>) =>
|
||||
contents
|
||||
.filter(({ file, text }) => file.endsWith(".js") && text.includes("__reactContainer$"))
|
||||
.map(({ file }) => path.basename(file));
|
||||
expect(reactDom(first)).toHaveLength(1);
|
||||
expect(reactDom(first)[0]).not.toMatch(/render-boot-failure/u);
|
||||
expect(reactDom(second)).toEqual(reactDom(first));
|
||||
|
||||
// 1103/15-07. react-router's exports map resolves every condition to its
|
||||
// development build; a production build must carry the production one,
|
||||
// without the router's development warnings.
|
||||
const developmentWarnings = first.contents
|
||||
.filter(({ file, text }) => file.endsWith(".js") && text.includes("You rendered descendant"))
|
||||
.map(({ file }) => path.basename(file));
|
||||
expect(developmentWarnings).toEqual([]);
|
||||
}, 120_000);
|
||||
|
||||
it("refuses a VITE_* variable the build does not declare", async () => {
|
||||
|
||||
@@ -28,6 +28,7 @@ const completed = {
|
||||
...inventory,
|
||||
measurements: {
|
||||
initialJsGzipBytes: 50,
|
||||
initialJsFiles: 1,
|
||||
lazyChunks: [{ path: "assets/lazy.js", gzipBytes: 40 }],
|
||||
},
|
||||
classification: {
|
||||
@@ -36,9 +37,10 @@ const completed = {
|
||||
missingImports: [],
|
||||
},
|
||||
missingOutputs: [],
|
||||
thresholds: { initialJsGzipBytes: 60, lazyChunkGzipBytes: 45 },
|
||||
thresholds: { initialJsGzipBytes: 60, initialJsFiles: 1, lazyChunkGzipBytes: 45 },
|
||||
results: {
|
||||
initialPassed: true,
|
||||
initialFilesPassed: true,
|
||||
lazyResults: [
|
||||
{ path: "assets/lazy.js", gzipBytes: 40, threshold: 45, passed: true },
|
||||
],
|
||||
@@ -47,6 +49,7 @@ const completed = {
|
||||
fixtures: [
|
||||
{ name: "initial-js-over-budget", passed: true },
|
||||
{ name: "lazy-chunk-over-budget", passed: true },
|
||||
{ name: "initial-files-over-budget", passed: true },
|
||||
],
|
||||
passed: true,
|
||||
} as const;
|
||||
@@ -64,8 +67,10 @@ describe("bundle artifact contracts", () => {
|
||||
["lazy classification", { classification: { ...completed.classification, lazyFiles: [] } }],
|
||||
["missing output", { missingOutputs: ["assets/missing.js"], passed: true }],
|
||||
["threshold result", { results: { ...completed.results, initialPassed: false } }],
|
||||
["initial file count", { measurements: { ...completed.measurements, initialJsFiles: 2 } }],
|
||||
["initial file result", { results: { ...completed.results, initialFilesPassed: false } }],
|
||||
["lazy result", { results: { ...completed.results, lazyResults: [] } }],
|
||||
["fixture identity", { fixtures: [{ name: "other", passed: true }, completed.fixtures[1]] }],
|
||||
["fixture identity", { fixtures: [{ name: "other", passed: true }, completed.fixtures[1], completed.fixtures[2]] }],
|
||||
["overall result", { passed: false }],
|
||||
] as const)("rejects inconsistent %s evidence", (_name, mutation) => {
|
||||
expect(() =>
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* 1103/15-03. An over-budget build printed only
|
||||
* "Bundle budget or manifest integrity failed: " with nothing after the
|
||||
* colon, so the first budget failure a project meets named neither the limit
|
||||
* nor the excess. check-bundle runs here on a hand-made build output.
|
||||
*/
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
type Output = Readonly<{ path: string; gzipBytes: number }>;
|
||||
|
||||
async function checkBundle(
|
||||
options: Readonly<{
|
||||
outputs: readonly Output[];
|
||||
manifest: Record<string, unknown>;
|
||||
budgets: Record<string, number>;
|
||||
}>,
|
||||
) {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "check-bundle-output-"));
|
||||
roots.push(root);
|
||||
const write = async (file: string, value: unknown) => {
|
||||
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
|
||||
await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`);
|
||||
};
|
||||
await write("config/performance/budgets.json", { schemaVersion: 1, bundle: options.budgets });
|
||||
await write("dist/.vite/manifest.json", options.manifest);
|
||||
await write("artifacts/performance/bundle.json", {
|
||||
schemaVersion: 1,
|
||||
generatedAt: "2026-11-04T00:00:00.000Z",
|
||||
context: { nodeVersion: "v24.14.0", packageManager: "pnpm@11.17.0", runnerImage: "fixture" },
|
||||
outputs: options.outputs.map((output) => ({
|
||||
path: `dist/${output.path}`,
|
||||
bytes: output.gzipBytes * 3,
|
||||
gzipBytes: output.gzipBytes,
|
||||
sha256: "a".repeat(64),
|
||||
})),
|
||||
});
|
||||
const result = spawnSync(process.execPath, [path.resolve("scripts/check-bundle.ts")], {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
});
|
||||
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
|
||||
}
|
||||
|
||||
const MANIFEST = {
|
||||
"index.html": {
|
||||
file: "assets/index-A.js",
|
||||
isEntry: true,
|
||||
imports: ["_boot"],
|
||||
},
|
||||
// The entry's own dynamic imports are initial (09-03); a route's are lazy.
|
||||
_boot: { file: "assets/boot-B.js", dynamicImports: ["src/lazy.tsx"] },
|
||||
"src/lazy.tsx": { file: "assets/lazy-C.js" },
|
||||
};
|
||||
const OUTPUTS = [
|
||||
{ path: "assets/index-A.js", gzipBytes: 400 },
|
||||
{ path: "assets/boot-B.js", gzipBytes: 500 },
|
||||
{ path: "assets/lazy-C.js", gzipBytes: 300 },
|
||||
];
|
||||
const BUDGETS = { initialJsGzipBytes: 1_000, initialJsFiles: 2, lazyChunkGzipBytes: 400 };
|
||||
|
||||
describe("check:bundle failure output (1103/15-03)", () => {
|
||||
it("passes and prints the total within budget", async () => {
|
||||
const result = await checkBundle({ outputs: OUTPUTS, manifest: MANIFEST, budgets: BUDGETS });
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout).toContain("initial JS 900 / 1000 gzip bytes");
|
||||
});
|
||||
|
||||
it("names the measured initial total, the budget and the excess", async () => {
|
||||
const result = await checkBundle({
|
||||
outputs: OUTPUTS,
|
||||
manifest: MANIFEST,
|
||||
budgets: { ...BUDGETS, initialJsGzipBytes: 899 },
|
||||
});
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("Bundle budget failed (config/performance/budgets.json):");
|
||||
expect(result.stderr).toContain("initial JavaScript 900 gzip bytes > budget 899 (over by 1)");
|
||||
expect(result.stderr).not.toContain("manifest integrity");
|
||||
});
|
||||
|
||||
it("names each lazy chunk over its budget", async () => {
|
||||
const result = await checkBundle({
|
||||
outputs: OUTPUTS,
|
||||
manifest: MANIFEST,
|
||||
budgets: { ...BUDGETS, lazyChunkGzipBytes: 250 },
|
||||
});
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain(
|
||||
"lazy chunk assets/lazy-C.js 300 gzip bytes > budget 250 (over by 50)",
|
||||
);
|
||||
});
|
||||
|
||||
// 1103/15-05. The entry preloads every initial file at once; over HTTP/1.1
|
||||
// they queue for six connections. A change that adds an initial file is a
|
||||
// decision recorded in the budget, not a side effect.
|
||||
it("fails when the initial JavaScript has more files than the budget", async () => {
|
||||
const result = await checkBundle({
|
||||
outputs: OUTPUTS,
|
||||
manifest: MANIFEST,
|
||||
budgets: { ...BUDGETS, initialJsFiles: 1 },
|
||||
});
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("initial JavaScript files 2 > budget 1 (over by 1)");
|
||||
});
|
||||
|
||||
it("reports a manifest integrity failure apart from the budget", async () => {
|
||||
const result = await checkBundle({
|
||||
outputs: OUTPUTS.filter(({ path: file }) => file !== "assets/boot-B.js"),
|
||||
manifest: MANIFEST,
|
||||
budgets: BUDGETS,
|
||||
});
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("Bundle manifest integrity failed:");
|
||||
expect(result.stderr).toContain("output missing from the inventory: assets/boot-B.js");
|
||||
expect(result.stderr).not.toContain("Bundle budget failed");
|
||||
});
|
||||
});
|
||||
@@ -196,8 +196,8 @@ describe("CI gate contract", () => {
|
||||
).filter((gateId) => gateId !== "FE-GATE-016"),
|
||||
);
|
||||
expect(contract.jobs).toHaveLength(10);
|
||||
expect(contract.commands).toHaveLength(99);
|
||||
expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(103);
|
||||
expect(contract.commands).toHaveLength(100);
|
||||
expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(104);
|
||||
expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(30);
|
||||
expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(88);
|
||||
expect(contract.artifacts).toHaveLength(110);
|
||||
@@ -387,7 +387,14 @@ describe("CI gate contract", () => {
|
||||
);
|
||||
const workflow = renderCiWorkflow(contract);
|
||||
const job = workflow.slice(workflow.indexOf(" deployment:\n"), workflow.indexOf(" production_gate:\n"));
|
||||
expect(job).toContain('DEPLOY_SSH_KEY: "${{ secrets.DEPLOY_SSH_KEY }}"');
|
||||
// 1103/13-05. Job env reaches every step, checkout and the third-party
|
||||
// download action included; a credential belongs to the deploy step only.
|
||||
const jobEnvironment = job.slice(job.indexOf(" env:\n"), job.indexOf(" steps:\n"));
|
||||
const deployStep = job.slice(job.indexOf(" - name: Deploy the promoted release"));
|
||||
expect(jobEnvironment).toContain('DEPLOY_HOST: "${{ vars.DEPLOY_HOST }}"');
|
||||
expect(jobEnvironment).not.toContain("secrets.");
|
||||
expect(deployStep).toContain(' env:\n DEPLOY_SSH_KEY: "${{ secrets.DEPLOY_SSH_KEY }}"\n');
|
||||
expect(job.match(/secrets\./gu)).toHaveLength(1);
|
||||
expect(job.indexOf("--extract-to")).toBeLessThan(job.indexOf("corepack pnpm deploy:release"));
|
||||
expect(job.indexOf("corepack pnpm deploy:release")).toBeLessThan(
|
||||
job.indexOf('echo "deployed=true" >> "$GITHUB_OUTPUT"'),
|
||||
@@ -412,6 +419,18 @@ describe("CI gate contract", () => {
|
||||
(slot: Record<string, any>) => slot.steps.push({ kind: "checkout" }),
|
||||
/deploy step/u,
|
||||
],
|
||||
// 1103/13-01. A slot that rebuilt (or deployed anything but the promoted
|
||||
// archive) passed the contract under the name deploy-promoted-release.
|
||||
[
|
||||
"a slot that deploys without the promoted candidate",
|
||||
(slot: Record<string, any>) => slot.steps.splice(3, 2),
|
||||
/promoted-release/u,
|
||||
],
|
||||
[
|
||||
"a slot that extracts the candidate without its digest",
|
||||
(slot: Record<string, any>) => slot.environment.shift(),
|
||||
/CANDIDATE_ARCHIVE_SHA256/u,
|
||||
],
|
||||
])("rejects %s (1101/13-01)", async (_name, mutate, diagnostic) => {
|
||||
const contract = fillDeploymentSlot(
|
||||
JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { summarizeDependencyAdvisories } from "../../scripts/lib/dependency-advisories.ts";
|
||||
|
||||
/**
|
||||
* 1103/13-03. The lockfile broke the template's own vulnerability policy
|
||||
* (high and above, no exception) and nothing said so before the production
|
||||
* promotion provider, which a template copy may not have. The summary applies
|
||||
* that policy to `pnpm audit --json`.
|
||||
*/
|
||||
const POLICY = { blockAtSeverity: "high" };
|
||||
const NO_EXCEPTIONS = { schemaVersion: 1, exceptions: [] };
|
||||
const LOCKFILE = "a".repeat(64);
|
||||
|
||||
const advisory = (
|
||||
id: string,
|
||||
module: string,
|
||||
severity: string,
|
||||
findings: readonly Readonly<{ version: string; dev: boolean }>[],
|
||||
) => ({
|
||||
github_advisory_id: id,
|
||||
module_name: module,
|
||||
severity,
|
||||
patched_versions: ">=9.9.9",
|
||||
findings: findings.map((finding) => ({ ...finding, paths: [`.>${module}`] })),
|
||||
});
|
||||
const audit = (...advisories: ReturnType<typeof advisory>[]) => ({
|
||||
advisories: Object.fromEntries(advisories.map((entry, index) => [String(index), entry])),
|
||||
metadata: { vulnerabilities: {} },
|
||||
});
|
||||
|
||||
describe("dependency advisory summary (1103/13-03)", () => {
|
||||
it("names what the policy would block at promotion, in production and development", () => {
|
||||
const summary = summarizeDependencyAdvisories(
|
||||
audit(
|
||||
advisory("GHSA-prod-high", "zod", "high", [{ version: "4.4.3", dev: false }]),
|
||||
advisory("GHSA-dev-critical", "storybook", "critical", [{ version: "10.5.4", dev: true }]),
|
||||
advisory("GHSA-dev-moderate", "postcss", "moderate", [{ version: "8.5.22", dev: true }]),
|
||||
),
|
||||
POLICY,
|
||||
NO_EXCEPTIONS,
|
||||
LOCKFILE,
|
||||
);
|
||||
expect(summary.status).toBe("POLICY_VIOLATION");
|
||||
expect(summary.blocking).toEqual([
|
||||
"GHSA-prod-high:zod@4.4.3:high",
|
||||
"GHSA-dev-critical:storybook@10.5.4:critical",
|
||||
]);
|
||||
expect(summary.counts.production).toMatchObject({ high: 1, critical: 0 });
|
||||
expect(summary.counts.development).toMatchObject({ critical: 1, moderate: 1 });
|
||||
});
|
||||
|
||||
it("passes when nothing reaches the blocking severity", () => {
|
||||
const summary = summarizeDependencyAdvisories(
|
||||
audit(advisory("GHSA-dev-moderate", "postcss", "moderate", [{ version: "8.5.22", dev: true }])),
|
||||
POLICY,
|
||||
NO_EXCEPTIONS,
|
||||
LOCKFILE,
|
||||
);
|
||||
expect(summary).toMatchObject({ status: "PASS", blocking: [] });
|
||||
});
|
||||
|
||||
it("honours a valid exception the way the promotion verdict does", () => {
|
||||
const exceptions = {
|
||||
schemaVersion: 1,
|
||||
exceptions: [
|
||||
{
|
||||
vulnerabilityId: "GHSA-prod-high",
|
||||
packageName: "zod",
|
||||
owner: "frontend-platform",
|
||||
reviewer: "security-review",
|
||||
reason: "not reachable",
|
||||
expiresAt: "2027-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
summarizeDependencyAdvisories(
|
||||
audit(advisory("GHSA-prod-high", "zod", "high", [{ version: "4.4.3", dev: false }])),
|
||||
POLICY,
|
||||
exceptions,
|
||||
LOCKFILE,
|
||||
new Date("2026-11-04T00:00:00.000Z"),
|
||||
),
|
||||
).toMatchObject({ status: "PASS", blocking: [] });
|
||||
});
|
||||
|
||||
it("is UNVERIFIED, not PASS, when the audit returned no report", () => {
|
||||
for (const output of [null, {}, { error: { code: "ENOTFOUND" } }]) {
|
||||
expect(summarizeDependencyAdvisories(output, POLICY, NO_EXCEPTIONS, LOCKFILE)).toMatchObject({
|
||||
status: "UNVERIFIED",
|
||||
reason: expect.stringContaining("pnpm audit"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("runs at release admission (FE-GATE-027) and never fails the gate by itself", async () => {
|
||||
const contract = JSON.parse(await readFile("config/ci/gates.json", "utf8")) as {
|
||||
gates: { id: string; commandIds: string[] }[];
|
||||
commands: { id: string; script: string }[];
|
||||
};
|
||||
const scripts = (contract.gates.find(({ id }) => id === "FE-GATE-027")?.commandIds ?? []).map(
|
||||
(commandId) => contract.commands.find(({ id }) => id === commandId)?.script,
|
||||
);
|
||||
expect(scripts).toEqual(["check:release-admission", "scan:dependency-advisories"]);
|
||||
const source = await readFile("scripts/scan-dependency-advisories.ts", "utf8");
|
||||
expect(source).not.toMatch(/process\.exit(?:Code)?\s*(?:=|\()\s*[1-9]/u);
|
||||
});
|
||||
});
|
||||
@@ -5,8 +5,10 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
FEATURE_SHAPE_BASELINE_PATH,
|
||||
FEATURE_SHAPE_CEILINGS_PATH,
|
||||
measureInitialJavascriptGzipBytes,
|
||||
initialJavascriptRecordDrift,
|
||||
measureInitialJavascriptCosts,
|
||||
renameReferenceFeature,
|
||||
type InitialJavascriptCosts,
|
||||
} from "../../scripts/scale/measure-feature-shape-growth.ts";
|
||||
import { APP_MAX_CONTEXTS } from "../../src/apps/template-app/app-module.ts";
|
||||
import { CONTEXT_MAX_FEATURES } from "../../src/contexts/reference-context/context-module.ts";
|
||||
@@ -131,17 +133,59 @@ describe("feature-shape growth measurement (11-04)", () => {
|
||||
* contracts, schemas, mappers, HTTP gateway and API loaded at boot: +3,922 B
|
||||
* per copy, and the first added feature exceeded the budget. Only what the
|
||||
* shell needs before a feature route is entered may load at boot (route
|
||||
* table, navigation and page messages, invalidation identities: 741 B when
|
||||
* 15-01 landed); the rest loads with the feature's routes. The bound also
|
||||
* fails if the feature-declarations chunk group in vite.config.ts stops
|
||||
* matching.
|
||||
* table, navigation and page messages, invalidation identities); the rest
|
||||
* loads with the feature's routes. The bound also fails if the
|
||||
* feature-declarations chunk group in vite.config.ts stops matching.
|
||||
*
|
||||
* 1103/15-04. The first copy also adds a context (shape-context-0), so one
|
||||
* number mixed a context's cost with a feature's and had 40 B left under
|
||||
* the bound. A second copy in the same context is one more feature alone;
|
||||
* the rest of the first copy is the context. Each has its own bound and
|
||||
* the failure names which one grew.
|
||||
*
|
||||
* 1103/15-02. The record in config/scale/feature-shape-ceilings.json is the
|
||||
* one place the documents take the template's baseline from. Written by
|
||||
* hand, it went stale twice; it now has to match this build.
|
||||
*/
|
||||
it("adds at most 1 KiB of initial JavaScript per reference-shaped feature (15-01)", async () => {
|
||||
const withoutCopies = await measureInitialJavascriptGzipBytes(0);
|
||||
const withOneCopy = await measureInitialJavascriptGzipBytes(1);
|
||||
it("bounds what one more feature and one more context add, and matches the record (15-01)", async () => {
|
||||
const measured = await measureInitialJavascriptCosts();
|
||||
const { initialJavascript: record } = JSON.parse(
|
||||
await readFile(FEATURE_SHAPE_CEILINGS_PATH, "utf8"),
|
||||
) as { initialJavascript: InitialJavascriptCosts };
|
||||
const observed = `measured ${JSON.stringify(measured)}`;
|
||||
|
||||
expect(withOneCopy - withoutCopies).toBeLessThanOrEqual(1_024);
|
||||
}, 120_000);
|
||||
expect(measured.perFeatureGzipBytes, `one more feature in an existing context: ${observed}`)
|
||||
.toBeLessThanOrEqual(1_024);
|
||||
expect(measured.perContextGzipBytes, `one more context: ${observed}`)
|
||||
.toBeLessThanOrEqual(512);
|
||||
expect(
|
||||
initialJavascriptRecordDrift(measured, record),
|
||||
`${FEATURE_SHAPE_CEILINGS_PATH} initialJavascript is stale (${observed}); ` +
|
||||
"rewrite it with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write",
|
||||
).toEqual([]);
|
||||
}, 180_000);
|
||||
|
||||
it("reports a record more than 1% off the build, or a different file count", () => {
|
||||
const measured = {
|
||||
gzipBytes: 200_000,
|
||||
files: 25,
|
||||
perFeatureGzipBytes: 700,
|
||||
perContextGzipBytes: 250,
|
||||
};
|
||||
expect(initialJavascriptRecordDrift(measured, measured)).toEqual([]);
|
||||
expect(
|
||||
initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 201_500 }),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
initialJavascriptRecordDrift(measured, { ...measured, gzipBytes: 204_000 }),
|
||||
).toEqual(["gzipBytes: record 204000, build 200000"]);
|
||||
expect(initialJavascriptRecordDrift(measured, { ...measured, files: 26 })).toEqual([
|
||||
"files: record 26, build 25",
|
||||
]);
|
||||
expect(
|
||||
initialJavascriptRecordDrift(measured, { ...measured, perFeatureGzipBytes: 800 }),
|
||||
).toEqual(["perFeatureGzipBytes: record 800, build 700"]);
|
||||
});
|
||||
|
||||
it("states in the committed rationale what the ceilings rest on", async () => {
|
||||
// The rationale lives next to the baseline, not in a review document: the
|
||||
|
||||
@@ -152,11 +152,21 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
||||
releaseManifest: "/release-manifest.json",
|
||||
appRoute: "/__probe/deep-link",
|
||||
};
|
||||
const CANDIDATE = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" };
|
||||
const IDENTITY = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" };
|
||||
const CONFIG = JSON.stringify({
|
||||
APP_ENV: "production",
|
||||
AUTH_MODE: "external",
|
||||
API_BASE_URL: "https://api.frontend.example.test/",
|
||||
BUILD_ID: IDENTITY.buildId,
|
||||
RELEASE_ID: IDENTITY.releaseId,
|
||||
CAPABILITY_OVERRIDES: {},
|
||||
FEATURE_OVERRIDES: {},
|
||||
});
|
||||
const CANDIDATE = { ...IDENTITY, runtimeConfig: CONFIG, indexHtml: INDEX };
|
||||
const RELEASE: Record<string, [number, string]> = {
|
||||
"/": [200, INDEX],
|
||||
"/config.json": [200, "{}"],
|
||||
"/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...CANDIDATE })],
|
||||
"/config.json": [200, CONFIG],
|
||||
"/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...IDENTITY })],
|
||||
"/assets/index-A1.js": [200, ""],
|
||||
};
|
||||
const host = (routes: Record<string, [number, string]>) => async (url: URL) => {
|
||||
@@ -166,8 +176,14 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
||||
return response;
|
||||
};
|
||||
const base = new URL("https://frontend.example.test/");
|
||||
const failed = async (routes: Record<string, [number, string]>) =>
|
||||
(await probeLiveRelease(base, PATHS, CANDIDATE, host(routes))).results
|
||||
const probe = (routes: Record<string, [number, string]>, alpn: string | null = "h2") =>
|
||||
probeLiveRelease(base, PATHS, CANDIDATE, {
|
||||
fetcher: host(routes),
|
||||
negotiateAlpn: async () => alpn,
|
||||
alpnProtocols: ["h2"],
|
||||
});
|
||||
const failed = async (routes: Record<string, [number, string]>, alpn?: string | null) =>
|
||||
(await probe(routes, alpn)).results
|
||||
.filter((result) => !result.passed)
|
||||
.map((result) => `${result.surface} ${result.header}`);
|
||||
|
||||
@@ -198,6 +214,72 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
||||
).toEqual(["releaseManifest build-id", "releaseManifest release-id"]);
|
||||
});
|
||||
|
||||
// 1103/13-01. The manifest names come from the CI run, so a release rebuilt
|
||||
// in the same run with the local profile (APP_ENV=local, AUTH_MODE=demo, a
|
||||
// loopback API) passed. The candidate's config.json is the one release
|
||||
// admission (FE-GATE-027) admitted, so the served one must equal it.
|
||||
it("fails a host whose config.json is not the candidate's", async () => {
|
||||
const local = JSON.stringify({
|
||||
...JSON.parse(CONFIG),
|
||||
APP_ENV: "local",
|
||||
AUTH_MODE: "demo",
|
||||
API_BASE_URL: "http://localhost:8080/",
|
||||
});
|
||||
const { results } = await probe({
|
||||
...RELEASE,
|
||||
"/__probe/deep-link": [200, INDEX],
|
||||
"/config.json": [200, local],
|
||||
});
|
||||
expect(results.filter(({ passed }) => !passed)).toEqual([
|
||||
expect.objectContaining({
|
||||
surface: "runtimeConfig",
|
||||
header: "build-fields",
|
||||
observed: ["API_BASE_URL", "APP_ENV", "AUTH_MODE"],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
// FE-RB-001 changes the two emergency switches without a rebuild; the
|
||||
// probe after it must still pass.
|
||||
it("passes a host whose config.json differs only in the emergency switches", async () => {
|
||||
const switched = JSON.stringify({
|
||||
...JSON.parse(CONFIG),
|
||||
CAPABILITY_OVERRIDES: { realtime: "DISABLED" },
|
||||
FEATURE_OVERRIDES: { "reference-feature": false },
|
||||
});
|
||||
expect(
|
||||
await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, switched] }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails a host whose config.json is unreadable", async () => {
|
||||
expect(
|
||||
await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, "<html>"] }),
|
||||
).toEqual(["runtimeConfig build-fields"]);
|
||||
});
|
||||
|
||||
// 1103/13-01. A build of other sources under the same run names serves its
|
||||
// own entry script; the fallback check compared the host only with itself.
|
||||
it("fails a host whose index.html names another entry script than the candidate's", async () => {
|
||||
const other = '<script type="module" src="/assets/index-B2.js"></script>';
|
||||
expect(
|
||||
await failed({
|
||||
...RELEASE,
|
||||
"/": [200, other],
|
||||
"/__probe/deep-link": [200, other],
|
||||
"/assets/index-B2.js": [200, ""],
|
||||
}),
|
||||
).toEqual(["index candidate-entry-script"]);
|
||||
});
|
||||
|
||||
// 1103/13-02. The split initial chunks assume HTTP/2
|
||||
// (docs/architecture/static-delivery.md); over HTTP/1.1 they queue.
|
||||
it("fails a host that does not negotiate a declared protocol", async () => {
|
||||
const release: Record<string, [number, string]> = { ...RELEASE, "/__probe/deep-link": [200, INDEX] };
|
||||
expect(await failed(release, "http/1.1")).toEqual(["transport alpn"]);
|
||||
expect(await failed(release, null)).toEqual(["transport alpn"]);
|
||||
});
|
||||
|
||||
it("fails when the served release manifest is unreadable", async () => {
|
||||
expect(
|
||||
await failed({
|
||||
@@ -304,6 +386,7 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
async function verify(
|
||||
distFiles: Readonly<Record<string, string>>,
|
||||
env: Readonly<Record<string, string>> = {},
|
||||
editFixture?: (responses: Record<string, Record<string, string>>) => void,
|
||||
) {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "hosting-release-root-"));
|
||||
try {
|
||||
@@ -311,6 +394,14 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
for (const file of ["cache-policy.json", "security-headers.json", "response-headers.fixture.json"]) {
|
||||
await copyFile(`config/hosting/${file}`, path.join(root, "config/hosting", file));
|
||||
}
|
||||
if (editFixture) {
|
||||
const fixturePath = path.join(root, "config/hosting/response-headers.fixture.json");
|
||||
const fixture = JSON.parse(await readFile(fixturePath, "utf8")) as {
|
||||
responses: Record<string, Record<string, string>>;
|
||||
};
|
||||
editFixture(fixture.responses);
|
||||
await writeFile(fixturePath, JSON.stringify(fixture));
|
||||
}
|
||||
for (const [file, content] of Object.entries(distFiles)) {
|
||||
await mkdir(path.dirname(path.join(root, "candidate/dist", file)), { recursive: true });
|
||||
await writeFile(path.join(root, "candidate/dist", file), content);
|
||||
@@ -360,4 +451,25 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
expect(result.status).toBe(3);
|
||||
expect(result.stderr).toContain("deployment slot");
|
||||
});
|
||||
|
||||
// 1103/13-02. The bundle budget counts gzip bytes; an uncompressed entry
|
||||
// script means about three times as many bytes on the wire.
|
||||
it("declares compression for hashed assets and HTTP/2 for the host", async () => {
|
||||
const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as {
|
||||
transport?: { alpnProtocols?: string[] };
|
||||
surfaces: Record<string, { contentEncodings?: string[] }>;
|
||||
};
|
||||
expect(policy.transport?.alpnProtocols).toEqual(["h2"]);
|
||||
expect(policy.surfaces["hashedAsset"]?.contentEncodings).toEqual(
|
||||
expect.arrayContaining(["br", "gzip"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails a hashed asset served without a declared content encoding", async () => {
|
||||
const result = await verify(DIST, {}, (responses) => {
|
||||
delete responses["hashedAsset"]?.["content-encoding"];
|
||||
});
|
||||
expect(result.failed, result.stderr).toEqual(["hashedAsset content-encoding"]);
|
||||
expect(result.status).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,11 +11,12 @@ describe("performance budgets", () => {
|
||||
it("rejects initial and lazy JavaScript above their named limits", () => {
|
||||
const thresholds = {
|
||||
initialJsGzipBytes: 200,
|
||||
initialJsFiles: 2,
|
||||
lazyChunkGzipBytes: 120,
|
||||
};
|
||||
expect(
|
||||
evaluateBundleBudget(
|
||||
{ initialJsGzipBytes: 201, lazyChunks: [] },
|
||||
{ initialJsGzipBytes: 201, initialJsFiles: 1, lazyChunks: [] },
|
||||
thresholds,
|
||||
).passed,
|
||||
).toBe(false);
|
||||
@@ -23,11 +24,18 @@ describe("performance budgets", () => {
|
||||
evaluateBundleBudget(
|
||||
{
|
||||
initialJsGzipBytes: 100,
|
||||
initialJsFiles: 1,
|
||||
lazyChunks: [{ path: "lazy.js", gzipBytes: 121 }],
|
||||
},
|
||||
thresholds,
|
||||
).passed,
|
||||
).toBe(false);
|
||||
expect(
|
||||
evaluateBundleBudget(
|
||||
{ initialJsGzipBytes: 100, initialJsFiles: 3, lazyChunks: [] },
|
||||
thresholds,
|
||||
),
|
||||
).toMatchObject({ initialPassed: true, initialFilesPassed: false, passed: false });
|
||||
});
|
||||
|
||||
it("fails lab evidence when context is absent or a metric is over budget", () => {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* 0929/13-08. pnpm 11 reads its install policy from pnpm-workspace.yaml
|
||||
* (13-09 moved it out of .npmrc, which pnpm 11 ignores). Nothing failed when a
|
||||
* key was dropped or the release-age delay was shortened, so an unsupported
|
||||
* Node version could install again, a new dependency could be saved with a ^
|
||||
* range, or a version published minutes ago could be installed.
|
||||
*/
|
||||
const PNPM_DEFAULT_MINIMUM_RELEASE_AGE_MINUTES = 1_440;
|
||||
|
||||
describe("pnpm install policy (0929/13-08)", () => {
|
||||
it("keeps engineStrict, exact saves and at least the default release-age delay", async () => {
|
||||
const workspace = await readFile("pnpm-workspace.yaml", "utf8");
|
||||
const setting = (key: string) =>
|
||||
new RegExp(`^${key}:\\s*(\\S+)\\s*$`, "mu").exec(workspace)?.[1];
|
||||
|
||||
expect(setting("engineStrict")).toBe("true");
|
||||
expect(setting("saveExact")).toBe("true");
|
||||
const minimumReleaseAge = setting("minimumReleaseAge");
|
||||
if (minimumReleaseAge !== undefined) {
|
||||
expect(Number(minimumReleaseAge)).toBeGreaterThanOrEqual(PNPM_DEFAULT_MINIMUM_RELEASE_AGE_MINUTES);
|
||||
}
|
||||
});
|
||||
|
||||
it("excludes only exact versions from the release-age delay", async () => {
|
||||
const workspace = await readFile("pnpm-workspace.yaml", "utf8");
|
||||
const block = /^minimumReleaseAgeExclude:\n((?:\s+-\s+.+\n?)*)/mu.exec(workspace)?.[1] ?? "";
|
||||
const entries = block
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/^\s+-\s+/u, "").replaceAll("'", "").trim())
|
||||
.filter(Boolean);
|
||||
for (const entry of entries) expect(entry).toMatch(/^(?:@[^/@]+\/)?[^/@]+@\d+\.\d+\.\d+$/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts";
|
||||
import {
|
||||
loadProductCiOverlay,
|
||||
parseProductCiOverlay,
|
||||
PRODUCT_CI_OVERLAY_PATH,
|
||||
} from "../../scripts/contracts/product-ci-overlay.ts";
|
||||
import { renderCiWorkflow, workflowGateExecutionFailures } from "../../scripts/generate-ci-workflow.ts";
|
||||
|
||||
/**
|
||||
* 1103/12-07. A product attached its deployment and its own merge checks by
|
||||
* editing the template-owned config/ci/gates.json (3,000 lines) and the
|
||||
* generated workflow, and met them again in every template sync. The product
|
||||
* now writes them in config/ci/product-gates.json, which the template ships
|
||||
* empty and never changes.
|
||||
*/
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
async function productRoot(
|
||||
overlay: unknown,
|
||||
extraScripts: Readonly<Record<string, string>> = {},
|
||||
): Promise<string> {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "product-ci-overlay-"));
|
||||
roots.push(root);
|
||||
await mkdir(path.join(root, "config/ci"), { recursive: true });
|
||||
for (const file of ["config/ci/gates.json", "config/ci/contract-baseline.json"]) {
|
||||
await writeFile(path.join(root, file), await readFile(file));
|
||||
}
|
||||
const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as {
|
||||
scripts: Record<string, string>;
|
||||
};
|
||||
Object.assign(packageDocument.scripts, extraScripts);
|
||||
await writeFile(path.join(root, "package.json"), JSON.stringify(packageDocument, null, 2));
|
||||
await writeFile(path.join(root, PRODUCT_CI_OVERLAY_PATH), JSON.stringify(overlay, null, 2));
|
||||
return root;
|
||||
}
|
||||
|
||||
const DEPLOYMENT = {
|
||||
script: "deploy:desktop",
|
||||
environment: [
|
||||
{ name: "DEPLOY_HOST", value: "${{ vars.DEPLOY_HOST }}" },
|
||||
{ name: "DEPLOY_SSH_KEY", value: "${{ secrets.DEPLOY_SSH_KEY }}" },
|
||||
],
|
||||
};
|
||||
const DEPLOY_SCRIPTS = { "deploy:desktop": "node scripts/deploy-desktop.ts" };
|
||||
const GATE = { id: "PRODUCT-GATE-001", name: "backend-contract", script: "check:backend-contract" };
|
||||
const GATE_SCRIPTS = { "check:backend-contract": "node scripts/check-backend-contract.ts" };
|
||||
|
||||
describe("product CI overlay (1103/12-07)", () => {
|
||||
it("ships empty, so the template's own workflow is unchanged", async () => {
|
||||
expect(await loadProductCiOverlay(process.cwd())).toEqual({
|
||||
schemaVersion: 1,
|
||||
deployment: null,
|
||||
mergeGates: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fills the deployment slot with the promoted candidate and the product's script", async () => {
|
||||
const root = await productRoot(
|
||||
{ schemaVersion: 1, deployment: DEPLOYMENT, mergeGates: [] },
|
||||
DEPLOY_SCRIPTS,
|
||||
);
|
||||
|
||||
// The template baseline (config/ci/contract-baseline.json) is unchanged.
|
||||
const contract = await loadCiGateContract(root);
|
||||
const slot = contract.jobs.find(({ id }) => id === "deployment");
|
||||
expect(slot?.steps.map(({ kind }) => kind)).toEqual([
|
||||
"checkout",
|
||||
"setup-node",
|
||||
"frozen-install",
|
||||
"download",
|
||||
"extract",
|
||||
"deploy",
|
||||
]);
|
||||
expect(slot?.steps).toContainEqual(expect.objectContaining({ kind: "download", transferId: "promoted-release" }));
|
||||
expect(slot?.steps.at(-1)).toEqual({ kind: "deploy", script: "deploy:desktop" });
|
||||
expect(slot?.environment).toEqual([
|
||||
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
||||
...DEPLOYMENT.environment,
|
||||
]);
|
||||
|
||||
const workflow = renderCiWorkflow(contract);
|
||||
const job = workflow.slice(workflow.indexOf(" deployment:\n"), workflow.indexOf(" production_gate:\n"));
|
||||
expect(job).toContain("corepack pnpm deploy:desktop");
|
||||
expect(job.match(/secrets\./gu)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("refuses a slot filled in the template contract and in the overlay", async () => {
|
||||
const root = await productRoot(
|
||||
{ schemaVersion: 1, deployment: DEPLOYMENT, mergeGates: [] },
|
||||
DEPLOY_SCRIPTS,
|
||||
);
|
||||
const gatesPath = path.join(root, "config/ci/gates.json");
|
||||
const gates = JSON.parse(await readFile(gatesPath, "utf8")) as {
|
||||
jobs: { id: string; steps: unknown[]; environment: unknown[] }[];
|
||||
};
|
||||
const slot = gates.jobs.find(({ id }) => id === "deployment")!;
|
||||
slot.environment = [
|
||||
{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ needs.immutable_build.outputs.archive_sha256 }}" },
|
||||
];
|
||||
slot.steps = [
|
||||
{ kind: "download", transferId: "promoted-release", path: ".release/promoted" },
|
||||
{
|
||||
kind: "extract",
|
||||
archivePath: ".release/promoted/release-candidate.tar.gz",
|
||||
targetRoot: ".release/promoted-release",
|
||||
},
|
||||
{ kind: "deploy", script: "deploy:desktop" },
|
||||
];
|
||||
await writeFile(gatesPath, JSON.stringify(gates));
|
||||
|
||||
await expect(loadCiGateContract(root)).rejects.toThrow(/product-gates\.json/u);
|
||||
});
|
||||
|
||||
it("refuses an overlay script that package.json does not define", async () => {
|
||||
const root = await productRoot({ schemaVersion: 1, deployment: DEPLOYMENT, mergeGates: [GATE] });
|
||||
|
||||
await expect(loadCiGateContract(root)).rejects.toThrow(
|
||||
/missing package scripts: deploy:desktop, check:backend-contract/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("runs product merge gates in a job of their own, apart from the template gates", async () => {
|
||||
const root = await productRoot(
|
||||
{ schemaVersion: 1, deployment: null, mergeGates: [GATE] },
|
||||
GATE_SCRIPTS,
|
||||
);
|
||||
const contract = await loadCiGateContract(root);
|
||||
const { mergeGates } = await loadProductCiOverlay(root);
|
||||
|
||||
const workflow = renderCiWorkflow(contract, mergeGates);
|
||||
const job = workflow.slice(workflow.indexOf(" product_merge_gate:\n"));
|
||||
expect(job).toContain(' - { gate: PRODUCT-GATE-001, name: backend-contract, script: "check:backend-contract" }');
|
||||
expect(job).toContain(" run: corepack pnpm ${{ matrix.script }}");
|
||||
expect(job).toContain(` if: ${"${{ gitea.event_name != 'workflow_dispatch' || inputs.stage != 'documentation' }}"}`);
|
||||
expect(workflowGateExecutionFailures(contract, workflow, mergeGates)).toEqual([]);
|
||||
// The template part of the workflow is the same bytes with or without the overlay.
|
||||
expect(workflow.startsWith(renderCiWorkflow(contract).trimEnd())).toBe(true);
|
||||
|
||||
expect(workflowGateExecutionFailures(contract, renderCiWorkflow(contract), mergeGates)).toEqual([
|
||||
"product gate is not executed by the product_merge_gate job: PRODUCT-GATE-001",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a template gate id", { mergeGates: [{ ...GATE, id: "FE-GATE-030" }] }, /PRODUCT-GATE-NNN/u],
|
||||
["a duplicate gate id", { mergeGates: [GATE, { ...GATE, name: "other" }] }, /duplicate product gate/u],
|
||||
[
|
||||
"a binding to another job's output",
|
||||
{
|
||||
deployment: {
|
||||
...DEPLOYMENT,
|
||||
environment: [{ name: "NONCE", value: "${{ needs.promotion.outputs.staging_root }}" }],
|
||||
},
|
||||
},
|
||||
/vars\.\* or secrets\.\*/u,
|
||||
],
|
||||
[
|
||||
"the candidate digest the template binds",
|
||||
{
|
||||
deployment: {
|
||||
...DEPLOYMENT,
|
||||
environment: [{ name: "CANDIDATE_ARCHIVE_SHA256", value: "${{ vars.DIGEST }}" }],
|
||||
},
|
||||
},
|
||||
/CANDIDATE_ARCHIVE_SHA256/u,
|
||||
],
|
||||
["a script that is not a plain name", { deployment: { ...DEPLOYMENT, script: "deploy; rm -rf ." } }, /script/u],
|
||||
["an unknown field", { gates: [] }, /unrecognized|Unrecognized/u],
|
||||
] as const)("refuses %s", (_name, change, diagnostic) => {
|
||||
expect(() =>
|
||||
parseProductCiOverlay({ schemaVersion: 1, deployment: null, mergeGates: [], ...change }),
|
||||
).toThrow(diagnostic);
|
||||
});
|
||||
});
|
||||
+49
-2
@@ -1,3 +1,5 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
|
||||
import { defineConfig, loadEnv } from "vite";
|
||||
@@ -138,17 +140,48 @@ function createFeatureChunkGroups(root: string) {
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
/**
|
||||
* 1103/15-07. react-router publishes its production build under
|
||||
* dist/production, but its exports map points every condition at
|
||||
* dist/development. A production bundle carried the router's development
|
||||
* warnings (ENABLE_DEV_WARNINGS): 604 gzip bytes of initial JavaScript at
|
||||
* 15-07 and warnings in the production console. A build resolves the two
|
||||
* entries react-router-dom imports to the production files next to the
|
||||
* development entry. If an upgrade moves them, the build stops here rather
|
||||
* than silently shipping the development build again;
|
||||
* tests/unit/build-environment-bundle.test.ts checks the bundle. Remove this
|
||||
* when the package exports a production condition.
|
||||
*/
|
||||
function reactRouterProductionAliases(root: string) {
|
||||
const projectRequire = createRequire(path.join(root, "package.json"));
|
||||
const routerRequire = createRequire(projectRequire.resolve("react-router-dom"));
|
||||
const production = path.join(path.dirname(routerRequire.resolve("react-router")), "..", "production");
|
||||
const aliases = [
|
||||
{ find: /^react-router$/u, replacement: path.join(production, "index.mjs") },
|
||||
{ find: /^react-router\/dom$/u, replacement: path.join(production, "dom-export.mjs") },
|
||||
];
|
||||
const missing = aliases.filter(({ replacement }) => !existsSync(replacement));
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`react-router production build not found: ${missing.map(({ replacement }) => replacement).join(", ")}`,
|
||||
);
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
|
||||
export default defineConfig(({ command, mode }) => {
|
||||
assertDeclaredBuildVariables(mode);
|
||||
const base = routerBasePath(process.env);
|
||||
assertRuntimeConfigUnderBase(process.env, base);
|
||||
return {
|
||||
base,
|
||||
plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()],
|
||||
// Development keeps the router's warnings.
|
||||
resolve: command === "build" ? { alias: reactRouterProductionAliases(process.cwd()) } : {},
|
||||
build: {
|
||||
manifest: true,
|
||||
sourcemap: false,
|
||||
rollupOptions: {
|
||||
rolldownOptions: {
|
||||
/**
|
||||
* 1101/08-08. The design-system modules have no top-level effects:
|
||||
* they declare components, icons and token lists. Declared so, a
|
||||
@@ -182,6 +215,20 @@ export default defineConfig(({ mode }) => {
|
||||
// chunk would import the entry, whose hash changes with each
|
||||
// build id.
|
||||
{ name: "preload-helper", test: /vite[\\/]preload-helper/ },
|
||||
// 1103/15-06. react-dom and scheduler (about 56 KB gzip) shared
|
||||
// the boot-failure chunk with the build id, so a release that
|
||||
// only changed the build id renamed half of the initial
|
||||
// JavaScript (99,785 of 201,857 B) and returning visitors
|
||||
// downloaded it again. In a chunk of their own they keep their
|
||||
// name: the same change renames 44,297 B (boot, entry and the
|
||||
// boot-failure screen, which hold or import the build id).
|
||||
// The boot-failure screen still needs no module of the
|
||||
// application graph (09-03): this chunk is a library leaf.
|
||||
{
|
||||
name: "react-dom",
|
||||
test: /[\\/]node_modules[\\/](?:\.pnpm[\\/][^\\/]+[\\/]node_modules[\\/])?(?:react-dom|scheduler)[\\/]/,
|
||||
includeDependenciesRecursively: false,
|
||||
},
|
||||
// 1101/07-03. Every feature's schemas and runtime half import
|
||||
// the shared zod adapter. Alone it becomes a chunk of its own
|
||||
// once two features share it, and every route and runtime
|
||||
|
||||
@@ -76,7 +76,7 @@ export default defineConfig({
|
||||
// §17.2.2: exactly one input, exactly one output, no additional chunk.
|
||||
emptyOutDir: false,
|
||||
sourcemap: false,
|
||||
rollupOptions: {
|
||||
rolldownOptions: {
|
||||
input: "src/adapters/service-worker/service-worker-entry.ts",
|
||||
output: {
|
||||
format: "es",
|
||||
|
||||
Reference in New Issue
Block a user