Files
tech-log-frontend/tests/features/reference-feature/reference-runtime-composition.test.ts
T
DongHyeonka c80320dfc7 chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
2026-11-12 08:28:54 +09:00

307 lines
10 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";
// Template sync (af3d8e6). This product leaves the sample uninstalled
// (src/features/reference-feature/NOT_INSTALLED): its feature-module.ts would
// load the screens this product deleted. These tests exercise the production
// graph with a real feature, so they install the sample themselves, the way
// the template's platform tests install their test-only feature: through the
// generated index, with the upstream descriptor minus its route runtime.
vi.mock("../../../src/.generated/product-feature-index.ts", async () => {
const { defineFeatureModule } = await import("../../../src/features/feature-module.ts");
const { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } = await import(
"../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"
);
const { REFERENCE_FEATURE_CONTRACT } = await import(
"../../../src/features/reference-feature/contracts/reference-feature-contract.ts"
);
const { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } = await import(
"../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"
);
const { REFERENCE_MESSAGE_CATALOGS } = await import(
"../../../src/features/reference-feature/contracts/reference-message-catalog.ts"
);
const module = defineFeatureModule({
id: REFERENCE_FEATURE_CONTRACT.featureId,
contracts: REFERENCE_FEATURE_CONTRACT,
routes: REFERENCE_FEATURE_CONTRACT.routes,
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
runtimes: [],
messages: REFERENCE_MESSAGE_CATALOGS,
contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION],
});
return {
DECLARED_PRODUCT_FEATURE_IDS: [module.id],
PRODUCT_FEATURE_MODULES: [module],
};
});
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
const runtime: Runtime = {
config: {
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: {},
TECH_LOG_STUDIO_SOURCE: "MOCK",
TECH_LOG_PUBLIC_SOURCE: "MOCK",
},
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.
*/
function referenceInput<
Inputs extends Readonly<Partial<Record<typeof REFERENCE_FEATURE_ID, unknown>>>,
>(adapters: Readonly<{ featureInputs: Inputs }>) {
const input = adapters.featureInputs[REFERENCE_FEATURE_ID];
if (!input) {
throw new Error(
`${REFERENCE_FEATURE_ID} is not installed; the manifest did not select it`,
);
}
return input as NonNullable<Inputs[typeof REFERENCE_FEATURE_ID]>;
}
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(
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(
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(
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(
referenceInput(adapters).listResources({ limit: 20 }),
).resolves.toMatchObject({ ok: false });
expect(fetcher).toHaveBeenCalledOnce();
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
adapters.infrastructure.dispose();
});
});