fix(features): check declared needs and show the IndexedDB capability assembly (09-05)
A missing capability reached the feature factory as an anonymous TypeError. The composer now names the feature and the capability, and the IndexedDB provider example moves from a browser spec into an opt-in recipe with a test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
30cf71b249
commit
bc7c46b2d5
@@ -138,6 +138,17 @@ browser-capability test composes the feature over the real
|
||||
`createIndexedDbRuntime` and native IndexedDB, proving that this seam is not
|
||||
limited to an in-memory contract fixture.
|
||||
|
||||
The bootstrap does not build `indexedDb`: IndexedDB is an opt-in reference
|
||||
runtime (`productionComposition: false` in
|
||||
`config/recipes/frontend-capability-recipes.json`). The composition example is
|
||||
`recipes/frontend-capabilities/indexeddb-feature-capability.ts`
|
||||
(`createLocalDraftIndexedDbCapability`, exercised by
|
||||
`tests/recipes/indexeddb-feature-capability.test.ts`). A product that installs a
|
||||
feature with `needs: ["indexedDb"]` copies it and adds `indexedDb` to the feature
|
||||
capabilities in `src/bootstrap/runtime-adapters.ts`. Until it does, that object
|
||||
fails the app typecheck, and `composeFeatureAdapterInputs()` rejects the
|
||||
composition with `feature <id> needs indexedDb, which the host did not provide`.
|
||||
|
||||
## Presentation consumer surface
|
||||
|
||||
`ApplicationProvider` remains the composition root for presentation, but new
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import {
|
||||
createIndexedDbRuntime,
|
||||
type IndexedDbRuntimeDependencies,
|
||||
} from "../../src/adapters/storage/indexeddb/index.ts";
|
||||
import type { IndexedDbDatasetScope } from "../../src/application/ports/browser-file-storage/index.ts";
|
||||
import {
|
||||
createIndexedDbRepositoryProvider,
|
||||
type IndexedDbRepositoryProvider,
|
||||
} from "../../src/features/feature-adapter-contribution.ts";
|
||||
import type {} from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts";
|
||||
import type { LocalDraft } from "../../src/features/local-draft-feature/domain/local-draft.ts";
|
||||
|
||||
type LocalDraftRuntimeDependencies = IndexedDbRuntimeDependencies<
|
||||
LocalDraft,
|
||||
LocalDraft,
|
||||
never
|
||||
>;
|
||||
type LocalDraftRuntime = ReturnType<
|
||||
typeof createIndexedDbRuntime<LocalDraft, LocalDraft, never>
|
||||
>;
|
||||
|
||||
/**
|
||||
* 09-05. How a host builds the `indexedDb` feature capability, shown for the
|
||||
* local-draft sample. IndexedDB is an opt-in reference runtime
|
||||
* (`offline-indexeddb` in config/recipes/frontend-capability-recipes.json,
|
||||
* `productionComposition: false`), so `src/bootstrap/runtime-adapters.ts` does
|
||||
* not build it. A product that installs a feature with `needs: ["indexedDb"]`
|
||||
* copies this into its composition, replaces the codec, migrations and storage
|
||||
* policy with its own decisions, and adds `indexedDb` to the feature
|
||||
* capabilities there; until it does, that object fails the app typecheck and
|
||||
* `composeFeatureAdapterInputs` names the missing capability.
|
||||
*
|
||||
* The scope tokens come from the product's storage registry and the lifecycle
|
||||
* authority from its composition root; neither is invented here.
|
||||
*/
|
||||
export function createLocalDraftIndexedDbCapability(
|
||||
options: Readonly<{
|
||||
// The sample keeps drafts across sign-out, so its dataset is origin-shared.
|
||||
scope: IndexedDbDatasetScope & Readonly<{ accountScope: "ORIGIN_SHARED" }>;
|
||||
authorizeLifecycle: LocalDraftRuntimeDependencies["authorizeLifecycle"];
|
||||
/** Defaults to the browser's `indexedDB`; tests pass an in-memory one. */
|
||||
factory?: IDBFactory;
|
||||
}>,
|
||||
): Readonly<{
|
||||
indexedDb: IndexedDbRepositoryProvider;
|
||||
/** Opens (and migrates) the database; repository calls fail until it has. */
|
||||
open(signal?: AbortSignal): ReturnType<LocalDraftRuntime["open"]>;
|
||||
close(): void;
|
||||
}> {
|
||||
const runtime = createIndexedDbRuntime<LocalDraft, LocalDraft, never>({
|
||||
...(options.factory === undefined ? {} : { factory: options.factory }),
|
||||
scope: options.scope,
|
||||
storagePolicy: Object.freeze({
|
||||
owner: "local-draft-feature",
|
||||
namespace: "local-draft",
|
||||
classification: "INTERNAL",
|
||||
authority: "LOCAL_FIRST",
|
||||
accountScope: "ORIGIN_SHARED",
|
||||
retention: Object.freeze({ kind: "EXPLICIT_DELETE" }),
|
||||
softBudgetBytes: 1_000_000,
|
||||
hardBudgetBytes: 2_000_000,
|
||||
evictionPriority: "USER_AUTHORED",
|
||||
logoutAction: "KEEP_ORIGIN_SHARED",
|
||||
accountDeletionAction: "KEEP_ORIGIN_SHARED",
|
||||
pressureAction: "RETAIN",
|
||||
unavailableFallback: "READ_ONLY",
|
||||
}),
|
||||
schemaVersion: 1,
|
||||
recordStore: "records",
|
||||
governanceStore: "governance",
|
||||
retentionStore: "retention",
|
||||
retentionEligibilityIndex: "by-eligibility",
|
||||
lifecycleMetadataStores: [],
|
||||
idempotencyStore: "receipts",
|
||||
idempotencyExpiryIndex: "by-expiry",
|
||||
receiptRetentionMs: 60_000,
|
||||
maxIdempotencyReceipts: 100,
|
||||
migrations: [
|
||||
{
|
||||
id: "local-draft-schema-v1",
|
||||
fromVersion: 0,
|
||||
toVersion: 1,
|
||||
operations: [
|
||||
{ kind: "CREATE_STORE", name: "governance", keyPath: "bindingKey" },
|
||||
{
|
||||
kind: "CREATE_STORE",
|
||||
name: "retention",
|
||||
keyPath: "recordKey",
|
||||
indexes: [{ name: "by-eligibility", keyPath: "eligibleAtEpochMs" }],
|
||||
},
|
||||
{ kind: "CREATE_STORE", name: "records", keyPath: "key" },
|
||||
{
|
||||
kind: "CREATE_STORE",
|
||||
name: "receipts",
|
||||
keyPath: "idempotencyKey",
|
||||
indexes: [{ name: "by-expiry", keyPath: "expiresAtEpochMs" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
codec: {
|
||||
currentVersion: 1,
|
||||
encode: (value) => ({ ok: true, value }),
|
||||
measureStoredBytes: (value) =>
|
||||
new TextEncoder().encode(JSON.stringify(value)).byteLength,
|
||||
decode: (version, value) => {
|
||||
if (version !== 1 || value === null || typeof value !== "object") {
|
||||
return { ok: false };
|
||||
}
|
||||
const candidate = value as Partial<LocalDraft>;
|
||||
return typeof candidate.draftId === "string" &&
|
||||
typeof candidate.title === "string" &&
|
||||
typeof candidate.body === "string"
|
||||
? { ok: true, value: candidate as LocalDraft }
|
||||
: { ok: false };
|
||||
},
|
||||
fingerprint: async (value) => {
|
||||
const bytes = new TextEncoder().encode(
|
||||
JSON.stringify([value.draftId, value.title, value.body]),
|
||||
);
|
||||
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
||||
return Array.from(new Uint8Array(digest), (byte) =>
|
||||
byte.toString(16).padStart(2, "0"),
|
||||
).join("");
|
||||
},
|
||||
},
|
||||
queryPolicy: { plan: () => ({ limit: 1 }) },
|
||||
authorizeLifecycle: options.authorizeLifecycle,
|
||||
});
|
||||
return Object.freeze({
|
||||
indexedDb: createIndexedDbRepositoryProvider(
|
||||
Object.freeze({ "local-draft": runtime }),
|
||||
),
|
||||
open: (signal?: AbortSignal) => runtime.open(signal),
|
||||
close: () => runtime.close(),
|
||||
});
|
||||
}
|
||||
@@ -31,6 +31,8 @@ const runtimePaths = [
|
||||
"src/adapters/storage/opfs",
|
||||
"tests/browser-capabilities",
|
||||
"tests/fixtures/browser-file-storage-boundaries",
|
||||
// The composition example of this runtime goes with it.
|
||||
"recipes/frontend-capabilities/indexeddb-feature-capability.ts",
|
||||
] as const;
|
||||
const runtimeSourceRoots = runtimePaths.filter((entry) =>
|
||||
entry.startsWith("src/"),
|
||||
|
||||
@@ -557,6 +557,11 @@ export async function createRuntimeAdapters(
|
||||
...(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,
|
||||
|
||||
@@ -174,6 +174,20 @@ export function composeFeatureAdapterInputs<
|
||||
}
|
||||
seen.add(contribution.featureId);
|
||||
if (!enabled.has(contribution.featureId)) continue;
|
||||
// 09-05. The context type already asks for every declared need, but a
|
||||
// host that widens it (or JavaScript) used to reach the feature's factory
|
||||
// and fail there as an anonymous TypeError.
|
||||
const provided = context as Readonly<
|
||||
Partial<Record<FeaturePlatformCapabilityId, unknown>>
|
||||
>;
|
||||
const missing = contribution.needs.find(
|
||||
(need) => provided[need] === undefined,
|
||||
);
|
||||
if (missing !== undefined) {
|
||||
throw new TypeError(
|
||||
`feature ${contribution.featureId} needs ${missing}, which the host did not provide`,
|
||||
);
|
||||
}
|
||||
|
||||
const installed = invokeContribution(
|
||||
contribution as unknown as FeatureAdapterContribution<
|
||||
|
||||
@@ -140,6 +140,29 @@ describe("feature adapter composition", () => {
|
||||
).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",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeFeatureAdapterInputs } from "../../src/features/feature-adapter-contribution.ts";
|
||||
import { LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION } from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts";
|
||||
import { createLocalDraftIndexedDbCapability } from "../../recipes/frontend-capabilities/indexeddb-feature-capability.ts";
|
||||
import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts";
|
||||
|
||||
describe("IndexedDB feature capability recipe (09-05)", () => {
|
||||
it("composes local-draft over the recipe's IndexedDB capability", async () => {
|
||||
const memory = new MemoryIndexedDbFactory();
|
||||
const capability = createLocalDraftIndexedDbCapability({
|
||||
scope: Object.freeze({
|
||||
authorityToken: "a1b2c3d4e5f60718293a4b5c6d7e8f90",
|
||||
namespaceToken: "n1b2c3d4e5f60718293a4b5c6d7e8f90",
|
||||
partitionToken: "p1b2c3d4e5f60718293a4b5c6d7e8f90",
|
||||
accountScope: "ORIGIN_SHARED" as const,
|
||||
}),
|
||||
authorizeLifecycle: () => ({ authorized: false }),
|
||||
factory: memory.factory,
|
||||
});
|
||||
try {
|
||||
await expect(capability.open()).resolves.toEqual({
|
||||
ok: true,
|
||||
value: undefined,
|
||||
});
|
||||
const inputs = composeFeatureAdapterInputs(
|
||||
Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const),
|
||||
Object.freeze(["local-draft"]),
|
||||
Object.freeze({ indexedDb: capability.indexedDb }),
|
||||
);
|
||||
const localDraft = inputs["local-draft"];
|
||||
if (!localDraft) throw new Error("local-draft input was not composed");
|
||||
const draft = Object.freeze({
|
||||
draftId: "draft-1",
|
||||
title: "Architecture notes",
|
||||
body: "Stored through the recipe capability.",
|
||||
});
|
||||
|
||||
await expect(
|
||||
localDraft.saveDraft({
|
||||
draft,
|
||||
expectedRevision: null,
|
||||
idempotencyKey: "local-draft-create-1",
|
||||
}),
|
||||
).resolves.toEqual({ ok: true, value: { revision: 1 } });
|
||||
await expect(localDraft.findDraft("draft-1")).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { draft, revision: 1 },
|
||||
});
|
||||
} finally {
|
||||
capability.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user