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)
This commit is contained in:
DongHyeonka
2026-11-12 08:28:54 +09:00
parent 585c62431a
commit c80320dfc7
738 changed files with 55027 additions and 13567 deletions
@@ -0,0 +1,93 @@
import { spawnSync } from "node:child_process";
import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { inspectAppBuildInput } from "../../scripts/check-app-build-input.ts";
import { renderContextIndex, renderFeatureIndex } from "../../scripts/generate-product-feature-index.ts";
import { APP_A, writeFilesystemTopology } from "../scale/filesystem-topology.ts";
/**
* Deployable-app isolation regression gate: the build input of one app must
* never contain another app's features, whether through the generated index
* or through the production bundle.
*/
const GENERATOR = path.resolve("scripts/generate-product-feature-index.ts");
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
async function multiAppRepo() {
const root = await mkdtemp(path.join(tmpdir(), "app-build-input-"));
roots.push(root);
await writeFilesystemTopology(root, { globalFeatures: 1_100 });
const run = spawnSync(process.execPath, [GENERATOR, `--root=${root}`, `--app=${APP_A.id}`], {
encoding: "utf8",
});
if (run.status !== 0) throw new Error(run.stderr);
return root;
}
async function inventory(root: string, modules: readonly string[]) {
const file = path.join(root, "inventory.json");
await writeFile(file, JSON.stringify({ schemaVersion: 1, chunks: [{ fileName: "a.js", modules }] }));
return file;
}
describe("app build input isolation gate", () => {
it("accepts the production generator's output and an app-local bundle", async () => {
const root = await multiAppRepo();
const bundle = await inventory(root, [
"src/features/app-a-ctx0-f0/feature-module.ts",
"src/features/app-a-ctx1-f49/presentation/page.ts",
"src/platform/traffic/request-budget.ts",
]);
const report = await inspectAppBuildInput(root, { bundleInventory: bundle });
expect(report.violations).toEqual([]);
expect(report.appId).toBe(APP_A.id);
expect(report.generatedFeatureImports).toHaveLength(APP_A.contexts * APP_A.featuresPerContext);
expect(report.bundle.checked).toBe(true);
});
it("rejects a generator regression that imports every discovered feature", async () => {
const root = await multiAppRepo();
const everyFeature = (await readdir(path.join(root, "src/features"))).map((directory) => ({
id: directory,
importPath: `../features/${directory}/feature-module.ts`,
directory,
contextId: directory.replace(/-f\d+$/u, ""),
contextRoutePath: "x/*",
contextMaxFeatures: 200,
}));
await writeFile(path.join(root, "src/.generated/product-feature-index.ts"), renderFeatureIndex(everyFeature));
await writeFile(path.join(root, "src/.generated/product-context-index.ts"), renderContextIndex(everyFeature));
const report = await inspectAppBuildInput(root, { bundleInventory: null });
expect(report.violations.length).toBeGreaterThan(0);
expect(report.violations.join("\n")).toMatch(/imports feature "other-0-ctx0-f0" not owned by app app-a/);
expect(report.violations.join("\n")).toMatch(/declares context "other-0-ctx0" not owned/);
});
it("rejects a production bundle that contains another app's feature", async () => {
const root = await multiAppRepo();
const bundle = await inventory(root, [
"src/features/app-a-ctx0-f0/feature-module.ts",
"src/features/other-0-ctx3-f7/feature-module.ts",
]);
const report = await inspectAppBuildInput(root, { bundleInventory: bundle });
expect(report.violations).toEqual([
'production bundle contains feature "other-0-ctx3-f7" not owned by app app-a',
]);
});
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 });
expect(report.violations).toEqual([]);
expect(report.generatedFeatureImports).toEqual(report.ownedFeatureDirectories);
});
});
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
import { createAppRouteModules } from "../../src/platform/routing/context-route-module.ts";
const MAX_CONTEXTS_PER_APP = 20;
describe("context executable lazy loading", () => {
it("does no context route composition at boot and loads only the entered context", async () => {
const loadCounts = Array.from({ length: MAX_CONTEXTS_PER_APP }, () => 0);
const contexts = loadCounts.map((_, index) =>
defineBoundedContextModule({
id: `context-${index}`,
features: [],
budget: { maxFeatures: 200 },
route: {
path: `context-${index}/*`,
loadRoutes: async () => {
loadCounts[index] += 1;
return Object.freeze([]);
},
},
}),
);
const app = defineDeployableAppModule({
id: "scale-app",
contexts,
budget: { maxContexts: MAX_CONTEXTS_PER_APP },
});
const routeModules = createAppRouteModules(app);
expect(routeModules).toHaveLength(MAX_CONTEXTS_PER_APP);
expect(loadCounts.every((count) => count === 0)).toBe(true);
await routeModules[7]!.loadRoutes();
expect(loadCounts[7]).toBe(1);
expect(loadCounts.filter((count) => count !== 0)).toEqual([1]);
await routeModules[7]!.loadRoutes();
expect(loadCounts[7]).toBe(1);
});
});
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { defineFeatureModule } from "../../src/features/feature-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, adapters:[], runtimes:[], messages:{}, contractContributions:[] });
describe("module hierarchy", () => {
it("exposes only direct children and freezes copied arrays", () => {
const features = [feature];
const context = defineBoundedContextModule({ id:"commerce", features, budget:{maxFeatures:200} });
features.length = 0;
const contexts = [context];
const app = defineDeployableAppModule({ id:"customer", contexts, budget:{maxContexts:20} });
contexts.length = 0;
expect(context.features).toEqual([feature]);
expect(app.contexts).toEqual([context]);
expect("features" in app).toBe(false);
expect(Object.isFrozen(app.contexts)).toBe(true);
});
});
@@ -0,0 +1,114 @@
import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
/**
* Spec §17 / §24 / §50. Observability boundary gates:
* - feature (and every non-adapter) code never imports a vendor telemetry SDK,
* - no global union of every feature error or telemetry payload exists,
* - the dependency rule that enforces the first point stays configured.
*/
const ROOT = path.resolve(".");
async function productionSources(directory = path.join(ROOT, "src")): Promise<string[]> {
const files: string[] = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) files.push(...(await productionSources(target)));
else if (/\.tsx?$/u.test(entry.name) && !/\.d\.ts$/u.test(entry.name)) {
files.push(target);
}
}
return files;
}
async function readProductionSources(): Promise<string> {
const files = await productionSources();
const sources = await Promise.all(files.map((file) => readFile(file, "utf8")));
return sources.join("\n");
}
type DependencyRule = Readonly<{
name: string;
from: Readonly<{ path?: string; pathNot?: string }>;
to: Readonly<{ path?: string }>;
}>;
async function dependencyRules(): Promise<readonly DependencyRule[]> {
const config = JSON.parse(
await readFile(path.join(ROOT, ".dependency-cruiser.json"), "utf8"),
) as { forbidden: DependencyRule[] };
return config.forbidden;
}
const VENDOR_SDKS = [
"@sentry/browser",
"@sentry/react",
"@datadog/browser-rum",
"@datadog/browser-logs",
"@opentelemetry/api",
"@newrelic/browser-agent",
"logrocket",
"posthog-js",
];
describe("observability boundaries", () => {
it("configures a rule that rejects vendor SDK imports outside adapters", async () => {
const rule = (await dependencyRules()).find(
({ name }) => name === "observability-vendors-live-behind-adapters",
);
expect(rule).toBeDefined();
const from = new RegExp(rule?.from.path ?? "$^", "u");
const fromNot = new RegExp(rule?.from.pathNot ?? "$^", "u");
const to = new RegExp(rule?.to.path ?? "$^", "u");
const applies = (source: string, target: string) =>
from.test(source) && !fromNot.test(source) && to.test(target);
for (const vendor of VENDOR_SDKS) {
expect(applies("src/features/catalog/application/x.ts", vendor), vendor).toBe(true);
expect(applies("src/platform/telemetry/x.ts", vendor), vendor).toBe(true);
expect(applies("src/adapters/telemetry/vendor-transport.ts", vendor), vendor).toBe(false);
}
expect(applies("src/features/a/x.ts", "react")).toBe(false);
expect(applies("src/features/a/x.ts", "@sentry-like/other")).toBe(false);
});
it("finds no vendor telemetry SDK import in production sources outside adapters", async () => {
const offenders: string[] = [];
const vendorImport =
/from\s+["'](@sentry|@datadog|@opentelemetry|@newrelic|newrelic|logrocket|posthog-js|mixpanel-browser|@amplitude|@bugsnag)(\/[^"']*)?["']/u;
for (const file of await productionSources()) {
const relative = path.relative(ROOT, file).split(path.sep).join("/");
if (relative.startsWith("src/adapters/")) continue;
if (vendorImport.test(await readFile(file, "utf8"))) offenders.push(relative);
}
expect(offenders).toEqual([]);
});
it("does not define installed/global unions of all feature errors or telemetry payloads", async () => {
const source = await readProductionSources();
expect(source).not.toMatch(
/AllFeatureErrors|GlobalFeatureErrors|GlobalApplicationError|InstalledFeatureErrors|AllTelemetryEvents|AllFeatureTelemetry/u,
);
});
it("keeps the platform kernel independent of concrete product modules", async () => {
const rule = (await dependencyRules()).find(
({ name }) => name === "platform-kernel-is-product-neutral",
);
expect(rule).toBeDefined();
const offenders: string[] = [];
for (const file of await productionSources(path.join(ROOT, "src/platform"))) {
const relative = path.relative(ROOT, file).split(path.sep).join("/");
if (relative.startsWith("src/platform/routing/")) continue;
const source = await readFile(file, "utf8");
if (/from\s+["']\.\.\/\.\.\/(features|contexts|apps|adapters|bootstrap|presentation|application)\//u.test(source)) {
offenders.push(relative);
}
}
expect(offenders).toEqual([]);
});
});
+43
View File
@@ -0,0 +1,43 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
findRequestFanout,
scanRequestFanout,
} from "../../scripts/check-request-fanout.ts";
describe("no per-row transport loop (frontend N+1 source gate)", () => {
it("finds no per-row dispatch in feature code or application use cases", async () => {
const result = await scanRequestFanout(path.resolve("."));
expect(result.files).toBeGreaterThan(0);
expect(result.violations).toEqual([]);
});
it("rejects every forbidden fixture and accepts the bulk-read fixture", async () => {
const root = path.resolve(".");
const forbidden = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/forbidden"]);
const allowed = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/allowed"]);
expect(new Set(forbidden.violations.map((violation) => violation.file)).size).toBe(forbidden.files);
expect(forbidden.files).toBe(3);
expect(allowed.violations).toEqual([]);
});
it("names the dispatch and the repeating construct", async () => {
const violations = await findRequestFanout(
"inline.ts",
"export const load = (api: { get(id: string): Promise<unknown> }, ids: string[]) =>\n Promise.all(ids.map((id) => api.get(id)));\n",
);
expect(violations).toEqual([
{ file: "inline.ts", line: 2, call: "api.get()", context: ".map() callback" },
]);
});
it("honours an explicit reviewed exception on the call line", async () => {
const violations = await findRequestFanout(
"reviewed.ts",
"export async function f(http: { execute(): Promise<void> }) {\n for (let i = 0; i < 2; i += 1) await http.execute(); // fanout-reviewed: bounded 2-step handshake\n}\n",
);
expect(violations).toEqual([]);
});
});
@@ -0,0 +1,116 @@
import { describe, expect, it } from "vitest";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
import { defineFeatureModule } from "../../src/features/feature-module.ts";
import { planTopologyCapacity } from "../../src/platform/cardinality/topology-capacity.ts";
const MAX_FEATURES_PER_CONTEXT = 200;
const MAX_CONTEXTS_PER_APP = 20;
function fakeFeature(id: string) {
return defineFeatureModule({
id,
contracts: { featureId: id },
routes: {},
adapters: [],
runtimes: [],
messages: {},
contractContributions: [],
});
}
describe("topology cardinality", () => {
it("accepts direct children at the configured ceilings", () => {
const features = Array.from({ length: MAX_FEATURES_PER_CONTEXT }, (_, index) =>
fakeFeature(`feature-${index}`),
);
const contexts = Array.from({ length: MAX_CONTEXTS_PER_APP }, (_, index) =>
defineBoundedContextModule({
id: `context-${index}`,
features,
budget: { maxFeatures: MAX_FEATURES_PER_CONTEXT },
}),
);
expect(() =>
defineDeployableAppModule({
id: "scale-ceiling-app",
contexts,
budget: { maxContexts: MAX_CONTEXTS_PER_APP },
}),
).not.toThrow();
});
it("rejects a context above its feature budget", () => {
expect(() =>
defineBoundedContextModule({
id: "commerce",
features: Array.from({ length: 201 }, (_, index) => fakeFeature(`f${index}`)),
budget: { maxFeatures: MAX_FEATURES_PER_CONTEXT },
}),
).toThrow(/commerce.*201.*200/);
});
it("rejects duplicate direct child ids", () => {
const context = defineBoundedContextModule({
id: "commerce",
features: [],
budget: { maxFeatures: MAX_FEATURES_PER_CONTEXT },
});
expect(() =>
defineDeployableAppModule({
id: "customer",
contexts: [context, context],
budget: { maxContexts: MAX_CONTEXTS_PER_APP },
}),
).toThrow(/Duplicate.*commerce/);
});
});
describe("extreme-scale topology capacity", () => {
const cases = [
{ featureCount: 100, expectedContexts: 1, expectedApps: 1 },
{ featureCount: 1_000, expectedContexts: 5, expectedApps: 1 },
{ featureCount: 10_000, expectedContexts: 50, expectedApps: 3 },
{ featureCount: 100_000, expectedContexts: 500, expectedApps: 25 },
{ featureCount: 1_000_000, expectedContexts: 5_000, expectedApps: 250 },
] as const;
it.each(cases)(
"partitions $featureCount features without exceeding direct-child budgets",
({ featureCount, expectedContexts, expectedApps }) => {
const plan = planTopologyCapacity({
featureCount,
maxFeaturesPerContext: MAX_FEATURES_PER_CONTEXT,
maxContextsPerApp: MAX_CONTEXTS_PER_APP,
});
expect(plan.contextCount).toBe(expectedContexts);
expect(plan.appCount).toBe(expectedApps);
expect(plan.maxFeaturesInAnyContext).toBeLessThanOrEqual(MAX_FEATURES_PER_CONTEXT);
expect(plan.maxContextsInAnyApp).toBeLessThanOrEqual(MAX_CONTEXTS_PER_APP);
expect(plan.totalFeatureCapacity).toBeGreaterThanOrEqual(featureCount);
expect(plan.totalFeatureCapacity - featureCount).toBeLessThan(
MAX_FEATURES_PER_CONTEXT * MAX_CONTEXTS_PER_APP,
);
},
);
it("keeps a zero-feature product as one deployable app with no contexts", () => {
expect(
planTopologyCapacity({
featureCount: 0,
maxFeaturesPerContext: MAX_FEATURES_PER_CONTEXT,
maxContextsPerApp: MAX_CONTEXTS_PER_APP,
}),
).toMatchObject({
featureCount: 0,
contextCount: 0,
appCount: 1,
maxFeaturesInAnyContext: 0,
maxContextsInAnyApp: 0,
});
});
});
@@ -329,3 +329,127 @@ test("hands a bounded generated Blob to the real browser download path", async (
},
});
});
/**
* R3-6 / STO-08. The enhanced picker keeps `window.showOpenFilePicker` and
* calls it later. Called with the options object as receiver it would reject
* with "Illegal invocation" (TypeError → UNAVAILABLE). This spec passes the
* real, unbound function and an injected `isActive: true` reading so the app's
* own activation precheck lets the call through; with no real user gesture the
* browser must then reject with its activation error (SecurityError →
* PERMISSION_DENIED). Browsers without the API return UNSUPPORTED, because
* the capability evidence gate forbids skipped cases.
*/
test("calls the real showOpenFilePicker without a receiver and gets the activation error", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const system = (globalThis as typeof globalThis & {
showOpenFilePicker?: (options?: unknown) => Promise<unknown>;
}).showOpenFilePicker;
if (typeof system !== "function") return { kind: "UNSUPPORTED" as const };
// Playwright evaluates with a user gesture, so wait until that transient
// activation expires (5s in Chromium) to get a real "no gesture" call.
const deadline = performance.now() + 10_000;
while (navigator.userActivation.isActive && performance.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
const activationExpired = !navigator.userActivation.isActive;
const errorName = async (call: () => Promise<unknown>) => {
try {
await call();
return "RESOLVED";
} catch (error) {
return error instanceof Error ? error.name : String(error);
}
};
// Controls: the native activation error, and what a wrong receiver does.
const directWithoutGesture = await errorName(() => system());
const wrongReceiver = await errorName(() =>
Reflect.apply(system, {}, []) as Promise<unknown>,
);
const modulePath = "/src/adapters/browser-files/index.ts";
const { createBrowserFileRuntime, browserFilePolicyReference } =
(await import(
/* @vite-ignore */ modulePath
)) as typeof import("../../src/adapters/browser-files/index.ts");
const input = document.createElement("input");
input.type = "file";
const filePolicy = browserFilePolicyReference("avatar", "enhanced-unbound");
const runtime = createBrowserFileRuntime({
input,
showOpenFilePicker: system as never,
userActivation: { isActive: true },
policies: [
{
reference: filePolicy,
selection: {
policyId: "avatar-v1",
purpose: "avatar",
classification: "PERSONAL",
multiple: false,
maxCount: 1,
maxFileBytes: 1024,
maxTotalBytes: 1024,
allowEmpty: false,
accept: [{ mediaType: "image/png", extensions: [".png"] }],
},
},
],
limits: {
hardMaxPreviewBytes: 1024,
hardMaxObjectUrlBytes: 1024,
hardMaxTransferBytes: 4096,
},
download: {
host: Object.freeze({ handoff() {} }),
browserManagedCapabilities: {
resolve() {
return {
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
};
},
},
},
});
if (!runtime.enhancedPicker) {
throw new Error("Enhanced picker was not composed.");
}
try {
const selected = await runtime.enhancedPicker.select({
policy: filePolicy,
});
return {
kind: "SUPPORTED" as const,
activationExpired,
directWithoutGesture,
wrongReceiver,
selected,
};
} finally {
runtime.dispose();
}
});
if (result.kind === "UNSUPPORTED") {
expect(result).toEqual({ kind: "UNSUPPORTED" });
return;
}
expect(result.activationExpired).toBe(true);
expect(result.directWithoutGesture).toBe("SecurityError");
expect(result.wrongReceiver).toBe("TypeError");
expect(result.selected).toMatchObject({
ok: false,
error: { code: "PERMISSION_DENIED", operation: "FILE_SELECT" },
});
});
@@ -0,0 +1,29 @@
import { expect, test } from "@playwright/test";
// R3-7. The chunk-recovery classifier matches engine error wording. Run the
// app's own classifier (served by the dev server) against the error each real
// engine reports for a dynamic import whose chunk is gone after a deploy, so a
// wording change in Chromium, Firefox or WebKit fails here.
test("classifies the engine's missing dynamic-import chunk error as a chunk failure", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
// A browser URL served by the dev server, not a module tsc resolves.
const classifierUrl = "/src/presentation/boundaries/chunk-recovery-boundary.tsx";
const { isChunkLoadFailure } = (await import(classifierUrl)) as {
isChunkLoadFailure: (error: unknown) => boolean;
};
try {
await import(`/assets/removed-after-deploy-${Date.now()}.js`);
return { reported: "no error", classified: false };
} catch (error) {
return {
reported: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
classified: isChunkLoadFailure(error),
};
}
});
expect(result.classified, result.reported).toBe(true);
});
@@ -23,12 +23,14 @@ async function startLifecycleRuntime(
name: string,
targetVersion: 1 | 2,
blockedTimeoutMs = 1_000,
partitioned = false,
): Promise<void> {
await page.evaluate(
async ({
currentDatabaseName,
currentTargetVersion,
currentBlockedTimeoutMs,
currentPartitioned,
}) => {
const modulePath =
"/src/adapters/storage/indexeddb/indexeddb-runtime.ts";
@@ -38,24 +40,31 @@ async function startLifecycleRuntime(
type LifecycleValue = Readonly<{ value: string }>;
const [authorityToken, namespaceToken, partitionToken] =
currentDatabaseName.slice("ca-idb-v1:".length).split(".");
const accountScope = currentPartitioned
? ("OPAQUE_PARTITION" as const)
: ("ORIGIN_SHARED" as const);
const scope = {
authorityToken,
namespaceToken,
partitionToken,
accountScope: "ORIGIN_SHARED" as const,
accountScope,
};
const storagePolicy = {
owner: "platform-storage",
namespace: "indexeddb-browser-lifecycle",
classification: "INTERNAL" as const,
authority: "SERVER" as const,
accountScope: "ORIGIN_SHARED" as const,
accountScope,
retention: { kind: "EXPLICIT_DELETE" as const },
softBudgetBytes: 1_000_000,
hardBudgetBytes: 2_000_000,
evictionPriority: "SYNCED_COPY" as const,
logoutAction: "KEEP_ORIGIN_SHARED" as const,
accountDeletionAction: "KEEP_ORIGIN_SHARED" as const,
logoutAction: currentPartitioned
? ("PURGE_PARTITION" as const)
: ("KEEP_ORIGIN_SHARED" as const),
accountDeletionAction: currentPartitioned
? ("PURGE_PARTITION" as const)
: ("KEEP_ORIGIN_SHARED" as const),
pressureAction: "RETAIN" as const,
unavailableFallback: "ONLINE_ONLY" as const,
};
@@ -184,6 +193,7 @@ async function startLifecycleRuntime(
currentDatabaseName: name,
currentTargetVersion: targetVersion,
currentBlockedTimeoutMs: blockedTimeoutMs,
currentPartitioned: partitioned,
},
);
}
@@ -1067,3 +1077,155 @@ test("fails a blocked v2 upgrade closed, then closes its late connection after t
await blockerPage.close();
}
});
test("05-03 deletes a partition's dataset for an authorized ACCOUNT_DELETION when its budget row is corrupt", async ({
page,
}) => {
const name = databaseName("corrupt-governance");
await page.goto("/");
await startLifecycleRuntime(page, name, 1, 1_000, true);
expect(await settleLifecycleRuntime(page)).toMatchObject({
opened: { ok: true },
});
expect(
await page.evaluate(async () => {
const runtime = (
globalThis as unknown as {
__indexedDbLifecycleRuntime: {
compareAndSwap(input: unknown): Promise<unknown>;
close(): void;
};
}
).__indexedDbLifecycleRuntime;
const written = await runtime.compareAndSwap({
key: "personal-1",
value: { value: "mine" },
expectedRevision: null,
idempotencyKey: "personal-create",
});
runtime.close();
return written;
}),
).toMatchObject({ ok: true });
expect(
await page.evaluate(
async (currentDatabaseName) =>
await new Promise<string>((resolve) => {
const request = indexedDB.open(currentDatabaseName, 1);
request.onerror = () =>
resolve(request.error?.name ?? "UNKNOWN_ERROR");
request.onsuccess = () => {
const database = request.result;
const transaction = database.transaction(
"governance",
"readwrite",
);
transaction.objectStore("governance").put({
bindingKey: "dataset-budget",
budgetVersion: 1,
usedBytes: -5,
receiptCount: 1,
});
transaction.oncomplete = () => {
database.close();
resolve("CORRUPTED");
};
transaction.onabort = () => {
database.close();
resolve("ABORTED");
};
};
}),
name,
),
).toBe("CORRUPTED");
await startLifecycleRuntime(page, name, 1, 1_000, true);
expect(await settleLifecycleRuntime(page)).toMatchObject({
opened: { ok: false, error: { code: "POLICY_REJECTED" } },
});
const purged = await page.evaluate(async () => {
const runtime = (
globalThis as unknown as {
__indexedDbLifecycleRuntime: {
enforceLifecycleBatch(input: unknown): Promise<unknown>;
};
}
).__indexedDbLifecycleRuntime;
return await runtime.enforceLifecycleBatch({
action: "ACCOUNT_DELETION",
maxRows: 100,
maxDurationMs: 5_000,
});
});
expect(purged).toMatchObject({
ok: true,
value: { state: "COMPLETE", datasetDeleted: true },
});
const remaining = await page.evaluate(async (currentDatabaseName) => {
(
globalThis as unknown as {
__indexedDbLifecycleRuntime?: { close(): void };
}
).__indexedDbLifecycleRuntime?.close();
// A fresh open of a deleted database runs its upgrade from version 0.
return await new Promise<number>((resolve, reject) => {
const request = indexedDB.open(currentDatabaseName);
let oldVersion = -1;
request.onupgradeneeded = (event) => {
oldVersion = event.oldVersion;
};
request.onsuccess = () => {
request.result.close();
const deletion = indexedDB.deleteDatabase(currentDatabaseName);
deletion.onsuccess = () => resolve(oldVersion);
deletion.onerror = () => reject(deletion.error);
};
request.onerror = () => reject(request.error);
});
}, name);
expect(remaining).toBe(0);
});
test("05-06 an older tab meets a schema a newer tab upgraded and goes online-only", async ({
page,
}) => {
const olderPage = await page.context().newPage();
const name = databaseName("future-schema");
try {
await Promise.all([page.goto("/"), olderPage.goto("/")]);
expect(await installLifecycleRuntime(page, name, 2)).toMatchObject({
opened: { ok: true },
status: { kind: "READY", schemaVersion: 2 },
});
await closeLifecycleRuntime(page);
expect(await installLifecycleRuntime(olderPage, name, 1)).toEqual({
opened: {
ok: false,
error: {
code: "UNSUPPORTED",
operation: "INDEXEDDB_OPEN",
retryable: false,
recovery: "ONLINE_ONLY",
},
},
status: { kind: "INCOMPATIBLE", schemaVersion: 1 },
});
await closeLifecycleRuntime(olderPage);
const deletion = await page.evaluate(
async (currentDatabaseName) =>
await new Promise<string>((resolve) => {
const request = indexedDB.deleteDatabase(currentDatabaseName);
request.onsuccess = () => resolve("DELETED");
request.onerror = () =>
resolve(request.error?.name ?? "UNKNOWN_ERROR");
request.onblocked = () => resolve("BLOCKED");
}),
name,
);
expect(deletion).toBe("DELETED");
} finally {
await olderPage.close();
}
});
@@ -219,3 +219,193 @@ test("runs put, open, remove and reconcile through a native DedicatedWorker, OPF
expect(result.deletion).toBe("DELETED");
expect(["DELETED", "ABSENT"]).toContain(result.opfsCleanup);
});
type OpfsTabScope = Readonly<{
namespace: string;
authorityToken: string;
namespaceToken: string;
partitionToken: string;
}>;
/**
* Installs an OPFS runtime for `scope` in this tab and keeps it on
* `globalThis.__opfsTab` for later evaluate calls.
*/
async function installOpfsTab(
page: import("@playwright/test").Page,
scope: OpfsTabScope,
): Promise<boolean> {
return await page.evaluate(async (tabScope) => {
const runtimeModulePath =
"/src/adapters/storage/opfs/browser-opfs-runtime.ts";
const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts";
const { createBrowserOpfsRuntime, inspectBrowserOpfsSupport } =
(await import(
/* @vite-ignore */ runtimeModulePath
)) as typeof import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts");
const { resolveOpfsRuntimePolicy } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts");
const policy = resolveOpfsRuntimePolicy();
if (!inspectBrowserOpfsSupport(policy).ok) return false;
(globalThis as unknown as { __opfsTab: unknown }).__opfsTab =
createBrowserOpfsRuntime({
workerUrl: new URL(
"/tests/browser-capabilities/opfs-test.worker.ts",
location.href,
),
workerName: `opfs-tab-${crypto.randomUUID()}`,
scope: tabScope,
storagePolicy: {
owner: "browser-capability",
namespace: tabScope.namespace,
classification: "PERSONAL",
authority: "LOCAL_FIRST",
accountScope: "OPAQUE_PARTITION",
retention: { kind: "EXPLICIT_DELETE" },
softBudgetBytes: 1024 * 1024,
hardBudgetBytes: 2 * 1024 * 1024,
evictionPriority: "USER_AUTHORED",
logoutAction: "EXPORT_THEN_PURGE",
accountDeletionAction: "PURGE_PARTITION",
pressureAction: "RETAIN",
unavailableFallback: "EXPORT_REQUIRED",
},
policy,
});
return true;
}, scope);
}
test("05-01 a reconcile in another tab skips a live put and the put stays readable", async ({
page,
}) => {
const secondPage = await page.context().newPage();
const suffix = crypto.randomUUID().replaceAll("-", "");
const scope: OpfsTabScope = {
namespace: "durable-objects",
authorityToken: `authority_${suffix}`,
namespaceToken: `namespace_${suffix}`,
partitionToken: `partition_${suffix}`,
};
type Tab = import("../../src/adapters/storage/opfs/browser-opfs-runtime.ts").BrowserOpfsRuntime;
try {
await Promise.all([page.goto("/"), secondPage.goto("/")]);
if (!(await installOpfsTab(page, scope))) return;
expect(await installOpfsTab(secondPage, scope)).toBe(true);
// Tab A starts a put whose source stalls, so its journal row stays
// PREPARING and its worker holds the OPFS mutation lock.
await page.evaluate(async () => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__release?: () => void;
__put?: Promise<unknown>;
};
let streaming!: () => void;
const started = new Promise<void>((resolve) => {
streaming = resolve;
});
const gate = new Promise<void>((resolve) => {
state.__release = resolve;
});
state.__put = state.__opfsTab.objects.put({
objectId: "object_tab_12345678",
expectedGeneration: null,
mediaType: "application/octet-stream",
source: {
byteLength: 4,
async *stream() {
streaming();
await gate;
yield { ok: true as const, value: new Uint8Array([2, 7, 1, 8]) };
},
},
});
await started;
});
// Tab B reconciles while tab A's put is in flight.
await secondPage.evaluate(() => {
const state = globalThis as unknown as {
__opfsTab: Tab;
__reconcile?: Promise<unknown>;
};
state.__reconcile = state.__opfsTab.maintenance.reconcile();
});
await page.waitForTimeout(250);
const put = await page.evaluate(async () => {
const state = globalThis as unknown as {
__release: () => void;
__put: Promise<unknown>;
};
state.__release();
return await state.__put;
});
const reconciled = await secondPage.evaluate(
async () =>
await (globalThis as unknown as { __reconcile: Promise<unknown> })
.__reconcile,
);
const opened = await page.evaluate(async () => {
const runtime = (globalThis as unknown as { __opfsTab: Tab }).__opfsTab;
const result = await runtime.objects.open({
objectId: "object_tab_12345678",
});
if (!result.ok) return result.error.code;
const bytes: number[] = [];
for await (const chunk of result.value.source.stream(
new AbortController().signal,
)) {
if (!chunk.ok) return chunk.error.code;
bytes.push(...chunk.value);
}
return bytes;
});
expect(put).toMatchObject({ ok: true, value: { generation: 1 } });
expect(reconciled).toMatchObject({
ok: true,
value: { skippedLiveTransactions: 1, rolledBackTransactions: 0 },
});
expect(opened).toEqual([2, 7, 1, 8]);
} finally {
for (const tab of [page, secondPage]) {
await tab.evaluate(() =>
(globalThis as unknown as { __opfsTab?: Tab }).__opfsTab?.close(),
);
}
const cleanup = await page.evaluate(async (tabScope) => {
const journalModulePath =
"/src/adapters/storage/opfs/indexeddb-opfs-journal.ts";
const policyModulePath = "/src/adapters/storage/opfs/opfs-policy.ts";
const { opfsJournalDatabaseName } = (await import(
/* @vite-ignore */ journalModulePath
)) as typeof import("../../src/adapters/storage/opfs/indexeddb-opfs-journal.ts");
const { DEFAULT_OPFS_RUNTIME_POLICY } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/storage/opfs/opfs-policy.ts");
const deletion = await new Promise<string>((resolve) => {
const request = indexedDB.deleteDatabase(
opfsJournalDatabaseName(tabScope.authorityToken),
);
request.onsuccess = () => resolve("DELETED");
request.onerror = () => resolve(request.error?.name ?? "UNKNOWN");
request.onblocked = () => resolve("BLOCKED");
});
try {
const root = await (
await navigator.storage.getDirectory()
).getDirectoryHandle(DEFAULT_OPFS_RUNTIME_POLICY.rootDirectoryName);
await (
await root.getDirectoryHandle("authorities")
).removeEntry(tabScope.authorityToken, { recursive: true });
} catch {
// Nothing was written for this authority.
}
return deletion;
}, scope);
expect(cleanup).toBe("DELETED");
await secondPage.close();
}
});
@@ -310,3 +310,142 @@ test("keeps A active across a failed B stage, activates B with A rollback, and c
expect(result.rollbackAPreserved).toBe(true);
expect(result.remainingOwnedCount).toBe(3);
});
/**
* R3-6. The real Cache API applies `Vary` on `match()`, which the in-memory
* fakes do not. A public asset served with `Vary: Accept-Encoding` must stage,
* activate and still be found by the exact lookup.
*/
test("stages, activates, and looks up a Vary: Accept-Encoding response in the real Cache API", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const adapterModulePath =
"/src/adapters/cache-storage/public-response-cache-adapter.ts";
const policyModulePath =
"/src/adapters/cache-storage/public-cache-policy.ts";
const {
computePublicCacheManifestDigestHex,
createPublicCacheWebLock,
createPublicResponseCacheAdapter,
} = (await import(
/* @vite-ignore */ adapterModulePath
)) as typeof import("../../src/adapters/cache-storage/public-response-cache-adapter.ts");
const { createDefaultPublicCachePolicy } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/cache-storage/public-cache-policy.ts");
const suffix = crypto.randomUUID().replaceAll("-", "");
const releaseId = `browser-vary-${suffix.slice(0, 20)}`;
const policy = {
...createDefaultPublicCachePolicy(location.origin),
ownedCachePrefix: `cap-${suffix.slice(0, 24)}:`,
mutationLockName: `cap-${suffix}:mutation`,
};
const url = `${location.origin}/cache-${suffix}-vary.js`;
const bytes = new TextEncoder().encode("export const vary = 1;");
const digest = await crypto.subtle.digest("SHA-256", bytes);
const assets = [
{
absoluteUrl: url,
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256" as const,
digestHex: Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, "0"),
).join(""),
},
},
];
const manifest = {
releaseRegistryId: releaseId,
assets,
manifestDigestHex: await computePublicCacheManifestDigestHex(
crypto,
releaseId,
assets,
policy,
),
};
const adapter = createPublicResponseCacheAdapter({
cacheStorage: caches,
crypto,
mutationLock: createPublicCacheWebLock(
navigator.locks,
policy.mutationLockName,
),
policy,
fetcher: async (request) => {
if (request.url !== url) throw new TypeError("Unexpected cache URL.");
return new Response(Uint8Array.from(bytes), {
status: 200,
headers: {
"cache-control": "public, max-age=31536000, immutable",
"content-type": "application/javascript",
vary: "Accept-Encoding",
},
});
},
});
try {
const staged = await adapter.admin.stageRelease(manifest);
const activated = await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
);
const matched = await adapter.responses.matchActiveExact({
absoluteUrl: url,
});
const streamed: number[] = [];
if (matched.ok && matched.value) {
for await (const chunk of matched.value.body.stream(
new AbortController().signal,
)) {
if (!chunk.ok) return { staged, activated, matched: chunk };
streamed.push(...chunk.value);
}
}
// What the browser itself stored, read back through the raw Cache API.
const releaseCacheName = (await caches.keys()).find((name) =>
name.startsWith(`${policy.ownedCachePrefix}release:${releaseId}:`),
);
const raw = releaseCacheName
? await (await caches.open(releaseCacheName)).match(url)
: undefined;
return {
staged,
activated,
matched: matched.ok
? {
ok: true,
found: matched.value !== null,
vary:
matched.value?.headers.find(
([name]) => name.toLowerCase() === "vary",
)?.[1] ?? null,
}
: matched,
streamed,
rawVary: raw?.headers.get("vary") ?? null,
expected: Array.from(bytes),
};
} finally {
for (const name of await caches.keys()) {
if (name.startsWith(policy.ownedCachePrefix)) await caches.delete(name);
}
}
});
expect(result.staged).toMatchObject({ ok: true, value: { entryCount: 1 } });
expect(result.activated).toMatchObject({ ok: true });
expect(result.matched).toEqual({
ok: true,
found: true,
vary: "Accept-Encoding",
});
expect(result.streamed).toEqual(result.expected);
expect(result.rawVary).toBe("Accept-Encoding");
});
@@ -8,6 +8,10 @@ import {
useApplicationMutation,
} from "../../src/presentation/adapters/query/application-query.ts";
import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import type { MutationIntent } from "../../src/contracts/mutation-intent.ts";
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts";
import {
RESOURCE_INVALIDATION_TOPIC,
deterministicMutationIntentFactory,
@@ -160,6 +164,62 @@ describe("application mutation intent admission", () => {
await act(() => first);
});
it("bounds JOIN_IDENTICAL waiters without starting another mutation", async () => {
const client = queryClient();
const scope = scopeSnapshot();
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "joined-waiter-budget-v1",
definitionVersion: 1,
operationId: "CREATE_JOINED_BOUNDED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "JOIN_IDENTICAL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
let admitted: Promise<ApplicationResult<string>> | null = null;
let joined: readonly Promise<ApplicationResult<string>>[] = [];
let overflow: Promise<ApplicationResult<string>> | null = null;
act(() => {
admitted = hook.result.current.submit("same-input");
joined = Array.from(
{ length: MUTATION_COORDINATOR_BOUNDS.waitersPerJoinedIntent },
() => hook.result.current.submit("same-input"),
);
overflow = hook.result.current.submit("same-input");
});
expect(joined.every((waiter) => waiter === admitted)).toBe(true);
expect(overflow).not.toBe(admitted);
if (!overflow) throw new Error("expected overflow result");
await expect(overflow).resolves.toMatchObject({
ok: false,
error: {
kind: "DUPLICATE_IN_FLIGHT",
code: "JOIN_WAITER_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
});
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
complete({ ok: true, value: "same-input" });
if (!admitted) throw new Error("expected admitted mutation");
await act(() => admitted);
});
it("keeps the legacy raw mutation path outside the intent factory", async () => {
const client = queryClient();
const createIntent = vi.fn<MutationIntentFactory["create"]>();
@@ -314,4 +374,124 @@ describe("application mutation intent admission", () => {
});
});
describe("unknown-effect replay (D-1)", () => {
function replayScope() {
let token = 0;
return {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
}
function renderKeyedCreate(
outcomes: ApplicationResult<string>[],
) {
const client = queryClient();
const intents: MutationIntent[] = [];
const execute = vi.fn(
async (
input: string,
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
): Promise<ApplicationResult<string>> => {
intents.push(context.intent);
return outcomes.shift() ?? { ok: true, value: input };
},
);
const scope = replayScope();
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "replay-intent-v1",
definitionVersion: 1,
operationId: "CREATE_REPLAYED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
return { hook, intents, execute };
}
const unknown: ApplicationResult<string> = {
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, {
effect: "MAYBE_APPLIED",
}),
};
it("sends the same intent when the same input is saved again after an unknown effect", async () => {
const { hook, intents } = renderKeyedCreate([unknown]);
await act(() => hook.result.current.submit("same-input"));
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.submit("same-input"));
expect(intents).toHaveLength(2);
expect(intents[1]).toBe(intents[0]);
expect(intents[1]?.idempotencyKey).toBe("key-1");
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
});
it("mints a new key when the input changes after an unknown effect", async () => {
const { hook, intents } = renderKeyedCreate([unknown]);
await act(() => hook.result.current.submit("first-input"));
await act(() => hook.result.current.submit("changed-input"));
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
"key-1",
"key-2",
]);
// The first request is still unresolved; a different request cannot
// settle it.
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("resends the unknown head request with its original key", async () => {
const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]);
await act(() => hook.result.current.submit("resent-input"));
let resent: ApplicationResult<string> | null | undefined;
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toMatchObject({
ok: false,
error: { effect: "MAYBE_APPLIED" },
});
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toEqual({ ok: true, value: "resent-input" });
expect(execute.mock.calls.map(([input]) => input)).toEqual([
"resent-input",
"resent-input",
"resent-input",
]);
expect(new Set(intents.map((intent) => intent.idempotencyKey))).toEqual(
new Set(["key-1"]),
);
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
// Nothing is left to resend once the effect is settled.
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toBeNull();
expect(execute).toHaveBeenCalledTimes(3);
});
});
});
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { onlineManager } from "@tanstack/react-query";
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
@@ -47,6 +48,130 @@ describe("application query inbound bridge", () => {
expect(execute).toHaveBeenCalledTimes(3);
});
it("coalesces repeated manual retries while stale data is refetching", async () => {
const client = queryClient();
const pending: Array<
(value: ApplicationResult<string[]>) => void
> = [];
const execute = vi.fn(
({ signal }: Readonly<{ signal: AbortSignal }>) => {
if (execute.mock.calls.length === 1) {
return Promise.resolve({ ok: true as const, value: ["first"] });
}
return new Promise<ApplicationResult<string[]>>((resolve) => {
pending.push(resolve);
signal.addEventListener(
"abort",
() => resolve({ ok: true, value: ["aborted"] }),
{ once: true },
);
});
},
);
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["resource", "manual-retry-coalescing"],
execute,
}),
{ wrapper: wrapper(client) },
);
await waitFor(() => expect(hook.result.current.data).toEqual(["first"]));
let firstRetry: Promise<void> = Promise.resolve();
act(() => {
firstRetry = hook.result.current.retry();
});
await waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
let secondRetry: Promise<void> = Promise.resolve();
act(() => {
secondRetry = hook.result.current.retry();
});
await act(async () => {
await Promise.resolve();
await Promise.resolve();
});
const callsWhileActive = execute.mock.calls.length;
const physicalRefetches = pending.length;
act(() => {
for (const resolve of pending) {
resolve({ ok: true, value: ["recovered"] });
}
});
await act(() => Promise.all([firstRetry, secondRetry]));
await waitFor(() =>
expect(hook.result.current.data).toEqual(["recovered"]),
);
expect(callsWhileActive).toBe(2);
expect(physicalRefetches).toBe(1);
});
it("does not report a disabled query without data as loading", async () => {
// A dependent query waiting on its prerequisite is idle, not loading.
const client = queryClient();
const execute = vi.fn(async () => ({ ok: true as const, value: ["x"] }));
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["resource", "waiting-on-prerequisite"],
execute,
enabled: false,
}),
{ wrapper: wrapper(client) },
);
expect(hook.result.current.state.base).toBe("idle");
expect(execute).not.toHaveBeenCalled();
});
it("reports a completed query without items as empty, not idle", async () => {
const client = queryClient();
const hook = renderHook(
() =>
useApplicationQuery({
queryKey: ["resource", "completed-empty"],
execute: async () => ({ ok: true as const, value: [] as string[] }),
}),
{ wrapper: wrapper(client) },
);
await waitFor(() => expect(hook.result.current.state.base).toBe("empty"));
});
it("still reports a real first load as loading, including a paused offline one", async () => {
const client = queryClient();
const execute = vi.fn(
() => new Promise<ApplicationResult<string[]>>(() => {}),
);
const inFlight = renderHook(
() => useApplicationQuery({ queryKey: ["resource", "first"], execute }),
{ wrapper: wrapper(client) },
);
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
expect(inFlight.result.current.state.base).toBe("initial-loading");
// Offline, TanStack pauses the first fetch (isFetching=false) instead of
// running it; the user is still waiting for data.
onlineManager.setOnline(false);
try {
const paused = renderHook(
() =>
useApplicationQuery({ queryKey: ["resource", "offline"], execute }),
{ wrapper: wrapper(client) },
);
expect(client.getQueryState(["resource", "offline"])?.fetchStatus).toBe(
"paused",
);
expect(paused.result.current.state.base).toBe("initial-loading");
} finally {
onlineManager.setOnline(true);
}
});
it("projects an initial application failure into terminal state", async () => {
const client = queryClient();
const failure = createFailure("FORBIDDEN", "LIST", 0);
+87 -4
View File
@@ -7,6 +7,7 @@ import { describe, expect, it, vi } from "vitest";
import { deriveAsyncState } from "../../src/application/view-models/async-state.ts";
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
import { createFailure } from "../../src/contracts/errors.ts";
import { AccessSurface } from "../../src/presentation/design-system/index.ts";
describe("async UI state matrix", () => {
it.each([
@@ -14,6 +15,7 @@ describe("async UI state matrix", () => {
[{ data: [{ id: "1" }] }, "success"],
[{ data: [] }, "empty"],
[{ data: null }, "empty"],
[{}, "idle"],
[
{ failure: createFailure("SERVER_FAILURE", "LIST", 0) },
"terminal-error",
@@ -52,10 +54,11 @@ describe("async UI state matrix", () => {
});
});
it("renders unknown mutation effects with reconciliation-only actions", async () => {
it("renders unknown mutation effects with confirm-applied and resend only", async () => {
const user = userEvent.setup();
const retry = vi.fn();
const reconcile = vi.fn();
const resend = vi.fn();
const state = deriveAsyncState({
data: ["value"],
hasMutationEffectUnknown: true,
@@ -66,6 +69,7 @@ describe("async UI state matrix", () => {
state={state}
onRetry={retry}
onReconcileUnknownEffect={reconcile}
onResendUnknownEffect={resend}
>
existing content
</AsyncSurface>,
@@ -80,12 +84,15 @@ describe("async UI state matrix", () => {
expect(
screen.queryByRole("button", { name: "다시 시도" }),
).not.toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "변경됨으로 확인" }));
await user.click(
screen.getByRole("button", { name: "변경되지 않음으로 확인" }),
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
);
expect(reconcile).toHaveBeenNthCalledWith(1, "APPLIED");
expect(reconcile).toHaveBeenNthCalledWith(2, "NOT_APPLIED");
expect(reconcile).toHaveBeenCalledExactlyOnceWith("APPLIED");
expect(resend).toHaveBeenCalledOnce();
expect(retry).not.toHaveBeenCalled();
});
@@ -132,6 +139,17 @@ describe("async UI state matrix", () => {
expect(resolveConflict).toHaveBeenCalledOnce();
});
// 08-07. The id a user quotes when asking for help is the one the request
// diagnostics carry as `correlation_id`.
it("shows the failure's request id as its support reference", () => {
const failure = {
...createFailure("SERVER_FAILURE", "LIST", 1),
requestId: "req-7f3a",
};
render(<AsyncSurface state={deriveAsyncState({ failure })} />);
expect(screen.getByRole("alert")).toHaveTextContent("지원 참조: req-7f3a");
});
it("renders only safe error vocabulary", () => {
const failure = createFailure("SERVER_FAILURE", "LIST", 0, {
code: "SERVER_FAILURE",
@@ -186,6 +204,71 @@ describe("async UI state matrix", () => {
expect(action).toHaveBeenCalledOnce();
});
it("renders an idle query as neither loading nor empty", () => {
const { container, rerender } = render(
<AsyncSurface state={deriveAsyncState({})}>content</AsyncSurface>,
);
expect(container).toBeEmptyDOMElement();
rerender(
<AsyncSurface
state={deriveAsyncState({})}
idle={<p>조건을 먼저 선택하세요.</p>}
>
content
</AsyncSurface>,
);
expect(screen.getByText("조건을 먼저 선택하세요.")).toBeVisible();
expect(container.querySelector("[aria-busy]")).toBeNull();
expect(screen.queryByText("표시할 항목이 없습니다.")).toBeNull();
expect(screen.queryByText("content")).toBeNull();
});
it("still renders loading for a first load and the empty copy for an empty result", () => {
const { container, rerender } = render(
<AsyncSurface state={deriveAsyncState({ isInitialLoading: true })} />,
);
expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();
rerender(<AsyncSurface state={deriveAsyncState({ data: [] })} />);
expect(screen.getByText("표시할 항목이 없습니다.")).toBeVisible();
});
// 08-11. A query failure and the gallery draw one access set, not two.
it.each([
["AUTH_REQUIRED", "auth-required"],
["FORBIDDEN", "forbidden"],
["NOT_FOUND", "not-found"],
] as const)(
"renders a %s query failure with the gallery's access surface",
async (kind, accessKind) => {
const user = userEvent.setup();
const action = vi.fn();
const failure = createFailure(kind, "LIST", 0);
const gallery = render(
<AccessSurface kind={accessKind} onAction={() => {}} />,
);
const expected = gallery.container.querySelector(".state-surface");
expect(expected).not.toBeNull();
const expectedText = expected?.textContent;
gallery.unmount();
render(
<AsyncSurface
state={deriveAsyncState({ failure })}
onAction={action}
/>,
);
const alert = screen.getByRole("alert");
expect(alert).toHaveAttribute("data-message-key", failure.userMessageKey);
expect(alert.querySelector(".state-surface")?.textContent).toBe(
expectedText,
);
await user.click(screen.getByRole("button"));
expect(action).toHaveBeenCalledOnce();
},
);
it("does not retain a terminal error after usable data is restored", () => {
const failed = deriveAsyncState({
failure: createFailure("SERVER_FAILURE", "LIST", 0),
@@ -0,0 +1,25 @@
// @vitest-environment jsdom
import { screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
// 09-03. A throw while the feature graph evaluates (a duplicate message key,
// a route or operation conflict) used to stop main.tsx before boot() ran, so
// the static "loading" shell stayed up forever.
vi.mock("../../src/.generated/product-feature-index.ts", () => {
throw new TypeError("Duplicate ko-KR message key: probe.title");
});
describe("boot entry (09-03)", () => {
it("shows the boot error shell when the app graph fails to evaluate", async () => {
document.body.innerHTML =
'<div id="root"><div role="status" data-boot-shell="">불러오는 중</div></div>';
vi.spyOn(console, "error").mockImplementation(() => {});
await import("../../src/bootstrap/main.tsx");
const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 });
expect(shell).toHaveTextContent("애플리케이션을 시작할 수 없습니다.");
expect(document.querySelector("[data-boot-shell]")).toBeNull();
});
});
@@ -0,0 +1,52 @@
// @vitest-environment jsdom
import { render, screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx";
// 09-04. An assembly defect (here the TypeError a missing feature capability
// used to produce) was shown as BOOT_CONFIG_FAILURE and the error was dropped.
const assemblyDefect = new TypeError(
"Cannot read properties of undefined (reading 'get')",
);
vi.mock("../../src/bootstrap/create-runtime-composition.ts", () => ({
createRuntimeComposition: async () => {
throw assemblyDefect;
},
}));
describe("unexpected boot failure (09-04)", () => {
it("is shown as BOOT_UNEXPECTED_FAILURE and reports the error in development", async () => {
document.body.innerHTML =
'<div id="root"><div role="status" data-boot-shell="">불러오는 중</div></div>';
// jsdom has no reportError; browsers do.
const reportError = vi.fn<(error: unknown) => void>();
vi.stubGlobal("reportError", reportError);
await import("../../src/bootstrap/main.tsx");
const shell = await screen.findByRole("alert", undefined, { timeout: 5_000 });
expect(shell).toHaveTextContent("BOOT_UNEXPECTED_FAILURE");
expect(shell).not.toHaveTextContent("BOOT_CONFIG_FAILURE");
expect(shell).toHaveTextContent("local-build");
expect(shell).toHaveTextContent("TypeError");
expect(shell).not.toHaveTextContent("reading 'get'");
expect(reportError).toHaveBeenCalledWith(assemblyDefect);
});
it("lists the rejected configuration keys", () => {
const view = render(
<BootErrorShell
kind="BOOT_CONFIG_FAILURE"
code="CONFIG_SCHEMA_INVALID"
buildId="build-a"
invalidKeys={["TELEMETRY_ENABELD"]}
supportReference="build-a:CONFIG_SCHEMA_INVALID"
/>,
);
const shell = within(view.container).getByRole("alert");
expect(within(shell).getByText("잘못된 설정 키")).toBeInTheDocument();
expect(shell).toHaveTextContent("TELEMETRY_ENABELD");
});
});
+36 -1
View File
@@ -1,6 +1,9 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { readFileSync } from "node:fs";
import { act, render, screen } from "@testing-library/react";
import { createRoot } from "react-dom/client";
import { describe, expect, it } from "vitest";
function TestShell() {
@@ -15,3 +18,35 @@ describe("component test level", () => {
);
});
});
describe("static boot shell (Q-6.9-8)", () => {
function loadIndexBody(): HTMLElement {
const html = readFileSync("index.html", "utf8");
document.body.innerHTML = new DOMParser()
.parseFromString(html, "text/html")
.body.innerHTML;
const root = document.getElementById("root");
if (!root) throw new Error("index.html has no #root");
return root;
}
it("shows a busy loading status before boot renders anything", () => {
const root = loadIndexBody();
const status = root.querySelector('[role="status"]');
expect(status?.getAttribute("aria-busy")).toBe("true");
expect(status?.textContent?.trim()).not.toBe("");
});
it("is replaced by the first render of the real app", async () => {
const root = loadIndexBody();
const reactRoot = createRoot(root);
await act(async () => {
reactRoot.render(<TestShell />);
});
expect(root.querySelector('[aria-busy="true"]')).toBeNull();
expect(screen.getByRole("main", { name: "application shell" })).toBeTruthy();
await act(async () => {
reactRoot.unmount();
});
});
});
@@ -1,6 +1,8 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { lazy, Suspense } from "react";
import { describe, expect, it, vi } from "vitest";
import {
@@ -8,6 +10,25 @@ import {
isChunkLoadFailure,
} from "../../src/presentation/boundaries/chunk-recovery-boundary.tsx";
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
// The Explore page stands in for a route chunk the network could not deliver:
// a rejected lazy module throws its rejection on every render, as this does
// (template sync af3d8e6: upstream uses its states example page, which this
// product deleted).
vi.mock("../../src/features/tech-log/presentation/public/pages/explore-page.tsx", () => ({
ExplorePage: function UnreachableChunk(): never {
throw new TypeError(
"Failed to fetch dynamically imported module: /assets/explore.js",
);
},
}));
function ChunkDefect(): never {
throw new TypeError("Failed to fetch dynamically imported module");
@@ -27,6 +48,47 @@ describe("chunk recovery boundary classification", () => {
expect(isChunkLoadFailure(new Error("ordinary render defect"))).toBe(false);
});
it("recognizes the WebKit module failure and the Vite CSS preload failure", () => {
expect(
isChunkLoadFailure(new TypeError("Importing a module script failed.")),
).toBe(true);
expect(
isChunkLoadFailure(
new Error("Unable to preload CSS for /assets/states-3f2a.css"),
),
).toBe(true);
});
it("recovers when Vite rethrows a vite:preloadError into the lazy import", async () => {
// Vite dispatches `vite:preloadError` and, unless a listener prevents it,
// rejects the dynamic import with the same error. That rejection is what
// reaches this boundary.
const Page = lazy(() =>
Promise.reject(new Error("Unable to preload CSS for /assets/states.css")),
);
const recover = vi.fn(async () => ({
action: "support" as const,
reason: "reload-already-attempted",
}));
render(
<Suspense fallback={null}>
<ChunkRecoveryBoundary chunkId="route-states" recover={recover}>
<Page />
</ChunkRecoveryBoundary>
</Suspense>,
);
expect(
await screen.findByRole("heading", {
name: "화면 자산을 복구하지 못했습니다.",
}),
).toBeVisible();
expect(recover).toHaveBeenCalledWith({
chunkId: "route-states",
failureKind: "CHUNK_LOAD_FAILURE",
});
});
it("runs the recovery input only for a lazy chunk rejection", async () => {
const recover = vi.fn(async () => ({
action: "support" as const,
@@ -65,4 +127,99 @@ describe("chunk recovery boundary classification", () => {
);
expect(recover).not.toHaveBeenCalled();
});
it("offers a user-started reload on the failure surface", async () => {
render(
<ChunkRecoveryBoundary
chunkId="route-home"
recover={async () => ({
action: "support" as const,
reason: "reload-already-attempted",
})}
>
<ChunkDefect />
</ChunkRecoveryBoundary>,
);
expect(
await screen.findByRole("button", { name: "한 번 새로고침" }),
).toBeVisible();
});
// 08-07. An unrecovered chunk failure shows a reference the render
// diagnostic also records.
it("shows an unrecovered chunk failure's support reference and records it", async () => {
const record = vi.fn();
window.history.pushState({}, "", "/explore");
render(
renderWithQueryProviders(
<ApplicationProvider
application={createTestApplication({
diagnostics: { record },
featureInputs: {
"tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input,
},
})}
>
<PreferenceProviders>
<AppRouter buildId="build-a" />
</PreferenceProviders>
</ApplicationProvider>,
),
);
const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
const incidentId = reference.textContent?.split(":").at(-1);
expect(record).toHaveBeenCalledWith({
level: "error",
eventId: "ui.render.failed",
context: expect.objectContaining({
route_id: "TECH_LOG_EXPLORE",
build_id: "build-a",
correlation_id: incidentId,
}),
});
});
it("clears a failed route chunk when the user moves to a sibling route", async () => {
// React Router reuses the rendered-route instance between sibling routes,
// so a failure latched in one route's boundary would otherwise follow the
// user to every other page until a full reload.
const user = userEvent.setup();
window.history.pushState({}, "", "/explore");
render(
renderWithQueryProviders(
<ApplicationProvider
application={createTestApplication({
featureInputs: {
"tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input,
},
})}
>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
),
);
expect(
await screen.findByRole("heading", {
name: "화면 자산을 복구하지 못했습니다.",
}),
).toBeVisible();
await user.click(screen.getAllByRole("link", { name: "주제" })[0]!);
expect(
await screen.findByRole(
"heading",
{ name: "주제", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
expect(
screen.queryByRole("heading", { name: "화면 자산을 복구하지 못했습니다." }),
).toBeNull();
});
});
@@ -0,0 +1,156 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { ReactNode } from "react";
import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
import {
Breadcrumbs,
LinkButton,
Pagination,
} from "../../src/presentation/design-system/index.ts";
import { StandardPage } from "../../src/presentation/templates/index.ts";
function LocationProbe() {
const location = useLocation();
return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;
}
function renderInRouter(ui: ReactNode, entry = "/app/items?q=term&sort=name") {
return render(
<MemoryRouter basename="/app" initialEntries={[entry]}>
<Routes>
<Route
path="*"
element={
<>
{ui}
<LocationProbe />
</>
}
/>
</Routes>
</MemoryRouter>,
);
}
describe("design-system links inside the router", () => {
it("renders LinkButton `to` as a router link that keeps the basename", async () => {
const user = userEvent.setup();
renderInRouter(<LinkButton to="/examples/states">States</LinkButton>);
const link = screen.getByRole("link", { name: "States" });
expect(link).toHaveAttribute("href", "/app/examples/states");
expect(link).toHaveClass("ui-button", "ui-button--primary");
await user.click(link);
expect(screen.getByTestId("location")).toHaveTextContent(
/^\/examples\/states$/,
);
});
it("keeps LinkButton `href` as a plain anchor", () => {
renderInRouter(<LinkButton href="https://example.com/docs">Docs</LinkButton>);
expect(screen.getByRole("link", { name: "Docs" })).toHaveAttribute(
"href",
"https://example.com/docs",
);
});
it("renders breadcrumb `to` items as router links", async () => {
const user = userEvent.setup();
renderInRouter(
<Breadcrumbs
items={[
{ label: "Home", to: "/" },
{ label: "Examples", to: "/examples" },
{ label: "States" },
]}
label="Location"
/>,
);
expect(screen.getByRole("link", { name: "Home" })).toHaveAttribute(
"href",
"/app",
);
await user.click(screen.getByRole("link", { name: "Examples" }));
expect(screen.getByTestId("location")).toHaveTextContent(/^\/examples$/);
expect(screen.getByText("States")).toHaveAttribute("aria-current", "page");
});
it("renders page link actions with `to` as router links", async () => {
const user = userEvent.setup();
renderInRouter(
<StandardPage
actions={[
{ kind: "link", label: "Open states", to: "/examples/states" },
{ kind: "link", label: "External", href: "https://example.com" },
]}
heading={{ title: "Page" }}
/>,
);
expect(screen.getByRole("link", { name: "External" })).toHaveAttribute(
"href",
"https://example.com",
);
const link = screen.getByRole("link", { name: "Open states" });
expect(link).toHaveAttribute("href", "/app/examples/states");
await user.click(link);
expect(screen.getByTestId("location")).toHaveTextContent(
/^\/examples\/states$/,
);
});
it("keeps the other search parameters and the basename in pagination links", async () => {
const user = userEvent.setup();
const onChange = vi.fn();
renderInRouter(
<Pagination
label="Pages"
nextLabel="Next"
onChange={onChange}
page={1}
pageCount={3}
pageLabel={(page) => `Page ${page}`}
previousLabel="Previous"
/>,
"/app/items?q=term&sort=name&page=1",
);
expect(screen.getByRole("link", { name: "Page 2" })).toHaveAttribute(
"href",
"/app/items?q=term&sort=name&page=2",
);
await user.click(screen.getByRole("link", { name: "Page 3" }));
expect(onChange).toHaveBeenCalledWith(3);
// Page changes stay with the owner: the link itself does not navigate.
expect(screen.getByTestId("location")).toHaveTextContent(
"/items?q=term&sort=name&page=1",
);
});
});
describe("pagination outside a router", () => {
it("keeps the other search parameters of the document URL", () => {
window.history.pushState({}, "", "/list?q=term");
render(
<Pagination
label="Pages"
nextLabel="Next"
onChange={() => {}}
page={1}
pageCount={2}
pageLabel={(page) => `Page ${page}`}
previousLabel="Previous"
/>,
);
expect(screen.getByRole("link", { name: "Page 2" })).toHaveAttribute(
"href",
"?q=term&page=2",
);
});
});
@@ -23,12 +23,41 @@ import {
Pagination,
Popover,
RadioGroup,
SearchField,
Switch,
Tabs,
ToastProvider,
useToast,
} from "../../src/presentation/design-system/index.ts";
describe("SearchField", () => {
it("returns focus to the input when the clear button removes itself", async () => {
const user = userEvent.setup();
function ControlledSearch() {
const [value, setValue] = useState("query");
return (
<SearchField
clearLabel="Clear search"
label="Search"
onChange={(event) => setValue(event.currentTarget.value)}
onClear={() => setValue("")}
value={value}
/>
);
}
render(<ControlledSearch />);
await user.click(screen.getByRole("button", { name: "Clear search" }));
const input = screen.getByRole("searchbox", { name: "Search" });
expect(input).toHaveValue("");
expect(input).toHaveFocus();
expect(
screen.queryByRole("button", { name: "Clear search" }),
).not.toBeInTheDocument();
});
});
describe("design-system platform interactions", () => {
it("keeps decorative icons out of the accessibility tree and names icon actions", () => {
render(
@@ -150,6 +179,40 @@ describe("design-system platform interactions", () => {
await waitFor(() => expect(trigger).toHaveFocus());
});
it("does not pull back focus that moved out of a closed drawer", async () => {
// A route change focuses the new page in the same tick the drawer closes;
// the drawer's deferred restore must not take that focus back.
const user = userEvent.setup();
function Harness() {
const [open, setOpen] = useState(false);
return (
<>
<Button onClick={() => setOpen(true)}>탐색 열기</Button>
<h1 tabIndex={-1}>새 페이지</h1>
<Drawer onClose={() => setOpen(false)} open={open} title="탐색">
<Button
onClick={() => {
setOpen(false);
queueMicrotask(() =>
screen.getByRole("heading", { name: "새 페이지" }).focus(),
);
}}
>
이동
</Button>
</Drawer>
</>
);
}
render(<Harness />);
await user.click(screen.getByRole("button", { name: "탐색 열기" }));
await user.click(screen.getByRole("button", { name: "이동" }));
await act(() => new Promise((resolve) => setTimeout(resolve, 20)));
expect(screen.getByRole("heading", { name: "새 페이지" })).toHaveFocus();
});
it("bounds the toast queue and collapses duplicate IDs", async () => {
const user = userEvent.setup();
function Harness() {
+189
View File
@@ -13,6 +13,7 @@ import {
DirtyNavigationDialog,
ErrorSummary,
Form,
FormFailureStatus,
FormField,
useAppForm,
useDirtyNavigationGuard,
@@ -34,6 +35,7 @@ function FormHarness(props: Readonly<{
| Readonly<{ ok: false; error: ReturnType<typeof createFailure> }>
>;
resetOnSuccess?: boolean;
onFailureAction?(): void;
}>) {
const form = useAppForm({
schema,
@@ -57,6 +59,14 @@ function FormHarness(props: Readonly<{
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
<FormFailureStatus
failure={form.failure}
onAction={
form.result === "retry-later"
? () => void form.submitForm()
: props.onFailureAction
}
/>
<FormField {...form.field("name")} label="Name" required />
<FormField {...form.field("note")} label="Note" />
<Button type="submit" disabled={form.pending}>
@@ -137,6 +147,96 @@ describe("local form facade", () => {
expect(document.body).not.toHaveTextContent("raw-secret-message");
});
it.each([
[
"AUTH_REQUIRED",
"reauth-required",
"계속하려면 로그인이 필요합니다.",
"로그인",
],
[
"FORBIDDEN",
"forbidden",
"이 작업을 수행할 권한이 없습니다.",
"안전한 화면으로 이동",
],
[
"RATE_LIMITED",
"retry-later",
"요청이 많습니다. 잠시 후 다시 시도해 주세요.",
"다시 시도",
],
] as const)(
"shows %s as its own save state, not an input error",
async (kind, result, copy, action) => {
const user = userEvent.setup();
const onFailureAction = vi.fn();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure(kind, "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
}),
}));
render(
<FormHarness submit={submit} onFailureAction={onFailureAction} />,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent(result);
expect(screen.getByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
expect(document.body).not.toHaveTextContent("저장하지 못했습니다.");
expect(
document.body.textContent?.includes("입력한 내용은 사라집니다"),
).toBe(kind === "AUTH_REQUIRED");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Valid");
await user.click(screen.getByRole("button", { name: action }));
if (kind === "RATE_LIMITED") {
expect(submit).toHaveBeenCalledTimes(2);
expect(onFailureAction).not.toHaveBeenCalled();
} else {
expect(onFailureAction).toHaveBeenCalledOnce();
}
},
);
// F-10 (08-01). A save that failed for a reason the user cannot fix in the
// input is a status with its own action, never an input error summary.
it.each([
["NOT_FOUND", "요청한 항목을 찾을 수 없습니다.", "안전한 화면으로 이동"],
// This product's catalog copy (the template says "요청을 처리할 수 없습니다.").
["UNKNOWN_CLIENT_FAILURE", "요청을 처리하지 못했습니다.", "지원 정보 확인"],
] as const)(
"shows an unavailable %s save as a status, not an input error",
async (kind, copy, action) => {
const user = userEvent.setup();
const onFailureAction = vi.fn();
render(
<FormHarness
submit={async () => ({
ok: false,
error: createFailure(kind, "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
}),
})}
onFailureAction={onFailureAction}
/>,
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByTestId("result")).toHaveTextContent(
"unavailable",
);
expect(screen.getByRole("alert")).toHaveTextContent(copy);
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
await user.click(screen.getByRole("button", { name: action }));
expect(onFailureAction).toHaveBeenCalledOnce();
},
);
it("keeps conflict input out of URL and storage", async () => {
const user = userEvent.setup();
localStorage.clear();
@@ -278,3 +378,92 @@ describe("dirty navigation guard", () => {
expect(await screen.findByRole("heading", { name: "Target" })).toBeVisible();
});
});
describe("submission timing", () => {
it("submits once when a second submit arrives during async validation", async () => {
const user = userEvent.setup();
let releaseValidation: () => void = () => {};
const validationGate = new Promise<void>((resolve) => {
releaseValidation = resolve;
});
const asyncSchema = schema.refine(async () => {
await validationGate;
return true;
});
const submit = vi.fn(async () => ({ ok: true as const, value: "saved" }));
function AsyncForm() {
const form = useAppForm({
schema: asyncSchema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit,
});
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit">Submit</Button>
<output data-testid="result">{form.result}</output>
</Form>
);
}
render(<AsyncForm />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
await user.click(screen.getByRole("button", { name: "Submit" }));
await user.click(screen.getByRole("button", { name: "Submit" }));
releaseValidation();
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(submit).toHaveBeenCalledOnce();
});
it("does not ask to discard changes when navigating right after a save", async () => {
const user = userEvent.setup();
function SaveThenLeave() {
const navigate = useNavigate();
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit: async () => ({ ok: true as const, value: "saved" }),
});
const guard = useDirtyNavigationGuard(form.dirty);
return (
<Form
onSubmit={(event) => {
void form.submitForm(event).then((outcome) => {
if (outcome?.ok) void navigate("/done");
});
}}
pending={form.pending}
>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit">Save</Button>
<DirtyNavigationDialog guard={guard} />
</Form>
);
}
const router = createMemoryRouter(
[
{ path: "/", element: <SaveThenLeave /> },
{ path: "/done", element: <h1>Done</h1> },
],
{ initialEntries: ["/"] },
);
render(<RouterProvider router={router} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Ready");
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("heading", { name: "Done" })).toBeVisible();
expect(
screen.queryByRole("dialog", { name: "저장하지 않은 변경이 있습니다." }),
).not.toBeInTheDocument();
});
});
+115
View File
@@ -4,6 +4,7 @@ import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
Button,
@@ -16,6 +17,15 @@ import {
useLocale,
type SupportedLocale,
} from "../../src/presentation/i18n/index.ts";
import {
ErrorSummary,
Form,
FormField,
useAppForm,
} from "../../src/presentation/forms/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
function LocaleHarness() {
const { direction, locale, message, setLocale } = useLocale();
@@ -50,7 +60,71 @@ function LocaleHarness() {
);
}
function LocaleSelect() {
const { locale, message, setLocale } = useLocale();
return (
<>
<label htmlFor="form-locale">{message("shell.locale")}</label>
<select
id="form-locale"
onChange={(event) =>
setLocale(event.currentTarget.value as SupportedLocale)
}
value={locale}
>
<option value="ko-KR">한국어</option>
<option value="en-US">English</option>
</select>
</>
);
}
function ValidatedForm() {
const form = useAppForm({
schema: z.object({ name: z.string().min(2) }).strict(),
defaultValues: { name: "" },
allowedServerFields: ["name"],
mapToCommand: (values) => values,
submit: async () => ({ ok: true as const, value: null }),
});
return (
<Form onSubmit={(event) => void form.submitForm(event)}>
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name" }}
fieldId={form.fieldId}
/>
<FormField {...form.field("name")} label="Name" />
<button type="submit">Submit</button>
</Form>
);
}
describe("locale provider runtime", () => {
// 08-10. A shown error is kept as a message key, not a translated string.
it("re-translates displayed form errors when the locale changes", async () => {
const user = userEvent.setup();
render(
<LocaleProvider>
<LocaleSelect />
<ValidatedForm />
</LocaleProvider>,
);
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(screen.getByRole("alert")).toHaveTextContent(
"입력 내용을 확인해 주세요.Name: 입력값이 너무 짧습니다.",
);
await user.selectOptions(screen.getByLabelText("언어"), "en-US");
expect(screen.getByRole("alert")).toHaveTextContent(
"Review the entered information.Name: This value is too short.",
);
expect(screen.getByRole("textbox", { name: "Name" })).toHaveAccessibleDescription(
"This value is too short.",
);
});
it("switches copy and synchronizes the document language and direction", async () => {
const user = userEvent.setup();
render(
@@ -118,3 +192,44 @@ describe("locale provider runtime", () => {
expect(screen.queryByRole("img")).not.toBeInTheDocument();
});
});
describe("persisted locale preference", () => {
it("stores the chosen locale and starts the next mount from it", async () => {
const user = userEvent.setup();
const stored = new Map<string, unknown>();
const application = createTestApplication({
preferences: {
read: (name) => ({ ok: true as const, value: stored.get(name) }),
write: (name, value) => {
stored.set(name, value);
return { ok: true as const };
},
remove: (name) => {
stored.delete(name);
return { ok: true as const };
},
},
});
const mount = () =>
render(
<ApplicationProvider application={application}>
<PreferenceProviders>
{/* Template sync (af3d8e6): upstream drives its app shell's
language selector; this product's shells have none, so the
harness selector stands in for it. */}
<LocaleHarness />
</PreferenceProviders>
</ApplicationProvider>,
);
window.history.pushState({}, "", "/missing");
const first = mount();
await user.selectOptions(await screen.findByLabelText("언어"), "en-US");
expect(stored.get("LOCALE")).toBe("en-US");
first.unmount();
mount();
expect(await screen.findByLabelText("Language")).toHaveValue("en-US");
expect(document.documentElement).toHaveAttribute("lang", "en-US");
});
});
+118
View File
@@ -0,0 +1,118 @@
// @vitest-environment jsdom
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { Pagination } from "../../src/presentation/design-system/index.ts";
import { CollectionPage } from "../../src/presentation/templates/index.ts";
function pagination(page: number, pageCount: number) {
return (
<Pagination
label="Pages"
nextLabel="Next"
onChange={() => {}}
page={page}
pageCount={pageCount}
pageLabel={(candidate) => `Page ${candidate}`}
previousLabel="Previous"
/>
);
}
function pageLinks(): string[] {
return screen
.getAllByRole("link")
.map((link) => link.textContent ?? "");
}
describe("Pagination windowing", () => {
it("links the first, last and neighbouring pages only", () => {
render(pagination(50, 5000));
expect(pageLinks()).toEqual([
"Page 1",
"Page 49",
"Page 50",
"Page 51",
"Page 5000",
]);
expect(screen.getByRole("link", { name: "Page 50" })).toHaveAttribute(
"aria-current",
"page",
);
});
it("links a single skipped page instead of eliding it", () => {
render(pagination(3, 5000));
expect(pageLinks()).toEqual([
"Page 1",
"Page 2",
"Page 3",
"Page 4",
"Page 5000",
]);
});
it("keeps every page of a short range", () => {
render(pagination(1, 3));
expect(pageLinks()).toEqual(["Page 1", "Page 2", "Page 3"]);
});
});
describe("Pagination landmarks", () => {
it("is a navigation landmark on its own", () => {
render(pagination(1, 2));
expect(screen.getByRole("navigation", { name: "Pages" })).toBeVisible();
});
it("does not nest a navigation landmark inside the collection page slot", () => {
render(
<CollectionPage heading={{ title: "Collection" }} pagination={pagination(1, 2)}>
Results
</CollectionPage>,
);
const slot = screen.getByRole("navigation", { name: "페이지 탐색" });
expect(within(slot).queryAllByRole("navigation")).toHaveLength(0);
expect(within(slot).getByRole("group", { name: "Pages" })).toBeVisible();
});
});
// 08-12. A modified click is the browser's (new tab/window), not a page change.
describe("Pagination modified clicks", () => {
function renderWith(onChange: (page: number) => void) {
render(
<Pagination
label="Pages"
nextLabel="Next"
onChange={onChange}
page={1}
pageCount={3}
pageLabel={(candidate) => `Page ${candidate}`}
previousLabel="Previous"
/>,
);
return screen.getByRole("link", { name: "Page 2" });
}
it.each([
["Ctrl", { ctrlKey: true }],
["Cmd", { metaKey: true }],
["Shift", { shiftKey: true }],
["Alt", { altKey: true }],
])("leaves a %s click to the browser", (_, modifier) => {
const onChange = vi.fn();
const link = renderWith(onChange);
const notPrevented = fireEvent.click(link, { button: 0, ...modifier });
expect(notPrevented).toBe(true);
expect(onChange).not.toHaveBeenCalled();
});
it("changes the page on a plain primary click", () => {
const onChange = vi.fn();
const link = renderWith(onChange);
expect(fireEvent.click(link, { button: 0 })).toBe(false);
expect(onChange).toHaveBeenCalledWith(2);
});
});
+26 -13
View File
@@ -4,10 +4,11 @@ import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import type { ApplicationOutputPorts } from "../../src/application/create-application.ts";
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.ts";
/**
* §3.5. The runtime kill switch, exercised through the running app.
@@ -24,14 +25,17 @@ import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub.
*
* So the ownership map is the fixture. `ROUTE_FEATURE_OWNER` is empty in this
* product because no installed feature contributes a route; one real registered
* route is attributed to a real installed feature here, and everything else —
* router, shell, components, codecs — is the product's own.
* route is attributed to a feature here, and everything else — router, shell,
* components, codecs — is the product's own.
*
* Template sync (af3d8e6). No feature is generator-installed here any more
* (the sample carries NOT_INSTALLED), so the runtime's feature port is the
* other half of the fixture: it reports the owner active or switched off.
*/
const OWNED_ROUTE_ID = "TECH_LOG_EXPLORE";
const OWNER_FEATURE_ID = "reference-feature";
const OWNER_FEATURE_ID = "fixture-feature";
const OWNED_ROUTE_PATH = "/explore";
const OWNED_ROUTE_NAV_LABEL = "탐색";
vi.mock("../../src/features/installed-feature-contracts.ts", async (original) => {
const actual = await original<
@@ -51,6 +55,19 @@ const { ApplicationProvider } = await import(
);
const { renderWithQueryProviders } = await import("../helpers/query-providers.tsx");
function ownerFeaturePort(
disabled: boolean,
): ApplicationOutputPorts["productFeatures"] {
const status = Object.freeze({
featureId: OWNER_FEATURE_ID,
state: disabled ? ("DISABLED_BY_CONFIG" as const) : ("ACTIVE" as const),
});
return Object.freeze({
getSnapshot: () => Object.freeze([status]),
isActive: (featureId: string) => featureId === OWNER_FEATURE_ID && !disabled,
});
}
function renderAt(path: string, disabled: boolean) {
window.history.pushState({}, "", path);
return render(
@@ -59,16 +76,12 @@ function renderAt(path: string, disabled: boolean) {
application={createTestApplication({
session: createAnonymousSessionAdapter(),
featureInputs: { "tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input },
...(disabled
? {
productFeatures: createProductFeaturesStub({
[OWNER_FEATURE_ID]: "DISABLED_BY_CONFIG",
}),
}
: {}),
productFeatures: ownerFeaturePort(disabled),
})}
>
<AppRouter />
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
),
);
+101
View File
@@ -10,6 +10,23 @@ import { deriveAsyncState } from "../../src/application/view-models/async-state.
import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx";
import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx";
import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
// The Explore page stands in for any route page with a programmer defect
// (template sync af3d8e6: upstream uses its states example page, which this
// product deleted).
vi.mock("../../src/features/tech-log/presentation/public/pages/explore-page.tsx", () => ({
ExplorePage: function BrokenPage(): never {
throw new Error("ordinary render defect");
},
}));
function Defect(): ReactNode {
throw new Error("raw render stack");
@@ -35,9 +52,46 @@ describe("render recovery boundaries", () => {
routeId: "APP_HOME",
buildId: "build-a",
boundaryName: "feature",
incidentId: expect.stringMatching(/^[0-9a-f]{8}$/),
});
});
// 08-07. The route failure page shows the reference the user quotes, the
// same id the render diagnostic records, and a way out besides the URL.
it("shows a route render failure's support reference and records it", async () => {
const record = vi.fn();
window.history.pushState({}, "", "/explore");
render(
renderWithQueryProviders(
<ApplicationProvider
application={createTestApplication({
diagnostics: { record },
featureInputs: {
"tech-log": createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input,
},
})}
>
<PreferenceProviders>
<AppRouter buildId="build-a" />
</PreferenceProviders>
</ApplicationProvider>,
),
);
const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
const incidentId = reference.textContent?.split(":").at(-1);
expect(record).toHaveBeenCalledWith({
level: "error",
eventId: "ui.render.failed",
context: expect.objectContaining({
route_id: "TECH_LOG_EXPLORE",
build_id: "build-a",
correlation_id: incidentId,
}),
});
expect(screen.getByRole("button", { name: "한 번 새로고침" })).toBeVisible();
});
it("keeps normalized operational failures in normal async state", () => {
const state = deriveAsyncState({
failure: createFailure("SERVER_FAILURE", "LIST", 0),
@@ -72,6 +126,39 @@ describe("render recovery boundaries", () => {
expect(shell).not.toHaveTextContent("stack");
});
it.each(["CONFIG_FETCH_FAILED", "CONFIG_TIMEOUT", "MANIFEST_FETCH_FAILED", "MANIFEST_TIMEOUT"])(
"offers a retry for the network failure %s (09-10)",
async (code) => {
const onRetry = vi.fn();
const user = userEvent.setup();
render(
<BootErrorShell
kind="BOOT_CONFIG_FAILURE"
code={code}
supportReference={`build-a:${code}`}
onRetry={onRetry}
/>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"네트워크 연결을 확인한 뒤 다시 시도해 주세요.",
);
await user.click(screen.getByRole("button", { name: "다시 시도" }));
expect(onRetry).toHaveBeenCalledTimes(1);
},
);
it("offers no retry for a failure a reload cannot fix (09-10)", () => {
render(
<BootErrorShell
kind="BOOT_CONFIG_FAILURE"
code="CONFIG_SCHEMA_INVALID"
supportReference="build-a:CONFIG_SCHEMA_INVALID"
onRetry={() => {}}
/>,
);
expect(screen.queryByRole("button")).toBeNull();
});
it("allows a boundary reset action without reloading the page", async () => {
let shouldThrow = true;
function Recoverable() {
@@ -123,4 +210,18 @@ describe("render recovery boundaries", () => {
);
expect(await screen.findByText("next route")).toBeVisible();
});
it("renders the default fallback in the current locale", () => {
render(
<LocaleProvider initialLocale="en-US">
<FeatureBoundary routeId="APP_HOME" buildId="build-a">
<Defect />
</FeatureBoundary>
</LocaleProvider>,
);
expect(screen.getByRole("alert")).toHaveTextContent(
"The page could not be displayed.",
);
expect(screen.getByRole("button", { name: "Try again" })).toBeVisible();
});
});
+78 -4
View File
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
import { render, screen, waitFor, within } from "@testing-library/react";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, expectTypeOf, it } from "vitest";
import { describe, expect, expectTypeOf, it, vi } from "vitest";
import { z } from "zod";
import {
createMemoryRouter,
@@ -13,10 +13,12 @@ import {
import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import type { ApplicationOutputPorts } from "../../src/application/create-application.ts";
import { createTechLogFeatureInstalledInput } from "../../src/features/tech-log/adapters/create-tech-log-feature-input.ts";
import { MOCK_STUDIO_INSTALL_CONTEXT } from "../helpers/studio-install-context.ts";
import { TECH_LOG_FEATURE_ID } from "../../src/features/tech-log/application/tech-log-feature-input.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
import { renderWithQueryProviders } from "../helpers/query-providers.tsx";
import {
AppRouter,
@@ -118,25 +120,47 @@ function createSignedInSessionAdapter() {
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "restored" as const,
notifyUnauthenticated: () => {},
// Template sync (af3d8e6): the external owner must name its subject.
readSubject: () => "router-test-subject",
});
}
function renderRouter(session = createAnonymousSessionAdapter()) {
function renderRouter(
session = createAnonymousSessionAdapter(),
diagnostics: ApplicationOutputPorts["diagnostics"] = { record: () => {} },
) {
const techLog = createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT);
return render(
renderWithQueryProviders(
<ApplicationProvider
application={createTestApplication({
session,
diagnostics,
featureInputs: { [TECH_LOG_FEATURE_ID]: techLog.input },
})}
>
<AppRouter />
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
),
);
}
/** A back/forward style navigation that leaves focus where the user left it. */
function navigateByHistory(url: string) {
act(() => {
window.history.pushState({}, "", url);
window.dispatchEvent(new PopStateEvent("popstate"));
});
}
function routeChangeReports(record: ReturnType<typeof vi.fn>) {
return record.mock.calls.filter(
([event]) => (event as { eventId: string }).eventId === "route.changed",
).length;
}
describe("generic application router", () => {
it("renders and canonicalizes an isolated non-installed route codec contract", async () => {
expect(ROUTE_REGISTRY).not.toHaveProperty("REVIEW_FIXTURE");
@@ -434,4 +458,54 @@ describe("generic application router", () => {
expect(screen.getByRole("navigation", { name: "Studio 주 탐색" })).toBeVisible();
expect(window.location.pathname).toBe("/studio/missing");
});
// Template sync (af3d8e6). The template pins these two router behaviours on
// its example screens; this product deleted those, so they are pinned on
// TechLog routes instead.
it("ignores unknown query parameters on a route without search and keeps the URL", async () => {
// D-16: `?utm_source=` or an OAuth callback parameter is not an invalid
// address. The `none` codec drops it from the parsed input only.
window.history.pushState({}, "", "/projects?utm_source=mail#top");
const { container } = renderRouter();
expect(
await screen.findByRole(
"heading",
{ name: "프로젝트", level: 1 },
{ timeout: 5000 },
),
).toBeVisible();
expect(container.querySelector('[data-surface="invalid-route"]')).toBeNull();
expect(`${window.location.pathname}${window.location.search}`).toBe(
"/projects?utm_source=mail",
);
});
it("runs the route lifecycle on the authentication-required surface", async () => {
// Title and route telemetry belong to every answer a route gives, not only
// to the page it renders once allowed.
const record = vi.fn();
window.history.pushState({}, "", "/");
const { container } = renderRouter(createAnonymousSessionAdapter(), {
record,
});
await screen.findByRole("heading", { name: "TechLog", level: 1 });
navigateByHistory("/studio");
await waitFor(
() =>
expect(
container.querySelector('[data-surface="authentication-required"]'),
).not.toBeNull(),
{ timeout: 5000 },
);
expect(routeChangeReports(record)).toBeGreaterThan(1);
expect(record).toHaveBeenCalledWith(
expect.objectContaining({
eventId: "route.changed",
context: expect.objectContaining({ route_id: "TECH_LOG_STUDIO_HOME" }),
}),
);
});
});
+62 -2
View File
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
@@ -22,7 +23,7 @@ const runtimeConfig = {
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.1.0",
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
@@ -95,4 +96,63 @@ describe("production runtime application tree", () => {
expect(fetcher).toHaveBeenCalledTimes(2);
expect(composition).not.toHaveProperty("ports");
});
it("keeps locale state across a session scope fence and disposes routers", async () => {
const user = userEvent.setup();
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
return Response.json(
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
);
});
window.localStorage.clear();
const composition = await createRuntimeComposition({
fetcher,
host: { localStorage: window.localStorage },
});
// Spies call through; each router's history listens to popstate.
const add = vi.spyOn(window, "addEventListener");
const remove = vi.spyOn(window, "removeEventListener");
const popstateCalls = (spy: typeof add | typeof remove) =>
spy.mock.calls.filter(([type]) => type === "popstate").length;
try {
// Template sync (af3d8e6). Upstream picks the language in its app
// shell and signs in from the shell's session button. This product's
// shells have no language selector, so the preference is stored first,
// and the demo sign-in is the Studio sign-in gate's button.
composition.application.preferences.setLocale("en-US");
window.history.pushState({}, "", "/studio");
const app = render(<RuntimeApplication composition={composition} />);
const signIn = await screen.findByRole("button", {
name: "Start sign-in",
});
expect(document.documentElement).toHaveAttribute("lang", "en-US");
// Only the live provider holds the choice from here on; a remount would
// start over from empty storage.
window.localStorage.clear();
// Demo sign-in changes the session: the scope goes FENCED, then READY.
await user.click(signIn);
await waitFor(() =>
expect(
document.querySelector('[data-surface="authentication-required"]'),
).toBeNull(),
);
expect(document.documentElement).toHaveAttribute("lang", "en-US");
app.unmount();
expect(popstateCalls(add)).toBeGreaterThan(0);
expect(popstateCalls(remove)).toBe(popstateCalls(add));
} finally {
add.mockRestore();
remove.mockRestore();
await composition.dispose();
}
});
});
@@ -0,0 +1,169 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
/**
* 06-05. The optional host reports a Service Worker that did not start, but
* only if the composition hands it the application's telemetry port. This
* test runs the real composition with an ACTIVE selection and a first install
* that fails, and records what reaches the telemetry adapter.
*/
const emitted = vi.hoisted(
() => [] as Array<readonly [string, Record<string, unknown>]>,
);
vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-runtime-capabilities.ts")>();
return {
INSTALLED_RUNTIME_CAPABILITIES: Object.freeze({
...original.INSTALLED_RUNTIME_CAPABILITIES,
serviceWorker: Object.freeze({
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: Object.freeze(["PWA_STATIC_ASSETS"]),
}),
}),
};
});
vi.mock("../../src/adapters/telemetry/index.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/adapters/telemetry/index.ts")>();
return {
...original,
createTelemetryAdapter: (
options: Parameters<typeof original.createTelemetryAdapter>[0],
) => {
const adapter = original.createTelemetryAdapter(options);
return Object.freeze({
...adapter,
emit(eventName: string, attributes: Record<string, unknown>) {
emitted.push([eventName, attributes]);
adapter.emit(eventName as never, attributes);
},
});
},
};
});
const origin = "http://localhost";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-not-found": "assets/not-found.js",
},
};
async function fetcher(input: RequestInfo | URL): Promise<Response> {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
return Response.json(
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
);
}
/** A first install whose worker turns `redundant` (install event rejected). */
function failingInstallContainer(): ServiceWorkerContainer {
const register = vi.fn(
async (scriptURL: string | URL, options?: RegistrationOptions) => {
const installing = {
scriptURL: new URL(scriptURL, origin).href,
state: "installing",
addEventListener(type: string, listener: () => void) {
if (type !== "statechange") return;
queueMicrotask(() => {
installing.state = "redundant";
listener();
});
},
removeEventListener() {},
};
return {
scope: new URL(options?.scope ?? "/", origin).href,
installing,
waiting: null,
active: null,
addEventListener() {},
removeEventListener() {},
update: vi.fn(async () => {}),
} as unknown as ServiceWorkerRegistration;
},
);
return {
controller: null,
register,
getRegistration: vi.fn(async () => undefined),
getRegistrations: vi.fn(async () => []),
addEventListener() {},
removeEventListener() {},
} as unknown as ServiceWorkerContainer;
}
describe("06-05 runtime composition reports a Service Worker install failure", () => {
afterEach(() => {
emitted.length = 0;
});
it("emits exactly one service-worker.start.failed through the application telemetry port", async () => {
const container = failingInstallContainer();
const composition = await createRuntimeComposition({
fetcher,
host: {
location: { origin },
navigator: { serviceWorker: container },
},
});
try {
await composition.optional.startAfterMount();
expect(container.register).toHaveBeenCalledTimes(1);
expect(composition.optional.health().serviceWorker).toBe("DEGRADED");
expect(
emitted.filter(([eventName]) => eventName.startsWith("service-worker.")),
).toEqual([
[
"service-worker.start.failed",
{ error_kind: "INSTALL_FAILED", build_id: "local-build" },
],
]);
} finally {
await composition.dispose();
}
});
});
+63
View File
@@ -0,0 +1,63 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { Button, Tooltip } from "../../src/presentation/design-system/index.ts";
describe("Tooltip", () => {
it("describes the focusable trigger itself", async () => {
const user = userEvent.setup();
render(
<>
<p id="existing-hint">Existing hint</p>
<Tooltip content="Optional detail">
<Button aria-describedby="existing-hint">Help</Button>
</Tooltip>
</>,
);
await user.tab();
const trigger = screen.getByRole("button", { name: "Help" });
expect(trigger).toHaveFocus();
expect(trigger).toHaveAccessibleDescription("Existing hint Optional detail");
});
it("closes with Escape and opens again on the next focus", async () => {
const user = userEvent.setup();
render(
<>
<Tooltip content="Optional detail">
<Button>Help</Button>
</Tooltip>
<Button>Elsewhere</Button>
</>,
);
await user.tab();
const tooltip = screen.getByRole("tooltip");
expect(tooltip).toBeVisible();
await user.keyboard("{Escape}");
expect(tooltip).not.toBeVisible();
expect(screen.getByRole("button", { name: "Help" })).toHaveFocus();
await user.tab();
await user.tab({ shift: true });
expect(screen.getByRole("tooltip")).toBeVisible();
});
it("closes a hovered tooltip with Escape", async () => {
const user = userEvent.setup();
render(
<Tooltip content="Optional detail">
<Button>Help</Button>
</Tooltip>,
);
await user.hover(screen.getByRole("button", { name: "Help" }));
await user.keyboard("{Escape}");
expect(screen.getByRole("tooltip", { hidden: true })).not.toBeVisible();
});
});
@@ -1,97 +0,0 @@
import type {
BrowserDataResult,
IndexedDbRepositoryPort,
} from "../../../../src/application/ports/browser-file-storage/index.ts";
export type LocalDraft = Readonly<{
draftId: string;
title: string;
body: string;
}>;
export type SaveLocalDraftCommand = Readonly<{
draft: LocalDraft;
expectedRevision: number | null;
idempotencyKey: string;
}>;
export type RemoveLocalDraftCommand = Readonly<{
draftId: string;
expectedRevision: number;
idempotencyKey: string;
}>;
export type LocalDraftRecord = Readonly<{
draft: LocalDraft;
revision: number;
}>;
export interface LocalDraftStore {
save(
command: SaveLocalDraftCommand,
signal?: AbortSignal,
): Promise<BrowserDataResult<Readonly<{ revision: number }>>>;
find(
draftId: string,
signal?: AbortSignal,
): Promise<BrowserDataResult<LocalDraftRecord | null>>;
remove(
command: RemoveLocalDraftCommand,
signal?: AbortSignal,
): Promise<BrowserDataResult<void>>;
}
/**
* Feature-owned binding over the technology-neutral IndexedDB application port.
*
* The feature knows its domain type and optimistic concurrency inputs. It does
* not know database names, stores, transactions, native IDB objects, codecs,
* migrations, quota handling or connection lifecycle.
*/
export function createLocalDraftStore(
repository: IndexedDbRepositoryPort<LocalDraft, never>,
): LocalDraftStore {
const store: LocalDraftStore = {
async save(command, signal) {
const result = await repository.compareAndSwap({
key: command.draft.draftId,
value: command.draft,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
signal,
});
if (!result.ok) return result;
return Object.freeze({
ok: true as const,
value: Object.freeze({ revision: result.value.revision }),
});
},
async find(draftId, signal) {
const result = await repository.read(draftId, signal);
if (!result.ok) return result;
return Object.freeze({
ok: true as const,
value:
result.value === null
? null
: Object.freeze({
draft: result.value.value,
revision: result.value.revision,
}),
});
},
async remove(command, signal) {
const result = await repository.remove({
key: command.draftId,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
signal,
});
if (!result.ok) return result;
return Object.freeze({ ok: true as const, value: undefined });
},
};
return Object.freeze(store);
}
@@ -1,4 +1,5 @@
import { readFile } from "node:fs/promises";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
@@ -6,10 +7,25 @@ import type {
BrowserDataResult,
IndexedDbRepositoryPort,
} from "../../../src/application/ports/browser-file-storage/index.ts";
import {
createLocalDraftStore,
type LocalDraft,
} from "./fixtures/local-draft-feature.ts";
import { createLocalDraftStore } from "../../../src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts";
import type { LocalDraft } from "../../../src/features/local-draft-feature/domain/local-draft.ts";
// 09-12. This probe used to exercise a copy of the feature under fixtures/,
// which had drifted from src (it returned raw storage failures). It now reads
// and runs the one implementation.
const FEATURE_ROOT = "src/features/local-draft-feature";
async function featureSources(directory: string): Promise<string[]> {
const entries = await readdir(directory, { withFileTypes: true });
const nested = await Promise.all(
entries.map((entry) => {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) return featureSources(target);
return /\.tsx?$/u.test(entry.name) ? [target] : [];
}),
);
return nested.flat();
}
function success<Value>(value: Value): BrowserDataResult<Value> {
return Object.freeze({ ok: true as const, value });
@@ -133,29 +149,26 @@ describe("IndexedDB local-draft consumer experience", () => {
});
});
it("keeps native IndexedDB and runtime internals out of feature-owned code", async () => {
const source = await readFile(
new URL("./fixtures/local-draft-feature.ts", import.meta.url),
"utf8",
);
const importLines = source
.split("\n")
.filter((line) => line.startsWith("import "));
expect(importLines).toHaveLength(1);
expect(source).toContain(
"src/application/ports/browser-file-storage/index.ts",
);
for (const forbidden of [
"src/adapters/storage/indexeddb",
"globalThis.indexedDB",
"IDBFactory",
"IDBDatabase",
"IDBTransaction",
"IDBObjectStore",
]) {
expect(source).not.toContain(forbidden);
it("keeps native IndexedDB and the storage runtime out of feature-owned code", async () => {
const files = await featureSources(FEATURE_ROOT);
expect(files.length).toBeGreaterThan(0);
for (const file of files) {
const source = await readFile(file, "utf8");
for (const forbidden of [
"adapters/storage/indexeddb",
"application/ports/browser-file-storage",
"globalThis.indexedDB",
"IDBFactory",
"IDBDatabase",
"IDBTransaction",
"IDBObjectStore",
]) {
const importsOrUses = source
.split("\n")
.filter((line) => !/^\s*(?:\*|\/\/)/u.test(line))
.some((line) => line.includes(forbidden));
expect(importsOrUses, `${file} uses ${forbidden}`).toBe(false);
}
}
});
});
@@ -119,4 +119,66 @@ describe("feature adapter composition", () => {
value: { draft, revision: 1 },
});
});
const http = Object.freeze({
execute: async () => {
throw new Error("HTTP should not execute during composition");
},
}) as unknown as InstalledHttpOperationExecutor;
it("rejects two contributions for the same feature id (Q-6.9-6)", () => {
// A feature copied from another without renaming its id.
const copied = defineFeatureAdapterContribution({
...TEST_HTTP_FEATURE_ADAPTER_CONTRIBUTION,
});
expect(() =>
composeFeatureAdapterInputs(
Object.freeze([TEST_HTTP_FEATURE_ADAPTER_CONTRIBUTION, copied] as const),
Object.freeze(["test-http-feature"]),
Object.freeze({ http }),
),
).toThrow(/duplicate.*test-http-feature/u);
});
it("names the feature and the capability the host did not provide (09-05)", () => {
const withoutIndexedDb = Object.freeze({ http }) as unknown as Parameters<
typeof composeFeatureAdapterInputs<
readonly [typeof LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION]
>
>[2];
expect(() =>
composeFeatureAdapterInputs(
Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const),
Object.freeze(["local-draft"]),
withoutIndexedDb,
),
).toThrow("feature local-draft needs indexedDb, which the host did not provide");
// A feature switched off gets no input, so its needs are not asked for.
expect(
composeFeatureAdapterInputs(
Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const),
Object.freeze([]),
withoutIndexedDb,
),
).toEqual({});
});
it("rejects an input installed under another feature's id (Q-6.9-6)", () => {
const wrongId = defineFeatureAdapterContribution({
featureId: "test-http-feature",
needs: ["http"] as const,
createInput: () =>
Object.freeze({
featureId: "local-draft",
input: {},
}) as never,
});
expect(() =>
composeFeatureAdapterInputs(
Object.freeze([wrongId] as const),
Object.freeze(["test-http-feature"]),
Object.freeze({ http }),
),
).toThrow(/test-http-feature.*local-draft/u);
});
});
@@ -18,7 +18,6 @@ import type {
type ResourceInput = Readonly<{ resourceId: string }>;
type ResourceWire = Readonly<{ id: string; title: string }>;
type ResourceProblem = Readonly<{ code?: string }>;
type Resource = Readonly<{ id: string; title: string }>;
function validator<T>(schemaId: string): RuntimeValidator<T> {
return Object.freeze({
@@ -189,6 +188,87 @@ describe("feature HTTP binding", () => {
expect(result.error.code).toBe("MAPPING_INVARIANT_REJECTED");
});
it.each([
"FINAL_REQUEST_INVARIANT_FAILED",
"MISSING_IDEMPOTENCY_KEY",
"UNEXPECTED_IDEMPOTENCY_KEY",
] as const)(
"does not report the request-side violation %s as a server envelope mismatch",
async (violationKind) => {
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
Object.freeze({
kind: "CONTRACT_VIOLATION" as const,
violation: Object.freeze({
kind: violationKind,
operation: "REQUEST" as const,
}),
effect: "NOT_APPLICABLE" as const,
}),
);
const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS);
const result = await binding.execute("LOAD_RESOURCE", {
resourceId: "resource-1",
});
expect(result).toMatchObject({
ok: false,
error: { kind: "VALIDATION_REJECTED", code: violationKind },
});
},
);
it.each([
[
"mapSuccess",
Object.freeze({
kind: "SUCCESS" as const,
value: Object.freeze({ id: "resource-1", title: "Reference" }),
metadata: Object.freeze({ status: 201 }),
effect: "APPLIED_CONFIRMED" as const,
}),
],
[
"mapProblem",
Object.freeze({
kind: "PROBLEM" as const,
problem: Object.freeze({ code: "RESOURCE_NAME_EXISTS" }),
metadata: Object.freeze({ status: 409 }),
effect: "APPLIED_CONFIRMED" as const,
}),
],
])(
"returns a mapping failure with the server effect when %s throws",
async (_mapper, outcome) => {
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(outcome);
const binding = createFeatureHttpBinding(scripted.executor, {
LOAD_RESOURCE: defineFeatureHttpOperation({
contract: LOAD_RESOURCE_CONTRACT,
routeId: "RESOURCE_DETAIL",
mapSuccess(): never {
throw new TypeError("mapper defect");
},
mapProblem(): never {
throw new TypeError("mapper defect");
},
}),
} as const);
const result = await binding.execute("LOAD_RESOURCE", {
resourceId: "resource-1",
});
expect(result).toMatchObject({
ok: false,
error: {
kind: "MAPPING_CONTRACT_VIOLATION",
code: "MAPPING_CONTRACT_VIOLATION",
effect: "APPLIED_CONFIRMED",
},
});
},
);
it("lets the feature interpret a typed business problem", async () => {
const scripted = scriptedExecutor<ResourceWire, ResourceProblem>(
Object.freeze({
+35
View File
@@ -39,3 +39,38 @@ test("provides an escape-dismissible mobile navigation", async ({ page }) => {
await expect(page.getByRole("navigation", { name: "모바일 주요 탐색" })).toBeHidden();
await expect(menu).toBeFocused();
});
// R3-6. A drawer link closes the modal drawer and changes the route in the
// same click. The drawer's deferred focus restore must not win over the new
// page's heading focus; Escape (no navigation) still returns to the menu.
test("moves focus to the new page after a mobile drawer link, not back to the menu", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/");
const menu = page.getByRole("button", { name: "메뉴", exact: true });
const navigation = page.getByRole("navigation", { name: "주요 탐색" });
await menu.click();
await navigation.getByRole("link", { name: "화면 상태" }).click();
await expect(page).toHaveURL(/\/examples\/states$/);
await expect(menu).toHaveAttribute("aria-expanded", "false");
const heading = page.getByRole("heading", { level: 1, name: "화면 상태" });
await expect(heading).toBeFocused();
// Give any late restore (dialog close timer, lazy route commit) time to run.
await page.waitForTimeout(300);
expect(
await page.evaluate(() => {
const active = document.activeElement;
return active?.matches("h1, main") === true;
}),
).toBe(true);
await expect(menu).not.toBeFocused();
await menu.click();
await expect(navigation).toBeVisible();
await page.keyboard.press("Escape");
await expect(navigation).toBeHidden();
await expect(menu).toBeFocused();
});
+59
View File
@@ -0,0 +1,59 @@
import path from "node:path";
import { expect, test } from "../support/browser/strict-browser-test.ts";
import {
editOnce,
prepareFixtureBuilds,
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
* 09-03 (F-2). A production build whose application graph throws while its
* modules evaluate: the installed features are composed twice, so
* `installed-feature-messages.ts` meets every message key a second time and
* throws at module top level. The static "loading" shell used to stay up
* forever; the boot error shell has to replace it.
*/
let builds: FixtureBuilds<"broken"> | undefined;
test.beforeAll(async () => {
test.setTimeout(300_000);
builds = await prepareFixtureBuilds("boot-module-failure", [
{
name: "broken",
edit: (root) =>
editOnce(
path.join(root, "src/features/installed-feature-messages.ts"),
"composeInstalledMessageCatalogs(\n INSTALLED_PRODUCT_FEATURE_MODULES,\n)",
"composeInstalledMessageCatalogs([\n ...INSTALLED_PRODUCT_FEATURE_MODULES,\n ...INSTALLED_PRODUCT_FEATURE_MODULES,\n])",
),
},
]);
});
test.afterAll(async () => {
await removeFixtureBuilds(builds);
});
test("shows the boot error shell when a module throws while it evaluates", async ({
page,
}) => {
if (!builds) throw new Error("Fixture build was not prepared.");
const broken = builds.dist.broken;
const server = await startBuildServer({ a: broken, b: broken });
try {
await page.goto(`${server.origin}/`);
const shell = page.getByRole("alert");
await expect(shell).toContainText("애플리케이션을 시작할 수 없습니다.");
await expect(shell).toContainText("BOOT_UNEXPECTED_FAILURE");
await expect(shell).toContainText("TypeError");
await expect(shell).toContainText("boot-module-failure-broken");
await expect(page.locator("[data-boot-shell]")).toHaveCount(0);
} finally {
await server.close();
}
});
+129
View File
@@ -0,0 +1,129 @@
import { appendFile, readFile } from "node:fs/promises";
import path from "node:path";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import { expect, test } from "../support/browser/strict-browser-test.ts";
import {
prepareFixtureBuilds,
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
* 11-05. A tab opened on build A, in the default configuration (no Service
* Worker), after build B is deployed. B changes two lazy route pages, so their
* A chunks no longer exist on the server. The first missing chunk reloads the
* tab once, into B. A second missing chunk (the server alternates back to A,
* as mismatched replicas do) must not reload again: the tab shows the
* recovery failure instead.
*/
// Template sync (af3d8e6). Upstream uses two of its example pages, which this
// product deleted; two TechLog primary-navigation pages play the same part.
const PLATFORM = ROUTE_REGISTRY.TECH_LOG_EXPLORE;
const UI = ROUTE_REGISTRY.TECH_LOG_TOPICS;
const PAGES = [
"src/features/tech-log/presentation/public/pages/explore-page.tsx",
"src/features/tech-log/presentation/public/pages/topics-page.tsx",
] as const;
let builds: FixtureBuilds<"a" | "b"> | undefined;
test.beforeAll(async () => {
test.setTimeout(300_000);
builds = await prepareFixtureBuilds("chunk-recovery", [
{ name: "a" },
{
name: "b",
edit: async (root) => {
for (const page of PAGES) {
await appendFile(
path.join(root, page),
'\n(globalThis as Record<string, unknown>).__caFixtureBuild = "b";\n',
);
}
},
},
]);
});
test.afterAll(async () => {
await removeFixtureBuilds(builds);
});
async function routeChunk(dist: string, chunkId: string): Promise<string> {
const manifest = JSON.parse(
await readFile(path.join(dist, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> };
return `/${manifest.routeChunks[chunkId]}`;
}
// Each missing page chunk fails its request and the dynamic import. Chromium
// may also log the 404 itself (without its URL), Firefox logs the error
// object React caught, and WebKit logs its own import error without the URL.
// Nothing else is allowed.
const MISSING_PAGE = String.raw`/assets/route-tech-log-(?:explore|topics)-[\w-]+\.js`;
test.use({
allowedBrowserFailure: new RegExp(
[
String.raw`^requestfailed:GET:${MISSING_PAGE}:`,
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`,
String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`,
String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`,
String.raw`^console:error:JSHandle@object$`,
String.raw`^console:error:TypeError: Importing a module script failed\.$`,
].join("|"),
"u",
),
});
test("an old tab reloads once into the new build, then stops reloading", async ({
page,
}) => {
if (!builds) throw new Error("Fixture builds were not prepared.");
const aPlatform = await routeChunk(builds.dist.a, PLATFORM.chunkId);
const bPlatform = await routeChunk(builds.dist.b, PLATFORM.chunkId);
const bUi = await routeChunk(builds.dist.b, UI.chunkId);
expect(bPlatform).not.toBe(aPlatform);
expect(bUi).not.toBe(await routeChunk(builds.dist.a, UI.chunkId));
const server = await startBuildServer(builds.dist);
try {
await page.goto(`${server.origin}/`);
await expect(
page.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true }),
).toBeVisible();
let loads = 0;
page.on("load", () => {
loads += 1;
});
// Build B is deployed while the A tab stays open.
server.serve("b");
await page
.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true })
.click();
await expect(page.getByRole("heading", { name: PLATFORM.title })).toBeVisible();
expect(loads).toBe(1);
const served = server.served.map((entry) => entry.path);
expect(served).not.toContain(aPlatform);
expect(served).toContain(bPlatform);
await expect
.poll(() => page.evaluate(() => (globalThis as Record<string, unknown>).__caFixtureBuild))
.toBe("b");
// The replicas alternate: the B tab now meets A, which lacks B's chunk.
server.serve("a");
await page.getByRole("link", { name: UI.navigationLabel!, exact: true }).click();
await expect(page.getByRole("alert")).toContainText(
"화면 자산을 복구하지 못했습니다.",
);
expect(loads).toBe(1);
expect(page.url()).toBe(`${server.origin}${UI.path}`);
} finally {
await server.close();
}
});
+70
View File
@@ -0,0 +1,70 @@
import { readFileSync } from "node:fs";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
// 13-08. The Content-Security-Policy in config/hosting/security-headers.json was
// declared but never applied in a browser: `vite preview` sends no security
// headers. This smoke serves the build with the production headers attached
// and fails on any securitypolicyviolation event or console error.
const { headers: declaredHeaders } = JSON.parse(
readFileSync("config/hosting/security-headers.json", "utf8"),
) as { headers: Record<string, string> };
// The preview server is plain HTTP on loopback. `upgrade-insecure-requests` is a
// no-op for an HTTPS origin, but WebKit applies it to loopback and rewrites
// every same-origin request to https, which this server cannot answer. Every
// other directive is served exactly as declared.
const securityHeaders = {
...declaredHeaders,
"Content-Security-Policy": declaredHeaders["Content-Security-Policy"]!
.split(";")
.map((directive) => directive.trim())
.filter((directive) => directive !== "upgrade-insecure-requests")
.join("; "),
};
// F-7. No zod setup here: the app sets `jitless` in src/contracts/zod.ts before
// any schema is built, so zod's `Function("")` probe never reaches the policy.
test.beforeEach(async ({ page, baseURL }) => {
const origin = new URL(baseURL ?? "http://127.0.0.1:4173").origin;
await page.route(
(url) => url.origin === origin,
async (route) => {
const response = await route.fetch();
await route.fulfill({
response,
headers: { ...response.headers(), ...securityHeaders },
});
},
);
await page.addInitScript(() => {
const violations: string[] = [];
Object.defineProperty(window, "__cspViolations", { value: violations });
document.addEventListener("securitypolicyviolation", (event) => {
violations.push(`${event.effectiveDirective} ${event.blockedURI}`);
});
});
});
async function cspViolations(page: Page): Promise<string[]> {
return page.evaluate(() => (window as unknown as { __cspViolations: string[] }).__cspViolations);
}
test("boots and changes route under the production security headers", async ({ page }) => {
const response = await page.goto("/");
expect(response?.headers()["content-security-policy"]).toBe(
securityHeaders["Content-Security-Policy"],
);
await expect(page.getByRole("heading", { level: 1 })).toHaveText(
"Clean Architecture Frontend",
);
await page
.getByRole("navigation", { name: "주요 탐색" })
.getByRole("link", { name: "화면 상태" })
.click();
await expect(
page.getByRole("heading", { level: 1, name: "화면 상태" }),
).toBeFocused();
expect(await cspViolations(page)).toEqual([]);
});
+39
View File
@@ -0,0 +1,39 @@
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
const scrollY = (page: Page) => page.evaluate(() => Math.round(window.scrollY));
// 08-08. Back restores where the user was; a new route starts at the top.
test("restores the scroll position when navigating back", async ({ page }) => {
const heading = page.getByRole("heading", { level: 1 });
await page.goto("/examples/ui");
await expect(heading).toHaveText("UI 구성요소");
await page.evaluate(() => window.scrollTo(0, 900));
await expect.poll(() => scrollY(page)).toBe(900);
await page
.getByRole("navigation", { name: "주요 탐색" })
.getByRole("link", { name: "화면 상태" })
.click();
await expect(heading).toHaveText("화면 상태");
await expect.poll(() => scrollY(page)).toBe(0);
await page.goBack();
await expect(heading).toHaveText("UI 구성요소");
await expect.poll(() => scrollY(page)).toBe(900);
});
test("opens a hash link at its target below the sticky header", async ({
page,
}) => {
await page.goto("/examples/ui#tokens-title");
const target = page.locator("#tokens-title");
await expect(target).toBeInViewport();
const top = await target.evaluate((element) =>
Math.round(element.getBoundingClientRect().top),
);
const headerBottom = await page
.locator(".app-shell__header")
.evaluate((element) => Math.round(element.getBoundingClientRect().bottom));
expect(top).toBeGreaterThanOrEqual(headerBottom);
expect(await scrollY(page)).toBeGreaterThan(0);
});
+151
View File
@@ -0,0 +1,151 @@
import path from "node:path";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import {
ACTIVE_SELECTION,
prepareServiceWorkerBuilds,
removeServiceWorkerBuilds,
replaceOnce,
startBuildServer,
type ServiceWorkerBuilds,
} from "./support/service-worker-builds.ts";
/**
* 06-03 (D-5). The emergency exit for a worker that stops the page from
* booting. Page code cannot help then: the page never runs. Build A is the
* ACTIVE worker with its fetch handler broken (every intercepted request is a
* network error, the entry script included). Build B is a
* `REMOVE_REGISTRATION` release, which ships the self-unregistering
* `service-worker.js` (`scripts/lib/self-unregistering-service-worker.ts`).
* The browser's update check alone replaces A with it, and the next load boots
* B from the network.
*/
type Probe = typeof globalThis & {
__caServiceWorkerTest?: { events: string[] };
};
let builds: ServiceWorkerBuilds | undefined;
test.beforeAll(async () => {
test.setTimeout(180_000);
builds = await prepareServiceWorkerBuilds({
async beforeBuild(name, root) {
if (name === "a") {
await replaceOnce(
path.join(root, "src/adapters/service-worker/service-worker-entry.ts"),
"runtime.onFetch(described).then((cached) => cached ?? fetch(request)),",
"Promise.resolve(Response.error()),",
);
return;
}
await replaceOnce(
path.join(root, "src/features/installed-runtime-capabilities.ts"),
ACTIVE_SELECTION,
`const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
mode: "REMOVE_REGISTRATION",
scriptPath: "service-worker.js",
};`,
);
},
});
});
test.afterAll(async () => {
await removeServiceWorkerBuilds(builds);
});
async function startOutcome(page: Page): Promise<unknown> {
await page.waitForFunction(
() =>
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
event.startsWith("start:"),
) === true,
undefined,
{ timeout: 60_000 },
);
const event = await page.evaluate(() =>
(globalThis as Probe).__caServiceWorkerTest!.events.find((entry) =>
entry.startsWith("start:"),
)!,
);
return JSON.parse(event.slice("start:".length));
}
test("a REMOVE_REGISTRATION release unregisters a worker that blocks boot", async ({
browser,
browserName,
}) => {
// Same quarantine as service-worker-update.spec.ts.
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
test.skip(
browserName === "firefox",
"Playwright Firefox pages are never controlled by a service worker.",
);
if (!builds) throw new Error("Service Worker builds were not prepared.");
const server = await startBuildServer(builds.dist);
// The broken phase fails requests on purpose, so this test drives its own
// context instead of the strict `page` fixture and checks the recovered
// load for browser errors itself.
const context = await browser.newContext();
try {
const page = await context.newPage();
await page.goto(`${server.origin}/`);
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
await page.evaluate(async () => {
await navigator.serviceWorker.ready;
});
// Worker A controls the next load and fails the entry script.
await page.goto(`${server.origin}/`);
const blocked = await page.evaluate(async () => {
const entry = document.querySelector<HTMLScriptElement>(
'script[type="module"][src]',
);
if (!entry) return "no entry script";
try {
await fetch(entry.src);
return "loaded";
} catch {
return navigator.serviceWorker.controller ? "blocked" : "uncontrolled";
}
});
expect(blocked).toBe("blocked");
// Release B. Only the browser's update check runs; no code of B does.
server.serve("b");
await page.evaluate(async () => {
await (await navigator.serviceWorker.getRegistration())?.update();
});
await expect
.poll(
() =>
page.evaluate(
async () =>
(await navigator.serviceWorker.getRegistration()) === undefined,
),
{ timeout: 30_000 },
)
.toBe(true);
const failures: string[] = [];
page.on("console", (message) => {
if (["error", "warning"].includes(message.type())) {
failures.push(`console:${message.type()}:${message.text()}`);
}
});
page.on("pageerror", (error) => failures.push(`pageerror:${error.name}`));
page.on("requestfailed", (request) =>
failures.push(`requestfailed:${new URL(request.url()).pathname}`),
);
await page.goto(`${server.origin}/`);
expect(await startOutcome(page)).toEqual({ kind: "DISABLED" });
expect(
await page.evaluate(() => navigator.serviceWorker.controller === null),
).toBe(true);
expect(failures).toEqual([]);
} finally {
await context.close();
await server.close();
}
});
+271
View File
@@ -0,0 +1,271 @@
import { appendFile, readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import {
prepareServiceWorkerBuilds,
removeServiceWorkerBuilds,
startBuildServer,
type ServiceWorkerBuilds,
} from "./support/service-worker-builds.ts";
/**
* R3-6. Real-browser Service Worker checks, against real production builds.
*
* 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`
* (`{ 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
* copy of the repo, builds it twice (`VITE_BUILD_ID` sw-e2e-a / sw-e2e-b),
* and serves either dist from its own port per test. The copy also records
* the worker host's `onUpdateWaiting` / `onReloadRequired` callbacks, which
* the app itself does not subscribe to yet.
*
* The preview server of this suite is not used; each test uses absolute URLs.
*/
type Probe = typeof globalThis & {
__caServiceWorkerTest?: {
host: { requestActivation(): Promise<unknown> };
events: string[];
};
};
let builds: ServiceWorkerBuilds | undefined;
// B changes one route chunk on purpose. Route chunks used to differ only
// because they embedded the build ID; since 09-02 they do not, so two builds
// of the same source emit the same route chunks. A dynamically imported
// module keeps all its exports, so the extra export survives the bundler.
const CHANGED_ROUTE_SOURCE =
"src/presentation/pages/not-found-page.tsx";
test.beforeAll(async () => {
test.setTimeout(180_000);
builds = await prepareServiceWorkerBuilds({
beforeBuild: async (name, root) => {
if (name !== "b") return;
await appendFile(
path.join(root, CHANGED_ROUTE_SOURCE),
'\nexport const serviceWorkerE2eBuild = "b";\n',
);
},
});
});
test.afterAll(async () => {
await removeServiceWorkerBuilds(builds);
});
function requireBuilds(): ServiceWorkerBuilds {
if (!builds) throw new Error("Service Worker builds were not prepared.");
return builds;
}
async function waitForEvent(page: Page, prefix: string): Promise<string> {
await page.waitForFunction(
(expected) =>
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
event.startsWith(expected),
) === true,
prefix,
{ timeout: 60_000 },
);
const events = await page.evaluate(() => [
...((globalThis as Probe).__caServiceWorkerTest?.events ?? []),
]);
return events.find((event) => event.startsWith(prefix))!;
}
async function startOutcome(page: Page): Promise<unknown> {
return JSON.parse((await waitForEvent(page, "start:")).slice("start:".length));
}
async function hashedAssets(dist: string): Promise<string[]> {
return (await readdir(path.join(dist, "assets")))
.map((file) => `/assets/${file}`)
.sort();
}
const headerCases = [
{
name: "Content-Type: application/javascript",
headers: { javascriptContentType: "application/javascript", gzip: false },
},
{
name: "Content-Encoding: gzip with the compressed Content-Length",
headers: { javascriptContentType: "text/javascript", gzip: true },
},
] as const;
for (const { name, headers } of headerCases) {
test(`installs the static asset set served with ${name}`, async ({ page }) => {
const { dist } = requireBuilds();
const server = await startBuildServer(dist, headers);
try {
await page.goto(`${server.origin}/`);
// A failed install (CONTENT_TYPE_INVALID, BYTES_MISMATCH, ...) ends as
// FAILED/INSTALL_FAILED; a first install that worked asks for a reload.
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
const cached = await page.evaluate(async () => {
const names = (await caches.keys()).filter((cacheName) =>
cacheName.startsWith("ca-static-v1-"),
);
const cache = await caches.open(names[0] ?? "missing");
const paths = (await cache.keys())
.map((request) => new URL(request.url))
.filter((url) => url.origin === location.origin)
.map((url) => url.pathname);
return { names, paths };
});
expect(cached.names).toHaveLength(1);
expect(cached.paths.sort()).toEqual(await hashedAssets(dist.a));
// The server really sent the headers under test.
const assets = server.served.filter((response) =>
response.path.startsWith("/assets/"),
);
expect(assets.length).toBeGreaterThan(0);
if (headers.gzip) {
expect(assets.every((response) => response.contentEncoding === "gzip"))
.toBe(true);
expect(
assets.some(
(response) => response.contentLength < response.decodedLength,
),
).toBe(true);
} else {
expect(
assets
.filter((response) => response.path.endsWith(".js"))
.every(
(response) => response.contentType === "application/javascript",
),
).toBe(true);
}
} finally {
await server.close();
}
});
}
type BuildServer = Awaited<ReturnType<typeof startBuildServer>>;
// Playwright's Firefox never lets a worker control a page: even a trivial
// classic worker leaves `navigator.serviceWorker.controller` null after a new
// navigation (checked by hand with Playwright 1.62). With no controlled
// client, B skips `waiting` and activates by itself (`requestActivation()` then
// returns NO_WAITING_WORKER), and the fetch handler is never reached. The
// update tests therefore run where a page can be controlled. Not a product
// defect.
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
const NO_CONTROLLED_PAGES =
"Playwright Firefox pages are never controlled by a service worker.";
/**
* Loads build A twice (first install, then a normal navigation), switches the
* server to B, runs the update check and activates B through the app host.
* Returns whether the second load of A was controlled by the worker.
*/
async function updateFromAToB(
page: Page,
server: BuildServer,
): Promise<{ secondLoad: unknown; controlled: boolean }> {
await page.goto(`${server.origin}/`);
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
await page.evaluate(async () => {
await navigator.serviceWorker.ready;
});
// A normal navigation. (`page.reload()` would not change anything here.)
await page.goto(`${server.origin}/`);
const secondLoad = await startOutcome(page);
const controlled = await page.evaluate(
() => navigator.serviceWorker.controller !== null,
);
server.serve("b");
await page.evaluate(async () => {
await (await navigator.serviceWorker.getRegistration())?.update();
});
await waitForEvent(page, "update-waiting");
const activation = await page.evaluate(() =>
(globalThis as Probe).__caServiceWorkerTest!.host.requestActivation(),
);
expect(activation).toEqual({ kind: "ACTIVATED_RELOAD_REQUIRED" });
await waitForEvent(page, "reload-required");
return { secondLoad, controlled };
}
test("announces update-waiting and reload-required through the host when build B replaces A", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const server = await startBuildServer(requireBuilds().dist);
try {
await updateFromAToB(page, server);
const registration = await page.evaluate(async () => {
const current = await navigator.serviceWorker.getRegistration();
return {
active: current?.active?.state ?? null,
waiting: current?.waiting ?? null,
};
});
expect(registration).toEqual({ active: "activated", waiting: null });
} finally {
await server.close();
}
});
test("serves A's removed chunk from the previous cache once B controls the page", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const { dist } = requireBuilds();
const routeChunks = Object.values(
(
JSON.parse(
await readFile(path.join(dist.a, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> }
).routeChunks,
);
const inB = new Set(await hashedAssets(dist.b));
const removedChunk = routeChunks
.map((chunk) => `/${chunk}`)
.find((chunk) => !inB.has(chunk));
if (!removedChunk) throw new Error("Build B kept every route chunk of A.");
const server = await startBuildServer(dist);
try {
const { secondLoad, controlled } = await updateFromAToB(page, server);
expect(secondLoad).toEqual({ kind: "ACTIVE", buildId: "sw-e2e-a" });
expect(controlled).toBe(true);
// B's worker now controls the page. The chunk is not in B's manifest and
// not on the server any more, so only A's retained cache can answer.
const fromWorker = await page.evaluate(async (url) => {
const response = await fetch(url);
return { status: response.status, body: await response.text() };
}, removedChunk);
expect(fromWorker).toEqual({
status: 200,
body: await readFile(path.join(dist.a, removedChunk), "utf8"),
});
expect((await page.request.get(`${server.origin}${removedChunk}`)).status())
.toBe(404);
} finally {
await server.close();
}
});
// `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default
// `bundle` config loader); this pins that both builds emitted the worker.
test("builds the ACTIVE worker with the repo's unmodified build script", async () => {
const { dist } = requireBuilds();
for (const root of [dist.a, dist.b]) {
expect(await readdir(root)).toContain("service-worker.js");
}
});
+97
View File
@@ -0,0 +1,97 @@
import { spawnSync } from "node:child_process";
import { cp, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
/**
* Real production builds of an edited temp copy of the repository, in the
* template's default configuration (`serviceWorker: null`). `edit` changes the
* copy right before that build runs, and edits persist into later builds. The
* working tree and its `dist` (served by the e2e preview server) are never
* touched. Serve the result with `startBuildServer` from
* `service-worker-builds.ts`.
*/
const repoRoot = path.resolve(import.meta.dirname, "../../..");
const skipped = new Set([
"node_modules",
".git",
".claude",
".generated",
".tmp",
"dist",
"artifacts",
"graphify-out",
]);
export type FixtureBuild<Name extends string> = Readonly<{
name: Name;
edit?: (root: string) => Promise<void>;
}>;
export type FixtureBuilds<Name extends string> = Readonly<{
root: string;
dist: Readonly<Record<Name, string>>;
}>;
/** Replaces the one occurrence of `search` in `file` of the copy. */
export async function editOnce(
file: string,
search: string,
replacement: string,
): Promise<void> {
const source = await readFile(file, "utf8");
if (source.split(search).length !== 2) {
throw new Error(`Expected exactly one "${search}" in ${file}.`);
}
await writeFile(file, source.replace(search, replacement));
}
function run(cwd: string, script: string, buildId: string): void {
const result = spawnSync("node", [script], {
cwd,
encoding: "utf8",
env: { ...process.env, VITE_BUILD_ID: buildId, RELEASE_ID: buildId },
});
if (result.status !== 0) {
throw new Error(
`${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`,
);
}
}
export async function prepareFixtureBuilds<Name extends string>(
prefix: string,
builds: readonly FixtureBuild<Name>[],
): Promise<FixtureBuilds<Name>> {
const root = await mkdtemp(path.join(tmpdir(), `${prefix}-`));
try {
await cp(repoRoot, root, {
recursive: true,
filter: (source) =>
!skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!),
});
await linkFixtureNodeModules(root, repoRoot);
const dist = {} as Record<Name, string>;
for (const build of builds) {
await build.edit?.(root);
const buildId = `${prefix}-${build.name}`;
run(root, "scripts/generate-product-feature-index.ts", buildId);
run(root, "scripts/build-frontend.ts", buildId);
dist[build.name] = path.join(root, `dist-${build.name}`);
await rename(path.join(root, "dist"), dist[build.name]);
}
return { root, dist };
} catch (error) {
await rm(root, { recursive: true, force: true });
throw error;
}
}
export async function removeFixtureBuilds(
builds: Readonly<{ root: string }> | undefined,
): Promise<void> {
if (builds) await rm(builds.root, { recursive: true, force: true });
}
+252
View File
@@ -0,0 +1,252 @@
import { spawnSync } from "node:child_process";
import {
cp,
mkdtemp,
readFile,
rename,
rm,
writeFile,
} from "node:fs/promises";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { gzipSync } from "node:zlib";
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
/**
* R3-6 test helper: two real production builds with the Service Worker on,
* 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
* `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
* repo's own build scripts twice with different `VITE_BUILD_ID`s. The working
* tree and its `dist` (served by the e2e preview server) are never touched.
*
* The app composes the worker host but nothing subscribes to it yet, and it is
* not reachable from outside. The copy therefore also wraps
* `createServiceWorkerRuntimeHost` so the page records the host's own
* `onUpdateWaiting` / `onReloadRequired` callbacks and `start()` outcome on
* `globalThis.__caServiceWorkerTest`. Only the temp copy is edited.
*/
const repoRoot = path.resolve(import.meta.dirname, "../../..");
const skipped = new Set([
"node_modules",
".git",
".claude",
".generated",
"dist",
"artifacts",
"graphify-out",
]);
export type BuildName = "a" | "b";
export type ServiceWorkerBuilds = Readonly<{
root: string;
dist: Readonly<Record<BuildName, string>>;
}>;
export const ACTIVE_SELECTION = `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = {
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: ["PWA_STATIC_ASSETS"],
};`;
const HOST_PROBE = `
export function createServiceWorkerRuntimeHost(
input: ServiceWorkerHostInput,
): ServiceWorkerRuntimeHost | null {
const host = createServiceWorkerRuntimeHostUnobserved(input);
if (!host) return host;
const events: string[] = [];
host.onUpdateWaiting(() => events.push("update-waiting"));
host.onReloadRequired(() => events.push("reload-required"));
const observed: ServiceWorkerRuntimeHost = Object.freeze({
...host,
start: async () => {
const outcome = await host.start();
events.push("start:" + JSON.stringify(outcome));
return outcome;
},
});
Object.assign(globalThis, { __caServiceWorkerTest: { host: observed, events } });
return observed;
}
`;
export async function replaceOnce(
file: string,
search: string,
replacement: string,
): Promise<void> {
const source = await readFile(file, "utf8");
if (source.split(search).length !== 2) {
throw new Error(`Expected exactly one "${search}" in ${file}.`);
}
await writeFile(file, source.replace(search, replacement));
}
function run(cwd: string, script: string, buildId: string): void {
const result = spawnSync("node", [script], {
cwd,
encoding: "utf8",
env: { ...process.env, VITE_BUILD_ID: buildId, RELEASE_ID: buildId },
});
if (result.status !== 0) {
throw new Error(
`${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`,
);
}
}
/**
* `beforeBuild` edits the temp copy right before build `name` (06-03: a
* broken worker A, then a `REMOVE_REGISTRATION` release B). Edits persist
* into the later build.
*/
export async function prepareServiceWorkerBuilds(
options: Readonly<{
beforeBuild?: (name: BuildName, root: string) => Promise<void>;
}> = {},
): Promise<ServiceWorkerBuilds> {
const root = await mkdtemp(path.join(tmpdir(), "ca-sw-builds-"));
await cp(repoRoot, root, {
recursive: true,
filter: (source) =>
!skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!),
});
await linkFixtureNodeModules(root, repoRoot);
await replaceOnce(
path.join(root, "src/features/installed-runtime-capabilities.ts"),
"const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null;",
ACTIVE_SELECTION,
);
const hostFile = path.join(root, "src/bootstrap/register-service-worker.ts");
await replaceOnce(
hostFile,
"export function createServiceWorkerRuntimeHost(",
"function createServiceWorkerRuntimeHostUnobserved(",
);
await writeFile(hostFile, (await readFile(hostFile, "utf8")) + HOST_PROBE);
const dist = { a: path.join(root, "dist-a"), b: path.join(root, "dist-b") };
for (const name of ["a", "b"] as const) {
await options.beforeBuild?.(name, root);
run(root, "scripts/generate-product-feature-index.ts", `sw-e2e-${name}`);
run(root, "scripts/build-frontend.ts", `sw-e2e-${name}`);
await rename(path.join(root, "dist"), dist[name]);
}
return { root, dist };
}
export async function removeServiceWorkerBuilds(
builds: ServiceWorkerBuilds | undefined,
): Promise<void> {
if (builds) await rm(builds.root, { recursive: true, force: true });
}
export type AssetHeaders = Readonly<{
/** Sent for every `.js` file, the worker script included. */
javascriptContentType: string;
/** gzip every `/assets/*` body; Content-Length is the compressed size. */
gzip: boolean;
}>;
export type ServedResponse = Readonly<{
path: string;
contentType: string;
contentEncoding: string | null;
contentLength: number;
decodedLength: number;
}>;
const CONTENT_TYPES: Readonly<Record<string, string>> = {
".html": "text/html; charset=utf-8",
".css": "text/css",
".json": "application/json",
".svg": "image/svg+xml",
".png": "image/png",
".webp": "image/webp",
".woff2": "font/woff2",
};
/**
* Serves one dist directory at a time from an ephemeral 127.0.0.1 port, so
* every test gets its own origin (and its own Service Worker registration).
* Paths without an extension get `index.html`; a missing file is a plain 404,
* never the SPA fallback, so a chunk that the served build lacks really 404s.
*/
export async function startBuildServer(
dist: Readonly<Record<BuildName, string>>,
headers: AssetHeaders = {
javascriptContentType: "text/javascript",
gzip: false,
},
) {
let current: BuildName = "a";
const served: ServedResponse[] = [];
const server: Server = createServer((request, response) => {
void (async () => {
const pathname = decodeURIComponent(
new URL(request.url ?? "/", "http://127.0.0.1").pathname,
);
const root = dist[current];
const file = path.extname(pathname)
? path.join(root, path.normalize(pathname))
: path.join(root, "index.html");
let body: Buffer;
try {
if (!file.startsWith(root + path.sep)) throw new Error("outside root");
body = await readFile(file);
} catch {
response.writeHead(404, { "cache-control": "no-store" }).end();
return;
}
const extension = path.extname(file);
const contentType =
extension === ".js"
? headers.javascriptContentType
: (CONTENT_TYPES[extension] ?? "application/octet-stream");
const encoded = headers.gzip && pathname.startsWith("/assets/");
const payload = encoded ? gzipSync(body) : body;
served.push({
path: pathname,
contentType,
contentEncoding: encoded ? "gzip" : null,
contentLength: payload.byteLength,
decodedLength: body.byteLength,
});
response
.writeHead(200, {
"content-type": contentType,
"content-length": String(payload.byteLength),
"cache-control": "no-cache",
...(encoded
? { "content-encoding": "gzip", vary: "Accept-Encoding" }
: {}),
})
.end(request.method === "HEAD" ? undefined : payload);
})();
});
await new Promise<void>((resolve) =>
server.listen(0, "127.0.0.1", () => resolve()),
);
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
served,
serve(name: BuildName) {
current = name;
},
async close() {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
},
};
}
@@ -0,0 +1,8 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
const files=["installed-product-manifest.ts","installed-feature-adapters.ts","installed-feature-runtimes.tsx","installed-feature-messages.ts","installed-contract-contributions.ts","installed-feature-contracts.ts"];
describe("feature installation surface", () => {
it("contains no reference-specific central imports", async () => {
for(const name of files){const source=await readFile(new URL(`../../src/features/${name}`,import.meta.url),"utf8"); expect(source).not.toMatch(/REFERENCE_FEATURE_(ADAPTER|RUNTIME|CONTRACT)/); expect(source).not.toMatch(/REFERENCE_MESSAGE_CATALOGS/);}
});
});
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { defineFeatureModule } from "../../src/features/feature-module.ts";
describe("defineFeatureModule", () => {
it("keeps one stable feature id and freezes the descriptor", () => {
const module = defineFeatureModule({
id: "feature-a",
contracts: { featureId: "feature-a" },
routes: {}, adapters: [], runtimes: [], messages: {}, contractContributions: [],
});
expect(module.id).toBe("feature-a");
expect(Object.isFrozen(module)).toBe(true);
});
// 09-11: the one check defineFeatureModule makes at runtime.
it("rejects a module whose id differs from its contract featureId", () => {
expect(() =>
defineFeatureModule({
id: "feature-a",
contracts: { featureId: "feature-b" },
routes: {}, adapters: [], runtimes: [], messages: {}, contractContributions: [],
}),
).toThrow("Feature module id feature-a does not match contract featureId feature-b");
});
});
@@ -0,0 +1,11 @@
import { describe, expect, it } from "vitest";
import { resolveProductFeatures, selectCompiledProductFeatures } from "../../src/contracts/product-features.ts";
describe("product feature membership", () => {
it("preserves selection semantics", () => {
const compiled = [{featureId:"reference"},{featureId:"local-draft"}] as const;
expect(selectCompiledProductFeatures(compiled,"reference").map(x=>x.featureId)).toEqual(["reference"]);
});
it("resolves installed state", () => {
expect(resolveProductFeatures(["reference","local-draft"],["reference"]).map(x=>x.state)).toEqual(["NOT_INSTALLED","ACTIVE"]);
});
});
@@ -0,0 +1,62 @@
import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { createFailure } from "../../../src/contracts/errors.ts";
import { isAppError } from "../../../src/platform/errors/app-error.ts";
import {
REFERENCE_ERRORS,
toReferenceError,
type ReferenceError,
} from "../../../src/features/reference-feature/application/reference-error.ts";
describe("reference feature-local errors", () => {
it("keeps concrete error kinds feature-local", () => {
const error: ReferenceError = {
kind: "reference.not-found",
category: "domain",
severity: "warning",
retryability: "never",
};
expect(isAppError(error)).toBe(true);
for (const known of Object.values(REFERENCE_ERRORS)) {
expect(isAppError(known)).toBe(true);
}
});
it("interprets only its own domain outcomes", () => {
expect(toReferenceError(createFailure("NOT_FOUND", "GET_REFERENCE_RESOURCE", 0))).toBe(
REFERENCE_ERRORS.NOT_FOUND,
);
expect(toReferenceError(createFailure("CONFLICT", "CREATE_REFERENCE_RESOURCE", 0))).toBe(
REFERENCE_ERRORS.CONFLICT,
);
expect(
toReferenceError(createFailure("NETWORK_UNREACHABLE", "GET_REFERENCE_RESOURCE", 0)),
).toBeNull();
});
it("is not referenced by any global or central error union", async () => {
const offenders: string[] = [];
const walk = async (directory: string): Promise<void> => {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) {
if (!target.endsWith(path.join("features", "reference-feature"))) {
await walk(target);
}
continue;
}
if (!/\.tsx?$/u.test(entry.name)) continue;
const source = await readFile(target, "utf8");
if (/reference-error\.ts|ReferenceError\b(?!Boundary)/u.test(source)) {
offenders.push(target);
}
}
};
await walk(path.resolve("src"));
expect(offenders).toEqual([]);
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from "vitest";
import {
createQueryClient,
QUERY_CACHE_DEFAULTS,
} from "../../../src/adapters/query-cache/tanstack-query-cache.ts";
import {
jsonRows,
networkFailure,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
import { referenceFeatureOver } from "./reference-traffic-kit.ts";
/**
* Spec §16. Multiple consumers of one query identity must not imply multiple
* physical requests. TanStack Query owns in-flight coalescing; this suite pins
* that the installed query client plus the real V3 executor keep it that way.
*/
describe("request deduplication and coalescing", () => {
function loadSameQuery(
client: ReturnType<typeof createQueryClient>,
reference: ReturnType<typeof referenceFeatureOver>,
key: readonly unknown[] = ["reference", "list", { limit: 20 }],
) {
return client.fetchQuery({
queryKey: key,
queryFn: ({ signal }) => reference.listResources({ limit: 20 }, { signal }),
});
}
it("coalesces concurrent consumers of the same query identity", async () => {
const transport = vi.fn<Transport>(async () => jsonRows(3));
const reference = referenceFeatureOver(transport);
const client = createQueryClient();
const results = await Promise.all([
loadSameQuery(client, reference),
loadSameQuery(client, reference),
loadSameQuery(client, reference),
]);
expect(transport).toHaveBeenCalledTimes(1);
expect(results.every((result) => result.ok)).toBe(true);
client.clear();
});
it("keeps distinct query identities as distinct physical requests", async () => {
const transport = vi.fn<Transport>(async () => jsonRows(1));
const reference = referenceFeatureOver(transport);
const client = createQueryClient();
await Promise.all([
loadSameQuery(client, reference, ["reference", "list", 1]),
loadSameQuery(client, reference, ["reference", "list", 2]),
]);
expect(transport).toHaveBeenCalledTimes(2);
client.clear();
});
it("does not stack a query-layer retry on top of the executor retry budget", async () => {
expect(QUERY_CACHE_DEFAULTS.retry).toBe(false);
expect(QUERY_CACHE_DEFAULTS.mutationRetry).toBe(false);
const transport = vi.fn<Transport>(networkFailure);
const reference = referenceFeatureOver(transport, { maxRetryAttempts: 2 });
const client = createQueryClient();
await Promise.all([
loadSameQuery(client, reference),
loadSameQuery(client, reference),
]);
// One coalesced logical execution: 1 attempt + at most 2 executor retries.
expect(transport.mock.calls.length).toBeLessThanOrEqual(3);
client.clear();
});
});
@@ -0,0 +1,86 @@
import { describe, expect, it, vi } from "vitest";
import {
assertRequestFanoutWithinBudget,
RequestFanoutExceededError,
} from "../../../src/platform/traffic/request-fanout.ts";
import {
jsonRows,
paginatedCollection,
testExecutionContext,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
import { referenceFeatureOver } from "./reference-traffic-kit.ts";
/** Physical requests one representative collection load may cost. */
const COLLECTION_LOAD_FANOUT_BUDGET = 1;
describe("request fan-out budget", () => {
it.each([10, 50, 100, 1_000])(
"loads the first page of a %i-row collection with one physical request",
async (totalRows) => {
const transport = paginatedCollection(totalRows);
const reference = referenceFeatureOver(transport);
const result = await reference.listResources({ limit: 100 });
expect(result).toMatchObject({ ok: true });
expect(result.ok && result.value).toHaveLength(Math.min(totalRows, 100));
expect(() =>
assertRequestFanoutWithinBudget(transport.calls, COLLECTION_LOAD_FANOUT_BUDGET),
).not.toThrow();
},
);
it("walks a 1,000-row collection in page-sized bulk requests, never one per row", async () => {
const transport = paginatedCollection(1_000);
const reference = referenceFeatureOver(transport);
const rows: unknown[] = [];
for (let cursor = 0; ; cursor += 100) {
const page = await reference.listResources({
limit: 100,
...(cursor === 0 ? {} : { cursor: String(cursor) }),
});
expect(page.ok).toBe(true);
if (!page.ok || page.value.length === 0) break;
rows.push(...page.value);
if (page.value.length < 100) break;
}
expect(rows).toHaveLength(1_000);
// ceil(N / pageSize) + one empty terminal page, versus N per-row calls.
expect(transport.calls).toBeLessThanOrEqual(Math.ceil(1_000 / 100) + 1);
});
it("rejects a single oversized response in one request without row-proportional fan-out", async () => {
const transport = vi.fn<Transport>(async () => jsonRows(1_000));
const reference = referenceFeatureOver(transport);
const result = await reference.listResources({ limit: 100 });
expect(result.ok).toBe(false);
expect(transport).toHaveBeenCalledTimes(1);
});
it("keeps a whole interaction's request count bounded while cardinality grows", async () => {
const counts: number[] = [];
for (const rows of [10, 100, 1_000]) {
const transport = vi.fn<Transport>(paginatedCollection(rows));
const reference = referenceFeatureOver(transport);
const execution = testExecutionContext({ maxPhysicalRequests: 3 });
await reference.listResources({ limit: 100 }, { execution });
counts.push(transport.mock.calls.length);
expect(execution.traffic.requests.consumed).toBe(transport.mock.calls.length);
}
expect(new Set(counts)).toEqual(new Set([1]));
});
it("fails loudly when a flow exceeds its fan-out budget", () => {
expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow(
RequestFanoutExceededError,
);
expect(() => assertRequestFanoutWithinBudget(4, 3)).toThrow(
/fan-out 4 exceeds 3/,
);
expect(() => assertRequestFanoutWithinBudget(1, 0)).toThrow(TypeError);
});
});
@@ -1,5 +1,6 @@
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";
@@ -9,6 +10,41 @@ import {
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"];
@@ -44,7 +80,7 @@ const runtime: Runtime = {
const release: Release = {
schemaVersion: 2,
appVersion: "0.1.0",
appVersion: "0.2.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
@@ -212,4 +248,59 @@ describe("reference feature runtime composition", () => {
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();
});
});
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from "vitest";
import { createReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts";
import { createFailure } from "../../../src/contracts/errors.ts";
import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts";
import {
createTelemetryPipeline,
type TelemetryTransport,
} from "../../../src/platform/telemetry/telemetry-pipeline.ts";
import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts";
function failingGateway() {
const failure = Object.freeze({
ok: false as const,
error: createFailure("REQUEST_TIMEOUT", "LIST_REFERENCE_RESOURCES", 0),
});
return Object.freeze({
list: vi.fn(async () => failure),
get: vi.fn(async () => failure),
create: vi.fn(async () => failure),
});
}
describe("reference feature telemetry through the platform port", () => {
it("declares the provider-neutral telemetry capability", () => {
expect(REFERENCE_FEATURE_ADAPTER_CONTRIBUTION.needs).toContain("telemetry");
});
it("emits a feature-owned event with a bounded payload on load failure", async () => {
const emit = vi.fn<TelemetryPort["emit"]>();
const input = createReferenceFeatureInput(failingGateway(), { telemetry: { emit } });
const result = await input.listResources({ limit: 20 });
expect(result.ok).toBe(false);
expect(emit).toHaveBeenCalledWith({
kind: "reference.load.failed",
severity: "warning",
featureId: "reference-feature",
payload: { operation: "list", reason: "REQUEST_TIMEOUT" },
});
});
it("returns the business result even when the port throws or rejects", async () => {
const throwing = createReferenceFeatureInput(failingGateway(), {
telemetry: {
emit() {
throw new Error("port broken");
},
},
});
const rejecting = createReferenceFeatureInput(failingGateway(), {
telemetry: { emit: () => Promise.reject(new Error("collector down")) },
});
await expect(throwing.getResource("id-1")).resolves.toMatchObject({ ok: false });
await expect(rejecting.getResource("id-1")).resolves.toMatchObject({ ok: false });
});
it("collapses a failure storm into bounded sends via the pipeline", async () => {
const send = vi.fn<TelemetryTransport["send"]>();
const pipeline = createTelemetryPipeline({ transport: { send } });
const input = createReferenceFeatureInput(failingGateway(), { telemetry: pipeline });
for (let i = 0; i < 500; i += 1) await input.listResources({ limit: 20 });
await pipeline.flush();
// The first failure goes out at once; the 499 duplicates ride on the flush.
expect(send).toHaveBeenCalledTimes(2);
const occurrences = send.mock.calls
.flatMap(([batch]) => batch)
.reduce((sum, item) => sum + item.occurrences, 0);
expect(occurrences).toBe(500);
expect(pipeline.stats().deduplicated).toBe(499);
pipeline.dispose();
});
});
@@ -0,0 +1,36 @@
import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts";
import {
scopeSnapshot,
testExecutor,
type Transport,
} from "../../helpers/traffic-test-kit.ts";
/**
* The reference feature's real application input, wired to the real V3
* executor over an injected transport. Used to prove collection loads and
* multi-operation interactions stay bounded end to end.
*/
export function referenceFeatureOver(
transport: Transport,
options: Parameters<typeof testExecutor>[1] = {},
) {
const executor = testExecutor(transport, {
credentialHeaders: { authorization: "Bearer traffic-test-token" },
...options,
});
return createReferenceFeatureInstalledInput({
http: Object.freeze({
execute(operation, input, context) {
return executor.execute(operation, input, {
routeId: context.routeId,
scope: scopeSnapshot(),
...(context.signal === undefined ? {} : { signal: context.signal }),
...(context.intent === undefined ? {} : { intent: context.intent }),
...(context.execution === undefined
? {}
: { execution: context.execution }),
});
},
}),
}).input;
}
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { composeContractContributions } from "../../../src/contracts/external-contract-runtime.ts";
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
describe("reference operation traffic policy", () => {
it("declares explicit bounded traffic on every representative reference operation", () => {
const composed = composeContractContributions([
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION,
]);
for (const operationId of [
"LIST_REFERENCE_RESOURCES",
"GET_REFERENCE_RESOURCE",
"CREATE_REFERENCE_RESOURCE",
]) {
const traffic = composed.httpByOperationId.get(operationId)?.frontend.traffic;
expect(traffic, operationId).toBeDefined();
expect(Number.isSafeInteger(traffic?.maxPhysicalRequests)).toBe(true);
}
// A KEYED command never retries automatically; its policy says so too.
expect(
composed.httpByOperationId.get("CREATE_REFERENCE_RESOURCE")?.frontend
.traffic,
).toMatchObject({ maxPhysicalRequests: 1, maxRetries: 0 });
});
});
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import {
CREATE_REFERENCE_RESOURCE_CONTRACT,
LIST_REFERENCE_RESOURCES_CONTRACT,
} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
import {
REFERENCE_RUNTIME_SCHEMA_CODECS,
validateReferencePayload,
validateReferenceRequest,
} from "../../../src/features/reference-feature/contracts/reference-schemas.ts";
/**
* Q-6.7-8 characterization. The reference feature exposes one schema through
* two protocols: the canonical `RuntimeValidator` (array paths) for the HTTP
* contract and the registry-facing `RuntimeSchemaCodec` (dotted paths). Both
* must keep answering exactly this after they share one zod wrapper.
*/
describe("reference validator protocols", () => {
const badList = [{ id: "unsafe", name: 42 }];
it("answers the canonical validator with array paths", () => {
expect(
LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse(
badList,
),
).toEqual({
success: false,
issues: [{ path: [0, "name"], code: "invalid_type" }],
});
expect(
CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({
name: " Example ",
}),
).toEqual({ success: true, data: { name: "Example" } });
});
it("answers the schema codec with dotted paths", () => {
const codecs = REFERENCE_RUNTIME_SCHEMA_CODECS;
expect(codecs.ReferenceResourceListPayload.parse(badList)).toEqual({
success: false,
issues: [{ path: "0.name", code: "invalid_type" }],
});
expect(
codecs.CreateReferenceResourceCommand.parse({ name: "a", extra: 1 }),
).toEqual({
success: false,
issues: [{ path: "", code: "unrecognized_keys" }],
});
expect(
codecs.ReferenceResourceListQuery.parse({ limit: "5", tags: "open" }),
).toEqual({ success: true, data: { limit: 5, tags: ["open"] } });
expect(Object.keys(codecs)).toEqual([
"ReferenceResourceParams",
"ReferenceResourceListQuery",
"NoRequest",
"CreateReferenceResourceCommand",
"ReferenceResourceListPayload",
"ReferenceResourcePayload",
]);
for (const [schemaId, codec] of Object.entries(codecs)) {
expect(codec.schemaId).toBe(schemaId);
}
});
it("keeps the payload and request lookups apart", () => {
expect(validateReferencePayload("ReferenceResourceListPayload", badList))
.toEqual({
success: false,
issues: [{ path: "0.name", code: "invalid_type" }],
});
expect(validateReferencePayload("NoRequest", {})).toEqual({
success: false,
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
});
expect(
validateReferenceRequest("CreateReferenceResourceCommand", {
name: " Example ",
}),
).toEqual({ success: true, data: { name: "Example" } });
expect(
validateReferenceRequest("ReferenceResourcePayload", {}),
).toEqual({
success: false,
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
});
});
});
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { createExternalAuthSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
import { createBffSessionOwner } from "../../../src/features/tech-log/adapters/http/bff-session-owner.ts";
// Template sync (af3d8e6). The runtime closes an external owner without
// `readSubject` as `integration-failed`; the HTTP Studio's only owner is this one.
describe("BFF session owner", () => {
it("is a complete external owner and names no subject", async () => {
const owner = createBffSessionOwner(
"https://api.example.test/",
async () => new Response(null, { status: 401 }),
);
// Compiles only while the owner has every method the adapter requires.
const session = createExternalAuthSessionAdapter(owner);
await owner.recoverSession();
expect(session.getState()).toBe("unauthenticated");
expect(session.getSubject()).toBeNull();
});
});
@@ -10,7 +10,6 @@ import {
parseCaseContent,
} from "../../../src/features/tech-log/domain/content-format/parse-case-content.ts";
import {
evidenceCatalogEntryFor,
projectWorkingCopy,
} from "../../../src/features/tech-log/domain/content-format/project-public-render-model.ts";
import { serializeCaseContent } from "../../../src/features/tech-log/domain/content-format/serialize-case-content.ts";
@@ -13,14 +13,16 @@ type Equal<Left, Right> =
: false;
type Assert<Condition extends true> = Condition;
type TechLogFeatureInputExposesNoMissingOrAdditionalKeys = Assert<
// Exported so noUnusedLocals keeps these compile-time checks rather than
// flagging them; the `Assert` constraint is what fails the typecheck.
export type TechLogFeatureInputExposesNoMissingOrAdditionalKeys = Assert<
Equal<
keyof ApplicationFeatureInputs["tech-log"],
| "publicContent"
| "createStudioApplication"
>
>;
type TechLogFeatureInputRegistryValueMatchesFeatureContract = Assert<
export type TechLogFeatureInputRegistryValueMatchesFeatureContract = Assert<
Equal<ApplicationFeatureInputs["tech-log"], TechLogFeatureInput>
>;
@@ -16,7 +16,6 @@ import { MOCK_STUDIO_INSTALL_CONTEXT } from "../../helpers/studio-install-contex
import {
TECH_LOG_ROUTE_REGISTRY,
TECH_LOG_ROUTE_RUNTIME_CONTRACT,
type TechLogRouteId,
} from "../../../src/features/tech-log/contracts/tech-log-route-contract.ts";
import { PublicShell } from "../../../src/features/tech-log/presentation/public/public-shell.tsx";
import { ExploreKindPage } from "../../../src/features/tech-log/presentation/public/pages/explore-kind-page.tsx";
@@ -105,8 +104,15 @@ async function renderDiscoveryRoute<RouteId extends DiscoveryRouteId>(
// 단언하도록 여기서 한 번 기다린다 — 각 테스트에 흩어 놓으면 빠뜨린 곳이 생긴다.
// `main` 을 기다리지 않는다 — 이 파일에는 의도적으로 렌더에 실패하는 라우트도 있고,
// 그때는 main 이 아예 없다. 로딩 표면이 사라지는 것이 두 경우 모두에 맞는 기준이다.
// Template sync (af3d8e6): the route's own loading surface is now the shared
// LoadingSurface too, so only a page's data loading is waited out here; a
// route chunk a test holds pending stays on screen.
await waitFor(() =>
expect(document.querySelector(".state-surface--loading")).toBeNull(),
expect(
[...document.querySelectorAll(".state-surface--loading")].filter(
(surface) => !surface.closest(".route-loading"),
),
).toEqual([]),
);
return { ...view, router } satisfies ReturnType<typeof render> & {
router: RouterProviderProps["router"];
@@ -391,7 +397,7 @@ describe("TechLog explore discovery", () => {
);
expect(
screen.getByText("화면을 준비하고 있습니다.").closest("section"),
screen.getByText("화면을 준비하고 있습니다.").closest(".route-loading"),
).toHaveAttribute("data-surface", "none");
await waitFor(() => expect(rejectNotFound).toBeTypeOf("function"));
await act(async () => {
@@ -423,9 +429,19 @@ describe("TechLog explore discovery", () => {
}),
}),
]);
// Template sync (af3d8e6, 08-07). An unrecovered chunk failure is now
// recorded once, by the chunk boundary, under the not-found route's own
// id and with the incident id its support reference shows. The route
// render boundary still catches nothing.
expect(
record.mock.calls.some(([entry]) => entry.eventId === "ui.render.failed"),
).toBe(false);
record.mock.calls
.map(([entry]) => entry)
.filter((entry) => entry.eventId === "ui.render.failed"),
).toEqual([
expect.objectContaining({
context: expect.objectContaining({ route_id: "NOT_FOUND" }),
}),
]);
});
});
@@ -65,8 +65,7 @@ function installedInputs(
studioSource,
publicSource,
// Template sync (ebea300). The platform capability the manifest-governed
// contributions declare in `needs`. Composition builds the reference
// feature's gateway from it and never calls it here.
// contributions declare in `needs`. Composition never calls it here.
http: {
async execute() {
throw new Error("platform executor is not used by composition tests");
@@ -82,10 +81,13 @@ function installedInputs(
});
}
test("installs TechLog beside the retained reference feature through application-facing inputs", async () => {
test("installs TechLog through application-facing inputs", async () => {
const installed = installedInputs();
assert.deepEqual(Object.keys(installed), ["reference-feature", "tech-log"]);
// Template sync (af3d8e6). The reference sample is no longer installed
// (src/features/reference-feature/NOT_INSTALLED), so TechLog is the only
// input; it is composed directly and cannot be narrowed out.
assert.deepEqual(Object.keys(installed), ["tech-log"]);
assert.deepEqual(Object.keys(installed["tech-log"]).sort(), [
"createStudioApplication",
"publicContent",
@@ -77,7 +77,9 @@ type RequiredStudioGatewayOperation =
| "getPublicationSnapshot"
| "getCatalog";
type StudioGatewayExposesNoMissingOrAdditionalOperations = Assert<
// Exported so noUnusedLocals keeps this compile-time check rather than
// flagging it; the `Assert` constraint is what fails the typecheck.
export type StudioGatewayExposesNoMissingOrAdditionalOperations = Assert<
Equal<keyof StudioGateway, RequiredStudioGatewayOperation>
>;
@@ -2,7 +2,6 @@
import { fireEvent, render as testingRender, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { ReactNode } from "react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { fireEvent, render as testingRender, screen, waitFor } from "@testing-library/react";
import { render as testingRender, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import {
@@ -188,7 +188,7 @@ describe("TechLog Studio publication flow", () => {
});
});
it("keeps the publish pending state, preserves gateway command order, and retries with a new key", async () => {
it("keeps the publish pending state, preserves gateway command order, and retries with the original key", async () => {
const user = userEvent.setup();
const base = studioGatewayFromApplication(createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioApplication());
const document = await warningReadyDocument(base);
@@ -243,7 +243,9 @@ describe("TechLog Studio publication flow", () => {
);
await user.click(screen.getByRole("button", { name: "게시" }));
await waitFor(() => expect(publishDocument).toHaveBeenCalledTimes(2));
expect(keys[1]).not.toBe(keys[0]);
// Template sync (af3d8e6, 03-01): a write whose outcome is unknown is sent
// again with its original idempotency key, so the backend applies it once.
expect(keys[1]).toBe(keys[0]);
});
it("filters publication events and recovers a failed history read", async () => {
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { fireEvent, render as testingRender, screen, waitFor } from "@testing-library/react";
import { render as testingRender, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useEffect } from "react";
import { MemoryRouter } from "react-router-dom";
@@ -176,7 +176,7 @@ describe("TechLog Studio save workflow", () => {
expect(screen.getByRole("button", { name: "저장" })).toBeDisabled();
});
it("surfaces a save error and retries with a new user-command key without losing input", async () => {
it("surfaces a save error and retries with the original user-command key without losing input", async () => {
const user = userEvent.setup();
const base = studioGatewayFromApplication(createTechLogFeatureInstalledInput(MOCK_STUDIO_INSTALL_CONTEXT).input.createStudioApplication());
const keys: string[] = [];
@@ -213,7 +213,9 @@ describe("TechLog Studio save workflow", () => {
await user.click(screen.getByRole("button", { name: "저장" }));
await waitFor(() => expect(screen.getByRole("status", { name: "편집 상태" })).toHaveTextContent("저장됨"));
expect(saveDocument).toHaveBeenCalledTimes(2);
expect(keys[1]).not.toBe(keys[0]);
// Template sync (af3d8e6, 03-01): a write whose outcome is unknown is sent
// again with its original idempotency key, so the backend applies it once.
expect(keys[1]).toBe(keys[0]);
});
});
@@ -58,6 +58,7 @@ async function renderStudio(
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "restored" as const,
notifyUnauthenticated: () => {},
readSubject: () => "studio-shell-subject",
}),
featureInputs: {
"tech-log": {
@@ -0,0 +1 @@
export { createFixtureHttpClient as createInternalClient } from "../client.ts";
@@ -0,0 +1 @@
export const openFixtureDatabase = (): string => "indexeddb";
@@ -0,0 +1,4 @@
// storage/indexeddb is a runtime of the browser-file-storage bundle; its index.ts is its public boundary.
import { openFixtureDatabase } from "../adapters/storage/indexeddb/index.ts";
export const storageComposition = openFixtureDatabase;
@@ -0,0 +1,4 @@
// 12-07 P3b: a second-level index.ts is not a public barrel.
import { createInternalClient } from "../adapters/http/internals/index.ts";
export const subBarrelComposition = createInternalClient;
@@ -0,0 +1 @@
export const telemetryAdapter = 1;
@@ -0,0 +1 @@
export const adminValue = 1;
@@ -0,0 +1,2 @@
import { adminValue } from "../admin/value.ts";
export const customerValue = adminValue;
@@ -0,0 +1,2 @@
// 12-03 P4b: a context module re-exporting a concrete adapter.
export * from "../../adapters/telemetry/index.ts";
@@ -0,0 +1,2 @@
import { betaValue } from "../beta/value.ts";
export const alphaValue = betaValue;
@@ -0,0 +1,2 @@
// 12-03 P4a: a feature root file re-exporting a concrete adapter.
export * from "../../adapters/telemetry/index.ts";
@@ -0,0 +1 @@
export const betaValue = 1;
@@ -0,0 +1 @@
export { telemetryAdapter as contextTelemetry } from "../contexts/customer/telemetry.ts";
@@ -0,0 +1 @@
export { telemetryAdapter } from "../features/alpha/telemetry.ts";
@@ -0,0 +1 @@
export const connectRealtime = (): undefined => undefined;
@@ -0,0 +1,4 @@
// The realtime runtime is not selected, so the composition root does not build it.
import { connectRealtime } from "../adapters/realtime/index.ts";
export const composedRealtime = connectRealtime;
@@ -0,0 +1,6 @@
// F-7 (13-08): the one module that imports zod itself.
import { z } from "zod";
z.config({ jitless: true });
export { z };
@@ -0,0 +1,2 @@
// A named facade that re-exports a primitive under its pre-VD-05 path.
export { Button } from "../../design-system/primitives/core.ts";
@@ -0,0 +1 @@
export { Button } from "./primitives/core.ts";
@@ -0,0 +1 @@
export const Button = "button";
@@ -0,0 +1,4 @@
// 12-08 P6: a deep import past the design-system index.
import { Button } from "../design-system/primitives/core.ts";
export const DeepImport = Button;
@@ -1,3 +1,4 @@
// VD-05: lucide-react is imported only by the icon vendor facade.
import { Menu } from "lucide-react";
export const DirectIcon = Menu;
@@ -0,0 +1,5 @@
// F-7 (13-08): schema code imports z from src/contracts/zod.ts, which sets
// jitless before any schema is built.
import { z } from "zod";
export const directSchema = z.string();
@@ -0,0 +1,3 @@
import { Button } from "../design-system/index.ts";
export const PublicImport = Button;
@@ -0,0 +1,3 @@
import { z } from "../../contracts/zod.ts";
export const wrappedSchema = z.string();
@@ -0,0 +1,2 @@
// 12-06 P1d: import.meta.glob loads modules the graph cannot list, so it is refused.
export const valueModules = import.meta.glob("../domain/*.ts");
@@ -0,0 +1,12 @@
// Allowed: one bulk request, then per-row work is local mapping only.
type Gateway = { list(filters: { limit: number }): Promise<readonly { id: string }[]> };
export async function loadPage(gateway: Gateway) {
const rows = await gateway.list({ limit: 100 });
return rows.map((row) => ({ ...row, label: row.id.toUpperCase() }));
}
export function bindHandlers(gateway: Gateway, ids: readonly string[]) {
// Declaring a function per row is fine; it dispatches only when a user acts.
return ids.map((id) => () => gateway.list({ limit: id.length }));
}
@@ -0,0 +1,6 @@
// Forbidden: raw fetch per element.
export function prefetch(urls: readonly string[]) {
urls.forEach((url) => {
void fetch(url);
});
}
@@ -0,0 +1,10 @@
// Forbidden: a dispatch inside a loop over rows.
type Http = { execute(operation: string, input: unknown): Promise<unknown> };
export async function loadEach(http: Http, rows: readonly { id: string }[]) {
const results: unknown[] = [];
for (const row of rows) {
results.push(await http.execute("GET_ROW", { id: row.id }));
}
return results;
}
@@ -0,0 +1,6 @@
// Forbidden: one physical request per collection row (frontend N+1).
type Gateway = { get(id: string): Promise<unknown> };
export async function loadDetails(gateway: Gateway, ids: readonly string[]) {
return Promise.all(ids.map((id) => gateway.get(id)));
}
+8 -8
View File
@@ -1,14 +1,14 @@
{
"total": {
"lines": { "pct": 0 },
"statements": { "pct": 0 },
"functions": { "pct": 0 },
"branches": { "pct": 0 }
"lines": { "total": 10, "covered": 0, "skipped": 0, "pct": 0 },
"statements": { "total": 10, "covered": 0, "skipped": 0, "pct": 0 },
"functions": { "total": 2, "covered": 0, "skipped": 0, "pct": 0 },
"branches": { "total": 4, "covered": 0, "skipped": 0, "pct": 0 }
},
"src/adapters/http/http-execution-v3.ts": {
"lines": { "pct": 0 },
"statements": { "pct": 0 },
"functions": { "pct": 0 },
"branches": { "pct": 0 }
"lines": { "total": 10, "covered": 0, "skipped": 0, "pct": 0 },
"statements": { "total": 10, "covered": 0, "skipped": 0, "pct": 0 },
"functions": { "total": 2, "covered": 0, "skipped": 0, "pct": 0 },
"branches": { "total": 4, "covered": 0, "skipped": 0, "pct": 0 }
}
}
+2 -2
View File
@@ -38,10 +38,10 @@
"src/contracts/compatibility.ts": {
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
},
"src/application/policies/performance-budgets.ts": {
"src/bootstrap/load-release-manifest.ts": {
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
},
"src/application/policies/promotion-readiness.ts": {
"src/bootstrap/read-bounded-boot-json.ts": {
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
},
"src/application/use-cases/decide-chunk-recovery.ts": {
@@ -1,3 +0,0 @@
import { Button } from "../../../../src/presentation/design-system/primitives/core.tsx";
export const DeepImport = Button;
@@ -0,0 +1,3 @@
export default function SampleFeaturePage() {
return <button type="button">새 항목 만들기</button>;
}
@@ -0,0 +1,3 @@
export default function SamplePage() {
return <h1>프로젝트 시작점</h1>;
}

Some files were not shown because too many files have changed in this diff Show More