@voltro/client 0.84.0 → 0.86.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 (111) hide show
  1. package/CHANGELOG.md +1215 -0
  2. package/THIRD-PARTY-NOTICES.md +5 -89
  3. package/dist/analyticsCatalog.js +47 -0
  4. package/dist/apiConnectivity.js +33 -0
  5. package/dist/apiRuntime.js +135 -0
  6. package/dist/apiSupervisor.js +125 -0
  7. package/dist/authRefresh.js +20 -0
  8. package/dist/awaitResolvedApi.js +23 -0
  9. package/dist/bootstrap.d.ts +1144 -0
  10. package/dist/bootstrap.js +8 -0
  11. package/dist/cellMerger.js +6 -0
  12. package/dist/clientDiagnostics.js +94 -0
  13. package/dist/clientErrorBus.js +16 -0
  14. package/dist/clientScheduler.js +31 -0
  15. package/dist/connectionPrerequisite.js +70 -0
  16. package/dist/connectionScope.js +35 -0
  17. package/dist/connectionSetupController.js +206 -0
  18. package/dist/createHooks.js +15 -0
  19. package/dist/deepLink.js +69 -0
  20. package/dist/filters.js +58 -0
  21. package/dist/form.d.ts +8 -11
  22. package/dist/form.js +5 -2
  23. package/dist/formBinding.js +325 -0
  24. package/dist/formData.js +65 -0
  25. package/dist/formFlashId.js +4 -0
  26. package/dist/frameworkRuntimesContext.js +8 -0
  27. package/dist/globalContext.js +10 -0
  28. package/dist/index.d.ts +285 -279
  29. package/dist/index.js +83 -3686
  30. package/dist/liveRowSort.js +66 -0
  31. package/dist/mutationConnectionSetup.js +16 -0
  32. package/dist/mutationIdentity.js +10 -0
  33. package/dist/mutationSerialExecution.js +53 -0
  34. package/dist/mutationsBus.js +40 -0
  35. package/dist/onlineSource.js +13 -0
  36. package/dist/outbox.js +213 -0
  37. package/dist/outboxHttp.js +104 -0
  38. package/dist/outboxState.js +43 -0
  39. package/dist/permissions.js +20 -0
  40. package/dist/platform.js +121 -0
  41. package/dist/preloadSeed.js +47 -0
  42. package/dist/provider.js +22 -0
  43. package/dist/query.js +12 -2
  44. package/dist/recoveryCoordinator.js +195 -0
  45. package/dist/recoveryRetry.js +24 -0
  46. package/dist/richText.js +176 -0
  47. package/dist/rpcErrorBus.js +39 -0
  48. package/dist/rpcErrorKind.js +13 -0
  49. package/dist/runRpc.js +12 -0
  50. package/dist/runtime.d.ts +79 -15
  51. package/dist/runtime.js +16 -129
  52. package/dist/runtimeCapabilities.js +44 -0
  53. package/dist/runtimeContext.js +49 -0
  54. package/dist/schemaFields.js +219 -0
  55. package/dist/scopeMembership.js +12 -0
  56. package/dist/seedResolvers.js +7 -0
  57. package/dist/sequence.js +65 -0
  58. package/dist/serverRequest.js +24 -0
  59. package/dist/serviceClient.js +128 -0
  60. package/dist/squashRpcCause.js +8 -0
  61. package/dist/stableKey.js +21 -0
  62. package/dist/store.js +288 -0
  63. package/dist/storeStorage.js +28 -0
  64. package/dist/subscriptionCache.js +724 -0
  65. package/dist/tagWalk.js +23 -0
  66. package/dist/traceBus.js +10 -0
  67. package/dist/tracking.js +40 -0
  68. package/dist/uploadProgress.js +21 -0
  69. package/dist/useAction.js +101 -0
  70. package/dist/useAgent.js +53 -0
  71. package/dist/useAgentChat.js +43 -0
  72. package/dist/useAgentStream.js +64 -0
  73. package/dist/useApiOnline.js +14 -0
  74. package/dist/useCapabilityManifest.js +101 -0
  75. package/dist/useConnectionSetup.js +28 -0
  76. package/dist/useConnectionStatus.js +38 -0
  77. package/dist/useConnections.js +107 -0
  78. package/dist/useDataCopilot.js +24 -0
  79. package/dist/useDataTable.js +34 -0
  80. package/dist/useDerived.js +22 -0
  81. package/dist/useEvent.js +88 -0
  82. package/dist/useFormBinding.js +476 -0
  83. package/dist/useLocalQuery.js +59 -0
  84. package/dist/useMutation.js +214 -0
  85. package/dist/useOnRpcError.js +13 -0
  86. package/dist/usePreloadedSubscription.js +18 -0
  87. package/dist/usePreview.js +14 -0
  88. package/dist/useProvenance.js +51 -0
  89. package/dist/useQueryField.js +34 -0
  90. package/dist/useRecord.js +12 -0
  91. package/dist/useRefreshSubscriptions.js +22 -0
  92. package/dist/useResourceCan.js +18 -0
  93. package/dist/useResumableAgentStream.js +75 -0
  94. package/dist/useSequence.js +25 -0
  95. package/dist/useSkeleton.js +13 -0
  96. package/dist/useSubscription.js +89 -0
  97. package/dist/useSubscriptionHealth.js +32 -0
  98. package/dist/useTranscription.js +51 -0
  99. package/dist/useUndo.js +33 -0
  100. package/dist/useUndoLog.js +44 -0
  101. package/dist/useUpload.js +296 -0
  102. package/dist/useWindowedSubscription.js +65 -0
  103. package/dist/useWorkflow.js +284 -0
  104. package/dist/useWorkflowRunState.js +93 -0
  105. package/dist/validation.js +39 -0
  106. package/dist/validationMessages.js +5 -0
  107. package/package.json +8 -5
  108. package/dist/authRefresh-C4Ow8HH7.js +0 -346
  109. package/dist/formData-dGz5aoUR.js +0 -649
  110. package/dist/queryOnce-CvdopzOj.js +0 -55
  111. package/dist/runRpc-DvHpFZAZ.js +0 -1034
