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 >; /** * 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; close(): void; }> { const runtime = createIndexedDbRuntime({ ...(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; 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(), }); }