Files
clean-architecture-frontend…/src/bootstrap/runtime-adapters.ts
T
DongHyeonka ddf411e4e2 fix(bootstrap): ANONYMOUS 프로필 요청을 세션 상태와 상관없이 보낸다 (09-01)
조립 루트의 attachCredentials가 operation의 인증 프로필을 보지 않고
세션 상태만 본다. 그래서 auth: "none" operation(ANONYMOUS 프로필)이
로그아웃이면 UNAUTHENTICATED, 로그인이면 세션 헤더가 붙어
CREDENTIAL_HEADER_NOT_ALLOWED로 거절되고, 외부 owner가 없으면
CREDENTIAL_OWNER_UNAVAILABLE로 끝난다. 어느 상태에서도 fetch가 0회다.

scope 확인 바로 다음에 INSTALLED_REST_AUTH_PROFILES에서
operation.authProfileId의 transport를 읽고, ANONYMOUS면 세션을 보지
않고 빈 헤더로 READY를 돌려준다. executor에 넘기는 레지스트리와 같은
값을 같은 객체 안에서 읽는다. 그 밖의 프로필은 기존 경로 그대로다.

버린 대안:
- executor(http-execution-v3.ts)가 ANONYMOUS면 attachCredentials를
  부르지 않게 하기. adapter 공개 동작이 바뀐다. 지금 executor는 익명
  프로필에도 협력자를 부르고 헤더를 내면 거절하며, 이 동작을 고정한
  계약 테스트가 있다. 세션을 아는 쪽은 조립 루트라서 판단도 거기 둔다.
- 리뷰 R1(attachCredentials를 createCredentialAttacher로 꺼내기).
  구조 변경이라 이번 범위를 넘는다. 09-02에서 함께 다룬다. 새 테스트가
  실제 createRuntimeAdapters를 거치므로 그때도 그대로 쓸 수 있다.
- 새 케이스를 tests/unit/runtime-adapters.test.ts에 넣기. vi.mock은
  파일 단위라 설치된 계약 묶음을 바꾸면 그 파일의 기존 테스트에도
  번진다. 그래서 runtime-adapters-auth-profile.test.ts를 따로 만들었다.

위험·한계:
- 로그인 상태의 익명 호출에 토큰이 붙지 않고 owner에게도 가지 않는다.
  ANONYMOUS 프로필이 자격증명 헤더를 하나도 허용하지 않으니 의도한
  결과다. 인증 통합이 실패한 상태에서도 공개 읽기는 나간다.
- scope fence는 익명 분기보다 먼저 본다. 모르는 프로필 id는 executor가
  attachCredentials 전에 UNKNOWN_AUTH_PROFILE로 막는다.
- 브라우저 화면은 보지 않았다. test:sample-removal도 돌리지 않았다.
  새 테스트는 템플릿 소유 fixture와 src/contracts의 프로필만 쓴다.
- tech-log 제품 쪽 우회는 다음 동기화 때 지운다.

검증:
- RED(수정 전): 새 테스트 11건 중 5건 실패. ANONYMOUS 4개 상태가
  expected 'UNAUTHENTICATED' to be 'SUCCESS'(demo 로그아웃),
  expected 'AUTH_INTEGRATION_FAILURE' to be 'SUCCESS'(demo 로그인,
  외부 owner 로그인, owner 없음)로 실패. owner의 attachCredential이
  1회 불림. 인증 필요 프로필의 UNAUTHENTICATED, CREDENTIAL_OWNER_
  UNAVAILABLE 2건, fence 중 ABORTED_BY_SCOPE, 로그인 후 bearer 전송,
  익명 요청의 SCOPE_FENCED 6건은 수정 전후 모두 통과.
- GREEN: 새 테스트 11/11 통과.
- 회귀: runtime-adapters, http-execution-v3(unit·integration),
  auth-recovery, legacy-http-credential-authority, tests/features,
  tests/component, 영역 R1 목록 71 files / 485 tests 통과.
- tsc(tsconfig.app.json, tsconfig.test.json) 오류 0. 바꾼 두 파일
  eslint 통과. check:architecture(pnpm 대신 exec 대행) 통과,
  376 modules.

Refs: docs/reviews/2026-11-01-maturity-review/09-app-core.md 09-01
2026-11-01 19:07:05 +09:00