@@ -0,0 +1,724 @@
1
+ import { registeredCellMerger as e } from "./cellMerger.js";
2
+ import { squashRpcCause as t } from "./squashRpcCause.js";
3
+ import { publishClientTrace as n } from "./traceBus.js";
4
+ import { rpcErrorKind as r } from "./rpcErrorKind.js";
5
+ import { recordClientDiagnostic as i } from "./clientDiagnostics.js";
6
+ import { stableKey as a } from "./stableKey.js";
7
+ import { Cause as o, Effect as s, Exit as c, Fiber as l, Option as u, Stream as d } from "effect";
8
+ import * as f from "effect/http/Headers";
9
+ import { RpcClient as p } from "effect/rpc";
10
+ import { createRowPatchApplier as m } from "@voltro/protocol";
11
+ //#region src/subscriptionCache.ts
12
+ var h = (e) => e === void 0 ? /* @__PURE__ */ Error("[voltro] the subscription failed without an error value") : e, g = Object.freeze({
13
+ data: void 0,
14
+ revision: -1,
15
+ emittedAt: void 0,
16
+ error: void 0,
17
+ pendingPatches: 0
18
+ }), _ = 5e3, v = (e, t) => e._tag === "snapshot" && t !== void 0 && e.reconciles === t, y = 0, b = 0, x = () => `patch_${++b}`, S = (e, t) => {
19
+ let n = e;
20
+ for (let e of t.split(".")) {
21
+ if (typeof n != "object" || !n) return;
22
+ n = n[e];
23
+ }
24
+ return n;
25
+ }, C = (e, t, n) => {
26
+ let r = t.split("."), i = (e) => typeof e == "object" && e && !Array.isArray(e) ? { ...e } : {}, a = i(e), o = a;
27
+ for (let e = 0; e < r.length - 1; e += 1) o[r[e]] = i(o[r[e]]), o = o[r[e]];
28
+ return o[r[r.length - 1]] = n, a;
29
+ }, w = (e, t) => {
30
+ let n = e.by ?? "id", r = e.identify ? e.identify(t) : typeof t[n] == "string" ? t[n] : typeof t.id == "string" ? t.id : void 0, i = r === void 0 ? [] : Array.isArray(r) ? r : [r];
31
+ return i.length === 0 ? null : new Set(i);
32
+ }, T = (e, t, n) => {
33
+ let r = e.path, i = e.by ?? "id";
34
+ if (e.op === "insert") {
35
+ let a = e.shapeItem ?? e.shape, o = a ? {
36
+ [i]: n,
37
+ ...a(t, n),
38
+ optimistic: !0
39
+ } : {
40
+ [i]: n,
41
+ ...t,
42
+ optimistic: !0
43
+ }, s = e.order ?? "append";
44
+ return (e) => {
45
+ let t = Array.isArray(S(e, r)) ? S(e, r) : [];
46
+ return C(e ?? {}, r, s === "append" ? [...t, o] : [o, ...t]);
47
+ };
48
+ }
49
+ let a = w(e, t);
50
+ if (a === null) return null;
51
+ if (e.op === "update") {
52
+ let n = e.shapeItem ?? e.shape, o = n ? (e) => ({
53
+ ...n(t, e),
54
+ [i]: e[i],
55
+ optimistic: !0
56
+ }) : (e) => ({
57
+ ...e,
58
+ ...t,
59
+ [i]: e[i],
60
+ optimistic: !0
61
+ });
62
+ return (e) => {
63
+ let t = S(e, r);
64
+ if (!Array.isArray(t)) {
65
+ if (typeof t != "object" || !t) return e;
66
+ let n = t;
67
+ return a.has(n[i]) ? C(e, r, o(n)) : e;
68
+ }
69
+ return C(e, r, t.map((e) => a.has(e[i]) ? o(e) : e));
70
+ };
71
+ }
72
+ return (e) => {
73
+ let t = Array.isArray(S(e, r)) ? S(e, r) : [];
74
+ return C(e, r, t.filter((e) => !a.has(e[i])));
75
+ };
76
+ }, E = (e, t, n) => {
77
+ if (e.op === "insert") return n;
78
+ let r = t.id;
79
+ return typeof r == "string" && r.length > 0 ? r : null;
80
+ }, D = (e, t, n, r) => {
81
+ let { anchorColumn: i, targetColumn: a } = e, o = new Set(n.map((e) => String(e)));
82
+ return (e) => {
83
+ if (!Array.isArray(e)) return e;
84
+ let n = [], s = /* @__PURE__ */ new Set(), c = !1;
85
+ for (let r of e) {
86
+ if (typeof r != "object" || !r) {
87
+ n.push(r);
88
+ continue;
89
+ }
90
+ let e = r;
91
+ if (String(e[i]) !== t) {
92
+ n.push(r);
93
+ continue;
94
+ }
95
+ let l = String(e[a]);
96
+ o.has(l) ? (s.add(l), n.push(r)) : c = !0;
97
+ }
98
+ let l = 0;
99
+ for (let e of o) s.has(e) || (l += 1, c = !0, n.push({
100
+ id: `${r}-link-${l}`,
101
+ [i]: t,
102
+ [a]: e,
103
+ optimistic: !0
104
+ }));
105
+ return c ? n : e;
106
+ };
107
+ }, O = (e) => {
108
+ if (typeof e != "object" || !e) return !1;
109
+ let t = Object.getPrototypeOf(e);
110
+ return (t === Object.prototype || t === null) && Object.values(Object.getOwnPropertyDescriptors(e)).every((e) => "value" in e);
111
+ }, k = (e) => Array.isArray(e) ? Object.getPrototypeOf(e) === Array.prototype && Object.values(Object.getOwnPropertyDescriptors(e)).every((e) => "value" in e) && e.every(O) : O(e), A = (e) => {
112
+ let t = Object.getPrototypeOf(e);
113
+ if (t !== Object.prototype && t !== null || Object.getOwnPropertySymbols(e).length > 0) return;
114
+ let n = Object.entries(Object.getOwnPropertyDescriptors(e));
115
+ if (!n.some(([, e]) => !("value" in e))) return () => Object.getPrototypeOf(e) === t && Object.getOwnPropertySymbols(e).length === 0 && Object.getOwnPropertyNames(e).length === n.length && n.every(([t, n]) => {
116
+ let r = Object.getOwnPropertyDescriptor(e, t);
117
+ return r !== void 0 && "value" in r && r.enumerable === n.enumerable && Object.is(r.value, n.value);
118
+ });
119
+ }, j = (e, t, n) => {
120
+ if (e.path !== void 0) return T(e, t, n);
121
+ switch (e.op) {
122
+ case "insert": {
123
+ let r = e.shape ? {
124
+ id: n,
125
+ ...e.shape(t, n),
126
+ optimistic: !0
127
+ } : {
128
+ id: n,
129
+ ...t,
130
+ optimistic: !0
131
+ }, i = e.order ?? "prepend";
132
+ return (e) => {
133
+ let t = Array.isArray(e) ? e : [];
134
+ return i === "append" ? [...t, r] : [r, ...t];
135
+ };
136
+ }
137
+ case "update": {
138
+ let n = w(e, t);
139
+ if (n === null) return null;
140
+ let r = e.shape, i = r ? (e) => ({
141
+ ...r(t, e),
142
+ id: e.id,
143
+ optimistic: !0
144
+ }) : (e) => ({
145
+ ...e,
146
+ ...t,
147
+ optimistic: !0
148
+ });
149
+ return (e) => {
150
+ if (!Array.isArray(e)) {
151
+ let t = e;
152
+ return typeof t != "object" || !t ? e : n.has(t.id) ? i(t) : e;
153
+ }
154
+ return e.map((e) => {
155
+ let t = e;
156
+ return n.has(t.id) ? i(t) : t;
157
+ });
158
+ };
159
+ }
160
+ case "delete": {
161
+ let n = w(e, t);
162
+ return n === null ? null : (e) => {
163
+ if (!Array.isArray(e)) {
164
+ let t = e;
165
+ return typeof t != "object" || !t ? e : n.has(t.id) ? null : e;
166
+ }
167
+ return e.filter((e) => !n.has(e.id));
168
+ };
169
+ }
170
+ }
171
+ }, M = 5e3, N = 15e3, P = 2e3, F = () => globalThis.document?.visibilityState === "hidden", I = class {
172
+ entries = /* @__PURE__ */ new Map();
173
+ entriesByTable = /* @__PURE__ */ new Map();
174
+ entriesByTag = /* @__PURE__ */ new Map();
175
+ entriesByMutation = /* @__PURE__ */ new Map();
176
+ patchMemberships = /* @__PURE__ */ new WeakMap();
177
+ entryOrder = /* @__PURE__ */ new WeakMap();
178
+ orderedMemberships = /* @__PURE__ */ new WeakMap();
179
+ nextEntryOrder = 0;
180
+ intents = /* @__PURE__ */ new Map();
181
+ tableRows = /* @__PURE__ */ new Map();
182
+ anyListeners = /* @__PURE__ */ new Set();
183
+ tableListeners = /* @__PURE__ */ new Map();
184
+ refreshing = /* @__PURE__ */ new WeakSet();
185
+ successor;
186
+ inactiveTtlMs;
187
+ onChangeHook;
188
+ errorBus;
189
+ mirror;
190
+ mergeCell;
191
+ apiName;
192
+ recoveryStuckMs;
193
+ constructor(e = {}) {
194
+ this.inactiveTtlMs = e.inactiveTtlMs ?? M, this.onChangeHook = e.onChange, this.errorBus = e.errorBus, this.mirror = e.mirror, this.mergeCell = e.mergeCell, this.apiName = e.apiName, this.recoveryStuckMs = e.recoveryStuckMs ?? N;
195
+ }
196
+ diagnose(e, t, n = {}) {
197
+ this.apiName !== void 0 && i(this.apiName, e, {
198
+ tag: t.tag ?? "unknown",
199
+ revision: t.state.baseRevision,
200
+ subscribers: t.subscribers.size,
201
+ attempt: t.recoveryAttempt,
202
+ ...n
203
+ });
204
+ }
205
+ subscribe(e, t, n, r, i = {}) {
206
+ let o = a(e), s = typeof e[0] == "string" ? e[0] : void 0, c = this.entries.get(o);
207
+ return c && c.evictionTimer !== null && (clearTimeout(c.evictionTimer), c.evictionTimer = null), c ? (c.subscribers.add(r), c.fiber === null && (c.fetch = t, c.runtime = n, this.startFiber(c, t, n)), c.source === void 0 && i.source !== void 0 && (c.source = i.source, this.indexSource(c), this.invalidate(c), this.applyStandingIntents(c))) : (c = this.create(o, s, t, n, i.source), this.applyStandingIntents(c), c.subscribers.add(r), this.startFiber(c, t, n)), {
208
+ getSnapshot: () => this.getSnapshot(o),
209
+ unsubscribe: () => this.unsubscribe(o, r)
210
+ };
211
+ }
212
+ update(e, t, n) {
213
+ let r = a(e), i = typeof e[0] == "string" ? e[0] : void 0, o = this.entries.get(r);
214
+ o ||= this.createStub(r, i);
215
+ let s = {
216
+ id: x(),
217
+ mutationId: n,
218
+ reducer: t
219
+ };
220
+ return this.appendPatch(o, s), this.invalidate(o), this.successor?.update(e, t, n), {
221
+ patchId: s.id,
222
+ revert: () => this.revertPatch(r, s.id)
223
+ };
224
+ }
225
+ forTag(e, t, n) {
226
+ let r = 0;
227
+ for (let i of this.orderedEntries(this.entriesByTag.get(e), !0)) {
228
+ let e = {
229
+ id: `forTag-${++b}`,
230
+ mutationId: n,
231
+ reducer: t
232
+ };
233
+ this.appendPatch(i, e), this.invalidate(i), r++;
234
+ }
235
+ return this.successor?.forTag(e, t, n), { patchedCount: r };
236
+ }
237
+ revertByMutation(e) {
238
+ this.intents.delete(e);
239
+ for (let t of this.orderedEntries(this.entriesByMutation.get(e))) {
240
+ let n = t.state.patches.length;
241
+ this.replacePatches(t, t.state.patches.filter((t) => t.mutationId !== e)), t.state.patches.length !== n && this.invalidate(t);
242
+ }
243
+ this.successor?.revertByMutation(e);
244
+ }
245
+ confirmByMutation(e) {
246
+ this.intents.delete(e);
247
+ let t = !1;
248
+ for (let n of this.orderedEntries(this.entriesByMutation.get(e))) {
249
+ let r = !1;
250
+ for (let i of n.state.patches) i.mutationId === e && i.confirmed !== !0 && (i.confirmed = !0, r = !0, t = !0);
251
+ if (r && !n.reconciliationScheduled) {
252
+ n.reconciliationScheduled = !0;
253
+ let e = n.generation;
254
+ queueMicrotask(() => {
255
+ n.reconciliationScheduled = !1, this.entries.get(n.key) === n && n.fetch !== null && n.runtime !== null && n.generation === e && n.state.patches.some((e) => e.confirmed === !0) && this.reissue(n, n.runtime, !1);
256
+ });
257
+ }
258
+ }
259
+ t && setTimeout(() => this.resyncUnechoedMutation(e), _), this.successor?.confirmByMutation(e);
260
+ }
261
+ resyncUnechoedMutation(e) {
262
+ for (let t of this.orderedEntries(this.entriesByMutation.get(e))) {
263
+ if (!t.state.patches.some((t) => t.mutationId === e && t.confirmed === !0)) continue;
264
+ let n = t.tag ?? t.key, r = `optimistic patch for ${n} got no superseding server event within ${_}ms — the write is confirmed, so the preview is KEPT. Check the post-ACK primary subscription read and matching client/server versions.`;
265
+ this.errorBus?.emit({
266
+ source: "subscription",
267
+ tag: n,
268
+ error: Error(r),
269
+ kind: "client",
270
+ outcome: "not-applicable",
271
+ ...t.traceId === void 0 ? {} : { traceId: t.traceId }
272
+ }), console.warn(`[voltro] ${r}`, {
273
+ mutationId: e,
274
+ tag: n
275
+ }), t.fetch !== null && t.runtime !== null && this.reissue(t, t.runtime, !1);
276
+ }
277
+ }
278
+ autoApply(e, t, n, r = {}) {
279
+ let i = {
280
+ targets: e,
281
+ input: t,
282
+ opticId: `optimistic-${n}-${++b}`
283
+ };
284
+ r.standing === !0 && this.intents.set(n, i);
285
+ let a = /* @__PURE__ */ new Set();
286
+ for (let t of e) {
287
+ for (let e of this.entriesByTable.get(t.table) ?? []) a.add(e);
288
+ for (let e of Object.values(t.relations ?? {})) for (let t of this.entriesByTable.get(e.junction) ?? []) a.add(t);
289
+ }
290
+ for (let e of this.orderedEntries(a)) this.applyIntent(e, n, i);
291
+ this.successor?.autoApply(e, t, n, r);
292
+ }
293
+ hasIntent(e) {
294
+ return this.intents.has(e);
295
+ }
296
+ applyIntent(e, t, n) {
297
+ if (e.source === void 0 || e.state.patches.some((e) => e.mutationId === t)) return;
298
+ let { targets: r, input: i, opticId: a } = n, o = (t) => Array.isArray(e.source) ? e.source.includes(t) : e.source === t, s = !1;
299
+ for (let n of r) {
300
+ if (o(n.table)) {
301
+ let r = !0;
302
+ if (n.match !== void 0) try {
303
+ r = n.match(e.state.base, i);
304
+ } catch {
305
+ r = !1;
306
+ }
307
+ if (r && !(e.computed && n.op === "insert" && n.path === void 0)) {
308
+ let r = j(n, i, a);
309
+ r !== null && (this.appendPatch(e, {
310
+ id: `${a}-${e.key}`,
311
+ mutationId: t,
312
+ reducer: r,
313
+ ...n.op === "update" && n.path === void 0 && n.shape === void 0 ? { canReuse: A(i) } : {}
314
+ }), s = !0);
315
+ }
316
+ }
317
+ let r = n.relations;
318
+ if (r !== void 0 && !e.computed) for (let [c, l] of Object.entries(r)) {
319
+ let r = i[c];
320
+ if (!Array.isArray(r) || !o(l.junction)) continue;
321
+ let u = E(n, i, a);
322
+ if (u === null) continue;
323
+ let d = D(l, u, r.map((e) => String(e)), `${a}-${c}`);
324
+ this.appendPatch(e, {
325
+ id: `${a}-${c}-${e.key}`,
326
+ mutationId: t,
327
+ reducer: d
328
+ }), s = !0;
329
+ }
330
+ }
331
+ s && this.invalidate(e);
332
+ }
333
+ applyStandingIntents(e) {
334
+ for (let [t, n] of this.intents) this.applyIntent(e, t, n);
335
+ }
336
+ revertPatch(e, t) {
337
+ let n = this.entries.get(e);
338
+ if (!n) return;
339
+ let r = n.state.patches.length;
340
+ this.replacePatches(n, n.state.patches.filter((e) => e.id !== t)), n.state.patches.length !== r && this.invalidate(n);
341
+ }
342
+ peek(e) {
343
+ return this.getSnapshot(a(e));
344
+ }
345
+ getEntry(e) {
346
+ return this.entries.get(a(e));
347
+ }
348
+ size() {
349
+ return this.entries.size;
350
+ }
351
+ peekAll() {
352
+ let e = [];
353
+ for (let t of this.entries.values()) e.push({
354
+ key: t.key,
355
+ tag: t.tag,
356
+ source: t.source,
357
+ subscriberCount: t.subscribers.size,
358
+ hasFiber: t.fiber !== null,
359
+ evicting: t.evictionTimer !== null,
360
+ recovery: {
361
+ phase: t.recoveryPhase,
362
+ attempt: t.recoveryAttempt,
363
+ lastTransportFailureAt: t.lastTransportFailureAt,
364
+ lastReissueAt: t.lastReissueAt,
365
+ lastDeliveryAt: t.lastDeliveryAt,
366
+ basePreserved: t.recoveryBasePreserved
367
+ },
368
+ snapshot: this.getSnapshot(t.key)
369
+ });
370
+ return e;
371
+ }
372
+ destroy(e) {
373
+ for (let t of this.entries.values()) t.rowPatchApplier?.reset(), delete t.rowPatchApplier, t.evictionTimer !== null && clearTimeout(t.evictionTimer), t.recoveryTimer !== null && clearTimeout(t.recoveryTimer), t.fiber && e.runFork(l.interrupt(t.fiber));
374
+ this.entries.clear(), this.entriesByTable.clear(), this.entriesByTag.clear(), this.entriesByMutation.clear(), this.orderedMemberships = /* @__PURE__ */ new WeakMap(), this.tableRows.clear();
375
+ }
376
+ refreshAll(e) {
377
+ for (let t of this.entries.values()) t.fetch && this.reissue(t, e);
378
+ }
379
+ refresh(e) {
380
+ let t = this.entries.get(a(e));
381
+ return !t?.fetch || !t.runtime || t.subscribers.size === 0 || this.refreshing.has(t) || t.state.base === void 0 && t.state.baseError === void 0 ? !1 : (this.refreshing.add(t), this.reissue(t, t.runtime, !1), !0);
382
+ }
383
+ resumeTransportFailures(e) {
384
+ let t = 0;
385
+ for (let n of this.entries.values()) n.resumeAfterTransportOpen && (n.fiber !== null || n.fetch === null || n.subscribers.size === 0 ? this.diagnose("subscription.reissue-skipped", n, { reason: n.fiber === null ? n.fetch === null ? "missing-fetch" : "no-subscribers" : "fiber-running" }) : (n.recoveryAttempt += 1, n.recoveryPhase = "awaiting-delivery", n.lastReissueAt = Date.now(), n.recoveryBasePreserved = n.state.base !== void 0, this.diagnose("subscription.reissue-started", n, { basePreserved: n.recoveryBasePreserved }), this.reissue(n, e, !1), this.armRecoveryWatchdog(n), t += 1));
386
+ return t;
387
+ }
388
+ armRecoveryWatchdog(e) {
389
+ let t = e.recoveryAttempt;
390
+ e.recoveryTimer !== null && clearTimeout(e.recoveryTimer);
391
+ let n = 0, r = () => {
392
+ let i = Date.now();
393
+ e.recoveryTimer = setTimeout(() => {
394
+ if (e.recoveryPhase !== "awaiting-delivery" || e.recoveryAttempt !== t) return;
395
+ let a = Date.now() - i, o = Math.max(0, a - this.recoveryStuckMs), s = F();
396
+ o > P || s ? (n += 1, n === 1 && this.diagnose("subscription.recovery-timer-late", e, {
397
+ waitedMs: a,
398
+ timerLateMs: o,
399
+ hidden: s
400
+ }), r()) : (e.recoveryPhase = "stuck", e.recoveryTimer = null, this.diagnose("subscription.recovery-stuck", e, {
401
+ waitedMs: a,
402
+ deferrals: n,
403
+ help: "run voltroDiagnostics.download() in the browser console"
404
+ }), console.warn(`[voltro] subscription recovery stalled for ${e.tag ?? "unknown"} after ${a}ms. Run voltroDiagnostics.download() in the browser console and attach the JSON support snapshot.`), this.invalidate(e));
405
+ }, this.recoveryStuckMs);
406
+ };
407
+ r();
408
+ }
409
+ reissue(e, t, n = !0) {
410
+ if (!e.fetch) return;
411
+ let r = e.fiber;
412
+ e.fiber = null, r && t.runFork(l.interrupt(r));
413
+ let i = e.state.patches, a = e.state.base, o = e.state.baseRevision, s = e.state.baseEmittedAt, c = e.state.baseError;
414
+ e.rowPatchApplier?.reset(), e.state = this.freshState(), e.state.patches = i, n || (e.state.base = a, e.state.baseRevision = o, e.state.baseEmittedAt = s, e.state.baseError = c), this.startFiber(e, e.fetch, t);
415
+ }
416
+ seedStaleFrom(e) {
417
+ e.successor = this;
418
+ for (let [t, n] of e.intents) this.intents.set(t, n);
419
+ let t = 0, n = /* @__PURE__ */ new Set();
420
+ for (let r of e.entries.values()) {
421
+ if (r.state.base === void 0 || this.entries.has(r.key)) continue;
422
+ let e = {
423
+ key: r.key,
424
+ tag: r.tag,
425
+ state: {
426
+ base: r.state.base,
427
+ baseRevision: r.state.baseRevision,
428
+ baseEmittedAt: r.state.baseEmittedAt,
429
+ baseError: void 0,
430
+ patches: r.state.patches.map((e) => (e.confirmed === !0 && n.add(e.mutationId), { ...e })),
431
+ cachedSnapshot: null
432
+ },
433
+ generation: 0,
434
+ reconciliationScheduled: !1,
435
+ primaryReads: r.primaryReads,
436
+ subscribers: /* @__PURE__ */ new Set(),
437
+ fiber: null,
438
+ resumeAfterTransportOpen: !1,
439
+ recoveryPhase: "steady",
440
+ recoveryAttempt: 0,
441
+ lastTransportFailureAt: void 0,
442
+ lastReissueAt: void 0,
443
+ lastDeliveryAt: void 0,
444
+ recoveryBasePreserved: !1,
445
+ recoveryTimer: null,
446
+ evictionTimer: null,
447
+ source: r.source,
448
+ computed: r.computed,
449
+ fetch: null,
450
+ runtime: null
451
+ };
452
+ this.registerEntry(e), this.scheduleEviction(e), t += 1;
453
+ }
454
+ for (let e of n) setTimeout(() => this.resyncUnechoedMutation(e), _);
455
+ return t;
456
+ }
457
+ create(e, t, n, r, i) {
458
+ let a = {
459
+ key: e,
460
+ tag: t,
461
+ state: this.freshState(),
462
+ generation: 0,
463
+ reconciliationScheduled: !1,
464
+ primaryReads: !1,
465
+ subscribers: /* @__PURE__ */ new Set(),
466
+ fiber: null,
467
+ resumeAfterTransportOpen: !1,
468
+ recoveryPhase: "steady",
469
+ recoveryAttempt: 0,
470
+ lastTransportFailureAt: void 0,
471
+ lastReissueAt: void 0,
472
+ lastDeliveryAt: void 0,
473
+ recoveryBasePreserved: !1,
474
+ recoveryTimer: null,
475
+ evictionTimer: null,
476
+ source: i,
477
+ computed: !1,
478
+ fetch: n,
479
+ runtime: r
480
+ };
481
+ return this.registerEntry(a), this.mirror !== void 0 && this.mirror.load(e).then((t) => {
482
+ t !== void 0 && this.entries.get(e) === a && a.state.base === void 0 && a.state.baseRevision === -1 && (a.state.base = t.data, a.state.baseRevision = t.revision, this.invalidate(a));
483
+ }).catch(() => {}), a;
484
+ }
485
+ createStub(e, t) {
486
+ let n = {
487
+ key: e,
488
+ tag: t,
489
+ state: this.freshState(),
490
+ generation: 0,
491
+ reconciliationScheduled: !1,
492
+ primaryReads: !1,
493
+ subscribers: /* @__PURE__ */ new Set(),
494
+ fiber: null,
495
+ resumeAfterTransportOpen: !1,
496
+ recoveryPhase: "steady",
497
+ recoveryAttempt: 0,
498
+ lastTransportFailureAt: void 0,
499
+ lastReissueAt: void 0,
500
+ lastDeliveryAt: void 0,
501
+ recoveryBasePreserved: !1,
502
+ recoveryTimer: null,
503
+ evictionTimer: null,
504
+ source: void 0,
505
+ computed: !1,
506
+ fetch: null,
507
+ runtime: null
508
+ };
509
+ return this.registerEntry(n), n;
510
+ }
511
+ freshState() {
512
+ return {
513
+ base: void 0,
514
+ baseRevision: -1,
515
+ baseEmittedAt: void 0,
516
+ baseError: void 0,
517
+ patches: [],
518
+ cachedSnapshot: null
519
+ };
520
+ }
521
+ startFiber(i, a, l) {
522
+ let g = i.tag ?? i.key, _ = ++i.generation, b = /* @__PURE__ */ new Set();
523
+ i.state.patches.forEach((e) => {
524
+ e.confirmed === !0 && b.add(e.id);
525
+ }), b.size > 0 && (i.primaryReads = !0);
526
+ let x = i.primaryReads ? `reconcile-${++y}` : void 0;
527
+ i.resumeAfterTransportOpen = !1;
528
+ let S = a(), C = d.unwrap(s.currentSpan.pipe(s.catch(() => s.succeed(void 0)), s.map((e) => (e && (i.traceId = e.traceId, n({
529
+ traceId: e.traceId,
530
+ spanId: e.spanId,
531
+ source: "subscription",
532
+ tag: g
533
+ })), S)))).pipe(d.withSpan(`client.subscription.${g}`, { attributes: { "rpc.tag": g } })), w = x === void 0 && i.state.baseRevision >= 0 ? i.state.baseRevision : void 0, T = C.pipe(d.runForEach((t) => s.sync(() => {
534
+ if (i.generation === _ && this.entries.get(i.key) === i) {
535
+ if (t._tag === "snapshot") i.rowPatchApplier?.reset(), i.state.base = t.data, i.state.baseRevision = t.revision, i.state.baseEmittedAt = void 0, i.state.baseError = void 0, t.computed === !0 && (i.computed = !0);
536
+ else if (t._tag === "error") {
537
+ let e = h(t.error);
538
+ i.state.baseError = e, typeof t.revision == "number" && (i.state.baseRevision = t.revision), this.errorBus?.emit({
539
+ source: "subscription",
540
+ tag: i.tag ?? i.key,
541
+ error: e,
542
+ kind: "handler",
543
+ outcome: "not-applicable",
544
+ ...i.traceId === void 0 ? {} : { traceId: i.traceId }
545
+ });
546
+ } else {
547
+ let n = i.state.base, r = this.mergeCell ?? e();
548
+ Array.isArray(n) && (i.rowPatchApplier ??= m(), i.state.base = i.rowPatchApplier.apply(n, t.patch, r === void 0 ? {} : { mergeCell: r })), i.state.baseRevision = t.revision, i.state.baseEmittedAt = t.emittedAt, i.state.baseError = void 0;
549
+ }
550
+ this.refreshing.delete(i), t._tag !== "error" && (i.lastDeliveryAt = Date.now(), i.recoveryPhase !== "steady" && (i.recoveryTimer !== null && clearTimeout(i.recoveryTimer), i.recoveryTimer = null, this.diagnose("subscription.first-delivery", i, {
551
+ delivery: t._tag,
552
+ basePreserved: i.recoveryBasePreserved
553
+ }), i.recoveryPhase = "steady", this.diagnose("subscription.health-cleared", i, { delivery: t._tag })), this.errorBus?.emitSuccess({
554
+ source: "subscription",
555
+ tag: i.tag ?? i.key
556
+ })), v(t, x) && this.replacePatches(i, i.state.patches.filter((e) => !b.has(e.id))), this.mirror !== void 0 && t._tag !== "error" && this.mirror.save(i.key, {
557
+ tag: i.tag,
558
+ data: i.state.base,
559
+ revision: i.state.baseRevision
560
+ }).catch(() => {}), delete i.state.previewPrefix, delete i.state.previewBase, this.invalidate(i);
561
+ }
562
+ }))), E = l.runFork(x === void 0 ? w === void 0 ? T : T.pipe(s.updateService(p.CurrentHeaders, (e) => f.set(e, "voltro-resume-from", String(w)))) : T.pipe(s.updateService(p.CurrentHeaders, (e) => f.set(f.remove(e, "voltro-resume-from"), "voltro-reconcile", x))));
563
+ i.fiber = E, E.addObserver((e) => {
564
+ if (i.generation === _ && this.entries.get(i.key) === i && i.fiber === E && (this.refreshing.delete(i), i.fiber === E && (i.fiber = null), c.isFailure(e) && !o.hasInterruptsOnly(e.cause))) {
565
+ let n = h(t(e.cause)), a = o.findErrorOption(e.cause), s = u.isSome(a) ? r(a.value, "handler") : "unknown";
566
+ (s !== "transport" || i.state.base === void 0) && (i.state.baseError = n, this.invalidate(i)), s === "transport" && (i.recoveryTimer !== null && clearTimeout(i.recoveryTimer), i.recoveryTimer = null, i.resumeAfterTransportOpen = !0, i.recoveryPhase = "awaiting-protocol", i.lastTransportFailureAt = Date.now(), this.diagnose("subscription.transport-failed", i)), this.errorBus && this.errorBus.emit({
567
+ source: "subscription",
568
+ tag: i.tag ?? i.key,
569
+ error: n,
570
+ kind: s,
571
+ outcome: "not-applicable",
572
+ ...i.traceId === void 0 ? {} : { traceId: i.traceId }
573
+ });
574
+ }
575
+ });
576
+ }
577
+ sourceTables(e) {
578
+ return e.source === void 0 ? [] : typeof e.source == "string" ? [e.source] : e.source;
579
+ }
580
+ addIndex(e, t, n) {
581
+ let r = e.get(t);
582
+ if (r === void 0) {
583
+ e.set(t, /* @__PURE__ */ new Set([n]));
584
+ return;
585
+ }
586
+ if (e === this.entriesByMutation) {
587
+ r.add(n);
588
+ return;
589
+ }
590
+ let i = r.size;
591
+ r.add(n), r.size !== i && this.orderedMemberships.delete(r);
592
+ }
593
+ removeIndex(e, t, n) {
594
+ let r = e.get(t);
595
+ r?.delete(n) && e !== this.entriesByMutation && this.orderedMemberships.delete(r), r?.size === 0 && e.delete(t);
596
+ }
597
+ orderedEntries(e, t = !1) {
598
+ if (e === void 0) return [];
599
+ let n = t ? this.orderedMemberships.get(e) : void 0;
600
+ if (n !== void 0) return n;
601
+ let r = [...e].sort((e, t) => this.entryOrder.get(e) - this.entryOrder.get(t));
602
+ return t && this.orderedMemberships.set(e, r), r;
603
+ }
604
+ indexSource(e) {
605
+ for (let t of this.sourceTables(e)) this.addIndex(this.entriesByTable, t, e), this.tableRows.delete(t);
606
+ }
607
+ appendPatch(e, t) {
608
+ if (e.state.patches.push(t), t.canReuse === void 0 && delete e.state.previewPrefix, this.entries.get(e.key) !== e) return;
609
+ let n = this.patchMemberships.get(e);
610
+ n === void 0 && (n = /* @__PURE__ */ new Set(), this.patchMemberships.set(e, n)), n.has(t.mutationId) || (n.add(t.mutationId), this.addIndex(this.entriesByMutation, t.mutationId, e));
611
+ }
612
+ replacePatches(e, t) {
613
+ t.length !== e.state.patches.length && (e.state.patches = t, delete e.state.previewPrefix, this.entries.get(e.key) === e && this.indexPatches(e));
614
+ }
615
+ indexPatches(e) {
616
+ let t = this.patchMemberships.get(e) ?? /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set();
617
+ for (let t of e.state.patches) n.add(t.mutationId);
618
+ for (let r of t) n.has(r) || this.removeIndex(this.entriesByMutation, r, e);
619
+ for (let r of n) t.has(r) || this.addIndex(this.entriesByMutation, r, e);
620
+ this.patchMemberships.set(e, n);
621
+ }
622
+ registerEntry(e) {
623
+ this.entries.set(e.key, e), this.entryOrder.set(e, ++this.nextEntryOrder), e.tag !== void 0 && this.addIndex(this.entriesByTag, e.tag, e), this.indexSource(e), this.indexPatches(e);
624
+ }
625
+ unindexEntry(e) {
626
+ e.tag !== void 0 && this.removeIndex(this.entriesByTag, e.tag, e);
627
+ for (let t of this.sourceTables(e)) this.removeIndex(this.entriesByTable, t, e);
628
+ for (let t of this.patchMemberships.get(e) ?? []) this.removeIndex(this.entriesByMutation, t, e);
629
+ this.patchMemberships.delete(e);
630
+ }
631
+ invalidate(e) {
632
+ e.state.cachedSnapshot = null;
633
+ for (let t of this.sourceTables(e)) this.tableRows.delete(t);
634
+ let t = /* @__PURE__ */ new Set();
635
+ for (let n of this.sourceTables(e)) for (let e of this.tableListeners.get(n) ?? []) t.add(e);
636
+ for (let e of t) try {
637
+ e();
638
+ } catch {}
639
+ for (let t of e.subscribers) t();
640
+ this.onChangeHook?.(e.key);
641
+ for (let e of this.anyListeners) try {
642
+ e();
643
+ } catch {}
644
+ }
645
+ rowsOf(e) {
646
+ let t = this.tableRows.get(e);
647
+ if (t !== void 0) return t;
648
+ let n = /* @__PURE__ */ new Map();
649
+ for (let t of this.orderedEntries(this.entriesByTable.get(e), !0)) {
650
+ if (t.source !== e && !(Array.isArray(t.source) && t.source.length === 1 && t.source[0] === e)) continue;
651
+ let r = this.getSnapshot(t.key).data;
652
+ if (Array.isArray(r)) for (let e of r) {
653
+ if (typeof e != "object" || !e) continue;
654
+ let t = e.id;
655
+ if (t === void 0) continue;
656
+ let r = n.get(t);
657
+ (r === void 0 || r.optimistic === !0 || e.optimistic !== !0) && n.set(t, e);
658
+ }
659
+ }
660
+ let r = [...n.values()];
661
+ return this.tableRows.set(e, r), r;
662
+ }
663
+ subscribeTable(e, t) {
664
+ let n = this.tableListeners.get(e);
665
+ n === void 0 && (n = /* @__PURE__ */ new Set(), this.tableListeners.set(e, n)), n.add(t);
666
+ let r = n;
667
+ return () => {
668
+ r.delete(t), r.size === 0 && this.tableListeners.get(e) === r && this.tableListeners.delete(e);
669
+ };
670
+ }
671
+ subscribeAny(e) {
672
+ return this.anyListeners.add(e), () => {
673
+ this.anyListeners.delete(e);
674
+ };
675
+ }
676
+ getSnapshot(e) {
677
+ let t = this.entries.get(e);
678
+ if (!t) return g;
679
+ if (t.state.cachedSnapshot !== null) return t.state.cachedSnapshot;
680
+ let n = t.state.base, r = t.state.patches;
681
+ if (n !== void 0 && r.length > 0) {
682
+ let e = t.state.previewBase, i = e?.base === n ? e.eligible : k(n);
683
+ t.state.previewBase = {
684
+ base: n,
685
+ eligible: i
686
+ };
687
+ let a = i && r.every((e) => e.canReuse?.() === !0), o = a ? t.state.previewPrefix : void 0, s = o?.base === n && o.count <= r.length ? o.count : 0;
688
+ s > 0 && (n = o.data);
689
+ for (let e = s; e < r.length; e++) n = r[e].reducer(n);
690
+ a ? t.state.previewPrefix = {
691
+ base: t.state.base,
692
+ count: r.length,
693
+ data: n
694
+ } : delete t.state.previewPrefix;
695
+ } else delete t.state.previewPrefix;
696
+ let i = {
697
+ data: n,
698
+ revision: t.state.baseRevision,
699
+ emittedAt: t.state.baseEmittedAt,
700
+ error: t.state.baseError,
701
+ pendingPatches: t.state.patches.length
702
+ };
703
+ return t.state.cachedSnapshot = i, i;
704
+ }
705
+ unsubscribe(e, t) {
706
+ let n = this.entries.get(e);
707
+ n && (n.subscribers.delete(t), !(n.subscribers.size > 0) && this.scheduleEviction(n));
708
+ }
709
+ scheduleEviction(e) {
710
+ e.evictionTimer !== null && clearTimeout(e.evictionTimer), e.evictionTimer = setTimeout(() => {
711
+ let t = this.entries.get(e.key);
712
+ t && t.subscribers.size === 0 && (t.rowPatchApplier?.reset(), delete t.rowPatchApplier, t.recoveryTimer !== null && clearTimeout(t.recoveryTimer), t.fiber && s.runFork(l.interrupt(t.fiber)), this.entries.delete(e.key), this.unindexEntry(t), this.invalidate(t));
713
+ }, this.inactiveTtlMs);
714
+ }
715
+ }, L = class extends I {
716
+ subscribe(e, t, n, r, i = {}) {
717
+ return {
718
+ getSnapshot: () => this.peek(e),
719
+ unsubscribe: () => {}
720
+ };
721
+ }
722
+ };
723
+ //#endregion
724
+ export { L as LoadingSubscriptionCache, I as SubscriptionCache, a as stableKey, v as supersedesConfirmedPatches };