chore: sync the frontend template from 5434760 to ebea300

Carries 21 template commits: the shared IndexedDB connection/transaction
kernel and the four runtimes moved onto it, the adapter barrel boundary and
the architecture rule that enforces it, the feature adapter contribution
model, `feature-http-binding`, the split of several oversized test files,
and the release identity now derived from the package name.

Product identity is unchanged. The three hard-coded `tech-log-frontend/…`
verifier ids are gone because the template derives them from the package
name and this package is `tech-log-frontend`.

Two decisions worth naming. The platform HTTP executor is the template's
verbatim — it now takes the installed contract so a feature's types flow
through the binding — and TechLog's four gateways, which address operations
by id, reach it through one adapter at the composition root instead of being
rewritten here. And the three derived CI baselines were recomputed from the
merged `config/ci/gates.json` rather than taken from either side: 94 command
definitions, 106 references, 141 artifacts, gate shape `629e5898…`. The
method was checked by first reproducing the pre-merge values from the
pre-merge file.

Verified here: types, lint, architecture, adapter inventory, CI contract,
design system, diagnostics, remediation ledger, browser security and build
all pass; 1789 unit, 152 component, 415 TechLog, 102 integration, 19
reference-feature, 17 recipe and 7 contract tests pass. Five gates stay
red and every one was reproduced at b297d65 first: `check:i18n`,
`check:registries`, `test:runtime-schema`, `verify:documentation` and
`test:sample-removal`.

