Files
clean-architecture-frontend…/tests/unit/product-composition-fixture.test.ts
T
DongHyeonka ece944d08b feat(bootstrap): 제품 세션 owner와 FE-REG-ENV 행을 제품 파일로 받는다 (1101/09-02)
문제
09-02(da1e128) 뒤에도 tech-log가 하는 일 두 가지는 템플릿 파일을 고쳐야
한다(리뷰 1101 README 14.4 "09-02 이식").
- 제품 설정 키의 FE-REG-ENV 행: tech-log는 템플릿 src/contracts/env.ts의
  ENV_REGISTRY에 TECH_LOG_STUDIO_SOURCE·TECH_LOG_PUBLIC_SOURCE 행을 직접
  넣었다(tech-log env.ts:63-70).
- 부트 전 BFF 세션 owner: 세션이 httpOnly 쿠키라 owner가 백엔드에 묻는다.
  tech-log는 템플릿 create-runtime-composition.ts에서 AUTH_MODE external이고
  Studio가 HTTP일 때 createRuntimeAdapters 전에 host 전역
  __CA_FRONTEND_AUTH_OWNER__에 owner를 넣는다(:2, :36-52,
  bff-session-owner.ts:188-194). composeProduct는 http가 생긴 뒤에 불리고
  http는 세션이 필요해서 이 일을 받을 수 없다.

고른 방법
- product-contracts.ts에 PRODUCT_ENV_REGISTRY를 빈 값으로 둔다. env.ts는
  PRODUCT_REST_AUTH_PROFILES·PRODUCT_RUNTIME_CONFIG_FIELDS와 같은 모양으로
  그 행을 ENV_REGISTRY에 합친다. 템플릿 키와 이름이 겹치면 모듈 로드 때
  throw한다. check:registries와 vite.config.ts가 같은 객체를 읽으므로 제품
  행도 같은 필드 검사를 받는다. 행을 더하기만 하면 additive라 기준선을
  고치지 않는다(실험: 제품 행 2개 → compatibility=additive PASS, 허용 밖
  classification → 실패).
- product-composition.ts에 composeProductSessionOwner(context)를 둔다.
  템플릿은 null을 돌려준다. 조립 루트가 세션을 고르기 전에, AUTH_MODE가
  external일 때만 부른다. 제품 owner가 host 전역보다 먼저다. null이면
  지금처럼 host 전역, 없으면 unavailable이다. demo 모드는 묻지 않는다.
  context는 config와 fetcher뿐이다(http 전이라 capability가 없다).

버린 대안
- owner를 composeProduct 반환값에 넣기: http가 세션을 쓰므로 순서가 꼬인다.
- 제품이 host 전역에 계속 넣게 두고 문서화: 부트 전 훅이 템플릿 파일
  (create-runtime-composition.ts)에 남는다.
- FE-REG-ENV 행을 PRODUCT_RUNTIME_CONFIG_FIELDS에서 자동으로 만들기: zod
  필드로는 classification·required를 알 수 없다.
- 행 타입·도우미를 product-contracts.ts가 env.ts에서 import: 순환 의존
  (no-circular-dependencies)이다. 타입 검사는 env.ts의 대입에서 한다.

위험·한계
- product-composition.ts에 export가 하나 늘었다. 이 파일을 이미 복사한
  제품은 composeProductSessionOwner를 더해야 한다. da1e128은 아직 main에
  없고 두 다운스트림 모두 받지 않았다.
- 제품 행을 as const 없이 쓰면 phase가 string으로 넓어져 tsc 오류가
  env.ts:78(템플릿 파일)에서 난다. 메시지에 키 이름은 나온다. product-
  contracts.ts 주석에 as const를 적었다.
- 제품 설정 키에 FE-REG-ENV 행이 있는지 요구하는 검사는 여전히 없다.
  템플릿 키도 RELEASE_ID·BUILD_ID는 행이 없어서 이 변경에서 넣지 않았다.
- 제품 owner가 throw하면 createRuntimeAdapters가 실패해 부트 실패
  화면이 된다. composeProduct와 같다.
- tech-log의 owner는 subject를 null로 돌려준다(템플릿 동작대로 매 변경
  fence). 이 변경과 무관하다.

