@voltro/client 0.83.0 → 0.84.0

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