From 2963c6f42c1e40ec14224cb4971d1f2b94d29325 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 20:35:11 +0900 Subject: [PATCH] =?UTF-8?q?fix(features):=20=EC=84=A0=ED=83=9D=20=EB=9F=B0?= =?UTF-8?q?=ED=83=80=EC=9E=84(SW=20=EB=93=B1)=20=EC=84=A0=ED=83=9D?= =?UTF-8?q?=EC=9D=84=20=EC=A0=9C=ED=92=88=20=EC=86=8C=EC=9C=A0=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=EB=A1=9C=20=EC=98=AE=EA=B8=B4=EB=8B=A4=20(1103/09-05)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 Service Worker를 켜는 유일한 방법은 src/features/installed-runtime-capabilities.ts의 SERVICE_WORKER 상수를 바꾸는 것이었다. 그 파일에는 "Product-owned." 표시가 없고, 매뉴얼 03 D절은 src/features/installed-*.ts를 고치지 말라고 한다. 매뉴얼대로 하면 SW를 켤 수 없고, 켜면 동기화마다 템플릿 파일을 손으로 병합한다. 템플릿 상태 설명과 제품 선택 상수가 한 블록에 섞여 있었다(1101/09-05). 고른 방법 리뷰의 최소 방향을 따른다. - 선택 상수 넷(REALTIME, WEB_WORKERS, SERVICE_WORKER, OFFLINE_COMMANDS)을 제품 소유 src/features/product-capabilities.ts의 PRODUCT_RUNTIME_CAPABILITY_SELECTION으로 옮긴다. 09-02에서 만든 같은 새 제품 소유 파일이다. product-contracts.ts에 넣지 않은 이유: 계약 층(src/contracts)이 아니라 기능 카탈로그 옆의 선택이고, 템플릿은 복사 뒤 기존 제품 소유 파일에 칸을 더하지 않는다. - installed-runtime-capabilities.ts는 템플릿 소유로 남고 그 선택을 검사 (validateRealtimeContributions, validateWebWorkerContributions)하고 투영만 한다. §3.5 설명과 템플릿 상태 설명은 여기에 남는다. - 매뉴얼 03 C절에 "SW 켜기"를 넣었다. 조립 거절 메시지, e2e SW 빌드 도우미의 편집 대상(premise 1), 레시피·운영 문서, dependency-cruiser 주석의 경로를 새 파일로 바꿨다. - 09-02 typecheck 테스트는 이제 출하된 product-capabilities.ts에 타입만 채우고 (선택은 유지), 복사 목록은 REMOVAL_FIXTURE_COPY_TARGETS 하나를 쓴다. 위험·한계 - 리뷰가 함께 제안한 composeProduct의 SW 연결 칸(blockers, observe)은 만들지 않았다. 그 연결은 여전히 템플릿 파일 create-runtime-composition.ts를 고쳐야 한다. 매뉴얼 "SW 켜기"에 적었다. - 템플릿 안의 선택을 이미 바꾼 다운스트림은 값을 새 파일로 옮겨야 한다. 검증 - RED: tests/unit/product-runtime-capability-selection.test.ts 3건(선택이 제품 소유 파일에만 있음, 제품 SW 선택 투영, 잘못된 선택은 여전히 검사)이 수정 전 실패. - 그 테스트, service-worker-build-output, optional-runtime-host, runtime-composition-service-worker-telemetry, product-features, product-extension-typecheck, runtime-adapters 통과. - check:types, check:architecture, eslint, verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-05 --- .dependency-cruiser.json | 2 +- docs/architecture/optional-adapter-recipes.md | 4 +- docs/manual/03-outside-feature-folder.md | 30 +++++++++ .../browser-file-storage-recovery.md | 2 +- docs/operations/release-cache-rollback.md | 2 +- src/bootstrap/optional-runtime-host.ts | 2 +- .../installed-runtime-capabilities.ts | 47 ++++++------- src/features/product-capabilities.ts | 29 ++++++++ tests/e2e/service-worker-update.spec.ts | 2 +- tests/e2e/support/service-worker-builds.ts | 8 +-- .../unit/product-extension-typecheck.test.ts | 45 +++---------- ...oduct-runtime-capability-selection.test.ts | 67 +++++++++++++++++++ .../unit/service-worker-build-output.test.ts | 2 +- 13 files changed, 170 insertions(+), 72 deletions(-) create mode 100644 tests/unit/product-runtime-capability-selection.test.ts diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index 133c1641..7f34a402 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -172,7 +172,7 @@ }, { "name": "unselected-realtime-runtime-is-not-composed", - "comment": "§9.2 / 12-10. Realtime and Web Push are NOT_SELECTED in the template (src/features/installed-runtime-capabilities.ts), so the composition root and the installed-feature registries do not import their concrete adapters. A project that selects one replaces this rule when it wires the runtime. Owner: frontend-platform.", + "comment": "§9.2 / 12-10. Realtime and Web Push are NOT_SELECTED in the template (src/features/product-capabilities.ts), so the composition root and the installed-feature registries do not import their concrete adapters. A project that selects one replaces this rule when it wires the runtime. Owner: frontend-platform.", "severity": "error", "from": { "path": "^src/(bootstrap/|features/installed-feature-)" diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 4281ddba..6b98ba1c 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -126,8 +126,10 @@ SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7과 2의 시작 실패 이벤트만 갖고 있다. -1. `src/features/installed-runtime-capabilities.ts`의 `SERVICE_WORKER`를 +1. 제품 소유 파일 `src/features/product-capabilities.ts`의 `SERVICE_WORKER`를 `ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다. + 템플릿 파일 `src/features/installed-runtime-capabilities.ts`는 그 선택을 + 검사하고 투영만 하므로 고치지 않는다. 2. 관측: `createRuntimeComposition`이 텔레메트리 포트를 optional host에 넘긴다 (`src/bootstrap/create-runtime-composition.ts`). 시작 결과가 `FAILED`나 `INCOMPATIBLE`이면 `service-worker.start.failed`가 1건 남는다 diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 923be2f8..bb4cfe7e 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -109,6 +109,7 @@ release admission refused for staging: - `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때. - 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다. - `config/runtime/.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`). +- `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다. - `package.json`, lockfile, `config/security/dependency-change-evidence.json`: 계약 패키지를 더할 때(B절). 정본 표에 없는 것: @@ -119,6 +120,35 @@ release admission refused for staging: 왜 이것들이 기능 폴더 밖인가: 제품 전체가 하나만 갖는 파일이다. 템플릿은 이 자리를 제품 소유로 비워 두었다. 템플릿을 동기화해도 제품의 내용과 충돌하지 않는다. +### SW 켜기 + +Service Worker는 기본으로 꺼져 있다. 켜는 것은 제품 소유 파일 하나만 고치는 일이다. + +```text +src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) + → src/features/installed-runtime-capabilities.ts (템플릿: 검사하고 그대로 투영) + → scripts/build-frontend.ts (worker 빌드를 한 번 더 돈다) + → createOptionalRuntimeHost (부팅 때 worker를 등록한다) +``` + +1. `src/features/product-capabilities.ts`의 `SERVICE_WORKER`를 바꾼다. + + ```ts + const SERVICE_WORKER: InstalledServiceWorkerSelection | null = { + mode: "ACTIVE", + scriptPath: "service-worker.js", + handlers: ["PWA_STATIC_ASSETS"], + }; + ``` + +2. `corepack pnpm build`로 `dist/service-worker.js`가 생기는지 본다. +3. 운영에서 끄려면 런타임 설정 `CAPABILITY_OVERRIDES.SERVICE_WORKER`를 쓴다. 런타임 설정은 끄기만 한다. 켜는 것은 이 파일뿐이다. +4. 지우려면 한 번에 `null`로 가지 않는다. `REMOVE_REGISTRATION` → `PURGE_OWNED_RESOURCES` → `null` 순서로 릴리스한다. 이미 설치된 브라우저의 worker를 먼저 내려야 한다. + +- 고치지 않는다: `src/features/installed-runtime-capabilities.ts`(템플릿 소유, D절). +- 템플릿이 아직 연결하지 않은 것: 저장하지 않은 편집이 있는 탭의 활성화 거절(`blockers`), page controller의 `observe`, 활성화 화면. 지금은 `src/bootstrap/create-runtime-composition.ts`(템플릿 소유)를 고쳐야 연결된다. 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다. +- realtime·Web Worker·오프라인 명령을 고르면 조립이 `Selected optional capabilities have no runtime to start them`로 거절한다. 템플릿 조립에 아직 그 런타임이 없다. + --- ## D. 고치지 않는다 diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 66ae77e5..da72af2e 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -512,7 +512,7 @@ bounded inspect/cleanup은 아직 없다. Service Worker의 waiting/client-drain 활성화는 page controller의 `requestActivation()` 핸드셰이크로 구현돼 있다 (`src/adapters/service-worker/service-worker-page-controller.ts`). 템플릿에는 이를 부르는 화면이 없다. Service Worker는 제품이 static selection -(`src/features/installed-runtime-capabilities.ts`)을 `ACTIVE`로 바꾼 경우에만 아래 +(`src/features/product-capabilities.ts`)을 `ACTIVE`로 바꾼 경우에만 아래 worker 절차를 적용한다. ### 신호 diff --git a/docs/operations/release-cache-rollback.md b/docs/operations/release-cache-rollback.md index 2ec859a3..02f44b01 100644 --- a/docs/operations/release-cache-rollback.md +++ b/docs/operations/release-cache-rollback.md @@ -49,7 +49,7 @@ The provider-independent cache defaults are: - runtime config and release manifest: `no-store` - public source maps: disabled - service worker/offline cache: disabled, unless the static selection in - `src/features/installed-runtime-capabilities.ts` is `ACTIVE` or + `src/features/product-capabilities.ts` is `ACTIVE` or `REMOVE_REGISTRATION`; then `dist` holds exactly the selected `service-worker.js`, served `no-cache` so the browser's update check sees each release's worker diff --git a/src/bootstrap/optional-runtime-host.ts b/src/bootstrap/optional-runtime-host.ts index fac1945a..6607c9d3 100644 --- a/src/bootstrap/optional-runtime-host.ts +++ b/src/bootstrap/optional-runtime-host.ts @@ -60,7 +60,7 @@ export function createOptionalRuntimeHost( if (unstartable.length > 0) { throw new TypeError( `Selected optional capabilities have no runtime to start them: ${unstartable.join(", ")}. ` + - "Connect a runtime in src/bootstrap/optional-runtime-host.ts or remove the selection from src/features/installed-runtime-capabilities.ts.", + "Connect a runtime in src/bootstrap/optional-runtime-host.ts or remove the selection from src/features/product-capabilities.ts.", ); } diff --git a/src/features/installed-runtime-capabilities.ts b/src/features/installed-runtime-capabilities.ts index 8e8d4d70..79bd68b0 100644 --- a/src/features/installed-runtime-capabilities.ts +++ b/src/features/installed-runtime-capabilities.ts @@ -1,29 +1,27 @@ -import type { InstalledOfflineCommandContribution } from "../contracts/offline-command.ts"; -import type { - InstalledRealtimeContribution, - InstalledRuntimeCapabilities, -} from "../contracts/runtime-capabilities.ts"; +import type { InstalledRuntimeCapabilities } from "../contracts/runtime-capabilities.ts"; import { validateRealtimeContributions, } from "../contracts/runtime-capabilities.ts"; -import type { InstalledServiceWorkerSelection } from "../contracts/service-worker.ts"; -import { - validateWebWorkerContributions, - type InstalledWebWorkerContribution, -} from "../contracts/web-worker.ts"; +import { validateWebWorkerContributions } from "../contracts/web-worker.ts"; +import { PRODUCT_RUNTIME_CAPABILITY_SELECTION } from "./product-capabilities.ts"; /** * §3.5. Static optional capability selection SSOT. * - * Runtime Config can only disable what this file already selected, and no + * Runtime Config can only disable what was selected at build time, and no * dynamic import path is ever built from a configuration string. * - * Only the Service Worker is installed by an entry here alone. Realtime, Web + * 1103/09-05. The selection itself is the product's: it is declared in the + * product-owned `product-capabilities.ts`, and turning the Service Worker on + * edits that file. This file stays the template's and only validates and + * projects it. + * + * Only the Service Worker is installed by a selection alone. Realtime, Web * Workers and offline commands have no runtime in the composition yet: a * selection without one makes `createOptionalRuntimeHost` refuse to compose - * (09-07). Connect the runtime there first. + * (09-07). * - * Current template state, matching the §25 stop conditions: + * The template ships every selection empty, matching the §25 stop conditions: * * - realtime: `NOT_SELECTED`. The RT-01..RT-04 common runtime exists and is * independently verified, but no product contribution supplies an exact @@ -35,19 +33,14 @@ import { * - offlineCommands: `NOT_SELECTED`. No external package declares a `KEYED` * operation with a recovery descriptor (§19.3). */ - -const REALTIME: readonly InstalledRealtimeContribution[] = Object.freeze([]); - -const WEB_WORKERS: readonly InstalledWebWorkerContribution[] = Object.freeze([]); - -const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null; - -const OFFLINE_COMMANDS: InstalledOfflineCommandContribution | null = null; - export const INSTALLED_RUNTIME_CAPABILITIES: InstalledRuntimeCapabilities = Object.freeze({ - realtime: validateRealtimeContributions(REALTIME), - webWorkers: validateWebWorkerContributions(WEB_WORKERS), - serviceWorker: SERVICE_WORKER, - offlineCommands: OFFLINE_COMMANDS, + realtime: validateRealtimeContributions( + PRODUCT_RUNTIME_CAPABILITY_SELECTION.realtime, + ), + webWorkers: validateWebWorkerContributions( + PRODUCT_RUNTIME_CAPABILITY_SELECTION.webWorkers, + ), + serviceWorker: PRODUCT_RUNTIME_CAPABILITY_SELECTION.serviceWorker, + offlineCommands: PRODUCT_RUNTIME_CAPABILITY_SELECTION.offlineCommands, }); diff --git a/src/features/product-capabilities.ts b/src/features/product-capabilities.ts index 894a7658..85fcb5ba 100644 --- a/src/features/product-capabilities.ts +++ b/src/features/product-capabilities.ts @@ -1,3 +1,8 @@ +import type { InstalledOfflineCommandContribution } from "../contracts/offline-command.ts"; +import type { InstalledRealtimeContribution } from "../contracts/runtime-capabilities.ts"; +import type { InstalledServiceWorkerSelection } from "../contracts/service-worker.ts"; +import type { InstalledWebWorkerContribution } from "../contracts/web-worker.ts"; + /** * Product-owned. The template ships it empty and does not change it after a * copy. @@ -9,6 +14,30 @@ * this interface, so every typecheck program that sees a feature sees these * keys too. A key the template builds (`http`, `telemetry`, `indexedDb`) * cannot be declared again here. + * - `PRODUCT_RUNTIME_CAPABILITY_SELECTION`: the static optional-capability + * selection (§3.5). Runtime Config can only switch off what is selected + * here. `installed-runtime-capabilities.ts` validates it. + * - `SERVICE_WORKER`: `{ mode: "ACTIVE", scriptPath: "service-worker.js", + * handlers: ["PWA_STATIC_ASSETS"] }` turns the worker on, and the build + * (`scripts/build-frontend.ts`) adds the worker pass. Removal is staged: + * `REMOVE_REGISTRATION`, then `PURGE_OWNED_RESOURCES`, then `null`. + * - `REALTIME`, `WEB_WORKERS`, `OFFLINE_COMMANDS`: the composition has no + * runtime to start them yet, so a selection makes it refuse to compose. */ export interface ProductFeaturePlatformCapabilities {} + +const REALTIME: readonly InstalledRealtimeContribution[] = Object.freeze([]); + +const WEB_WORKERS: readonly InstalledWebWorkerContribution[] = Object.freeze([]); + +const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null; + +const OFFLINE_COMMANDS: InstalledOfflineCommandContribution | null = null; + +export const PRODUCT_RUNTIME_CAPABILITY_SELECTION = Object.freeze({ + realtime: REALTIME, + webWorkers: WEB_WORKERS, + serviceWorker: SERVICE_WORKER, + offlineCommands: OFFLINE_COMMANDS, +}); diff --git a/tests/e2e/service-worker-update.spec.ts b/tests/e2e/service-worker-update.spec.ts index f6ed2f84..361c281a 100644 --- a/tests/e2e/service-worker-update.spec.ts +++ b/tests/e2e/service-worker-update.spec.ts @@ -14,7 +14,7 @@ import { * * How the worker is enabled: the template's default build has * `serviceWorker: null`, and the only supported switch is the static - * capability selection in `src/features/installed-runtime-capabilities.ts` + * capability selection in `src/features/product-capabilities.ts` * (`{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers: * ["PWA_STATIC_ASSETS"] }`); `scripts/build-frontend.ts` then adds the worker * build. `support/service-worker-builds.ts` applies that selection in a temp diff --git a/tests/e2e/support/service-worker-builds.ts b/tests/e2e/support/service-worker-builds.ts index 5469b9b2..4c132e6b 100644 --- a/tests/e2e/support/service-worker-builds.ts +++ b/tests/e2e/support/service-worker-builds.ts @@ -24,8 +24,8 @@ import type { StaticAssetManifestV1 } from "../../../src/contracts/service-worke * and a static server that can switch which one it serves. * * The template ships with `serviceWorker: null`. The supported way to turn the - * worker on is the static capability selection in - * `src/features/installed-runtime-capabilities.ts` (`mode: "ACTIVE"` with the + * worker on is the static capability selection in the product-owned + * `src/features/product-capabilities.ts` (`mode: "ACTIVE"` with the * `PWA_STATIC_ASSETS` handler); `scripts/build-frontend.ts` then runs the * two-pass worker build. Runtime Config can only disable it. So the helper * copies the repo to a temp dir, edits the selection there, and runs the @@ -40,7 +40,7 @@ import type { StaticAssetManifestV1 } from "../../../src/contracts/service-worke * * 0929/11-03. What the copy relies on, and where to change it when a product * changes that code: - * 1. `src/features/installed-runtime-capabilities.ts` has one + * 1. `src/features/product-capabilities.ts` has one * `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = …;`. * A selection that is already `ACTIVE` (a product that turned the worker * on) is kept as it is; anything else becomes `ACTIVE_VALUE`. @@ -72,7 +72,7 @@ export type ServiceWorkerBuilds = Readonly<{ precached: Readonly>; }>; -const SELECTION_FILE = "src/features/installed-runtime-capabilities.ts"; +const SELECTION_FILE = "src/features/product-capabilities.ts"; const SELECTION_DECLARATION = /(const SERVICE_WORKER: InstalledServiceWorkerSelection \| null = )([\s\S]*?);\n/gu; diff --git a/tests/unit/product-extension-typecheck.test.ts b/tests/unit/product-extension-typecheck.test.ts index 7606bc83..aaff8f7c 100644 --- a/tests/unit/product-extension-typecheck.test.ts +++ b/tests/unit/product-extension-typecheck.test.ts @@ -1,11 +1,12 @@ import { spawnSync } from "node:child_process"; -import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; +import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts"; /** * 1103/09-02. The product extension point has to hold on the typecheck path, @@ -23,13 +24,10 @@ import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.t * * Only product-owned files and the feature's own directory are written. */ -const PRODUCT_CAPABILITIES = `/** - * Product-owned. Filled by the 1103/09-02 typecheck fixture. - */ -export interface ProductFeaturePlatformCapabilities { +/** Filled into the shipped `product-capabilities.ts`, the rest kept. */ +const PRODUCT_CAPABILITY_TYPES = `export interface ProductFeaturePlatformCapabilities { readonly noticeSettings: Readonly<{ pageSize(): number }>; -} -`; +}`; const PRODUCT_CONTRACTS = `import { z } from "./zod.ts"; @@ -143,31 +141,6 @@ export const CONTEXT_ROUTE_PATH = "notice/*"; export const CONTEXT_MAX_FEATURES = 1; `; -/** What the three `check:types` programs include, plus what they import. */ -const COPIED = [ - "src", - "scripts", - "tests", - "recipes", - "config", - "schemas", - ".storybook", - "package.json", - "tsconfig.base.json", - "tsconfig.app.json", - "tsconfig.node.json", - "tsconfig.test.json", - "eslint.config.ts", - "vite.config.ts", - "vite.service-worker.config.ts", - "vitest.config.ts", - "playwright.config.ts", - "playwright.capabilities.config.ts", - "playwright.dev.config.ts", - "playwright.storybook.config.ts", - "playwright.visual.config.ts", -]; - const roots: string[] = []; afterAll(async () => { @@ -178,15 +151,19 @@ describe("1103/09-02 a product filled through its own files typechecks", () => { it("passes the app, node and test programs", async () => { const root = await mkdtemp(path.join(tmpdir(), "product-extension-typecheck-")); roots.push(root); - for (const entry of COPIED) { + // The repository's one copy-target list for a fixture copy. + for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) { await cp(path.resolve(entry), path.join(root, entry), { recursive: true, filter: (source) => !source.includes(`${path.sep}.generated`), }); } await linkFixtureNodeModules(root); + const shipped = await readFile(path.resolve("src/features/product-capabilities.ts"), "utf8"); + const emptyTypes = "export interface ProductFeaturePlatformCapabilities {}"; + expect(shipped.split(emptyTypes)).toHaveLength(2); const files: Readonly> = { - "src/features/product-capabilities.ts": PRODUCT_CAPABILITIES, + "src/features/product-capabilities.ts": shipped.replace(emptyTypes, PRODUCT_CAPABILITY_TYPES), "src/contracts/product-contracts.ts": PRODUCT_CONTRACTS, "src/bootstrap/product-composition.ts": PRODUCT_COMPOSITION, [`src/contexts/${CONTEXT_ID}/context-module.ts`]: CONTEXT_MODULE, diff --git a/tests/unit/product-runtime-capability-selection.test.ts b/tests/unit/product-runtime-capability-selection.test.ts new file mode 100644 index 00000000..7db973bf --- /dev/null +++ b/tests/unit/product-runtime-capability-selection.test.ts @@ -0,0 +1,67 @@ +import { readFile } from "node:fs/promises"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +/** + * 1103/09-05. The static optional-capability selection (§3.5) is the + * product's choice, so it lives in a product-owned file. Turning the Service + * Worker on is an edit there; `installed-runtime-capabilities.ts` stays the + * template's and only validates and projects what the product selected. + */ + +const source = (file: string) => + readFile(new URL(`../../${file}`, import.meta.url), "utf8"); + +const ACTIVE = Object.freeze({ + mode: "ACTIVE" as const, + scriptPath: "service-worker.js" as const, + handlers: Object.freeze(["PWA_STATIC_ASSETS" as const]), +}); + +afterEach(() => { + vi.doUnmock("../../src/features/product-capabilities.ts"); + vi.resetModules(); +}); + +async function installedWith(selection: Record) { + vi.resetModules(); + vi.doMock("../../src/features/product-capabilities.ts", () => ({ + PRODUCT_RUNTIME_CAPABILITY_SELECTION: Object.freeze({ + realtime: Object.freeze([]), + webWorkers: Object.freeze([]), + serviceWorker: null, + offlineCommands: null, + ...selection, + }), + })); + return (await import("../../src/features/installed-runtime-capabilities.ts")) + .INSTALLED_RUNTIME_CAPABILITIES; +} + +describe("1103/09-05 the optional runtime selection is product-owned", () => { + it("declares the selection in the product-owned file only", async () => { + const product = await source("src/features/product-capabilities.ts"); + const installed = await source("src/features/installed-runtime-capabilities.ts"); + + expect(product).toContain("Product-owned."); + // tests/e2e/support/service-worker-builds.ts premise 1 edits this line. + expect( + product.match(/const SERVICE_WORKER: InstalledServiceWorkerSelection \| null = /gu), + ).toHaveLength(1); + expect(installed).not.toContain("Product-owned."); + expect(installed).not.toMatch(/const (REALTIME|WEB_WORKERS|SERVICE_WORKER|OFFLINE_COMMANDS)\b/u); + }); + + it("projects the product's Service Worker selection", async () => { + const installed = await installedWith({ serviceWorker: ACTIVE }); + + expect(installed.serviceWorker).toEqual(ACTIVE); + expect(Object.isFrozen(installed)).toBe(true); + }); + + it("still validates what the product selected", async () => { + await expect( + installedWith({ webWorkers: Object.freeze([Object.freeze({ taskGroupId: "" })]) }), + ).rejects.toThrow(TypeError); + }); +}); diff --git a/tests/unit/service-worker-build-output.test.ts b/tests/unit/service-worker-build-output.test.ts index b3eedb97..0ec124e3 100644 --- a/tests/unit/service-worker-build-output.test.ts +++ b/tests/unit/service-worker-build-output.test.ts @@ -177,7 +177,7 @@ describe("turnOnServiceWorker (0929/06-04, 0929/11-03)", () => { try { const file = path.join( root, - "src/features/installed-runtime-capabilities.ts", + "src/features/product-capabilities.ts", ); await mkdir(path.dirname(file), { recursive: true }); const around = (selection: string) =>