검증
- RED: tests/unit/product-composition-fixture.test.ts 13건 중 3건 실패.
  FE-REG-ENV 행 없음, external 모드 세션이 authenticated가 아니라
  integration-failed, env 이름 충돌을 거절하지 않음.
- GREEN: 같은 파일 13/13, runtime-adapters-credential-order 7/7(mock에
  composeProductSessionOwner: () => null 추가).
- fixture는 vi.mock 대상이 제품 소유 두 파일(머리 주석 "Product-owned.")과
  설치 기능 seam 두 개뿐이고, tech-log가 고친 템플릿 파일 4개(env.ts,
  create-runtime-composition.ts, runtime-config-schema.ts,
  runtime-adapters.ts)는 대상이 아님을 이 파일의 소스를 읽어 확인한다.
- 회귀: tests/unit·contract·runtime-schema·integration 198 files 2861
  tests 통과(heavy lock 아래).
- tsc app·node·test 통과, 바꾼 파일 eslint 통과, check:registries PASS
  (compatibility=none, 재승인 불필요), verify:documentation PASS_SCOPED,
  check:adapter-inventory PASS.
- 초기 JS gzip 202,770 → 202,931 B(+161, 예산 204,800). 같은 방법(dist
  manifest의 초기 파일 26개, gzipSync 기본 레벨)으로 전·후를 쟀다.
- 미실행: check:architecture(pnpm 필요), test:component, e2e.
2026-11-03 20:23:14 +09:00

