From 8e0ea60eaceaa580b615f46cb57d472bd94c9774 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:33:48 +0900 Subject: [PATCH 1/5] =?UTF-8?q?perf(tech-log):=20MOCK=20=EC=86=8C=EC=8A=A4?= =?UTF-8?q?=EC=99=80=20Studio=20gateway=EB=A5=BC=20=EC=B2=AB=20=EC=82=AC?= =?UTF-8?q?=EC=9A=A9=20=EB=95=8C=20=EB=B0=9B=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 런타임 문서가 MOCK·HTTP를 고르므로 두 소스가 모든 빌드에 들어간다. 기능 입력 조립(create-tech-log-feature-input.ts)이 MOCK 공개 콘텐츠, MOCK·HTTP Studio gateway를 정적으로 가져와, 운영(HTTP) 공개 화면을 여는 사람도 그 코드를 초기 JS로 받았다. MOCK이 쓰는 content-format은 마크다운 파서(micromark·mdast·unified)까지 끌고 왔다. 초기 JS는 main 에서 300,869 B(gzip)로 예산 204,800 B를 넘는다(FE-GATE-012). 고른 방법 - 포트는 이미 모두 Promise를 돌려준다. deferAsyncPort가 포트를 먼저 만들고 첫 호출에서 구현 모듈을 동적 import해 넘긴다. 호출하는 쪽과 feature input의 모양(publicContent, createStudioApplication)은 그대로다. - 포트 키 목록은 `Record`로 적어, 포트에 메서드가 늘거나 줄면 타입 검사가 실패한다. - 구현 받기에 실패하면 잊고 다음 호출에서 다시 받는다. - MOCK 공개 콘텐츠는 첫 조회 때 받는다. HTTP 공개 gateway는 공개 첫 화면의 데이터 요청에 쓰이므로 그대로 둔다. - Studio gateway 셋(MOCK이면 Studio state 하나를 나눠 씀)은 묶음 하나로 받는다(mock-studio-gateways.ts, http-studio-gateways.ts). createStudioApplication은 Studio가 마운트될 때 불리므로 그때 바로 받기 시작한다(startNow). 첫 조회 때 받으면 화면 청크 → 조회 → gateway 청크 → 요청으로 한 번 더 기다린다. 버린 대안 - createStudioApplication을 async로 바꾸기: StudioProvider와 시험 15곳이 함께 바뀐다. 포트가 이미 비동기라 필요 없다. - 공개 HTTP gateway도 지연 로드: 첫 화면 데이터 요청 앞에 청크 왕복이 하나 생긴다. 위험·한계 - MOCK 빌드(로컬·e2e·visual)는 첫 공개 조회와 첫 Studio 조회 앞에 청크를 한 번 받는다. - 포트 메서드가 동기 값을 돌려주게 바뀌면 이 방식은 맞지 않는다. 타입 제약(모든 멤버가 Promise를 돌려줌)이 그때 컴파일에서 막는다. 검증 - desktop CI env 빌드: 초기 JS 300,869 → 232,337 B(Studio 셸 지연을 포함한 측정, 다음 커밋). 빠진 모듈 179개 중 npm(마크다운 파서) 약 88 KB, mock 23 KB, static 11 KB(모듈 단독 gzip 합). - tests/features/tech-log/deferred-async-port.test.ts: 한 번만 받기, 동시 첫 호출, 실패 뒤 다시 받기, 키·freeze, gateway 셋의 state 공유, startNow. --- .../adapters/create-tech-log-feature-input.ts | 72 +++++---- .../tech-log/adapters/deferred-async-port.ts | 39 +++++ .../adapters/deferred-tech-log-ports.ts | 137 ++++++++++++++++++ .../adapters/http/http-studio-gateways.ts | 33 +++++ .../adapters/mock/mock-studio-gateways.ts | 21 +++ .../tech-log/deferred-async-port.test.ts | 112 ++++++++++++++ 6 files changed, 375 insertions(+), 39 deletions(-) create mode 100644 src/features/tech-log/adapters/deferred-async-port.ts create mode 100644 src/features/tech-log/adapters/deferred-tech-log-ports.ts create mode 100644 src/features/tech-log/adapters/http/http-studio-gateways.ts create mode 100644 src/features/tech-log/adapters/mock/mock-studio-gateways.ts create mode 100644 tests/features/tech-log/deferred-async-port.test.ts diff --git a/src/features/tech-log/adapters/create-tech-log-feature-input.ts b/src/features/tech-log/adapters/create-tech-log-feature-input.ts index dd19d1a..e2a6232 100644 --- a/src/features/tech-log/adapters/create-tech-log-feature-input.ts +++ b/src/features/tech-log/adapters/create-tech-log-feature-input.ts @@ -6,17 +6,12 @@ import type { Asset } from "../contracts/studio/contract.ts"; import { createTechLogStudioApplication } from "../application/studio-application.ts"; import type { InstalledHttpOperationExecutor } from "../../../adapters/http/index.ts"; import { createTechLogHttpBinding } from "./http/tech-log-http-binding.ts"; -import { createAssetUploadTransport } from "./http/asset-upload-transport.ts"; -import { createHttpStudioAssetGateway } from "./http/http-studio-asset-gateway.ts"; -import { createHttpStudioGateway } from "./http/http-studio-gateway.ts"; import type { CsrfTokenProvider } from "./http/studio-session-csrf.ts"; -import { createMockStudioAssetGateway } from "./mock/mock-studio-asset-gateway.ts"; -import { createMockManagementGateway } from "./mock/mock-management-gateway.ts"; -import { createMockStudioState } from "./mock/mock-state.ts"; -import { createMockStudioGateway } from "./mock/mock-studio-gateway.ts"; -import { createHttpManagementGateway } from "./http/http-management-gateway.ts"; import { createHttpPublicContentGateway } from "./http/http-public-content-gateway.ts"; -import { publicContentQueries } from "./static/public-query.ts"; +import { + deferPublicContentQueries, + deferStudioGateways, +} from "./deferred-tech-log-ports.ts"; /** * The HTTP gateway builds no headers of its own — `Idempotency-Key` comes @@ -55,26 +50,18 @@ export function createTechLogFeatureInstalledInput( const mockAssets = new Map(); const http = createTechLogHttpBinding(context.http); - - const createStudioAssetGateway = () => - context.studioSource === "MOCK" - ? createMockStudioAssetGateway(mockAssets) - : createHttpStudioAssetGateway({ - http, - csrf: context.csrf, - upload: createAssetUploadTransport({ - baseUrl: context.apiBaseUrl, - timeoutMs: context.requestTimeoutMs, - }), - }); - - // The public read source switches independently of Studio: the two are // different services, and the combination that matters today is an authoring // backend that is live while the public read API is not. + // + // FE-GATE-012. Both sources ship in every build (the runtime document picks + // one), so the MOCK content is loaded on its first query instead of riding + // the initial JavaScript of a production page that reads HTTP. const publicContent = context.publicSource === "MOCK" - ? publicContentQueries + ? deferPublicContentQueries( + async () => (await import("./static/public-query.ts")).publicContentQueries, + ) : createHttpPublicContentGateway({ http }); // MOCK: one in-memory Studio state per application, shared by the document @@ -82,21 +69,28 @@ export function createTechLogFeatureInstalledInput( // also takes it out of the document list. Management used to be HTTP even // here, and a MOCK build (local development, the e2e and visual builds) // asked an API that is not there for its topics and projects. - const createStudioApplication = () => { - if (context.studioSource === "MOCK") { - const state = createMockStudioState(); - return createTechLogStudioApplication({ - studio: createMockStudioGateway({ assets: mockAssets, state }), - assets: createStudioAssetGateway(), - management: createMockManagementGateway({ studioState: state }), - }); - } - return createTechLogStudioApplication({ - studio: createHttpStudioGateway({ http }), - assets: createStudioAssetGateway(), - management: createHttpManagementGateway({ http }), - }); - }; + // + // FE-GATE-012. Studio's gateways, MOCK or HTTP, are a chunk of their own. + // StudioProvider calls this when Studio mounts, so the chunk starts loading + // then, next to the page chunk, rather than on the first query. Each call + // still gets its own set (and, for MOCK, its own state). + const createStudioApplication = () => + createTechLogStudioApplication( + deferStudioGateways( + async () => + context.studioSource === "MOCK" + ? (await import("./mock/mock-studio-gateways.ts")).createMockStudioGateways( + mockAssets, + ) + : (await import("./http/http-studio-gateways.ts")).createHttpStudioGateways({ + http, + csrf: context.csrf, + apiBaseUrl: context.apiBaseUrl, + requestTimeoutMs: context.requestTimeoutMs, + }), + { startNow: true }, + ), + ); const input: TechLogFeatureInput = Object.freeze({ publicContent, diff --git a/src/features/tech-log/adapters/deferred-async-port.ts b/src/features/tech-log/adapters/deferred-async-port.ts new file mode 100644 index 0000000..23213d0 --- /dev/null +++ b/src/features/tech-log/adapters/deferred-async-port.ts @@ -0,0 +1,39 @@ +type AsyncMethods = { + readonly [Key in keyof Port]: (...args: never[]) => Promise; +}; + +/** + * 모든 멤버가 Promise 를 돌려주는 포트를, 구현 모듈을 받기 전에 만든다. + * + * 부팅 그래프가 MOCK gateway·정적 공개 콘텐츠·Studio gateway 를 정적으로 가져와, 운영 + * 공개 화면을 여는 사람도 그 코드를 전부 초기 JS 로 받았다(FE-GATE-012). 포트는 이미 + * 비동기라, 첫 호출에서 구현을 받고 넘겨 주면 호출하는 쪽은 바뀌지 않는다. + * + * - `methods` 는 포트의 키 전부다. 타입이 빠진 키와 남는 키를 막는다. + * - 구현은 한 번만 받는다. 받기에 실패하면 잊고 다음 호출에서 다시 받는다 — 청크를 한 번 + * 못 받았다고 그 세션 내내 실패하지 않는다. + */ +export function deferAsyncPort>( + load: () => Promise, + methods: Readonly>, +): Port { + let loaded: Promise | undefined; + const target = (): Promise => { + loaded ??= load().catch((error: unknown) => { + loaded = undefined; + throw error; + }); + return loaded; + }; + const port: Record Promise> = {}; + for (const name of Object.keys(methods)) { + port[name] = async (...args: unknown[]) => { + const implementation = await target(); + const method = implementation[name as keyof Port] as unknown as ( + ...methodArgs: unknown[] + ) => Promise; + return method.apply(implementation, args); + }; + } + return Object.freeze(port) as unknown as Port; +} diff --git a/src/features/tech-log/adapters/deferred-tech-log-ports.ts b/src/features/tech-log/adapters/deferred-tech-log-ports.ts new file mode 100644 index 0000000..c104ffd --- /dev/null +++ b/src/features/tech-log/adapters/deferred-tech-log-ports.ts @@ -0,0 +1,137 @@ +import type { PublicContentQueries } from "../application/ports/public-content-queries.ts"; +import type { ManagementGateway } from "../application/ports/management-gateway.ts"; +import type { StudioAssetGateway } from "../application/ports/studio-asset-gateway.ts"; +import type { StudioGateway } from "../application/ports/studio-gateway.ts"; +import { deferAsyncPort } from "./deferred-async-port.ts"; + +/* + 포트마다 키 전부다. `Record` 라 포트에 메서드가 늘거나 줄면 타입 검사가 + 여기서 실패한다. +*/ +const PUBLIC_CONTENT_QUERY_METHODS = Object.freeze({ + listRecords: true, + getRecord: true, + getProject: true, + getRelease: true, + getProjectRecords: true, + getProjectDecisions: true, + getProjectActivity: true, + listTopics: true, + listContacts: true, + getTopicDetail: true, + getHome: true, + listProjects: true, + listReleases: true, + listCatalog: true, + getLatestEntries: true, + getHomeFocusItems: true, + searchPublicContent: true, +} as const satisfies Record); + +const STUDIO_GATEWAY_METHODS = Object.freeze({ + getDashboard: true, + listDocuments: true, + createDocument: true, + getDocument: true, + saveDocument: true, + validateDocument: true, + createPreview: true, + getCurrentPreview: true, + publishDocument: true, + unpublishPublication: true, + listPublications: true, + getPublicationSnapshot: true, + getCatalog: true, +} as const satisfies Record); + +const STUDIO_ASSET_GATEWAY_METHODS = Object.freeze({ + listAssets: true, + uploadAsset: true, + getAsset: true, + updateAssetMetadata: true, + deleteAsset: true, +} as const satisfies Record); + +const MANAGEMENT_GATEWAY_METHODS = Object.freeze({ + listTopics: true, + createTopic: true, + updateTopic: true, + deleteTopic: true, + listTopicVariants: true, + createTopicVariant: true, + updateTopicVariant: true, + deleteTopicVariant: true, + listProjects: true, + listQuestions: true, + listProjectDecisions: true, + getProject: true, + createProject: true, + updateProject: true, + deleteProject: true, + publishProject: true, + unpublishProject: true, + listProjectActivities: true, + createProjectActivity: true, + updateProjectActivity: true, + deleteProjectActivity: true, + getHomeFocus: true, + updateHomeFocus: true, + listReleases: true, + getRelease: true, + createRelease: true, + updateRelease: true, + deleteRelease: true, + publishRelease: true, + archiveRelease: true, + deleteDocument: true, + deleteDecision: true, +} as const satisfies Record); + +export function deferPublicContentQueries( + load: () => Promise, +): PublicContentQueries { + return deferAsyncPort(load, PUBLIC_CONTENT_QUERY_METHODS); +} + +export type StudioGateways = Readonly<{ + studio: StudioGateway; + assets: StudioAssetGateway; + management: ManagementGateway; +}>; + +/** + * Studio gateway 셋을 한 번에 받는다. 셋이 같은 구현 묶음(MOCK 이면 같은 Studio state)을 + * 써야 해서, 묶음 하나를 받고 각 포트가 그 안의 자기 gateway 로 넘긴다. + * + * `startNow` 면 첫 호출을 기다리지 않고 바로 받기 시작한다. Studio 가 마운트될 때 만들어지므로, + * 첫 조회 때 받으면 화면 청크 → 조회 → gateway 청크 → 요청으로 한 번 더 기다린다. 미리 받다 + * 실패해도 여기서 삼키고, 첫 호출이 다시 받는다. + */ +export function deferStudioGateways( + load: () => Promise, + { startNow = false }: Readonly<{ startNow?: boolean }> = {}, +): StudioGateways { + let loaded: Promise | undefined; + const gateways = (): Promise => { + loaded ??= load().catch((error: unknown) => { + loaded = undefined; + throw error; + }); + return loaded; + }; + if (startNow) void gateways().catch(() => undefined); + return Object.freeze({ + studio: deferAsyncPort( + async () => (await gateways()).studio, + STUDIO_GATEWAY_METHODS, + ), + assets: deferAsyncPort( + async () => (await gateways()).assets, + STUDIO_ASSET_GATEWAY_METHODS, + ), + management: deferAsyncPort( + async () => (await gateways()).management, + MANAGEMENT_GATEWAY_METHODS, + ), + }); +} diff --git a/src/features/tech-log/adapters/http/http-studio-gateways.ts b/src/features/tech-log/adapters/http/http-studio-gateways.ts new file mode 100644 index 0000000..a13a3ad --- /dev/null +++ b/src/features/tech-log/adapters/http/http-studio-gateways.ts @@ -0,0 +1,33 @@ +import { createAssetUploadTransport } from "./asset-upload-transport.ts"; +import { createHttpManagementGateway } from "./http-management-gateway.ts"; +import { createHttpStudioAssetGateway } from "./http-studio-asset-gateway.ts"; +import { createHttpStudioGateway } from "./http-studio-gateway.ts"; +import type { CsrfTokenProvider } from "./studio-session-csrf.ts"; +import type { TechLogHttpBinding } from "./tech-log-http-binding.ts"; + +export type HttpStudioGatewaysContext = Readonly<{ + http: TechLogHttpBinding; + csrf: CsrfTokenProvider; + apiBaseUrl: string; + requestTimeoutMs: number; +}>; + +/** + * HTTP Studio 의 gateway 셋. Studio 에 들어갈 때 받는 청크다 + * (`create-tech-log-feature-input.ts`). 공개 화면은 이 코드를 쓰지 않는다. + */ +export function createHttpStudioGateways(context: HttpStudioGatewaysContext) { + const { http } = context; + return Object.freeze({ + studio: createHttpStudioGateway({ http }), + assets: createHttpStudioAssetGateway({ + http, + csrf: context.csrf, + upload: createAssetUploadTransport({ + baseUrl: context.apiBaseUrl, + timeoutMs: context.requestTimeoutMs, + }), + }), + management: createHttpManagementGateway({ http }), + }); +} diff --git a/src/features/tech-log/adapters/mock/mock-studio-gateways.ts b/src/features/tech-log/adapters/mock/mock-studio-gateways.ts new file mode 100644 index 0000000..d138366 --- /dev/null +++ b/src/features/tech-log/adapters/mock/mock-studio-gateways.ts @@ -0,0 +1,21 @@ +import type { Asset } from "../../contracts/studio/contract.ts"; +import { createMockManagementGateway } from "./mock-management-gateway.ts"; +import { createMockStudioAssetGateway } from "./mock-studio-asset-gateway.ts"; +import { createMockStudioState } from "./mock-state.ts"; +import { createMockStudioGateway } from "./mock-studio-gateway.ts"; + +/** + * MOCK Studio 의 gateway 셋. Studio 에 들어갈 때 받는 청크다 + * (`create-tech-log-feature-input.ts`). + * + * 문서 gateway 와 관리 gateway 는 Studio state 하나를 나눠 쓴다 — 관리 화면에서 작업본을 + * 지우면 문서 목록에서도 빠진다. Asset 저장소는 앱 하나에 하나라 호출하는 쪽이 넘긴다. + */ +export function createMockStudioGateways(assets: Map) { + const state = createMockStudioState(); + return Object.freeze({ + studio: createMockStudioGateway({ assets, state }), + assets: createMockStudioAssetGateway(assets), + management: createMockManagementGateway({ studioState: state }), + }); +} diff --git a/tests/features/tech-log/deferred-async-port.test.ts b/tests/features/tech-log/deferred-async-port.test.ts new file mode 100644 index 0000000..09b8b95 --- /dev/null +++ b/tests/features/tech-log/deferred-async-port.test.ts @@ -0,0 +1,112 @@ +import assert from "node:assert/strict"; +import { test } from "vitest"; + +import { deferAsyncPort } from "../../../src/features/tech-log/adapters/deferred-async-port.ts"; +import { deferStudioGateways } from "../../../src/features/tech-log/adapters/deferred-tech-log-ports.ts"; +import { createMockStudioGateways } from "../../../src/features/tech-log/adapters/mock/mock-studio-gateways.ts"; +import { FIXTURE_IDS } from "../../../src/features/tech-log/adapters/mock/fixtures.ts"; +import type { Asset } from "../../../src/features/tech-log/contracts/studio/contract.ts"; + +type Greeter = Readonly<{ + greet(name: string): Promise; + count(): Promise; +}>; + +function greeterImplementation(): Greeter { + let calls = 0; + return { + async greet(name) { + calls += 1; + return `hello ${name}`; + }, + async count() { + return calls; + }, + }; +} + +const GREETER_METHODS = { greet: true, count: true } as const; + +test("구현을 첫 호출에서 한 번만 받고 모든 메서드가 같은 구현을 쓴다", async () => { + let loads = 0; + const port = deferAsyncPort(async () => { + loads += 1; + return greeterImplementation(); + }, GREETER_METHODS); + + assert.equal(loads, 0, "만들기만 해서는 구현을 받지 않는다"); + assert.equal(await port.greet("a"), "hello a"); + assert.equal(await port.greet("b"), "hello b"); + assert.equal(await port.count(), 2); + assert.equal(loads, 1); +}); + +test("동시에 들어온 첫 호출들도 구현을 한 번만 받는다", async () => { + let loads = 0; + const port = deferAsyncPort(async () => { + loads += 1; + await Promise.resolve(); + return greeterImplementation(); + }, GREETER_METHODS); + + await Promise.all([port.greet("a"), port.greet("b"), port.count()]); + assert.equal(loads, 1); +}); + +test("구현을 받지 못하면 그 호출은 실패하고 다음 호출에서 다시 받는다", async () => { + let loads = 0; + const port = deferAsyncPort(async () => { + loads += 1; + if (loads === 1) throw new TypeError("Failed to fetch dynamically imported module"); + return greeterImplementation(); + }, GREETER_METHODS); + + await assert.rejects(port.greet("a"), /dynamically imported module/u); + assert.equal(await port.greet("b"), "hello b"); + assert.equal(loads, 2); +}); + +test("포트는 선언한 메서드만 가진 얼린 객체다", () => { + const port = deferAsyncPort(async () => greeterImplementation(), GREETER_METHODS); + + assert.deepEqual(Object.keys(port).sort(), ["count", "greet"]); + assert.equal(Object.isFrozen(port), true); +}); + +test("Studio gateway 셋은 구현 묶음 하나를 같이 쓴다", async () => { + let loads = 0; + const assets = new Map(); + const gateways = deferStudioGateways(async () => { + loads += 1; + return createMockStudioGateways(assets); + }); + + assert.equal(loads, 0); + const draft = (await gateways.studio.getDocument(FIXTURE_IDS.conflictCase)).document; + await gateways.management.deleteDocument("CASE", draft.id, draft.version, { + idempotencyKey: "deferred-shared-state", + }); + // 관리 gateway 로 지운 작업본이 같은 묶음의 문서 gateway 에서도 사라진다. + await assert.rejects(gateways.studio.getDocument(FIXTURE_IDS.conflictCase)); + await gateways.assets.listAssets({}); + assert.equal(loads, 1); +}); + +test("startNow 면 만들 때 받기 시작하고, 그때의 실패는 첫 호출이 다시 받는다", async () => { + let loads = 0; + const assets = new Map(); + const gateways = deferStudioGateways( + async () => { + loads += 1; + if (loads === 1) throw new TypeError("Failed to fetch dynamically imported module"); + return createMockStudioGateways(assets); + }, + { startNow: true }, + ); + + assert.equal(loads, 1, "만들자마자 받기 시작한다"); + // 미리 받기의 실패가 처리된 뒤 첫 호출이 들어온다. + await new Promise((resolve) => setTimeout(resolve, 0)); + await gateways.studio.getDashboard(); + assert.equal(loads, 2); +}); -- 2.54.0 From 02cf5ed3f98f0409141c340b7fc870c8853f2115 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:33:48 +0900 Subject: [PATCH 2/5] =?UTF-8?q?perf(studio):=20Studio=20=EC=85=B8=EC=9D=84?= =?UTF-8?q?=20/studio=EC=97=90=20=EB=93=A4=EC=96=B4=EA=B0=88=20=EB=95=8C?= =?UTF-8?q?=20=EB=B0=9B=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 라우트 레이아웃 표(tech-log-route-runtime.tsx)가 StudioShell을 정적으로 가져와, 공개 화면의 초기 JS에 StudioProvider·Studio 머리말·문서 server state가 들어갔다. 고른 방법 - STUDIO 레이아웃은 lazy StudioShell을 Suspense와 ChunkRecoveryBoundary로 감싼다. 청크를 못 받으면 라우트 청크와 같은 recoverChunk가 한 번 새로 읽기를 정한다(chunkId `tech-log-studio-shell`). - tests/features/tech-log/boot-graph.test.ts가 부팅 그래프(main.tsx, 그 정적 import, 진입점이 바로 동적으로 읽는 boot·render-boot-failure)를 빌드 없이 따라가, MOCK 소스·정적 콘텐츠·Studio 화면·HTTP Studio gateway가 다시 들어오지 않는지 본다. 공개 셸과 기능 입력 조립이 그래프에 있는지도 봐서 빈 결과로 통과하지 않는다. 버린 대안 - 템플릿 소유 app-router.tsx에서 레이아웃 route에 lazy를 거는 것: 템플릿 파일을 고치게 되고, 자식 화면 청크는 여전히 셸 뒤에 받는다. 위험·한계 - /studio 첫 진입은 셸 청크를 받은 뒤 화면 청크를 받는다(직렬 왕복 하나). Studio는 작성자 한 사람이 쓰는 화면이다. - 셸을 받는 동안 LoadingSurface가 보인다. 검증 - desktop CI env 빌드: 앞 커밋과 함께 초기 JS 300,869 → 232,337 B. - boot-graph.test.ts 통과. --- .../presentation/tech-log-route-runtime.tsx | 34 ++++- tests/features/tech-log/boot-graph.test.ts | 117 ++++++++++++++++++ 2 files changed, 148 insertions(+), 3 deletions(-) create mode 100644 tests/features/tech-log/boot-graph.test.ts diff --git a/src/features/tech-log/presentation/tech-log-route-runtime.tsx b/src/features/tech-log/presentation/tech-log-route-runtime.tsx index 344bc96..fea021f 100644 --- a/src/features/tech-log/presentation/tech-log-route-runtime.tsx +++ b/src/features/tech-log/presentation/tech-log-route-runtime.tsx @@ -1,17 +1,45 @@ import { lazy, + Suspense, type ComponentType, type LazyExoticComponent, type ReactNode, } from "react"; import { Outlet } from "react-router-dom"; +import { ChunkRecoveryBoundary } from "../../../presentation/boundaries/chunk-recovery-boundary.tsx"; +import { LoadingSurface } from "../../../presentation/design-system/index.ts"; +import { useApplicationRecovery } from "../../../presentation/providers/application-provider.tsx"; import { TECH_LOG_ROUTE_RUNTIME_CONTRACT, type TechLogRouteId, } from "../contracts/tech-log-route-contract.ts"; import { PublicShell } from "./public/public-shell.tsx"; -import { StudioShell } from "./studio/studio-shell.tsx"; + +/* + Studio 셸은 공개 화면을 읽는 사람에게 필요 없다. 정적으로 가져오면 셸이 끌고 오는 + StudioProvider·Studio 머리말·문서 server state 가 모든 첫 화면의 초기 JS 에 들어갔다 + (FE-GATE-012). /studio 에 들어갈 때 받는다. 라우트 청크와 같이 청크를 못 받으면 + ChunkRecoveryBoundary 가 한 번 새로 읽기를 정한다. +*/ +const StudioShell = lazy(async () => { + const module = await import("./studio/studio-shell.tsx"); + return { default: module.StudioShell }; +}); + +function DeferredStudioShell({ children }: Readonly<{ children: ReactNode }>) { + const recovery = useApplicationRecovery(); + return ( + + }> + {children} + + + ); +} type RouteRuntime = Readonly<{ moduleId: string; @@ -297,8 +325,8 @@ export const TECH_LOG_ROUTE_LAYOUTS: Readonly< ), STUDIO: ( - + - + ), }); diff --git a/tests/features/tech-log/boot-graph.test.ts b/tests/features/tech-log/boot-graph.test.ts new file mode 100644 index 0000000..f25cf8c --- /dev/null +++ b/tests/features/tech-log/boot-graph.test.ts @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { parseAsync } from "@babel/core"; +import { test } from "vitest"; + +/** + * FE-GATE-012. 첫 화면의 초기 JS 는 진입점(main.tsx), 그 정적 import, 진입점이 바로 + * 동적으로 읽는 boot·render-boot-failure 와 그 정적 import 다 + * (`scripts/lib/classify-vite-bundle.ts`). 공개 화면을 읽는 사람에게 필요 없는 아래 코드가 + * 정적 import 하나로 이 그래프에 다시 들어오면 번들 예산을 넘는다. 빌드 없이 여기서 먼저 잡는다. + */ +const BOOT_SEEDS = [ + "src/bootstrap/main.tsx", + "src/bootstrap/boot.tsx", + "src/bootstrap/render-boot-failure.tsx", +]; + +const DEFERRED = [ + // MOCK 소스: 런타임 문서가 MOCK 을 고른 빌드(로컬·시험)에서만 쓰인다. + "src/features/tech-log/adapters/mock/", + "src/features/tech-log/adapters/static/", + // Studio: /studio 에 들어갈 때 받는다. + "src/features/tech-log/presentation/studio/", + "src/features/tech-log/adapters/http/http-studio-gateways.ts", + "src/features/tech-log/adapters/http/http-studio-gateway.ts", + "src/features/tech-log/adapters/http/http-management-gateway.ts", + "src/features/tech-log/adapters/http/http-studio-asset-gateway.ts", + "src/features/tech-log/adapters/http/asset-upload-transport.ts", +]; + +type Node = Readonly & { type: string }>; + +function isTypeOnly(statement: Node): boolean { + if (statement["importKind"] === "type" || statement["exportKind"] === "type") return true; + const specifiers = statement["specifiers"] as readonly Node[] | undefined; + if (statement.type !== "ImportDeclaration" || !specifiers || specifiers.length === 0) { + return false; + } + // `import { type A, type B } from "x"` 는 컴파일 뒤 남지 않는다(verbatimModuleSyntax 없음). + return specifiers.every((specifier) => specifier["importKind"] === "type"); +} + +function resolveRelative(from: string, specifier: string): string | undefined { + if (!specifier.startsWith(".")) return undefined; + const target = path.posix.normalize(path.posix.join(path.posix.dirname(from), specifier)); + if (!/\.tsx?$/u.test(target)) return undefined; + assert.ok(existsSync(target), `${from} 가 없는 파일을 가져온다: ${specifier}`); + return target; +} + +async function staticImports(file: string): Promise { + const plugins: ("jsx" | ["typescript", { dts: boolean }])[] = [["typescript", { dts: false }]]; + if (file.endsWith(".tsx")) plugins.push("jsx"); + const tree = (await parseAsync(readFileSync(file, "utf8"), { + filename: file, + babelrc: false, + configFile: false, + sourceType: "module", + parserOpts: { plugins }, + })) as unknown as { program: { body: readonly Node[] } } | null; + assert.ok(tree, `cannot parse ${file}`); + const imports: string[] = []; + for (const statement of tree.program.body) { + if ( + statement.type !== "ImportDeclaration" && + statement.type !== "ExportNamedDeclaration" && + statement.type !== "ExportAllDeclaration" + ) { + continue; + } + const source = statement["source"] as Node | null | undefined; + if (!source || isTypeOnly(statement)) continue; + const resolved = resolveRelative(file, String(source["value"])); + if (resolved) imports.push(resolved); + } + return imports; +} + +async function bootGraph(): Promise> { + const importedBy = new Map(BOOT_SEEDS.map((seed) => [seed, "(seed)"])); + const pending = [...BOOT_SEEDS]; + while (pending.length > 0) { + const file = pending.pop()!; + for (const imported of await staticImports(file)) { + if (importedBy.has(imported)) continue; + importedBy.set(imported, file); + pending.push(imported); + } + } + return importedBy; +} + +function chain(importedBy: ReadonlyMap, file: string): string { + const links = [file]; + let current = importedBy.get(file); + while (current && current !== "(seed)") { + links.push(current); + current = importedBy.get(current); + } + return links.join(" <- "); +} + +test("공개 첫 화면의 부팅 그래프에 MOCK 소스와 Studio 코드가 없다", async () => { + const graph = await bootGraph(); + + // 그래프를 제대로 따라갔는지: 공개 셸과 기능 입력 조립은 부팅 때 필요하다. + assert.ok(graph.has("src/features/tech-log/presentation/public/public-shell.tsx")); + assert.ok(graph.has("src/features/tech-log/adapters/create-tech-log-feature-input.ts")); + + const leaked = [...graph.keys()] + .filter((file) => DEFERRED.some((prefix) => file.startsWith(prefix))) + .sort() + .map((file) => chain(graph, file)); + assert.deepEqual(leaked, [], `부팅 그래프로 들어온 지연 코드:\n${leaked.join("\n")}`); +}); -- 2.54.0 From 0bb8f1df9cf338701bf4e6f8bb83c15a54247ac3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:33:48 +0900 Subject: [PATCH 3/5] =?UTF-8?q?perf(build):=20design-system=20=EB=AA=A8?= =?UTF-8?q?=EB=93=88=EC=9D=84=20side=20effect=20=EC=97=86=EC=9D=8C?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=84=A0=EC=96=B8=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 공개 셸은 design-system/index.ts 배럴에서 Button 몇 개를 가져온다. 번들러는 배럴이 다시 내보내는 모듈을 side effect가 있다고 보고 모두 싣는다. 그래서 공개 첫 화면이 쓰지 않는 navigation·overlays·patterns primitive와 폼 모듈(use-app-form 등)이 초기 JS에 있었다. 고른 방법 - 템플릿 1101/08-08(51941a54)과 같은 treeshake.moduleSideEffects 규칙을 vite.config.ts에 둔다. 같은 vite 8.1.5다. - design-system 파일은 선언만 하고 top-level 효과가 없다. 효과만을 위한 import(`import "x"`)는 이 선언 아래에서 모듈과 같이 사라지므로, tests/unit/design-system-side-effects.test.ts가 그런 import가 없는지 본다. CSS는 bootstrap/main.tsx에서 읽는다. - 배럴을 통해서만 닿던 폼 모듈도 같이 빠진다. 폼 모듈에도 top-level 효과가 없는 것을 확인했다. 위험·한계 - 초기 파일 수가 27개에서 28개로 는다. HTTP/2에서는 진입 청크의 preload 목록으로 병렬로 받는다(템플릿 같은 판단). 검증 - desktop CI env 분석 빌드: 초기 JS 229,765 → 226,554 B(-3,211 B, 분석 빌드 기준. 공식 수치는 예산 커밋). --- tests/unit/design-system-side-effects.test.ts | 32 +++++++++++++++++++ vite.config.ts | 15 +++++++++ 2 files changed, 47 insertions(+) create mode 100644 tests/unit/design-system-side-effects.test.ts diff --git a/tests/unit/design-system-side-effects.test.ts b/tests/unit/design-system-side-effects.test.ts new file mode 100644 index 0000000..1b2e8e1 --- /dev/null +++ b/tests/unit/design-system-side-effects.test.ts @@ -0,0 +1,32 @@ +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const DESIGN_SYSTEM = "src/presentation/design-system"; + +function sourceFiles(directory: string): string[] { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const file = path.posix.join(directory, entry.name); + if (entry.isDirectory()) return sourceFiles(file); + return /\.tsx?$/u.test(entry.name) && !/\.stories\.tsx?$/u.test(entry.name) + ? [file] + : []; + }); +} + +/** + * vite.config.ts 가 design-system 모듈을 side effect 없음으로 선언한다(템플릿 1101/08-08). + * 그 아래에서는 `import "x"` 처럼 효과만을 위한 import 가 모듈과 같이 빌드에서 사라진다. + * 그런 import 가 생기면 선언이 틀린 것이다. + */ +describe("design-system modules declared free of side effects", () => { + it("hold no import kept only for its effect", () => { + const files = sourceFiles(DESIGN_SYSTEM); + expect(files.length).toBeGreaterThan(0); + const effectOnly = files.filter((file) => + /^\s*import\s+["'][^"']+["']/mu.test(readFileSync(file, "utf8")), + ); + expect(effectOnly).toEqual([]); + }); +}); diff --git a/vite.config.ts b/vite.config.ts index 6000eeb..003f48a 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -138,6 +138,21 @@ export default defineConfig(({ mode }) => { // Template sync (af3d8e6): the template's chunk groups, then TechLog's // named route chunks, in the template's `codeSplitting` form. rolldownOptions: { + /* + 템플릿 1101/08-08(51941a54)과 같다. design-system 모듈은 컴포넌트·아이콘·토큰 목록을 + 선언만 하고 top-level 효과가 없다. 그렇게 선언해 두면 공개 셸이 배럴(index.ts)에서 + Button 하나를 가져와도, 아무 export 도 안 쓰인 primitive 파일은 초기 청크에서 + 빠진다. 효과만을 위한 import 를 두면 선언 아래에서 모듈과 같이 사라지므로 이 범위에는 + 그런 import 가 없다. CSS 는 bootstrap/main.tsx 에서 읽는다. + */ + treeshake: { + moduleSideEffects: [ + { + test: /[\\/]src[\\/]presentation[\\/]design-system[\\/].+\.tsx?$/, + sideEffects: false, + }, + ], + }, output: { codeSplitting: { groups: [ -- 2.54.0 From 7558a8f495d15228888a4dda127310bc8a6bf1e4 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:33:48 +0900 Subject: [PATCH 4/5] =?UTF-8?q?build(perf):=20=EC=B4=88=EA=B8=B0=20JS=20?= =?UTF-8?q?=EC=98=88=EC=82=B0=EC=9D=84=20TechLog=20=EC=B8=A1=EC=A0=95?= =?UTF-8?q?=EA=B0=92=EC=9C=BC=EB=A1=9C=20225=20KiB=EC=97=90=20=EB=91=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 예산 204,800 B는 템플릿을 받을 때의 기본값이다. TechLog는 기능을 붙인 뒤 예산을 다시 정하지 않았다(템플릿 문서는 첫 기능을 추가하기 전에 정하라고 한다). 앞 커밋들로 초기 JS를 300,869 B에서 229,224 B로 줄였지만, 템플릿 공통 부분(react-dom·react-router·zod·tanstack·플랫폼 src)만 약 205 KB여서 TechLog 코드를 모두 빼도 204,800 B 안에 들지 않는다. 고른 방법 - 템플릿 규칙(1106/15-01, 결정 D9)을 그대로 쓴다. CI env 측정값에 기능 하나의 상한 1 KiB를 더해 KiB 단위로 올린다. 229,224 + 1,024 = 230,248 B → 225 KiB = 230,400 B. 여유 1,176 B는 기능 하나와 올림 몫이다. - docs/operations/performance-evidence.md에 전후 수치, 뺀 것, 204,800 B로 돌아가지 못한 이유, 다시 볼 조건과 되돌림 규칙을 적는다. feature-shape-ceilings.json의 예산 언급도 맞춘다. 버린 대안 - 남은 TechLog 몫(문구 catalog 약 7.5 KB, 공개 HTTP gateway·mapping 약 6.7 KB, Studio·관리·공개 계약 약 6.6 KB, 모듈 단독 gzip)을 더 빼기. 문구와 계약은 부팅 때 합쳐 검증하는 구조라, 템플릿 15-01(기능 실행부를 라우트 진입 때 적재)을 옮기는 템플릿 동기화 일이다. 공개 gateway는 첫 화면 데이터 요청에 쓰인다. 위험·한계 - 예산이 템플릿보다 23,552 B 크다. 템플릿 동기화로 15-01을 받으면 다시 재고 같은 규칙으로 내린다. 측정값이 203,776 B 이하이면 200 KiB로 돌아간다. 검증 - desktop CI env(CI=true, VITE_BUILD_ID, RELEASE_ID, VITE_COMMIT_SHA, CI_RUNNER_IMAGE): 초기 JS 229,224 B, 초기 파일 28개, 가장 큰 lazy chunk 40,038 B(예산 122,880 B). --- config/performance/budgets.json | 2 +- config/scale/feature-shape-ceilings.json | 2 +- docs/operations/performance-evidence.md | 56 +++++++++++++++++++++++- 3 files changed, 57 insertions(+), 3 deletions(-) diff --git a/config/performance/budgets.json b/config/performance/budgets.json index adf9cc7..417a0d5 100644 --- a/config/performance/budgets.json +++ b/config/performance/budgets.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "bundle": { - "initialJsGzipBytes": 204800, + "initialJsGzipBytes": 230400, "lazyChunkGzipBytes": 122880 }, "lab": { diff --git a/config/scale/feature-shape-ceilings.json b/config/scale/feature-shape-ceilings.json index 1731d96..faef43f 100644 --- a/config/scale/feature-shape-ceilings.json +++ b/config/scale/feature-shape-ceilings.json @@ -23,7 +23,7 @@ "axis": "Initial JavaScript", "verified": "Grows by about 2.9 KB gzip and one file per feature: every installed feature's contracts and module load at boot", "condition": "Same", - "notVerified": "The initial budget (204,800 B, config/performance/budgets.json) is exceeded after a few more reference-shaped features, far below the context ceiling" + "notVerified": "The initial budget (230,400 B, config/performance/budgets.json) is exceeded after a few more reference-shaped features, far below the context ceiling" }, { "axis": "Lazy JavaScript", diff --git a/docs/operations/performance-evidence.md b/docs/operations/performance-evidence.md index 9faa165..c9c977a 100644 --- a/docs/operations/performance-evidence.md +++ b/docs/operations/performance-evidence.md @@ -3,7 +3,7 @@ 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 225 KiB gzip and every lazy chunk at 120 KiB gzip. - `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, @@ -40,6 +40,60 @@ Performance evidence is deliberately split by measurement context: 예산을 올릴 때는 이 표의 기준선과 새 측정값, 이유를 같은 변경에 적는다. +### TechLog 예산 (2026-11-12, FE-GATE-012) + +위 표는 템플릿을 받을 때의 기록이다. TechLog는 기능을 붙인 뒤 예산을 다시 정하지 +않았고, 초기 JS가 main(`e5fe335e`)에서 300,869 B로 예산을 96,069 B 넘었다. + +| 항목 | 값 | +|---|---| +| 초기 JS 예산 | 230,400 gzip bytes(225 KiB) | +| 바꾸기 전(main `e5fe335e`, CI env) | 300,869 B, 초기 파일 26개 | +| 바꾼 뒤(CI env) | 229,224 B, 초기 파일 28개 | +| 그중 템플릿 공통 부분 | 약 205 KB. react-dom·scheduler 56.5 KB 청크, react-router, zod, tanstack, 플랫폼 `src` | +| 그중 TechLog 코드 | 약 24 KB. 문구 카탈로그, 공개 HTTP gateway와 mapping, Studio·관리·공개 계약, 라우트 표, 공개 셸 | +| 가장 큰 lazy chunk | 40,038 B(마크다운 파서와 content-format). 예산 122,880 B | + +두 몫은 분석 빌드의 모듈별 minify 바이트 비율(TechLog 10.5%)로 나눈 추정이다. + +이번에 초기 JS에서 뺀 것(바꾸기 전 대비 -71,645 B): + +- **MOCK 소스.** 런타임 문서가 MOCK·HTTP를 고르므로 두 소스가 모든 빌드에 들어 + 있다. MOCK 공개 콘텐츠와 MOCK Studio gateway가 운영(HTTP) 공개 화면의 초기 JS에 + 있었고, MOCK이 쓰는 content-format이 마크다운 파서(micromark·mdast·unified)를 + 끌고 왔다. 지금은 첫 조회 때 받는다(`adapters/deferred-async-port.ts`). +- **Studio.** Studio 셸(StudioProvider, Studio 머리말, 문서 server state)과 + MOCK·HTTP Studio gateway를 `/studio`에 들어갈 때 받는다. gateway는 Studio가 + 마운트될 때 바로 받기 시작한다. +- **쓰이지 않는 design-system·폼 모듈.** 템플릿 1101/08-08(`51941a54`)처럼 + design-system 모듈을 side effect 없음으로 선언했다. + +`tests/features/tech-log/boot-graph.test.ts`가 MOCK 소스와 Studio 코드가 부팅 +그래프에 다시 들어오지 않는지 빌드 없이 본다. + +예산 값을 정한 규칙은 템플릿과 같다(템플릿 +`docs/operations/performance-evidence.md` 1106/15-01, 결정 D9). 측정값에 기능 +하나의 상한 1 KiB를 더해 KiB 단위로 올린다. 229,224 + 1,024 = 230,248 B를 +올리면 225 KiB = 230,400 B다. 여유 1,176 B는 기능 하나(1,024 B)와 올림(152 B) +몫이다. 빌드 id에 따라 합계가 수백 B 움직인다. + +204,800 B로 되돌리지 못한 이유: + +- 템플릿 공통 부분만 약 205 KB다. TechLog 코드를 초기 JS에서 모두 빼도 예산 + 안에 남는 여유가 없다. +- 남은 TechLog 몫(문구, 공개 gateway, 계약)은 공개 첫 화면이 실제로 쓴다. 공개 + gateway를 지연 로드하면 첫 화면 데이터 요청 앞에 청크 왕복이 하나 더 생긴다. +- 템플릿은 1101/15-01(`298201f3`)에서 기능 실행부(계약 contribution, adapter)를 + 라우트 진입 때 받게 바꿨다. TechLog는 템플릿 `af3d8e6`(2026-09-28)에 머물러 있고, + 계약·문구 catalog를 부팅 때 합친다. 그 구조를 옮기는 것은 템플릿 동기화 일이다. + +다시 볼 때: + +- 예산을 다시 넘을 때. 늘린 변경이 무엇을 초기 그래프에 넣었는지 먼저 본다. +- 템플릿 동기화로 15-01(기능 실행부 지연 적재)을 받을 때. 그때 다시 재고 같은 + 규칙으로 예산을 내린다. 측정값이 203,776 B 이하이면 규칙의 값이 200 KiB 이하가 + 되어 원래 예산으로 돌아간다. + lab 측정(`scripts/test-performance.ts`, FE-GATE-026)은 local 프로필 build를 `vite preview --strictPort`로 띄워 잰다(리뷰 11-07). -- 2.54.0 From 8422c41e767ab51cadda0fb48c69315d62f80fb6 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 22:38:22 +0900 Subject: [PATCH 5/5] =?UTF-8?q?fix(build):=20=EB=B2=88=EB=93=A4=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EC=86=8C=EC=9C=A0=20=EA=B2=80=EC=82=AC?= =?UTF-8?q?=EA=B0=80=20=EC=A7=81=EC=A0=91=20=EC=A1=B0=EB=A6=BD=ED=95=98?= =?UTF-8?q?=EB=8A=94=20TechLog=EB=A5=BC=20=EB=B0=9B=EC=95=84=EB=93=A4?= =?UTF-8?q?=EC=9D=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 FE-GATE-012의 check:app-build-input:bundle은 production 번들에 든 `src/features//` 모듈이 모두 앱의 context가 소유한(생성기로 설치한) 기능이어야 한다고 본다. TechLog는 조립부가 직접 붙이는 기능이라 (`src/features/tech-log/NOT_INSTALLED`) 어떤 context도 소유하지 않는다. 그래서 이 검사는 TechLog의 모든 production 번들을 거절한다. 9-29 템플릿 동기화(af3d8e6)로 들어온 뒤, 같은 게이트의 번들 예산 검사가 먼저 실패해 한 번도 이 단계까지 가지 않았다. 예산을 맞추자 드러났다. 고른 방법 - DIRECTLY_COMPOSED_FEATURE_DIRECTORIES(["tech-log"])를 두고, 번들 쪽 검사에서만 이름으로 허용한다. - 생성 인덱스 쪽 검사는 그대로다. 생성기가 TechLog를 import하면 여전히 실패한다. 버린 대안 - NOT_INSTALLED 표시가 있는 디렉터리를 모두 허용: reference-feature와 local-draft-feature도 NOT_INSTALLED다. 그 샘플이 번들에 새면 이 검사가 잡아야 한다. 위험·한계 - 템플릿 소유 스크립트를 고친다. TechLog를 feature-module.ts로 옮기는 후속 작업(docs/operations/template-sync-2026-09-29.md)을 하면 이 목록을 지운다. 검증 - tests/architecture/app-build-input.test.ts: TechLog 모듈은 받아들이고, 같은 번들의 reference-feature는 거절한다. - desktop CI env에서 이 커밋 전 head로 돌린 FE-GATE-012: 번들 예산은 PASS (229,223 / 230,400 B), check:app-build-input:bundle이 "production bundle contains feature \"tech-log\" not owned by app template-app"으로 실패. --- scripts/check-app-build-input.ts | 18 +++++++++++++++++- tests/architecture/app-build-input.test.ts | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/scripts/check-app-build-input.ts b/scripts/check-app-build-input.ts index c8c6002..8177407 100644 --- a/scripts/check-app-build-input.ts +++ b/scripts/check-app-build-input.ts @@ -27,6 +27,21 @@ export type AppBuildInputReport = Readonly<{ violations: readonly string[]; }>; +/** + * Template sync (af3d8e6). TechLog is this product's own domain, composed + * directly by the composition root rather than by the index generator + * (`src/features/tech-log/NOT_INSTALLED`). No context owns it, so the + * template's ownership rule refused every production bundle of this product; + * FE-GATE-012 stopped at the bundle budget before reaching it, which hid that. + * + * It is allowed in the bundle by name only. The generated indexes still may not + * import it, and every other directory marked NOT_INSTALLED (the reference and + * local-draft samples) is still refused if it reaches the bundle. + */ +export const DIRECTLY_COMPOSED_FEATURE_DIRECTORIES: readonly string[] = Object.freeze([ + "tech-log", +]); + const GENERATED = [ "src/.generated/product-feature-index.ts", "src/.generated/product-context-index.ts", @@ -99,8 +114,9 @@ export async function inspectAppBuildInput( }), ); bundle = { checked: true, featureDirectories }; + const composedDirectly = new Set(DIRECTLY_COMPOSED_FEATURE_DIRECTORIES); for (const directory of featureDirectories) { - if (!owned.has(directory)) { + if (!owned.has(directory) && !composedDirectly.has(directory)) { violations.push(`production bundle contains feature "${directory}" not owned by app ${appId}`); } } diff --git a/tests/architecture/app-build-input.test.ts b/tests/architecture/app-build-input.test.ts index 6c28bbe..151a5ab 100644 --- a/tests/architecture/app-build-input.test.ts +++ b/tests/architecture/app-build-input.test.ts @@ -84,6 +84,24 @@ describe("app build input isolation gate", () => { ]); }); + it("accepts this product's directly composed TechLog and still refuses an uninstalled sample", async () => { + // TechLog is composed by the composition root (src/features/tech-log/NOT_INSTALLED), + // so it is in every production bundle while no context owns it. The + // reference sample is NOT_INSTALLED too, and must not ride along. + const root = path.resolve("."); + const scratch = await mkdtemp(path.join(tmpdir(), "app-build-input-product-")); + roots.push(scratch); + const bundle = await inventory(scratch, [ + "src/features/tech-log/presentation/public/public-shell.tsx", + "src/features/reference-feature/feature-module.ts", + ]); + const report = await inspectAppBuildInput(root, { bundleInventory: bundle }); + expect(report.bundle.featureDirectories).toEqual(["reference-feature", "tech-log"]); + expect(report.violations).toEqual([ + `production bundle contains feature "reference-feature" not owned by app ${report.appId}`, + ]); + }); + it("holds for this repository's generated indexes", async () => { // The bundle side is gated after a fresh build (check:app-build-input:bundle). const report = await inspectAppBuildInput(path.resolve("."), { bundleInventory: null }); -- 2.54.0