@voltro/client 0.70.0 → 0.71.1

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