648 lines
22 KiB
TypeScript

import {
createDemoSessionAdapter,
createExternalAuthSessionAdapter,
createUnavailableSessionAdapter,
type ExternalSessionOwner,
} from "../adapters/auth/index.ts";
import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts";
import {
createContractHttpExecutor,
createHttpClient,
type HttpExecutionObservation,
type InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
import {
attemptBucket,
durationBucket,
statusGroup,
type DiagnosticRecordInput,
} from "../contracts/diagnostics.ts";
import type { TelemetryEventName } from "../contracts/telemetry.ts";
import {
createBrowserCrossContextInvalidationFromHost,
crossContextCacheEpochForRelease,
} from "../adapters/cross-context-invalidation/index.ts";
import {
createConditionalValidatorStore,
createQueryClient,
createServerStateScopeRuntime,
createTanStackCacheCoordinator,
} from "../adapters/query-cache/index.ts";
import { createBrowserStorageAdapter } from "../adapters/storage/index.ts";
import { createBrowserMutationIntentFactory } from "../adapters/platform/index.ts";
import {
createFeatureTelemetry,
createTelemetryAdapter,
createTelemetryCollector,
} from "../adapters/telemetry/index.ts";
import type { AuthSessionPort } from "../application/ports/auth-session-port.ts";
import type { ReleaseInfo } from "../application/ports/release-info-port.ts";
import {
createRestProviderProfile,
INSTALLED_REST_AUTH_PROFILES,
} from "../contracts/rest-profiles.ts";
import type { ClockPort } from "../application/ports/clock-port.ts";
import { createInstalledFeatureInputs } from "../features/installed-feature-adapters.ts";
import {
INVALIDATION_REGISTRY,
INVALIDATION_TOPIC_VERSIONS,
} from "../features/installed-feature-contracts.ts";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../features/installed-runtime-capabilities.ts";
import {
COMPILED_PRODUCT_FEATURE_IDS,
INSTALLED_PRODUCT_FEATURE_IDS,
} from "../features/installed-product-manifest.ts";
import {
activeProductFeatureIds,
resolveProductFeatures,
unknownProductFeatureOverrides,
} from "../contracts/product-features.ts";
import { describeRuntimeCapabilities } from "../contracts/runtime-capabilities.ts";
import {
fetchReleaseManifest,
type ReleaseManifest,
} from "./load-release-manifest.ts";
import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts";
import { createServerStateGenerationStore } from "./server-state-generation-store.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../features/installed-contract-contributions.ts";
import {
indexInvalidationRegistry,
indexInvalidationTopicVersions,
} from "../contracts/query-invalidation.ts";
type HttpClientDependencies = Parameters<typeof createHttpClient>[0];
/**
* 제품이 V2 전송을 쓰려면 채워야 하는 슬롯 네 개.
*
* 이 템플릿은 넷 다 비워서 출하한다. 기본값인
* `contracts/api-operations.ts`의 `API_OPERATIONS`는 빈 객체이고
* `adapters/http/resource-mapper.ts`의 `mapOperationPayload`는 항상
* `MAPPING_INVARIANT_REJECTED`를 반환한다. 그래서 **이 레포 상태 그대로는
* V2로 어떤 오퍼레이션도 실행되지 않는다** — 그건 결함이 아니라 제품이
* 채우는 자리다.
*
* V2는 V3를 그대로 되돌리는 롤백 경로가 아니다. 두 경로는 wire 형식이
* 다르다. V2는 `{ success, data, meta }` 봉투를 검증하고
* (`adapters/http/schema-registry.ts`), V3는 봉투 없는 DTO 자체를 검증한다.
* 그래서 네 슬롯을 모두 주입해도 같은 백엔드로 V2로 되돌리면 모든 응답이
* `ENVELOPE_MISMATCH`다. V2로 되돌리려면 슬롯 주입과 함께 서버도 V2 봉투로
* 응답해야 한다.
* V3(`createContractHttpExecutor`)는 설치된 feature 계약에서 오퍼레이션을
* 받으므로 이 슬롯과 무관하게 동작한다.
*/
export type RuntimeHttpContract = Pick<
HttpClientDependencies,
"getOperation" | "validatePayload" | "validateRequest" | "mapPayload"
>;
type RuntimeHttpContext = Readonly<{
runtime: RuntimeConfigLoadResult;
authSession: AuthSessionPort;
fetcher?: typeof fetch;
clock?: ClockPort;
scheduler?: HttpClientDependencies["scheduler"];
diagnostics?: HttpClientDependencies["diagnostics"];
telemetry?: HttpClientDependencies["telemetry"];
}>;
export type RuntimeAdaptersContext = Readonly<{
runtime: RuntimeConfigLoadResult;
release: Readonly<ReleaseManifest>;
host?: Record<string, unknown>;
fetcher?: typeof fetch;
}>;
/**
* §5.2. The composition root is where a manifest becomes release info. A V2
* manifest states contract identity as a verified contract set and a V1
* manifest as the legacy scalar; the application layer sees one shape and never
* branches on the schema version to find the identity.
*/
function toReleaseInfo(manifest: Readonly<ReleaseManifest>): ReleaseInfo {
const { contractSet, legacyApiContractVersion, ...rest } =
structuredClone(manifest);
return Object.freeze({
...rest,
...(legacyApiContractVersion === undefined
? {}
: { apiContractVersion: legacyApiContractVersion }),
...(contractSet === null
? {}
: { contractSetDigest: contractSet.setDigest }),
});
}
const EXTERNAL_OWNER_METHODS = Object.freeze([
"readState",
"readSubject",
"subscribe",
"beginSignIn",
"signOut",
"attachCredential",
"recoverSession",
"notifyUnauthenticated",
] as const);
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object";
}
function externalOwnerFrom(
host: Record<string, unknown>,
): ExternalSessionOwner | null {
const candidate = host.__CA_FRONTEND_AUTH_OWNER__;
if (!isRecord(candidate)) return null;
return EXTERNAL_OWNER_METHODS.every(
(name) => typeof candidate[name] === "function",
)
? (candidate as ExternalSessionOwner)
: null;
}
function hostValue(
host: Record<string, unknown>,
property: string,
): unknown {
try {
return Reflect.get(host, property);
} catch {
return undefined;
}
}
function storageOrUndefined(value: unknown): Storage | undefined {
if (!value || typeof value !== "object") return undefined;
const candidate = value as Record<string, unknown>;
try {
return ["getItem", "setItem", "removeItem"].every(
(method) => typeof Reflect.get(candidate, method) === "function",
)
? (value as Storage)
: undefined;
} catch {
return undefined;
}
}
/**
* Runtime-aware transport factory. Feature gateway composition calls this
* factory when a registered API capability is installed.
*/
export function createRuntimeHttpClient(
context: RuntimeHttpContext,
contract: RuntimeHttpContract = {},
) {
return createHttpClient({
baseUrl: context.runtime.config.API_BASE_URL,
timeoutMs: context.runtime.config.REQUEST_TIMEOUT_MS,
maxRetryAttempts: context.runtime.config.MAX_RETRY_ATTEMPTS,
authSession: context.authSession,
providerProfile: createRestProviderProfile(
"PRIMARY_API",
context.runtime.config.API_BASE_URL,
["omit"],
),
fetcher: context.fetcher,
clock: context.clock,
scheduler: context.scheduler,
diagnostics: context.diagnostics,
telemetry: context.telemetry,
...contract,
});
}
/**
* VD-07. Exactly one diagnostic per logical V3 execution and exactly one
* `api.request.failed` telemetry event per terminal non-abort failure.
*
* The projection is closed: only registered context keys and bucketed values
* reach the sinks, and neither sink can change the HTTP outcome, because the
* caller invokes this inside the executor's isolated observation boundary.
*/
export function createHttpObservationProjector(
sinks: Readonly<{
diagnostics: Readonly<{ record(input: DiagnosticRecordInput): void }>;
telemetry: Readonly<{
emit(
eventName: TelemetryEventName,
attributes: Record<string, unknown>,
): void;
}>;
}>,
): (observation: HttpExecutionObservation) => void {
return (observation) => {
const safeAttributes = {
route_id: observation.routeId,
operation_id: observation.operationId,
error_kind: observation.errorKind,
http_status_group: statusGroup(observation.status),
attempt_count_bucket: attemptBucket(observation.attemptCount),
duration_bucket: durationBucket(observation.durationMs),
};
try {
sinks.diagnostics.record({
level: observation.outcome === "SUCCESS" ? "info" : "warn",
eventId: "http.request.completed",
context: {
...safeAttributes,
operation: observation.diagnosticsOperation,
outcome: observation.outcome,
// 03-03. Request-scoped: diagnostics may carry it, telemetry never.
...(observation.correlationId === undefined
? {}
: { correlation_id: observation.correlationId }),
},
});
} catch {
// Diagnostics cannot change a contract execution outcome.
}
if (!isTerminalNonAbortFailure(observation)) return;
try {
sinks.telemetry.emit("api.request.failed", { ...safeAttributes });
} catch {
// Telemetry cannot change a contract execution outcome.
}
};
}
/**
* LIVE-05. Cancellation and scope fencing are caller- or generation-owned
* decisions, not API failures: they produce a diagnostic once and never
* `api.request.failed`.
*
* A `DEADLINE` owner is the opposite case. Nobody asked for it — the API did
* not answer inside the contract's own budget — so excluding it would hide
* exactly the outage this event exists to report.
*/
const CALLER_OWNED_CANCELLATION: ReadonlySet<string> = new Set([
"CALLER",
"ROUTE_TRANSITION",
"SCOPE_FENCE",
"APPLICATION_SHUTDOWN",
]);
function isTerminalNonAbortFailure(
observation: HttpExecutionObservation,
): boolean {
if (observation.outcome === "SUCCESS") return false;
if (observation.outcome === "CANCELLED") return false;
// 03-07. No credential, nothing sent: a client state, not an API failure.
if (
observation.outcome === "UNAUTHENTICATED" &&
observation.status === undefined
) {
return false;
}
if (
observation.cancellationOwner !== undefined &&
CALLER_OWNED_CANCELLATION.has(observation.cancellationOwner)
) {
return false;
}
return !(
observation.outcome === "CONTRACT_VIOLATION" &&
observation.errorKind === "SCOPE_FENCED"
);
}
export async function createRuntimeAdapters(
context: RuntimeAdaptersContext,
) {
const host =
context.host ?? (globalThis as unknown as Record<string, unknown>);
const config = context.runtime.config;
const mutationIntentFactory = createBrowserMutationIntentFactory();
const externalOwner = externalOwnerFrom(host);
const authSession =
config.AUTH_MODE === "demo"
? createDemoSessionAdapter()
: externalOwner
? createExternalAuthSessionAdapter(externalOwner)
: createUnavailableSessionAdapter();
const diagnostics = createDiagnosticsAdapter();
// Q-6.9-4. Both telemetry ports post through one collector transport: one
// send-rate window, one page-exit flush and one fetch policy per endpoint.
const telemetryCollector =
config.TELEMETRY_ENABLED && config.TELEMETRY_ENDPOINT
? createTelemetryCollector({
endpoint: config.TELEMETRY_ENDPOINT,
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
release: {
buildId: context.release.buildId,
releaseId: context.release.releaseId,
},
})
: undefined;
const telemetry = createTelemetryAdapter({
enabled: config.TELEMETRY_ENABLED,
endpoint: config.TELEMETRY_ENDPOINT,
fetcher: context.fetcher,
...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }),
onDrop(event) {
const attributes =
event.attributes && typeof event.attributes === "object"
? event.attributes
: {};
diagnostics.record({
level: "warn",
eventId: "telemetry.delivery.dropped",
context: attributes,
});
},
});
const invalidationIndex = indexInvalidationRegistry(INVALIDATION_REGISTRY);
const invalidationTopicVersions = indexInvalidationTopicVersions(
INVALIDATION_REGISTRY,
INVALIDATION_TOPIC_VERSIONS,
);
const conditionalValidators = createConditionalValidatorStore();
const serverStateGeneration = createServerStateGenerationStore(() => {
const queryClient = createQueryClient({ diagnostics });
const crossContextInvalidation =
createBrowserCrossContextInvalidationFromHost({
...(context.host === undefined ? {} : { host: context.host }),
cacheEpoch: crossContextCacheEpochForRelease(
context.release.releaseId,
),
topics: [...invalidationTopicVersions].map(([topic, topicVersion]) =>
Object.freeze({
topic,
topicVersion,
}),
),
observe(observation) {
if (
observation.outcome !== "FAILED" &&
observation.outcome !== "DEGRADED"
) {
return;
}
diagnostics.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation: observation.operation,
outcome: observation.outcome,
reason: observation.reason,
},
});
},
});
const queryInvalidation = createTanStackCacheCoordinator({
queryClient,
invalidationIndex,
topicVersions: invalidationTopicVersions,
crossContext: crossContextInvalidation,
diagnostics,
});
return Object.freeze({
queryClient,
queryInvalidation,
crossContextStatus: () =>
crossContextInvalidation?.getStatus() ?? "DEGRADED_LOCAL_ONLY",
});
});
const serverStateScope = createServerStateScopeRuntime({
session: authSession,
diagnostics,
queryInvalidation: {
resetLocal: () => serverStateGeneration.resetCurrent(),
},
participants: [
{
order: 4,
label: "conditional-validators",
close: () => conditionalValidators.clear(),
},
],
activateNextGeneration: () => serverStateGeneration.activateNext(),
});
const storage = createBrowserStorageAdapter({
localStorage: storageOrUndefined(hostValue(host, "localStorage")),
sessionStorage: storageOrUndefined(
hostValue(host, "sessionStorage"),
),
diagnostics,
});
const releaseInfo = Object.freeze({
async getCurrent() {
return toReleaseInfo(context.release);
},
async refresh() {
return toReleaseInfo(
await fetchReleaseManifest(config.RELEASE_MANIFEST_URL, {
fetcher: context.fetcher,
buildId: context.release.buildId,
releaseId: context.release.releaseId,
}),
);
},
});
const runtimeCapabilities = Object.freeze({
getSnapshot() {
return describeRuntimeCapabilities(
INSTALLED_RUNTIME_CAPABILITIES,
config.CAPABILITY_OVERRIDES,
);
},
});
/**
* §3.5. The two halves of the feature answer meet here and nowhere else: the
* manifest says what the build compiled in, the runtime document says what is
* switched off. Neither can add to the other.
*/
const productFeatureStatuses = resolveProductFeatures(
COMPILED_PRODUCT_FEATURE_IDS,
INSTALLED_PRODUCT_FEATURE_IDS,
config.FEATURE_OVERRIDES,
);
const activeFeatureIds = new Set(
activeProductFeatureIds(productFeatureStatuses),
);
for (const key of unknownProductFeatureOverrides(
COMPILED_PRODUCT_FEATURE_IDS,
config.FEATURE_OVERRIDES,
)) {
diagnostics.record({
level: "warn",
eventId: "feature.override.unknown",
context: { feature_override_key: key },
});
}
const productFeatures = Object.freeze({
getSnapshot() {
return productFeatureStatuses;
},
isActive(featureId: string) {
return activeFeatureIds.has(featureId);
},
});
const navigation = Object.freeze({
reload() {
const location = host.location;
if (!isRecord(location) || typeof location.reload !== "function") {
throw new Error("Browser reload is unavailable");
}
location.reload();
},
});
const contractHttp = createContractHttpExecutor({
baseUrl: config.API_BASE_URL,
maxRetryAttempts: config.MAX_RETRY_ATTEMPTS,
// §6.1. `REQUEST_TIMEOUT_MS` was declared, validated and then dropped on the
// floor here: every V3 operation ran on its contract's own 10s deadline and
// the deployment dial did nothing. It is a ceiling, so it can tighten an
// operation but never loosen one.
requestDeadlineCeilingMs: config.REQUEST_TIMEOUT_MS,
fetcher: context.fetcher,
// §7.7. The installed registry owns Fetch credentials and the exact
// credential-header sets; this collaborator only supplies proof headers.
authProfiles: INSTALLED_REST_AUTH_PROFILES,
async attachCredentials(operation, authContext) {
if (serverStateScope.getPhase() !== "READY") {
return Object.freeze({ kind: "SCOPE_FENCED" as const });
}
// 09-01. The operation's installed profile decides first, the session
// second. An ANONYMOUS profile admits no credential header at all, so it
// goes out bare in every session state and never reaches the owner. Every
// other profile still needs a session and never downgrades to anonymous.
if (
INSTALLED_REST_AUTH_PROFILES.get(operation.authProfileId)?.transport ===
"ANONYMOUS"
) {
return Object.freeze({ kind: "READY" as const, headers: {} });
}
const state = authSession.getState();
if (state === "integration-failed") {
return Object.freeze({ kind: "UNAVAILABLE" as const });
}
if (state !== "authenticated") {
return Object.freeze({ kind: "UNAUTHENTICATED" as const });
}
try {
const patch = await authSession.credentialPatch(
{
origin: new URL(config.API_BASE_URL).origin,
method: operation.method,
operationId: operation.operationId,
},
authContext,
);
if (serverStateScope.getPhase() !== "READY") {
return Object.freeze({ kind: "SCOPE_FENCED" as const });
}
return Object.freeze({
kind: "READY" as const,
headers: patch.headers,
});
} catch {
return Object.freeze({ kind: "UNAVAILABLE" as const });
}
},
observe: createHttpObservationProjector({ diagnostics, telemetry }),
});
const contractOperations: InstalledHttpOperationExecutor = Object.freeze({
async execute(operation, input, executionContext) {
const installed =
COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(
operation.contract.operationId,
);
if (!installed) {
return Object.freeze({
kind: "CONTRACT_VIOLATION" as const,
effect: "NOT_STARTED" as const,
violation: Object.freeze({
kind: "FINAL_REQUEST_INVARIANT_FAILED" as const,
operation: "REQUEST" as const,
}),
});
}
// composeContractContributions deliberately snapshots every installed
// contract. Runtime authority is therefore the validated registry entry,
// not object identity with the feature-owned source declaration.
const executableContract = installed as typeof operation;
const outcome = await contractHttp.execute(executableContract, input, {
routeId: executionContext.routeId,
scope: serverStateScope.getSnapshot(),
...(executionContext.signal === undefined
? {}
: { signal: executionContext.signal }),
...(executionContext.intent === undefined
? {}
: { intent: executionContext.intent }),
...(executionContext.execution === undefined
? {}
: { execution: executionContext.execution }),
});
// R-3.2. Only a server 401 is a session verdict. A request refused before
// dispatch for lack of a credential carries no response metadata; telling
// the owner would overwrite a recovering session and re-fence the scope.
if (outcome.kind === "UNAUTHENTICATED" && outcome.metadata !== undefined) {
authSession.onUnauthenticated();
}
return outcome;
},
});
// Spec §24–§27. Feature-owned events go through the bounded, fail-open
// pipeline behind the provider-neutral port; features never see the sink.
const featureTelemetry = createFeatureTelemetry({
enabled: config.TELEMETRY_ENABLED,
...(config.TELEMETRY_ENDPOINT === undefined
? {}
: { endpoint: config.TELEMETRY_ENDPOINT }),
...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }),
...(telemetryCollector === undefined ? {} : { collector: telemetryCollector }),
});
// Each installed contribution receives only the capabilities it declares.
// 09-05. `indexedDb` is not built here: IndexedDB is an opt-in reference
// runtime (`productionComposition: false`). Installing a feature that needs
// it makes this object fail the app typecheck until the product adds
// `indexedDb`, built as in recipes/frontend-capabilities/
// indexeddb-feature-capability.ts.
const featureCapabilities = Object.freeze({
http: contractOperations,
telemetry: featureTelemetry,
});
const featureInputs = createInstalledFeatureInputs(featureCapabilities, [
...activeFeatureIds,
]);
return Object.freeze({
outputPorts: Object.freeze({
session: authSession,
preferences: storage,
diagnostics,
telemetry,
releaseInfo,
runtimeCapabilities,
productFeatures,
navigation,
}),
infrastructure: Object.freeze({
get queryClient() {
return serverStateGeneration.getSnapshot().queryClient;
},
get queryInvalidation() {
return serverStateGeneration.getSnapshot().queryInvalidation;
},
serverStateGeneration,
serverStateScope,
mutationIntentFactory,
conditionalValidators,
crossContextInvalidationStatus: () =>
serverStateGeneration.getSnapshot().crossContextStatus(),
dispose() {
// N-04. Telemetry is torn down first: it must stop scheduling and
// delivering before the diagnostics and state dependencies it observes
// are destroyed.
telemetry.dispose();
featureTelemetry.dispose();
conditionalValidators.clear();
serverStateScope.dispose();
serverStateGeneration.dispose();
},
}),
featureInputs,
});
}