@ancientpantheon/khronoton-core 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Public entry for `@ancientpantheon/khronoton-core/handlers` — the
3
+ * framework-agnostic route surface over the `/server` store + executor. A
4
+ * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
+ * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
+ * resolver + an {@link AuthSeam}), and calls the sixteen handlers below.
7
+ *
8
+ * The read handlers keep their contract names here (aliasing their module's
9
+ * `*Handler` implementations), so the barrel exposes the exact route contract
10
+ * from [PARITY §4]. This entry is React-free and built by `tsc` (not tsup) so it
11
+ * stays importable in any server runtime; it imports no `@stoachain/*` (REQ-P01).
12
+ *
13
+ * Every re-export is `export type` where the symbol is a type, so the emitted
14
+ * `.d.ts` stays fully erasable. Explicit `.js` extensions throughout.
15
+ */
16
+ export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, } from "./read.js";
17
+ export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
18
+ export type { CommitBody, CommitEnvelope, CommitSchedule } from "./cronoton.js";
19
+ export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
20
+ export { startExecuteBatch, getExecuteBatch, cancelExecuteBatch } from "./batch.js";
21
+ export { json, err, errorBody, mapStoreError } from "./http.js";
22
+ export type { HandlerRequest, HandlerResponse } from "./http.js";
23
+ export { defaultSignerSource, descriptorSourceToDisplay } from "./http.js";
24
+ export type { SignerSource, CodexSignerDescriptor } from "./http.js";
25
+ export { defaultOpenAuth, NeedsConfirmError } from "./context.js";
26
+ export type { Handler, HandlerContext, AuthSeam, AuthIdentity, AuthResult, } from "./context.js";
27
+ export type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode, } from "./context.js";
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Public entry for `@ancientpantheon/khronoton-core/handlers` — the
3
+ * framework-agnostic route surface over the `/server` store + executor. A
4
+ * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
+ * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
+ * resolver + an {@link AuthSeam}), and calls the sixteen handlers below.
7
+ *
8
+ * The read handlers keep their contract names here (aliasing their module's
9
+ * `*Handler` implementations), so the barrel exposes the exact route contract
10
+ * from [PARITY §4]. This entry is React-free and built by `tsc` (not tsup) so it
11
+ * stays importable in any server runtime; it imports no `@stoachain/*` (REQ-P01).
12
+ *
13
+ * Every re-export is `export type` where the symbol is a type, so the emitted
14
+ * `.d.ts` stays fully erasable. Explicit `.js` extensions throughout.
15
+ */
16
+ // ── Read handlers (TC.2) — aliased to their contract names ────────────────────
17
+ export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, } from "./read.js";
18
+ // ── Cronoton-lifecycle handlers (TC.3) ────────────────────────────────────────
19
+ export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
20
+ // ── Execution handlers (TC.4) ─────────────────────────────────────────────────
21
+ export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
22
+ // ── Manual-batch handlers (TC.5) ──────────────────────────────────────────────
23
+ export { startExecuteBatch, getExecuteBatch, cancelExecuteBatch } from "./batch.js";
24
+ // ── Kernel contract (TC.1): normalized request/response + helpers ─────────────
25
+ // The request/response shapes plus the response helpers a consumer needs to
26
+ // build its own auth seam, signer source, or error mapping.
27
+ export { json, err, errorBody, mapStoreError } from "./http.js";
28
+ // ── Kernel contract (TC.1): signer descriptor seam (secret-free) ──────────────
29
+ export { defaultSignerSource, descriptorSourceToDisplay } from "./http.js";
30
+ // ── Kernel contract (TC.1): handler context + auth/confirm seam ───────────────
31
+ // The gate wrappers stay module-internal to the handlers; a consumer WIRES the
32
+ // surface with the context type, the injectable auth seam, and the default open
33
+ // (trusted single-tenant) impl.
34
+ export { defaultOpenAuth, NeedsConfirmError } from "./context.js";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The read-tier route surface: `list`, `get`, `signers`, `fires`. Every one runs
3
+ * behind the READ gate ({@link withRead}) — no fresh-confirm is demanded, so a
4
+ * plain viewer can observe the codex-cronoton state (matching the Hub's
5
+ * SSR-public list/detail). These handlers ORCHESTRATE the `/server` store; they
6
+ * do not reimplement any query.
7
+ *
8
+ * The two pieces of branching that live in THIS layer (not the store) are the
9
+ * defensive query parsing — NaN/garbage falls back to a default, and every value
10
+ * is clamped to the store's own bounds so the echoed page window matches what was
11
+ * used — and the fire page-size default of 50 (REQ-G08/REQ-H07), which overrides
12
+ * the store's own default of 20. The signer projection stays SECRET-FREE
13
+ * (REQ-H10): only `publicKey` + a coarse `display`, never key material.
14
+ */
15
+ import { type HandlerResponse } from "./http.js";
16
+ import { type HandlerContext } from "./context.js";
17
+ import type { HandlerRequest } from "./http.js";
18
+ /** `GET /` — the newest-first cronoton list (store clamps limit 1..200). */
19
+ export declare function listHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
20
+ /** `GET /[id]` — the single cronoton row, or 404 when absent. */
21
+ export declare function getHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
22
+ /** `GET /signers` — the SECRET-FREE signer descriptors (never key material). */
23
+ export declare function signersHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
24
+ /**
25
+ * `GET /[id]/fires?limit&offset` — paginated fire history. The page size defaults
26
+ * to 50 (REQ-G08) — overriding the store's own default of 20 — and both echoed
27
+ * values reflect the window actually queried.
28
+ */
29
+ export declare function firesHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The read-tier route surface: `list`, `get`, `signers`, `fires`. Every one runs
3
+ * behind the READ gate ({@link withRead}) — no fresh-confirm is demanded, so a
4
+ * plain viewer can observe the codex-cronoton state (matching the Hub's
5
+ * SSR-public list/detail). These handlers ORCHESTRATE the `/server` store; they
6
+ * do not reimplement any query.
7
+ *
8
+ * The two pieces of branching that live in THIS layer (not the store) are the
9
+ * defensive query parsing — NaN/garbage falls back to a default, and every value
10
+ * is clamped to the store's own bounds so the echoed page window matches what was
11
+ * used — and the fire page-size default of 50 (REQ-G08/REQ-H07), which overrides
12
+ * the store's own default of 20. The signer projection stays SECRET-FREE
13
+ * (REQ-H10): only `publicKey` + a coarse `display`, never key material.
14
+ */
15
+ import { json, err, defaultSignerSource, } from "./http.js";
16
+ import { withRead } from "./context.js";
17
+ import { listCodexCronotons, getCodexCronoton, listFires, } from "../server/index.js";
18
+ /** First scalar of a query value (a repeated key arrives as an array); `undefined` if empty. */
19
+ function firstScalar(raw) {
20
+ const value = Array.isArray(raw) ? raw[0] : raw;
21
+ return value === undefined || value === null || value === "" ? undefined : value;
22
+ }
23
+ /**
24
+ * Parse a query int, falling back to `def` for absent/NaN input, then clamp into
25
+ * `[min, max]`. Clamping in the handler (not only in the store) keeps the echoed
26
+ * `limit`/`offset` equal to the window actually queried.
27
+ */
28
+ function clampInt(raw, { def, min, max }) {
29
+ const scalar = firstScalar(raw);
30
+ const parsed = scalar === undefined ? Number.NaN : Number.parseInt(scalar, 10);
31
+ const base = Number.isNaN(parsed) ? def : parsed;
32
+ const lowerBounded = Math.max(base, min);
33
+ return max === undefined ? lowerBounded : Math.min(lowerBounded, max);
34
+ }
35
+ const CRONOTON_STATUSES = new Set([
36
+ "active",
37
+ "paused",
38
+ "completed",
39
+ "error",
40
+ ]);
41
+ /** Narrow a raw query status to the row union, or `undefined` for an unknown value. */
42
+ function parseStatus(raw) {
43
+ const scalar = firstScalar(raw);
44
+ return scalar !== undefined && CRONOTON_STATUSES.has(scalar)
45
+ ? scalar
46
+ : undefined;
47
+ }
48
+ // ── Handlers ──────────────────────────────────────────────────────────────────
49
+ /** `GET /` — the newest-first cronoton list (store clamps limit 1..200). */
50
+ export async function listHandler(ctx, request) {
51
+ return withRead(ctx, request, async () => {
52
+ const query = request.query ?? {};
53
+ const codexCronotons = listCodexCronotons({
54
+ limit: clampInt(query.limit, { def: 50, min: 1, max: 200 }),
55
+ offset: clampInt(query.offset, { def: 0, min: 0 }),
56
+ status: parseStatus(query.status),
57
+ }, { db: ctx.db });
58
+ return json(200, { ok: true, codexCronotons });
59
+ });
60
+ }
61
+ /** `GET /[id]` — the single cronoton row, or 404 when absent. */
62
+ export async function getHandler(ctx, request) {
63
+ return withRead(ctx, request, async () => {
64
+ const id = request.params?.id ?? "";
65
+ const codexCronoton = getCodexCronoton(id, { db: ctx.db });
66
+ if (!codexCronoton) {
67
+ return err(404, "not found");
68
+ }
69
+ return json(200, { ok: true, codexCronoton });
70
+ });
71
+ }
72
+ /** `GET /signers` — the SECRET-FREE signer descriptors (never key material). */
73
+ export async function signersHandler(ctx, request) {
74
+ return withRead(ctx, request, async () => {
75
+ const source = ctx.signers ?? defaultSignerSource(ctx.resolver);
76
+ const signers = await source.listSignerDescriptors();
77
+ return json(200, { ok: true, signers });
78
+ });
79
+ }
80
+ /**
81
+ * `GET /[id]/fires?limit&offset` — paginated fire history. The page size defaults
82
+ * to 50 (REQ-G08) — overriding the store's own default of 20 — and both echoed
83
+ * values reflect the window actually queried.
84
+ */
85
+ export async function firesHandler(ctx, request) {
86
+ return withRead(ctx, request, async () => {
87
+ const id = request.params?.id ?? "";
88
+ const query = request.query ?? {};
89
+ const limit = clampInt(query.limit, { def: 50, min: 1, max: 100 });
90
+ const offset = clampInt(query.offset, { def: 0, min: 0 });
91
+ const { fires, total } = listFires(id, { limit, offset }, { db: ctx.db });
92
+ return json(200, { ok: true, fires, total, limit, offset });
93
+ });
94
+ }
@@ -0,0 +1,143 @@
1
+ import { L as ListCronotonsQuery, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, R as RecoverView, S as SimulateEnvelope, e as SimulateView, f as StartBatchView, g as RuntimeArgs } from '../context-BKtdrA2B.js';
2
+ export { U as UseKhronotonResult, u as useKhronoton } from '../context-BKtdrA2B.js';
3
+ import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-u_nUX1Bg.js';
4
+ import 'react';
5
+
6
+ /** The `useCronotons()` return shape — the list, its load state, and a refetch. */
7
+ interface UseCronotonsView {
8
+ cronotons: CodexCronotonRow[];
9
+ loading: boolean;
10
+ error: Error | null;
11
+ /** Re-run the load (SSR-style refresh the action hooks call after a mutation). */
12
+ refetch: () => Promise<void>;
13
+ }
14
+ declare function useCronotons(query?: ListCronotonsQuery): UseCronotonsView;
15
+
16
+ /** The `useCronoton()` return shape — the row, its load state, and a refetch. */
17
+ interface UseCronotonView {
18
+ cronoton: CodexCronotonRow | null;
19
+ loading: boolean;
20
+ error: Error | null;
21
+ /** Re-run the load (SSR-style refresh the action hooks call after a mutation). */
22
+ refetch: () => Promise<void>;
23
+ }
24
+ declare function useCronoton(id: string): UseCronotonView;
25
+
26
+ interface UseCronotonFiresOptions {
27
+ /** Overrides the provider's page size (default 50) for this history view. */
28
+ pageSize?: number;
29
+ }
30
+ interface UseCronotonFiresResult {
31
+ fires: CodexCronotonFireRow[];
32
+ total: number;
33
+ page: number;
34
+ pageCount: number;
35
+ loading: boolean;
36
+ error: Error | null;
37
+ setPage: (page: number) => void;
38
+ refetch: () => void;
39
+ }
40
+ declare function useCronotonFires(id: string, opts?: UseCronotonFiresOptions): UseCronotonFiresResult;
41
+
42
+ /** The `useManualBatch` return surface the Phase-E detail view consumes. */
43
+ interface UseManualBatchResult {
44
+ /** The current batch projection, or `null` when the cronoton has no active batch. */
45
+ batch: ManualBatchView | null;
46
+ /** `true` while a batch is running — the poller-live / show-progress flag. */
47
+ active: boolean;
48
+ /** `true` from mount until the first explicit load settles. */
49
+ loading: boolean;
50
+ /** An explicit-load failure (mount or `refetch`); poll failures never set this. */
51
+ error: Error | null;
52
+ /** Re-read the batch on demand (e.g. after a start/cancel action elsewhere). */
53
+ refetch: () => Promise<void>;
54
+ }
55
+ declare function useManualBatch(id: string): UseManualBatchResult;
56
+
57
+ /** A successful action: the adapter body, untouched. */
58
+ interface ActionOk<T> {
59
+ ok: true;
60
+ result: T;
61
+ }
62
+ /** A failed action: a cancelled re-confirm, a second expiry, or a transport error. */
63
+ interface ActionFail {
64
+ ok: false;
65
+ error: Error;
66
+ }
67
+ /** The envelope every `run` resolves to — the host branches on `ok`. */
68
+ type ActionResult<T> = ActionOk<T> | ActionFail;
69
+ /** One lifecycle action's public surface. */
70
+ interface GatedAction<Args extends unknown[], T> {
71
+ run: (...args: Args) => Promise<ActionResult<T>>;
72
+ pending: boolean;
73
+ error: Error | null;
74
+ result: T | null;
75
+ }
76
+ type CreateAction = GatedAction<[CommitBody], CommitView>;
77
+ type EditAction = GatedAction<[EditPatch], EditView>;
78
+ type ToggleAction = GatedAction<[], ToggleView>;
79
+ type DeleteAction = GatedAction<[], DeleteView>;
80
+ /** The bundle `useCronotonActions` returns. */
81
+ interface CronotonActions {
82
+ create: CreateAction;
83
+ edit: EditAction;
84
+ pause: ToggleAction;
85
+ resume: ToggleAction;
86
+ remove: DeleteAction;
87
+ }
88
+ interface UseCronotonActionsOptions {
89
+ /** Fired after any successful mutation — the host's SSR-style refetch hook. */
90
+ onSuccess?: () => void;
91
+ }
92
+ /**
93
+ * The lifecycle action bundle. Pass the detail-page `id` to scope
94
+ * edit/pause/resume/remove to that cronoton; `create` needs no id. Every action
95
+ * is confirm-gated with the shared retry-once re-prompt.
96
+ */
97
+ declare function useCronotonActions(id?: string, options?: UseCronotonActionsOptions): CronotonActions;
98
+
99
+ /**
100
+ * The shared execution-action result. `run` performs the action and returns the
101
+ * adapter body on success (or `undefined` when the call threw), while `pending`,
102
+ * `error`, and `result` mirror the last invocation for render.
103
+ */
104
+ interface UseExecuteActionResult<TArgs extends unknown[], TView> {
105
+ /** Perform the action; resolves the adapter body, or `undefined` on a thrown error. */
106
+ run: (...args: TArgs) => Promise<TView | undefined>;
107
+ /** True while `run` is in flight. */
108
+ pending: boolean;
109
+ /** A transport/confirm failure (a thrown path). Never set for a 200-on-`ok:false` body. */
110
+ error: Error | null;
111
+ /** The last successful adapter body — including a fire-level `{ ok:false }`. */
112
+ result?: TView;
113
+ }
114
+ /** Fire a cronoton once, right now, outside its schedule (confirm-gated). */
115
+ declare function useExecuteNow(): UseExecuteActionResult<[id: string], ExecuteView>;
116
+ /** Fire a cronoton now with supplied runtime args (confirm-gated). */
117
+ declare function useTrigger(): UseExecuteActionResult<[
118
+ id: string,
119
+ args: RuntimeArgs
120
+ ], ExecuteView>;
121
+ /** Preview a tx build/gas without firing it (confirm-gated; full union returned). */
122
+ declare function useSimulate(): UseExecuteActionResult<[
123
+ envelope: SimulateEnvelope
124
+ ], SimulateView>;
125
+ /** Start a manual execute-batch of `count` fires (confirm-gated). */
126
+ declare function useStartBatch(): UseExecuteActionResult<[
127
+ id: string,
128
+ count: number
129
+ ], StartBatchView>;
130
+ /**
131
+ * Cancel the active manual batch — CONFIRM-FREE (REQ-H09). Deliberately bypasses
132
+ * `runGated`: a runaway batch must halt in one click, never blocked on a
133
+ * confirm-gate expiry.
134
+ */
135
+ declare function useCancelBatch(): UseExecuteActionResult<[id: string], CancelBatchView>;
136
+ /** Reconcile a stale failed fire against the chain (confirm-gated; REQ-G09). */
137
+ declare function useRecoverFire(): UseExecuteActionResult<[
138
+ id: string,
139
+ fireId: string,
140
+ requestKey: string
141
+ ], RecoverView>;
142
+
143
+ export { type ActionFail, type ActionOk, type ActionResult, type CreateAction, type CronotonActions, type DeleteAction, type EditAction, type GatedAction, type ToggleAction, type UseCronotonActionsOptions, type UseCronotonFiresOptions, type UseCronotonFiresResult, type UseCronotonView, type UseCronotonsView, type UseExecuteActionResult, type UseManualBatchResult, useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useSimulate, useStartBatch, useTrigger };
@@ -0,0 +1,2 @@
1
+ export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useSimulate, useStartBatch, useTrigger } from '../chunk-DK4CDPXH.js';
2
+ export { useKhronoton } from '../chunk-U3F5HEHO.js';
@@ -0,0 +1,220 @@
1
+ import { ReactNode } from 'react';
2
+ import { H as HandlerRequest, h as HandlerResponse, K as KhronotonProviderProps, i as KhronotonAdapter, j as SignerSource } from '../context-BKtdrA2B.js';
3
+ export { c as CancelBatchView, k as CodexSignerDescriptor, C as CommitBody, a as CommitView, l as ConfirmGate, m as ConfirmOpts, n as DEFAULT_EXPLORER_BASE, o as DEFAULT_PAGE_SIZE, p as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, q as FiresView, G as GetBatchView, r as GetCronotonView, s as KhronotonConfig, t as KhronotonSnapshot, L as ListCronotonsQuery, v as ListCronotonsView, R as RecoverView, w as RenderMultiTx, g as RuntimeArgs, x as ServerResolverOption, y as SignersView, S as SimulateEnvelope, e as SimulateView, f as StartBatchView, T as ToggleView, U as UseKhronotonResult, z as assertAdapter, A as emptySnapshot, u as useKhronoton } from '../context-BKtdrA2B.js';
4
+ import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-BvPnTSmg.js';
5
+ export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-u_nUX1Bg.js';
6
+
7
+ /**
8
+ * The per-request handler context + the injectable auth/confirm seam + the two
9
+ * gate wrappers.
10
+ *
11
+ * The consumer supplies a {@link HandlerContext} on every call: the injected DB
12
+ * handle, chain runtime, key resolver, and the seams the store/executor already
13
+ * defined in `/server` (all re-exported below so a consumer imports the whole
14
+ * handler contract from one entry — never redeclared here). The {@link AuthSeam}
15
+ * genericizes the Hub's role + fresh-confirm model into two gates: a READ gate
16
+ * (list/get/fires/signers + the batch stop path) and a CONFIRM gate (every
17
+ * mutating handler). {@link withRead} / {@link withConfirm} run the appropriate
18
+ * gate, short-circuit on denial, otherwise invoke the handler body and translate
19
+ * any thrown store error through {@link mapStoreError}.
20
+ */
21
+
22
+ /** The (optional) identity a passing gate attaches for the handler body to attribute writes to. */
23
+ interface AuthIdentity {
24
+ id?: string;
25
+ email?: string;
26
+ }
27
+ /**
28
+ * A gate outcome: either a pass carrying an optional identity, or a block
29
+ * carrying the exact {@link HandlerResponse} the wrapper returns verbatim (a 401
30
+ * `admin_confirm_required` for a stale/absent confirm, a 403 for a non-admin).
31
+ */
32
+ type AuthResult = {
33
+ ok: true;
34
+ identity?: AuthIdentity;
35
+ } | {
36
+ ok: false;
37
+ response: HandlerResponse;
38
+ };
39
+ /**
40
+ * The injectable auth/confirm contract. A trusted single-tenant consumer uses
41
+ * {@link defaultOpenAuth}; a stricter consumer implements both gates against its
42
+ * own role + confirm-modal flow. Each gate may be sync or async.
43
+ */
44
+ interface AuthSeam {
45
+ /** Read tier: list/get/fires/signers + the batch get/cancel stop path. */
46
+ requireRead(req: HandlerRequest): AuthResult | Promise<AuthResult>;
47
+ /** Mutate tier: demands a fresh admin-confirm; blocks with 401/403 otherwise. */
48
+ requireConfirm(req: HandlerRequest): AuthResult | Promise<AuthResult>;
49
+ }
50
+ /**
51
+ * A sentinel a strict consumer's confirm gate (or a handler body) may THROW to
52
+ * signal a stale/absent confirm; the gate wrappers translate it to the canonical
53
+ * 401 `admin_confirm_required`. The gate may equally RETURN a blocking
54
+ * {@link AuthResult} — this class is the throw-based alternative.
55
+ */
56
+ declare class NeedsConfirmError extends Error {
57
+ readonly code = "admin_confirm_required";
58
+ constructor(message?: string);
59
+ }
60
+
61
+ declare function KhronotonProvider(props: KhronotonProviderProps): ReactNode;
62
+
63
+ /**
64
+ * The minimal HTTP-response surface the fetch adapter needs — a status plus a
65
+ * JSON body reader. Defined structurally (not as the DOM `Response`) so the
66
+ * package typechecks without `lib:["DOM"]` and a test can inject a plain stub;
67
+ * the platform `fetch`'s `Response` satisfies it.
68
+ */
69
+ interface FetchResponse {
70
+ readonly status: number;
71
+ json(): Promise<unknown>;
72
+ }
73
+ /** A decoded handler outcome: the HTTP status paired with the parsed JSON body. */
74
+ interface StatusResult {
75
+ status: number;
76
+ body: unknown;
77
+ }
78
+ /**
79
+ * Translate a `{ status, body }` handler outcome into the seam's return value:
80
+ * resolve the body on 2xx, throw {@link NeedsConfirmError} on a 401
81
+ * `admin_confirm_required`, throw `Error(body.error ?? 'HTTP {status}')`
82
+ * otherwise. Shared by the fetch + memory adapters so their error mapping never
83
+ * drifts.
84
+ */
85
+ declare function parseHandlerResult<T>({ status, body }: StatusResult): T;
86
+ /**
87
+ * Read a {@link FetchResponse}'s JSON body and run it through
88
+ * {@link parseHandlerResult}. A body that fails to parse (an empty/non-JSON
89
+ * error page) is treated as `{}` so the status still maps to the right error.
90
+ */
91
+ declare function parseFetchResponse<T>(res: FetchResponse): Promise<T>;
92
+
93
+ /**
94
+ * `createFetchAdapter` — the fetch-based reference {@link KhronotonAdapter}. It
95
+ * is the CLIENT side of the Phase-C handler contract: each of the 16 seam methods
96
+ * issues the matching `fetch` (verb + path + JSON body) against `baseUrl` — the
97
+ * same routes a consumer wraps its `khronoton-core/handlers` with — and parses
98
+ * every response through the shared {@link parseFetchResponse} status map
99
+ * (2xx → body; 401 `admin_confirm_required` → {@link NeedsConfirmError}; other
100
+ * non-2xx → `Error`). React-free: it only touches `fetch`, so a server route, a
101
+ * worker, or a browser can all use it.
102
+ *
103
+ * ── Confirm threading ─────────────────────────────────────────────────────────
104
+ * The confirm gate lives in the provider/hook layer (`runGated`, T4.5); this
105
+ * adapter only CARRIES the fresh-confirm signal. Each mutating method takes a
106
+ * trailing {@link ConfirmOpts}; when `opts.confirmed === true` the request adds a
107
+ * `{@link CONFIRMED_HEADER}: "1"` header the host route reads back into
108
+ * `req.confirmed`. Read methods send no confirm. `cancelBatch` is a deliberately
109
+ * confirm-free one-click stop (parity §5), so it takes no opts.
110
+ */
111
+
112
+ /**
113
+ * The header the fetch adapter sets to `"1"` on a fresh-confirm mutating request;
114
+ * the consumer's route maps it back to `req.confirmed === true`.
115
+ */
116
+ declare const CONFIRMED_HEADER = "x-khronoton-confirmed";
117
+ /** The minimal request init the adapter builds — a structural subset of the DOM `RequestInit`. */
118
+ interface FetchInit {
119
+ method?: string;
120
+ headers?: Record<string, string>;
121
+ body?: string;
122
+ }
123
+ /** The injectable `fetch` — the platform `fetch` satisfies it; tests pass a stub. */
124
+ type FetchLike = (url: string, init?: FetchInit) => Promise<FetchResponse>;
125
+ /** Static headers to merge onto every request: an object or a per-call factory. */
126
+ type HeaderSource = Record<string, string> | (() => Record<string, string>);
127
+ interface FetchAdapterOptions {
128
+ /** Override the `fetch` implementation (default: the global `fetch`). */
129
+ fetch?: FetchLike;
130
+ /** Headers merged onto every request (e.g. an auth token) — static or per-call. */
131
+ headers?: HeaderSource;
132
+ }
133
+ /**
134
+ * Build a fetch-backed {@link KhronotonAdapter} against `baseUrl` (the host's
135
+ * cronoton API base, e.g. `/api/admin/codex-cronotons`). Stateless — safe to
136
+ * construct per render or share.
137
+ */
138
+ declare function createFetchAdapter(baseUrl: string, opts?: FetchAdapterOptions): KhronotonAdapter;
139
+
140
+ /**
141
+ * `createMemoryAdapter` — the in-process reference {@link KhronotonAdapter}. It is
142
+ * the SAME client seam the fetch adapter implements, but with NO network: instead
143
+ * of issuing HTTP against a host's routes, each method drives the corresponding
144
+ * Phase-C `/handlers` function DIRECTLY over an internal {@link HandlerContext}
145
+ * (an in-memory `better-sqlite3` DB + `installSchema`, an injectable
146
+ * `ChainRuntime`/`KeyResolver`, and {@link defaultOpenAuth}). It is the
147
+ * "in-process handler driver" for tests, SSR-seed, and demos — not a
148
+ * browser-localStorage store.
149
+ *
150
+ * ── The DB is the seam ────────────────────────────────────────────────────────
151
+ * `better-sqlite3` is an optional/dev dependency (native, Node-only), so the
152
+ * adapter never imports it — the CONSUMER injects a `db` handle. In a browser
153
+ * demo where `better-sqlite3` is unavailable, a consumer supplies its own
154
+ * `Database`-shaped handle; the adapter installs the schema on it by default
155
+ * (idempotent `IF NOT EXISTS` DDL) so a fresh `:memory:` db works out of the box.
156
+ * A pre-migrated/pre-seeded demo db passes `migrate: false`. The caller OWNS the
157
+ * db lifecycle (the adapter never closes an injected handle).
158
+ *
159
+ * ── Confirm threading (parity with the fetch adapter) ─────────────────────────
160
+ * The confirm gate lives in the provider/hook layer (`runGated`, T4.5); this
161
+ * adapter only CARRIES the signal. Each mutating method threads
162
+ * `opts?.confirmed` onto `req.confirmed`, so `defaultOpenAuth.requireConfirm`
163
+ * passes only when a fresh confirm accompanied the call — exactly like the fetch
164
+ * adapter's header. Read methods (and the confirm-free `getBatch`/`cancelBatch`)
165
+ * set no confirm. Every handler's `{ status, body }` envelope runs through the
166
+ * SHARED {@link parseHandlerResult} (2xx → body; 401 `admin_confirm_required` →
167
+ * {@link NeedsConfirmError}; other non-2xx → `Error`), so the memory + fetch
168
+ * adapters map outcomes identically — no drift.
169
+ */
170
+
171
+ /** The seams a consumer injects when building an in-process adapter. */
172
+ interface MemoryAdapterOptions {
173
+ /**
174
+ * The in-process store handle — a `better-sqlite3` `Database` in Node, or any
175
+ * `Database`-shaped handle a consumer supplies (the adapter never imports
176
+ * `better-sqlite3` itself, keeping the module browser-safe).
177
+ */
178
+ db: Database;
179
+ /** Run `installSchema` on `db` before first use (default `true`; `false` for a pre-migrated db). */
180
+ migrate?: boolean;
181
+ /**
182
+ * The chain runtime the execution handlers drive. Default: a throwing stub —
183
+ * read/lifecycle/batch ops never touch it, but `simulate`/`executeNow`/
184
+ * `trigger` require a real (or mock) runtime, so inject one to exercise them.
185
+ */
186
+ runtime?: ChainRuntime;
187
+ /** The key resolver the signer projection reads. Default: an empty (no-signer) resolver. */
188
+ resolver?: KeyResolver;
189
+ resolveFireMode?: ResolveFireMode;
190
+ onAudit?: OnAudit;
191
+ config?: Partial<Config>;
192
+ /** The auth/confirm seam. Default {@link defaultOpenAuth} (trusted single-tenant). */
193
+ auth?: AuthSeam;
194
+ /** A richer signer source (else the default reads the resolver's owned pubs). */
195
+ signers?: SignerSource;
196
+ }
197
+ /**
198
+ * Build an in-process {@link KhronotonAdapter}. Constructing it touches neither
199
+ * `window` nor the network, so it is safe to build during a server render, a
200
+ * test, or an SSR seed. The returned adapter shares one {@link HandlerContext}:
201
+ * every method assembles the matching {@link HandlerRequest} and calls the real
202
+ * handler, then maps `{ status, body }` through {@link parseHandlerResult}.
203
+ */
204
+ declare function createMemoryAdapter(opts: MemoryAdapterOptions): KhronotonAdapter;
205
+
206
+ /** The confirm-gated call: the provider threads the fresh-confirm signal in. */
207
+ type GatedFn<T> = (opts: {
208
+ confirmed: boolean;
209
+ }) => Promise<T>;
210
+ interface RunGatedOptions {
211
+ /**
212
+ * The host re-confirm gate. Resolves `true` when the user re-confirms after an
213
+ * expiry (triggering the single retry) and `false` on cancel. When omitted, an
214
+ * expired confirm surfaces without a retry.
215
+ */
216
+ onNeedConfirm?: () => Promise<boolean>;
217
+ }
218
+ declare function runGated<T>(fn: GatedFn<T>, options?: RunGatedOptions): Promise<T>;
219
+
220
+ export { CONFIRMED_HEADER, type FetchAdapterOptions, type FetchLike, type FetchResponse, type GatedFn, KhronotonAdapter, KhronotonProvider, KhronotonProviderProps, type MemoryAdapterOptions, NeedsConfirmError, type RunGatedOptions, type StatusResult, createFetchAdapter, createMemoryAdapter, parseFetchResponse, parseHandlerResult, runGated };