@voltro/client 0.83.1 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1172 @@
1
+ import { Cause as e, Effect as t, Exit as n, Fiber as r, Option as i, Schedule as a, Schema as o, Stream as s } from "effect";
2
+ import * as c from "effect/http/Headers";
3
+ import { RpcClient as l } from "effect/rpc";
4
+ import { createRowPatchApplier as u } from "@voltro/protocol";
5
+ //#region src/cellMerger.ts
6
+ var d = Symbol.for("voltro.client.cellMerger"), f = (e) => {
7
+ globalThis[d] = e;
8
+ }, p = () => globalThis[d], m = (t) => {
9
+ let n = e.squash(t);
10
+ return i.isNone(e.findErrorOption(t)) && o.isSchemaError(n) && console.error("[voltro] a value failed its schema in the client — if it is the request payload, the request never reached the server, so no server log has it:\n" + n.message), n;
11
+ }, h = /* @__PURE__ */ new Set(), g = (e) => {
12
+ for (let t of h) try {
13
+ t(e);
14
+ } catch {}
15
+ }, _ = (e) => (h.add(e), () => {
16
+ h.delete(e);
17
+ }), v = /* @__PURE__ */ new WeakMap(), y = (e, t) => ((typeof e == "object" && e || typeof e == "function") && v.set(e, t), e), b = (e, t) => {
18
+ if ((typeof e != "object" || !e) && typeof e != "function") return t;
19
+ let n = v.get(e);
20
+ if (n !== void 0) return n;
21
+ try {
22
+ return e._tag === "RpcClientError" ? "transport" : t;
23
+ } catch {
24
+ return t;
25
+ }
26
+ }, x = "voltro.client-diagnostics.v1", S = 400, C = 240, w = Symbol.for("@voltro/client/diagnostics"), T = globalThis, E = () => typeof performance < "u" && typeof performance.now == "function" ? performance.now() : Date.now(), D = T[w] ?? (T[w] = {
27
+ sessionStartedAt: Date.now(),
28
+ monotonicStartedAt: E(),
29
+ sequence: 0,
30
+ dropped: 0,
31
+ storage: void 0,
32
+ events: [],
33
+ resolved: {},
34
+ loadedStorage: !1,
35
+ listeners: /* @__PURE__ */ new Set()
36
+ }), O = (e) => e.length <= C ? e : `${e.slice(0, C)}…`, ee = (e) => {
37
+ let t = {};
38
+ for (let [n, r] of Object.entries(e)) r !== void 0 && (t[n] = typeof r == "string" ? O(r) : r);
39
+ return t;
40
+ }, te = (e) => {
41
+ if (typeof e != "object" || !e) return !1;
42
+ let t = e;
43
+ return typeof t.sequence == "number" && typeof t.at == "number" && typeof t.elapsedMs == "number" && typeof t.api == "string" && typeof t.kind == "string" && typeof t.fields == "object" && t.fields !== null;
44
+ }, k = () => {
45
+ if (D.storage !== void 0) try {
46
+ D.storage.setItem(x, JSON.stringify({
47
+ version: 1,
48
+ sessionStartedAt: D.sessionStartedAt,
49
+ sequence: D.sequence,
50
+ dropped: D.dropped,
51
+ events: D.events
52
+ }));
53
+ } catch {}
54
+ }, A = () => {
55
+ for (let e of D.listeners) try {
56
+ e();
57
+ } catch {}
58
+ }, ne = (e) => {
59
+ if (D.storage = e, !D.loadedStorage) {
60
+ D.loadedStorage = !0;
61
+ try {
62
+ let t = e.getItem(x);
63
+ if (t !== null) {
64
+ let e = JSON.parse(t), n = Array.isArray(e.events) ? e.events : [], r = 0;
65
+ for (let e of n) te(e) && (n[r++] = e);
66
+ n.length = r;
67
+ let i = n, a = Math.max(typeof e.sequence == "number" ? e.sequence : 0, 0);
68
+ for (let e of i) a = Math.max(a, e.sequence);
69
+ let o = D.events.map((e, t) => ({
70
+ ...e,
71
+ sequence: a + t + 1
72
+ })), s = i.length + o.length, c = Math.max(0, s - S), l = Array(Math.min(S, s));
73
+ for (let e = 0; e < l.length; e += 1) {
74
+ let t = c + e;
75
+ l[e] = t < i.length ? i[t] : o[t - i.length];
76
+ }
77
+ let u = typeof e.dropped == "number" ? e.dropped : 0;
78
+ D.dropped = D.dropped + u + c, D.events = l, D.sequence = a + o.length;
79
+ for (let e of D.events) D.sequence = Math.max(D.sequence, e.sequence);
80
+ typeof e.sessionStartedAt == "number" && (D.sessionStartedAt = Math.min(D.sessionStartedAt, e.sessionStartedAt));
81
+ }
82
+ } catch {}
83
+ }
84
+ k();
85
+ }, re = () => {
86
+ D.storage = void 0;
87
+ }, j = (e, t, n = {}) => {
88
+ let r = {
89
+ sequence: ++D.sequence,
90
+ at: Date.now(),
91
+ elapsedMs: Math.max(0, Math.round(E() - D.monotonicStartedAt)),
92
+ api: O(e),
93
+ kind: t,
94
+ fields: ee(n)
95
+ };
96
+ return t === "runtime.resolved" && (D.resolved = {
97
+ ...D.resolved,
98
+ [r.api]: r.fields
99
+ }), D.events.push(r), D.events.length > S && (D.events.splice(0, D.events.length - S), D.dropped += 1), k(), A(), r;
100
+ }, ie = (e) => ({
101
+ version: 1,
102
+ generatedAt: Date.now(),
103
+ sessionStartedAt: D.sessionStartedAt,
104
+ persisted: D.storage !== void 0,
105
+ dropped: D.dropped,
106
+ events: e === void 0 ? [...D.events] : D.events.filter((t) => t.api === e),
107
+ runtime: e === void 0 ? { ...D.resolved } : D.resolved[e] === void 0 ? {} : { [e]: D.resolved[e] }
108
+ }), ae = () => {
109
+ D.events = [], D.dropped = 0;
110
+ try {
111
+ D.storage?.removeItem(x);
112
+ } catch {}
113
+ A();
114
+ }, oe = (e) => (D.listeners.add(e), () => {
115
+ D.listeners.delete(e);
116
+ }), M = (e) => {
117
+ let t = (e) => {
118
+ if (e == null) return "null";
119
+ if (typeof e == "string") return JSON.stringify(e);
120
+ if (typeof e == "number" || typeof e == "boolean") return String(e);
121
+ if (Array.isArray(e)) return `[${e.map(t).join(",")}]`;
122
+ if (typeof e == "object") {
123
+ let n = Object.keys(e).sort(), r = "";
124
+ for (let i = 0; i < n.length; i++) {
125
+ let a = n[i];
126
+ i > 0 && (r += ","), r += `${JSON.stringify(a)}:${t(e[a])}`;
127
+ }
128
+ return `{${r}}`;
129
+ }
130
+ return String(e);
131
+ };
132
+ return t(e);
133
+ }, N = (e) => e === void 0 ? /* @__PURE__ */ Error("[voltro] the subscription failed without an error value") : e, se = Object.freeze({
134
+ data: void 0,
135
+ revision: -1,
136
+ emittedAt: void 0,
137
+ error: void 0,
138
+ pendingPatches: 0
139
+ }), P = 5e3, F = (e, t) => e._tag === "snapshot" && t !== void 0 && e.reconciles === t, ce = 0, I = 0, le = () => `patch_${++I}`, L = (e, t) => {
140
+ let n = e;
141
+ for (let e of t.split(".")) {
142
+ if (typeof n != "object" || !n) return;
143
+ n = n[e];
144
+ }
145
+ return n;
146
+ }, R = (e, t, n) => {
147
+ let r = t.split("."), i = (e) => typeof e == "object" && e && !Array.isArray(e) ? { ...e } : {}, a = i(e), o = a;
148
+ for (let e = 0; e < r.length - 1; e += 1) o[r[e]] = i(o[r[e]]), o = o[r[e]];
149
+ return o[r[r.length - 1]] = n, a;
150
+ }, z = (e, t) => {
151
+ 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];
152
+ return i.length === 0 ? null : new Set(i);
153
+ }, ue = (e, t, n) => {
154
+ let r = e.path, i = e.by ?? "id";
155
+ if (e.op === "insert") {
156
+ let a = e.shapeItem ?? e.shape, o = a ? {
157
+ [i]: n,
158
+ ...a(t, n),
159
+ optimistic: !0
160
+ } : {
161
+ [i]: n,
162
+ ...t,
163
+ optimistic: !0
164
+ }, s = e.order ?? "append";
165
+ return (e) => {
166
+ let t = Array.isArray(L(e, r)) ? L(e, r) : [];
167
+ return R(e ?? {}, r, s === "append" ? [...t, o] : [o, ...t]);
168
+ };
169
+ }
170
+ let a = z(e, t);
171
+ if (a === null) return null;
172
+ if (e.op === "update") {
173
+ let n = e.shapeItem ?? e.shape, o = n ? (e) => ({
174
+ ...n(t, e),
175
+ [i]: e[i],
176
+ optimistic: !0
177
+ }) : (e) => ({
178
+ ...e,
179
+ ...t,
180
+ [i]: e[i],
181
+ optimistic: !0
182
+ });
183
+ return (e) => {
184
+ let t = L(e, r);
185
+ if (!Array.isArray(t)) {
186
+ if (typeof t != "object" || !t) return e;
187
+ let n = t;
188
+ return a.has(n[i]) ? R(e, r, o(n)) : e;
189
+ }
190
+ return R(e, r, t.map((e) => a.has(e[i]) ? o(e) : e));
191
+ };
192
+ }
193
+ return (e) => {
194
+ let t = Array.isArray(L(e, r)) ? L(e, r) : [];
195
+ return R(e, r, t.filter((e) => !a.has(e[i])));
196
+ };
197
+ }, de = (e, t, n) => {
198
+ if (e.op === "insert") return n;
199
+ let r = t.id;
200
+ return typeof r == "string" && r.length > 0 ? r : null;
201
+ }, fe = (e, t, n, r) => {
202
+ let { anchorColumn: i, targetColumn: a } = e, o = new Set(n.map((e) => String(e)));
203
+ return (e) => {
204
+ if (!Array.isArray(e)) return e;
205
+ let n = [], s = /* @__PURE__ */ new Set(), c = !1;
206
+ for (let r of e) {
207
+ if (typeof r != "object" || !r) {
208
+ n.push(r);
209
+ continue;
210
+ }
211
+ let e = r;
212
+ if (String(e[i]) !== t) {
213
+ n.push(r);
214
+ continue;
215
+ }
216
+ let l = String(e[a]);
217
+ if (!o.has(l)) {
218
+ c = !0;
219
+ continue;
220
+ }
221
+ s.add(l), n.push(r);
222
+ }
223
+ let l = 0;
224
+ for (let e of o) s.has(e) || (l += 1, c = !0, n.push({
225
+ id: `${r}-link-${l}`,
226
+ [i]: t,
227
+ [a]: e,
228
+ optimistic: !0
229
+ }));
230
+ return c ? n : e;
231
+ };
232
+ }, B = (e) => {
233
+ if (typeof e != "object" || !e) return !1;
234
+ let t = Object.getPrototypeOf(e);
235
+ return (t === Object.prototype || t === null) && Object.values(Object.getOwnPropertyDescriptors(e)).every((e) => "value" in e);
236
+ }, V = (e) => Array.isArray(e) ? Object.getPrototypeOf(e) === Array.prototype && Object.values(Object.getOwnPropertyDescriptors(e)).every((e) => "value" in e) && e.every(B) : B(e), pe = (e) => {
237
+ let t = Object.getPrototypeOf(e);
238
+ if (t !== Object.prototype && t !== null || Object.getOwnPropertySymbols(e).length > 0) return;
239
+ let n = Object.entries(Object.getOwnPropertyDescriptors(e));
240
+ 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]) => {
241
+ let r = Object.getOwnPropertyDescriptor(e, t);
242
+ return r !== void 0 && "value" in r && r.enumerable === n.enumerable && Object.is(r.value, n.value);
243
+ });
244
+ }, me = (e, t, n) => {
245
+ if (e.path !== void 0) return ue(e, t, n);
246
+ switch (e.op) {
247
+ case "insert": {
248
+ let r = e.shape ? {
249
+ id: n,
250
+ ...e.shape(t, n),
251
+ optimistic: !0
252
+ } : {
253
+ id: n,
254
+ ...t,
255
+ optimistic: !0
256
+ }, i = e.order ?? "prepend";
257
+ return (e) => {
258
+ let t = Array.isArray(e) ? e : [];
259
+ return i === "append" ? [...t, r] : [r, ...t];
260
+ };
261
+ }
262
+ case "update": {
263
+ let n = z(e, t);
264
+ if (n === null) return null;
265
+ let r = e.shape, i = r ? (e) => ({
266
+ ...r(t, e),
267
+ id: e.id,
268
+ optimistic: !0
269
+ }) : (e) => ({
270
+ ...e,
271
+ ...t,
272
+ optimistic: !0
273
+ });
274
+ return (e) => {
275
+ if (!Array.isArray(e)) {
276
+ let t = e;
277
+ return typeof t != "object" || !t ? e : n.has(t.id) ? i(t) : e;
278
+ }
279
+ return e.map((e) => {
280
+ let t = e;
281
+ return n.has(t.id) ? i(t) : t;
282
+ });
283
+ };
284
+ }
285
+ case "delete": {
286
+ let n = z(e, t);
287
+ return n === null ? null : (e) => {
288
+ if (!Array.isArray(e)) {
289
+ let t = e;
290
+ return typeof t != "object" || !t ? e : n.has(t.id) ? null : e;
291
+ }
292
+ return e.filter((e) => !n.has(e.id));
293
+ };
294
+ }
295
+ }
296
+ }, he = 5e3, ge = 15e3, _e = 2e3, ve = () => globalThis.document?.visibilityState === "hidden", H = class {
297
+ entries = /* @__PURE__ */ new Map();
298
+ entriesByTable = /* @__PURE__ */ new Map();
299
+ entriesByTag = /* @__PURE__ */ new Map();
300
+ entriesByMutation = /* @__PURE__ */ new Map();
301
+ patchMemberships = /* @__PURE__ */ new WeakMap();
302
+ entryOrder = /* @__PURE__ */ new WeakMap();
303
+ orderedMemberships = /* @__PURE__ */ new WeakMap();
304
+ nextEntryOrder = 0;
305
+ intents = /* @__PURE__ */ new Map();
306
+ tableRows = /* @__PURE__ */ new Map();
307
+ anyListeners = /* @__PURE__ */ new Set();
308
+ tableListeners = /* @__PURE__ */ new Map();
309
+ refreshing = /* @__PURE__ */ new WeakSet();
310
+ successor;
311
+ inactiveTtlMs;
312
+ onChangeHook;
313
+ errorBus;
314
+ mirror;
315
+ mergeCell;
316
+ apiName;
317
+ recoveryStuckMs;
318
+ constructor(e = {}) {
319
+ this.inactiveTtlMs = e.inactiveTtlMs ?? he, this.onChangeHook = e.onChange, this.errorBus = e.errorBus, this.mirror = e.mirror, this.mergeCell = e.mergeCell, this.apiName = e.apiName, this.recoveryStuckMs = e.recoveryStuckMs ?? ge;
320
+ }
321
+ diagnose(e, t, n = {}) {
322
+ this.apiName !== void 0 && j(this.apiName, e, {
323
+ tag: t.tag ?? "unknown",
324
+ revision: t.state.baseRevision,
325
+ subscribers: t.subscribers.size,
326
+ attempt: t.recoveryAttempt,
327
+ ...n
328
+ });
329
+ }
330
+ subscribe(e, t, n, r, i = {}) {
331
+ let a = M(e), o = typeof e[0] == "string" ? e[0] : void 0, s = this.entries.get(a);
332
+ return s && s.evictionTimer !== null && (clearTimeout(s.evictionTimer), s.evictionTimer = null), s ? (s.subscribers.add(r), s.fiber === null && (s.fetch = t, s.runtime = n, this.startFiber(s, t, n)), s.source === void 0 && i.source !== void 0 && (s.source = i.source, this.indexSource(s), this.invalidate(s), this.applyStandingIntents(s))) : (s = this.create(a, o, t, n, i.source), this.applyStandingIntents(s), s.subscribers.add(r), this.startFiber(s, t, n)), {
333
+ getSnapshot: () => this.getSnapshot(a),
334
+ unsubscribe: () => this.unsubscribe(a, r)
335
+ };
336
+ }
337
+ update(e, t, n) {
338
+ let r = M(e), i = typeof e[0] == "string" ? e[0] : void 0, a = this.entries.get(r);
339
+ a ||= this.createStub(r, i);
340
+ let o = {
341
+ id: le(),
342
+ mutationId: n,
343
+ reducer: t
344
+ };
345
+ return this.appendPatch(a, o), this.invalidate(a), this.successor?.update(e, t, n), {
346
+ patchId: o.id,
347
+ revert: () => this.revertPatch(r, o.id)
348
+ };
349
+ }
350
+ forTag(e, t, n) {
351
+ let r = 0;
352
+ for (let i of this.orderedEntries(this.entriesByTag.get(e), !0)) {
353
+ let e = {
354
+ id: `forTag-${++I}`,
355
+ mutationId: n,
356
+ reducer: t
357
+ };
358
+ this.appendPatch(i, e), this.invalidate(i), r++;
359
+ }
360
+ return this.successor?.forTag(e, t, n), { patchedCount: r };
361
+ }
362
+ revertByMutation(e) {
363
+ this.intents.delete(e);
364
+ for (let t of this.orderedEntries(this.entriesByMutation.get(e))) {
365
+ let n = t.state.patches.length;
366
+ this.replacePatches(t, t.state.patches.filter((t) => t.mutationId !== e)), t.state.patches.length !== n && this.invalidate(t);
367
+ }
368
+ this.successor?.revertByMutation(e);
369
+ }
370
+ confirmByMutation(e) {
371
+ this.intents.delete(e);
372
+ let t = !1;
373
+ for (let n of this.orderedEntries(this.entriesByMutation.get(e))) {
374
+ let r = !1;
375
+ for (let i of n.state.patches) i.mutationId === e && i.confirmed !== !0 && (i.confirmed = !0, r = !0, t = !0);
376
+ if (r && !n.reconciliationScheduled) {
377
+ n.reconciliationScheduled = !0;
378
+ let e = n.generation;
379
+ queueMicrotask(() => {
380
+ 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);
381
+ });
382
+ }
383
+ }
384
+ t && setTimeout(() => this.resyncUnechoedMutation(e), P), this.successor?.confirmByMutation(e);
385
+ }
386
+ resyncUnechoedMutation(e) {
387
+ for (let t of this.orderedEntries(this.entriesByMutation.get(e))) {
388
+ if (!t.state.patches.some((t) => t.mutationId === e && t.confirmed === !0)) continue;
389
+ let n = t.tag ?? t.key, r = `optimistic patch for ${n} got no superseding server event within ${P}ms — the write is confirmed, so the preview is KEPT. Check the post-ACK primary subscription read and matching client/server versions.`;
390
+ this.errorBus?.emit({
391
+ source: "subscription",
392
+ tag: n,
393
+ error: Error(r),
394
+ kind: "client",
395
+ outcome: "not-applicable",
396
+ ...t.traceId === void 0 ? {} : { traceId: t.traceId }
397
+ }), console.warn(`[voltro] ${r}`, {
398
+ mutationId: e,
399
+ tag: n
400
+ }), t.fetch !== null && t.runtime !== null && this.reissue(t, t.runtime, !1);
401
+ }
402
+ }
403
+ autoApply(e, t, n, r = {}) {
404
+ let i = {
405
+ targets: e,
406
+ input: t,
407
+ opticId: `optimistic-${n}-${++I}`
408
+ };
409
+ r.standing === !0 && this.intents.set(n, i);
410
+ let a = /* @__PURE__ */ new Set();
411
+ for (let t of e) {
412
+ for (let e of this.entriesByTable.get(t.table) ?? []) a.add(e);
413
+ for (let e of Object.values(t.relations ?? {})) for (let t of this.entriesByTable.get(e.junction) ?? []) a.add(t);
414
+ }
415
+ for (let e of this.orderedEntries(a)) this.applyIntent(e, n, i);
416
+ this.successor?.autoApply(e, t, n, r);
417
+ }
418
+ hasIntent(e) {
419
+ return this.intents.has(e);
420
+ }
421
+ applyIntent(e, t, n) {
422
+ if (e.source === void 0 || e.state.patches.some((e) => e.mutationId === t)) return;
423
+ let { targets: r, input: i, opticId: a } = n, o = (t) => Array.isArray(e.source) ? e.source.includes(t) : e.source === t, s = !1;
424
+ for (let n of r) {
425
+ if (o(n.table)) {
426
+ let r = !0;
427
+ if (n.match !== void 0) try {
428
+ r = n.match(e.state.base, i);
429
+ } catch {
430
+ r = !1;
431
+ }
432
+ if (r && !(e.computed && n.op === "insert" && n.path === void 0)) {
433
+ let r = me(n, i, a);
434
+ r !== null && (this.appendPatch(e, {
435
+ id: `${a}-${e.key}`,
436
+ mutationId: t,
437
+ reducer: r,
438
+ ...n.op === "update" && n.path === void 0 && n.shape === void 0 ? { canReuse: pe(i) } : {}
439
+ }), s = !0);
440
+ }
441
+ }
442
+ let r = n.relations;
443
+ if (r !== void 0 && !e.computed) for (let [c, l] of Object.entries(r)) {
444
+ let r = i[c];
445
+ if (!Array.isArray(r) || !o(l.junction)) continue;
446
+ let u = de(n, i, a);
447
+ if (u === null) continue;
448
+ let d = fe(l, u, r.map((e) => String(e)), `${a}-${c}`);
449
+ this.appendPatch(e, {
450
+ id: `${a}-${c}-${e.key}`,
451
+ mutationId: t,
452
+ reducer: d
453
+ }), s = !0;
454
+ }
455
+ }
456
+ s && this.invalidate(e);
457
+ }
458
+ applyStandingIntents(e) {
459
+ for (let [t, n] of this.intents) this.applyIntent(e, t, n);
460
+ }
461
+ revertPatch(e, t) {
462
+ let n = this.entries.get(e);
463
+ if (!n) return;
464
+ let r = n.state.patches.length;
465
+ this.replacePatches(n, n.state.patches.filter((e) => e.id !== t)), n.state.patches.length !== r && this.invalidate(n);
466
+ }
467
+ peek(e) {
468
+ return this.getSnapshot(M(e));
469
+ }
470
+ getEntry(e) {
471
+ return this.entries.get(M(e));
472
+ }
473
+ size() {
474
+ return this.entries.size;
475
+ }
476
+ peekAll() {
477
+ let e = [];
478
+ for (let t of this.entries.values()) e.push({
479
+ key: t.key,
480
+ tag: t.tag,
481
+ source: t.source,
482
+ subscriberCount: t.subscribers.size,
483
+ hasFiber: t.fiber !== null,
484
+ evicting: t.evictionTimer !== null,
485
+ recovery: {
486
+ phase: t.recoveryPhase,
487
+ attempt: t.recoveryAttempt,
488
+ lastTransportFailureAt: t.lastTransportFailureAt,
489
+ lastReissueAt: t.lastReissueAt,
490
+ lastDeliveryAt: t.lastDeliveryAt,
491
+ basePreserved: t.recoveryBasePreserved
492
+ },
493
+ snapshot: this.getSnapshot(t.key)
494
+ });
495
+ return e;
496
+ }
497
+ destroy(e) {
498
+ 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(r.interrupt(t.fiber));
499
+ this.entries.clear(), this.entriesByTable.clear(), this.entriesByTag.clear(), this.entriesByMutation.clear(), this.orderedMemberships = /* @__PURE__ */ new WeakMap(), this.tableRows.clear();
500
+ }
501
+ refreshAll(e) {
502
+ for (let t of this.entries.values()) t.fetch && this.reissue(t, e);
503
+ }
504
+ refresh(e) {
505
+ let t = this.entries.get(M(e));
506
+ 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);
507
+ }
508
+ resumeTransportFailures(e) {
509
+ let t = 0;
510
+ for (let n of this.entries.values()) if (n.resumeAfterTransportOpen) {
511
+ if (n.fiber !== null || n.fetch === null || n.subscribers.size === 0) {
512
+ this.diagnose("subscription.reissue-skipped", n, { reason: n.fiber === null ? n.fetch === null ? "missing-fetch" : "no-subscribers" : "fiber-running" });
513
+ continue;
514
+ }
515
+ 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;
516
+ }
517
+ return t;
518
+ }
519
+ armRecoveryWatchdog(e) {
520
+ let t = e.recoveryAttempt;
521
+ e.recoveryTimer !== null && clearTimeout(e.recoveryTimer);
522
+ let n = 0, r = () => {
523
+ let i = Date.now();
524
+ e.recoveryTimer = setTimeout(() => {
525
+ if (e.recoveryPhase !== "awaiting-delivery" || e.recoveryAttempt !== t) return;
526
+ let a = Date.now() - i, o = Math.max(0, a - this.recoveryStuckMs), s = ve();
527
+ if (o > _e || s) {
528
+ n += 1, n === 1 && this.diagnose("subscription.recovery-timer-late", e, {
529
+ waitedMs: a,
530
+ timerLateMs: o,
531
+ hidden: s
532
+ }), r();
533
+ return;
534
+ }
535
+ e.recoveryPhase = "stuck", e.recoveryTimer = null, this.diagnose("subscription.recovery-stuck", e, {
536
+ waitedMs: a,
537
+ deferrals: n,
538
+ help: "run voltroDiagnostics.download() in the browser console"
539
+ }), 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);
540
+ }, this.recoveryStuckMs);
541
+ };
542
+ r();
543
+ }
544
+ reissue(e, t, n = !0) {
545
+ if (!e.fetch) return;
546
+ let i = e.fiber;
547
+ e.fiber = null, i && t.runFork(r.interrupt(i));
548
+ let a = e.state.patches, o = e.state.base, s = e.state.baseRevision, c = e.state.baseEmittedAt;
549
+ e.rowPatchApplier?.reset(), e.state = this.freshState(), e.state.patches = a, n || (e.state.base = o, e.state.baseRevision = s, e.state.baseEmittedAt = c), this.startFiber(e, e.fetch, t);
550
+ }
551
+ seedStaleFrom(e) {
552
+ e.successor = this;
553
+ for (let [t, n] of e.intents) this.intents.set(t, n);
554
+ let t = 0, n = /* @__PURE__ */ new Set();
555
+ for (let r of e.entries.values()) {
556
+ if (r.state.base === void 0 || this.entries.has(r.key)) continue;
557
+ let e = {
558
+ key: r.key,
559
+ tag: r.tag,
560
+ state: {
561
+ base: r.state.base,
562
+ baseRevision: r.state.baseRevision,
563
+ baseEmittedAt: r.state.baseEmittedAt,
564
+ baseError: void 0,
565
+ patches: r.state.patches.map((e) => (e.confirmed === !0 && n.add(e.mutationId), { ...e })),
566
+ cachedSnapshot: null
567
+ },
568
+ generation: 0,
569
+ reconciliationScheduled: !1,
570
+ primaryReads: r.primaryReads,
571
+ subscribers: /* @__PURE__ */ new Set(),
572
+ fiber: null,
573
+ resumeAfterTransportOpen: !1,
574
+ recoveryPhase: "steady",
575
+ recoveryAttempt: 0,
576
+ lastTransportFailureAt: void 0,
577
+ lastReissueAt: void 0,
578
+ lastDeliveryAt: void 0,
579
+ recoveryBasePreserved: !1,
580
+ recoveryTimer: null,
581
+ evictionTimer: null,
582
+ source: r.source,
583
+ computed: r.computed,
584
+ fetch: null,
585
+ runtime: null
586
+ };
587
+ this.registerEntry(e), this.scheduleEviction(e), t += 1;
588
+ }
589
+ for (let e of n) setTimeout(() => this.resyncUnechoedMutation(e), P);
590
+ return t;
591
+ }
592
+ create(e, t, n, r, i) {
593
+ let a = {
594
+ key: e,
595
+ tag: t,
596
+ state: this.freshState(),
597
+ generation: 0,
598
+ reconciliationScheduled: !1,
599
+ primaryReads: !1,
600
+ subscribers: /* @__PURE__ */ new Set(),
601
+ fiber: null,
602
+ resumeAfterTransportOpen: !1,
603
+ recoveryPhase: "steady",
604
+ recoveryAttempt: 0,
605
+ lastTransportFailureAt: void 0,
606
+ lastReissueAt: void 0,
607
+ lastDeliveryAt: void 0,
608
+ recoveryBasePreserved: !1,
609
+ recoveryTimer: null,
610
+ evictionTimer: null,
611
+ source: i,
612
+ computed: !1,
613
+ fetch: n,
614
+ runtime: r
615
+ };
616
+ return this.registerEntry(a), this.mirror !== void 0 && this.mirror.load(e).then((t) => {
617
+ 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));
618
+ }).catch(() => {}), a;
619
+ }
620
+ createStub(e, t) {
621
+ let n = {
622
+ key: e,
623
+ tag: t,
624
+ state: this.freshState(),
625
+ generation: 0,
626
+ reconciliationScheduled: !1,
627
+ primaryReads: !1,
628
+ subscribers: /* @__PURE__ */ new Set(),
629
+ fiber: null,
630
+ resumeAfterTransportOpen: !1,
631
+ recoveryPhase: "steady",
632
+ recoveryAttempt: 0,
633
+ lastTransportFailureAt: void 0,
634
+ lastReissueAt: void 0,
635
+ lastDeliveryAt: void 0,
636
+ recoveryBasePreserved: !1,
637
+ recoveryTimer: null,
638
+ evictionTimer: null,
639
+ source: void 0,
640
+ computed: !1,
641
+ fetch: null,
642
+ runtime: null
643
+ };
644
+ return this.registerEntry(n), n;
645
+ }
646
+ freshState() {
647
+ return {
648
+ base: void 0,
649
+ baseRevision: -1,
650
+ baseEmittedAt: void 0,
651
+ baseError: void 0,
652
+ patches: [],
653
+ cachedSnapshot: null
654
+ };
655
+ }
656
+ startFiber(r, a, o) {
657
+ let d = r.tag ?? r.key, f = ++r.generation, h = /* @__PURE__ */ new Set();
658
+ r.state.patches.forEach((e) => {
659
+ e.confirmed === !0 && h.add(e.id);
660
+ }), h.size > 0 && (r.primaryReads = !0);
661
+ let _ = r.primaryReads ? `reconcile-${++ce}` : void 0;
662
+ r.resumeAfterTransportOpen = !1;
663
+ let v = a(), y = s.unwrap(t.currentSpan.pipe(t.catch(() => t.succeed(void 0)), t.map((e) => (e && (r.traceId = e.traceId, g({
664
+ traceId: e.traceId,
665
+ spanId: e.spanId,
666
+ source: "subscription",
667
+ tag: d
668
+ })), v)))).pipe(s.withSpan(`client.subscription.${d}`, { attributes: { "rpc.tag": d } })), x = _ === void 0 && r.state.baseRevision >= 0 ? r.state.baseRevision : void 0, S = y.pipe(s.runForEach((e) => t.sync(() => {
669
+ if (r.generation === f && this.entries.get(r.key) === r) {
670
+ if (e._tag === "snapshot") r.rowPatchApplier?.reset(), r.state.base = e.data, r.state.baseRevision = e.revision, r.state.baseEmittedAt = void 0, r.state.baseError = void 0, e.computed === !0 && (r.computed = !0);
671
+ else if (e._tag === "error") {
672
+ let t = N(e.error);
673
+ r.state.baseError = t, typeof e.revision == "number" && (r.state.baseRevision = e.revision), this.errorBus?.emit({
674
+ source: "subscription",
675
+ tag: r.tag ?? r.key,
676
+ error: t,
677
+ kind: "handler",
678
+ outcome: "not-applicable",
679
+ ...r.traceId === void 0 ? {} : { traceId: r.traceId }
680
+ });
681
+ } else {
682
+ let t = r.state.base, n = this.mergeCell ?? p();
683
+ Array.isArray(t) && (r.rowPatchApplier ??= u(), r.state.base = r.rowPatchApplier.apply(t, e.patch, n === void 0 ? {} : { mergeCell: n })), r.state.baseRevision = e.revision, r.state.baseEmittedAt = e.emittedAt, r.state.baseError = void 0;
684
+ }
685
+ this.refreshing.delete(r), e._tag !== "error" && (r.lastDeliveryAt = Date.now(), r.recoveryPhase !== "steady" && (r.recoveryTimer !== null && clearTimeout(r.recoveryTimer), r.recoveryTimer = null, this.diagnose("subscription.first-delivery", r, {
686
+ delivery: e._tag,
687
+ basePreserved: r.recoveryBasePreserved
688
+ }), r.recoveryPhase = "steady", this.diagnose("subscription.health-cleared", r, { delivery: e._tag })), this.errorBus?.emitSuccess({
689
+ source: "subscription",
690
+ tag: r.tag ?? r.key
691
+ })), F(e, _) && this.replacePatches(r, r.state.patches.filter((e) => !h.has(e.id))), this.mirror !== void 0 && e._tag !== "error" && this.mirror.save(r.key, {
692
+ tag: r.tag,
693
+ data: r.state.base,
694
+ revision: r.state.baseRevision
695
+ }).catch(() => {}), delete r.state.previewPrefix, delete r.state.previewBase, this.invalidate(r);
696
+ }
697
+ }))), C = o.runFork(_ === void 0 ? x === void 0 ? S : S.pipe(t.updateService(l.CurrentHeaders, (e) => c.set(e, "voltro-resume-from", String(x)))) : S.pipe(t.updateService(l.CurrentHeaders, (e) => c.set(c.remove(e, "voltro-resume-from"), "voltro-reconcile", _))));
698
+ r.fiber = C, C.addObserver((t) => {
699
+ if (r.generation === f && this.entries.get(r.key) === r && r.fiber === C && (this.refreshing.delete(r), r.fiber = null, n.isFailure(t) && !e.hasInterruptsOnly(t.cause))) {
700
+ let n = N(m(t.cause));
701
+ r.state.baseRevision === -1 && (r.state.baseError = n, this.invalidate(r));
702
+ let a = e.findErrorOption(t.cause), o = i.isSome(a) ? b(a.value, "handler") : "unknown";
703
+ o === "transport" && (r.recoveryTimer !== null && clearTimeout(r.recoveryTimer), r.recoveryTimer = null, r.resumeAfterTransportOpen = !0, r.recoveryPhase = "awaiting-protocol", r.lastTransportFailureAt = Date.now(), this.diagnose("subscription.transport-failed", r)), this.errorBus && this.errorBus.emit({
704
+ source: "subscription",
705
+ tag: r.tag ?? r.key,
706
+ error: n,
707
+ kind: o,
708
+ outcome: "not-applicable",
709
+ ...r.traceId === void 0 ? {} : { traceId: r.traceId }
710
+ });
711
+ }
712
+ });
713
+ }
714
+ sourceTables(e) {
715
+ return e.source === void 0 ? [] : typeof e.source == "string" ? [e.source] : e.source;
716
+ }
717
+ addIndex(e, t, n) {
718
+ let r = e.get(t);
719
+ if (r === void 0) {
720
+ e.set(t, /* @__PURE__ */ new Set([n]));
721
+ return;
722
+ }
723
+ if (e === this.entriesByMutation) {
724
+ r.add(n);
725
+ return;
726
+ }
727
+ let i = r.size;
728
+ r.add(n), r.size !== i && this.orderedMemberships.delete(r);
729
+ }
730
+ removeIndex(e, t, n) {
731
+ let r = e.get(t);
732
+ r?.delete(n) && e !== this.entriesByMutation && this.orderedMemberships.delete(r), r?.size === 0 && e.delete(t);
733
+ }
734
+ orderedEntries(e, t = !1) {
735
+ if (e === void 0) return [];
736
+ let n = t ? this.orderedMemberships.get(e) : void 0;
737
+ if (n !== void 0) return n;
738
+ let r = [...e].sort((e, t) => this.entryOrder.get(e) - this.entryOrder.get(t));
739
+ return t && this.orderedMemberships.set(e, r), r;
740
+ }
741
+ indexSource(e) {
742
+ for (let t of this.sourceTables(e)) this.addIndex(this.entriesByTable, t, e), this.tableRows.delete(t);
743
+ }
744
+ appendPatch(e, t) {
745
+ if (e.state.patches.push(t), t.canReuse === void 0 && delete e.state.previewPrefix, this.entries.get(e.key) !== e) return;
746
+ let n = this.patchMemberships.get(e);
747
+ 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));
748
+ }
749
+ replacePatches(e, t) {
750
+ t.length !== e.state.patches.length && (e.state.patches = t, delete e.state.previewPrefix, this.entries.get(e.key) === e && this.indexPatches(e));
751
+ }
752
+ indexPatches(e) {
753
+ let t = this.patchMemberships.get(e) ?? /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set();
754
+ for (let t of e.state.patches) n.add(t.mutationId);
755
+ for (let r of t) n.has(r) || this.removeIndex(this.entriesByMutation, r, e);
756
+ for (let r of n) t.has(r) || this.addIndex(this.entriesByMutation, r, e);
757
+ this.patchMemberships.set(e, n);
758
+ }
759
+ registerEntry(e) {
760
+ 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);
761
+ }
762
+ unindexEntry(e) {
763
+ e.tag !== void 0 && this.removeIndex(this.entriesByTag, e.tag, e);
764
+ for (let t of this.sourceTables(e)) this.removeIndex(this.entriesByTable, t, e);
765
+ for (let t of this.patchMemberships.get(e) ?? []) this.removeIndex(this.entriesByMutation, t, e);
766
+ this.patchMemberships.delete(e);
767
+ }
768
+ invalidate(e) {
769
+ e.state.cachedSnapshot = null;
770
+ for (let t of this.sourceTables(e)) this.tableRows.delete(t);
771
+ let t = /* @__PURE__ */ new Set();
772
+ for (let n of this.sourceTables(e)) for (let e of this.tableListeners.get(n) ?? []) t.add(e);
773
+ for (let e of t) try {
774
+ e();
775
+ } catch {}
776
+ for (let t of e.subscribers) t();
777
+ this.onChangeHook?.(e.key);
778
+ for (let e of this.anyListeners) try {
779
+ e();
780
+ } catch {}
781
+ }
782
+ rowsOf(e) {
783
+ let t = this.tableRows.get(e);
784
+ if (t !== void 0) return t;
785
+ let n = /* @__PURE__ */ new Map();
786
+ for (let t of this.orderedEntries(this.entriesByTable.get(e), !0)) {
787
+ if (t.source !== e && !(Array.isArray(t.source) && t.source.length === 1 && t.source[0] === e)) continue;
788
+ let r = this.getSnapshot(t.key).data;
789
+ if (Array.isArray(r)) for (let e of r) {
790
+ if (typeof e != "object" || !e) continue;
791
+ let t = e.id;
792
+ if (t === void 0) continue;
793
+ let r = n.get(t);
794
+ (r === void 0 || r.optimistic === !0 || e.optimistic !== !0) && n.set(t, e);
795
+ }
796
+ }
797
+ let r = [...n.values()];
798
+ return this.tableRows.set(e, r), r;
799
+ }
800
+ subscribeTable(e, t) {
801
+ let n = this.tableListeners.get(e);
802
+ n === void 0 && (n = /* @__PURE__ */ new Set(), this.tableListeners.set(e, n)), n.add(t);
803
+ let r = n;
804
+ return () => {
805
+ r.delete(t), r.size === 0 && this.tableListeners.get(e) === r && this.tableListeners.delete(e);
806
+ };
807
+ }
808
+ subscribeAny(e) {
809
+ return this.anyListeners.add(e), () => {
810
+ this.anyListeners.delete(e);
811
+ };
812
+ }
813
+ getSnapshot(e) {
814
+ let t = this.entries.get(e);
815
+ if (!t) return se;
816
+ if (t.state.cachedSnapshot !== null) return t.state.cachedSnapshot;
817
+ let n = t.state.base, r = t.state.patches;
818
+ if (n !== void 0 && r.length > 0) {
819
+ let e = t.state.previewBase, i = e?.base === n ? e.eligible : V(n);
820
+ t.state.previewBase = {
821
+ base: n,
822
+ eligible: i
823
+ };
824
+ 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;
825
+ s > 0 && (n = o.data);
826
+ for (let e = s; e < r.length; e++) n = r[e].reducer(n);
827
+ a ? t.state.previewPrefix = {
828
+ base: t.state.base,
829
+ count: r.length,
830
+ data: n
831
+ } : delete t.state.previewPrefix;
832
+ } else delete t.state.previewPrefix;
833
+ let i = {
834
+ data: n,
835
+ revision: t.state.baseRevision,
836
+ emittedAt: t.state.baseEmittedAt,
837
+ error: t.state.baseError,
838
+ pendingPatches: t.state.patches.length
839
+ };
840
+ return t.state.cachedSnapshot = i, i;
841
+ }
842
+ unsubscribe(e, t) {
843
+ let n = this.entries.get(e);
844
+ n && (n.subscribers.delete(t), !(n.subscribers.size > 0) && this.scheduleEviction(n));
845
+ }
846
+ scheduleEviction(e) {
847
+ e.evictionTimer !== null && clearTimeout(e.evictionTimer), e.evictionTimer = setTimeout(() => {
848
+ let n = this.entries.get(e.key);
849
+ n && n.subscribers.size === 0 && (n.rowPatchApplier?.reset(), delete n.rowPatchApplier, n.recoveryTimer !== null && clearTimeout(n.recoveryTimer), n.fiber && t.runFork(r.interrupt(n.fiber)), this.entries.delete(e.key), this.unindexEntry(n), this.invalidate(n));
850
+ }, this.inactiveTtlMs);
851
+ }
852
+ }, ye = class extends H {
853
+ subscribe(e, t, n, r, i = {}) {
854
+ return {
855
+ getSnapshot: () => this.peek(e),
856
+ unsubscribe: () => {}
857
+ };
858
+ }
859
+ }, U = /* @__PURE__ */ new Set(), W = (e) => {
860
+ for (let t of U) try {
861
+ t(e);
862
+ } catch {}
863
+ }, be = (e) => (U.add(e), () => {
864
+ U.delete(e);
865
+ }), xe = (e, t) => {
866
+ W({
867
+ error: e,
868
+ source: "manual",
869
+ ...t ? { context: t } : {}
870
+ });
871
+ }, Se = class {
872
+ #e = /* @__PURE__ */ new Set();
873
+ #t = /* @__PURE__ */ new Set();
874
+ on(e) {
875
+ return this.#e.add(e), () => {
876
+ this.#e.delete(e);
877
+ };
878
+ }
879
+ emit(e) {
880
+ for (let t of this.#e) try {
881
+ t(e);
882
+ } catch {}
883
+ W({
884
+ error: e.error,
885
+ source: `rpc.${e.source}`,
886
+ context: {
887
+ rpcTag: e.tag,
888
+ rpcErrorKind: e.kind,
889
+ ...e.affectsTransport === void 0 ? {} : { affectsTransport: e.affectsTransport },
890
+ ...e.outcome === void 0 ? {} : { rpcCallOutcome: e.outcome },
891
+ ...e.traceId === void 0 ? {} : { traceId: e.traceId }
892
+ }
893
+ });
894
+ }
895
+ onSuccess(e) {
896
+ return this.#t.add(e), () => {
897
+ this.#t.delete(e);
898
+ };
899
+ }
900
+ emitSuccess(e) {
901
+ for (let t of this.#t) try {
902
+ t(e);
903
+ } catch {}
904
+ }
905
+ }, Ce = Symbol.for("voltro.client.connectivity"), we = () => {
906
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set(), n = () => {
907
+ for (let e of t) try {
908
+ e();
909
+ } catch {}
910
+ };
911
+ return {
912
+ online: (t) => {
913
+ let n = [];
914
+ if (t === void 0) for (let t of e.values()) for (let e of t) n.push(e);
915
+ else for (let r of e.get(t) ?? []) n.push(r);
916
+ if (n.length !== 0) return n.some((e) => e.connected());
917
+ },
918
+ subscribe: (e) => (t.add(e), () => {
919
+ t.delete(e);
920
+ }),
921
+ register: (t, r) => {
922
+ let i = e.get(t) ?? /* @__PURE__ */ new Set();
923
+ return i.add(r), e.set(t, i), n(), () => {
924
+ i.delete(r), i.size === 0 && e.delete(t), n();
925
+ };
926
+ },
927
+ notify: n
928
+ };
929
+ }, G = () => {
930
+ let e = globalThis;
931
+ return e[Ce] ??= we();
932
+ }, Te = (e, t) => G().register(e, { connected: t }), K = () => {
933
+ G().notify();
934
+ }, Ee = () => G(), q = (e, t, n, r) => Math.min(r, Math.max(n, e === void 0 || !Number.isFinite(e) ? t : e)), De = (e) => {
935
+ let t = Math.trunc(q(e?.maxMs, 5e3, 50, 6e4));
936
+ return {
937
+ initialMs: Math.trunc(q(e?.initialMs, 0, 0, t)),
938
+ thenMs: Math.trunc(q(e?.thenMs, 500, 50, t)),
939
+ factor: q(e?.factor, 1.5, 1, 10),
940
+ maxMs: t
941
+ };
942
+ }, J = (e, t) => t <= 1 ? e.initialMs : Math.min(e.maxMs, e.thenMs * e.factor ** (t - 2)), Oe = (e, n) => {
943
+ let r = 0;
944
+ return {
945
+ reset: () => {
946
+ r = 0;
947
+ },
948
+ schedule: a.forever.pipe(a.addDelay(() => t.sync(() => {
949
+ let t = J(e, ++r);
950
+ return n(r, t), t;
951
+ })))
952
+ };
953
+ }, Y = (e, t, n, r) => e === void 0 || !Number.isFinite(e) ? t : Math.min(r, Math.max(n, Math.trunc(e))), X = (e) => ({
954
+ graceMs: Y(e?.graceMs, 1500, 0, 3e4),
955
+ retry: De(e?.retry),
956
+ maxPendingMutations: Y(e?.maxPendingMutations, 32, 0, 256),
957
+ replayWindowMs: Y(e?.replayWindowMs, 1e4, 250, 6e4),
958
+ capabilitiesUrl: e?.capabilitiesUrl
959
+ }), Z = Object.freeze({
960
+ rawTransport: "connected",
961
+ status: "connected",
962
+ failureCount: 0,
963
+ lastFailureAt: void 0,
964
+ failedSubscriptions: Object.freeze([]),
965
+ pendingMutationReplays: 0,
966
+ mutationReplay: "unknown"
967
+ }), Q = class {
968
+ #e;
969
+ #t;
970
+ #n;
971
+ #r = /* @__PURE__ */ new Set();
972
+ #i = /* @__PURE__ */ new Set();
973
+ #a = /* @__PURE__ */ new Set();
974
+ #o = /* @__PURE__ */ new Set();
975
+ #s = /* @__PURE__ */ new Set();
976
+ #c = "connected";
977
+ #l = "connected";
978
+ #u = 0;
979
+ #d;
980
+ #f = 0;
981
+ #p = "unknown";
982
+ #m = -1;
983
+ #h = 0;
984
+ #g = new AbortController();
985
+ #_;
986
+ #v;
987
+ #y = !1;
988
+ #b;
989
+ #x;
990
+ constructor(e, t, n) {
991
+ this.#e = e, this.#t = X(t), this.#n = {
992
+ now: n?.now ?? Date.now,
993
+ setTimeout: n?.setTimeout ?? ((e, t) => setTimeout(e, t)),
994
+ clearTimeout: n?.clearTimeout ?? ((e) => clearTimeout(e))
995
+ }, this.#b = this.#S(), this.#x = Te(e, () => this.#c === "connected");
996
+ }
997
+ get options() {
998
+ return this.#t;
999
+ }
1000
+ get subjectSignal() {
1001
+ return this.#g.signal;
1002
+ }
1003
+ getSnapshot = () => this.#b;
1004
+ getServerSnapshot = () => Z;
1005
+ subscribe = (e) => (this.#r.add(e), () => {
1006
+ this.#r.delete(e);
1007
+ });
1008
+ onVisibleError(e) {
1009
+ return this.#i.add(e), () => {
1010
+ this.#i.delete(e);
1011
+ };
1012
+ }
1013
+ #S() {
1014
+ return {
1015
+ rawTransport: this.#c,
1016
+ status: this.#l,
1017
+ failureCount: this.#u,
1018
+ lastFailureAt: this.#d,
1019
+ failedSubscriptions: [...this.#s].sort(),
1020
+ pendingMutationReplays: this.#f,
1021
+ mutationReplay: this.#p
1022
+ };
1023
+ }
1024
+ #C() {
1025
+ let e = this.#b.rawTransport !== this.#c;
1026
+ this.#b = this.#S();
1027
+ for (let e of this.#r) try {
1028
+ e();
1029
+ } catch {}
1030
+ e && K(), j(this.#e, "recovery.state", {
1031
+ rawTransport: this.#b.rawTransport,
1032
+ status: this.#b.status,
1033
+ failureCount: this.#b.failureCount,
1034
+ failedSubscriptions: this.#b.failedSubscriptions.length,
1035
+ pendingMutationReplays: this.#b.pendingMutationReplays,
1036
+ mutationReplay: this.#b.mutationReplay
1037
+ });
1038
+ }
1039
+ #w(e) {
1040
+ for (let t of this.#i) try {
1041
+ t(e);
1042
+ } catch {}
1043
+ }
1044
+ #T() {
1045
+ if (this.#l === "connected") {
1046
+ if (this.#l = this.#t.graceMs === 0 ? "degraded" : "recovering", this.#t.graceMs === 0) {
1047
+ this.#v !== void 0 && (this.#y = !0, this.#w(this.#v));
1048
+ return;
1049
+ }
1050
+ this.#_ = this.#n.setTimeout(() => {
1051
+ this.#_ = void 0, this.#l === "recovering" && (this.#l = "degraded", this.#v !== void 0 && (this.#y = !0, this.#w(this.#v)), this.#C());
1052
+ }, this.#t.graceMs);
1053
+ }
1054
+ }
1055
+ #E() {
1056
+ this.#c !== "connected" || this.#s.size > 0 || (this.#_ !== void 0 && (this.#n.clearTimeout(this.#_), this.#_ = void 0), this.#l = "connected", this.#u = 0, this.#v = void 0, this.#y = !1);
1057
+ }
1058
+ transportIssue() {
1059
+ this.#c = "disconnected", this.#u += 1, this.#d = this.#n.now(), this.#T(), this.#C();
1060
+ }
1061
+ protocolReady() {
1062
+ this.#c = "connected";
1063
+ for (let e of this.#a) e();
1064
+ this.#a.clear(), this.#E(), this.#C();
1065
+ }
1066
+ observeError(e) {
1067
+ if (e.kind !== "transport" || e.affectsTransport !== !1) {
1068
+ if (e.kind !== "transport") {
1069
+ this.#w(e);
1070
+ return;
1071
+ }
1072
+ this.#v === void 0 && (this.#v = e), e.source === "subscription" && this.#s.add(e.tag), this.#c !== "disconnected" && (this.#c = "disconnected", this.#u += 1, this.#d = this.#n.now()), this.#T(), this.#l === "degraded" && !this.#y && (this.#y = !0, this.#w(e)), this.#C();
1073
+ }
1074
+ }
1075
+ observeSuccess(e) {
1076
+ e.source === "subscription" && this.#s.delete(e.tag), this.#E(), this.#C();
1077
+ }
1078
+ reportExternalSuccess() {
1079
+ this.#c = "connected";
1080
+ for (let e of this.#a) e();
1081
+ this.#a.clear(), this.#E(), this.#C();
1082
+ }
1083
+ resetForSubjectChange(e = 0) {
1084
+ this.#_ !== void 0 && this.#n.clearTimeout(this.#_), this.#_ = void 0, this.#c = "disconnected", this.#l = "connected", this.#u = 0, this.#d = void 0, this.#s.clear(), this.#v = void 0, this.#y = !1, this.#p = "unknown", this.#h += 1;
1085
+ let t = this.#g;
1086
+ this.#g = new AbortController(), t.abort(), this.#m = e;
1087
+ for (let e of this.#o) e(!1);
1088
+ this.#o.clear();
1089
+ for (let e of this.#a) e();
1090
+ this.#a.clear(), this.#T(), this.#C();
1091
+ }
1092
+ setMutationReplaySupported(e, t = 0) {
1093
+ if (!(t < this.#m)) {
1094
+ this.#m = t, this.#p = e ? "enabled" : "disabled";
1095
+ for (let t of this.#o) t(e);
1096
+ this.#o.clear(), this.#C();
1097
+ }
1098
+ }
1099
+ replayWindowRemaining(e) {
1100
+ return Math.max(0, this.#t.replayWindowMs - (this.#n.now() - e));
1101
+ }
1102
+ waitForMutationReplaySupport(e) {
1103
+ if (this.#p !== "unknown") return Promise.resolve(this.#p === "enabled");
1104
+ let t = this.#t.replayWindowMs - (this.#n.now() - e);
1105
+ return t <= 0 ? Promise.resolve(!1) : new Promise((e) => {
1106
+ let n = !1, r, i = (t) => {
1107
+ n || (n = !0, this.#o.delete(i), r !== void 0 && this.#n.clearTimeout(r), e(t));
1108
+ };
1109
+ this.#o.add(i), r = this.#n.setTimeout(() => i(!1), t);
1110
+ });
1111
+ }
1112
+ reserveMutationReplay(e) {
1113
+ if (this.#p === "disabled" || this.#n.now() - e > this.#t.replayWindowMs || this.#f >= this.#t.maxPendingMutations) return;
1114
+ this.#f += 1, this.#C();
1115
+ let t = this.#h, n = !1;
1116
+ return {
1117
+ isValid: () => !n && t === this.#h && this.#p === "enabled" && this.#c === "connected" && this.#n.now() - e <= this.#t.replayWindowMs,
1118
+ release: () => {
1119
+ n || (n = !0, --this.#f, this.#C());
1120
+ }
1121
+ };
1122
+ }
1123
+ waitForProtocolReady(e) {
1124
+ if (this.#c === "connected") return Promise.resolve(!0);
1125
+ let t = this.#t.replayWindowMs - (this.#n.now() - e);
1126
+ return t <= 0 ? Promise.resolve(!1) : new Promise((e) => {
1127
+ let n = !1, r = (t) => {
1128
+ n || (n = !0, this.#a.delete(i), this.#n.clearTimeout(a), e(t && this.#c === "connected"));
1129
+ }, i = () => r(!0);
1130
+ this.#a.add(i);
1131
+ let a = this.#n.setTimeout(() => r(!1), t);
1132
+ });
1133
+ }
1134
+ dispose() {
1135
+ this.#x(), this.#g.abort(), this.#_ !== void 0 && this.#n.clearTimeout(this.#_), this.#_ = void 0;
1136
+ for (let e of this.#a) e();
1137
+ this.#a.clear();
1138
+ for (let e of this.#o) e(!1);
1139
+ this.#o.clear(), this.#r.clear(), this.#i.clear();
1140
+ }
1141
+ }, $ = /* @__PURE__ */ new WeakMap(), ke = (e, t, n) => {
1142
+ let r = $.get(e);
1143
+ if (r !== void 0) return r;
1144
+ let i = new Q(t, n);
1145
+ return e.on((e) => i.observeError(e)), typeof e.onSuccess == "function" && e.onSuccess((e) => i.observeSuccess(e)), $.set(e, i), i;
1146
+ }, Ae = (e, t) => {
1147
+ let n = t.split("."), r = e, i = 0;
1148
+ for (let e = 0; e < n.length; e++) {
1149
+ let a = n[e];
1150
+ if (r === null || typeof r != "object" && typeof r != "function") throw Error(`@voltro/client: rpc tag ${JSON.stringify(t)} not reachable on client. Stopped at segment ${JSON.stringify(a)}. The api's descriptor map is likely out of sync with the rpc group; restart \`voltro dev\` to regenerate.`);
1151
+ let o = r;
1152
+ if (a in o) {
1153
+ r = o[a], i += a.length + 1;
1154
+ continue;
1155
+ }
1156
+ let s = t.slice(i);
1157
+ if (s in o) {
1158
+ r = o[s];
1159
+ break;
1160
+ }
1161
+ throw Error(`@voltro/client: rpc tag ${JSON.stringify(t)} not reachable on client. Stopped at segment ${JSON.stringify(a)}. The api's descriptor map is likely out of sync with the rpc group; restart \`voltro dev\` to regenerate.`);
1162
+ }
1163
+ if (typeof r != "function") throw Error(`@voltro/client: rpc tag ${JSON.stringify(t)} did not resolve to a callable method.`);
1164
+ return r;
1165
+ }, je = async (t, r, a) => {
1166
+ let o = await t.runPromiseExit(r, a?.signal === void 0 ? void 0 : { signal: a.signal });
1167
+ if (n.isSuccess(o)) return o.value;
1168
+ let s = m(o.cause), c = e.findErrorOption(o.cause);
1169
+ throw y(s, i.isSome(c) ? b(c.value, "handler") : "unknown");
1170
+ };
1171
+ //#endregion
1172
+ export { p as A, oe as C, _ as D, g as E, m as O, j as S, b as T, F as _, ke as a, re as b, J as c, W as d, xe as f, M as g, H as h, Q as i, f as k, Ee as l, ye as m, Ae as n, X as o, be as p, Z as r, Oe as s, je as t, Se as u, ae as v, y as w, ne as x, ie as y };