@voltro/client 0.85.0 → 0.87.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +5987 -0
  2. package/THIRD-PARTY-NOTICES.md +1125 -34
  3. package/dist/analyticsCatalog.js +47 -0
  4. package/dist/apiConnectivity.js +33 -0
  5. package/dist/apiRoleTransports.js +48 -0
  6. package/dist/apiRuntime.js +145 -0
  7. package/dist/apiSocketTracker.js +21 -0
  8. package/dist/apiSupervisor.js +136 -0
  9. package/dist/authRefresh.js +20 -0
  10. package/dist/awaitResolvedApi.js +23 -0
  11. package/dist/bootstrap.d.ts +1153 -0
  12. package/dist/bootstrap.js +8 -0
  13. package/dist/cellMerger.js +6 -0
  14. package/dist/clientDiagnostics.js +94 -0
  15. package/dist/clientErrorBus.js +16 -0
  16. package/dist/clientScheduler.js +31 -0
  17. package/dist/connectionPrerequisite.js +70 -0
  18. package/dist/connectionScope.js +47 -0
  19. package/dist/connectionSetupController.js +206 -0
  20. package/dist/createHooks.js +15 -0
  21. package/dist/deepLink.js +69 -0
  22. package/dist/filters.js +58 -0
  23. package/dist/form.d.ts +37 -4
  24. package/dist/form.js +7 -2
  25. package/dist/formBinding.js +325 -0
  26. package/dist/formData.js +127 -0
  27. package/dist/formFlashId.js +4 -0
  28. package/dist/formRejection.js +23 -0
  29. package/dist/formSource.js +13 -0
  30. package/dist/frameworkRuntimesContext.js +8 -0
  31. package/dist/globalContext.js +10 -0
  32. package/dist/index.d.ts +152 -27
  33. package/dist/index.js +87 -4121
  34. package/dist/liveRowSort.js +66 -0
  35. package/dist/mutationConnectionSetup.js +16 -0
  36. package/dist/mutationIdentity.js +10 -0
  37. package/dist/mutationSerialExecution.js +53 -0
  38. package/dist/mutationsBus.js +40 -0
  39. package/dist/onlineSource.js +13 -0
  40. package/dist/outbox.js +213 -0
  41. package/dist/outboxHttp.js +104 -0
  42. package/dist/outboxState.js +43 -0
  43. package/dist/permissions.js +20 -0
  44. package/dist/platform.js +121 -0
  45. package/dist/preloadSeed.js +47 -0
  46. package/dist/provider.js +22 -0
  47. package/dist/query.js +12 -2
  48. package/dist/recoveryCoordinator.js +195 -0
  49. package/dist/recoveryRetry.js +24 -0
  50. package/dist/richText.js +176 -0
  51. package/dist/rpcErrorBus.js +39 -0
  52. package/dist/rpcErrorKind.js +13 -0
  53. package/dist/runRpc.js +12 -0
  54. package/dist/runtime.d.ts +49 -3
  55. package/dist/runtime.js +16 -126
  56. package/dist/runtimeCapabilities.js +44 -0
  57. package/dist/runtimeContext.js +49 -0
  58. package/dist/schemaFields.js +219 -0
  59. package/dist/scopeMembership.js +12 -0
  60. package/dist/seedResolvers.js +7 -0
  61. package/dist/sequence.js +65 -0
  62. package/dist/serverRequest.js +28 -0
  63. package/dist/serviceClient.js +129 -0
  64. package/dist/squashRpcCause.js +8 -0
  65. package/dist/stableKey.js +21 -0
  66. package/dist/store.js +288 -0
  67. package/dist/storeStorage.js +28 -0
  68. package/dist/subscriptionCache.js +724 -0
  69. package/dist/tagWalk.js +23 -0
  70. package/dist/traceBus.js +10 -0
  71. package/dist/tracking.js +40 -0
  72. package/dist/uploadProgress.js +21 -0
  73. package/dist/useAction.js +101 -0
  74. package/dist/useAgent.js +53 -0
  75. package/dist/useAgentChat.js +43 -0
  76. package/dist/useAgentStream.js +64 -0
  77. package/dist/useApiOnline.js +14 -0
  78. package/dist/useCapabilityManifest.js +105 -0
  79. package/dist/useConnectionSetup.js +28 -0
  80. package/dist/useConnectionStatus.js +38 -0
  81. package/dist/useConnections.js +107 -0
  82. package/dist/useDataCopilot.js +24 -0
  83. package/dist/useDataTable.js +34 -0
  84. package/dist/useDerived.js +22 -0
  85. package/dist/useEvent.js +98 -0
  86. package/dist/useFormBinding.js +478 -0
  87. package/dist/useLocalQuery.js +59 -0
  88. package/dist/useMutation.js +214 -0
  89. package/dist/useOnRpcError.js +13 -0
  90. package/dist/usePreloadedSubscription.js +18 -0
  91. package/dist/usePreview.js +14 -0
  92. package/dist/useProvenance.js +51 -0
  93. package/dist/useQueryField.js +34 -0
  94. package/dist/useRecord.js +12 -0
  95. package/dist/useRefreshSubscriptions.js +22 -0
  96. package/dist/useResourceCan.js +18 -0
  97. package/dist/useResumableAgentStream.js +75 -0
  98. package/dist/useRpcCaller.js +17 -0
  99. package/dist/useSequence.js +25 -0
  100. package/dist/useSkeleton.js +13 -0
  101. package/dist/useSubscription.js +98 -0
  102. package/dist/useSubscriptionHealth.js +32 -0
  103. package/dist/useTranscription.js +51 -0
  104. package/dist/useUndo.js +33 -0
  105. package/dist/useUndoLog.js +44 -0
  106. package/dist/useUpload.js +296 -0
  107. package/dist/useWindowedSubscription.js +65 -0
  108. package/dist/useWorkflow.js +284 -0
  109. package/dist/useWorkflowRunState.js +93 -0
  110. package/dist/validation.js +39 -0
  111. package/dist/validationMessages.js +5 -0
  112. package/package.json +7 -2
  113. package/dist/authRefresh-DmfSoCca.js +0 -360
  114. package/dist/formData-BfpBt7BQ.js +0 -769
  115. package/dist/queryOnce-D5Y4V1SB.js +0 -55
  116. package/dist/runRpc-Zfz3w709.js +0 -1172