669 lines
25 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { InstalledHttpOperationExecutor } from "../../src/adapters/http/index.ts";
import type {
ProductComposition,
ProductCompositionContext,
ProductSessionOwner,
ProductSessionOwnerContext,
} from "../../src/bootstrap/product-composition-contract.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { validateRuntimeConfig } from "../../src/bootstrap/runtime-config-schema.ts";
import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts";
import type { FeaturePlatformCapabilityId } from "../../src/features/feature-adapter-contribution.ts";
import { TEST_LIST_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
/**
* 09-02 completion check. The two products' current needs — memento's
* `offsetUpload` and `runtime` capabilities and its BFF cookie XSRF write,
* tech-log's Studio CSRF, its product runtime-config key with its FE-REG-ENV
* row, and its BFF session owner installed before boot — expressed by filling
* only the two product-owned files:
*
* - `src/contracts/product-contracts.ts`: product auth profiles, config keys
* and their FE-REG-ENV rows
* - `src/bootstrap/product-composition.ts`: the session owner, capabilities and
* credential providers
*
* Both are replaced below by what a product would write in them. Everything
* else is the template as shipped; only the installed contract set (adds the
* operations) and the feature-input composer (to read the capability context
* a feature receives) are swapped, as in the 09-01 test.
*/
declare module "../../src/features/feature-adapter-contribution.ts" {
interface FeaturePlatformCapabilities {
readonly offsetUpload: Readonly<{
upload(path: string, body: Blob): Promise<number | "NO_CREDENTIAL">;
}>;
readonly runtime: Readonly<{ appEnvironment: string; apiBaseUrl: string }>;
readonly studioSource: "MOCK" | "HTTP";
readonly studioHttp: InstalledHttpOperationExecutor;
}
}
/** Fails to compile unless the capability interface takes product keys. */
const PRODUCT_NEEDS: readonly FeaturePlatformCapabilityId[] = [
"offsetUpload",
"runtime",
"studioSource",
"studioHttp",
];
const fixture = vi.hoisted(() => ({
capabilities: undefined as Record<string, unknown> | undefined,
sessionOwnerRequests: 0,
withProfile<T extends { contract: object; frontend: object }>(
contract: T,
operationId: string,
authProfileId: string,
): T {
return {
...contract,
contract: { ...contract.contract, operationId },
frontend: { ...contract.frontend, authProfileId },
};
},
}));
/** The product's `src/contracts/product-contracts.ts`. */
vi.mock("../../src/contracts/product-contracts.ts", async () => {
const { z } = await import("../../src/contracts/zod.ts");
const cookieProfile = (
authProfileId: string,
header: readonly ("x-csrf-token" | "x-xsrf-token")[],
) =>
Object.freeze({
authProfileId,
transport: "SAME_ORIGIN_COOKIE" as const,
credentials: "include" as const,
allowedCredentialHeaders: Object.freeze([...header]),
requiredCredentialHeaders: Object.freeze([...header]),
});
return {
PRODUCT_RUNTIME_CONFIG_FIELDS: Object.freeze({
TECH_LOG_STUDIO_SOURCE: z.enum(["MOCK", "HTTP"]).default("MOCK"),
}),
// tech-log added this row to the template's `env.ts`.
PRODUCT_ENV_REGISTRY: Object.freeze({
TECH_LOG_STUDIO_SOURCE: Object.freeze({
phase: "runtime",
classification: "public",
required: false,
defaultValue: "MOCK",
}),
}),
PRODUCT_REST_AUTH_PROFILES: Object.freeze({
MEMENTO_BFF_READ: cookieProfile("MEMENTO_BFF_READ", []),
// The paired backend's default CSRF header (Spring CookieCsrfTokenRepository).
MEMENTO_BFF_WRITE: cookieProfile("MEMENTO_BFF_WRITE", ["x-xsrf-token"]),
TECH_LOG_STUDIO_BOOTSTRAP: cookieProfile("TECH_LOG_STUDIO_BOOTSTRAP", []),
TECH_LOG_STUDIO_SESSION: cookieProfile("TECH_LOG_STUDIO_SESSION", ["x-csrf-token"]),
}),
};
});
const OPERATIONS = vi.hoisted(() => ({
bffRead: ["MEMENTO_READ", "MEMENTO_BFF_READ"],
bffWrite: ["MEMENTO_WRITE", "MEMENTO_BFF_WRITE"],
studio: ["STUDIO_LIST", "TECH_LOG_STUDIO_SESSION"],
studioSession: ["STUDIO_SESSION", "TECH_LOG_STUDIO_BOOTSTRAP"],
} as const));
/** The product's `src/bootstrap/product-composition.ts`. */
vi.mock("../../src/bootstrap/product-composition.ts", async () => {
const { TEST_DETAIL_HTTP_CONTRACT: detail } = await import(
"../helpers/external-contract-fixture.ts"
);
const studioSession = fixture.withProfile(detail, ...OPERATIONS.studioSession);
/**
* tech-log's BFF session owner (`bff-session-owner.ts`), which it put on the
* host global from the template's `create-runtime-composition.ts`. The
* session is an httpOnly cookie, so the owner asks the backend.
*/
function composeProductSessionOwner(
context: ProductSessionOwnerContext,
): ProductSessionOwner {
fixture.sessionOwnerRequests += 1;
if (Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") !== "HTTP") return null;
const fetcher = context.fetcher ?? fetch;
let state: "recovery-pending" | "authenticated" | "unauthenticated" =
"recovery-pending";
const listeners = new Set<() => void>();
const probe = async () => {
const response = await fetcher(
new URL("api/v1/studio/session", context.config.API_BASE_URL),
{ method: "GET", credentials: "include" },
);
state = response.ok ? "authenticated" : "unauthenticated";
for (const listener of listeners) listener();
return response.ok ? ("restored" as const) : ("no-session" as const);
};
void probe();
return Object.freeze({
readState: () => state,
readSubject: () => (state === "authenticated" ? "studio-user" : null),
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: probe,
notifyUnauthenticated() {
state = "unauthenticated";
},
});
}
function composeProduct(context: ProductCompositionContext) {
// tech-log: one Studio CSRF token per session, fetched through `http` with
// the credential-free bootstrap profile and dropped on 401/403.
let csrfToken: Promise<string> | null = null;
const csrf = {
token(signal?: AbortSignal) {
csrfToken ??= context.http
.execute(studioSession, { entityId: "session" }, {
routeId: "STUDIO",
...(signal === undefined ? {} : { signal }),
})
.then((outcome) => {
if (outcome.kind !== "SUCCESS") throw new Error("no studio session");
return outcome.value.id;
});
return csrfToken.catch((error: unknown) => {
csrfToken = null;
throw error;
});
},
invalidate() {
csrfToken = null;
},
};
return {
capabilities: {
// memento: its resumable upload transport, fenced like every request.
offsetUpload: Object.freeze({
async upload(path: string, body: Blob) {
const token = context.isScopeReady()
? context.readCookie("XSRF-TOKEN")
: undefined;
if (token === undefined) return "NO_CREDENTIAL" as const;
const fetcher = context.fetcher ?? fetch;
const response = await fetcher(
new URL(path, context.config.API_BASE_URL),
{
method: "PATCH",
credentials: "include",
headers: { "x-xsrf-token": token },
body,
},
);
return response.status;
},
}),
// memento: runtime values its features read.
runtime: Object.freeze({
appEnvironment: context.config.APP_ENV,
apiBaseUrl: context.config.API_BASE_URL,
}),
// tech-log: a product runtime-config key. Read untyped here only
// because the shipped `product-contracts.ts` declares no keys.
studioSource: Reflect.get(context.config, "TECH_LOG_STUDIO_SOURCE") as
| "MOCK"
| "HTTP",
// tech-log: Studio calls go through `http`; a 401/403 drops the token.
studioHttp: Object.freeze({
async execute(...args: Parameters<InstalledHttpOperationExecutor["execute"]>) {
const outcome = await context.http.execute(...args);
if (outcome.kind === "UNAUTHENTICATED" || outcome.kind === "FORBIDDEN") {
csrf.invalidate();
}
return outcome;
},
}) as InstalledHttpOperationExecutor,
},
credentialProviders: {
// memento BFF: the cookie is the session; writes add the XSRF cookie.
MEMENTO_BFF_READ: () => ({ kind: "READY" as const, headers: {} }),
MEMENTO_BFF_WRITE: () => {
const token = context.readCookie("XSRF-TOKEN");
return token === undefined
? { kind: "UNAVAILABLE" as const }
: { kind: "READY" as const, headers: { "x-xsrf-token": token } };
},
// tech-log Studio: the token's own issuing call carries none.
TECH_LOG_STUDIO_BOOTSTRAP: () => ({ kind: "READY" as const, headers: {} }),
TECH_LOG_STUDIO_SESSION: async (_operation, { signal }) => ({
kind: "READY" as const,
headers: { "x-csrf-token": await csrf.token(signal) },
}),
},
} satisfies ProductComposition;
}
return { composeProduct, composeProductSessionOwner };
});
vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-contract-contributions.ts")>();
const fixtures = await import("../helpers/external-contract-fixture.ts");
const { TEST_CONTRACT_CONTRIBUTION: contribution } = fixtures;
const source = contribution.source;
if (source.kind !== "EXTERNAL_PACKAGE") throw new Error("fixture source changed");
return {
...original,
createInstalledContractRegistry: () => {
const registry = original.createInstalledContractRegistry([
...original.EXPECTED_CONTRACT_SET_PACKAGES,
source.package,
]);
registry.install(contribution.featureId, [
{
...contribution,
http: [
fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.bffRead),
fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.bffWrite),
fixture.withProfile(fixtures.TEST_LIST_HTTP_CONTRACT, ...OPERATIONS.studio),
fixture.withProfile(fixtures.TEST_DETAIL_HTTP_CONTRACT, ...OPERATIONS.studioSession),
] as typeof contribution.http,
},
]);
return registry;
},
};
});
vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-feature-adapters.ts")>();
return {
...original,
createInstalledFeatureLoaders: (
...args: Parameters<typeof original.createInstalledFeatureLoaders>
) => {
fixture.capabilities = { ...args[0] };
return original.createInstalledFeatureLoaders(...args);
},
};
});
const CONFIG_DOCUMENT = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "2.0",
RELEASE_MANIFEST_URL: "/release-manifest.json",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
} as const;
const release: Parameters<typeof createRuntimeAdapters>[0]["release"] = {
schemaVersion: 2,
appVersion: "0.1.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" },
};
let current: Awaited<ReturnType<typeof createRuntimeAdapters>> | undefined;
afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
fixture.capabilities = undefined;
fixture.sessionOwnerRequests = 0;
});
async function compose(
options: Readonly<{
cookie?: string;
studioStatus?: number;
authMode?: "demo" | "external";
studioSource?: "MOCK" | "HTTP";
studioSessionStatus?: number;
host?: Record<string, unknown>;
}> = {},
) {
const validated = validateRuntimeConfig({
...CONFIG_DOCUMENT,
AUTH_MODE: options.authMode ?? CONFIG_DOCUMENT.AUTH_MODE,
TECH_LOG_STUDIO_SOURCE: options.studioSource ?? "HTTP",
});
if (!validated.success) throw new Error(JSON.stringify(validated.issues));
const fetcher = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
const url = String(input);
if (url.endsWith("/api/v1/studio/session")) {
return new Response(null, { status: options.studioSessionStatus ?? 200 });
}
if (url.endsWith("/api/test-entities/session")) {
return Response.json({ id: "studio-csrf", name: "session" });
}
if (url.includes("/api/test-entities?") && options.studioStatus !== undefined) {
return Response.json(
{ type: "about:blank", title: "Forbidden", status: options.studioStatus },
{ status: options.studioStatus },
);
}
return Response.json([{ id: "entity-1", name: "Entity" }]);
});
current = await createRuntimeAdapters({
runtime: {
config: validated.data,
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
},
release,
host: {
...options.host,
...(options.cookie === undefined ? {} : { document: { cookie: options.cookie } }),
},
fetcher: fetcher as unknown as typeof fetch,
});
const capabilities = fixture.capabilities;
if (!capabilities) throw new Error("feature capabilities were not composed");
return {
capabilities,
http: capabilities.http as InstalledHttpOperationExecutor,
studioHttp: capabilities.studioHttp as InstalledHttpOperationExecutor,
fetcher,
};
}
const list = (operation: readonly [string, string]) =>
fixture.withProfile(TEST_LIST_HTTP_CONTRACT, ...operation);
function sent(fetcher: ReturnType<typeof vi.fn>, index: number) {
const [url, init] = fetcher.mock.calls[index] as [RequestInfo | URL, RequestInit];
return { url: String(url), credentials: init.credentials, headers: new Headers(init.headers) };
}
describe("09-02 product needs through the product-owned files only", () => {
it("adds product capabilities next to the template's own", async () => {
const { capabilities } = await compose();
expect(Object.keys(capabilities).sort()).toEqual(
[...PRODUCT_NEEDS, "http", "telemetry"].sort(),
);
expect(capabilities.runtime).toEqual({
appEnvironment: "local",
apiBaseUrl: "http://localhost:8080/",
});
expect(capabilities.studioSource).toBe("HTTP");
});
it("memento: offsetUpload sends the XSRF cookie while the scope is ready", async () => {
const { capabilities, fetcher } = await compose({ cookie: "XSRF-TOKEN=xsrf-1" });
const offsetUpload = capabilities.offsetUpload as {
upload(path: string, body: Blob): Promise<unknown>;
};
await expect(offsetUpload.upload("/api/uploads/1", new Blob(["chunk"]))).resolves.toBe(200);
expect(sent(fetcher, 0).headers.get("x-xsrf-token")).toBe("xsrf-1");
});
it("memento: BFF reads go out signed out, with the cookie and no header", async () => {
const { http, fetcher } = await compose();
const outcome = await http.execute(list(OPERATIONS.bffRead), { limit: 1 }, { routeId: "R" });
expect(outcome.kind).toBe("SUCCESS");
expect(sent(fetcher, 0).credentials).toBe("include");
expect([...sent(fetcher, 0).headers.keys()]).not.toContain("x-xsrf-token");
});
it("memento: BFF writes carry the XSRF cookie and fail closed without it", async () => {
const withCookie = await compose({ cookie: "theme=dark; XSRF-TOKEN=xsrf-1" });
await expect(
withCookie.http.execute(list(OPERATIONS.bffWrite), { limit: 1 }, { routeId: "R" }),
).resolves.toMatchObject({ kind: "SUCCESS" });
expect(sent(withCookie.fetcher, 0).headers.get("x-xsrf-token")).toBe("xsrf-1");
current?.infrastructure.dispose();
const without = await compose();
await expect(
without.http.execute(list(OPERATIONS.bffWrite), { limit: 1 }, { routeId: "R" }),
).resolves.toMatchObject({
kind: "AUTH_INTEGRATION_FAILURE",
reason: "CREDENTIAL_OWNER_UNAVAILABLE",
});
expect(without.fetcher).not.toHaveBeenCalled();
});
it("tech-log: Studio calls fetch the CSRF token once and then send it", async () => {
const { studioHttp, fetcher } = await compose();
for (let call = 0; call < 2; call += 1) {
await expect(
studioHttp.execute(list(OPERATIONS.studio), { limit: 1 }, { routeId: "STUDIO" }),
).resolves.toMatchObject({ kind: "SUCCESS" });
}
expect(fetcher.mock.calls.map((_, index) => sent(fetcher, index).url)).toEqual([
"http://localhost:8080/api/test-entities/session",
"http://localhost:8080/api/test-entities?limit=1",
"http://localhost:8080/api/test-entities?limit=1",
]);
expect(sent(fetcher, 0).headers.has("x-csrf-token")).toBe(false);
expect(sent(fetcher, 2).headers.get("x-csrf-token")).toBe("studio-csrf");
});
it("tech-log: a 403 drops the Studio token so the next call fetches a new one", async () => {
const { studioHttp, fetcher } = await compose({ studioStatus: 403 });
for (let call = 0; call < 2; call += 1) {
await expect(
studioHttp.execute(list(OPERATIONS.studio), { limit: 1 }, { routeId: "STUDIO" }),
).resolves.toMatchObject({ kind: "FORBIDDEN" });
}
const sessionFetches = fetcher.mock.calls.filter(([url]) =>
String(url).endsWith("/session"),
);
expect(sessionFetches).toHaveLength(2);
});
it("tech-log: the product config key joins the strict document", () => {
const parsed = (document: Record<string, unknown>) => validateRuntimeConfig(document);
expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" })).toMatchObject({
success: true,
data: { TECH_LOG_STUDIO_SOURCE: "HTTP" },
});
expect(parsed(CONFIG_DOCUMENT)).toMatchObject({
success: true,
data: { TECH_LOG_STUDIO_SOURCE: "MOCK" },
});
expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "LIVE" })).toMatchObject({
success: false,
issues: [{ path: "TECH_LOG_STUDIO_SOURCE" }],
});
expect(parsed({ ...CONFIG_DOCUMENT, TECH_LOG_TYPO: "HTTP" })).toMatchObject({
success: false,
issues: [{ path: "TECH_LOG_TYPO", code: "unrecognized_keys" }],
});
// The build scripts read the same schema (generate-runtime-config.ts).
expect(
runtimeConfigV2ArtifactSchema.parse({ ...CONFIG_DOCUMENT, TECH_LOG_STUDIO_SOURCE: "HTTP" }),
).toMatchObject({ TECH_LOG_STUDIO_SOURCE: "HTTP" });
});
it("tech-log: the config key's FE-REG-ENV row joins ENV_REGISTRY", async () => {
// check:registries and vite.config.ts read this same object.
const { ENV_REGISTRY } = await import("../../src/contracts/env.ts");
expect(ENV_REGISTRY).toMatchObject({
APP_ENV: { phase: "runtime", classification: "public", required: true },
TECH_LOG_STUDIO_SOURCE: {
phase: "runtime",
classification: "public",
required: false,
defaultValue: "MOCK",
},
});
});
it("tech-log: the BFF session owner is the session from boot, in external mode only", async () => {
const session = async (options: Parameters<typeof compose>[0]) => {
const { fetcher } = await compose(options);
const port = current?.outputPorts.session;
if (!port) throw new Error("not composed");
await vi.waitFor(() => expect(port.getState()).not.toBe("recovery-pending"));
const state = port.getState();
current?.infrastructure.dispose();
current = undefined;
return { state, fetcher };
};
const signedIn = await session({ authMode: "external" });
expect(signedIn.state).toBe("authenticated");
expect(sent(signedIn.fetcher, 0)).toMatchObject({
url: "http://localhost:8080/api/v1/studio/session",
credentials: "include",
});
await expect(
session({ authMode: "external", studioSessionStatus: 401 }),
).resolves.toMatchObject({ state: "unauthenticated" });
// The product's owner comes before the host's global owner.
await expect(
session({ authMode: "external", host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() } }),
).resolves.toMatchObject({ state: "authenticated" });
// The product returns none: the host's owner, or no owner, as before.
await expect(
session({
authMode: "external",
studioSource: "MOCK",
host: { __CA_FRONTEND_AUTH_OWNER__: hostOwner() },
}),
).resolves.toMatchObject({ state: "unauthenticated" });
await expect(
session({ authMode: "external", studioSource: "MOCK" }),
).resolves.toMatchObject({ state: "integration-failed" });
expect(fixture.sessionOwnerRequests).toBe(5);
// Demo mode keeps its own session and does not ask the product.
fixture.sessionOwnerRequests = 0;
await expect(session({})).resolves.toMatchObject({ state: "unauthenticated" });
expect(fixture.sessionOwnerRequests).toBe(0);
});
});
/** A host-published owner that is signed out. */
function hostOwner() {
return {
readState: () => "unauthenticated",
readSubject: () => null,
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated() {},
};
}
/**
* The template files tech-log edited (af3d8e6 sync) for the needs above. They
* stay template-owned; this fixture reaches the same result without them.
*/
const TECH_LOG_EDITED_TEMPLATE_FILES = [
"src/contracts/env.ts",
"src/bootstrap/create-runtime-composition.ts",
"src/bootstrap/runtime-config-schema.ts",
"src/bootstrap/runtime-adapters.ts",
];
/** Stand in for an installed feature and observe its capabilities; not product code. */
const INSTALLED_FEATURE_SEAMS = [
"src/features/installed-contract-contributions.ts",
"src/features/installed-feature-adapters.ts",
];
describe("09-02 the fixture replaces product-owned files only", () => {
const source = (file: string) => readFile(new URL(`../../${file}`, import.meta.url), "utf8");
it("mocks the two product-owned files and none tech-log edited", async () => {
const mocked = [
...(await source("tests/unit/product-composition-fixture.test.ts")).matchAll(
/vi\.(?:doMock|mock)\(\s*"\.\.\/\.\.\/(src\/[^"]+)"/g,
),
].flatMap((match) => (match[1] === undefined ? [] : [match[1]]));
const product = [...new Set(mocked)]
.filter((file) => !INSTALLED_FEATURE_SEAMS.includes(file))
.sort();
expect(product).toEqual([
"src/bootstrap/product-composition.ts",
"src/contracts/product-contracts.ts",
]);
for (const file of product) {
expect(await source(file), file).toContain("Product-owned.");
}
for (const file of TECH_LOG_EDITED_TEMPLATE_FILES) {
expect(await source(file), file).not.toContain("Product-owned.");
}
});
});
const EMPTY_PRODUCT = {
PRODUCT_RUNTIME_CONFIG_FIELDS: {},
PRODUCT_REST_AUTH_PROFILES: {},
PRODUCT_ENV_REGISTRY: {},
};
describe("09-02 a product row cannot take a template name", () => {
afterEach(() => {
vi.doUnmock("../../src/contracts/product-contracts.ts");
vi.resetModules();
});
it.each([
{
registry: "auth profiles",
load: () => import("../../src/contracts/rest-profiles.ts"),
product: { ...EMPTY_PRODUCT, PRODUCT_REST_AUTH_PROFILES: { ANONYMOUS: {} } },
error: "Product REST auth profile ANONYMOUS reuses a template profile id.",
},
{
registry: "runtime config",
load: () => import("../../src/contracts/release-artifacts.ts"),
product: { ...EMPTY_PRODUCT, PRODUCT_RUNTIME_CONFIG_FIELDS: { APP_ENV: {} } },
error: "Product runtime config key APP_ENV is a template key.",
},
{
registry: "FE-REG-ENV",
load: () => import("../../src/contracts/env.ts"),
product: { ...EMPTY_PRODUCT, PRODUCT_ENV_REGISTRY: { APP_ENV: {} } },
error: "Product env key APP_ENV is a template key.",
},
])("refuses to load ($registry)", async ({ load, product, error }) => {
vi.resetModules();
vi.doMock("../../src/contracts/product-contracts.ts", () => product);
await expect(load()).rejects.toThrow(error);
});
});