Files
clean-architecture-frontend…/tests/recipes/browser-file-session-capability.test.ts
DongHyeonka d31c7d6b18 fix(recipes): 세션 파일 레시피가 매뉴얼과 같은 capability 타입 위치를 가리킨다
문제: 세션 레시피 주석이 "`FeaturePlatformCapabilities`를
`files: SessionBrowserFiles`로 보강한다"고 적는다. 매뉴얼
(`docs/manual/03-outside-feature-folder.md`)은 그 타입을
`src/features/product-capabilities.ts`의
`ProductFeaturePlatformCapabilities`에 적으라고 하고, `declare module`
보강은 `check:types:node`가 키를 보지 못한다고 막는다. 주석대로 하면 앱
typecheck는 통과하고 node typecheck에서 키를 잃는다. 또 레시피 테스트는
`capabilities: {}`로 조립하고 `files.current()`를 레시피 객체에서 직접
불러서, capability가 기능 쪽으로 넘어가는 절반이 깨져도 통과한다.

고른 방법:
- 주석이 `ProductFeaturePlatformCapabilities`에 적는 예와 매뉴얼 경로를
  보이고, `declare module` 보강은 쓰지 말라고 적는다.
- 레시피 테스트가 `capabilities: { files }`를 돌려주고, 템플릿이 설치된
  기능의 loader에 넘기는 capability 객체(`createInstalledFeatureLoaders`의
  첫 인자)를 기록한다. 테스트의 모든 파일 동작(선택, 읽기, download,
  계정 전환 뒤 새 runtime)을 그 객체의 `files.current()`로 돈다. 같은
  mock 방식은 `tests/recipes/session-owners-runtime.test.ts`가 이미 쓴다.

버린 대안: `files`를 `needs`에 적은 가짜 기능을 생성 index에 끼워 넣기.
`ProductFeaturePlatformCapabilities`가 비어 있는 템플릿에서는 타입을
우회해야 하고, `needs`로 고르는 부분은 1103/09-08 테스트가 이미 잡는다.

위험·한계: 검사는 loader가 받는 capability 객체까지다. 기능 factory가
`needs`로 골라 받는 마지막 단계는 기존 테스트에 맡긴다. 동작 코드는
바뀌지 않는다(주석과 테스트만).

검증: desktop batch에서 확인
- node scripts/run-vitest.ts run tests/recipes/browser-file-session-capability.test.ts
- 변이: 테스트 mock의 `capabilities`에서 `files`를 빼거나,
  `src/bootstrap/runtime-adapters.ts`의 `...product.capabilities`를 지우면
  "Features did not receive the files capability"로 실패해야 한다.

Refs: 1105/02-03
2026-11-05 22:16:46 +09:00

317 lines
9.7 KiB
TypeScript

// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import type { LocalFileRef } from "../../src/application/ports/browser-file-storage/index.ts";
import {
browserFilePolicyReference,
createBrowserFileRuntime,
type BrowserFilePolicyProfile,
} from "../../src/adapters/browser-files/index.ts";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import {
createSessionBrowserFileCapability,
type SessionBrowserFiles,
} from "../../recipes/frontend-capabilities/browser-file-session-capability.ts";
import { testRuntimeConfig } from "../helpers/runtime-config.ts";
/**
* 2026-11-03 02-01. A product wires the browser file runtime to the session by
* filling only its own `product-composition.ts`: the recipe capability goes to
* features, its scope participant to the template. The real
* `createRuntimeAdapters` runs; only the product-owned file is replaced, with
* what a product would write in it. 1105/02-03. The test drives the runtime
* through the capability the template hands the feature loaders, so dropping
* `files` from the composition's `capabilities` fails it.
*/
const selectPolicy = browserFilePolicyReference("session-file", "select-text");
const downloadPolicy = browserFilePolicyReference(
"session-download",
"bounded-generated-bin",
);
const policies: readonly BrowserFilePolicyProfile[] = [
{
reference: selectPolicy,
selection: {
policyId: "attachment-v1",
purpose: "attachment",
classification: "PERSONAL",
multiple: false,
maxCount: 1,
maxFileBytes: 8,
maxTotalBytes: 8,
allowEmpty: false,
accept: [{ mediaType: "text/plain", extensions: [".txt"] }],
},
},
{
reference: downloadPolicy,
download: {
strategy: "BOUNDED_OBJECT_URL",
mediaType: "application/octet-stream",
safeExtension: ".bin",
maxTransferBytes: 8,
maxBufferedBytes: 8,
integrity: "OPTIONAL",
},
},
];
const fixture = vi.hoisted(() => ({
files: undefined as
| ReturnType<typeof createSessionBrowserFileCapability>["files"]
| undefined,
/** What the template hands the installed features' loaders. */
featureCapabilities: undefined as Readonly<Record<string, unknown>> | undefined,
inputs: [] as HTMLInputElement[],
handoffs: 0,
owner: undefined as
| Readonly<{ switchUser(subject: string): void }>
| undefined,
}));
function fileInput(): HTMLInputElement {
const input = document.createElement("input");
input.type = "file";
input.setAttribute("aria-label", "Attachment");
Object.defineProperty(input, "click", { configurable: true, value: vi.fn() });
document.body.append(input);
fixture.inputs.push(input);
return input;
}
function externalOwner() {
const listeners = new Set<() => void>();
let subject = "user-a";
return {
readState: () => "authenticated",
readSubject: () => subject,
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
switchUser(next: string) {
subject = next;
for (const listener of listeners) listener();
},
};
}
/** The product-owned file, filled the way a product fills it. */
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner: () => {
const owner = externalOwner();
fixture.owner = owner;
return owner;
},
composeProduct: () => {
const browserFiles = createSessionBrowserFileCapability(() =>
createBrowserFileRuntime({
input: fileInput(),
policies,
limits: {
hardMaxPreviewBytes: 8,
hardMaxObjectUrlBytes: 8,
hardMaxTransferBytes: 16,
},
objectUrlApi: {
createObjectURL: () => "blob:session-download",
revokeObjectURL() {},
},
download: {
host: {
handoff() {
fixture.handoffs += 1;
},
},
browserManagedCapabilities: {
resolve: () => ({
ok: false as const,
error: {
code: "POLICY_REJECTED" as const,
operation: "DOWNLOAD" as const,
retryable: false,
recovery: "NONE" as const,
},
}),
},
},
}),
);
fixture.files = browserFiles.files;
return {
capabilities: { files: browserFiles.files },
credentialProviders: {},
scopeParticipants: [browserFiles.scopeParticipant],
};
},
}));
/** Records the capabilities features receive; the loaders run unchanged. */
vi.mock("../../src/features/installed-feature-adapters.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-feature-adapters.ts")>();
return {
...original,
createInstalledFeatureLoaders(
...args: Parameters<typeof original.createInstalledFeatureLoaders>
) {
fixture.featureCapabilities = args[0] as unknown as Readonly<
Record<string, unknown>
>;
return original.createInstalledFeatureLoaders(...args);
},
};
});
let current: Awaited<ReturnType<typeof createRuntimeAdapters>> | undefined;
afterEach(() => {
current?.infrastructure.dispose();
current = undefined;
for (const input of fixture.inputs.splice(0)) input.remove();
fixture.files = undefined;
fixture.featureCapabilities = undefined;
fixture.handoffs = 0;
});
async function compose() {
current = await createRuntimeAdapters({
runtime: {
config: testRuntimeConfig({
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "external",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 0,
RELEASE_MANIFEST_URL: "/release-manifest.json",
CONFIG_SCHEMA_VERSION: "2.0",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
}),
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
},
release: {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
},
host: {},
});
const owner = fixture.owner;
if (!fixture.files || !owner) {
throw new Error("The product composition did not run");
}
// What a feature that lists `files` in `needs` is given.
const files = fixture.featureCapabilities?.files as
| SessionBrowserFiles
| undefined;
if (!files) throw new Error("Features did not receive the files capability");
return { adapters: current, files, owner };
}
async function selectOne(
runtime: ReturnType<NonNullable<typeof fixture.files>["current"]>,
name: string,
) {
const pending = runtime.baselinePicker.select({ policy: selectPolicy });
const input = fixture.inputs.at(-1)!;
Object.defineProperty(input, "files", {
configurable: true,
value: [new File(["text"], name, { type: "text/plain", lastModified: 1 })],
});
input.dispatchEvent(new Event("change"));
return await pending;
}
describe("a session-scoped browser file runtime (2026-11-03 02-01)", () => {
it("closes the previous user's files and downloads on an account switch and serves the next session a new runtime", async () => {
const { adapters, files, owner } = await compose();
const previous = files.current();
const selected = await selectOne(previous, "user-a.txt");
if (!selected.ok || selected.value.kind !== "SELECTED") {
throw new Error(`The first selection failed: ${JSON.stringify(selected)}`);
}
const ref: LocalFileRef = selected.value.files[0]!.ref;
let producing!: () => void;
const started = new Promise<void>((resolve) => {
producing = resolve;
});
const download = previous.downloads.deliver({
policy: downloadPolicy,
source: {
kind: "GENERATED",
bytes: {
byteLength: 1,
async *stream() {
producing();
await new Promise(() => {});
yield { ok: true as const, value: new Uint8Array([1]) };
},
},
},
suggestedFileName: "user-a-report",
maxTransferBytes: 8,
maxBufferedBytes: 8,
signal: new AbortController().signal,
onProgress() {},
});
await started;
owner.switchUser("user-b");
await vi.waitFor(() =>
expect(adapters.infrastructure.serverStateScope.getPhase()).toBe("READY"),
);
expect(
await previous.content.readRange({
ref,
offset: 0,
length: 1,
signal: new AbortController().signal,
}),
).toMatchObject({ ok: false, error: { code: "UNAVAILABLE" } });
expect(await download).toMatchObject({
ok: false,
error: { code: "ABORTED", operation: "DOWNLOAD" },
});
expect(fixture.handoffs).toBe(0);
const next = files.current();
expect(next).not.toBe(previous);
expect(await selectOne(next, "user-b.txt")).toMatchObject({
ok: true,
value: { kind: "SELECTED" },
});
});
});