@voltro/client 0.83.1 → 0.84.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.
package/dist/runtime.d.ts CHANGED
@@ -19,6 +19,22 @@ import { TargetRelations } from '@voltro/protocol';
19
19
  * React context (and its browser globals) merely to name this Effect type. */
20
20
  export declare type AnyRuntime = ManagedRuntime.ManagedRuntime<never, never>;
21
21
 
22
+ /** The registry's read side, as other packages see it through the slot. */
23
+ export declare interface ApiConnectivity {
24
+ /**
25
+ * Is the transport up? With a name: that api's. Without: any mounted api's
26
+ * — the right default for a writer that does not say which api it talks to,
27
+ * because answering "down" while its own api is up would hold its queue
28
+ * shut. `undefined` when no api (of that name) is mounted: nothing is known.
29
+ */
30
+ readonly online: (apiName?: string) => boolean | undefined;
31
+ /** Called on every transport change of any api. Returns the unsubscribe. */
32
+ readonly subscribe: (listener: () => void) => () => void;
33
+ }
34
+
35
+ /** The read side — what `useApiOnline` and other packages consume. */
36
+ export declare const apiConnectivity: () => ApiConnectivity;
37
+
22
38
  export declare interface ApiHandle {
23
39
  readonly runtime: AnyRuntime;
24
40
  readonly cache: SubscriptionCache;
@@ -167,6 +183,16 @@ export declare interface BuildApiRuntimeOptions {
167
183
  * its concern.
168
184
  */
169
185
  readonly surfaceAudience?: 'client' | 'service';
186
+ /**
187
+ * Durable local mirror for this generation's subscription cache — the
188
+ * offline read half of local-first. Resolved once here, before the cache
189
+ * exists; see {@link SubscriptionMirrorSource} for why it is never swapped
190
+ * under a live cache.
191
+ */
192
+ readonly mirror?: SubscriptionMirrorSource | undefined;
193
+ /** The api's rpc descriptors. Handed to the mirror source, and each warm
194
+ * query's `source` routes queued writes' previews onto it. */
195
+ readonly descriptors?: Readonly<Record<string, ClientDescriptor>> | undefined;
170
196
  }
171
197
 
172
198
  export declare type BuildClient = (api: MountedApi, generation: number, onSocketOpen: () => void, onSocketIssue: (kind: SocketIssueKind) => void,
@@ -312,7 +338,7 @@ export declare interface ClientDiagnosticEvent {
312
338
  readonly fields: Readonly<Record<string, ClientDiagnosticValue>>;
313
339
  }
314
340
 
315
- export declare type ClientDiagnosticKind = 'runtime.build-started' | 'runtime.resolved' | 'runtime.failed' | 'runtime.capabilities' | 'runtime.surface-mismatch' | 'runtime.swapped' | 'runtime.disposed' | 'socket.created' | 'socket.raw-open' | 'socket.close' | 'socket.error' | 'socket.connect-timeout' | 'socket.retry-scheduled' | 'socket.frames' | 'protocol.ready' | 'subscription.transport-failed' | 'subscription.reissue-started' | 'subscription.reissue-skipped' | 'subscription.first-delivery' | 'subscription.recovery-stuck' | 'subscription.recovery-timer-late' | 'subscription.health-cleared' | 'event.gap' | 'connection.status' | 'recovery.state' | 'fault.transport-cut';
341
+ export declare type ClientDiagnosticKind = 'runtime.build-started' | 'runtime.resolved' | 'runtime.failed' | 'runtime.capabilities' | 'runtime.surface-mismatch' | 'runtime.mirror' | 'runtime.swapped' | 'runtime.disposed' | 'socket.created' | 'socket.raw-open' | 'socket.close' | 'socket.error' | 'socket.connect-timeout' | 'socket.retry-scheduled' | 'socket.frames' | 'protocol.ready' | 'subscription.transport-failed' | 'subscription.reissue-started' | 'subscription.reissue-skipped' | 'subscription.first-delivery' | 'subscription.recovery-stuck' | 'subscription.recovery-timer-late' | 'subscription.health-cleared' | 'event.gap' | 'connection.status' | 'recovery.state' | 'fault.transport-cut';
316
342
 
317
343
  export declare interface ClientDiagnosticsSnapshot {
318
344
  readonly version: 1;
@@ -514,6 +540,9 @@ export declare interface MountedApi {
514
540
  readonly wsUrl: string;
515
541
  readonly headers?: ResolvableHeaders | undefined;
516
542
  readonly recovery?: RecoveryOptions | undefined;
543
+ /** Durable local mirror, resolved per transport generation — see
544
+ * `BuildApiRuntimeOptions.mirror`. */
545
+ readonly mirror?: SubscriptionMirrorSource | undefined;
517
546
  }
518
547
 
519
548
  export declare interface MutationReplayReservation {
@@ -885,6 +914,10 @@ export declare const subscribeClientTraces: (listener: ClientTraceListener) => (
885
914
 
886
915
  export declare class SubscriptionCache {
887
916
  private readonly entries;
917
+ /** Standing optimistic intents, by mutation id — see `autoApply`. */
918
+ private readonly intents;
919
+ private readonly tableRows;
920
+ private readonly anyListeners;
888
921
  private readonly refreshing;
889
922
  /**
890
923
  * Same-subject runtime replacement. A mutation may settle against the cache
@@ -1006,7 +1039,15 @@ export declare class SubscriptionCache {
1006
1039
  * these defaults. All patches are tagged with `mutationId` for atomic
1007
1040
  * revert.
1008
1041
  */
1009
- autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string): void;
1042
+ autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string, options?: {
1043
+ readonly standing?: boolean;
1044
+ }): void;
1045
+ /** Whether a standing intent for `mutationId` is still held (see
1046
+ * {@link SubscriptionCache.autoApply}). Carried to a same-subject
1047
+ * replacement cache, so a stager can tell "already staged" from "new". */
1048
+ hasIntent(mutationId: string): boolean;
1049
+ private applyIntent;
1050
+ private applyStandingIntents;
1010
1051
  /** Drop a specific patch by id. */
1011
1052
  private revertPatch;
1012
1053
  /**
@@ -1133,6 +1174,17 @@ export declare class SubscriptionCache {
1133
1174
  private freshState;
1134
1175
  private startFiber;
1135
1176
  private invalidate;
1177
+ /**
1178
+ * Every row of `table` this cache holds — the client's local replica of the
1179
+ * table: the union of the rows of every entry sourced on that table ALONE
1180
+ * (an entry over several tables holds joined shapes, not rows of one),
1181
+ * optimistic previews and mirror-seeded rows included, deduplicated by `id`.
1182
+ * Memoised per table until the next change, so the result is reference-stable
1183
+ * for `useSyncExternalStore`.
1184
+ */
1185
+ rowsOf(table: string): ReadonlyArray<Readonly<Record<string, unknown>>>;
1186
+ /** Call `listener` after any entry changed. Returns the unsubscribe. */
1187
+ subscribeAny(listener: () => void): () => void;
1136
1188
  private getSnapshot;
1137
1189
  private unsubscribe;
1138
1190
  /** Start (or restart) the inactive-TTL countdown for `entry`: unless
@@ -1189,8 +1241,42 @@ export declare interface SubscriptionMirror {
1189
1241
  readonly data: unknown;
1190
1242
  readonly revision: number;
1191
1243
  }) => Promise<void>;
1244
+ /**
1245
+ * Queries to keep subscribed for the whole connection generation, as
1246
+ * `[tag, input]` — so they are mirrored, and readable offline, before any
1247
+ * screen ever opened them. Offline coverage is otherwise "what the user
1248
+ * happened to visit"; this makes it a declaration.
1249
+ */
1250
+ readonly warm?: ReadonlyArray<readonly [tag: string, input: Readonly<Record<string, unknown>>]>;
1251
+ /**
1252
+ * Tags to keep warm with an EMPTY input — each one whose declared input
1253
+ * schema accepts `{}` (a list, a feed, a settings read). The runtime makes
1254
+ * that check against the descriptors; a tag that needs parameters is left
1255
+ * out rather than subscribed into an error.
1256
+ */
1257
+ readonly warmTags?: ReadonlyArray<string>;
1192
1258
  }
1193
1259
 
1260
+ /** What a {@link SubscriptionMirrorSource} is told about the api it mirrors. */
1261
+ export declare interface SubscriptionMirrorContext {
1262
+ /** The api's mount name (`'app'`). */
1263
+ readonly apiName: string;
1264
+ /** The api's rpc descriptors — each query's `source` table(s) is how a source
1265
+ * derives which queries read local-first tables without being told. */
1266
+ readonly descriptors: Readonly<Record<string, ClientDescriptor>>;
1267
+ }
1268
+
1269
+ /**
1270
+ * Where a runtime gets its {@link SubscriptionMirror}: called ONCE per
1271
+ * connection generation, before that generation's cache exists. The cache
1272
+ * keeps what it returned for its whole life, so a mirror is never swapped
1273
+ * under a live cache — a sign-in or tenant switch (`reconnect()`) builds a new
1274
+ * generation, and THAT call resolves the next subject's partition. Resolving
1275
+ * to `undefined` (nobody signed in, no durable storage) mirrors nothing.
1276
+ * `@voltro/local-first`'s `createMirrorSource` is the implementation.
1277
+ */
1278
+ export declare type SubscriptionMirrorSource = (context: SubscriptionMirrorContext) => SubscriptionMirror | undefined | Promise<SubscriptionMirror | undefined>;
1279
+
1194
1280
  /**
1195
1281
  * The matching token proves this snapshot was read after the covered ACKs.
1196
1282
  * Contents need not equal the preview: server normalisation, no-op writes and
package/dist/runtime.js CHANGED
@@ -1,50 +1,51 @@
1
- import { A as e, C as t, D as n, M as r, N as i, O as a, S as o, _ as s, a as c, b as l, c as u, d, f, g as p, h as m, i as h, j as g, k as _, l as v, m as y, n as b, o as x, p as S, r as C, s as w, t as T, v as E, w as D, x as O, y as k } from "./authRefresh-Cu2A-H5R.js";
2
- import { Duration as A, Effect as j, Exit as M, Option as N, Schedule as P, Stream as F } from "effect";
3
- import * as I from "@effect/platform/Headers";
4
- import { RpcClient as L } from "@effect/rpc";
5
- import { ApiUnavailable as R, MUTATION_IN_FLIGHT_RETRY_AFTER_MS as z } from "@voltro/protocol";
1
+ import { C as e, D as t, E as n, O as r, S as i, T as a, _ as o, a as s, d as c, f as l, g as u, h as d, i as f, l as p, m, n as h, o as g, p as _, r as v, t as y, u as b, v as x, w as S, y as C } from "./runRpc-DvHpFZAZ.js";
2
+ import { a as w, i as T, n as E, o as D, r as O, s as k, t as A } from "./authRefresh-C4Ow8HH7.js";
3
+ import { Duration as j, Effect as M, Exit as N, Option as P, Schedule as F, Stream as I } from "effect";
4
+ import * as L from "@effect/platform/Headers";
5
+ import { RpcClient as R } from "@effect/rpc";
6
+ import { ApiUnavailable as z, MUTATION_IN_FLIGHT_RETRY_AFTER_MS as B } from "@voltro/protocol";
6
7
  //#region src/serviceClient.ts
7
- var B = (e) => e?._tag === "MutationInFlight", V = 1e4, H = (e, t) => {
8
+ var V = (e) => e?._tag === "MutationInFlight", H = 1e4, U = (e, t) => {
8
9
  let n = e.descriptors[t]?.kind;
9
10
  return n === "query" || n === "mutation" || n === "action" ? n : void 0;
10
- }, U = (e) => {
11
- let t = e.defaultTimeoutMs ?? 1e4, n, r, a = !1, o = () => {
12
- if (a) return Promise.reject(new R({
11
+ }, W = (e) => {
12
+ let t = e.defaultTimeoutMs ?? 1e4, n, i, a = !1, o = () => {
13
+ if (a) return Promise.reject(new z({
13
14
  api: e.name,
14
15
  tag: "",
15
16
  reason: "closed",
16
17
  message: "client closed"
17
18
  }));
18
19
  if (n !== void 0) return n;
19
- let t = typeof e.wsUrl == "function" ? e.wsUrl() : e.wsUrl, i = e.webSocketConstructor ?? ((e, t) => new globalThis.WebSocket(e, t));
20
- return n = u({
20
+ let t = typeof e.wsUrl == "function" ? e.wsUrl() : e.wsUrl, r = e.webSocketConstructor ?? ((e, t) => new globalThis.WebSocket(e, t));
21
+ return n = D({
21
22
  name: `service:${e.name}`,
22
23
  wsUrl: t,
23
24
  group: e.group,
24
25
  headers: async () => ({ authorization: `Bearer ${e.token()}` }),
25
- webSocketConstructor: i,
26
+ webSocketConstructor: r,
26
27
  surfaceAudience: "service"
27
- }).then((e) => (r = e, e), (e) => {
28
+ }).then((e) => (i = e, e), (e) => {
28
29
  throw n = void 0, e;
29
30
  }), n;
30
- }, s = (t, n, r) => new R({
31
+ }, s = (t, n, r) => new z({
31
32
  api: e.name,
32
33
  tag: t,
33
34
  reason: n,
34
35
  message: r
35
36
  }), c = (t) => {
36
37
  let n = e.callHeaders?.() ?? {};
37
- return t.pipe(j.locallyWith(L.currentHeaders, (t) => {
38
- let r = I.set(t, "authorization", `Bearer ${e.token()}`);
39
- for (let [e, t] of Object.entries(n)) r = I.set(r, e, t);
38
+ return t.pipe(M.locallyWith(R.currentHeaders, (t) => {
39
+ let r = L.set(t, "authorization", `Bearer ${e.token()}`);
40
+ for (let [e, t] of Object.entries(n)) r = L.set(r, e, t);
40
41
  return r;
41
42
  }));
42
- }, l = (e) => e.pipe(F.filter((e) => e._tag === "snapshot" || e._tag === "error"), F.runHead, j.flatMap((e) => {
43
- if (N.isNone(e)) return j.fail(/* @__PURE__ */ Error("the query stream ended before its first snapshot"));
43
+ }, l = (e) => e.pipe(I.filter((e) => e._tag === "snapshot" || e._tag === "error"), I.runHead, M.flatMap((e) => {
44
+ if (P.isNone(e)) return M.fail(/* @__PURE__ */ Error("the query stream ended before its first snapshot"));
44
45
  let t = e.value;
45
- return t._tag === "error" ? j.fail(t.error) : j.succeed(t.data);
46
- })), d = (n, r, i) => {
47
- let u = H(e, n), d = i?.timeoutMs ?? t, f = Date.now(), p = (t) => {
46
+ return t._tag === "error" ? M.fail(t.error) : M.succeed(t.data);
47
+ })), u = (n, r, i) => {
48
+ let u = U(e, n), d = i?.timeoutMs ?? t, f = Date.now(), p = (t) => {
48
49
  e.onCall?.({
49
50
  api: e.name,
50
51
  tag: n,
@@ -52,46 +53,46 @@ var B = (e) => e?._tag === "MutationInFlight", V = 1e4, H = (e, t) => {
52
53
  outcome: t
53
54
  });
54
55
  };
55
- if (u === void 0) return j.die(/* @__PURE__ */ Error(`apis.${e.name}: '${n}' is not a service procedure of this api — is the caller built against an older contract?`));
56
- let m = j.gen(function* () {
57
- let t = yield* j.tryPromise({
56
+ if (u === void 0) return M.die(/* @__PURE__ */ Error(`apis.${e.name}: '${n}' is not a service procedure of this api — is the caller built against an older contract?`));
57
+ let m = M.gen(function* () {
58
+ let t = yield* M.tryPromise({
58
59
  try: () => o(),
59
60
  catch: (e) => s(n, a ? "closed" : "transport", `could not build the connection: ${String(e)}`)
60
- }), d = x(t.client, n);
61
+ }), d = h(t.client, n);
61
62
  if (u === "query") {
62
63
  let e = d(r);
63
64
  return yield* c(l(e));
64
65
  }
65
- let f = i?.idempotencyKey === void 0 && e.ambientIdempotencyKey !== void 0 ? yield* e.ambientIdempotencyKey(n, r) : void 0, p = i?.idempotencyKey ?? f ?? C();
66
- return yield* c(h(d(r), p)).pipe(j.tapError((e) => j.sync(() => {
67
- B(e) && (g = !0);
68
- })), j.retry({
69
- while: B,
70
- schedule: P.spaced(A.millis(z))
66
+ let f = i?.idempotencyKey === void 0 && e.ambientIdempotencyKey !== void 0 ? yield* e.ambientIdempotencyKey(n, r) : void 0, p = i?.idempotencyKey ?? f ?? O();
67
+ return yield* c(T(d(r), p)).pipe(M.tapError((e) => M.sync(() => {
68
+ V(e) && (g = !0);
69
+ })), M.retry({
70
+ while: V,
71
+ schedule: F.spaced(j.millis(B))
71
72
  }));
72
73
  }), g = !1;
73
- return m.pipe(j.timeoutFail({
74
- duration: A.millis(d),
74
+ return m.pipe(M.timeoutFail({
75
+ duration: j.millis(d),
75
76
  onTimeout: () => s(n, "timeout", g ? `no answer within ${d} ms — an earlier send with this idempotency key is still in flight on the callee` : `no answer within ${d} ms`)
76
- }), j.mapError((e) => e?._tag === "RpcClientError" ? s(n, "transport", String(e.message ?? e)) : e), j.tapBoth({
77
- onFailure: (e) => j.sync(() => p(e?._tag === "ApiUnavailable" ? "unavailable" : "error")),
78
- onSuccess: () => j.sync(() => p("ok"))
77
+ }), M.mapError((e) => e?._tag === "RpcClientError" ? s(n, "transport", String(e.message ?? e)) : e), M.tapBoth({
78
+ onFailure: (e) => M.sync(() => p(e?._tag === "ApiUnavailable" ? "unavailable" : "error")),
79
+ onSuccess: () => M.sync(() => p("ok"))
79
80
  }));
80
81
  };
81
82
  return {
82
83
  name: e.name,
83
84
  call: async (e, t, n) => {
84
- let r = await j.runPromiseExit(d(e, t, n), n?.signal === void 0 ? void 0 : { signal: n.signal });
85
- if (M.isSuccess(r)) return r.value;
86
- throw i(r.cause);
85
+ let i = await M.runPromiseExit(u(e, t, n), n?.signal === void 0 ? void 0 : { signal: n.signal });
86
+ if (N.isSuccess(i)) return i.value;
87
+ throw r(i.cause);
87
88
  },
88
- callEffect: d,
89
+ callEffect: u,
89
90
  subscribe: (t, n, r) => {
90
- if (H(e, t) !== "query") throw Error(`apis.${e.name}: '${t}' is not a query — only a query can be subscribed to`);
91
+ if (U(e, t) !== "query") throw Error(`apis.${e.name}: '${t}' is not a query — only a query can be subscribed to`);
91
92
  let i, a = !1, c = -2, l;
92
93
  return o().then((e) => {
93
94
  if (a) return;
94
- let o = [t, n], s = e.cache.subscribe(o, () => x(e.client, t)(n), e.runtime, () => {
95
+ let o = [t, n], s = e.cache.subscribe(o, () => h(e.client, t)(n), e.runtime, () => {
95
96
  let e = s.getSnapshot();
96
97
  e.error !== void 0 && e.error !== l && (l = e.error, r.onError?.(e.error)), e.revision >= 0 && e.revision !== c && e.data !== void 0 && (c = e.revision, r.onValue(e.data));
97
98
  });
@@ -102,14 +103,14 @@ var B = (e) => e?._tag === "MutationInFlight", V = 1e4, H = (e, t) => {
102
103
  a = !0, i?.();
103
104
  } };
104
105
  },
105
- connected: () => r !== void 0,
106
+ connected: () => i !== void 0,
106
107
  close: async () => {
107
108
  a = !0;
108
- let e = r;
109
- r = void 0, n = void 0, e !== void 0 && (e.cache.destroy(e.runtime), await e.runtime.dispose());
109
+ let e = i;
110
+ i = void 0, n = void 0, e !== void 0 && (e.cache.destroy(e.runtime), await e.runtime.dispose());
110
111
  }
111
112
  };
112
- }, W = (e) => {
113
+ }, G = (e) => {
113
114
  let t = (n) => {
114
115
  let r = n.join("."), i = Object.assign((t, n) => e.call(r, t, n), {
115
116
  effect: (t, n) => e.callEffect(r, t, n),
@@ -125,4 +126,4 @@ var B = (e) => e?._tag === "MutationInFlight", V = 1e4, H = (e, t) => {
125
126
  return new Proxy({}, { get: (e, n) => typeof n == "string" && n !== "then" ? t([n]) : void 0 });
126
127
  };
127
128
  //#endregion
128
- export { V as DEFAULT_SERVICE_CALL_TIMEOUT_MS, d as INITIAL_RECOVERY_SNAPSHOT, k as LoadingSubscriptionCache, f as RecoveryCoordinator, m as RpcErrorBus, l as SubscriptionCache, u as buildApiRuntime, t as clearClientDiagnostics, D as clientDiagnosticsSnapshot, T as isUnauthenticated, U as makeServiceClient, p as publishClientError, g as publishClientTrace, n as recordClientDiagnostic, S as recoveryCoordinatorFor, _ as rememberRpcErrorKind, s as reportClientError, x as resolveByTag, y as resolveRecoveryOptions, e as rpcErrorKind, c as runRpcPromise, W as serviceApi, O as stableKey, w as startApiSupervisor, a as subscribeClientDiagnostics, E as subscribeClientErrors, r as subscribeClientTraces, o as supersedesConfirmedPatches, b as wireAuthRefresh, v as withProtocolOpenRecovery };
129
+ export { H as DEFAULT_SERVICE_CALL_TIMEOUT_MS, v as INITIAL_RECOVERY_SNAPSHOT, m as LoadingSubscriptionCache, f as RecoveryCoordinator, b as RpcErrorBus, d as SubscriptionCache, p as apiConnectivity, D as buildApiRuntime, x as clearClientDiagnostics, C as clientDiagnosticsSnapshot, A as isUnauthenticated, W as makeServiceClient, c as publishClientError, n as publishClientTrace, i as recordClientDiagnostic, s as recoveryCoordinatorFor, S as rememberRpcErrorKind, l as reportClientError, h as resolveByTag, g as resolveRecoveryOptions, a as rpcErrorKind, y as runRpcPromise, G as serviceApi, u as stableKey, w as startApiSupervisor, e as subscribeClientDiagnostics, _ as subscribeClientErrors, t as subscribeClientTraces, o as supersedesConfirmedPatches, E as wireAuthRefresh, k as withProtocolOpenRecovery };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/client",
3
- "version": "0.83.1",
3
+ "version": "0.84.0",
4
4
  "description": "Framework-agnostic client bindings — the typed RpcClient, subscription cache, and reactive data layer the web hooks build on.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -33,6 +33,11 @@
33
33
  "types": "./dist/runtime.d.ts",
34
34
  "import": "./dist/runtime.js",
35
35
  "default": "./dist/runtime.js"
36
+ },
37
+ "./query": {
38
+ "types": "./dist/query.d.ts",
39
+ "import": "./dist/query.js",
40
+ "default": "./dist/query.js"
36
41
  }
37
42
  },
38
43
  "main": "./dist/index.js",
@@ -45,7 +50,7 @@
45
50
  "dependencies": {
46
51
  "@tanstack/form-core": "^1.33.5",
47
52
  "@tanstack/react-store": "^0.11.1",
48
- "@voltro/protocol": "0.83.1"
53
+ "@voltro/protocol": "0.84.0"
49
54
  },
50
55
  "peerDependencies": {
51
56
  "@effect/platform": "^0.97.2",