@@ -0,0 +1,1153 @@
1
+ import { ClientDescriptor } from '@voltro/protocol';
2
+ import { Context } from 'react';
3
+ import { createRowPatchApplier } from '@voltro/protocol';
4
+ import { Fiber } from 'effect';
5
+ import { ManagedRuntime } from 'effect';
6
+ import { ReactNode } from 'react';
7
+ import type * as Socket from 'effect/socket/Socket';
8
+ import { Stream } from 'effect';
9
+ import { SubscriptionEvent } from '@voltro/protocol';
10
+ import { TargetRelations } from '@voltro/protocol';
11
+
12
+ /** Erased per-api runtime boundary. Headless cache code must not import the
13
+ * React context (and its browser globals) merely to name this Effect type. */
14
+ declare type AnyRuntime = ManagedRuntime.ManagedRuntime<never, never>;
15
+
16
+ export declare interface ApiHandle {
17
+ readonly runtime: AnyRuntime;
18
+ readonly cache: SubscriptionCache;
19
+ /** Resolved typed rpc client. Methods nest by tag (`todos.list` →
20
+ * `client.todos.list`). Hooks walk by tag-segment (see `resolveByTag`)
21
+ * to invoke, so the static type here is the erased `unknown`; the typed
22
+ * view comes from `useAppClient<T>(name)` at the call site. */
23
+ readonly client: unknown;
24
+ /** Per-rpc-tag descriptor metadata. Drives auto-optimistic and source-
25
+ * based cache routing. */
26
+ readonly descriptors: Readonly<Record<string, ClientDescriptor>>;
27
+ /**
28
+ * Base HTTP origin where the api's `/_voltro/inspect/*` endpoints
29
+ * live. Derived from `wsUrl` at mount time (`ws://host:port/ws` →
30
+ * `http://host:port`). DevTools and any inspect-consuming tooling
31
+ * use this for the metrics / subscriptions / events endpoints.
32
+ */
33
+ readonly inspectBaseUrl: string;
34
+ /** Per-api error bus. Mutations + subscription failures land here so
35
+ * app-level listeners can react to typed errors globally (auto-logout
36
+ * on `Unauthenticated`, network-error toasts, etc.). */
37
+ readonly errorBus: RpcErrorBus;
38
+ /** Stable UI/raw transport recovery state for this logical api. */
39
+ readonly recovery?: RecoveryCoordinator;
40
+ /** Identity lifetime captured when this transport was built. */
41
+ readonly subjectSignal?: AbortSignal;
42
+ }
43
+
44
+ /**
45
+ * Apply preload seeds from the hydration payload, BEFORE the first client
46
+ * render. Idempotent (a Map upsert) so a re-hydration or a repeated key is
47
+ * harmless — last write wins, matching the store-seed rule.
48
+ */
49
+ export declare const applyPreloadSeeds: (seeds: ReadonlyArray<PreloadSeed> | undefined) => void;
50
+
51
+ /**
52
+ * Apply seeds from the hydration payload, BEFORE the first client render.
53
+ *
54
+ * Unknown store names are skipped rather than throwing: a payload can outlive a
55
+ * deploy (a cached document, a user with a stale tab), and refusing to boot the
56
+ * app over a store somebody deleted would turn a cosmetic staleness into a
57
+ * blank page.
58
+ */
59
+ export declare const applyStoreSeeds: (seeds: ReadonlyArray<StoreSeed> | undefined) => void;
60
+
61
+ /**
62
+ * Auto-apply target as seen from the client. Identical shape to the
63
+ * server's TargetSpec but with all schema generics erased (the client
64
+ * sees concrete row shapes at runtime, not Schema instances).
65
+ *
66
+ * Optional overrides:
67
+ * - `shape` for insert: build the row from input + optimistic id
68
+ * for update: build the patched row from (input, current)
69
+ * - `identify` for update/delete: extract the row id from input
70
+ * (defaults to `input.id`)
71
+ * - `order` for insert: 'prepend' (default) or 'append'
72
+ */
73
+ declare interface AutoApplyTarget {
74
+ readonly table: string;
75
+ readonly op: 'insert' | 'update' | 'delete';
76
+ readonly order?: 'prepend' | 'append' | undefined;
77
+ readonly shape?: ((input: Record<string, unknown>, optimisticIdOrCurrent?: unknown) => Record<string, unknown>) | undefined;
78
+ readonly identify?: ((input: Record<string, unknown>) => string | ReadonlyArray<string>) | undefined;
79
+ /** Dot-path to a nested array WITHIN the query value (e.g.
80
+ * `'snapshot.projects'`). When set, the reducer patches that nested array at
81
+ * ITEM granularity instead of the top-level row array — for JSON array
82
+ * columns + computed/shaped query results. */
83
+ readonly path?: string | undefined;
84
+ /** Item key within the nested array (default `'id'`). Only with `path`. */
85
+ readonly by?: string | undefined;
86
+ /** Guard which cached entries to patch — only entries whose current (base)
87
+ * value satisfies this. Stops a patch bleeding across sibling subscriptions
88
+ * sharing a source table. */
89
+ readonly match?: ((value: unknown, input: Record<string, unknown>) => boolean) | undefined;
90
+ /** Nested-item shaper — the client uses this (not `shape`) to build/patch a
91
+ * nested-array item when `path` is set. Typed to the item, not the output.
92
+ * 2nd arg is the optimistic id (insert) or the current item (update). */
93
+ readonly shapeItem?: ((input: Record<string, unknown>, currentOrOptimisticId: unknown) => Record<string, unknown>) | undefined;
94
+ /** Declared many-to-many relations (`{ inputField: { junction, anchorColumn,
95
+ * targetColumn } }`). Drives JUNCTION auto-optimistic: entries sourced on the
96
+ * junction table get their link rows for this anchor reconciled against
97
+ * `input[inputField]` immediately, instead of waiting for the server delta
98
+ * while every scalar field of the same form has already flipped. */
99
+ readonly relations?: TargetRelations | undefined;
100
+ }
101
+
102
+ declare interface BiometricSource {
103
+ readonly available: () => Promise<boolean>;
104
+ readonly authenticate: (reason: string) => Promise<boolean>;
105
+ }
106
+
107
+ /**
108
+ * The browser adapter. `@voltro/web` installs it at mount; it is also the
109
+ * lazy default so hooks answer sensibly in a tab that never called
110
+ * `installPlatform` (and under jsdom, where the shell reads as `'test'`).
111
+ */
112
+ export declare const browserPlatform: (overrides?: Partial<PlatformAdapterInput>) => PlatformAdapter;
113
+
114
+ declare interface CacheEntry {
115
+ rowPatchApplier?: ReturnType<typeof createRowPatchApplier>;
116
+ readonly key: string;
117
+ /** First element of the keyArr — the rpc tag (e.g. 'todos.list'). Used
118
+ * by `forTag()` so callers can patch every sub-key for a tag without
119
+ * knowing the inputs. Captured at create-time so updates without a
120
+ * prior subscribe still work (stub entries get tag too). */
121
+ readonly tag: string | undefined;
122
+ state: EntryState<unknown>;
123
+ /** Retired stream callbacks must not mutate the replacement generation. */
124
+ generation: number;
125
+ /** Coalesce same-tick mutation ACKs into one causal read per entry. */
126
+ reconciliationScheduled: boolean;
127
+ /** Once this entry has read its own write, reconnects must not downgrade to
128
+ * a lagging replica. Same-subject replacements carry this bit with rows. */
129
+ primaryReads: boolean;
130
+ /** Subscriber re-render callbacks. */
131
+ subscribers: Set<() => void>;
132
+ /** Fiber running the underlying stream. */
133
+ fiber: Fiber.Fiber<unknown, unknown> | null;
134
+ /** The last fiber ended because the rpc transport failed. A later socket
135
+ * `open` re-issues active entries with their last-known-good base intact. */
136
+ resumeAfterTransportOpen: boolean;
137
+ recoveryPhase: 'steady' | 'awaiting-protocol' | 'awaiting-delivery' | 'stuck';
138
+ recoveryAttempt: number;
139
+ lastTransportFailureAt: number | undefined;
140
+ lastReissueAt: number | undefined;
141
+ lastDeliveryAt: number | undefined;
142
+ recoveryBasePreserved: boolean;
143
+ recoveryTimer: ReturnType<typeof setTimeout> | null;
144
+ /** Pending eviction (last subscriber gone, TTL countdown). */
145
+ evictionTimer: NodeJS.Timeout | null;
146
+ /** Source table(s) this entry reads (from the rpc descriptor). Used by
147
+ * auto-optimistic to find which entries to patch when a mutation with
148
+ * a matching `target.table` is invoked — an array matches if the target is
149
+ * among the listed tables. May be undefined for queries whose source isn't
150
+ * expressed as table(s) (joins, aggregates). */
151
+ source: string | ReadonlyArray<string> | undefined;
152
+ /** True once a server snapshot reported this query as COMPUTED (handler
153
+ * returns a shaped value, not a table row-set). Auto-optimistic skips
154
+ * blind INSERTs into computed entries — the client can't evaluate the
155
+ * query's opaque server-side filter to know if a new row belongs, so it
156
+ * defers to the authoritative recompute push. UPDATE/DELETE (matched by
157
+ * id) still apply. Defaults false until the first snapshot resolves it. */
158
+ computed: boolean;
159
+ /** Saved `fetch` thunk from the first subscribe(). Used by `refreshAll()`
160
+ * to re-issue the WS subscription after a connection-subject re-bind
161
+ * (e.g. soft re-auth after login). Each subscriber's hook keeps its
162
+ * own fetch closure, but only the first one's identity matters — the
163
+ * server-side subscription is one per cache-entry key, not per
164
+ * subscriber. */
165
+ fetch: (() => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>) | null;
166
+ /** The runtime the saved `fetch` was forked against. Stored so a SINGLE entry
167
+ * can be re-issued without the whole-cache `refreshAll(runtime)` — the
168
+ * confirmed-patch resync needs exactly one, and threading a runtime down
169
+ * from a `setTimeout` is not available to it. */
170
+ runtime: AnyRuntime | null;
171
+ /** W3C trace id of the live stream, captured when the fiber starts.
172
+ * Shared with the server (the subscription span propagates it) and
173
+ * attached to error-bus events so a failure points at the right
174
+ * `voltro logs --trace <id>`. */
175
+ traceId?: string;
176
+ }
177
+
178
+ /** Plain-data snapshot of a single cache entry for devtools / test
179
+ * introspection. Doesn't carry the live fiber or React-subscriber
180
+ * set — those are kept private. */
181
+ declare interface CacheEntrySnapshot {
182
+ readonly key: string;
183
+ readonly tag: string | undefined;
184
+ readonly source: string | ReadonlyArray<string> | undefined;
185
+ readonly subscriberCount: number;
186
+ /** True while the underlying stream's fiber is running. */
187
+ readonly hasFiber: boolean;
188
+ /** True after the last subscriber left and the eviction TTL is
189
+ * counting down — a quick remount within the window resurrects. */
190
+ readonly evicting: boolean;
191
+ /** Recovery of a transport-terminal stream, without exposing its input. */
192
+ readonly recovery: {
193
+ readonly phase: 'steady' | 'awaiting-protocol' | 'awaiting-delivery' | 'stuck';
194
+ readonly attempt: number;
195
+ readonly lastTransportFailureAt: number | undefined;
196
+ readonly lastReissueAt: number | undefined;
197
+ readonly lastDeliveryAt: number | undefined;
198
+ readonly basePreserved: boolean;
199
+ };
200
+ readonly snapshot: CacheSnapshot<unknown>;
201
+ }
202
+
203
+ declare interface CacheSnapshot<T> {
204
+ /** Current visible data = base + all live patches applied in order. */
205
+ readonly data: T | undefined;
206
+ /** Most recent revision the server delivered. -1 if no snapshot yet. */
207
+ readonly revision: number;
208
+ /** Wall-clock ms when the most recent server delta was emitted; undefined for snapshots. */
209
+ readonly emittedAt: number | undefined;
210
+ /** Why the stream failed, if no snapshot has ever arrived — the value the
211
+ * api's error bus carries in `RpcError.error` for the same failure: the
212
+ * declared error itself (match on `_tag`), an `RpcClientError` for a
213
+ * transport failure, or the defect. Never an Effect `Cause`. */
214
+ readonly error: unknown | undefined;
215
+ /** Number of live optimistic patches currently applied. */
216
+ readonly pendingPatches: number;
217
+ }
218
+
219
+ /** The installed adapter, or the lazily-built browser default. */
220
+ export declare const currentPlatform: () => PlatformAdapter;
221
+
222
+ /** Inbound URLs: the one the app was opened with, and the ones that arrive
223
+ * while it runs (universal links, custom schemes, protocol handlers). */
224
+ declare interface DeepLinkSource {
225
+ readonly initialUrl: () => Promise<string | null>;
226
+ readonly subscribe: (onUrl: (url: string) => void) => () => void;
227
+ }
228
+
229
+ declare interface EntryState<T> {
230
+ /** Last server-delivered data (base for patches). */
231
+ base: T | undefined;
232
+ baseRevision: number;
233
+ baseEmittedAt: number | undefined;
234
+ baseError: unknown | undefined;
235
+ patches: Array<OptimisticPatch<T>>;
236
+ /** Cached optimistic snapshot — invalidated on every state change so
237
+ * `getSnapshot` returns a stable reference between mutations. */
238
+ cachedSnapshot: CacheSnapshot<T> | null;
239
+ previewPrefix?: {
240
+ readonly base: T;
241
+ readonly count: number;
242
+ readonly data: T;
243
+ };
244
+ previewBase?: {
245
+ readonly base: T;
246
+ readonly eligible: boolean;
247
+ };
248
+ }
249
+
250
+ /**
251
+ * The error/values payload a failed no-JS form POST carries back into the
252
+ * 422 re-render. Keyed by `formKey` so a page with several forms re-fills
253
+ * only the one that was submitted. The SSR render passes it through the
254
+ * server-request context; the client reads the same payload back off the
255
+ * `#__voltro_form_flash__` JSON script, so a late-hydrating page shows the
256
+ * identical state (no mismatch, no vanished errors).
257
+ */
258
+ declare interface FormFlashPayload {
259
+ /** The submitted form's key — `<AutoForm formKey>` or its mutation tag. */
260
+ readonly formKey: string;
261
+ /** The mapped input values as posted (pre-decode), to re-fill the fields. */
262
+ readonly values: Readonly<Record<string, unknown>>;
263
+ /** First error per field — the `validateFields` shape. */
264
+ readonly errors: Readonly<Record<string, string>>;
265
+ /** A non-field error (the RPC refused after valid input: guard, server). */
266
+ readonly formError?: string;
267
+ /** JSON encoded through the procedure's declared error schema. Private to
268
+ * this failed submit; never a publication or permission proof. */
269
+ readonly rejection?: unknown;
270
+ /** Admitted original page for repeated native errors and late hydration. */
271
+ readonly sourcePath?: string;
272
+ }
273
+
274
+ export declare interface FrameworkRuntimes {
275
+ /** Look up an api handle (runtime + cache) by name. Throws if no such api was mounted. */
276
+ readonly get: (name: string) => ApiHandle;
277
+ /** Enumerate the names of currently-installed apis (for debug). */
278
+ readonly names: ReadonlyArray<string>;
279
+ /**
280
+ * "Something in this tree needs `apiName`."
281
+ *
282
+ * Under `web.api.connect: 'lazy'` the provider does not open a socket until
283
+ * this is called, so a page that reads no data never opens one. Under the
284
+ * default `'eager'` it is a no-op — every api connects at mount, as before.
285
+ *
286
+ * It exists because the alternative was worse in a specific, measured way:
287
+ * `interactive: 'full'` is the DEFAULT render mode, and the client opened a
288
+ * WebSocket on every such page whether or not it subscribed. A pre-rendered
289
+ * documentation page with no data at all opened one (measured in a real
290
+ * browser: 0 sockets on `interactive: 'none'` / `'islands'`, one on `'full'`).
291
+ * And an open socket keeps a dormancy-managed instance awake — `isIdleNow`
292
+ * returns false while `connectedClients() > 0` — so one browser tab on a
293
+ * pricing page prevented scale-to-zero indefinitely.
294
+ *
295
+ * Optional so a foreign host embedding `FrameworkRuntimesContext` by hand
296
+ * keeps working; absent means "already connected", which is the safe reading.
297
+ */
298
+ readonly demand?: (apiName: string) => void;
299
+ /**
300
+ * One read through an api's client — the browser half of a loader's
301
+ * `ctx.query`. Supplied by the host that builds the rpc runtime
302
+ * (`VoltroRuntimeProvider`), not by this context: the read reaches the rpc
303
+ * client and with it the Effect runtime, and an app that mounts no api must
304
+ * not load either just because its router can ask. Absent → `ctx.query` is
305
+ * `undefined` in the browser, as it is for an app without apis.
306
+ */
307
+ readonly queryOnce?: QueryOnce;
308
+ /**
309
+ * Resolves once the rpc runtime behind these apis is loaded. A host that
310
+ * loads it on demand (the web boot keeps it out of an app's first load and
311
+ * fetches it with the first route that reads data) supplies it; absent means
312
+ * the runtime is already there.
313
+ */
314
+ readonly ready?: () => Promise<void>;
315
+ }
316
+
317
+ export declare const FrameworkRuntimesContext: Context<FrameworkRuntimes | null>;
318
+
319
+ export declare const FrameworkRuntimesProvider: ({ apis, children, demand, queryOnce, }: FrameworkRuntimesProviderProps) => ReactNode;
320
+
321
+ export declare interface FrameworkRuntimesProviderProps {
322
+ readonly apis: ReadonlyMap<string, ApiHandle>;
323
+ readonly children: ReactNode;
324
+ /** Passed straight through to the context so `useFrameworkApi` can say that
325
+ * something in the tree needs an api. The web boot supplies it under
326
+ * `web.api.connect: 'lazy'`; a foreign host may omit it, which reads as
327
+ * "already connected". */
328
+ readonly demand?: (apiName: string) => void;
329
+ /** Passed straight through to the context for loader reads in the browser —
330
+ * see `FrameworkRuntimes.queryOnce`. The web boot supplies `queryOnce`. */
331
+ readonly queryOnce?: QueryOnce;
332
+ }
333
+
334
+ /**
335
+ * A process-wide singleton React context, pinned on the global symbol registry.
336
+ *
337
+ * WHY this exists: the SSG prerender (`voltro build`) loads the framework
338
+ * through TWO separate module instances — the renderer comes in via Vite's
339
+ * `ssrLoadModule('@voltro/web/ssr')` (Vite-transformed) while a page's own
340
+ * framework import is externalised to Node — so a plain `createContext()`
341
+ * in a shared module is evaluated twice and yields two DISTINCT context
342
+ * objects. The `<Router>` provider then holds one while the page's
343
+ * `useLocation()` reads the other, which throws "Router hooks must be used
344
+ * inside <Router>." The same duplicate-instance hazard shows up wherever a
345
+ * deployment ends up with two copies of a package (the classic dual-package
346
+ * hazard, monorepo hoisting quirks, separate SSR vs client bundles).
347
+ *
348
+ * Resolving every context through `Symbol.for(...)` on `globalThis` makes all
349
+ * module copies share ONE instance, so provider and consumer can never diverge.
350
+ * A duplicated copy of THIS helper is harmless — both copies hit the same
351
+ * global registry entry.
352
+ *
353
+ * Lives in @voltro/client (the lowest React-carrying package) so both
354
+ * @voltro/web and @voltro/ui reach it without a cycle; the key prefix keeps
355
+ * its historical spelling on purpose — a mixed dist/src world must resolve
356
+ * to the same registry entries.
357
+ */
358
+ export declare const globalContext: <T>(key: string, initial: T) => Context<T>;
359
+
360
+ /**
361
+ * Install the platform adapter. Call it once, before the first render — on
362
+ * React Native after the persistence adapter has hydrated, because this also
363
+ * installs the adapter's `storage` as the persisted-store backing.
364
+ */
365
+ export declare const installPlatform: (adapter: PlatformAdapter) => void;
366
+
367
+ /** Is an adapter installed (as opposed to the lazy browser default)? */
368
+ export declare const isPlatformInstalled: () => boolean;
369
+
370
+ /** Foreground/background transitions — `AppState` on React Native,
371
+ * `visibilitychange` in a browser, window focus in a desktop shell. */
372
+ declare interface LifecycleSource {
373
+ readonly read: () => LifecycleState;
374
+ readonly subscribe: (onChange: (state: LifecycleState) => void) => () => void;
375
+ }
376
+
377
+ declare type LifecycleState = 'active' | 'inactive' | 'background';
378
+
379
+ declare interface MutationReplayReservation {
380
+ /** Re-check immediately before sending: identity, capability and transport may have changed while waiting. */
381
+ readonly isValid: () => boolean;
382
+ /** Release the bounded pending slot. Safe to call more than once. */
383
+ readonly release: () => void;
384
+ }
385
+
386
+ declare type NotificationPermission_2 = 'granted' | 'denied' | 'prompt';
387
+
388
+ declare interface NotificationSurface {
389
+ readonly permission: () => Promise<NotificationPermission_2>;
390
+ readonly requestPermission: () => Promise<NotificationPermission_2>;
391
+ /** The push token/subscription to register with the server — present only
392
+ * where the shell has a push channel (Expo push token, Web Push). */
393
+ readonly pushToken?: () => Promise<string | null>;
394
+ /** Show a local/system notification — present where the shell can. */
395
+ readonly show?: (notification: {
396
+ readonly title: string;
397
+ readonly body?: string;
398
+ readonly data?: Readonly<Record<string, unknown>>;
399
+ }) => Promise<void>;
400
+ }
401
+
402
+ /** A reachability signal: a synchronous read plus change notifications. */
403
+ declare interface OnlineSource {
404
+ readonly read: () => boolean;
405
+ readonly subscribe: (onChange: (online: boolean) => void) => () => void;
406
+ }
407
+
408
+ declare interface OptimisticPatch<T = unknown> {
409
+ readonly id: string;
410
+ readonly mutationId: string;
411
+ readonly reducer: (current: T) => T;
412
+ /** A successful write stays previewed until a matching post-ACK primary
413
+ * snapshot supersedes it. A different write's delta proves nothing. */
414
+ confirmed?: boolean;
415
+ /** Only framework-owned reducers with an unchanged input can reuse a prefix. */
416
+ readonly canReuse?: (() => boolean) | undefined;
417
+ }
418
+
419
+ declare interface PlatformAdapter {
420
+ readonly platform: PlatformInfo;
421
+ readonly capabilities: PlatformCapabilities;
422
+ /** The WebSocket the api runtime opens — `buildApiRuntime`'s constructor. */
423
+ readonly webSocket: (url: string, options?: Socket.WebSocketConstructorOptions) => WebSocket;
424
+ /** Backing store for `defineStore({ persist })`; installed via `setStoreStorage`. */
425
+ readonly storage: StoreStorageProvider;
426
+ readonly secureStorage: TokenStore;
427
+ readonly online: OnlineSource;
428
+ readonly lifecycle: LifecycleSource;
429
+ readonly links: DeepLinkSource;
430
+ readonly notifications?: NotificationSurface;
431
+ readonly updates?: UpdateChannel;
432
+ readonly biometrics?: BiometricSource;
433
+ readonly clock: {
434
+ readonly now: () => number;
435
+ };
436
+ /** Shell-specific surfaces, keyed by shell (`tauri`, `electron`, `expo`).
437
+ * See `useShellExtension`. */
438
+ readonly extensions?: Readonly<Record<string, unknown>>;
439
+ }
440
+
441
+ /** The adapter minus what `definePlatform` derives. */
442
+ declare type PlatformAdapterInput = Omit<PlatformAdapter, 'capabilities'> & {
443
+ readonly capabilities?: Partial<PlatformCapabilities>;
444
+ };
445
+
446
+ /** What the running shell can do. Derived from the ports an adapter fills in
447
+ * (`capabilitiesOf`); an adapter may narrow a derived `true` it cannot honour. */
448
+ declare interface PlatformCapabilities {
449
+ readonly offlineStart: boolean;
450
+ readonly secureTokenStorage: boolean;
451
+ readonly push: boolean;
452
+ readonly localNotifications: boolean;
453
+ readonly updates: boolean;
454
+ readonly deepLinks: boolean;
455
+ readonly biometrics: boolean;
456
+ readonly backgroundSync: boolean;
457
+ readonly installPrompt: boolean;
458
+ }
459
+
460
+ declare interface PlatformInfo {
461
+ readonly kind: PlatformKind;
462
+ readonly shell: ShellKind;
463
+ /** True when running as an installed app (a PWA in standalone mode, any
464
+ * native shell); false in a browser tab. */
465
+ readonly installed: boolean;
466
+ /** The app's own version, where the shell knows it (a store build, a
467
+ * desktop release). Undefined in a browser tab. */
468
+ readonly appVersion?: string;
469
+ /** The build the running code came from — what an update feed compares. */
470
+ readonly buildId?: string;
471
+ }
472
+
473
+ declare type PlatformKind = 'web' | 'pwa' | 'ios' | 'android' | 'macos' | 'windows' | 'linux' | 'unknown';
474
+
475
+ /** One preloaded subscription snapshot, as it travels in the hydration payload. */
476
+ declare interface PreloadSeed {
477
+ /** The api mount name the subscription reads from (first arg of `useSubscription`). */
478
+ readonly api: string;
479
+ /** `stableKey([rpcTag, input])` — identical to the SubscriptionCache's own key,
480
+ * so the seed and the live subscription address the same entry. */
481
+ readonly key: string;
482
+ /** The server-fetched snapshot value. `undefined` when `failed`. */
483
+ readonly value: unknown;
484
+ /**
485
+ * The server ATTEMPTED this preload and it failed.
486
+ *
487
+ * Reported from a real deployment whose SSR seeds all failed at once (an expired
488
+ * session token — the api answered every preload with a scope error): the
489
+ * page rendered a skeleton title and an empty table, and the ONLY record of
490
+ * it was a `preload seed failed` WARN in the server log. The client could not
491
+ * tell that state from "this page declares no preload", because both arrive
492
+ * as the absence of a seed. So an app cannot distinguish "still loading" from
493
+ * "actually empty" without inventing its own convention — which the reporting
494
+ * consumer then did, page by page.
495
+ *
496
+ * NOTHING about the cause travels. A boolean is the whole contract: the
497
+ * server's failure text is for the server's log, and a reason string here
498
+ * would be an error message from a refused call rendered into a browser.
499
+ */
500
+ readonly failed?: true;
501
+ }
502
+
503
+ /** `queryOnce`'s shape, declared here so this module stays free of it. */
504
+ declare type QueryOnce = (handleRef: {
505
+ readonly current: {
506
+ readonly runtime: unknown;
507
+ readonly client: unknown;
508
+ };
509
+ }, apiName: string, tag: string, input: Record<string, unknown> | undefined, signal?: AbortSignal) => Promise<unknown>;
510
+
511
+ declare type RawTransportStatus = 'connected' | 'disconnected';
512
+
513
+ /**
514
+ * State owned by one logical API, not by one socket or one React hook.
515
+ *
516
+ * Raw listeners (`RpcErrorBus.on`) still receive every failure immediately.
517
+ * Presentation listeners receive non-transport failures immediately, but at
518
+ * most one transport failure per outage and only after the grace window. A
519
+ * fully healed gap therefore leaves no toast/banner flash while diagnostics
520
+ * retain the complete sequence.
521
+ */
522
+ declare class RecoveryCoordinator {
523
+ #private;
524
+ constructor(apiName: string, options?: RecoveryOptions, scheduler?: Partial<RecoveryScheduler>);
525
+ get options(): ResolvedRecoveryOptions;
526
+ /** Ends on login/logout, tenant change or API disposal, not ordinary reconnect. */
527
+ get subjectSignal(): AbortSignal;
528
+ /** Hydration values belong to the initial subject only. Once identity may
529
+ * have changed, a later generation/remount must obtain its own snapshot.
530
+ * Ordinary transport recovery does not cross this boundary. */
531
+ getPreloadSeedPermission: () => boolean;
532
+ /** A whole-cache resnapshot can follow same-socket re-authentication. Its
533
+ * replacement reads must not reuse the original server-rendered values. */
534
+ invalidatePreloadSeeds(): void;
535
+ getSnapshot: () => RecoverySnapshot;
536
+ /** The SSR / hydration snapshot — see INITIAL_RECOVERY_SNAPSHOT. Stable by
537
+ * reference, so both renders agree and React swaps to the live one after. */
538
+ getServerSnapshot: () => RecoverySnapshot;
539
+ subscribe: (listener: () => void) => (() => void);
540
+ onVisibleError(listener: RpcErrorListener): () => void;
541
+ /** Called from the socket seam before request fibers report their errors. */
542
+ transportIssue(): void;
543
+ /** Called only after the rpc protocol has cleared its previous transport error. */
544
+ protocolReady(): void;
545
+ observeError(error: RpcError): void;
546
+ observeSuccess(success: RpcSuccess): void;
547
+ reportExternalSuccess(): void;
548
+ /** Discard every stale row/replay/health fact at the subject boundary. */
549
+ resetForSubjectChange(minimumCapabilityGeneration?: number): void;
550
+ setMutationReplaySupported(supported: boolean, generation?: number): void;
551
+ /**
552
+ * Wait for the capability probe when transport fails during initial boot.
553
+ * Unknown is never permission: the wait is bounded by the replay window and
554
+ * resolves false if the server never proves that idempotency is active.
555
+ */
556
+ /** What is left of the replay window for a mutation that started at `startedAt`. */
557
+ replayWindowRemaining(startedAt: number): number;
558
+ waitForMutationReplaySupport(startedAt: number): Promise<boolean>;
559
+ /**
560
+ * Reserve one bounded waiting/replay slot; caller MUST release the returned
561
+ * reservation. An unknown capability may reserve while its probe is in flight,
562
+ * otherwise that short boot window would permit an unbounded waiter set.
563
+ * Disabled is final for the current generation and refuses immediately.
564
+ */
565
+ reserveMutationReplay(startedAt: number): MutationReplayReservation | undefined;
566
+ waitForProtocolReady(startedAt: number, signal?: AbortSignal): Promise<boolean>;
567
+ dispose(): void;
568
+ }
569
+
570
+ declare interface RecoveryOptions {
571
+ /** Hide a transport gap from the UI while recovery is still plausible. */
572
+ readonly graceMs?: number;
573
+ /** Socket reconnect timing, independent of the presentation grace window. */
574
+ readonly retry?: RecoveryRetryOptions;
575
+ /** Maximum mutations allowed to wait for one safe replay at once. */
576
+ readonly maxPendingMutations?: number;
577
+ /** Maximum age of a mutation before an automatic replay is refused. */
578
+ readonly replayWindowMs?: number;
579
+ /**
580
+ * Explicit HTTP endpoint for runtime capability discovery. Usually omitted:
581
+ * the client derives a sibling of the WebSocket path. Set this only when an
582
+ * edge routes the WebSocket and ordinary HTTP through unrelated paths.
583
+ */
584
+ readonly capabilitiesUrl?: string;
585
+ }
586
+
587
+ declare type RecoveryPresentationStatus = 'connected' | 'recovering' | 'degraded';
588
+
589
+ /** Delays after failed socket attempts; the first connection is always immediate. */
590
+ declare interface RecoveryRetryOptions {
591
+ /** First retry delay in ms (default 0). Clamped to 0–maxMs. */
592
+ readonly initialMs?: number;
593
+ /** Second retry delay in ms (default 500). Clamped to 50–maxMs. */
594
+ readonly thenMs?: number;
595
+ /** Multiplier after the second retry (default 1.5). Clamped to 1–10. */
596
+ readonly factor?: number;
597
+ /** Maximum retry delay in ms (default 5000). Clamped to 50–60000. */
598
+ readonly maxMs?: number;
599
+ }
600
+
601
+ declare interface RecoveryScheduler {
602
+ readonly now: () => number;
603
+ readonly setTimeout: (callback: () => void, ms: number) => unknown;
604
+ readonly clearTimeout: (handle: unknown) => void;
605
+ }
606
+
607
+ declare interface RecoverySnapshot {
608
+ readonly rawTransport: RawTransportStatus;
609
+ readonly status: RecoveryPresentationStatus;
610
+ readonly failureCount: number;
611
+ readonly lastFailureAt: number | undefined;
612
+ readonly failedSubscriptions: ReadonlyArray<string>;
613
+ readonly pendingMutationReplays: number;
614
+ readonly mutationReplay: 'unknown' | 'enabled' | 'disabled';
615
+ }
616
+
617
+ declare interface ResolvedRecoveryOptions {
618
+ readonly graceMs: number;
619
+ readonly retry: Required<RecoveryRetryOptions>;
620
+ readonly maxPendingMutations: number;
621
+ readonly replayWindowMs: number;
622
+ readonly capabilitiesUrl: string | undefined;
623
+ }
624
+
625
+ /** What the client can prove about a unary call's server-side result. */
626
+ declare type RpcCallOutcome = 'not-applicable' | 'not-started' | 'known' | 'unknown';
627
+
628
+ declare interface RpcError {
629
+ /** Source — `'mutation'` for transactional unary calls, `'action'` for
630
+ * non-transactional unary calls, `'subscription'` for streams. */
631
+ readonly source: 'mutation' | 'action' | 'subscription';
632
+ /** RPC tag (e.g. `'orgs.create'`, `'projects.list'`). */
633
+ readonly tag: string;
634
+ /** The raw error value. May be a Schema.TaggedError instance, a plain
635
+ * Error, an unknown thrown value. Pattern-match on `_tag` for typed errors. */
636
+ readonly error: unknown;
637
+ /** Failure origin. Use `transport` for connection-level UX; `handler` means
638
+ * the rpc returned a declared failure; `client` is framework work that
639
+ * failed locally; `unknown` is deliberately unclassified. */
640
+ readonly kind: RpcErrorKind;
641
+ /** False when the native caller proves this transport failure belongs to an
642
+ * ended physical attempt. The call still failed (and may have committed),
643
+ * but it must not mark the replacement socket down. Omitted preserves the
644
+ * conservative fallback for emitters without native lifetime evidence. */
645
+ readonly affectsTransport?: boolean;
646
+ /** A transport failure after a unary request started is `unknown`: the
647
+ * server may have committed before the response disappeared. */
648
+ readonly outcome?: RpcCallOutcome;
649
+ /** Trace id of the CLIENT call span. When the server accepted the request,
650
+ * effect/rpc propagates this same id into its span. A transport failure may
651
+ * happen before that, so the id is not proof that server logs exist. Present
652
+ * only when a client span was active. */
653
+ readonly traceId?: string;
654
+ }
655
+
656
+ declare class RpcErrorBus {
657
+ #private;
658
+ /** Subscribe. Returns an unsubscribe function. */
659
+ on(listener: RpcErrorListener): () => void;
660
+ /** Emit. Pipeline code (useMutation / subscriptionCache) calls this. */
661
+ emit(event: RpcError): void;
662
+ /**
663
+ * Subscribe to SUCCESSES — the channel that makes a consecutive-failure
664
+ * ceiling mean what it says.
665
+ *
666
+ * ── Why the bus grew a second channel ──────────────────────────────────
667
+ *
668
+ * `wireAuthRefresh` bounds how often it may rebuild the transport on
669
+ * `Unauthenticated`, and `maxConsecutive` bounds the TOTAL — after that many
670
+ * refreshes *with no successful call in between*, it stops and leaves the
671
+ * error to the app, because at that point the credential is not stale, it is
672
+ * refused. "With no successful call in between" was carried by
673
+ * `AuthRefreshHandle.noteSuccess()`, a method the HOST had to remember to
674
+ * call, and the only host never called it.
675
+ *
676
+ * What that turns the ceiling into is the part worth writing down: not a
677
+ * loop, but a LIFETIME budget. A tab that rotates its token three times over
678
+ * a few hours exhausts it and then never refreshes again for as long as it
679
+ * stays open — every later expiry rejects every subscription it opens, each
680
+ * rejected entry is terminal for its transport, and the screen waits on a
681
+ * spinner that has nothing left to wait for.
682
+ *
683
+ * A host that must remember something will eventually not, which is the
684
+ * shape this repo keeps meeting. So the signal comes from the pipeline that
685
+ * already knows — the same one that emits the errors — and no host has to
686
+ * wire anything. `noteSuccess()` stays for a host with a better signal of its
687
+ * own; it is no longer what the policy depends on.
688
+ */
689
+ onSuccess(listener: RpcSuccessListener): () => void;
690
+ /** Emit a success. Called by the same pipeline code that calls `emit`. */
691
+ emitSuccess(event: RpcSuccess): void;
692
+ }
693
+
694
+ /** Where the failure originated, classified only as far as the client can
695
+ * prove. In particular, `transport` does NOT mean the server definitely saw
696
+ * nothing: a connection can disappear after a request was accepted but before
697
+ * its response reached the browser. */
698
+ declare type RpcErrorKind = 'transport' | 'handler' | 'client' | 'unknown';
699
+
700
+ declare type RpcErrorListener = (event: RpcError) => void;
701
+
702
+ /** A call that SUCCEEDED. Carries only its source and tag — there is no payload
703
+ * here on purpose: this channel exists so cross-cutting policy can tell
704
+ * "working again" from "still broken", not so listeners can read data. */
705
+ declare interface RpcSuccess {
706
+ readonly source: 'mutation' | 'action' | 'subscription';
707
+ readonly tag: string;
708
+ }
709
+
710
+ declare type RpcSuccessListener = (event: RpcSuccess) => void;
711
+
712
+ declare interface ServerRequestContextValue {
713
+ readonly cookies: Readonly<Record<string, string>>;
714
+ readonly headers: Readonly<Record<string, string>>;
715
+ /** Raw request URL as it came off the wire (path + query). Useful
716
+ * for SSR pages that need to read `?q=…` style search params
717
+ * without touching anything client-only. Empty string for build-
718
+ * time SSG renders where there is no incoming request. */
719
+ readonly url: string;
720
+ /** Present ONLY on the 422 re-render of a failed no-JS form POST:
721
+ * the submitted values + field errors, keyed by formKey. Travels on
722
+ * the EXISTING request context deliberately — a dedicated provider
723
+ * would add a fiber fork the client boot does not have, and every
724
+ * ancestor arity difference shifts every useId in the app. */
725
+ readonly formFlash?: FormFlashPayload;
726
+ /** Public captured build/class selection, never a credential or write permit. */
727
+ readonly formSource?: string;
728
+ }
729
+
730
+ declare type ShellKind = 'browser' | 'expo' | 'tauri' | 'electron' | 'node' | 'test';
731
+
732
+ /** One seeded value, as it travels in the hydration payload. */
733
+ declare interface StoreSeed {
734
+ readonly store: string;
735
+ readonly key?: string;
736
+ readonly value: unknown;
737
+ }
738
+
739
+ /** The synchronous subset of the DOM `Storage` interface a persisted store
740
+ * needs. `removeItem` is optional — nothing in the store layer clears keys. */
741
+ declare interface StoreStorage {
742
+ readonly getItem: (key: string) => string | null;
743
+ readonly setItem: (key: string, value: string) => void;
744
+ readonly removeItem?: (key: string) => void;
745
+ }
746
+
747
+ /** Which area a store asked for. Platforms without a session/local split map
748
+ * both onto one backing store; that is expected, not a downgrade. */
749
+ declare type StoreStorageArea = 'local' | 'session';
750
+
751
+ /** A backing store provider: given the requested area, return the storage to
752
+ * use, or `null` for "there is none here" (the store then does not persist). */
753
+ declare type StoreStorageProvider = (area: StoreStorageArea) => StoreStorage | null;
754
+
755
+ declare class SubscriptionCache {
756
+ private readonly entries;
757
+ private readonly entriesByTable;
758
+ private readonly entriesByTag;
759
+ private readonly entriesByMutation;
760
+ private readonly patchMemberships;
761
+ private readonly entryOrder;
762
+ private orderedMemberships;
763
+ private nextEntryOrder;
764
+ /** Standing optimistic intents, by mutation id — see `autoApply`. */
765
+ private readonly intents;
766
+ private readonly tableRows;
767
+ private readonly anyListeners;
768
+ private readonly tableListeners;
769
+ private readonly refreshing;
770
+ /**
771
+ * Same-subject runtime replacement. A mutation may settle against the cache
772
+ * it started on after React has already switched to the replacement cache.
773
+ * Keep this link one-way so staging and settlement follow the visible data
774
+ * without retaining an old cache from the new runtime.
775
+ */
776
+ private successor;
777
+ private readonly inactiveTtlMs;
778
+ private readonly onChangeHook;
779
+ private readonly errorBus;
780
+ private readonly mirror;
781
+ private readonly mergeCell;
782
+ private readonly apiName;
783
+ private readonly recoveryStuckMs;
784
+ constructor(options?: SubscriptionCacheOptions);
785
+ private diagnose;
786
+ /**
787
+ * Register a subscriber. The cache forks the underlying fiber on the
788
+ * first subscriber and re-uses it for the rest. Returns the snapshot
789
+ * getter, the per-subscriber notify-on-change hook, and an unsubscribe
790
+ * function.
791
+ *
792
+ * `fetch` is invoked once per live stream attempt (it builds the Effect
793
+ * Stream against the runtime). Concurrent subscribers piggy-back on that
794
+ * stream; a transport recovery may invoke it again to replace the terminal
795
+ * fiber left by the failed socket.
796
+ */
797
+ subscribe(keyArr: ReadonlyArray<unknown>, fetch: () => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>, runtime: AnyRuntime, onChange: () => void, options?: {
798
+ readonly source?: string | ReadonlyArray<string>;
799
+ }): {
800
+ readonly getSnapshot: () => CacheSnapshot<unknown>;
801
+ readonly unsubscribe: () => void;
802
+ };
803
+ /**
804
+ * Stage an optimistic patch against `keyArr`. Subscribers see the
805
+ * patched value on the next snapshot read. Returns a handle for manual
806
+ * revert (the canonical revert is via `revertByMutation` once the
807
+ * mutation resolves).
808
+ *
809
+ * If the entry doesn't exist yet (mutation fires before its
810
+ * subscription mounts — uncommon but possible), we create a stub entry
811
+ * with no fiber. When a subscription later mounts for the same key,
812
+ * the patch is preserved and the fiber is forked normally.
813
+ */
814
+ update<T>(keyArr: ReadonlyArray<unknown>, reducer: (current: T) => T, mutationId: string): {
815
+ readonly revert: () => void;
816
+ readonly patchId: string;
817
+ };
818
+ /**
819
+ * Patch every cached entry whose rpc tag matches `tag`, regardless of
820
+ * the input the subscription was opened with. The escape hatch for
821
+ * sourceless queries — joins, aggregates, custom-projection routes —
822
+ * that the auto-optimistic source-router can't reach.
823
+ *
824
+ * Usage from `.withOptimistic`:
825
+ *
826
+ * create.withOptimistic((cache, input) => {
827
+ * cache.forTag('todos.summary', (current) => ({
828
+ * ...(current as { count: number }),
829
+ * count: (current as { count: number }).count + 1,
830
+ * }))
831
+ * })
832
+ *
833
+ * Returns the number of entries that were patched, so callers can warn
834
+ * if zero entries matched (probably means the tag is misspelt).
835
+ */
836
+ forTag<T>(tag: string, reducer: (current: T) => T, mutationId: string): {
837
+ readonly patchedCount: number;
838
+ };
839
+ /** Drop every patch owned by `mutationId` from EVERY entry. */
840
+ revertByMutation(mutationId: string): void;
841
+ /**
842
+ * Mark a SUCCEEDED mutation's optimistic patches as confirmed. Unlike
843
+ * `revertByMutation` (used on failure), this does NOT drop them — they stay
844
+ * visible until a matching post-ACK primary snapshot replaces `base`.
845
+ * This removes the on→off→on flash where dropping the patch on mutation
846
+ * resolve briefly exposes a stale base before the server delta lands.
847
+ */
848
+ confirmByMutation(mutationId: string): void;
849
+ /**
850
+ * The confirmed-patch window expired: a committed write never got its
851
+ * superseding server event. Re-issue the affected subscriptions instead of
852
+ * discarding the write's preview.
853
+ *
854
+ * Three things are load-bearing, and each was a way to reintroduce the bug:
855
+ *
856
+ * - **The patch is KEPT across the resync.** `refreshAll` already
857
+ * establishes that shape ("the new base snapshot will land on top of
858
+ * them"). Clearing it here would be the revert again, wearing a longer
859
+ * word.
860
+ * - **A stub entry — no `fetch`, no `runtime` — is left ALONE.** There is
861
+ * nothing to re-issue, and the only other option is to show a base the
862
+ * client knows is stale. Keeping the patch is the honest state.
863
+ * - **It is LOUD.** The reporter found the jump only by reading minified
864
+ * source, because in the UI it is indistinguishable from "the server did
865
+ * not save it" — and that is the false trail they followed first. This
866
+ * goes to the error bus, so it reaches `voltro logs` rather than only a
867
+ * console nobody has open.
868
+ *
869
+ * No second timer is armed: this runs once per mutation, from the one
870
+ * `confirmByMutation` scheduled it, so a server that never echoes cannot put
871
+ * the client into a resync loop.
872
+ */
873
+ private resyncUnechoedMutation;
874
+ /**
875
+ * Auto-derive optimistic patches from a mutation's declared target(s).
876
+ * Iterates every cache entry whose `source` table matches a target's
877
+ * table; applies the canonical patch for the op:
878
+ *
879
+ * - insert : prepend (or append) a row derived from input + an
880
+ * `optimistic: true` flag + a generated id.
881
+ * - update : replace the row whose id matches `input.id` (or the
882
+ * custom identify fn from the spec) by merging input
883
+ * fields on top of the current row.
884
+ * - delete : filter out the row whose id matches `input.id`.
885
+ *
886
+ * Specs with a custom `shape`/`identify`/`order` function override
887
+ * these defaults. All patches are tagged with `mutationId` for atomic
888
+ * revert.
889
+ */
890
+ autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string, options?: {
891
+ readonly standing?: boolean;
892
+ }): void;
893
+ /** Whether a standing intent for `mutationId` is still held (see
894
+ * {@link SubscriptionCache.autoApply}). Carried to a same-subject
895
+ * replacement cache, so a stager can tell "already staged" from "new". */
896
+ hasIntent(mutationId: string): boolean;
897
+ private applyIntent;
898
+ private applyStandingIntents;
899
+ /** Drop a specific patch by id. */
900
+ private revertPatch;
901
+ /**
902
+ * Read the current snapshot for a key WITHOUT subscribing. If the
903
+ * entry doesn't exist, returns the "empty" snapshot (data=undefined,
904
+ * revision=-1, no patches). Safe to call from `useSyncExternalStore`'s
905
+ * getSnapshot, which is invoked many times during a single render.
906
+ */
907
+ peek(keyArr: ReadonlyArray<unknown>): CacheSnapshot<unknown>;
908
+ /** Test / debug helper. */
909
+ getEntry(keyArr: ReadonlyArray<unknown>): CacheEntry | undefined;
910
+ /** Test / debug helper. */
911
+ size(): number;
912
+ /**
913
+ * Devtools introspection: snapshot every cache entry's wire state +
914
+ * metadata. Returns plain data (no live references) so consumers can
915
+ * render without worrying about React state-equality.
916
+ *
917
+ * The map is keyed by the cache's stable-key string (same one the
918
+ * fan-out invalidation uses). Entries appear in insertion order;
919
+ * sort at the call site if order matters.
920
+ */
921
+ peekAll(): ReadonlyArray<CacheEntrySnapshot>;
922
+ /** Tear down every entry (used on runtime dispose). */
923
+ destroy(runtime: AnyRuntime): void;
924
+ /**
925
+ * Re-issue every active subscription against the runtime. Used after
926
+ * a soft re-auth (login on the same WebSocket connection) so the
927
+ * server resolves the new subject for each subscription's tenant
928
+ * scope — without dropping the connection.
929
+ *
930
+ * For each entry with a saved fetch:
931
+ * - interrupt the current fiber (stops the old WS subscription)
932
+ * - clear the base state so the next snapshot fully replaces it
933
+ * - re-fork via the saved fetch (new WS subscription with the
934
+ * server's now-current subject for this connection)
935
+ *
936
+ * Subscribers' `onChange` callbacks fire when the new snapshot
937
+ * lands, prompting React to re-render with the post-reauth data.
938
+ *
939
+ * Stub entries (no fetch saved yet) are left alone — they'll
940
+ * promote naturally on their next subscriber.
941
+ */
942
+ refreshAll(runtime: AnyRuntime): void;
943
+ /** Refresh one active query without clearing its visible data or optimistic
944
+ * patches. Coalesce refreshes until that request answers or fails; never
945
+ * interrupt an initial read merely because another refresh was requested. */
946
+ refresh(key: ReadonlyArray<unknown>): boolean;
947
+ /* Excluded from this release type: resumeTransportFailures */
948
+ /**
949
+ * The stall watchdog for one re-issued entry: `recoveryStuckMs` after the
950
+ * re-issue with neither snapshot nor delta, the entry is reported stuck and
951
+ * its subscribers are notified.
952
+ *
953
+ * That is a finding only if the watchdog itself ran on time. A browser
954
+ * throttles timers in a hidden tab — to a one-second grid, then a one-minute
955
+ * grid — so a timer there fires whenever the tab next wakes, and it used to
956
+ * report the interval it was ARMED with as the interval waited. A delivery
957
+ * queued behind the same throttling then arrived a moment after the warning
958
+ * and the invalidation, under the same attempt: the watchdog had measured
959
+ * its own delay and called it a stall.
960
+ *
961
+ * So the watchdog compares its due time with its fire time. Late beyond the
962
+ * tolerance, or firing in a hidden tab, it does not judge: it records ONE
963
+ * `recovery-timer-late` for the attempt (with how late, and whether hidden)
964
+ * and re-arms. The first on-time fire in a visible tab decides — which gives
965
+ * a delivery `recoveryStuckMs` of unthrottled time once the tab is looked at
966
+ * again, and reports a real stall within that.
967
+ */
968
+ private armRecoveryWatchdog;
969
+ /**
970
+ * Re-issue ONE entry's subscription: interrupt the fiber, reset the base,
971
+ * re-fork through the saved `fetch`.
972
+ *
973
+ * Extracted so `refreshAll` and the confirmed-patch resync cannot disagree
974
+ * about it — and the thing they must agree on is that **optimistic patches
975
+ * survive**. For a re-auth they belong to in-flight mutations; for the resync
976
+ * they describe a write the server has already committed. Dropping them here
977
+ * would be a revert with a longer name, which is the defect the resync exists
978
+ * to remove.
979
+ */
980
+ private reissue;
981
+ /**
982
+ * Seed this (fresh) cache with the last-known-good rows held by the cache it
983
+ * REPLACES, so a transport rebuild degrades to STALE DATA rather than to
984
+ * skeletons.
985
+ *
986
+ * A reconnect builds an entirely new client stack — new runtime, new socket,
987
+ * new cache — and the new cache starts empty, so every live `useSubscription`
988
+ * went `data: undefined` → `loading: true` and the whole app blanked until
989
+ * each stream's first snapshot round-tripped. Carrying the previous `base`
990
+ * over is the same trick `initialSnapshot` plays for SSR: render real (if
991
+ * momentarily old) data now, let the first server snapshot replace it.
992
+ *
993
+ * What is carried and what is NOT:
994
+ *
995
+ * - Only entries that actually HOLD server data (`base !== undefined`).
996
+ * A pending or cold-start-failed entry has nothing better than the
997
+ * loading state it is already in.
998
+ * - `baseError` is dropped: the new transport gets to re-establish the
999
+ * truth, and a stale error banner over live data is worse than neither.
1000
+ * - Optimistic patches are carried. A transport failure has an UNKNOWN
1001
+ * unary outcome, not a proven failure, and removing the preview before a
1002
+ * safe replay settles would flash stale data. The old cache links to this
1003
+ * one so later stage/confirm/revert operations reach the visible copy.
1004
+ * - Seeded entries carry no fiber and no fetch, exactly like the stub
1005
+ * entries a pre-mount optimistic patch creates. The first `subscribe()`
1006
+ * promotes one: it saves the fetch and forks the stream, with the seeded
1007
+ * `base` still in place, so the component never sees `undefined`.
1008
+ *
1009
+ * **Caller contract — this must only be used for a SAME-SUBJECT swap.** The
1010
+ * caller (the api supervisor) gates it on the rebuild being transport-driven.
1011
+ * A rebuild that exists to re-resolve WHO the connection is (login, logout,
1012
+ * tenant switch) must NOT seed: the next subject may be entitled to strictly
1013
+ * less, and painting the previous subject's rows into their screens is a data
1014
+ * exposure, not a UX win. That is also why `refreshAll` above clears `base`
1015
+ * outright — same reasoning, same boundary.
1016
+ *
1017
+ * Returns the number of entries seeded (diagnostics / tests).
1018
+ */
1019
+ seedStaleFrom(previous: SubscriptionCache): number;
1020
+ private create;
1021
+ private createStub;
1022
+ private freshState;
1023
+ private startFiber;
1024
+ private sourceTables;
1025
+ private addIndex;
1026
+ private removeIndex;
1027
+ private orderedEntries;
1028
+ private indexSource;
1029
+ private appendPatch;
1030
+ private replacePatches;
1031
+ private indexPatches;
1032
+ private registerEntry;
1033
+ private unindexEntry;
1034
+ private invalidate;
1035
+ /**
1036
+ * Every row of `table` this cache holds — the client's local replica of the
1037
+ * table: the union of the rows of every entry sourced on that table ALONE
1038
+ * (an entry over several tables holds joined shapes, not rows of one),
1039
+ * optimistic previews and mirror-seeded rows included, deduplicated by `id`.
1040
+ * Memoised per table until the next change, so the result is reference-stable
1041
+ * for `useSyncExternalStore`.
1042
+ */
1043
+ rowsOf(table: string): ReadonlyArray<Readonly<Record<string, unknown>>>;
1044
+ /** Subscribe to cache changes affecting this source table only. */
1045
+ subscribeTable(table: string, listener: () => void): () => void;
1046
+ /** Call `listener` after any entry changed. Returns the unsubscribe. */
1047
+ subscribeAny(listener: () => void): () => void;
1048
+ private getSnapshot;
1049
+ private unsubscribe;
1050
+ /** Start (or restart) the inactive-TTL countdown for `entry`: unless
1051
+ * something subscribes first, interrupt its fiber and drop it. Shared by
1052
+ * the last-subscriber-out path and by `seedStaleFrom`'s unclaimed seeds. */
1053
+ private scheduleEviction;
1054
+ }
1055
+
1056
+ declare interface SubscriptionCacheOptions {
1057
+ /** Durable local mirror (see {@link SubscriptionMirror}). */
1058
+ readonly mirror?: SubscriptionMirror;
1059
+ /**
1060
+ * CRDT cell merger for the downstream lane (plan 18): folds a
1061
+ * `mergeCells` delta op's incremental update into the held cell. The one
1062
+ * real implementation is `crdtMergeCell` from `@voltro/local-first` (this
1063
+ * package stays CRDT-library-free). Absent → the merger registered with
1064
+ * `registerCellMerger` (`@voltro/local-first` registers `crdtMergeCell` on
1065
+ * import); with none at all, a mergeCells op replaces the cell.
1066
+ */
1067
+ readonly mergeCell?: (column: string, prevValue: unknown, update: unknown) => unknown;
1068
+ /** Milliseconds to keep an entry alive after the last subscriber leaves.
1069
+ * Lets back-button / quick remount reuse the warm subscription. */
1070
+ readonly inactiveTtlMs?: number;
1071
+ /** Debug hook fired on every cache state change. */
1072
+ readonly onChange?: (key: string) => void;
1073
+ /** Optional error bus — when a subscription stream errors out, the
1074
+ * cache reports it to the bus so global listeners (e.g. auto-logout
1075
+ * on Unauthenticated) can react. */
1076
+ readonly errorBus?: RpcErrorBus;
1077
+ /** Logical api name for payload-free diagnostics. Omit for standalone caches. */
1078
+ readonly apiName?: string;
1079
+ /** Time after a transport reissue with no delivery before one stuck event. */
1080
+ readonly recoveryStuckMs?: number;
1081
+ }
1082
+
1083
+ /**
1084
+ * Durable local mirror seam (plan 02 — local-first). `save` fires after every
1085
+ * server event that moved an entry's base (snapshot or delta) with the rows
1086
+ * AND the revision; `load` runs once for a COLD entry (no server data yet)
1087
+ * and, when it resolves first, seeds the entry so the UI renders mirrored
1088
+ * rows offline — and the NEXT (re)subscribe presents the mirrored revision as
1089
+ * `voltro-resume-from`, composing with delta-resume. The implementation
1090
+ * (`@voltro/local-first`'s query mirror) owns partitioning, encrypted-column
1091
+ * stripping and which tags mirror at all — the cache calls it for every
1092
+ * entry and a foreign tag is the mirror's no-op.
1093
+ */
1094
+ declare interface SubscriptionMirror {
1095
+ readonly load: (key: string) => Promise<{
1096
+ readonly data: unknown;
1097
+ readonly revision: number;
1098
+ } | undefined>;
1099
+ readonly save: (key: string, snap: {
1100
+ readonly tag: string | undefined;
1101
+ readonly data: unknown;
1102
+ readonly revision: number;
1103
+ }) => Promise<void>;
1104
+ /**
1105
+ * Queries to keep subscribed for the whole connection generation, as
1106
+ * `[tag, input]` — so they are mirrored, and readable offline, before any
1107
+ * screen ever opened them. Offline coverage is otherwise "what the user
1108
+ * happened to visit"; this makes it a declaration.
1109
+ */
1110
+ readonly warm?: ReadonlyArray<readonly [tag: string, input: Readonly<Record<string, unknown>>]>;
1111
+ /**
1112
+ * Tags to keep warm with an EMPTY input — each one whose declared input
1113
+ * schema accepts `{}` (a list, a feed, a settings read). The runtime makes
1114
+ * that check against the descriptors; a tag that needs parameters is left
1115
+ * out rather than subscribed into an error.
1116
+ */
1117
+ readonly warmTags?: ReadonlyArray<string>;
1118
+ }
1119
+
1120
+ /**
1121
+ * Where a credential lives. `kind` says how it is protected; a store that
1122
+ * cannot protect anything says so (`'none'`) and refuses to write, rather
1123
+ * than falling back to plain storage — a session token in a key-value store
1124
+ * is the defect this port exists to make impossible.
1125
+ */
1126
+ declare interface TokenStore {
1127
+ readonly kind: 'keychain' | 'keystore' | 'credential-manager' | 'stronghold' | 'memory' | 'none';
1128
+ readonly get: (key: string) => Promise<string | null>;
1129
+ readonly set: (key: string, value: string) => Promise<void>;
1130
+ readonly delete: (key: string) => Promise<void>;
1131
+ }
1132
+
1133
+ /** How the running code gets replaced: a service worker, a desktop updater,
1134
+ * an OTA bundle. `apply` is the restart/reload; callers gate it on an empty
1135
+ * outbox. */
1136
+ export declare interface UpdateChannel {
1137
+ readonly check: () => Promise<UpdateInfo | null>;
1138
+ readonly apply: () => Promise<void>;
1139
+ readonly subscribe?: (onAvailable: (update: UpdateInfo) => void) => () => void;
1140
+ }
1141
+
1142
+ export declare interface UpdateInfo {
1143
+ readonly version: string;
1144
+ readonly notes?: string;
1145
+ }
1146
+
1147
+ /** The running platform: info, capabilities and ports. Re-renders when an
1148
+ * adapter is installed after mount. */
1149
+ export declare const usePlatform: () => PlatformAdapter;
1150
+
1151
+ export declare const useServerRequest: () => ServerRequestContextValue | null;
1152
+
1153
+ export { }