Full decision record, including what was deliberately not carried and the
five open follow-ups, in `docs/operations/template-sync-2026-09-21.md`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-21 16:31:05 +09:00
co-authored by Claude Opus 5
parent b297d659f5
commit afde2b1da1
196 changed files with 21854 additions and 9992 deletions
+9
View File
@@ -0,0 +1,9 @@
export {
createAnonymousSessionAdapter,
createDemoSessionAdapter,
createExternalAuthSessionAdapter,
createUnavailableSessionAdapter,
DEMO_AUTHORIZATION_MARKER,
type DemoSessionAdapter,
type ExternalSessionOwner,
} from "./external-session-adapter.ts";
@@ -108,14 +108,12 @@ export class NativeInputFilePicker implements DisposableFilePicker {
const addInputEvent = options.input.addEventListener;
const removeInputEvent = options.input.removeEventListener;
const getInputAttribute = options.input.getAttribute;
const showPicker = options.input.showPicker;
const click = options.input.click;
if (
typeof addInputEvent !== "function" ||
typeof removeInputEvent !== "function" ||
typeof getInputAttribute !== "function" ||
(typeof showPicker !== "function" &&
typeof click !== "function")
typeof click !== "function"
) {
throw new TypeError("Native file input API is invalid.");
}
@@ -123,10 +121,11 @@ export class NativeInputFilePicker implements DisposableFilePicker {
add: addInputEvent.bind(options.input),
remove: removeInputEvent.bind(options.input),
getAttribute: getInputAttribute.bind(options.input),
activate:
typeof showPicker === "function"
? showPicker.bind(options.input)
: click.bind(options.input),
// The baseline <input type="file"> path intentionally uses click().
// showPicker() exists in multiple engines but is not a portable
// automation/event-interception contract. Enhanced native picking is a
// separate capability owned by EnhancedFilePicker.
activate: click.bind(options.input),
});
const windowHost = options.window ?? globalThis.window;
if (windowHost) {
@@ -8,7 +8,7 @@ import type {
BrowserRpcUnaryPort,
} from "../../application/ports/browser-rpc/index.ts";
import type { ClockPort } from "../../application/ports/clock-port.ts";
import type { Result } from "../../application/result.ts";
import type { Result } from "../../contracts/result.ts";
import {
installBrowserRpcContractBindings,
type InstalledBrowserRpcContractBindings,
@@ -4,12 +4,26 @@ import type {
ResumableUploadCheckpointStore,
PartitionDeleteOutcome,
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
import type { BrowserDataResult } from "../../../application/ports/browser-file-storage/shared.ts";
import type {
BrowserDataFailure,
BrowserDataFailureCode,
BrowserDataRecovery,
BrowserDataResult,
} from "../../../application/ports/browser-file-storage/shared.ts";
import { isBrowserDataFailureCode } from "../../../application/ports/browser-file-storage/shared.ts";
import {
browserDataFailure,
browserDataSuccess,
mapBrowserDataException,
} from "../../browser-file-storage/result.ts";
import { snapshotAbortTimers } from "../../platform/abortable-operation.ts";
import {
createIndexedDbConnection,
deleteIndexedDbDatabase,
openIndexedDbDatabase,
type IndexedDbTranslate,
} from "../../platform/indexeddb-connection.ts";
import { runIndexedDbTransaction } from "../../platform/indexeddb-transaction.ts";
import {
isResumableUploadCheckpoint,
SAFE_OPAQUE_ID,
@@ -20,6 +34,7 @@ const DATABASE_VERSION = 1;
const CHECKPOINT_STORE = "checkpoints";
const GOVERNANCE_STORE = "governance";
const GOVERNANCE_KEY = "scope-binding";
const OPERATION = "UPLOAD_RECONCILE";
const DEFAULT_BLOCKED_TIMEOUT_MS = 5_000;
/**
@@ -65,10 +80,94 @@ type ScopeBinding = Readonly<{
partitionToken: string;
}>;
type OpenFactory = (
name: string,
version?: number,
) => IDBOpenDBRequest;
/**
* `browserDataFailure` and `mapBrowserDataException` build a `Result`, while the
* kernel's `translate` contract wants the failure on its own. Both only ever
* build the failure arm, so the branch below is a narrowing, not a claim.
*/
function failureOf(result: BrowserDataResult<never>): BrowserDataFailure {
if (result.ok) {
throw new TypeError("A browser data failure was expected.");
}
return result.error;
}
function checkpointFailure(
code: BrowserDataFailureCode,
options: Readonly<{
retryable?: boolean;
recovery?: BrowserDataRecovery;
}> = {},
): BrowserDataFailure {
return failureOf(browserDataFailure(code, OPERATION, options));
}
function mappedFailure(error: unknown): BrowserDataFailure {
return failureOf(mapBrowserDataException(error, OPERATION));
}
/**
* The kernel keeps an admission's `detail` opaque, so a rejected scope binding
* carries its own failure through it and the guard hands that failure straight
* back. Any other shape would mean a second taxonomy grew beside this one.
*/
function admissionFailure(detail: unknown): BrowserDataFailure | null {
if (!detail || typeof detail !== "object") return null;
const record = detail as Record<string, unknown>;
return isBrowserDataFailureCode(record.code) && record.operation === OPERATION
? (detail as BrowserDataFailure)
: null;
}
/**
* BT-UP-03. The checkpoint store keeps its own failure table rather than the
* `mapIndexedDbException` the other three IndexedDB adapters share: the same
* native error is a different answer here (a `ConstraintError` recovers by
* REOPEN, a quota failure is retryable), and unifying the four tables is a
* separate change from moving the mechanics onto the kernel.
*/
const translate: IndexedDbTranslate<BrowserDataFailure> = (cause) => {
switch (cause.kind) {
case "NATIVE_EXCEPTION":
return mappedFailure(cause.error);
case "NO_VALUE_PRODUCED":
// Three adapters call this UNAVAILABLE. Here a checkpoint transaction
// that committed without producing a value read a row it could not turn
// into a checkpoint, so reconciling is the only way forward; retrying
// would read the same row again.
return checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" });
case "BLOCKED":
case "BLOCKED_DEADLINE":
return checkpointFailure("BLOCKED", {
retryable: true,
recovery: "RESUME",
});
case "CALLER_ABORT":
return checkpointFailure("ABORTED");
case "CLOSED":
// A closed handle is not the caller aborting: the upload can resume once
// a new store is built over the partition.
return checkpointFailure("UNAVAILABLE", { recovery: "RESUME" });
case "UPGRADE_REJECTED":
// The schema body's own throw is what the caller sees. A rejection with
// no detail can only come from a null `newVersion`, which an open request
// never reports.
return cause.detail === undefined
? checkpointFailure("MIGRATION_FAILED", { recovery: "READ_ONLY" })
: mappedFailure(cause.detail);
case "ADMISSION_REJECTED":
return (
admissionFailure(cause.detail) ??
checkpointFailure("POLICY_REJECTED", { recovery: "READ_ONLY" })
);
case "UNSUPPORTED":
return checkpointFailure("UNSUPPORTED", { recovery: "READ_ONLY" });
default: {
const exhaustive: never = cause;
return exhaustive;
}
}
};
export function uploadCheckpointDatabaseName(
scope: IndexedDbUploadCheckpointScope,
@@ -104,13 +203,19 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
) {
throw new TypeError("Upload checkpoint blocked timeout is invalid.");
}
const openFactory: OpenFactory | undefined = factory
? factory.open.bind(factory)
: undefined;
const deleteFactory =
factory && typeof factory.deleteDatabase === "function"
? factory.deleteDatabase.bind(factory)
: undefined;
// X-AUDIT-02. The timer callables are captured once, bound to their receiver,
// so replacing a global after composition cannot change how a blocked open or
// a blocked deletion already in flight is bounded. The kernel throws at
// construction if a positive deadline arrives without them.
const timers = snapshotAbortTimers({
setTimeout: (callback: () => void, milliseconds: number) =>
globalThis.setTimeout(callback, milliseconds),
clearTimeout: (handle: ReturnType<typeof globalThis.setTimeout>) => {
globalThis.clearTimeout(handle);
},
});
const canDelete =
factory !== undefined && typeof factory.deleteDatabase === "function";
const databaseName = uploadCheckpointDatabaseName(scope);
const pendingDeletions = pendingDeletionsFor(factory);
if (pendingDeletions.has(databaseName)) {
@@ -125,118 +230,60 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
schemaVersion: 1,
...scope,
});
let database: IDBDatabase | null = null;
let opening: Promise<BrowserDataResult<IDBDatabase>> | null = null;
let closed = false;
async function open(
signal?: AbortSignal,
): Promise<BrowserDataResult<IDBDatabase>> {
if (closed || !openFactory) {
return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
recovery: "RESUME",
});
}
if (signal?.aborted) {
return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
}
if (database) return browserDataSuccess(database);
if (!opening) {
opening = openAndBind().finally(() => {
opening = null;
});
}
const result = await opening;
if (signal?.aborted) {
return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
}
return result;
}
async function openAndBind(): Promise<BrowserDataResult<IDBDatabase>> {
let request: IDBOpenDBRequest;
try {
request = openFactory!(databaseName, DATABASE_VERSION);
} catch (error) {
return mapBrowserDataException(error, "UPLOAD_RECONCILE");
}
const opened = await new Promise<BrowserDataResult<IDBDatabase>>(
(resolve) => {
let settled = false;
let blockedTimer: ReturnType<typeof setTimeout> | undefined;
const finish = (result: BrowserDataResult<IDBDatabase>) => {
if (settled) {
if (result.ok) result.value.close();
return;
}
settled = true;
if (blockedTimer) clearTimeout(blockedTimer);
resolve(result);
};
request.onupgradeneeded = () => {
try {
const db = request.result;
if (!db.objectStoreNames.contains(CHECKPOINT_STORE)) {
db.createObjectStore(CHECKPOINT_STORE, {
keyPath: "uploadKey",
});
}
if (!db.objectStoreNames.contains(GOVERNANCE_STORE)) {
db.createObjectStore(GOVERNANCE_STORE, {
keyPath: "key",
});
}
} catch (error) {
try {
request.transaction?.abort();
} catch {
// The open request will surface the original closed failure.
}
finish(mapBrowserDataException(error, "UPLOAD_RECONCILE"));
}
};
request.onblocked = () => {
blockedTimer = setTimeout(() => {
finish(
browserDataFailure("BLOCKED", "UPLOAD_RECONCILE", {
retryable: true,
recovery: "RESUME",
}),
);
}, blockedTimeoutMs);
};
request.onerror = () =>
finish(
mapBrowserDataException(
request.error,
"UPLOAD_RECONCILE",
),
);
request.onsuccess = () => finish(browserDataSuccess(request.result));
},
);
if (!opened.ok) return opened;
if (closed) {
opened.value.close();
return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
recovery: "RESUME",
});
}
const bound = await bindScope(opened.value, expectedBinding);
if (!bound.ok) {
opened.value.close();
return bound;
}
opened.value.onversionchange = () => {
opened.value.close();
if (database === opened.value) database = null;
};
opened.value.onclose = () => {
if (database === opened.value) database = null;
};
database = opened.value;
return browserDataSuccess(opened.value);
}
/**
* The handle owns the cached connection, the single-flight open and the
* `versionchange`/`close` invalidation this file used to wire by hand. No
* `onVersionChange` callback is passed because closing the connection and
* dropping the cached handle — which the kernel already does — was this
* store's entire listener body; registering one inside `admit` instead would
* be overwritten when the handle adopts the connection.
*/
const connection = createIndexedDbConnection<BrowserDataFailure>({
translate,
open: (signal) =>
factory === undefined
? Promise.resolve(
browserDataFailure("UNAVAILABLE", OPERATION, {
recovery: "RESUME",
}),
)
: openIndexedDbDatabase<BrowserDataFailure>({
factory,
databaseName,
version: DATABASE_VERSION,
translate,
signal,
blockedTimeoutMs,
timers,
upgrade: ({ database }) => {
try {
if (!database.objectStoreNames.contains(CHECKPOINT_STORE)) {
database.createObjectStore(CHECKPOINT_STORE, {
keyPath: "uploadKey",
});
}
if (!database.objectStoreNames.contains(GOVERNANCE_STORE)) {
database.createObjectStore(GOVERNANCE_STORE, {
keyPath: "key",
});
}
} catch (error) {
return { kind: "REJECTED", detail: error };
}
return { kind: "APPLIED" };
},
// The binding runs before the caller ever sees the connection, so a
// partition bound to another scope can never serve a read. A
// rejected admission closes the connection inside the kernel.
admit: async (database) => {
const bound = await bindScope(database, expectedBinding);
return bound.ok
? { kind: "ADMIT" }
: { kind: "REJECT", detail: bound.error };
},
}),
});
const storeValue: ResumableUploadCheckpointStore = {
async read(
@@ -246,12 +293,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
BrowserDataResult<ResumableUploadCheckpoint | null>
> {
if (!SAFE_UPLOAD_KEY.test(uploadKey)) {
return browserDataFailure(
"INVALID_INPUT",
"UPLOAD_RECONCILE",
);
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await open(signal);
const opened = await connection.acquire(signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<
ResumableUploadCheckpoint | null
@@ -261,7 +305,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
signal,
(nativeStore, context) => {
const request = nativeStore.get(uploadKey);
request.onerror = () => context.nativeFailure(request.error);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (request.result === undefined) {
context.succeed(null);
@@ -269,11 +313,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
}
if (!isResumableUploadCheckpoint(request.result)) {
context.fail(
browserDataFailure(
"CORRUPT_DATA",
"UPLOAD_RECONCILE",
{ recovery: "RECONCILE" },
),
checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }),
);
return;
}
@@ -294,10 +334,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
try {
checkpoint = snapshotCheckpoint(inputValue.checkpoint);
} catch {
return browserDataFailure(
"INVALID_INPUT",
"UPLOAD_RECONCILE",
);
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const expectedRevision = inputValue.expectedRevision;
if (
@@ -306,12 +343,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
expectedRevision < 1)) ||
checkpoint.revision !== (expectedRevision ?? 0) + 1
) {
return browserDataFailure(
"INVALID_INPUT",
"UPLOAD_RECONCILE",
);
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await open(inputValue.signal);
const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<ResumableUploadCheckpoint>(
opened.value,
@@ -319,7 +353,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(checkpoint.uploadKey);
request.onerror = () => context.nativeFailure(request.error);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
const current = request.result;
if (
@@ -329,16 +363,12 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
current.revision !== expectedRevision))
) {
context.fail(
browserDataFailure(
"CONFLICT",
"UPLOAD_RECONCILE",
{ recovery: "RECONCILE" },
),
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const put = nativeStore.put(checkpoint);
put.onerror = () => context.nativeFailure(put.error);
put.onerror = () => context.fail(mappedFailure(put.error));
put.onsuccess = () => context.succeed(checkpoint);
};
},
@@ -355,12 +385,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
!Number.isSafeInteger(inputValue.expectedRevision) ||
inputValue.expectedRevision < 1
) {
return browserDataFailure(
"INVALID_INPUT",
"UPLOAD_RECONCILE",
);
return browserDataFailure("INVALID_INPUT", OPERATION);
}
const opened = await open(inputValue.signal);
const opened = await connection.acquire(inputValue.signal);
if (!opened.ok) return opened;
return await runCheckpointTransaction<void>(
opened.value,
@@ -368,24 +395,20 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
inputValue.signal,
(nativeStore, context) => {
const request = nativeStore.get(inputValue.uploadKey);
request.onerror = () => context.nativeFailure(request.error);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (
!isResumableUploadCheckpoint(request.result) ||
request.result.revision !== inputValue.expectedRevision
) {
context.fail(
browserDataFailure(
"CONFLICT",
"UPLOAD_RECONCILE",
{ recovery: "RECONCILE" },
),
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
);
return;
}
const deletion = nativeStore.delete(inputValue.uploadKey);
deletion.onerror = () =>
context.nativeFailure(deletion.error);
context.fail(mappedFailure(deletion.error));
deletion.onsuccess = () => context.succeed(undefined);
};
},
@@ -393,9 +416,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
},
close() {
closed = true;
database?.close();
database = null;
connection.close();
},
};
const store = Object.freeze(storeValue);
@@ -405,82 +426,50 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
): Promise<
BrowserDataResult<PartitionDeleteOutcome>
> {
// IDB deleteDatabase cannot be cancelled after dispatch. AbortSignal is
// intentionally observed only before dispatch so the adapter never
// reports ABORTED while deletion may still commit — which is also why the
// kernel's delete takes no signal.
if (signal?.aborted) {
return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
return browserDataFailure("ABORTED", OPERATION);
}
closed = true;
database?.close();
database = null;
if (!deleteFactory) {
return browserDataFailure(
"UNSUPPORTED",
"UPLOAD_RECONCILE",
{ recovery: "READ_ONLY" },
connection.close();
if (factory === undefined || !canDelete) {
return browserDataFailure("UNSUPPORTED", OPERATION, {
recovery: "READ_ONLY",
});
}
// BT-UP-03. Once dispatched the deletion may still commit after this call
// returns, so the pending registration is installed before the promise
// settles and is only released by the real native completion — which is
// exactly what `onSettled` reports and a blocked deadline never does.
pendingDeletions.add(databaseName);
const deleted = await deleteIndexedDbDatabase<BrowserDataFailure>({
factory,
databaseName,
translate,
blockedTimeoutMs,
timers,
onSettled: () => {
pendingDeletions.delete(databaseName);
},
});
if (!deleted.ok) return deleted;
if (deleted.value.kind === "DELETED") {
return browserDataSuccess(
Object.freeze({
state: "DELETED" as const,
effect: "APPLIED" as const,
}),
);
}
let request: IDBOpenDBRequest;
try {
request = deleteFactory(databaseName);
} catch (error) {
return mapBrowserDataException(error, "UPLOAD_RECONCILE");
}
// BT-UP-03. Once dispatched the deletion may still commit after this
// call returns, so the pending registration is installed before the
// promise settles and is only released by the real native completion.
pendingDeletions.add(databaseName);
return await new Promise<BrowserDataResult<PartitionDeleteOutcome>>(
(resolve) => {
let settled = false;
let blockedTimer: ReturnType<typeof setTimeout> | undefined;
const finish = (
result: BrowserDataResult<PartitionDeleteOutcome>,
) => {
if (settled) return;
settled = true;
if (blockedTimer) clearTimeout(blockedTimer);
resolve(result);
};
const releasePending = () => {
pendingDeletions.delete(databaseName);
};
// IDB deleteDatabase cannot be cancelled after dispatch. AbortSignal
// is intentionally observed only before dispatch so the adapter never
// reports ABORTED while deletion may still commit.
request.onblocked = () => {
blockedTimer = setTimeout(() => {
// Not NOT_APPLIED: the request is still live in the browser.
finish(
browserDataSuccess(
Object.freeze({
state: "PENDING" as const,
effect: "UNKNOWN" as const,
reason: "BLOCKED_DEADLINE" as const,
}),
),
);
}, blockedTimeoutMs);
};
request.onerror = () => {
releasePending();
finish(
mapBrowserDataException(
request.error,
"UPLOAD_RECONCILE",
),
);
};
request.onsuccess = () => {
releasePending();
finish(
browserDataSuccess(
Object.freeze({
state: "DELETED" as const,
effect: "APPLIED" as const,
}),
),
);
};
},
// Not NOT_APPLIED: the request is still live in the browser.
return browserDataSuccess(
Object.freeze({
state: "PENDING" as const,
effect: "UNKNOWN" as const,
reason: "BLOCKED_DEADLINE" as const,
}),
);
},
};
@@ -488,168 +477,79 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
return Object.freeze({ store, admin });
}
type TransactionContext<Value> = Readonly<{
succeed(value: Value): void;
fail(result: BrowserDataResult<never>): void;
nativeFailure(error: unknown): void;
}>;
/**
* `durability` is deliberately `undefined` rather than `"default"`: that opens
* the transaction with no options bag at all, which is what checkpoint writes
* have always done. Passing a named value would quietly move them onto a
* different flush policy and slow every checkpoint write down.
*
* A request error goes through `fail`, which aborts, rather than through the
* kernel's `requestFailed`, which only records. `compareAndSwap` issues its put
* inside the get's success handler, so a transaction left running after a
* failed request is a transaction that can still commit half of a swap.
*/
async function runCheckpointTransaction<Value>(
database: IDBDatabase,
mode: IDBTransactionMode,
mode: "readonly" | "readwrite",
signal: AbortSignal | undefined,
execute: (
store: IDBObjectStore,
context: TransactionContext<Value>,
context: Readonly<{
succeed(value: Value): void;
fail(failure: BrowserDataFailure): void;
}>,
) => void,
): Promise<BrowserDataResult<Value>> {
if (signal?.aborted) {
return browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
}
return await new Promise<BrowserDataResult<Value>>((resolve) => {
let transaction: IDBTransaction;
try {
transaction = database.transaction(CHECKPOINT_STORE, mode);
} catch (error) {
resolve(mapBrowserDataException(error, "UPLOAD_RECONCILE"));
return;
}
let value: Value | undefined;
let hasValue = false;
let failure: BrowserDataResult<never> | null = null;
let settled = false;
const finish = (result: BrowserDataResult<Value>) => {
if (settled) return;
settled = true;
signal?.removeEventListener("abort", abort);
resolve(result);
};
const abort = () => {
const previousFailure = failure;
failure = browserDataFailure("ABORTED", "UPLOAD_RECONCILE");
try {
transaction.abort();
} catch {
// The transaction may already be durably committed while its
// completion event is still queued. Wait for oncomplete/onabort so we
// never report ABORTED for a mutation that actually committed.
failure = previousFailure;
}
};
signal?.addEventListener("abort", abort, { once: true });
transaction.oncomplete = () => {
if (!hasValue) {
finish(
browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", {
recovery: "RECONCILE",
}),
);
return;
}
finish(browserDataSuccess(value as Value));
};
transaction.onerror = () => {
// onabort is the terminal transaction signal.
};
transaction.onabort = () =>
finish(
failure ??
mapBrowserDataException(
transaction.error,
"UPLOAD_RECONCILE",
),
);
const context: TransactionContext<Value> = Object.freeze({
succeed(next) {
if (failure) return;
value = next;
hasValue = true;
},
fail(result) {
if (failure) return;
failure = result;
try {
transaction.abort();
} catch {
finish(result);
}
},
nativeFailure(error) {
if (failure) return;
failure = mapBrowserDataException(
error,
"UPLOAD_RECONCILE",
);
try {
transaction.abort();
} catch {
finish(failure);
}
},
});
try {
return await runIndexedDbTransaction<Value, BrowserDataFailure>({
database,
stores: [CHECKPOINT_STORE],
mode,
translate,
signal,
durability: undefined,
queue: (transaction, context) => {
execute(transaction.objectStore(CHECKPOINT_STORE), context);
} catch (error) {
context.nativeFailure(error);
}
},
});
}
/**
* No `signal`: the binding is part of opening the connection, and an open the
* caller gave up on is already ended by the kernel's own abort path.
*/
async function bindScope(
database: IDBDatabase,
expected: ScopeBinding,
): Promise<BrowserDataResult<void>> {
return await new Promise<BrowserDataResult<void>>((resolve) => {
let transaction: IDBTransaction;
try {
transaction = database.transaction(GOVERNANCE_STORE, "readwrite");
} catch (error) {
resolve(mapBrowserDataException(error, "UPLOAD_RECONCILE"));
return;
}
let failure: BrowserDataResult<never> | null = null;
transaction.onerror = () => {
// onabort owns terminal resolution.
};
transaction.onabort = () =>
resolve(
failure ??
mapBrowserDataException(
transaction.error,
"UPLOAD_RECONCILE",
),
);
transaction.oncomplete = () => resolve(browserDataSuccess(undefined));
const store = transaction.objectStore(GOVERNANCE_STORE);
const request = store.get(GOVERNANCE_KEY);
request.onerror = () => {
failure = mapBrowserDataException(
request.error,
"UPLOAD_RECONCILE",
);
transaction.abort();
};
request.onsuccess = () => {
if (request.result === undefined) {
const add = store.add(expected);
add.onerror = () => {
failure = mapBrowserDataException(
add.error,
"UPLOAD_RECONCILE",
return await runIndexedDbTransaction<void, BrowserDataFailure>({
database,
stores: [GOVERNANCE_STORE],
mode: "readwrite",
translate,
durability: undefined,
queue: (transaction, context) => {
const store = transaction.objectStore(GOVERNANCE_STORE);
const request = store.get(GOVERNANCE_KEY);
request.onerror = () => context.fail(mappedFailure(request.error));
request.onsuccess = () => {
if (request.result === undefined) {
const add = store.add(expected);
add.onerror = () => context.fail(mappedFailure(add.error));
// The binding is the value: without this the committed transaction
// would report NO_VALUE_PRODUCED, which this store reads as
// CORRUPT_DATA.
add.onsuccess = () => context.succeed(undefined);
return;
}
if (!sameScopeBinding(request.result, expected)) {
context.fail(
checkpointFailure("POLICY_REJECTED", { recovery: "READ_ONLY" }),
);
transaction.abort();
};
return;
}
if (!sameScopeBinding(request.result, expected)) {
failure = browserDataFailure(
"POLICY_REJECTED",
"UPLOAD_RECONCILE",
{ recovery: "READ_ONLY" },
);
transaction.abort();
}
};
return;
}
context.succeed(undefined);
};
},
});
}
+7
View File
@@ -0,0 +1,7 @@
export {
createDiagnosticsAdapter,
getLastBootEvidence,
MAX_DIAGNOSTIC_ENTRIES,
noOpDiagnostics,
recordBootFailure,
} from "./bounded-diagnostics.ts";
+400
View File
@@ -0,0 +1,400 @@
import type {
InstalledHttpContract,
} from "../../contracts/external-contract-runtime.ts";
import type { Result } from "../../contracts/result.ts";
import type { MappingResult } from "../../contracts/boundary-mapper.ts";
import {
createFailure,
kindForStatus,
type ApiFailure,
type FailureEffectCertainty,
type FailureKind,
} from "../../contracts/errors.ts";
import type { MutationIntent } from "../../contracts/mutation-intent.ts";
import type {
HttpExecutionOutcome,
SafeResponseMetadata,
} from "./http-execution-v3.ts";
type ValidatorValue<Validator> =
Validator extends Readonly<{
safeParse(value: unknown): infer ParseResult;
}>
? Extract<
ParseResult,
Readonly<{ success: true; data: unknown }>
> extends Readonly<{ data: infer Value }>
? Value
: never
: never;
export type HttpContractInput<Contract> =
Contract extends Readonly<{
contract: Readonly<{ inputValidator: infer Validator }>;
}>
? ValidatorValue<Validator>
: never;
export type HttpContractWireOutput<Contract> =
Contract extends Readonly<{
contract: Readonly<{ outputValidator: infer Validator }>;
}>
? ValidatorValue<Validator>
: never;
export type HttpContractProblem<Contract> =
Contract extends Readonly<{
contract: Readonly<{ problemValidator: infer Validator }>;
}>
? ValidatorValue<Validator>
: never;
export type HttpContractOperationId<Contract> =
Contract extends Readonly<{
contract: Readonly<{ operationId: infer OperationId extends string }>;
}>
? OperationId
: never;
export type InstalledHttpOperationExecutor = Readonly<{
execute<Input, WireOutput, Problem>(
contract: InstalledHttpContract<Input, WireOutput, Problem>,
input: Input,
context: Readonly<{
routeId: string;
signal?: AbortSignal;
intent?: MutationIntent;
}>,
): Promise<HttpExecutionOutcome<WireOutput, Problem>>;
}>;
export type FeatureHttpProblemMapping = Readonly<{
kind: FailureKind;
code: string;
}>;
type FeatureHttpOperationSpec<
Contract,
Value,
RouteId extends string,
> = Readonly<{
contract: Contract;
routeId: RouteId;
mapSuccess(
value: HttpContractWireOutput<Contract>,
): MappingResult<Value>;
mapProblem?(
problem: HttpContractProblem<Contract>,
metadata: SafeResponseMetadata,
): FeatureHttpProblemMapping | undefined;
}>;
export type FeatureHttpOperation<
Contract,
Value,
RouteId extends string = string,
> = FeatureHttpOperationSpec<Contract, Value, RouteId> &
Readonly<{
operationId: HttpContractOperationId<Contract>;
/**
* Compile-time only carrier. The runtime object has no extra type payload;
* the contract remains the authority for input/wire/problem types.
*/
__types?: Readonly<{
value: Value;
}>;
}>;
type ContractValidity<Contract> =
HttpContractOperationId<Contract> extends never
? never
: HttpContractInput<Contract> extends never
? never
: HttpContractWireOutput<Contract> extends never
? never
: HttpContractProblem<Contract> extends never
? never
: unknown;
function defineFeatureHttpOperationForRoute<
const RouteId extends string,
const Contract,
Value,
>(
spec: FeatureHttpOperationSpec<Contract, Value, RouteId> &
ContractValidity<Contract>,
): FeatureHttpOperation<Contract, Value, RouteId> {
return Object.freeze({
...spec,
operationId: (spec.contract as Readonly<{
contract: Readonly<{ operationId: HttpContractOperationId<Contract> }>;
}>).contract.operationId,
}) as FeatureHttpOperation<Contract, Value, RouteId>;
}
export function defineFeatureHttpOperation<
const Contract,
Value,
const RouteId extends string,
>(
spec: FeatureHttpOperationSpec<Contract, Value, RouteId> &
ContractValidity<Contract>,
): FeatureHttpOperation<Contract, Value, RouteId> {
return defineFeatureHttpOperationForRoute(spec);
}
/**
* Feature-local route typing without introducing a dependency from the HTTP
* capability to the presentation route registry.
*/
export function defineFeatureHttpOperationForRoutes<
const RouteId extends string,
>() {
return function defineRouteBoundFeatureHttpOperation<
const Contract,
Value,
>(
spec: FeatureHttpOperationSpec<Contract, Value, RouteId> &
ContractValidity<Contract>,
): FeatureHttpOperation<Contract, Value, RouteId> {
return defineFeatureHttpOperationForRoute(spec);
};
}
type FeatureHttpOperationShape = Readonly<{
contract: object;
operationId: string;
routeId: string;
mapSuccess: (...args: never[]) => unknown;
mapProblem?: (...args: never[]) => unknown;
}>;
type OperationContract<Operation> =
Operation extends Readonly<{ contract: infer Contract }> ? Contract : never;
type OperationInput<Operation> = HttpContractInput<OperationContract<Operation>>;
type OperationWireOutput<Operation> =
HttpContractWireOutput<OperationContract<Operation>>;
type OperationProblem<Operation> =
HttpContractProblem<OperationContract<Operation>>;
type OperationValue<Operation> =
Operation extends FeatureHttpOperation<infer _Contract, infer Value, string>
? Value
: never;
type InvalidOperationRegistryKeys<
Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
> = {
[OperationId in keyof Operations & string]:
OperationId extends Operations[OperationId]["operationId"]
? Operations[OperationId]["operationId"] extends OperationId
? never
: OperationId
: OperationId;
}[keyof Operations & string];
type ValidOperationRegistry<
Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
> = InvalidOperationRegistryKeys<Operations> extends never
? unknown
: Readonly<{
__operationRegistryKeyMismatch: InvalidOperationRegistryKeys<Operations>;
}>;
export type FeatureHttpBinding<
Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
> = Readonly<{
execute<OperationId extends keyof Operations & string>(
operationId: OperationId,
input: OperationInput<Operations[OperationId]>,
context?: Readonly<{
signal?: AbortSignal;
intent?: MutationIntent;
}>,
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>>;
}>;
/**
* Capability-specific feature binding for the installed HTTP runtime.
*
* The installed contract is the single type authority. A feature contributes
* only a route identity plus wire-to-domain/problem interpretation. Transport,
* retry, validation and effect-certainty stay in the reusable HTTP capability.
*/
export function createFeatureHttpBinding<
const Operations extends Readonly<Record<string, FeatureHttpOperationShape>>,
>(
executor: InstalledHttpOperationExecutor,
operations: Operations & ValidOperationRegistry<Operations>,
): FeatureHttpBinding<Operations> {
for (const [registryId, operation] of Object.entries(operations)) {
if (registryId !== operation.operationId) {
throw new TypeError(
`Feature HTTP operation key mismatch: ${registryId} !== ${operation.operationId}`,
);
}
}
return Object.freeze({
async execute<OperationId extends keyof Operations & string>(
operationId: OperationId,
input: OperationInput<Operations[OperationId]>,
context: Readonly<{
signal?: AbortSignal;
intent?: MutationIntent;
}> = {},
): Promise<Result<OperationValue<Operations[OperationId]>, ApiFailure>> {
const operation = operations[operationId];
type SelectedOperation = Operations[OperationId];
type Input = OperationInput<SelectedOperation>;
type WireOutput = OperationWireOutput<SelectedOperation>;
type Problem = OperationProblem<SelectedOperation>;
type Value = OperationValue<SelectedOperation>;
const contract = operation.contract as InstalledHttpContract<
Input,
WireOutput,
Problem
>;
const outcome = await executor.execute(contract, input, {
routeId: operation.routeId,
...(context.signal === undefined ? {} : { signal: context.signal }),
...(context.intent === undefined ? {} : { intent: context.intent }),
});
return projectExecutionOutcome(
operation.operationId,
operation.mapSuccess as (value: WireOutput) => MappingResult<Value>,
operation.mapProblem as
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
outcome,
);
},
});
}
function projectExecutionOutcome<WireOutput, Problem, Value>(
operationId: string,
mapSuccess: (value: WireOutput) => MappingResult<Value>,
mapProblem:
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
outcome: HttpExecutionOutcome<WireOutput, Problem>,
): Result<Value, ApiFailure> {
switch (outcome.kind) {
case "SUCCESS": {
const mapped = mapSuccess(outcome.value);
return mapped.ok
? Object.freeze({ ok: true as const, value: mapped.value })
: failure(
"MAPPING_CONTRACT_VIOLATION",
operationId,
mapped.code,
{ effect: outcome.effect },
);
}
case "PROBLEM": {
const mapped = mapProblem?.(outcome.problem, outcome.metadata);
return failure(
mapped?.kind ?? kindForStatus(outcome.metadata.status),
operationId,
mapped?.code ?? "CONTRACT_PROBLEM",
{ httpStatus: outcome.metadata.status, effect: outcome.effect },
);
}
case "UNAUTHENTICATED":
return failure("AUTH_REQUIRED", operationId, "UNAUTHENTICATED", {
effect: outcome.effect,
});
case "FORBIDDEN":
return failure("FORBIDDEN", operationId, "FORBIDDEN", {
effect: outcome.effect,
});
case "RATE_LIMITED":
return failure("RATE_LIMITED", operationId, "RATE_LIMITED", {
...(outcome.retryAfterMs === undefined
? {}
: { retryAfterMs: outcome.retryAfterMs }),
effect: outcome.effect,
});
case "CANCELLED":
return failure("REQUEST_ABORTED", operationId, "REQUEST_ABORTED", {
effect: outcome.effect,
});
case "AUTH_INTEGRATION_FAILURE":
return failure(
"AUTH_INTEGRATION_FAILURE",
operationId,
outcome.reason,
{ effect: outcome.effect },
);
case "TRANSPORT_FAILURE":
return failure(
outcome.failure.kind === "TIMEOUT"
? "REQUEST_TIMEOUT"
: outcome.failure.kind === "ABORTED_BY_SCOPE"
? "SCOPE_GENERATION_CHANGED"
: "NETWORK_UNREACHABLE",
operationId,
outcome.failure.kind,
{ effect: outcome.effect },
);
case "CONTRACT_VIOLATION":
return failure(
failureKindForViolation(outcome.violation.kind),
operationId,
outcome.violation.kind,
{ effect: outcome.effect },
);
}
}
function failureKindForViolation(
violation: Extract<
HttpExecutionOutcome<unknown, unknown>,
{ kind: "CONTRACT_VIOLATION" }
>["violation"]["kind"],
): FailureKind {
switch (violation) {
case "CONTENT_TYPE_MISMATCH":
return "CONTENT_TYPE_MISMATCH";
case "RESPONSE_TOO_LARGE":
return "RESPONSE_BODY_LIMIT";
case "UTF8_INVALID":
case "JSON_INVALID":
return "MALFORMED_JSON";
case "MAPPING_CONTRACT_VIOLATION":
return "MAPPING_CONTRACT_VIOLATION";
case "SCOPE_FENCED":
return "SCOPE_GENERATION_CHANGED";
case "SUCCESS_SCHEMA_INVALID":
case "PROBLEM_SCHEMA_INVALID":
case "VALIDATOR_RUNTIME_FAILURE":
return "SCHEMA_MISMATCH";
default:
return "ENVELOPE_MISMATCH";
}
}
function failure(
kind: FailureKind,
operationId: string,
code: string,
details: Readonly<{
httpStatus?: number;
retryAfterMs?: number;
effect?: FailureEffectCertainty;
}> = {},
): Result<never, ApiFailure> {
return Object.freeze({
ok: false as const,
error: createFailure(kind, operationId, 0, { code, ...details }),
});
}
+8 -59
View File
@@ -41,6 +41,13 @@ import {
type PhysicalAttemptState,
} from "./http-effect-certainty.ts";
import { parseRetryAfter } from "./retry-policy.ts";
import {
canRetryTransport,
isRetryableHttpStatus,
isRetryableSemantics,
jitteredDelay,
retryDelayFor,
} from "./http-retry-lifecycle.ts";
/**
* §7–§8. Descriptor-driven HTTP execution.
@@ -299,14 +306,6 @@ export type ContractHttpExecutorDependencies = Readonly<{
observe?: (observation: HttpExecutionObservation) => void;
}>;
const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([
408, 425, 429, 502, 503, 504,
]);
const RETRY_BASE_DELAY_MS = 250;
const RETRY_MAX_LOCAL_DELAY_MS = 2_000;
const RETRY_AFTER_CEILING_MS = 5_000;
type MutationIntentValidation =
| Readonly<{ ok: true; intent?: MutationIntent }>
| Readonly<{
@@ -1347,7 +1346,7 @@ async function admitProblem<Input, WireOutput, Problem>(
): Promise<AdmissionOutcome<WireOutput, Problem>> {
const contract = operation.contract;
const isCommand = contract.commandEffect !== null;
const retryable = RETRYABLE_STATUSES.has(status);
const retryable = isRetryableHttpStatus(status);
const bytes = await readResponseBytes(
response,
@@ -1434,56 +1433,6 @@ async function admitProblem<Input, WireOutput, Problem>(
});
}
/**
* §8.3. `SAFE` and `IDEMPOTENT` may replay the same frozen request. `KEYED`
* must not automatically retry once an attempt was dispatched and its response
* was lost; that path goes to inspect/reconciliation instead. `NEVER` is zero.
*/
function canRetryTransport(
semantics: InstalledHttpContract<
unknown,
unknown,
unknown
>["contract"]["retrySemantics"],
attemptState: PhysicalAttemptState,
): boolean {
if (semantics === "NEVER") return false;
if (semantics === "KEYED") {
return attemptState === "PREPARING" || attemptState === "READY_TO_SEND";
}
return true;
}
function isRetryableSemantics(
semantics: InstalledHttpContract<
unknown,
unknown,
unknown
>["contract"]["retrySemantics"],
): boolean {
return semantics === "SAFE" || semantics === "IDEMPOTENT";
}
/** §8.2. Full jitter over `min(2000, 250 * 2^index)`. */
function jitteredDelay(retryIndex: number, random: () => number): number {
const ceiling = Math.min(
RETRY_MAX_LOCAL_DELAY_MS,
RETRY_BASE_DELAY_MS * 2 ** retryIndex,
);
return Math.floor(random() * ceiling);
}
function retryDelayFor(
retryAfterMs: number | null,
retryIndex: number,
random: () => number,
): number | null {
const local = jitteredDelay(retryIndex, random);
if (retryAfterMs === null) return local;
if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null;
return Math.max(local, retryAfterMs);
}
/** §7.12. No raw header map, URL, cookie, traceparent or ETag value escapes. */
function safeMetadata(
response: Response,
+57
View File
@@ -0,0 +1,57 @@
import type { RetrySemantics } from "../../contracts/external-contract-runtime.ts";
import type { PhysicalAttemptState } from "./http-effect-certainty.ts";
const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([
408, 425, 429, 502, 503, 504,
]);
const RETRY_BASE_DELAY_MS = 250;
const RETRY_MAX_LOCAL_DELAY_MS = 2_000;
const RETRY_AFTER_CEILING_MS = 5_000;
export function isRetryableHttpStatus(status: number): boolean {
return RETRYABLE_STATUSES.has(status);
}
/**
* Transport replay authority.
*
* KEYED commands may retry only before a physical dispatch. Once dispatched,
* an uncertain result belongs to reconciliation rather than automatic replay.
*/
export function canRetryTransport(
semantics: RetrySemantics,
attemptState: PhysicalAttemptState,
): boolean {
if (semantics === "NEVER") return false;
if (semantics === "KEYED") {
return attemptState === "PREPARING" || attemptState === "READY_TO_SEND";
}
return true;
}
export function isRetryableSemantics(semantics: RetrySemantics): boolean {
return semantics === "SAFE" || semantics === "IDEMPOTENT";
}
/** Full jitter over min(2000, 250 * 2^retryIndex). */
export function jitteredDelay(
retryIndex: number,
random: () => number,
): number {
const ceiling = Math.min(
RETRY_MAX_LOCAL_DELAY_MS,
RETRY_BASE_DELAY_MS * 2 ** retryIndex,
);
return Math.floor(random() * ceiling);
}
export function retryDelayFor(
retryAfterMs: number | null,
retryIndex: number,
random: () => number,
): number | null {
const local = jitteredDelay(retryIndex, random);
if (retryAfterMs === null) return local;
if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null;
return Math.max(local, retryAfterMs);
}
+55
View File
@@ -0,0 +1,55 @@
/**
* §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된
* 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을
* 런타임이 소유한다.
*/
export {
createContractHttpExecutor,
type AuthIntegrationFailureReason,
type AuthOperationContext,
type CancellationOwner,
type ContractHttpExecutor,
type ContractHttpExecutorDependencies,
type HttpContractViolation,
type HttpContractViolationKind,
type HttpEffectCertainty,
type HttpExecutionContext,
type HttpExecutionObservation,
type HttpExecutionOutcome,
type HttpTransportFailure,
type SafeResponseMetadata,
} from "./http-execution-v3.ts";
export {
createFeatureHttpBinding,
defineFeatureHttpOperation,
defineFeatureHttpOperationForRoutes,
type FeatureHttpBinding,
type FeatureHttpOperation,
type FeatureHttpProblemMapping,
type HttpContractInput,
type HttpContractOperationId,
type HttpContractProblem,
type HttpContractWireOutput,
type InstalledHttpOperationExecutor,
} from "./feature-http-binding.ts";
/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
/**
* V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다.
* 새 코드는 위의 V3 실행기를 쓴다.
*
* 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다.
* 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네
* 슬롯을 주입해야 동작한다 — 주입 없이 V3에서 되돌리면 모든 요청이 실패한다.
*/
export {
createHttpClient,
type HttpClient,
type HttpClientDependencies,
type HttpFailure,
type HttpResult,
type LegacyHttpInput,
type Scheduler,
} from "./client.ts";
/** V2 `HttpClient.execute`의 첫 인자 타입. */
export type { OperationRequestInput } from "./request-builder.ts";
+31
View File
@@ -0,0 +1,31 @@
/**
* 어댑터 커널의 공개 경계.
*
* `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일
* 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts:63-83`이
* `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게
* 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다.
* 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다.
*/
export {
compensateLateHandle,
createAbortableOperation,
snapshotAbortTimers,
type AbortableOperation,
type AbortableOperationInput,
type AbortRace,
type AbortTerminalReason,
type AbortTimerSnapshot,
} from "./abortable-operation.ts";
export { assertBoundedCapacity } from "./bounded-capacity.ts";
export {
createBrowserLifecycleRuntime,
type BrowserLifecycleEvent,
type BrowserLifecycleRuntime,
type BrowserLifecycleSnapshot,
} from "./browser-lifecycle.ts";
export {
createBrowserMutationIntentFactory,
type BrowserMutationIntentFactoryDependencies,
} from "./browser-mutation-intent-factory.ts";
export { systemClock } from "./system-clock.ts";
@@ -0,0 +1,699 @@
/**
* IDB-X-01. Shared IndexedDB connection mechanics.
*
* Four adapters independently reimplemented "turn an open request into a
* promise, hold a blocked deadline, route upgrade/error/success, close a
* connection that arrives after the caller gave up, and drop the cached handle
* when the browser takes it away". Only the mechanics are shared here. Database
* naming, schema, migrations, governance binding and the failure taxonomy stay
* with each subsystem, so this module imports none of them and is not a
* generic storage layer.
*
* The `IDBFactory` is a required parameter rather than a read of
* `globalThis.indexedDB`. `eslint.config.ts:40-63` bans that property on every
* browser root and `eslint.config.ts:519-530` grants the owned-adapter escape
* hatch to `src/adapters/platform/browser-lifecycle.ts` as a single file, not
* to this folder. Requiring the factory is also what all four callers already
* do, so nothing in eslint.config.ts has to change.
*
* What this module owns: event wiring, the settle-once latch, the blocked
* deadline and the cached-handle lifecycle. What it must never own: database
* names, schemas, migrations, governance bindings, codecs, byte budgets,
* retention, idempotency receipts, failure code tables, operation labels,
* observation event shapes, durability defaults and budget criteria. Wanting to
* move one of those in here is the signal to stop.
*/
import type { Result } from "../../contracts/result.ts";
import type { AbortTimerSnapshot } from "./abortable-operation.ts";
/**
* Everything that can end an IndexedDB operation without the caller getting a
* value. The kernel reports the cause; the caller's `translate` turns it into
* that subsystem's failure code.
*
* This union is the extension point. `abortable-operation.ts:11` baked a closed
* three-member `AbortTerminalReason` into its return type, so http v3 needed
* five owners and could not use the kernel at all. Here the owner vocabulary is
* never in a return type: adding a member is a compile error in every
* `translate` (they are total functions over the union) rather than a silent
* behavior change, and no consumer has to fork.
*/
export type IndexedDbFailureCause =
/** A native throw or a `request.error` / `transaction.error`. */
| Readonly<{ kind: "NATIVE_EXCEPTION"; error: unknown }>
/** `onblocked` fired and no deadline was configured. */
| Readonly<{ kind: "BLOCKED"; oldVersion: number; newVersion: number | null }>
/** `onblocked` fired and the configured deadline then elapsed. */
| Readonly<{ kind: "BLOCKED_DEADLINE" }>
/** The caller's own `AbortSignal` fired. */
| Readonly<{ kind: "CALLER_ABORT" }>
/** The connection handle was closed, which is not the caller aborting. */
| Readonly<{ kind: "CLOSED" }>
/** `upgrade` returned `REJECTED`, or a version change happened unexpectedly. */
| Readonly<{
kind: "UPGRADE_REJECTED";
oldVersion: number;
newVersion: number | null;
detail?: unknown;
}>
/** `admit` returned `REJECT`. `detail` is opaque to the kernel. */
| Readonly<{ kind: "ADMISSION_REJECTED"; detail?: unknown }>
/** A transaction completed without `succeed()` ever being called. */
| Readonly<{ kind: "NO_VALUE_PRODUCED" }>
/**
* No `IDBFactory`, or a required `IDBKeyRange` the caller did not supply.
* The kernel never raises this itself — the factory is a required parameter,
* so the condition can only exist before the kernel is called. It is part of
* the vocabulary so a caller that resolves those globals has one place to
* name the failure instead of a second taxonomy beside `translate`.
*/
| Readonly<{ kind: "UNSUPPORTED" }>;
/**
* Turns a cause into this subsystem's failure value. Built per call site so the
* kernel never learns an operation label or a failure code; a caller that needs
* `INDEXEDDB_READ` and one that needs `UPLOAD_RECONCILE` differ only here.
*/
export type IndexedDbTranslate<Failure> = (
cause: IndexedDbFailureCause,
) => Failure;
export type IndexedDbUpgradeContext = Readonly<{
database: IDBDatabase;
transaction: IDBTransaction;
oldVersion: number;
/** Never `null`: a null `newVersion` is reported as `UPGRADE_REJECTED` before `upgrade` runs. */
newVersion: number;
}>;
/**
* `REJECTED` aborts the versionchange transaction, so a schema change can never
* commit under a rejected policy. A throw from `upgrade` is equivalent to
* `REJECTED` with the thrown value as `detail`.
*/
export type IndexedDbUpgradeOutcome =
| Readonly<{ kind: "APPLIED" }>
| Readonly<{ kind: "REJECTED"; detail?: unknown }>;
/**
* Post-open validation. It runs after `onsuccess` and may be asynchronous, so
* store/index assertions and governance reads both fit. A rejected or failed
* admission closes the connection before the caller ever sees it.
*/
export type IndexedDbAdmission =
| Readonly<{ kind: "ADMIT" }>
| Readonly<{ kind: "REJECT"; detail?: unknown }>
| Readonly<{ kind: "FAIL"; cause: IndexedDbFailureCause }>;
export type IndexedDbOpenInput<Failure> = Readonly<{
/** Required. See the module comment for why this is not read from a global. */
factory: IDBFactory;
databaseName: string;
/** Omit to open whatever version exists. */
version?: number;
translate: IndexedDbTranslate<Failure>;
/**
* Called inside the versionchange transaction. Omitting it means any upgrade
* is unexpected and the open fails with `UPGRADE_REJECTED` — which is what
* `indexeddb-maintenance.ts:477-484` does by hand today.
*/
upgrade?: (context: IndexedDbUpgradeContext) => IndexedDbUpgradeOutcome;
/** Post-open validation. Omitting it admits every successful open. */
admit?: (
database: IDBDatabase,
) => IndexedDbAdmission | Promise<IndexedDbAdmission>;
/** Aborts a pending upgrade transaction and settles with `CALLER_ABORT`. */
signal?: AbortSignal;
/**
* `undefined` or `0`: the `onblocked` event itself is terminal and settles
* with `BLOCKED` (maintenance's behavior). A positive value waits that long
* before settling with `BLOCKED_DEADLINE` (runtime/opfs/checkpoint).
*/
blockedTimeoutMs?: number;
/**
* Required when `blockedTimeoutMs` is positive. Build it with
* `snapshotAbortTimers` from `./abortable-operation.ts`, which binds the
* callables once so replacing a method after composition cannot change how an
* open already in flight is bounded.
*/
timers?: AbortTimerSnapshot;
/** Observation only; it cannot change the outcome and its throw is swallowed. */
onBlocked?: (
event: Readonly<{ oldVersion: number; newVersion: number | null }>,
) => void;
}>;
export type IndexedDbConnection<Failure> = Readonly<{
/**
* Single-flight: concurrent callers share one in-flight open, and a cached
* live connection is returned without touching the factory.
*/
acquire(signal?: AbortSignal): Promise<Result<IDBDatabase, Failure>>;
/** The cached connection, or `null` while none is live. Live accessor, not a snapshot. */
current(): IDBDatabase | null;
/**
* Idempotent. Closes the cached connection and settles any in-flight open
* with `CLOSED` — not `CALLER_ABORT`, because the two have different codes in
* `indexeddb-runtime.ts` (`L743` resolves UNAVAILABLE while `L676` resolves
* ABORTED), and collapsing them would change one of them.
*/
close(): void;
isClosed(): boolean;
}>;
export type IndexedDbConnectionInput<Failure> = Readonly<{
/**
* How to produce a connection. Normally a closure over
* `openIndexedDbDatabase`. It is a seam rather than a fixed body so a caller
* can retry, decorate or fake the open without faking an `IDBFactory`.
*/
open: (
signal: AbortSignal | undefined,
) => Promise<Result<IDBDatabase, Failure>>;
translate: IndexedDbTranslate<Failure>;
/**
* Fired after the handle has already dropped its cached connection, so a
* listener cannot keep a connection the browser is taking back. The next
* `acquire()` opens again.
*/
onVersionChange?: (event: IDBVersionChangeEvent) => void;
/** `onclose`: the browser closed the connection without a version change. */
onForcedClose?: () => void;
}>;
export type IndexedDbDeleteOutcome =
| Readonly<{ kind: "DELETED" }>
/**
* The request is still live in the browser. It is not a failure and it is not
* "not applied": `deleteDatabase` cannot be cancelled after dispatch, so the
* effect is unknown. `indexeddb-checkpoint-store.ts:449-462` makes the same
* distinction and its comment explains why.
*/
| Readonly<{ kind: "BLOCKED_DEADLINE" }>;
export type IndexedDbDeleteInput<Failure> = Readonly<{
factory: IDBFactory;
databaseName: string;
translate: IndexedDbTranslate<Failure>;
blockedTimeoutMs?: number;
timers?: AbortTimerSnapshot;
/**
* Called exactly once when the native request truly settles, success or
* error — never on a blocked deadline. The caller uses it to release a
* pending-deletion registration; the kernel does not own such a registry
* because whether a realm may recreate the database is the caller's policy.
*/
onSettled?: () => void;
}>;
function succeeded<Value, Failure>(value: Value): Result<Value, Failure> {
return Object.freeze({ ok: true as const, value });
}
function failed<Value, Failure>(error: Failure): Result<Value, Failure> {
return Object.freeze({ ok: false as const, error });
}
/**
* A connection that lost a race is closed, never leaked. The close itself is
* best effort: a handle the browser already tore down cannot be closed again,
* and that must not replace the outcome the caller was given.
*/
function closeQuietly(database: IDBDatabase): void {
try {
database.close();
} catch {
// A connection that cannot be closed is already gone.
}
}
/**
* A positive deadline with no scheduler leaves the open unbounded, which is the
* same class of configuration defect `assertBoundedCapacity` and
* `snapshotAbortTimers` reject at construction rather than at runtime. It is a
* throw instead of a `Failure` because no `translate` could describe it without
* the caller first deciding it is acceptable to run unbounded.
*/
function assertBlockedDeadline(
blockedTimeoutMs: number | undefined,
timers: AbortTimerSnapshot | undefined,
): boolean {
const bounded =
blockedTimeoutMs !== undefined &&
Number.isFinite(blockedTimeoutMs) &&
blockedTimeoutMs > 0;
if (bounded && !timers) {
throw new TypeError(
"A positive blockedTimeoutMs requires a timer snapshot.",
);
}
return bounded;
}
/**
* Settles exactly once. A connection that arrives after the settle — a late
* `onsuccess`, a rejected admission, an abort — is closed rather than leaked.
*/
export function openIndexedDbDatabase<Failure>(
input: IndexedDbOpenInput<Failure>,
): Promise<Result<IDBDatabase, Failure>> {
const { factory, databaseName, translate } = input;
const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers);
if (input.signal?.aborted) {
return Promise.resolve(failed(translate({ kind: "CALLER_ABORT" })));
}
return new Promise<Result<IDBDatabase, Failure>>((resolve) => {
let settled = false;
let blockedTimer: unknown;
let blockedTimerSet = false;
let upgradeRejection: IndexedDbFailureCause | null = null;
const settle = (result: Result<IDBDatabase, Failure>) => {
if (settled) {
if (result.ok) closeQuietly(result.value);
return;
}
settled = true;
if (blockedTimerSet) {
blockedTimerSet = false;
try {
input.timers?.clearTimer(blockedTimer);
} catch {
// A throwing scheduler cannot keep the open unresolved.
}
}
try {
input.signal?.removeEventListener("abort", onCallerAbort);
} catch {
// A hostile signal facade cannot block cleanup.
}
resolve(result);
};
const settleFailure = (cause: IndexedDbFailureCause) => {
settle(failed(translate(cause)));
};
let request: IDBOpenDBRequest;
try {
request =
input.version === undefined
? factory.open(databaseName)
: factory.open(databaseName, input.version);
} catch (error) {
settleFailure({ kind: "NATIVE_EXCEPTION", error });
return;
}
/**
* An upgrade transaction is the only cancellable part of an open request:
* aborting it makes the request fail through `onerror`, and there is no
* other way to stop a dispatched open.
*/
const abortUpgrade = () => {
try {
request.transaction?.abort();
} catch {
// The request's own error path owns whatever happens next.
}
};
function onCallerAbort(): void {
abortUpgrade();
settleFailure({ kind: "CALLER_ABORT" });
}
input.signal?.addEventListener("abort", onCallerAbort, { once: true });
request.onupgradeneeded = (event) => {
const transaction = request.transaction;
const oldVersion = event.oldVersion;
const newVersion = event.newVersion;
// A null `newVersion` means a delete is in progress, and no `upgrade`
// policy can be applied to a schema that is going away. It is reported
// before the callback runs so a caller never sees a half-open upgrade.
if (!transaction || newVersion === null || !input.upgrade) {
upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion };
abortUpgrade();
return;
}
let outcome: IndexedDbUpgradeOutcome;
try {
outcome = input.upgrade({
database: request.result,
transaction,
oldVersion,
newVersion,
});
} catch (error) {
outcome = { kind: "REJECTED", detail: error };
}
if (outcome.kind === "APPLIED") return;
upgradeRejection = {
kind: "UPGRADE_REJECTED",
oldVersion,
newVersion,
detail: outcome.detail,
};
abortUpgrade();
};
request.onblocked = (event) => {
const blocked = Object.freeze({
oldVersion: event.oldVersion,
newVersion: event.newVersion,
});
if (input.onBlocked) {
try {
input.onBlocked(blocked);
} catch {
// Observation cannot change the outcome.
}
}
if (!bounded) {
settleFailure({ kind: "BLOCKED", ...blocked });
return;
}
if (blockedTimerSet || settled) return;
try {
blockedTimer = input.timers?.setTimer(() => {
settleFailure({ kind: "BLOCKED_DEADLINE" });
}, input.blockedTimeoutMs as number);
blockedTimerSet = true;
} catch {
// A scheduler that cannot install the deadline leaves the open
// unbounded, so the deadline is treated as already elapsed.
settleFailure({ kind: "BLOCKED_DEADLINE" });
}
};
request.onerror = () => {
settleFailure(
upgradeRejection ?? { kind: "NATIVE_EXCEPTION", error: request.error },
);
};
const routeAdmission = (
database: IDBDatabase,
admission: IndexedDbAdmission,
) => {
if (settled) {
closeQuietly(database);
return;
}
if (admission.kind === "ADMIT") {
settle(succeeded(database));
return;
}
// A connection the caller will never see is closed before the failure is
// reported, so a rejected admission cannot leak a live handle.
closeQuietly(database);
settleFailure(
admission.kind === "REJECT"
? { kind: "ADMISSION_REJECTED", detail: admission.detail }
: admission.cause,
);
};
request.onsuccess = () => {
const database = request.result;
if (settled) {
closeQuietly(database);
return;
}
if (!input.admit) {
settle(succeeded(database));
return;
}
let admission: IndexedDbAdmission | Promise<IndexedDbAdmission>;
try {
admission = input.admit(database);
} catch (error) {
closeQuietly(database);
settleFailure({ kind: "NATIVE_EXCEPTION", error });
return;
}
void Promise.resolve(admission).then(
(resolved) => routeAdmission(database, resolved),
(error: unknown) => {
closeQuietly(database);
settleFailure({ kind: "NATIVE_EXCEPTION", error });
},
);
};
});
}
export function createIndexedDbConnection<Failure>(
input: IndexedDbConnectionInput<Failure>,
): IndexedDbConnection<Failure> {
let connection: IDBDatabase | null = null;
let attempt: Promise<Result<IDBDatabase, Failure>> | null = null;
let controller: AbortController | null = null;
let closed = false;
const closeWaiters = new Set<() => void>();
/**
* The browser is taking the connection back. The cached handle is dropped
* before the subsystem is told, so a notification callback cannot hand out a
* connection that is already gone. The next `acquire()` opens again.
*/
const invalidate = (database: IDBDatabase, notify: () => void) => {
if (connection !== database) return;
connection = null;
try {
notify();
} catch {
// Losing the connection is independent from announcing it.
}
};
const adopt = (database: IDBDatabase): IDBDatabase => {
database.onversionchange = (event) => {
// The connection has to go for the other context's upgrade to proceed,
// so it is closed here rather than left to a listener's discretion.
closeQuietly(database);
invalidate(database, () => input.onVersionChange?.(event));
};
database.onclose = () => {
// `onclose` means the browser already tore the connection down, so there
// is nothing left to close — only a cached handle to drop.
invalidate(database, () => input.onForcedClose?.());
};
return database;
};
const start = (): Promise<Result<IDBDatabase, Failure>> => {
const openController = new AbortController();
controller = openController;
const started = input.open(openController.signal).then(
(result) => {
if (attempt === started) {
attempt = null;
controller = null;
}
if (!result.ok) return result;
if (closed) {
// The handle was closed while the open was in flight; the connection
// that arrived belongs to nobody.
closeQuietly(result.value);
return result;
}
connection = adopt(result.value);
return result;
},
(error: unknown) => {
if (attempt === started) {
attempt = null;
controller = null;
}
return failed<IDBDatabase, Failure>(
input.translate({ kind: "NATIVE_EXCEPTION", error }),
);
},
);
attempt = started;
return started;
};
return Object.freeze({
acquire(signal) {
if (closed) {
return Promise.resolve(
failed<IDBDatabase, Failure>(input.translate({ kind: "CLOSED" })),
);
}
if (signal?.aborted) {
return Promise.resolve(
failed<IDBDatabase, Failure>(
input.translate({ kind: "CALLER_ABORT" }),
),
);
}
const live = connection;
if (live) return Promise.resolve(succeeded<IDBDatabase, Failure>(live));
const shared = attempt ?? start();
// The shared open is not cancelled by one caller giving up: another
// caller may still want the connection, and the request cannot be
// un-dispatched anyway.
return new Promise<Result<IDBDatabase, Failure>>((resolve) => {
let callerSettled = false;
const finishCaller = (result: Result<IDBDatabase, Failure>) => {
if (callerSettled) return;
callerSettled = true;
try {
signal?.removeEventListener("abort", onAbort);
} catch {
// A hostile signal facade cannot block cleanup.
}
resolve(result);
};
function onAbort(): void {
finishCaller(
failed(input.translate({ kind: "CALLER_ABORT" })),
);
}
function onClose(): void {
finishCaller(failed(input.translate({ kind: "CLOSED" })));
}
signal?.addEventListener("abort", onAbort, { once: true });
closeWaiters.add(onClose);
void shared.then(
(result) => {
closeWaiters.delete(onClose);
// A handle closed mid-open reports CLOSED even if the open itself
// succeeded: the connection is already gone.
finishCaller(
closed
? failed(input.translate({ kind: "CLOSED" }))
: result,
);
},
() => {
closeWaiters.delete(onClose);
finishCaller(failed(input.translate({ kind: "CLOSED" })));
},
);
});
},
current: () => connection,
close() {
if (closed) return;
closed = true;
const live = connection;
connection = null;
if (live) closeQuietly(live);
// Cancelling the in-flight open aborts a pending upgrade transaction, so
// a closed handle does not leave a versionchange transaction running.
try {
controller?.abort();
} catch {
// A cancelled open still reports CLOSED to its waiters below.
}
controller = null;
for (const waiter of [...closeWaiters]) {
closeWaiters.delete(waiter);
waiter();
}
},
isClosed: () => closed,
});
}
/**
* In this module because it is the same `IDBOpenDBRequest` state machine as
* `openIndexedDbDatabase`, not because three subsystems need it — only
* `indexeddb-checkpoint-store.ts` deletes a database, and nothing here asks the
* other three to start. Leaving it out would leave a third hand-written copy of
* the settle-once blocked-deadline latch eight lines away from the kernel's.
*
* There is deliberately no `signal`: the request cannot be cancelled after
* dispatch, so reporting ABORTED while the deletion may still commit would be a
* lie. Callers check their signal before calling.
*/
export function deleteIndexedDbDatabase<Failure>(
input: IndexedDbDeleteInput<Failure>,
): Promise<Result<IndexedDbDeleteOutcome, Failure>> {
const { factory, databaseName, translate } = input;
const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers);
return new Promise<Result<IndexedDbDeleteOutcome, Failure>>((resolve) => {
let settled = false;
let notified = false;
let blockedTimer: unknown;
let blockedTimerSet = false;
/**
* Independent of `settle`: a blocked deadline resolves the caller while the
* request is still live, and the registration must be released when the
* request actually lands, not when the caller stopped waiting.
*/
const notifySettled = () => {
if (notified) return;
notified = true;
try {
input.onSettled?.();
} catch {
// Releasing a registration cannot change the deletion outcome.
}
};
const settle = (result: Result<IndexedDbDeleteOutcome, Failure>) => {
if (settled) return;
settled = true;
if (blockedTimerSet) {
blockedTimerSet = false;
try {
input.timers?.clearTimer(blockedTimer);
} catch {
// A throwing scheduler cannot keep the deletion unresolved.
}
}
resolve(result);
};
let request: IDBOpenDBRequest;
try {
request = factory.deleteDatabase(databaseName);
} catch (error) {
notifySettled();
settle(failed(translate({ kind: "NATIVE_EXCEPTION", error })));
return;
}
request.onsuccess = () => {
notifySettled();
settle(succeeded({ kind: "DELETED" as const }));
};
request.onerror = () => {
notifySettled();
settle(
failed(translate({ kind: "NATIVE_EXCEPTION", error: request.error })),
);
};
request.onblocked = (event) => {
if (!bounded) {
settle(
failed(
translate({
kind: "BLOCKED",
oldVersion: event.oldVersion,
newVersion: event.newVersion,
}),
),
);
return;
}
if (blockedTimerSet || settled) return;
try {
blockedTimer = input.timers?.setTimer(() => {
settle(succeeded({ kind: "BLOCKED_DEADLINE" as const }));
}, input.blockedTimeoutMs as number);
blockedTimerSet = true;
} catch {
settle(succeeded({ kind: "BLOCKED_DEADLINE" as const }));
}
};
});
}
@@ -0,0 +1,433 @@
/**
* IDB-X-02. Shared IndexedDB transaction and cursor mechanics.
*
* The same settle-once transaction state machine exists four times
* (`indexeddb-runtime.ts:976-1074`, `indexeddb-maintenance.ts:606-705`,
* `indexeddb-opfs-journal.ts:1098-1174`,
* `indexeddb-checkpoint-store.ts:497-596`) and the four already disagree: one
* of them never routes a request error at all, one aborts on a request error
* while two only record it, and one reports a value-less completion as
* CORRUPT_DATA while three report UNAVAILABLE. This module owns the mechanics
* and keeps every one of those choices at the call site.
*
* Like `indexeddb-connection.ts`, it owns no policy: not a store name, not a
* durability default, not a budget criterion, not a failure code.
*/
import type { Result } from "../../contracts/result.ts";
import type { IndexedDbTranslate } from "./indexeddb-connection.ts";
export type IndexedDbDurability = "default" | "strict" | "relaxed";
/**
* The failure half of a transaction context. Split out so helpers that only
* need to report failure (`onIndexedDbRequest`, `walkIndexedDbCursor`) do not
* have to be generic over the transaction's success type.
*/
export type IndexedDbRequestSink<Failure> = Readonly<{
/**
* Records the failure and aborts the transaction. The first failure wins.
* This is `indexeddb-runtime.ts:1047-1054`'s `fail`.
*/
fail(failure: Failure): void;
/**
* Records a request-level error **without aborting**: the transaction is left
* to complete or abort on its own, and the recorded error becomes the reported
* failure if it aborts. This is `indexeddb-runtime.ts:1055-1060`'s
* `requestFailed`.
*
* `indexeddb-checkpoint-store.ts:577-588` deliberately aborts instead. It
* keeps doing so by calling `fail(translate({kind:"NATIVE_EXCEPTION", error}))`.
* The kernel does not pick.
*/
requestFailed(error: unknown): void;
}>;
export type IndexedDbTransactionContext<Value, Failure> =
IndexedDbRequestSink<Failure> &
Readonly<{
/** The first `succeed` wins; later ones are ignored. */
succeed(value: Value): void;
/** For callers that need `objectStore()`/`index()` directly. */
readonly transaction: IDBTransaction;
}>;
export type IndexedDbTransactionInput<Value, Failure> = Readonly<{
database: IDBDatabase;
stores: readonly string[];
mode: "readonly" | "readwrite";
translate: IndexedDbTranslate<Failure>;
/** Aborts the transaction; the outcome is `CALLER_ABORT` unless completion won. */
signal?: AbortSignal;
/**
* `undefined` opens with **no options bag at all**, which is
* `indexeddb-checkpoint-store.ts:512`'s current behavior — not the same as
* `"default"`, which passes `{durability:"default"}`. A named value falls back
* to the no-options form when the engine rejects the bag with a `TypeError`.
*/
durability?: IndexedDbDurability;
queue: (
transaction: IDBTransaction,
context: IndexedDbTransactionContext<Value, Failure>,
) => void;
}>;
/** How the visitor wants the cursor advanced. */
export type IndexedDbCursorStep =
| Readonly<{ kind: "CONTINUE" }>
| Readonly<{ kind: "CONTINUE_FROM"; key: IDBValidKey }>
| Readonly<{
kind: "CONTINUE_PRIMARY";
key: IDBValidKey;
primaryKey: IDBValidKey;
}>
/** End the walk here; `done` gets `reason: "STOPPED"`. */
| Readonly<{ kind: "STOP" }>
/**
* The visitor started its own request chain and will call `resume(step)` when
* that chain finishes. Without this the pump is unusable by three of the four
* callers: every walk in `indexeddb-runtime.ts` and `indexeddb-maintenance.ts`
* issues nested requests before advancing (e.g. `L1487-1526`, `L2406-2471`,
* `L1490-1541`). A pump that only understood `CONTINUE` would be the
* too-narrow-to-adopt failure again.
*/
| Readonly<{ kind: "SUSPEND" }>;
export type IndexedDbBudgetVerdict = "CONTINUE" | "ROW_BUDGET" | "TIME_BUDGET";
export type IndexedDbBudget<Failure> = Readonly<{
/**
* Checked before each row, with the number of rows already handed to `visit`.
* The kernel counts nothing itself: runtime bounds on rows it deleted
* (`indexeddb-runtime.ts:2384`) while maintenance bounds on rows it scanned
* (`indexeddb-maintenance.ts:823`), so the counter, the clock and the deadline
* all belong to the caller. A clock that cannot be read is a failure rather
* than a `false`, which is what `monotonicClock()`
* (`indexeddb-runtime.ts:2260-2269`) already does.
*/
admit(scannedRows: number): Result<IndexedDbBudgetVerdict, Failure>;
}>;
export type IndexedDbCursorVisit = Readonly<{
cursor: IDBCursorWithValue;
/** Rows handed to `visit` so far, this row included. */
scannedRows: number;
/** Only meaningful after the visitor returned `SUSPEND`. Idempotent. */
resume(step: IndexedDbCursorStep): void;
}>;
export type IndexedDbWalkSummary = Readonly<{
reason: "EXHAUSTED" | "STOPPED" | "ROW_BUDGET" | "TIME_BUDGET" | "ABORTED";
scannedRows: number;
}>;
export type IndexedDbWalkInput<Failure> = Readonly<{
request: IDBRequest<IDBCursorWithValue | null>;
sink: IndexedDbRequestSink<Failure>;
translate: IndexedDbTranslate<Failure>;
budget?: IndexedDbBudget<Failure>;
/**
* Checked at each row. An aborted signal aborts the transaction and ends the
* walk with `reason: "ABORTED"`, which is what `indexeddb-runtime.ts:1375-1382`
* does inline today.
*/
signal?: AbortSignal;
visit: (visit: IndexedDbCursorVisit) => IndexedDbCursorStep;
/** The only success exit. The caller routes it into its own `succeed`. */
done: (summary: IndexedDbWalkSummary) => void;
}>;
function succeeded<Value, Failure>(value: Value): Result<Value, Failure> {
return Object.freeze({ ok: true as const, value });
}
function failed<Value, Failure>(error: Failure): Result<Value, Failure> {
return Object.freeze({ ok: false as const, error });
}
/**
* The durability fallback on its own, for a caller that manages its own
* transaction. `undefined` omits the options bag entirely.
*/
export function openIndexedDbTransaction(
database: IDBDatabase,
stores: readonly string[],
mode: "readonly" | "readwrite",
durability?: IndexedDbDurability,
): IDBTransaction {
const names = [...stores];
// Not the same as `{durability:"default"}`: an engine that has never seen the
// options bag treats the two differently, and one caller relies on that.
if (durability === undefined) return database.transaction(names, mode);
try {
return database.transaction(names, mode, { durability });
} catch (error) {
// Only an engine that does not know the option answers with a TypeError.
// Anything else — a closed connection, an unknown store — is a real error
// and must not be retried into a second, differently shaped failure.
if (error instanceof TypeError) return database.transaction(names, mode);
throw error;
}
}
/**
* A transaction that completes without `succeed()` is reported through
* `translate({kind:"NO_VALUE_PRODUCED"})`. Three callers map that to
* UNAVAILABLE and `indexeddb-checkpoint-store.ts:541-547` maps it to
* CORRUPT_DATA; the kernel never picks.
*/
export function runIndexedDbTransaction<Value, Failure>(
input: IndexedDbTransactionInput<Value, Failure>,
): Promise<Result<Value, Failure>> {
const { translate } = input;
if (input.signal?.aborted) {
return Promise.resolve(failed(translate({ kind: "CALLER_ABORT" })));
}
let transaction: IDBTransaction;
try {
transaction = openIndexedDbTransaction(
input.database,
input.stores,
input.mode,
input.durability,
);
} catch (error) {
return Promise.resolve(failed(translate({ kind: "NATIVE_EXCEPTION", error })));
}
return new Promise<Result<Value, Failure>>((resolve) => {
let candidate: Result<Value, Failure> | undefined;
let requestError: unknown;
let hasRequestError = false;
let callerAborted = false;
let settled = false;
const finish = (result: Result<Value, Failure>) => {
if (settled) return;
settled = true;
try {
input.signal?.removeEventListener("abort", onCallerAbort);
} catch {
// A hostile signal facade cannot block cleanup.
}
resolve(result);
};
function onCallerAbort(): void {
const previous = callerAborted;
callerAborted = true;
try {
transaction.abort();
} catch {
// CP-4. The transaction may already be durably committed while its
// completion event is still queued. Claiming the abort would report a
// committed mutation as ABORTED, so the claim is withdrawn and the
// transaction's own events decide.
callerAborted = previous;
}
}
transaction.oncomplete = () => {
finish(candidate ?? failed(translate({ kind: "NO_VALUE_PRODUCED" })));
};
transaction.onerror = () => {
// `onabort` is the terminal signal; this only captures the error that a
// request left behind before the transaction unwinds.
if (hasRequestError) return;
requestError = transaction.error;
hasRequestError = true;
};
transaction.onabort = () => {
if (callerAborted) {
finish(failed(translate({ kind: "CALLER_ABORT" })));
return;
}
if (candidate && !candidate.ok) {
finish(candidate);
return;
}
// An abort never yields the value a `succeed` recorded: the transaction
// did not commit, so the native error is what happened.
finish(
failed(
translate({
kind: "NATIVE_EXCEPTION",
error: hasRequestError ? requestError : transaction.error,
}),
),
);
};
input.signal?.addEventListener("abort", onCallerAbort, { once: true });
const context: IndexedDbTransactionContext<Value, Failure> = Object.freeze({
transaction,
succeed(value) {
candidate ??= succeeded(value);
},
fail(failure) {
candidate ??= failed(failure);
try {
transaction.abort();
} catch {
// The transaction is already finished, so no abort event is coming.
// The recorded failure is the outcome rather than a hang.
finish(candidate);
}
},
requestFailed(error) {
if (!hasRequestError) {
requestError = error;
hasRequestError = true;
}
candidate ??= failed(translate({ kind: "NATIVE_EXCEPTION", error }));
},
});
try {
input.queue(transaction, context);
} catch (error) {
context.fail(translate({ kind: "NATIVE_EXCEPTION", error }));
}
});
}
/**
* Wires `onsuccess`/`onerror` in one place. The four copies write this pair by
* hand at roughly 70 sites and `indexeddb-opfs-journal.ts` omits `onerror`
* everywhere, which is how a request-level error there becomes whatever
* `transaction.error` happens to hold.
*/
export function onIndexedDbRequest<Value, Failure>(
request: IDBRequest<Value>,
sink: IndexedDbRequestSink<Failure>,
onSuccess: (value: Value) => void,
): void {
request.onsuccess = () => {
onSuccess(request.result);
};
request.onerror = () => {
sink.requestFailed(request.error);
};
}
/**
* Drives an open cursor. It reports a native advance failure through `sink` and
* never decides what a finished walk means — `reason` distinguishes a row budget
* from a time budget so a caller can keep reporting `budgetExhausted` exactly as
* it does now (`indexeddb-runtime.ts:2387`).
*/
export function walkIndexedDbCursor<Failure>(
input: IndexedDbWalkInput<Failure>,
): void {
const { request, sink, translate } = input;
let scannedRows = 0;
let finished = false;
const end = (reason: IndexedDbWalkSummary["reason"]) => {
if (finished) return;
finished = true;
input.done(Object.freeze({ reason, scannedRows }));
};
const abandon = (failure: Failure) => {
if (finished) return;
finished = true;
sink.fail(failure);
};
const advance = (action: () => void) => {
try {
action();
} catch (error) {
abandon(translate({ kind: "NATIVE_EXCEPTION", error }));
}
};
const applyStep = (
cursor: IDBCursorWithValue,
step: IndexedDbCursorStep,
): void => {
switch (step.kind) {
case "CONTINUE":
advance(() => cursor.continue());
return;
case "CONTINUE_FROM":
advance(() => cursor.continue(step.key));
return;
case "CONTINUE_PRIMARY":
advance(() => cursor.continuePrimaryKey(step.key, step.primaryKey));
return;
case "STOP":
end("STOPPED");
return;
case "SUSPEND":
// The visitor owns the cursor until it calls `resume`.
return;
default: {
const exhaustive: never = step;
return exhaustive;
}
}
};
request.onerror = () => {
if (finished) return;
finished = true;
// No `done`: the walk produced no summary, and the transaction's own
// outcome decides what a failed advance means for this call site.
sink.requestFailed(request.error);
};
request.onsuccess = () => {
if (finished) return;
const cursor = request.result;
if (!cursor) {
end("EXHAUSTED");
return;
}
if (input.signal?.aborted) {
// Aborting through the sink keeps one abort path instead of reaching for
// a transaction the pump was never handed. `done` still runs so the
// caller sees why the walk stopped; the recorded failure outranks any
// value it produces there.
finished = true;
sink.fail(translate({ kind: "CALLER_ABORT" }));
input.done(Object.freeze({ reason: "ABORTED" as const, scannedRows }));
return;
}
if (input.budget) {
const verdict = input.budget.admit(scannedRows);
if (!verdict.ok) {
abandon(verdict.error);
return;
}
if (verdict.value === "ROW_BUDGET" || verdict.value === "TIME_BUDGET") {
end(verdict.value);
return;
}
}
scannedRows += 1;
let suspended = false;
let resumed = false;
const resume = (step: IndexedDbCursorStep) => {
if (!suspended || resumed || finished) return;
resumed = true;
applyStep(cursor, step);
};
let step: IndexedDbCursorStep;
try {
step = input.visit(
Object.freeze({ cursor, scannedRows, resume }),
);
} catch (error) {
// A visitor defect must not let a partially applied write commit, so it
// aborts rather than merely being recorded.
abandon(translate({ kind: "NATIVE_EXCEPTION", error }));
return;
}
if (step.kind === "SUSPEND") suspended = true;
applyStep(cursor, step);
};
}
@@ -1,4 +1,4 @@
import type { Result } from "./result.ts";
import type { Result } from "../../contracts/result.ts";
export type CursorPage<Value> = Readonly<{
items: readonly Value[];
@@ -1,9 +1,9 @@
import type { Result } from "../../application/result.ts";
import type { Result } from "../../contracts/result.ts";
import type {
CursorPage,
CursorPaginationProfile,
CursorPaginationRuntime,
} from "../../contracts/cursor-pagination.ts";
} from "./cursor-pagination-contract.ts";
import { createFailure } from "../../contracts/errors.ts";
import { snapshotExactObject } from "../../contracts/exact-snapshot.ts";
+26
View File
@@ -0,0 +1,26 @@
export {
createConditionalValidatorStore,
type ConditionalValidatorBinding,
type ConditionalValidatorStore,
} from "./conditional-validator-store.ts";
export { createCursorPaginationRuntime } from "./cursor-pagination-runtime.ts";
export type {
CursorPage,
CursorPaginationProfile,
CursorPaginationRuntime,
} from "./cursor-pagination-contract.ts";
export {
createServerStateScopeRuntime,
type ScopeResetParticipant,
type ServerStateScopeDependencies,
} from "./server-state-scope-runtime.ts";
export {
createTanStackCacheCoordinator,
type TanStackCacheCoordinatorDependencies,
} from "./tanstack-cache-coordinator.ts";
export {
createQueryCacheAdapter,
createQueryClient,
QUERY_CACHE_DEFAULTS,
type QueryCacheDependencies,
} from "./tanstack-query-cache.ts";
+31
View File
@@ -0,0 +1,31 @@
/**
* 이 배럴은 그룹 바깥(bootstrap, tests)을 위한 문이다. 워커 realm 진입점
* `service-worker-entry.ts`는 이 배럴을 쓰지 않고 파일을 직접 import한다.
*
* 그래서 `tsconfig.service-worker.json`의 `exclude`에 이 파일이 들어 있다.
* 그 설정은 `src/adapters/service-worker` 폴더를 통째로 WebWorker lib로
* 컴파일하면서 페이지 realm 파일(`service-worker-page-controller.ts`,
* `service-worker-removal.ts`)만 빼는 구조다. 배럴이 제외되지 않으면 그
* 페이지 realm 파일을 다시 끌어들여 `document`를 찾지 못한다.
* 타입 커버리지는 `tsconfig.app.json`이 이 배럴을 포함하므로 유지된다.
*
* `service-worker-entry.ts`도 여기서 참조하지 않는다. `tsconfig.app.json:18`이
* 제외한 파일이고, export가 0개이므로 넣을 것도 없다.
*/
export {
createServiceWorkerRuntime,
type WorkerClientLike,
type WorkerRuntimeConfig,
type WorkerScopeLike,
} from "./service-worker-lifecycle.ts";
export {
createServiceWorkerPageController,
type ActivationBlocker,
type PageControllerDependencies,
} from "./service-worker-page-controller.ts";
export {
createNonceRegistry,
createServiceWorkerMessage,
parseServiceWorkerMessage,
type ParsedMessage,
} from "./service-worker-protocol.ts";
+12
View File
@@ -0,0 +1,12 @@
/**
* 최상위 storage 배럴은 Web Storage 어댑터만 내보낸다.
*
* `./indexeddb/index.ts`와 `./opfs/index.ts`를 여기서 재수출하지 말 것.
* `scripts/test-browser-file-storage-runtime-removal.ts:23-34`가 그 두 폴더만
* 삭제한 뒤 잔존 import를 예외로 잡는다 — 재수출하면 제거 드릴이 죽는다.
* 두 서브배럴이 각자 제거 가능한 런타임의 경계다.
*/
export {
createBrowserStorageAdapter,
type BrowserStorageDependencies,
} from "./browser-storage-adapter.ts";
@@ -5,6 +5,7 @@ import type {
IndexedDbReceiptPruneBatchReceipt,
} from "../../../application/ports/browser-file-storage/indexeddb-port.ts";
import type {
BrowserDataFailure,
BrowserDataResult,
} from "../../../application/ports/browser-file-storage/shared.ts";
import {
@@ -12,6 +13,17 @@ import {
browserDataFailure,
browserDataSuccess,
} from "../../browser-file-storage/result.ts";
import {
openIndexedDbDatabase,
type IndexedDbTranslate,
} from "../../platform/indexeddb-connection.ts";
import {
openIndexedDbTransaction,
runIndexedDbTransaction,
walkIndexedDbCursor,
type IndexedDbBudget,
type IndexedDbTransactionContext,
} from "../../platform/indexeddb-transaction.ts";
import { mapIndexedDbException } from "./indexeddb-failure.ts";
import {
createIndexedDbDatasetBinding,
@@ -94,12 +106,6 @@ type PreparedRecord<WireValue> = Readonly<{
measuredBytes: number | undefined;
}>;
type TransactionContext<Value> = Readonly<{
succeed(value: Value): void;
fail(result: BrowserDataResult<never>): void;
requestFailed(error: unknown): void;
}>;
const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u;
const MAX_BATCH_ROWS = 500;
@@ -261,6 +267,41 @@ function unavailable(): BrowserDataResult<never> {
});
}
function unsupported(): BrowserDataResult<never> {
return browserDataFailure("UNSUPPORTED", "INDEXEDDB_MIGRATE", {
recovery: "ONLINE_ONLY",
});
}
/**
* `browserDataFailure` and `mapIndexedDbException` build a `Result`, while the
* kernel's `translate` and `context.fail` want the failure on its own. Both
* only ever build the failure arm, so the branch below is a narrowing rather
* than a claim.
*/
function failureOf(result: BrowserDataResult<never>): BrowserDataFailure {
if (result.ok) {
throw new TypeError("A browser data failure was expected.");
}
return result.error;
}
function invalidInputFailure(): BrowserDataFailure {
return failureOf(invalidInput());
}
function migrationFailure(): BrowserDataFailure {
return failureOf(migrationFailed());
}
function unsupportedFailure(): BrowserDataFailure {
return failureOf(unsupported());
}
function mappedFailure(error: unknown): BrowserDataFailure {
return failureOf(mapIndexedDbException(error, "INDEXEDDB_MIGRATE"));
}
function defaultNow(): number {
return typeof globalThis.performance === "undefined"
? Date.now()
@@ -420,6 +461,59 @@ export function createIndexedDbMaintenance<WireValue>(
}
}
/**
* STO-06. Maintenance keeps `mapIndexedDbException`, which the runtime and
* the OPFS journal share, rather than the checkpoint store's own table: the
* same native error is a different answer in the two families, and unifying
* them is a separate change from moving the mechanics onto the kernel.
*
* One translator covers the whole adapter because the operation label is the
* constant `INDEXEDDB_MIGRATE` here — the runtime needs one per operation.
*/
const translate: IndexedDbTranslate<BrowserDataFailure> = (cause) => {
switch (cause.kind) {
case "NATIVE_EXCEPTION":
return mappedFailure(cause.error);
case "BLOCKED":
case "BLOCKED_DEADLINE":
return failureOf(
browserDataFailure("BLOCKED", "INDEXEDDB_MIGRATE", {
retryable: true,
recovery: "RELOAD_OTHER_CONTEXTS",
}),
);
case "CALLER_ABORT":
return failureOf(
browserDataFailure("ABORTED", "INDEXEDDB_MIGRATE"),
);
case "CLOSED":
case "NO_VALUE_PRODUCED":
// A transaction that committed without producing a value is retried,
// not reconciled. `CLOSED` cannot reach here — maintenance opens a
// connection per batch instead of holding a cached handle — and is
// mapped alongside it so the union stays total.
return failureOf(unavailable());
case "UPGRADE_REJECTED":
// Maintenance owns no schema. Any upgrade means the database is not
// the one this batch was configured against.
return migrationFailure();
case "ADMISSION_REJECTED":
return cause.detail === "POLICY"
? failureOf(
browserDataFailure("POLICY_REJECTED", "INDEXEDDB_MIGRATE", {
recovery: storagePolicySnapshot.unavailableFallback,
}),
)
: migrationFailure();
case "UNSUPPORTED":
return unsupportedFailure();
default: {
const exhaustive: never = cause;
return exhaustive;
}
}
};
function validBatchInput(
input: IndexedDbMaintenanceBatchInput,
): boolean {
@@ -436,173 +530,76 @@ export function createIndexedDbMaintenance<WireValue>(
): Promise<BrowserDataResult<IDBDatabase>> {
const cancelled = abortedResult(signal, "INDEXEDDB_MIGRATE");
if (cancelled) return Promise.resolve(cancelled);
if (!factory) {
return Promise.resolve(
browserDataFailure("UNSUPPORTED", "INDEXEDDB_MIGRATE", {
recovery: "ONLINE_ONLY",
}),
);
}
if (!factory) return Promise.resolve(unsupported());
return new Promise<BrowserDataResult<IDBDatabase>>((resolve) => {
let request: IDBOpenDBRequest;
try {
request = factory.open(
databaseName,
dependencies.schemaVersion,
);
} catch (error) {
resolve(mapIndexedDbException(error, "INDEXEDDB_MIGRATE"));
return;
}
let settled = false;
let unexpectedUpgrade = false;
const finish = (result: BrowserDataResult<IDBDatabase>) => {
if (settled) return;
settled = true;
signal?.removeEventListener("abort", onAbort);
resolve(result);
};
function onAbort(): void {
try {
request.transaction?.abort();
} catch {
// A pending non-upgrade open request cannot be cancelled.
}
finish(browserDataFailure("ABORTED", "INDEXEDDB_MIGRATE"));
}
signal?.addEventListener("abort", onAbort, { once: true });
request.onupgradeneeded = () => {
unexpectedUpgrade = true;
try {
request.transaction?.abort();
} catch {
// The error handler below owns the closed failure result.
}
};
request.onblocked = () => {
finish(
browserDataFailure("BLOCKED", "INDEXEDDB_MIGRATE", {
retryable: true,
recovery: "RELOAD_OTHER_CONTEXTS",
}),
);
};
request.onerror = () => {
finish(
unexpectedUpgrade
? migrationFailed()
: mapIndexedDbException(
request.error,
"INDEXEDDB_MIGRATE",
),
);
};
request.onsuccess = () => {
const database = request.result;
if (settled) {
database.close();
return;
}
if (
!database.objectStoreNames.contains(
dependencies.recordStore,
) ||
!database.objectStoreNames.contains(
dependencies.governanceStore,
) ||
!database.objectStoreNames.contains(
dependencies.retentionStore,
) ||
!database.objectStoreNames.contains(
dependencies.checkpointStore,
) ||
!database.objectStoreNames.contains(
dependencies.idempotencyStore,
)
) {
database.close();
finish(migrationFailed());
return;
return openIndexedDbDatabase<BrowserDataFailure>({
factory,
databaseName,
version: dependencies.schemaVersion,
translate,
signal,
// No `blockedTimeoutMs`, and therefore no `timers`. The blocked event is
// terminal for maintenance: a batch is an opt-in background pass, so
// hanging it for a deadline in the hope another context goes away costs
// more than reporting BLOCKED and letting the caller retry.
//
// No `upgrade` either. The kernel reads an omitted callback as "any
// upgrade is unexpected" and rejects it, which is what maintenance has
// always done: it migrates records under a schema somebody else owns and
// must never create or change one.
admit: async (database) => {
for (const store of [
dependencies.recordStore,
dependencies.governanceStore,
dependencies.retentionStore,
dependencies.checkpointStore,
dependencies.idempotencyStore,
]) {
if (!database.objectStoreNames.contains(store)) {
return { kind: "REJECT", detail: "STORE" };
}
}
try {
const transaction = database.transaction(
dependencies.idempotencyStore,
openIndexedDbTransaction(
database,
[dependencies.idempotencyStore],
"readonly",
);
transaction
)
.objectStore(dependencies.idempotencyStore)
.index(dependencies.idempotencyExpiryIndex);
} catch {
database.close();
finish(migrationFailed());
return;
return { kind: "REJECT", detail: "INDEX" };
}
// Maintenance never holds the connection past a batch, so the listener
// belongs here rather than on a cached handle: `admit` runs on the
// successful open path only, which is exactly the window the batch
// owns the connection for.
database.onversionchange = () => database.close();
void (async () => {
const binding = await verifyIndexedDbDatasetBinding(
database,
dependencies.governanceStore,
expectedBinding,
signal,
);
if (!binding.ok) {
database.close();
if (!settled) {
finish(
binding.reason === "ABORTED"
? browserDataFailure(
"ABORTED",
"INDEXEDDB_MIGRATE",
)
: binding.reason === "NATIVE_ERROR"
? mapIndexedDbException(
binding.error,
"INDEXEDDB_MIGRATE",
)
: browserDataFailure(
"POLICY_REJECTED",
"INDEXEDDB_MIGRATE",
{
recovery:
storagePolicySnapshot.unavailableFallback,
},
),
);
}
return;
}
if (settled) {
database.close();
return;
}
finish(browserDataSuccess(database));
})();
};
const binding = await verifyIndexedDbDatasetBinding(
database,
dependencies.governanceStore,
expectedBinding,
signal,
);
if (binding.ok) return { kind: "ADMIT" };
return binding.reason === "ABORTED"
? { kind: "FAIL", cause: { kind: "CALLER_ABORT" } }
: binding.reason === "NATIVE_ERROR"
? {
kind: "FAIL",
cause: { kind: "NATIVE_EXCEPTION", error: binding.error },
}
: { kind: "REJECT", detail: "POLICY" };
},
});
}
function createTransaction(
database: IDBDatabase,
stores: readonly string[],
mode: "readonly" | "readwrite",
): IDBTransaction {
const durability =
mode === "readonly"
? dependencies.durability?.read ?? "default"
: dependencies.durability?.write ?? "strict";
try {
return database.transaction([...stores], mode, { durability });
} catch (error) {
if (error instanceof TypeError) {
return database.transaction([...stores], mode);
}
throw error;
}
}
/**
* Durability is named explicitly on both sides because maintenance rewrites
* records: a write that is only queued when the tab goes away would leave a
* checkpoint claiming rows that were never stored. The kernel falls back to
* the no-options form on an engine that rejects the bag.
*/
function runTransaction<Value>(
database: IDBDatabase,
stores: readonly string[],
@@ -610,97 +607,20 @@ export function createIndexedDbMaintenance<WireValue>(
signal: AbortSignal | undefined,
queue: (
transaction: IDBTransaction,
context: TransactionContext<Value>,
context: IndexedDbTransactionContext<Value, BrowserDataFailure>,
) => void,
): Promise<BrowserDataResult<Value>> {
const cancelled = abortedResult(signal, "INDEXEDDB_MIGRATE");
if (cancelled) return Promise.resolve(cancelled);
let transaction: IDBTransaction;
try {
transaction = createTransaction(database, stores, mode);
} catch (error) {
return Promise.resolve(
mapIndexedDbException(error, "INDEXEDDB_MIGRATE"),
);
}
return new Promise<BrowserDataResult<Value>>((resolve) => {
let candidate: BrowserDataResult<Value> | undefined;
let requestError: unknown;
let callerAborted = false;
let settled = false;
const finish = (result: BrowserDataResult<Value>) => {
if (settled) return;
settled = true;
signal?.removeEventListener("abort", onAbort);
resolve(result);
};
const abortTransaction = () => {
try {
transaction.abort();
} catch {
// Completion or a prior abort already owns the result.
}
};
function onAbort(): void {
callerAborted = true;
abortTransaction();
}
transaction.oncomplete = () => {
finish(candidate ?? unavailable());
};
transaction.onerror = () => {
requestError ??= transaction.error;
};
transaction.onabort = () => {
if (callerAborted) {
finish(
browserDataFailure("ABORTED", "INDEXEDDB_MIGRATE"),
);
return;
}
if (candidate && !candidate.ok) {
finish(candidate);
return;
}
finish(
mapIndexedDbException(
requestError ?? transaction.error,
"INDEXEDDB_MIGRATE",
),
);
};
signal?.addEventListener("abort", onAbort, { once: true });
const context: TransactionContext<Value> = Object.freeze({
succeed(value) {
if (!candidate) candidate = browserDataSuccess(value);
},
fail(result) {
if (!candidate) candidate = result;
abortTransaction();
},
requestFailed(error) {
requestError ??= error;
if (!candidate) {
candidate = mapIndexedDbException(
error,
"INDEXEDDB_MIGRATE",
);
}
},
});
try {
queue(transaction, context);
} catch (error) {
context.fail(
mapIndexedDbException(error, "INDEXEDDB_MIGRATE"),
);
}
return runIndexedDbTransaction<Value, BrowserDataFailure>({
database,
stores,
mode,
translate,
signal,
durability:
mode === "readonly"
? dependencies.durability?.read ?? "default"
: dependencies.durability?.write ?? "strict",
queue,
});
}
@@ -732,7 +652,7 @@ export function createIndexedDbMaintenance<WireValue>(
dependencies.checkpointKey,
)
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
const persisted = request.result;
@@ -777,85 +697,69 @@ export function createIndexedDbMaintenance<WireValue>(
true,
);
} catch {
context.fail(invalidInput());
context.fail(invalidInputFailure());
return;
}
if (checkpoint.effective.lastKey !== null && !query) {
context.fail(
browserDataFailure(
"UNSUPPORTED",
"INDEXEDDB_MIGRATE",
{ recovery: "ONLINE_ONLY" },
),
);
context.fail(unsupportedFailure());
return;
}
const rows: ScannedRecord[] = [];
const request = transaction
.objectStore(dependencies.recordStore)
.openCursor(query);
request.onerror = () => context.requestFailed(request.error);
request.onsuccess = () => {
if (input.signal?.aborted) {
try {
transaction.abort();
} catch {
// The transaction event decides the abort/complete race.
// The scan bounds on rows it read, so the counter the kernel offers is
// the right one here. The time check comes first so a batch that ran
// out of both answers `budgetExhausted` the way it does today.
const budget: IndexedDbBudget<BrowserDataFailure> = {
admit: (scannedRows) => {
const currentTime = clock();
if (!currentTime.ok) return currentTime;
if (currentTime.value >= deadline) {
return browserDataSuccess("TIME_BUDGET" as const);
}
return;
}
const cursor = request.result;
if (!cursor) {
context.succeed({
rows: Object.freeze(rows),
reachedEnd: true,
budgetExhausted: false,
});
return;
}
const currentTime = clock();
if (!currentTime.ok) {
context.fail(currentTime);
return;
}
if (
rows.length >= input.maxRows ||
currentTime.value >= deadline
) {
context.succeed({
rows: Object.freeze(rows),
reachedEnd: false,
budgetExhausted:
currentTime.value >= deadline,
});
return;
}
if (!isStoredRecord(cursor.value)) {
context.fail(migrationFailed());
return;
}
if (
cursor.value.codecVersion >
dependencies.migrationPolicy.targetCodecVersion
) {
context.fail(migrationFailed());
return;
}
rows.push({
key: cursor.value.key,
codecVersion: cursor.value.codecVersion,
revision: cursor.value.revision,
payload: cursor.value.payload,
});
try {
cursor.continue();
} catch (error) {
context.fail(
mapIndexedDbException(error, "INDEXEDDB_MIGRATE"),
return browserDataSuccess(
scannedRows >= input.maxRows
? ("ROW_BUDGET" as const)
: ("CONTINUE" as const),
);
}
},
};
walkIndexedDbCursor<BrowserDataFailure>({
request: transaction
.objectStore(dependencies.recordStore)
.openCursor(query),
sink: context,
translate,
budget,
signal: input.signal,
visit: ({ cursor }) => {
if (
!isStoredRecord(cursor.value) ||
cursor.value.codecVersion >
dependencies.migrationPolicy.targetCodecVersion
) {
context.fail(migrationFailure());
// `fail` aborts, so the walk has nowhere to go. Suspending
// without ever resuming says that without asking the pump for
// another row or claiming a summary the scan never reached.
return { kind: "SUSPEND" };
}
rows.push({
key: cursor.value.key,
codecVersion: cursor.value.codecVersion,
revision: cursor.value.revision,
payload: cursor.value.payload,
});
return { kind: "CONTINUE" };
},
done: (summary) => {
if (summary.reason === "ABORTED") return;
context.succeed({
rows: Object.freeze(rows),
reachedEnd: summary.reason === "EXHAUSTED",
budgetExhausted: summary.reason === "TIME_BUDGET",
});
},
});
},
);
}
@@ -1023,9 +927,7 @@ export function createIndexedDbMaintenance<WireValue>(
try {
request = checkpoints.put(stored);
} catch (error) {
context.fail(
mapIndexedDbException(error, "INDEXEDDB_MIGRATE"),
);
context.fail(mappedFailure(error));
return;
}
request.onerror = () =>
@@ -1057,7 +959,7 @@ export function createIndexedDbMaintenance<WireValue>(
const currentTime = clock();
if (!currentTime.ok) {
// A broken clock aborts rather than committing an unbounded batch.
context.fail(currentTime);
context.fail(currentTime.error);
return;
}
if (currentTime.value >= deadline) {
@@ -1069,9 +971,7 @@ export function createIndexedDbMaintenance<WireValue>(
try {
request = records.get(preparedRecord.source.key);
} catch (error) {
context.fail(
mapIndexedDbException(error, "INDEXEDDB_MIGRATE"),
);
context.fail(mappedFailure(error));
return;
}
request.onerror = () =>
@@ -1091,7 +991,7 @@ export function createIndexedDbMaintenance<WireValue>(
preparedRecord.source.key,
)
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
if (
@@ -1123,7 +1023,7 @@ export function createIndexedDbMaintenance<WireValue>(
!preparedRecord.needsMigration ||
preparedRecord.measuredBytes === undefined
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
const measuredBytes = preparedRecord.measuredBytes;
@@ -1137,7 +1037,7 @@ export function createIndexedDbMaintenance<WireValue>(
live.key,
)
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
const previousSidecar = sidecarRequest.result;
@@ -1152,7 +1052,7 @@ export function createIndexedDbMaintenance<WireValue>(
budgetRequest.result.usedBytes <
previousSidecar.measuredBytes
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
const usedBytes =
@@ -1165,7 +1065,7 @@ export function createIndexedDbMaintenance<WireValue>(
usedBytes >
storagePolicySnapshot.hardBudgetBytes
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
const writeRequest = records.put({
@@ -1221,7 +1121,7 @@ export function createIndexedDbMaintenance<WireValue>(
dependencies.checkpointKey,
)
) {
context.fail(migrationFailed());
context.fail(migrationFailure());
return;
}
liveCheckpoint = checkpointRequest.result;
@@ -1412,134 +1312,106 @@ export function createIndexedDbMaintenance<WireValue>(
let range: IDBKeyRange;
try {
if (!keyRange) {
context.fail(
browserDataFailure(
"UNSUPPORTED",
"INDEXEDDB_MIGRATE",
{ recovery: "ONLINE_ONLY" },
),
);
context.fail(unsupportedFailure());
return;
}
range = keyRange.upperBound(cutoff.value);
} catch {
context.fail(invalidInput());
context.fail(invalidInputFailure());
return;
}
const request = store
.index(dependencies.idempotencyExpiryIndex)
.openCursor(range);
let scannedRows = 0;
let deletedRows = 0;
const succeed = (
state: "MORE" | "COMPLETE",
budgetExhausted: boolean,
) => {
context.succeed(
Object.freeze({
state,
scannedRows,
deletedRows,
budgetExhausted,
}),
);
};
request.onerror = () =>
context.requestFailed(request.error);
request.onsuccess = () => {
if (input.signal?.aborted) {
try {
transaction.abort();
} catch {
// The transaction event owns the completion race.
// The prune bounds on rows it deleted, not on rows it read, so the
// counter stays here while the kernel counts scanned rows for the
// receipt. A row past the cutoff is corrupt data, not a stop
// condition, so the walk never reports STOPPED.
const budget: IndexedDbBudget<BrowserDataFailure> = {
admit: () => {
const currentTime = clock();
if (!currentTime.ok) return currentTime;
if (currentTime.value >= deadline) {
return browserDataSuccess("TIME_BUDGET" as const);
}
return;
}
const cursor = request.result;
if (!cursor) {
succeed("COMPLETE", false);
return;
}
const currentTime = clock();
if (!currentTime.ok) {
context.fail(currentTime);
return;
}
if (
deletedRows >= input.maxRows ||
currentTime.value >= deadline
) {
succeed(
"MORE",
currentTime.value >= deadline,
return browserDataSuccess(
deletedRows >= input.maxRows
? ("ROW_BUDGET" as const)
: ("CONTINUE" as const),
);
return;
}
if (
!isStoredReceipt(cursor.value) ||
cursor.value.idempotencyKey !==
String(cursor.primaryKey) ||
cursor.value.expiresAtEpochMs > cutoff.value
) {
context.fail(migrationFailed());
return;
}
scannedRows += 1;
let deleteRequest: IDBRequest<undefined>;
try {
deleteRequest = store.delete(
cursor.primaryKey,
);
} catch (error) {
context.fail(
mapIndexedDbException(
error,
"INDEXEDDB_MIGRATE",
),
);
return;
}
deleteRequest.onerror = () =>
context.requestFailed(deleteRequest.error);
deleteRequest.onsuccess = () => {
const budgetRequest = governance.get(
INDEXEDDB_DATASET_BUDGET_KEY,
);
budgetRequest.onerror = () =>
context.requestFailed(budgetRequest.error);
budgetRequest.onsuccess = () => {
if (
!isStoredDatasetBudget(budgetRequest.result) ||
budgetRequest.result.receiptCount < 1
) {
context.fail(migrationFailed());
return;
}
const budgetWrite = governance.put({
...budgetRequest.result,
receiptCount:
budgetRequest.result.receiptCount - 1,
} satisfies StoredDatasetBudget);
budgetWrite.onerror = () =>
context.requestFailed(budgetWrite.error);
budgetWrite.onsuccess = () => {
deletedRows += 1;
try {
cursor.continue();
} catch (error) {
context.fail(
mapIndexedDbException(
error,
"INDEXEDDB_MIGRATE",
),
);
},
};
walkIndexedDbCursor<BrowserDataFailure>({
request: store
.index(dependencies.idempotencyExpiryIndex)
.openCursor(range),
sink: context,
translate,
budget,
signal: input.signal,
visit: ({ cursor, resume }) => {
if (
!isStoredReceipt(cursor.value) ||
cursor.value.idempotencyKey !==
String(cursor.primaryKey) ||
cursor.value.expiresAtEpochMs > cutoff.value
) {
context.fail(migrationFailure());
return { kind: "SUSPEND" };
}
let deleteRequest: IDBRequest<undefined>;
try {
deleteRequest = store.delete(cursor.primaryKey);
} catch (error) {
context.fail(mappedFailure(error));
return { kind: "SUSPEND" };
}
deleteRequest.onerror = () =>
context.requestFailed(deleteRequest.error);
deleteRequest.onsuccess = () => {
const budgetRequest = governance.get(
INDEXEDDB_DATASET_BUDGET_KEY,
);
budgetRequest.onerror = () =>
context.requestFailed(budgetRequest.error);
budgetRequest.onsuccess = () => {
if (
!isStoredDatasetBudget(budgetRequest.result) ||
budgetRequest.result.receiptCount < 1
) {
context.fail(migrationFailure());
return;
}
const budgetWrite = governance.put({
...budgetRequest.result,
receiptCount:
budgetRequest.result.receiptCount - 1,
} satisfies StoredDatasetBudget);
budgetWrite.onerror = () =>
context.requestFailed(budgetWrite.error);
budgetWrite.onsuccess = () => {
deletedRows += 1;
resume({ kind: "CONTINUE" });
};
};
};
};
};
// The receipt is only counted once its whole delete chain
// commits, so the cursor stays parked until `resume`.
return { kind: "SUSPEND" };
},
done: (summary) => {
if (summary.reason === "ABORTED") return;
context.succeed(
Object.freeze({
state:
summary.reason === "EXHAUSTED"
? ("COMPLETE" as const)
: ("MORE" as const),
scannedRows: summary.scannedRows,
deletedRows,
budgetExhausted: summary.reason === "TIME_BUDGET",
}),
);
},
});
},
);
return observeResult(
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -46,8 +46,6 @@ type TelemetryLifecycle = "ACTIVE" | "DISPOSED";
/** N-11. Documented absolute ceiling for the in-memory best-effort queue. */
export const MAX_TELEMETRY_QUEUE = 10_000;
export { assertBoundedCapacity } from "../platform/bounded-capacity.ts";
export function createTelemetryAdapter(
options: TelemetryAdapterOptions,
+7
View File
@@ -0,0 +1,7 @@
export {
createTelemetryAdapter,
MAX_TELEMETRY_QUEUE,
noOpTelemetry,
type TelemetryAdapter,
type TelemetryAdapterOptions,
} from "./best-effort-telemetry.ts";
+4 -2
View File
@@ -4,8 +4,10 @@
* The implementation lives in `src/contracts/compatibility.ts`: it is a pure
* predicate over release tokens with no application state, and
* `src/contracts/release-tokens.ts` needs it, which previously made contracts
* import the application layer. This module re-exports it for application-side
* and script-side callers.
* import the application layer. This module is retained only as a migration
* shim; internal callers use src/contracts/compatibility.ts directly.
*
* @deprecated Import compatibility contracts from ../../contracts/compatibility.ts.
*/
export {
COMPATIBILITY_TUPLE_FIELDS,
@@ -21,9 +21,23 @@ export type IndexedDbSynchronizationState =
| "CONFIRMED";
export type IndexedDbConnectionStatus =
| Readonly<{ kind: "CLOSED"; reason: "NOT_OPENED" | "VERSION_CHANGE" | "FORCED" }>
| Readonly<{
kind: "CLOSED";
/**
* NOT_OPENED means the current open attempt has settled without a live
* connection. A blocked upgrade may therefore be observed as BLOCKED
* while it is waiting, then transition to CLOSED/NOT_OPENED when its
* blocked deadline fails closed.
*/
reason: "NOT_OPENED" | "VERSION_CHANGE" | "FORCED";
}>
| Readonly<{ kind: "OPENING"; targetVersion: number }>
| Readonly<{
/**
* A live open/upgrade attempt is currently waiting for another
* IndexedDB context. BLOCKED is transient and is not the settled state
* after the blocked deadline has expired.
*/
kind: "BLOCKED";
currentVersion: number;
targetVersion: number;
+5 -9
View File
@@ -1,13 +1,9 @@
/**
* The single success/failure carrier used across application input boundaries.
* Adapters map technology-specific errors to an application failure before
* constructing this value.
* Compatibility re-export for application-side callers from older revisions.
*
* The type itself lives in `src/contracts` because both layers need it and
* neither owns it: `src/contracts/server-state.ts` and
* `src/contracts/cursor-pagination.ts` reached back into the application layer
* for it, which made the ownership of the shared vocabulary ambiguous in both
* directions. Contracts is the lower of the two, so the shared shape sits there
* and this module re-exports it for every existing application-side importer.
* The canonical Result definition is src/contracts/result.ts. New code should
* import it from that module so the shared carrier has one public authority.
*
* @deprecated Import Result from ../contracts/result.ts.
*/
export type { Result } from "../contracts/result.ts";
+1 -1
View File
@@ -1,6 +1,6 @@
import { createRoot } from "react-dom/client";
import { recordBootFailure } from "../adapters/diagnostics/bounded-diagnostics.ts";
import { recordBootFailure } from "../adapters/diagnostics/index.ts";
import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx";
import "pretendard/dist/web/variable/pretendardvariable.css";
import "@fontsource/ibm-plex-mono/400.css";
+1 -1
View File
@@ -1,7 +1,7 @@
import {
createBrowserLifecycleRuntime,
type BrowserLifecycleRuntime,
} from "../adapters/platform/browser-lifecycle.ts";
} from "../adapters/platform/index.ts";
import type {
ResolvedRuntimeCapabilities,
RuntimeHealth,
+1 -1
View File
@@ -2,7 +2,7 @@ import type {
ResolvedRuntimeCapabilities,
} from "../contracts/runtime-capabilities.ts";
import type { ServiceWorkerRuntimeHost } from "../contracts/service-worker.ts";
import { createServiceWorkerPageController } from "../adapters/service-worker/service-worker-page-controller.ts";
import { createServiceWorkerPageController } from "../adapters/service-worker/index.ts";
/**
* §17.5. Composition-side factory. The host object is created without any
+91 -33
View File
@@ -3,13 +3,14 @@ import {
createExternalAuthSessionAdapter,
createUnavailableSessionAdapter,
type ExternalSessionOwner,
} from "../adapters/auth/external-session-adapter.ts";
import { createDiagnosticsAdapter } from "../adapters/diagnostics/bounded-diagnostics.ts";
import { createHttpClient } from "../adapters/http/client.ts";
} from "../adapters/auth/index.ts";
import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts";
import {
createContractHttpExecutor,
createHttpClient,
type HttpExecutionObservation,
} from "../adapters/http/http-execution-v3.ts";
type InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
import {
attemptBucket,
durationBucket,
@@ -19,14 +20,14 @@ import {
import type { TelemetryEventName } from "../contracts/telemetry.ts";
import { createBrowserCrossContextInvalidationFromHost } from "../adapters/cross-context-invalidation/index.ts";
import {
createConditionalValidatorStore,
createQueryClient,
createServerStateScopeRuntime,
createTanStackCacheCoordinator,
} from "../adapters/query-cache/tanstack-cache-coordinator.ts";
import { createQueryClient } from "../adapters/query-cache/tanstack-query-cache.ts";
import { createServerStateScopeRuntime } from "../adapters/query-cache/server-state-scope-runtime.ts";
import { createConditionalValidatorStore } from "../adapters/query-cache/conditional-validator-store.ts";
import { createBrowserStorageAdapter } from "../adapters/storage/browser-storage-adapter.ts";
import { createBrowserMutationIntentFactory } from "../adapters/platform/browser-mutation-intent-factory.ts";
import { createTelemetryAdapter } from "../adapters/telemetry/best-effort-telemetry.ts";
} from "../adapters/query-cache/index.ts";
import { createBrowserStorageAdapter } from "../adapters/storage/index.ts";
import { createBrowserMutationIntentFactory } from "../adapters/platform/index.ts";
import { createTelemetryAdapter } from "../adapters/telemetry/index.ts";
import { createCsrfTokenProvider } from "../features/tech-log/adapters/http/studio-session-csrf.ts";
import {
attachStudioSessionCredentials,
@@ -69,6 +70,21 @@ import {
} 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를 rollback/compatibility 경로로 쓰려는 제품은 이 네 슬롯을 주입해야
* 한다. 주입하지 않은 채 V3에서 되돌리면 모든 요청이 실패한다.
* V3(`createContractHttpExecutor`)는 설치된 feature 계약에서 오퍼레이션을
* 받으므로 이 슬롯과 무관하게 동작한다.
*/
export type RuntimeHttpContract = Pick<
HttpClientDependencies,
"getOperation" | "validatePayload" | "validateRequest" | "mapPayload"
@@ -436,10 +452,10 @@ export async function createRuntimeAdapters(
* entirely and must set the header itself. If each built its own provider,
* one Studio session would hold two different tokens.
*
* `execute` calls `getStudioSession` through `contractOperations`, which is
* declared further below — a real ordering hazard, since `attachCredentials`
* (needed to build `contractHttp`, needed to build `contractOperations`)
* needs this provider first.
* `execute` calls `getStudioSession` through `techLogOperations`, which is
* assigned further below — a real ordering hazard, since `attachCredentials`
* (needed to build `contractHttp`, needed to build `contractOperations`,
* needed to build `techLogOperations`) needs this provider first.
*
* Fix round 1 (C1). The original comment here claimed "`getStudioSession`
* is a SAFE operation and needs no CSRF, so there is no true cycle" — that
@@ -462,17 +478,17 @@ export async function createRuntimeAdapters(
* `await` between this declaration and the real assignment, where a stub
* fails loudly instead.
*/
let contractOperations: TechLogStudioOperationExecutor = Object.freeze({
let techLogOperations: TechLogStudioOperationExecutor = Object.freeze({
async execute() {
throw new Error(
"contractOperations used before assignment in createRuntimeAdapters — " +
"techLogOperations used before assignment in createRuntimeAdapters — " +
"construction order regressed.",
);
},
});
const techLogCsrf = createCsrfTokenProvider({
async execute(options) {
const outcome = await contractOperations.execute(
const outcome = await techLogOperations.execute(
"getStudioSession",
{},
{
@@ -554,19 +570,13 @@ export async function createRuntimeAdapters(
},
observe: createHttpObservationProjector({ diagnostics, telemetry }),
});
contractOperations = Object.freeze({
async execute(
operationId: string,
input: unknown,
executionContext: Readonly<{
routeId: string;
signal?: AbortSignal;
intent?: MutationIntent;
}>,
) {
const operation =
COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(operationId);
if (!operation) {
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,
@@ -576,7 +586,11 @@ export async function createRuntimeAdapters(
}),
});
}
const outcome = await contractHttp.execute(operation, input, {
// 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
@@ -608,8 +622,52 @@ export async function createRuntimeAdapters(
return outcome;
},
});
/**
* Template sync (ebea300). The platform executor above now takes the
* installed contract itself, so a feature's Input/WireOutput/Problem types
* flow through `createFeatureHttpBinding`. TechLog's four HTTP gateways
* still address operations by id through its own `StudioOperationExecutor`,
* so the id is resolved to the installed contract here — at the one place
* that already owns the registry — instead of being resolved inside the
* platform executor for every caller. Porting those gateways onto the typed
* binding is its own change; nothing about it is decided here.
*
* `!installed` returns the same `FINAL_REQUEST_INVARIANT_FAILED` violation
* the platform executor returns for an operation that is not installed, so
* an unregistered id fails identically on both paths.
*/
techLogOperations = Object.freeze({
async execute(
operationId: string,
input: unknown,
executionContext: Readonly<{
routeId: string;
signal?: AbortSignal;
intent?: MutationIntent;
}>,
) {
const installed =
COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(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,
}),
});
}
return contractOperations.execute(
installed as Parameters<typeof contractOperations.execute>[0],
input,
executionContext,
);
},
});
const featureInputs = createInstalledFeatureInputs({
contractOperations,
http: contractOperations,
contractOperations: techLogOperations,
studioSource: config.TECH_LOG_STUDIO_SOURCE,
publicSource: config.TECH_LOG_PUBLIC_SOURCE,
apiBaseUrl: config.API_BASE_URL,
@@ -0,0 +1,176 @@
import type {
ApplicationFeatureId,
ApplicationFeatureInputs,
} from "../application/ports/in/application-api.ts";
import type {
InstalledHttpOperationExecutor,
} from "../adapters/http/index.ts";
/**
* Features augment this registry with the repository identities they consume.
* The provider is a composition capability; feature use cases never import it.
*/
export interface FeatureIndexedDbRepositories {}
export type FeatureIndexedDbRepositoryId = Extract<
keyof FeatureIndexedDbRepositories,
string
>;
export type IndexedDbRepositoryProvider = Readonly<{
get<RepositoryId extends FeatureIndexedDbRepositoryId>(
repositoryId: RepositoryId,
): FeatureIndexedDbRepositories[RepositoryId];
}>;
export function createIndexedDbRepositoryProvider(
repositories: Readonly<Partial<FeatureIndexedDbRepositories>>,
): IndexedDbRepositoryProvider {
const snapshot = Object.freeze({ ...repositories });
return Object.freeze({
get<RepositoryId extends FeatureIndexedDbRepositoryId>(
repositoryId: RepositoryId,
): FeatureIndexedDbRepositories[RepositoryId] {
const repository = snapshot[repositoryId];
if (!repository) {
throw new TypeError(
`IndexedDB repository is not installed: ${repositoryId}`,
);
}
return repository as FeatureIndexedDbRepositories[RepositoryId];
},
});
}
export type FeaturePlatformCapabilities = Readonly<{
http: InstalledHttpOperationExecutor;
indexedDb: IndexedDbRepositoryProvider;
}>;
export type FeaturePlatformCapabilityId =
keyof FeaturePlatformCapabilities;
export type FeatureCapabilitySelection<
Needs extends readonly FeaturePlatformCapabilityId[],
> = Pick<FeaturePlatformCapabilities, Needs[number]>;
const FEATURE_ADAPTER_CONTRIBUTION = Symbol(
"feature-adapter-contribution",
);
type FeatureAdapterContributionDefinition<
FeatureId extends ApplicationFeatureId,
Needs extends readonly FeaturePlatformCapabilityId[],
> = Readonly<{
featureId: FeatureId;
needs: Needs;
createInput(
context: FeatureCapabilitySelection<Needs>,
): Readonly<{
featureId: FeatureId;
input: ApplicationFeatureInputs[FeatureId];
}>;
}>;
export type FeatureAdapterContribution<
FeatureId extends ApplicationFeatureId,
Needs extends readonly FeaturePlatformCapabilityId[],
> = FeatureAdapterContributionDefinition<FeatureId, Needs> &
Readonly<{
[FEATURE_ADAPTER_CONTRIBUTION]: true;
}>;
export function defineFeatureAdapterContribution<
const FeatureId extends ApplicationFeatureId,
const Needs extends readonly FeaturePlatformCapabilityId[],
>(
contribution: FeatureAdapterContributionDefinition<FeatureId, Needs>,
): FeatureAdapterContribution<FeatureId, Needs> {
return Object.freeze({
...contribution,
needs: Object.freeze([...contribution.needs]) as unknown as Needs,
[FEATURE_ADAPTER_CONTRIBUTION]: true as const,
});
}
type ContributionShape = Readonly<{
[FEATURE_ADAPTER_CONTRIBUTION]: true;
featureId: ApplicationFeatureId;
needs: readonly FeaturePlatformCapabilityId[];
createInput: (...args: never[]) => unknown;
}>;
type ContributionNeeds<Contribution> =
Contribution extends Readonly<{
needs: readonly (infer Capability)[];
}>
? Extract<Capability, FeaturePlatformCapabilityId>
: never;
export type ContributionsCapabilityContext<
Contributions extends readonly ContributionShape[],
> = Pick<
FeaturePlatformCapabilities,
ContributionNeeds<Contributions[number]>
>;
export type InstalledFeatureInputs = Readonly<
Partial<ApplicationFeatureInputs>
>;
function setFeatureInput<FeatureId extends ApplicationFeatureId>(
target: Partial<ApplicationFeatureInputs>,
featureId: FeatureId,
input: ApplicationFeatureInputs[FeatureId],
): void {
const writable = target as Record<
ApplicationFeatureId,
ApplicationFeatureInputs[ApplicationFeatureId]
>;
writable[featureId] = input;
}
function invokeContribution<
FeatureId extends ApplicationFeatureId,
Needs extends readonly FeaturePlatformCapabilityId[],
>(
contribution: FeatureAdapterContribution<FeatureId, Needs>,
context: FeaturePlatformCapabilities,
) {
return contribution.createInput(context);
}
/**
* Dynamic catalog assembly stays centralized here. Type authority lives at each
* feature contribution; the only dynamic write is isolated in setFeatureInput.
*/
export function composeFeatureAdapterInputs<
const Contributions extends readonly ContributionShape[],
>(
contributions: Contributions,
enabledFeatureIds: readonly string[],
context: ContributionsCapabilityContext<Contributions>,
): InstalledFeatureInputs {
const enabled = new Set<string>(enabledFeatureIds);
const result: Partial<ApplicationFeatureInputs> = {};
for (const contribution of contributions) {
if (contribution[FEATURE_ADAPTER_CONTRIBUTION] !== true) {
throw new TypeError(
"Feature adapter contribution must be defined through defineFeatureAdapterContribution()",
);
}
if (!enabled.has(contribution.featureId)) continue;
const installed = invokeContribution(
contribution as unknown as FeatureAdapterContribution<
ApplicationFeatureId,
readonly FeaturePlatformCapabilityId[]
>,
context as FeaturePlatformCapabilities,
);
setFeatureInput(result, installed.featureId, installed.input);
}
return Object.freeze(result);
}
@@ -3,35 +3,39 @@ import {
type InstalledContractContribution,
type InstalledContractPackageIdentity,
} from "../contracts/external-contract-runtime.ts";
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./reference-feature/contracts/reference-feature-contract-contribution.ts";
import { REFERENCE_FEATURE_ID } from "./reference-feature/contracts/reference-feature-contract.ts";
import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./reference-feature/contracts/reference-feature-contract-contribution.ts";
import { TECH_LOG_MANAGEMENT_CONTRIBUTION } from "./tech-log/contracts/tech-log-management-contract-contribution.ts";
import { TECH_LOG_PUBLIC_CONTRIBUTION } from "./tech-log/contracts/tech-log-public-contract-contribution.ts";
import { TECH_LOG_STUDIO_CONTRIBUTION } from "./tech-log/contracts/tech-log-studio-contract-contribution.ts";
const COMPILED_CONTRACT_CONTRIBUTIONS = Object.freeze([
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION,
] as const);
/**
* §4.8. Static contract selection SSOT.
* Central contract installation is aggregation only.
*
* A product feature adds exactly one entry per service package here and imports
* the generated package only from
* `src/features/<feature>/contracts/<service>-contract-contribution.ts`.
* Each feature owns its concrete service/package contribution. This catalog
* selects contributions whose feature is installed; it does not contain
* feature-specific branching or service wiring.
*
* Template sync (ebea300). The manifest-governed contributions are now selected
* by their own `featureId` rather than by this file naming the reference
* feature, so installing another selectable feature is one entry above and no
* edit here. TechLog's three contributions are appended unconditionally: it is
* this product's own domain, not a `SelectableProductFeature`, so the manifest
* does not govern it and the filter must not be able to drop it.
*/
export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] =
Object.freeze(
INSTALLED_PRODUCT_FEATURE_IDS.includes(REFERENCE_FEATURE_ID)
? [
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION,
TECH_LOG_STUDIO_CONTRIBUTION,
TECH_LOG_PUBLIC_CONTRIBUTION,
TECH_LOG_MANAGEMENT_CONTRIBUTION,
]
: [
TECH_LOG_STUDIO_CONTRIBUTION,
TECH_LOG_PUBLIC_CONTRIBUTION,
TECH_LOG_MANAGEMENT_CONTRIBUTION,
],
);
Object.freeze([
...COMPILED_CONTRACT_CONTRIBUTIONS.filter((contribution) =>
INSTALLED_PRODUCT_FEATURE_IDS.includes(contribution.featureId),
),
TECH_LOG_STUDIO_CONTRIBUTION,
TECH_LOG_PUBLIC_CONTRIBUTION,
TECH_LOG_MANAGEMENT_CONTRIBUTION,
]);
export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions(
INSTALLED_CONTRACT_CONTRIBUTIONS,
+42 -34
View File
@@ -1,44 +1,52 @@
import type { ApplicationFeatureInputs } from "../application/ports/in/application-api.ts";
import { createReferenceFeatureInstalledInput } from "./reference-feature/adapters/create-reference-feature-input.ts";
import { REFERENCE_FEATURE_ID } from "./reference-feature/contracts/reference-feature-contract.ts";
import { createTechLogFeatureInstalledInput } from "./tech-log/adapters/create-tech-log-feature-input.ts";
import type { CsrfTokenProvider } from "./tech-log/adapters/http/studio-session-csrf.ts";
import {
composeFeatureAdapterInputs,
type ContributionsCapabilityContext,
type InstalledFeatureInputs,
} from "./feature-adapter-contribution.ts";
import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./reference-feature/adapters/create-reference-feature-input.ts";
import {
createTechLogFeatureInstalledInput,
type TechLogInstallContext,
} from "./tech-log/adapters/create-tech-log-feature-input.ts";
import { TECH_LOG_FEATURE_ID } from "./tech-log/application/tech-log-feature-input.ts";
import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts";
const COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze([
REFERENCE_FEATURE_ADAPTER_CONTRIBUTION,
] as const);
type InstalledFeatureCapabilityContext =
ContributionsCapabilityContext<
typeof COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS
>;
/**
* §3.5. Partial on purpose: a feature the manifest did not select supplies no
* driving input, so consumers have to narrow before calling one. A total type
* here would let feature code compile against an input that is not there.
* Central adapter composition only selects and aggregates feature-owned
* contributions. The feature owns how its application input is bound to the
* reusable platform capabilities declared by its `needs` list.
*
* Template sync (ebea300). TechLog is this product's own domain rather than a
* `SelectableProductFeature`, so it is composed directly instead of through
* the manifest: `INSTALLED_PRODUCT_FEATURE_IDS` does not govern it and its
* input is therefore total, while every manifest-governed contribution stays
* optional because a build may narrow it out. This is the same split the
* previous sync recorded — see `docs/operations/template-merge-2026-08-17.md`
* — expressed through the template's new contribution mechanism.
*/
type InstalledFeatureInputs = Readonly<
// Template merge. The reference feature is optional — the manifest may
// narrow it out — so its input stays `Partial`. TechLog is this product's
// own UI and is always installed, so its input is total.
Partial<Pick<ApplicationFeatureInputs, typeof REFERENCE_FEATURE_ID>> &
Pick<ApplicationFeatureInputs, typeof TECH_LOG_FEATURE_ID>
>;
type ProductFeatureInputs = InstalledFeatureInputs &
Readonly<Pick<ApplicationFeatureInputs, typeof TECH_LOG_FEATURE_ID>>;
export function createInstalledFeatureInputs(
context: Parameters<typeof createReferenceFeatureInstalledInput>[0] &
Readonly<{
studioSource: "MOCK" | "HTTP";
publicSource: "MOCK" | "HTTP";
apiBaseUrl: string;
requestTimeoutMs: number;
csrf: CsrfTokenProvider;
}>,
): InstalledFeatureInputs {
const techLogFeature = createTechLogFeatureInstalledInput(context);
if (!INSTALLED_PRODUCT_FEATURE_IDS.includes(REFERENCE_FEATURE_ID)) {
// A build that narrowed the reference feature out still ships TechLog.
return Object.freeze({
[techLogFeature.featureId]: techLogFeature.input,
}) as InstalledFeatureInputs;
}
const referenceFeature = createReferenceFeatureInstalledInput(context);
context: InstalledFeatureCapabilityContext & TechLogInstallContext,
): ProductFeatureInputs {
const techLog = createTechLogFeatureInstalledInput(context);
return Object.freeze({
[referenceFeature.featureId]: referenceFeature.input,
[techLogFeature.featureId]: techLogFeature.input,
}) as InstalledFeatureInputs;
...composeFeatureAdapterInputs(
COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS,
INSTALLED_PRODUCT_FEATURE_IDS,
context,
),
[techLog.featureId]: techLog.input,
}) as ProductFeatureInputs;
}
+14 -4
View File
@@ -7,13 +7,23 @@ import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.tsx
* §3.5. A feature the manifest did not select contributes no codec and no route
* component, so the router has nothing to mount for it.
*
* Template merge. The template gated the reference feature's codecs and route
* components on the manifest. This product deleted that feature's presentation
* layer during the UI migration, so there is nothing left to gate — the import
* would not resolve. The gating belongs back here the day those screens return.
* Template merge. The template aggregates feature-owned runtime contributions
* here and filters them through the manifest — as of ebea300 through
* `COMPILED_FEATURE_RUNTIME_CONTRIBUTIONS`. This product deleted the reference
* feature's presentation layer during the UI migration, so there is no
* contribution to compile and nothing to gate; the import would not resolve.
* Carrying an empty contribution list plus the filter would be dead code that
* neither repository runs, so the aggregation belongs back here the day those
* screens return, together with the contribution they export.
*
* TechLog is spread unconditionally: it is this product's own UI, not a
* selectable feature. The platform entries are empty on this branch and are
* kept in the spread so a later platform route lands here without another edit.
*
* The object spread is also what keeps both catalogs precisely typed: the
* template's `Object.assign(..., ...contributions.map(...))` widens its result
* to `any`, which this product's router cannot afford — it resolves codecs and
* components by route id off these two objects.
*/
export const ROUTE_CODECS = Object.freeze({
...PLATFORM_ROUTE_CODECS,
@@ -0,0 +1,41 @@
import type {
IndexedDbRepositoryPort,
} from "../../../application/ports/browser-file-storage/index.ts";
import {
defineFeatureAdapterContribution,
} from "../../feature-adapter-contribution.ts";
import type {} from "../../feature-adapter-contribution.ts";
import {
createLocalDraftFeatureInput,
} from "../application/local-draft-api.ts";
import type { LocalDraft } from "../domain/local-draft.ts";
import {
LOCAL_DRAFT_FEATURE_ID,
LOCAL_DRAFT_REPOSITORY_ID,
} from "../contracts/local-draft-contract.ts";
import { createLocalDraftStore } from "./local-draft-indexeddb-store.ts";
declare module "../../feature-adapter-contribution.ts" {
interface FeatureIndexedDbRepositories {
"local-draft": IndexedDbRepositoryPort<LocalDraft, never>;
}
}
export function createLocalDraftFeatureInstalledInput(context: Readonly<{
indexedDb: Readonly<{
get(repositoryId: "local-draft"): IndexedDbRepositoryPort<LocalDraft, never>;
}>;
}>) {
const repository = context.indexedDb.get(LOCAL_DRAFT_REPOSITORY_ID);
return Object.freeze({
featureId: LOCAL_DRAFT_FEATURE_ID,
input: createLocalDraftFeatureInput(createLocalDraftStore(repository)),
});
}
export const LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION =
defineFeatureAdapterContribution({
featureId: LOCAL_DRAFT_FEATURE_ID,
needs: ["indexedDb"] as const,
createInput: createLocalDraftFeatureInstalledInput,
});
@@ -0,0 +1,105 @@
import type {
BrowserDataFailure,
IndexedDbRepositoryPort,
} from "../../../application/ports/browser-file-storage/index.ts";
import {
createFailure,
type AppFailure,
type FailureKind,
} from "../../../contracts/errors.ts";
import type { Result } from "../../../contracts/result.ts";
import type {
LocalDraftStore,
LocalDraftRecord,
RemoveLocalDraftCommand,
SaveLocalDraftCommand,
} from "../application/local-draft-api.ts";
import type { LocalDraft } from "../domain/local-draft.ts";
function failureKind(failure: BrowserDataFailure): FailureKind {
if (failure.code === "QUOTA_EXCEEDED") return "STORAGE_QUOTA_EXCEEDED";
if (failure.code === "CONFLICT") return "CONFLICT";
if (failure.code === "ABORTED") return "REQUEST_ABORTED";
return "STORAGE_UNAVAILABLE";
}
function mapFailure(
failure: BrowserDataFailure,
operationId: string,
): AppFailure {
return createFailure(failureKind(failure), operationId, 0, {
code: `INDEXEDDB_${failure.code}`,
});
}
function failed<Value>(
failure: BrowserDataFailure,
operationId: string,
): Result<Value> {
return Object.freeze({
ok: false as const,
error: mapFailure(failure, operationId),
});
}
/**
* Feature-owned adapter over the reusable IndexedDB repository capability.
* Native IDB objects, migrations, connection leases and quota internals do not
* cross this file.
*/
export function createLocalDraftStore(
repository: IndexedDbRepositoryPort<LocalDraft, never>,
): LocalDraftStore {
return Object.freeze({
async save(command: SaveLocalDraftCommand, signal?: AbortSignal) {
const result = await repository.compareAndSwap({
key: command.draft.draftId,
value: command.draft,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
signal,
});
return result.ok
? Object.freeze({
ok: true as const,
value: Object.freeze({ revision: result.value.revision }),
})
: failed<Readonly<{ revision: number }>>(
result.error,
"LOCAL_DRAFT_SAVE",
);
},
async find(draftId: string, signal?: AbortSignal) {
const result = await repository.read(draftId, signal);
if (!result.ok) {
return failed<LocalDraftRecord | null>(
result.error,
"LOCAL_DRAFT_FIND",
);
}
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: RemoveLocalDraftCommand, signal?: AbortSignal) {
const result = await repository.remove({
key: command.draftId,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
signal,
});
return result.ok
? Object.freeze({ ok: true as const, value: undefined })
: failed<void>(result.error, "LOCAL_DRAFT_REMOVE");
},
});
}
@@ -0,0 +1,72 @@
import type { Result } from "../../../contracts/result.ts";
import type {} from "../../../application/ports/in/application-api.ts";
import type { LocalDraft } from "../domain/local-draft.ts";
export type LocalDraftRecord = Readonly<{
draft: LocalDraft;
revision: number;
}>;
export type SaveLocalDraftCommand = Readonly<{
draft: LocalDraft;
expectedRevision: number | null;
idempotencyKey: string;
}>;
export type RemoveLocalDraftCommand = Readonly<{
draftId: string;
expectedRevision: number;
idempotencyKey: string;
}>;
export type LocalDraftStore = Readonly<{
save(
command: SaveLocalDraftCommand,
signal?: AbortSignal,
): Promise<Result<Readonly<{ revision: number }>>>;
find(
draftId: string,
signal?: AbortSignal,
): Promise<Result<LocalDraftRecord | null>>;
remove(
command: RemoveLocalDraftCommand,
signal?: AbortSignal,
): Promise<Result<void>>;
}>;
export type LocalDraftFeatureInput = Readonly<{
saveDraft(
command: SaveLocalDraftCommand,
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<Result<Readonly<{ revision: number }>>>;
findDraft(
draftId: string,
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<Result<LocalDraftRecord | null>>;
removeDraft(
command: RemoveLocalDraftCommand,
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<Result<void>>;
}>;
declare module "../../../application/ports/in/application-api.ts" {
interface ApplicationFeatureInputs {
"local-draft": LocalDraftFeatureInput;
}
}
export function createLocalDraftFeatureInput(
store: LocalDraftStore,
): LocalDraftFeatureInput {
return Object.freeze({
saveDraft(command, context) {
return store.save(command, context?.signal);
},
findDraft(draftId, context) {
return store.find(draftId, context?.signal);
},
removeDraft(command, context) {
return store.remove(command, context?.signal);
},
});
}
@@ -0,0 +1,2 @@
export const LOCAL_DRAFT_FEATURE_ID = "local-draft" as const;
export const LOCAL_DRAFT_REPOSITORY_ID = "local-draft" as const;
@@ -0,0 +1,21 @@
export type LocalDraft = Readonly<{
draftId: string;
title: string;
body: string;
}>;
export function createLocalDraft(values: LocalDraft): LocalDraft {
const draftId = values.draftId.trim();
const title = values.title.trim();
if (!draftId || !title) {
throw new TypeError("Local draft requires draftId and title");
}
if (title.length > 160 || values.body.length > 100_000) {
throw new TypeError("Local draft exceeds bounded field limits");
}
return Object.freeze({
draftId,
title,
body: values.body,
});
}
+19 -12
View File
@@ -19,16 +19,19 @@ augmentation으로 `"reference-feature": ReferenceFeatureInput`을 기여하므
별도 cast나 runtime shape 확인 없이 정확한 input type을 받는다. 다만 동적 호출로
설치되지 않은 ID가 들어오는 경우를 위해 `get`의 runtime guard도 유지한다.
예측 가능한 실패는 `src/application/result.ts`의 공통
`Result<Value, Failure = AppFailure>`로 반환한다. `AppFailure.kind`는
예측 가능한 실패는 canonical shared contract인
`src/contracts/result.ts`의 `Result<Value, Failure = AppFailure>`로 반환한다.
`src/application/result.ts`는 기존 호출자를 위한 deprecated migration shim일
뿐 새 코드의 import 경로가 아니다. `AppFailure.kind`는
`ERROR_REGISTRY` key에서 파생된 닫힌 vocabulary이며, transport 호환 이름인
`ApiFailure`는 같은 type의 alias다.
HTTP adapter의 operation map은 operation ID마다 허용된 route ID, request shape와
성공 value type을 함께 묶는다. raw HTTP executor의 성공값은 Zod request/response
검증과 feature mapper를 통과한 뒤 operation별 runtime result guard에서 typed
executor로 승격된다. 따라서 gateway 메서드는 개별 응답 cast 없이 정확한 결과를
반환하고, operation/route/request 조합 오류는 typecheck에서 차단된다.
HTTP adapter는 `src/adapters/http/feature-http-binding.ts`의 capability-specific
typed binding을 사용한다. feature는 operation ID, route ID, request type, 성공
value type, mapper만 소유한다. timeout/cancellation/auth/transport/contract
violation을 `AppFailure`로 정규화하는 책임은 reusable HTTP capability가 소유한다.
따라서 gateway 메서드는 transport outcome이나 runtime result guard를 반복 구현하지
않고도 정확한 결과 타입을 반환한다.
route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route type은
`route-contract.ts`, React context/provider/hook은 `route-input.tsx`가 각각
@@ -39,12 +42,16 @@ route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route t
## 설치 지점
- 직렬화 계약: `src/features/installed-feature-contracts.ts`
- component/codec: `src/features/installed-feature-runtimes.tsx`
- bootstrap input 조립: `src/features/installed-feature-adapters.ts`
feature가 실제 contribution을 소유한다.
새 기능도 이 세 지점에 contribution을 합성하되 feature ID를 generic application,
router나 HTTP client에 하드코딩하지 않는다.
- contract: `reference-feature-contract.ts`
- component/codec: `REFERENCE_FEATURE_RUNTIME_CONTRIBUTION`
- bootstrap input: `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`
중앙 파일인 `installed-feature-contracts.ts`,
`installed-feature-runtimes.tsx`, `installed-feature-adapters.ts`는 선택된
contribution을 합치는 역할만 한다. 새 기능의 내부 조립 규칙을 중앙 catalog에
추가하지 않는다.
## 검증과 제거
@@ -1,195 +1,45 @@
import type { Result } from "../../../application/result.ts";
import type { ApiFailure, FailureKind } from "../../../contracts/errors.ts";
import type { FailureEffectCertainty } from "../../../contracts/errors.ts";
import type { MutationIntent } from "../../../contracts/mutation-intent.ts";
import {
createFailure,
kindForStatus,
} from "../../../contracts/errors.ts";
import type { HttpExecutionOutcome } from "../../../adapters/http/http-execution-v3.ts";
createFeatureHttpBinding,
type InstalledHttpOperationExecutor,
} from "../../../adapters/http/index.ts";
import {
defineFeatureAdapterContribution,
} from "../../feature-adapter-contribution.ts";
import { createReferenceFeatureInput } from "../application/reference-feature-api.ts";
import {
REFERENCE_FEATURE_ID,
} from "../contracts/reference-feature-contract.ts";
import { mapReferenceOperation } from "../contracts/reference-mapper.ts";
import {
createReferenceHttpGateway,
type RawReferenceHttpExecutor,
type ReferenceHttpRequest,
type ReferenceOperationId,
REFERENCE_HTTP_OPERATIONS,
} from "./reference-http-gateway.ts";
export type InstalledContractOperationExecutor = Readonly<{
execute(
operationId: string,
input: unknown,
context: Readonly<{
routeId: string;
signal?: AbortSignal;
intent?: MutationIntent;
}>,
): Promise<HttpExecutionOutcome<unknown, unknown>>;
}>;
export type InstalledContractOperationExecutor =
InstalledHttpOperationExecutor;
/**
* The installed feature consumes the composed external-contract operation
* registry through one descriptor-driven executor. Legacy ApiOperation/schema
* registries are intentionally absent from this production composition seam.
* Feature-owned composition seam.
*
* The feature receives only the HTTP capability it declares in `needs`.
* HTTP lifecycle/error normalization stays in the reusable capability binding.
*/
export function createReferenceFeatureInstalledInput(context: Readonly<{
contractOperations: InstalledContractOperationExecutor;
http: InstalledHttpOperationExecutor;
}>) {
const rawHttp: RawReferenceHttpExecutor = Object.freeze({
async execute(request) {
const operationId = request.operationId;
const input = inputFor(request);
const signal = "signal" in request ? request.signal : undefined;
const intent = "intent" in request ? request.intent : undefined;
const outcome = await context.contractOperations.execute(
operationId,
input,
{
// §7.4. The gateway owns the low-cardinality route identity; losing
// it here is what made every V3 diagnostic unattributable.
routeId: request.routeId,
...(signal === undefined ? {} : { signal }),
...(intent === undefined ? {} : { intent }),
},
);
return projectExecutionOutcome(operationId, outcome);
},
});
const http = createFeatureHttpBinding(
context.http,
REFERENCE_HTTP_OPERATIONS,
);
return Object.freeze({
featureId: REFERENCE_FEATURE_ID,
input: createReferenceFeatureInput(createReferenceHttpGateway(rawHttp)),
input: createReferenceFeatureInput(createReferenceHttpGateway(http)),
});
}
function inputFor(
request: ReferenceHttpRequest<ReferenceOperationId>,
): unknown {
switch (request.operationId) {
case "LIST_REFERENCE_RESOURCES":
return request.searchParams;
case "CREATE_REFERENCE_RESOURCE":
return request.body;
case "GET_REFERENCE_RESOURCE":
return request.pathParams;
}
}
function projectExecutionOutcome(
operationId: ReferenceOperationId,
outcome: HttpExecutionOutcome<unknown, unknown>,
): Result<unknown, ApiFailure> {
switch (outcome.kind) {
case "SUCCESS": {
const mapped = mapReferenceOperation(operationId, outcome.value);
return mapped.ok
? Object.freeze({ ok: true as const, value: mapped.value })
: failure(
"MAPPING_CONTRACT_VIOLATION",
operationId,
mapped.code,
{ effect: outcome.effect },
);
}
case "PROBLEM":
return failure(
kindForStatus(outcome.metadata.status),
operationId,
"CONTRACT_PROBLEM",
{ httpStatus: outcome.metadata.status, effect: outcome.effect },
);
case "UNAUTHENTICATED":
return failure("AUTH_REQUIRED", operationId, "UNAUTHENTICATED", {
effect: outcome.effect,
});
case "FORBIDDEN":
return failure("FORBIDDEN", operationId, "FORBIDDEN", {
effect: outcome.effect,
});
case "RATE_LIMITED":
return failure("RATE_LIMITED", operationId, "RATE_LIMITED", {
...(outcome.retryAfterMs === undefined
? {}
: { retryAfterMs: outcome.retryAfterMs }),
effect: outcome.effect,
});
case "CANCELLED":
return failure("REQUEST_ABORTED", operationId, "REQUEST_ABORTED", {
effect: outcome.effect,
});
case "AUTH_INTEGRATION_FAILURE":
// §7.7. A configuration or collaborator breach, not a session state, so
// it must not drive the re-authentication surface.
return failure(
"AUTH_INTEGRATION_FAILURE",
operationId,
outcome.reason,
{ effect: outcome.effect },
);
case "TRANSPORT_FAILURE":
return failure(
outcome.failure.kind === "TIMEOUT"
? "REQUEST_TIMEOUT"
: outcome.failure.kind === "ABORTED_BY_SCOPE"
? "SCOPE_GENERATION_CHANGED"
: "NETWORK_UNREACHABLE",
operationId,
outcome.failure.kind,
{ effect: outcome.effect },
);
case "CONTRACT_VIOLATION":
return failure(
failureKindForViolation(outcome.violation.kind),
operationId,
outcome.violation.kind,
{ effect: outcome.effect },
);
}
}
function failureKindForViolation(
violation: Extract<
HttpExecutionOutcome<unknown, unknown>,
{ kind: "CONTRACT_VIOLATION" }
>["violation"]["kind"],
): FailureKind {
switch (violation) {
case "CONTENT_TYPE_MISMATCH":
return "CONTENT_TYPE_MISMATCH";
case "RESPONSE_TOO_LARGE":
return "RESPONSE_BODY_LIMIT";
case "UTF8_INVALID":
case "JSON_INVALID":
return "MALFORMED_JSON";
case "MAPPING_CONTRACT_VIOLATION":
return "MAPPING_CONTRACT_VIOLATION";
case "SCOPE_FENCED":
return "SCOPE_GENERATION_CHANGED";
case "SUCCESS_SCHEMA_INVALID":
case "PROBLEM_SCHEMA_INVALID":
case "VALIDATOR_RUNTIME_FAILURE":
return "SCHEMA_MISMATCH";
default:
return "ENVELOPE_MISMATCH";
}
}
function failure(
kind: FailureKind,
operationId: string,
code: string,
details: Readonly<{
httpStatus?: number;
retryAfterMs?: number;
effect?: FailureEffectCertainty;
}> = {},
): Result<never, ApiFailure> {
return Object.freeze({
ok: false as const,
error: createFailure(kind, operationId, 0, { code, ...details }),
export const REFERENCE_FEATURE_ADAPTER_CONTRIBUTION =
defineFeatureAdapterContribution({
featureId: REFERENCE_FEATURE_ID,
needs: ["http"] as const,
createInput: createReferenceFeatureInstalledInput,
});
}
@@ -1,160 +1,82 @@
import type { Result } from "../../../application/result.ts";
import {
createFailure,
type ApiFailure,
} from "../../../contracts/errors.ts";
defineFeatureHttpOperationForRoutes,
type FeatureHttpBinding,
} from "../../../adapters/http/index.ts";
import {
CREATE_REFERENCE_RESOURCE_CONTRACT,
GET_REFERENCE_RESOURCE_CONTRACT,
LIST_REFERENCE_RESOURCES_CONTRACT,
} from "../contracts/reference-feature-contract-contribution.ts";
import {
REFERENCE_FEATURE_CONTRACT,
} from "../contracts/reference-feature-contract.ts";
import {
mapReferenceResourceListPayload,
mapReferenceResourcePayload,
} from "../contracts/reference-mapper.ts";
import type {
ReferenceCreateCommand,
ReferenceGateway,
ReferenceListFilters,
} from "../application/reference-feature-api.ts";
import type { ReferenceResource } from "../domain/reference-resource.ts";
import type { MutationIntent } from "../../../contracts/mutation-intent.ts";
type ReferenceOperationMap = Readonly<{
LIST_REFERENCE_RESOURCES: Readonly<{
request: Readonly<{
operationId: "LIST_REFERENCE_RESOURCES";
routeId: "REFERENCE_RESOURCE_LIST";
searchParams: ReferenceListFilters;
signal?: AbortSignal;
}>;
value: readonly ReferenceResource[];
}>;
CREATE_REFERENCE_RESOURCE: Readonly<{
request: Readonly<{
operationId: "CREATE_REFERENCE_RESOURCE";
routeId: "REFERENCE_RESOURCE_LIST";
body: ReferenceCreateCommand;
signal?: AbortSignal;
intent?: MutationIntent;
}>;
value: ReferenceResource;
}>;
GET_REFERENCE_RESOURCE: Readonly<{
request: Readonly<{
operationId: "GET_REFERENCE_RESOURCE";
routeId: "REFERENCE_RESOURCE_DETAIL";
pathParams: Readonly<{ resourceId: string }>;
signal?: AbortSignal;
}>;
value: ReferenceResource;
}>;
}>;
export type ReferenceFeatureRouteId =
keyof typeof REFERENCE_FEATURE_CONTRACT.routes;
export type ReferenceOperationId = keyof ReferenceOperationMap;
const defineReferenceHttpOperation =
defineFeatureHttpOperationForRoutes<ReferenceFeatureRouteId>();
export type ReferenceHttpRequest<
OperationId extends ReferenceOperationId,
> = ReferenceOperationMap[OperationId]["request"];
export const REFERENCE_HTTP_OPERATIONS = Object.freeze({
LIST_REFERENCE_RESOURCES: defineReferenceHttpOperation({
contract: LIST_REFERENCE_RESOURCES_CONTRACT,
routeId: "REFERENCE_RESOURCE_LIST",
mapSuccess: mapReferenceResourceListPayload,
}),
CREATE_REFERENCE_RESOURCE: defineReferenceHttpOperation({
contract: CREATE_REFERENCE_RESOURCE_CONTRACT,
routeId: "REFERENCE_RESOURCE_LIST",
mapSuccess: mapReferenceResourcePayload,
mapProblem(problem, metadata) {
if (metadata.status === 409) {
return Object.freeze({
kind: "CONFLICT" as const,
code: problem.code ?? "REFERENCE_RESOURCE_CONFLICT",
});
}
if (metadata.status === 422) {
return Object.freeze({
kind: "VALIDATION_REJECTED" as const,
code: problem.code ?? "REFERENCE_RESOURCE_REJECTED",
});
}
return undefined;
},
}),
GET_REFERENCE_RESOURCE: defineReferenceHttpOperation({
contract: GET_REFERENCE_RESOURCE_CONTRACT,
routeId: "REFERENCE_RESOURCE_DETAIL",
mapSuccess: mapReferenceResourcePayload,
}),
} as const);
export type ReferenceHttpResult<
OperationId extends ReferenceOperationId,
> = Result<ReferenceOperationMap[OperationId]["value"], ApiFailure>;
export type RawReferenceHttpExecutor = Readonly<{
execute(
request: ReferenceHttpRequest<ReferenceOperationId>,
): Promise<Result<unknown, ApiFailure>>;
}>;
export type ReferenceHttpBinding = FeatureHttpBinding<
typeof REFERENCE_HTTP_OPERATIONS
>;
export function createReferenceHttpGateway(
http: RawReferenceHttpExecutor,
http: ReferenceHttpBinding,
): ReferenceGateway {
return Object.freeze({
async list(
filters: ReferenceListFilters,
context?: Readonly<{ signal?: AbortSignal }>,
) {
const result = await http.execute({
operationId: "LIST_REFERENCE_RESOURCES",
routeId: "REFERENCE_RESOURCE_LIST",
searchParams: filters,
signal: context?.signal,
});
return projectListResult(result);
list(filters, context) {
return http.execute("LIST_REFERENCE_RESOURCES", filters, context);
},
async create(
command: ReferenceCreateCommand,
context?: Readonly<{
signal?: AbortSignal;
intent?: MutationIntent;
}>,
) {
const result = await http.execute({
operationId: "CREATE_REFERENCE_RESOURCE",
routeId: "REFERENCE_RESOURCE_LIST",
body: command,
signal: context?.signal,
intent: context?.intent,
});
return projectResourceResult("CREATE_REFERENCE_RESOURCE", result);
create(command, context) {
return http.execute("CREATE_REFERENCE_RESOURCE", command, context);
},
async get(
resourceId: string,
context?: Readonly<{ signal?: AbortSignal }>,
) {
const result = await http.execute({
operationId: "GET_REFERENCE_RESOURCE",
routeId: "REFERENCE_RESOURCE_DETAIL",
pathParams: { resourceId },
signal: context?.signal,
});
return projectResourceResult("GET_REFERENCE_RESOURCE", result);
get(resourceId, context) {
return http.execute(
"GET_REFERENCE_RESOURCE",
Object.freeze({ resourceId }),
context,
);
},
});
}
function projectListResult(
result: Result<unknown, ApiFailure>,
): ReferenceHttpResult<"LIST_REFERENCE_RESOURCES"> {
if (!result.ok) return result;
if (isReferenceResourceList(result.value)) {
return { ok: true, value: result.value };
}
return typedResultFailure("LIST_REFERENCE_RESOURCES");
}
function projectResourceResult(
operationId:
| "CREATE_REFERENCE_RESOURCE"
| "GET_REFERENCE_RESOURCE",
result: Result<unknown, ApiFailure>,
): Result<ReferenceResource, ApiFailure> {
if (!result.ok) return result;
if (isReferenceResource(result.value)) {
return { ok: true, value: result.value };
}
return typedResultFailure(operationId);
}
function typedResultFailure(operationId: ReferenceOperationId) {
return {
ok: false as const,
error: createFailure(
"MAPPING_CONTRACT_VIOLATION",
operationId,
0,
{ code: "BOUND_RESULT_TYPE_MISMATCH" },
),
};
}
function isReferenceResourceList(
value: unknown,
): value is readonly ReferenceResource[] {
return Array.isArray(value) && value.every(isReferenceResource);
}
function isReferenceResource(value: unknown): value is ReferenceResource {
if (!value || typeof value !== "object") return false;
const candidate = value as Readonly<Record<string, unknown>>;
return (
typeof candidate.id === "string" &&
candidate.id.length > 0 &&
typeof candidate.displayName === "string" &&
candidate.displayName.length > 0 &&
(candidate.createdAt === null ||
typeof candidate.createdAt === "string")
);
}
@@ -1,4 +1,4 @@
import type { Result } from "../../../application/result.ts";
import type { Result } from "../../../contracts/result.ts";
import type {} from "../../../application/ports/in/application-api.ts";
import {
toReferenceView,
@@ -2,17 +2,22 @@ import { z } from "zod";
import type {
CommandEffectDescriptor,
HttpRequestProjection,
InstalledContractContribution,
InstalledHttpContract,
RuntimeValidator,
} from "../../../contracts/external-contract-runtime.ts";
import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts";
import {
createReferenceResourceCommandSchema,
referenceProblemSchema,
referenceResourceDtoSchema,
referenceResourceListQuerySchema,
referenceResourceParamsSchema,
type ReferenceProblem,
} from "./reference-schemas.ts";
export type { ReferenceProblem } from "./reference-schemas.ts";
/**
* §4.8. The single `TEMPLATE_FIXTURE` contribution. It keeps the reference
* HTTP vertical executable as deterministic template data and is excluded from
@@ -53,33 +58,10 @@ function zodValidator<T>(
});
}
const referenceResourceDto = z
.object({
id: z.string().min(1).max(120),
name: z.string().min(1).max(240),
createdAt: z.string().min(1).optional(),
})
.strip();
const problemSchema = z
.object({
type: z.string().min(1).max(512),
title: z.string().min(1).max(240),
status: z.int().min(100).max(599),
code: z.string().min(1).max(120).optional(),
})
.strip();
export type ReferenceProblem = z.output<typeof problemSchema>;
const PROBLEM_VALIDATOR = zodValidator("ReferenceProblem", problemSchema);
const createCommandSchema = z
.object({
name: z.string().trim().min(1).max(120),
note: z.string().trim().max(500).optional(),
})
.strict();
const PROBLEM_VALIDATOR = zodValidator(
"ReferenceProblem",
referenceProblemSchema,
);
/**
* Fixture-side classifier standing in for the package-provided pure bounded
@@ -87,17 +69,17 @@ const createCommandSchema = z
*/
const CREATE_EFFECT: CommandEffectDescriptor<ReferenceProblem> = Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem({ status }: Readonly<{ status: number; problem: ReferenceProblem }>) {
if (status === 400 || status === 409 || status === 422) return "NOT_APPLIED";
classifyProblem({
status,
}: Readonly<{ status: number; problem: ReferenceProblem }>) {
if (status === 400 || status === 409 || status === 422) {
return "NOT_APPLIED";
}
return "MAYBE_APPLIED";
},
});
const LIST_REFERENCE_RESOURCES: InstalledHttpContract<
z.output<typeof referenceResourceListQuerySchema>,
readonly z.output<typeof referenceResourceDto>[],
ReferenceProblem
> = Object.freeze({
export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "LIST_REFERENCE_RESOURCES",
method: "GET" as const,
@@ -108,7 +90,7 @@ const LIST_REFERENCE_RESOURCES: InstalledHttpContract<
),
outputValidator: zodValidator(
"ReferenceResourceListPayload",
z.array(referenceResourceDto).max(100),
z.array(referenceResourceDtoSchema).max(100),
),
problemValidator: PROBLEM_VALIDATOR,
acceptedStatuses: Object.freeze([200]),
@@ -139,13 +121,13 @@ const LIST_REFERENCE_RESOURCES: InstalledHttpContract<
authProfileId: "REFERENCE_EXTERNAL_BEARER",
diagnosticsOperation: "reference.list",
}),
});
const GET_REFERENCE_RESOURCE: InstalledHttpContract<
z.output<typeof referenceResourceParamsSchema>,
z.output<typeof referenceResourceDto>,
}) satisfies InstalledHttpContract<
z.output<typeof referenceResourceListQuerySchema>,
readonly z.output<typeof referenceResourceDtoSchema>[],
ReferenceProblem
> = Object.freeze({
>;
export const GET_REFERENCE_RESOURCE_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "GET_REFERENCE_RESOURCE",
method: "GET" as const,
@@ -156,7 +138,7 @@ const GET_REFERENCE_RESOURCE: InstalledHttpContract<
),
outputValidator: zodValidator(
"ReferenceResourcePayload",
referenceResourceDto,
referenceResourceDtoSchema,
),
problemValidator: PROBLEM_VALIDATOR,
acceptedStatuses: Object.freeze([200]),
@@ -183,24 +165,24 @@ const GET_REFERENCE_RESOURCE: InstalledHttpContract<
authProfileId: "REFERENCE_EXTERNAL_BEARER",
diagnosticsOperation: "reference.detail",
}),
});
const CREATE_REFERENCE_RESOURCE: InstalledHttpContract<
z.output<typeof createCommandSchema>,
z.output<typeof referenceResourceDto>,
}) satisfies InstalledHttpContract<
z.output<typeof referenceResourceParamsSchema>,
z.output<typeof referenceResourceDtoSchema>,
ReferenceProblem
> = Object.freeze({
>;
export const CREATE_REFERENCE_RESOURCE_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "CREATE_REFERENCE_RESOURCE",
method: "POST" as const,
pathTemplate: "/api/reference-resources",
inputValidator: zodValidator(
"CreateReferenceResourceCommand",
createCommandSchema,
createReferenceResourceCommandSchema,
),
outputValidator: zodValidator(
"ReferenceResourcePayload",
referenceResourceDto,
referenceResourceDtoSchema,
),
problemValidator: PROBLEM_VALIDATOR,
acceptedStatuses: Object.freeze([200, 201]),
@@ -213,7 +195,7 @@ const CREATE_REFERENCE_RESOURCE: InstalledHttpContract<
operationIdentityField: "idempotencyKey",
}),
commandEffect: CREATE_EFFECT,
projectRequest(input: z.output<typeof createCommandSchema>) {
projectRequest(input: z.output<typeof createReferenceResourceCommandSchema>) {
return Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
@@ -235,7 +217,11 @@ const CREATE_REFERENCE_RESOURCE: InstalledHttpContract<
authProfileId: "REFERENCE_EXTERNAL_BEARER",
diagnosticsOperation: "reference.create",
}),
});
}) satisfies InstalledHttpContract<
z.output<typeof createReferenceResourceCommandSchema>,
z.output<typeof referenceResourceDtoSchema>,
ReferenceProblem
>;
export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribution =
Object.freeze({
@@ -247,9 +233,9 @@ export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribut
revision: 1 as const,
}),
http: Object.freeze([
LIST_REFERENCE_RESOURCES,
GET_REFERENCE_RESOURCE,
CREATE_REFERENCE_RESOURCE,
LIST_REFERENCE_RESOURCES_CONTRACT,
GET_REFERENCE_RESOURCE_CONTRACT,
CREATE_REFERENCE_RESOURCE_CONTRACT,
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
events: Object.freeze([]),
});
@@ -5,9 +5,10 @@ import {
import {
mappingFailure,
mappingSuccess,
type MappingResult,
type InstalledBoundaryMapper,
type MappingResult,
} from "../../../contracts/boundary-mapper.ts";
import type { ReferenceResourceDto } from "./reference-schemas.ts";
export type ReferenceResourceView = Readonly<{
resourceId: string;
@@ -16,20 +17,19 @@ export type ReferenceResourceView = Readonly<{
optimistic?: boolean;
}>;
function mapReferenceDto(value: unknown): MappingResult<ReferenceResource> {
if (!value || typeof value !== "object") {
return mappingFailure("MAPPING_INVARIANT_REJECTED");
}
const dto = value as Record<string, unknown>;
if (typeof dto.id !== "string" || typeof dto.name !== "string") {
return mappingFailure("MAPPING_INVARIANT_REJECTED");
}
/**
* Operation-specific mapper. The HTTP contract has already validated the wire
* shape, so this mapper owns only wire -> domain construction.
*/
export function mapReferenceResourcePayload(
dto: ReferenceResourceDto,
): MappingResult<ReferenceResource> {
try {
return mappingSuccess(
createReferenceResource({
id: dto.id,
displayName: dto.name,
createdAt: typeof dto.createdAt === "string" ? dto.createdAt : null,
createdAt: dto.createdAt ?? null,
}),
);
} catch {
@@ -37,28 +37,70 @@ function mapReferenceDto(value: unknown): MappingResult<ReferenceResource> {
}
}
export function mapReferenceResourceListPayload(
payload: readonly ReferenceResourceDto[],
): MappingResult<readonly ReferenceResource[]> {
const output: ReferenceResource[] = [];
for (const item of payload) {
const mapped = mapReferenceResourcePayload(item);
if (!mapped.ok) return mapped;
output.push(mapped.value);
}
return mappingSuccess(Object.freeze(output));
}
function isReferenceResourceDto(value: unknown): value is ReferenceResourceDto {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const dto = value as Record<string, unknown>;
return (
typeof dto.id === "string" &&
typeof dto.name === "string" &&
(dto.createdAt === undefined || typeof dto.createdAt === "string")
);
}
function mapUnknownReferenceResourcePayload(
value: unknown,
): MappingResult<ReferenceResource> {
return isReferenceResourceDto(value)
? mapReferenceResourcePayload(value)
: mappingFailure("MAPPING_INVARIANT_REJECTED");
}
function mapUnknownReferenceResourceListPayload(
value: unknown,
): MappingResult<readonly ReferenceResource[]> {
if (
!Array.isArray(value) ||
value.length > 100 ||
!value.every(isReferenceResourceDto)
) {
return mappingFailure(
Array.isArray(value) && value.length > 100
? "OUTPUT_LIMIT_EXCEEDED"
: "MAPPING_INVARIANT_REJECTED",
);
}
return mapReferenceResourceListPayload(value);
}
/**
* Registry-facing compatibility projection. The registry is intentionally
* untyped, so its adapter performs the defensive shape check. Feature HTTP
* bindings use the typed operation-specific mappers above.
*/
export function mapReferenceOperation(
operationId: string,
payload: unknown,
): MappingResult<ReferenceResource | readonly ReferenceResource[]> {
if (operationId === "LIST_REFERENCE_RESOURCES") {
if (!Array.isArray(payload)) {
return mappingFailure("MAPPING_INVARIANT_REJECTED");
}
if (payload.length > 100) return mappingFailure("OUTPUT_LIMIT_EXCEEDED");
const output: ReferenceResource[] = [];
for (const item of payload) {
const mapped = mapReferenceDto(item);
if (!mapped.ok) return mapped;
output.push(mapped.value);
}
return mappingSuccess(Object.freeze(output));
return mapUnknownReferenceResourceListPayload(payload);
}
if (
operationId === "CREATE_REFERENCE_RESOURCE" ||
operationId === "GET_REFERENCE_RESOURCE"
) {
return mapReferenceDto(payload);
return mapUnknownReferenceResourcePayload(payload);
}
return mappingFailure("MAPPING_INVARIANT_REJECTED");
}
@@ -71,8 +113,7 @@ export const REFERENCE_BOUNDARY_MAPPERS = Object.freeze({
outputContractId: "ReferenceResourceList",
owner: "feature-frontend-reference-feature-vertical-slice",
maxOutputItems: 100,
map: (input: unknown) =>
mapReferenceOperation("LIST_REFERENCE_RESOURCES", input),
map: mapUnknownReferenceResourceListPayload,
}),
ReferenceResourceMapper: Object.freeze({
mapperId: "ReferenceResourceMapper",
@@ -81,8 +122,7 @@ export const REFERENCE_BOUNDARY_MAPPERS = Object.freeze({
outputContractId: "ReferenceResource",
owner: "feature-frontend-reference-feature-vertical-slice",
maxOutputItems: 1,
map: (input: unknown) =>
mapReferenceOperation("GET_REFERENCE_RESOURCE", input),
map: mapUnknownReferenceResourcePayload,
}),
} satisfies Readonly<Record<string, InstalledBoundaryMapper>>);
@@ -13,7 +13,7 @@ export const referenceResourceListQuerySchema = z
: Array.isArray(value)
? value
: [value],
z.array(z.string().trim().min(1)),
z.array(z.string().trim().min(1)).readonly(),
)
.optional(),
})
@@ -25,7 +25,7 @@ export const referenceResourceParamsSchema = z
})
.strict();
const referenceResourceDtoSchema = z
export const referenceResourceDtoSchema = z
.object({
id: z.string().min(1).max(120),
name: z.string().min(1).max(240),
@@ -33,6 +33,28 @@ const referenceResourceDtoSchema = z
})
.strip();
export type ReferenceResourceDto = z.output<
typeof referenceResourceDtoSchema
>;
export const referenceProblemSchema = z
.object({
type: z.string().min(1).max(512),
title: z.string().min(1).max(240),
status: z.int().min(100).max(599),
code: z.string().min(1).max(120).optional(),
})
.strip();
export type ReferenceProblem = z.output<typeof referenceProblemSchema>;
export const createReferenceResourceCommandSchema = z
.object({
name: z.string().trim().min(1).max(120),
note: z.string().trim().max(500).optional(),
})
.strict();
const payloadSchemas = {
ReferenceResourceListPayload: z.array(referenceResourceDtoSchema).max(100),
ReferenceResourcePayload: referenceResourceDtoSchema,
@@ -42,12 +64,7 @@ const requestSchemas = {
ReferenceResourceParams: referenceResourceParamsSchema,
ReferenceResourceListQuery: referenceResourceListQuerySchema,
NoRequest: z.object({}).strict(),
CreateReferenceResourceCommand: z
.object({
name: z.string().trim().min(1).max(120),
note: z.string().trim().max(500).optional(),
})
.strict(),
CreateReferenceResourceCommand: createReferenceResourceCommandSchema,
} satisfies Record<string, z.ZodType>;
function project(result: z.ZodSafeParseResult<unknown>) {
@@ -4,7 +4,7 @@ import {
MUTATION_INTENT_BOUNDS,
type MutationIntent,
} from "../../../../contracts/mutation-intent.ts";
import type { HttpExecutionOutcome } from "../../../../adapters/http/http-execution-v3.ts";
import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts";
import { stableStringify } from "../stable-stringify.ts";
import type {
IdempotentOptions,
@@ -1,4 +1,4 @@
import type { HttpExecutionOutcome } from "../../../../adapters/http/http-execution-v3.ts";
import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts";
import { StudioGatewayError } from "../../application/ports/studio-gateway-error.ts";
import type { ProblemDetails } from "../../contracts/studio/contract.ts";
@@ -1,4 +1,4 @@
import type { CredentialPatchOutcome } from "../../../../adapters/http/http-contract-bridge.ts";
import type { CredentialPatchOutcome } from "../../../../adapters/http/index.ts";
import {
CREDENTIAL_HEADER_NAMES,
type CredentialHeaderName,
@@ -91,7 +91,7 @@ function isTechLogStudioAuthProfileId(value: string): value is TechLogStudioAuth
* the caller's responsibility, not this function's.
*
* Final fix wave, item 8. `contractOperations.execute` is one executor shared
* by every installed feature, so it was calling this for reference-feature
* by every installed feature, so it was calling this for other features'
* operations too: an unrelated 403 discarded a perfectly good Studio token
* and forced an avoidable `getStudioSession` round trip — or, when the
* session endpoint is itself unhealthy, turned someone else's authorization
@@ -17,7 +17,7 @@ import {
deriveAsyncState,
type AsyncState,
} from "../../../application/view-models/async-state.ts";
import type { Result } from "../../../application/result.ts";
import type { Result } from "../../../contracts/result.ts";
import {
createFailure,
normalizeUnknownFailure,
+1 -1
View File
@@ -1,4 +1,4 @@
import type { Result } from "../../application/result.ts";
import type { Result } from "../../contracts/result.ts";
import type { AppFailure } from "../../contracts/errors.ts";
import {
formatMessage,
+2 -2
View File
@@ -20,7 +20,7 @@ import {
useLocale,
type MessageKey,
} from "../i18n/index.ts";
import { useApplication } from "../providers/application-provider.tsx";
import { useApplicationRuntime } from "../providers/application-provider.tsx";
import { useSession } from "../providers/session-provider.tsx";
import { useTheme } from "../providers/theme-provider.tsx";
@@ -168,7 +168,7 @@ export function AppShell() {
function PrimaryNavigation({ id }: Readonly<{ id: string }>) {
const { resolve, message } = useLocale();
const { runtime } = useApplication();
const runtime = useApplicationRuntime();
const { pathname } = useLocation();
// §3.5. A feature the runtime document disabled does not advertise itself.
// The router refuses its routes too, so this is presentation, not the switch.
@@ -4,7 +4,11 @@ import {
useContext,
} from "react";
import type { ApplicationApi } from "../../application/create-application.ts";
import type {
ApplicationApi,
ApplicationFeatureId,
ApplicationFeatureInputs,
} from "../../application/ports/in/application-api.ts";
const ApplicationContext = createContext<ApplicationApi | null>(null);
@@ -22,10 +26,47 @@ export function ApplicationProvider({
);
}
export function useApplication(): ApplicationApi {
function useApplicationContext(): ApplicationApi {
const application = useContext(ApplicationContext);
if (!application) {
throw new Error("ApplicationProvider is required");
}
return application;
}
export function useApplicationSession(): ApplicationApi["session"] {
return useApplicationContext().session;
}
export function useApplicationPreferences(): ApplicationApi["preferences"] {
return useApplicationContext().preferences;
}
export function useApplicationDiagnostics(): ApplicationApi["diagnostics"] {
return useApplicationContext().diagnostics;
}
export function useApplicationRuntime(): ApplicationApi["runtime"] {
return useApplicationContext().runtime;
}
export function useApplicationRecovery(): ApplicationApi["recovery"] {
return useApplicationContext().recovery;
}
export function useApplicationFeature<
FeatureId extends ApplicationFeatureId,
>(featureId: FeatureId): ApplicationFeatureInputs[FeatureId] {
return useApplicationContext().features.get(featureId);
}
/**
* Compatibility escape hatch for composition-oriented presentation code.
* New consumers should use the narrow hooks above so dependencies remain
* explicit instead of growing a root-object service locator.
*
* @deprecated Prefer a capability-specific hook.
*/
export function useApplication(): ApplicationApi {
return useApplicationContext();
}
@@ -10,7 +10,7 @@ import type {
ApplicationApi,
SessionState,
} from "../../application/ports/in/application-api.ts";
import { useApplication } from "./application-provider.tsx";
import { useApplicationSession } from "./application-provider.tsx";
export type SessionContextValue = Readonly<{
sessionState: SessionState;
@@ -24,7 +24,7 @@ const SessionContext = createContext<SessionContextValue | null>(null);
export function SessionProvider({
children,
}: Readonly<{ children: ReactNode }>) {
const { session } = useApplication();
const session = useApplicationSession();
const sessionState = useSyncExternalStore(
session.subscribe,
session.getSnapshot,
@@ -13,7 +13,7 @@ import {
normalizeColorSchemePreference,
resolveColorScheme,
} from "../../application/policies/color-scheme.ts";
import { useApplication } from "./application-provider.tsx";
import { useApplicationPreferences } from "./application-provider.tsx";
export type ThemeContextValue = Readonly<{
preference: ColorSchemePreference;
@@ -33,7 +33,7 @@ function systemPrefersDark(): boolean {
export function ThemeProvider({
children,
}: Readonly<{ children: ReactNode }>) {
const { preferences } = useApplication();
const preferences = useApplicationPreferences();
const [preference, updatePreference] = useState<ColorSchemePreference>(
preferences.getColorScheme,
);
+9 -3
View File
@@ -33,7 +33,11 @@ import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.tsx
import { Button, PageHeader } from "../design-system/index.ts";
import { LocaleProvider, useLocale } from "../i18n/index.ts";
import { TECH_LOG_ROUTE_LAYOUTS } from "../../features/tech-log/presentation/tech-log-route-runtime.tsx";
import { useApplication } from "../providers/application-provider.tsx";
import {
useApplicationDiagnostics,
useApplicationRecovery,
useApplicationRuntime,
} from "../providers/application-provider.tsx";
import { SessionProvider, useSession } from "../providers/session-provider.tsx";
import { ThemeProvider } from "../providers/theme-provider.tsx";
import {
@@ -136,7 +140,7 @@ function RouteLifecycle({
}) {
const location = useLocation();
const { message, resolve } = useLocale();
const { diagnostics } = useApplication();
const diagnostics = useApplicationDiagnostics();
useEffect(() => {
document.title = message("route.documentTitle", {
title: resolve(`route.${definition.routeId}.title`),
@@ -305,7 +309,9 @@ function RegisteredRoute<RouteIdValue extends string>({
const params = useParams();
const [search] = useSearchParams();
const location = useLocation();
const { diagnostics, runtime: platformRuntime, recovery } = useApplication();
const diagnostics = useApplicationDiagnostics();
const platformRuntime = useApplicationRuntime();
const recovery = useApplicationRecovery();
// §3.5 (template merge). A feature the runtime document disabled is out of
// service, not merely hidden: withdrawing it from navigation alone would
// leave a typed deep link that still mounts it. The template looked the