문제 제품 확장 지점이 실행 경로에서는 동작했지만 타입 검사 경로에서 막혔다. (a) 문서대로 product-composition.ts에서 FeaturePlatformCapabilities를 보강하면 check:types:node가 실패했다. scripts 프로그램은 기능 코드를 끌어오지만 product-composition.ts는 끌어오지 않아 보강이 보이지 않았고, 오류는 기능 파일을 가리켰다. (b) 기본값 있는 제품 설정 키(.default()) 하나가 RuntimeConfig를 리터럴로 쓰는 템플릿 테스트 7개 파일의 타입을 깼다. 픽스처는 vi.mock이라 이 경로를 지나지 않았다. 고른 방법 - 제품 소유 빈 파일 src/features/product-capabilities.ts를 두고 FeaturePlatformCapabilities가 그 ProductFeaturePlatformCapabilities를 extends한다. feature-adapter-contribution.ts가 import하므로 기능을 보는 모든 프로그램에 들어간다. 문서만 "기능 파일 안에서 보강"으로 고치는 최소안은 capability 하나를 여러 기능이 쓸 때 보강 위치가 갈려 버렸다. 기존 제품 소유 파일에 칸을 더하지 않고 새 파일로 둔 이유: 템플릿은 복사 뒤 제품 소유 파일을 고치지 않으므로, 새 파일이어야 동기화 때 충돌 없이 들어간다. - tests/helpers/runtime-config.ts의 testRuntimeConfig: 템플릿 키는 테스트가 쓰고, 제품 키는 실제 스키마(validateRuntimeConfig)로 기본값을 채운다. 템플릿 테스트 6개 파일이 이것을 쓰고, release-coherence는 문서 타입을 z.input으로 바꿨다. 제품 키를 모두 Partial로 하는 대안은 기본값 키에도 undefined 처리를 강요해 버렸다. - tests/unit/product-extension-typecheck.test.ts: 복사본에 제품 소유 파일 세 개와 기능 하나를 실제 파일로 채우고 tsc app·node·test를 돈다. - 문서: starter-experience 표, 매뉴얼 01·03·patterns·create-feature, frontend-application-foundation, 계약 주석. 위험·한계 - 기본값 없는 필수 제품 키는 여전히 템플릿 테스트에서 실패한다(이제 타입이 아니라 helper가 이유를 적고 throw). 문서에 ".default() 또는 .optional()"을 적었다. - product-composition.ts 안에서 이미 보강한 다운스트림은 보강을 새 파일로 옮겨야 node 검사가 통과한다. 검증 - RED: 새 typecheck 테스트가 수정 전 app·node(보강 미연결)와 test(템플릿 테스트 8건, E-PROD와 같은 위치)에서 실패. - 수정 후 그 테스트와 영향받는 9개 테스트 파일 → 10 files / 83 tests 통과. - check:types(tsc app·node·test), check:architecture, eslint, verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-02
273 lines
8.7 KiB
TypeScript
273 lines
8.7 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import type { DemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
|
|
import { createRuntimeAdapters } from "../../../src/bootstrap/runtime-adapters.ts";
|
|
import { createRuntimeIdentityRegistry } from "../../../src/contracts/query-keys.ts";
|
|
import { bindQuery } from "../../../src/contracts/server-state.ts";
|
|
import type { CacheScopeSnapshot } from "../../../src/contracts/server-state-scope.ts";
|
|
import {
|
|
REFERENCE_FEATURE_ID,
|
|
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
|
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
|
import { testRuntimeConfig } from "../../helpers/runtime-config.ts";
|
|
|
|
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
|
|
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
|
|
|
|
const runtime: Runtime = {
|
|
config: testRuntimeConfig({
|
|
APP_ENV: "local",
|
|
API_BASE_URL: "http://localhost:8080",
|
|
TELEMETRY_ENABLED: false,
|
|
AUTH_MODE: "demo",
|
|
REQUEST_TIMEOUT_MS: 4321,
|
|
MAX_RETRY_ATTEMPTS: 0,
|
|
RELEASE_MANIFEST_URL: "/release-manifest.json",
|
|
CONFIG_SCHEMA_VERSION: "2.0",
|
|
CAPABILITY_OVERRIDES: {
|
|
REALTIME: "DEFAULT",
|
|
WEB_WORKER: "DEFAULT",
|
|
SERVICE_WORKER: "DEFAULT",
|
|
OFFLINE_COMMANDS: "DEFAULT",
|
|
},
|
|
FEATURE_OVERRIDES: {},
|
|
}),
|
|
configSchema: "V2",
|
|
build: {
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
routerBasePath: "/",
|
|
runtimeConfigUrl: "/config.json",
|
|
},
|
|
validationDurationMs: 0,
|
|
};
|
|
|
|
const release: Release = {
|
|
schemaVersion: 2,
|
|
appVersion: "0.2.0",
|
|
buildId: "build-a",
|
|
commitSha: "abc123",
|
|
configSchemaVersion: "2.0",
|
|
contractSet: {
|
|
setAlgorithm: "CA_CONTRACT_SET_V1",
|
|
setDigest: `sha256:${"0".repeat(64)}`,
|
|
packages: [],
|
|
},
|
|
assetManifestHash: "hash-a",
|
|
releaseId: "release-a",
|
|
builtAt: "2026-07-25T00:00:00Z",
|
|
routeChunks: { "route-home": "assets/home.js" },
|
|
};
|
|
|
|
function referenceBoundQueryKey() {
|
|
const scope: CacheScopeSnapshot = {
|
|
generation: 1,
|
|
fingerprint: "runtime-scope-fingerprint-0001",
|
|
identities: createRuntimeIdentityRegistry({
|
|
tokenFactory: () => "runtime-identity-token-0001",
|
|
}),
|
|
signal: new AbortController().signal,
|
|
isCurrent: () => true,
|
|
};
|
|
return bindQuery(
|
|
{
|
|
definitionId: "reference-resource-runtime-test-v1",
|
|
definitionVersion: 1,
|
|
owner: REFERENCE_FEATURE_ID,
|
|
namespace: "reference-resource",
|
|
namespaceVersion: 1,
|
|
operationId: "GET_REFERENCE_RESOURCE",
|
|
profileId: "DETAIL_STANDARD",
|
|
measureResult: () => ({ itemCount: 1, estimatedBytes: 8 }),
|
|
execute: async () => ({ ok: true as const, value: "reference-1" }),
|
|
},
|
|
"reference-1",
|
|
scope,
|
|
).queryKey;
|
|
}
|
|
|
|
/**
|
|
* The installed feature inputs are partial by design: a feature the product
|
|
* manifest did not select supplies none. This suite is about the reference
|
|
* feature being composed, so it asserts that first and narrows once.
|
|
*/
|
|
async function referenceInput(
|
|
adapters: Awaited<ReturnType<typeof createRuntimeAdapters>>,
|
|
) {
|
|
// 15-01. The input is created when the feature's runtime half loads.
|
|
const load = adapters.featureLoaders[REFERENCE_FEATURE_ID];
|
|
const input = load ? (await load())[REFERENCE_FEATURE_ID] : undefined;
|
|
if (!input) {
|
|
throw new Error(
|
|
`${REFERENCE_FEATURE_ID} is not installed; the manifest did not select it`,
|
|
);
|
|
}
|
|
return input;
|
|
}
|
|
|
|
describe("reference feature runtime composition", () => {
|
|
it("invalidates a real bound query through the installed production graph", async () => {
|
|
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
|
|
const queryKey = referenceBoundQueryKey();
|
|
adapters.infrastructure.queryClient.setQueryData(queryKey, {
|
|
resourceId: "reference-1",
|
|
});
|
|
|
|
await adapters.infrastructure.queryInvalidation.invalidate([
|
|
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
|
]);
|
|
|
|
expect(
|
|
adapters.infrastructure.queryClient.getQueryState(queryKey)?.isInvalidated,
|
|
).toBe(true);
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("executes installed feature HTTP through the composed contract registry", async () => {
|
|
const fetcher = vi.fn(async () =>
|
|
Response.json([{ id: "reference-1", name: "Direct contract payload" }]),
|
|
);
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toEqual({
|
|
ok: true,
|
|
value: [
|
|
{
|
|
resourceId: "reference-1",
|
|
title: "Direct contract payload",
|
|
createdAt: null,
|
|
},
|
|
],
|
|
});
|
|
expect(fetcher).toHaveBeenCalledWith(
|
|
"http://localhost:8080/api/reference-resources?limit=20",
|
|
expect.objectContaining({
|
|
method: "GET",
|
|
redirect: "error",
|
|
cache: "no-store",
|
|
}),
|
|
);
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("keeps private command intent identity out of URLs and diagnostics", async () => {
|
|
const requests: Array<Readonly<{ url: string; headers: Headers }>> = [];
|
|
const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
requests.push({
|
|
url: String(input),
|
|
headers: new Headers(init?.headers),
|
|
});
|
|
return Response.json(
|
|
{ id: "resource-1", name: "Created resource" },
|
|
{ status: 201 },
|
|
);
|
|
});
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
const intent = Object.freeze({
|
|
intentId: "private-intent-id",
|
|
operationId: "CREATE_REFERENCE_RESOURCE",
|
|
canonicalInputIdentity: "private-canonical-input",
|
|
idempotencyKey: "private-idempotency-key",
|
|
createdAtMonotonicMs: 42,
|
|
});
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).createResource(
|
|
{ name: "Created resource" },
|
|
{ intent },
|
|
),
|
|
).resolves.toMatchObject({ ok: true });
|
|
|
|
expect(requests).toHaveLength(1);
|
|
expect(requests[0]?.headers.get("Idempotency-Key")).toBe(
|
|
"private-idempotency-key",
|
|
);
|
|
expect(requests[0]?.url).toBe(
|
|
"http://localhost:8080/api/reference-resources",
|
|
);
|
|
const safeEvidence = JSON.stringify({
|
|
requests: requests.map((request) => request.url),
|
|
diagnostics: adapters.outputPorts.diagnostics.entries(),
|
|
});
|
|
expect(safeEvidence).not.toContain("private-intent-id");
|
|
expect(safeEvidence).not.toContain("private-canonical-input");
|
|
expect(safeEvidence).not.toContain("private-idempotency-key");
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
/**
|
|
* R-3.2. A request refused before dispatch because no credential exists is
|
|
* not a session verdict. Reporting it to the owner overwrote a recovering
|
|
* session and could loop through the scope fence; only a server 401 may.
|
|
*/
|
|
it("does not report a request refused before dispatch as a sign-out", async () => {
|
|
const fetcher = vi.fn(async () => Response.json([]));
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
const session = adapters.outputPorts.session as DemoSessionAdapter;
|
|
session.setState("recovery-pending");
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
const notifications = vi.fn();
|
|
session.subscribe(notifications);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toMatchObject({ ok: false });
|
|
|
|
expect(fetcher).not.toHaveBeenCalled();
|
|
expect(session.getState()).toBe("recovery-pending");
|
|
expect(notifications).not.toHaveBeenCalled();
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
|
|
it("still signs out when the server answers 401", async () => {
|
|
const fetcher = vi.fn(
|
|
async () => new Response(null, { status: 401 }),
|
|
);
|
|
const adapters = await createRuntimeAdapters({
|
|
runtime,
|
|
release,
|
|
host: {},
|
|
fetcher,
|
|
});
|
|
await adapters.outputPorts.session.beginSignIn();
|
|
await vi.waitFor(() =>
|
|
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
|
|
);
|
|
|
|
await expect(
|
|
(await referenceInput(adapters)).listResources({ limit: 20 }),
|
|
).resolves.toMatchObject({ ok: false });
|
|
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
|
|
adapters.infrastructure.dispose();
|
|
});
|
|
});
|