@facto-to/notifications 0.0.0-stage → 0.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js ADDED
@@ -0,0 +1,1106 @@
1
+ const me = "sse_auth_header_required", Ae = "sse_stream_lagged", ve = "sse_http_error", Le = "sse_session_revoked", he = "invalid_multitab_scope";
2
+ class Y extends Error {
3
+ code = he;
4
+ field;
5
+ constructor(n, a) {
6
+ super(a), this.name = "InvalidMultiTabScopeError", this.field = n;
7
+ }
8
+ }
9
+ class te extends Error {
10
+ code;
11
+ status;
12
+ constructor(n, a, I) {
13
+ super(
14
+ a,
15
+ I?.cause !== void 0 ? { cause: I.cause } : void 0
16
+ ), this.name = "RealtimeStreamError", this.code = n, this.status = I?.status;
17
+ }
18
+ }
19
+ const ge = /^\d+$/;
20
+ function ue(e) {
21
+ let n = !0, a = !1, I = "", S = [], E, A, x, H;
22
+ function V() {
23
+ if (!(S.length > 0) && E === void 0) {
24
+ A = void 0, x = void 0;
25
+ return;
26
+ }
27
+ const r = {
28
+ event: E !== void 0 && E !== "" ? E : "message",
29
+ data: S.join(`
30
+ `)
31
+ };
32
+ A !== void 0 && (r.id = A), E !== void 0 && (r.explicitEvent = E), x !== void 0 && (r.retryMs = x), S = [], E = void 0, A = void 0, x = void 0, e.onFrame(r);
33
+ }
34
+ function M(s) {
35
+ if (s === "") {
36
+ V();
37
+ return;
38
+ }
39
+ if (s.startsWith(":")) {
40
+ e.onComment?.(s.slice(1));
41
+ return;
42
+ }
43
+ const o = s.indexOf(":");
44
+ let r, c;
45
+ switch (o === -1 ? (r = s, c = "") : (r = s.slice(0, o), c = s.slice(o + 1), c.startsWith(" ") && (c = c.slice(1))), r) {
46
+ case "event":
47
+ E = c;
48
+ break;
49
+ case "data":
50
+ S.push(c);
51
+ break;
52
+ case "id":
53
+ c.includes("\0") || (A = c, H = c, e.onId?.(c));
54
+ break;
55
+ case "retry":
56
+ if (ge.test(c)) {
57
+ const v = Number.parseInt(c, 10);
58
+ Number.isSafeInteger(v) && (x = v, e.onRetry?.(v));
59
+ }
60
+ break;
61
+ }
62
+ }
63
+ function d(s) {
64
+ if (!s) return;
65
+ let o = s;
66
+ n && (n = !1, o.startsWith("\uFEFF") && (o = o.slice(1)));
67
+ let r = 0;
68
+ a && (a = !1, o.startsWith(`
69
+ `) && (r = 1));
70
+ for (let c = r; c < o.length; c += 1) {
71
+ const v = o.charCodeAt(c);
72
+ if (v === 10) {
73
+ const g = I + o.slice(r, c);
74
+ I = "", r = c + 1, M(g);
75
+ } else if (v === 13) {
76
+ const g = I + o.slice(r, c);
77
+ I = "", c + 1 < o.length ? o.charCodeAt(c + 1) === 10 && (c += 1) : a = !0, r = c + 1, M(g);
78
+ }
79
+ }
80
+ r < o.length && (I += o.slice(r));
81
+ }
82
+ function f() {
83
+ n = !0, a = !1, I = "", S = [], E = void 0, A = void 0, x = void 0;
84
+ }
85
+ return {
86
+ feed: d,
87
+ reset: f,
88
+ getLastEventId: () => H
89
+ };
90
+ }
91
+ function ke(e) {
92
+ const n = [];
93
+ return ue({
94
+ onFrame: (I) => n.push(I)
95
+ }).feed(e), n;
96
+ }
97
+ class Ie {
98
+ capacity;
99
+ entries = /* @__PURE__ */ new Set();
100
+ constructor(n = 500) {
101
+ this.capacity = Number.isFinite(n) && n >= 1 ? Math.floor(n) : 500;
102
+ }
103
+ /**
104
+ * Records `key` in the LRU set.
105
+ * Returns `true` if `key` was newly added, or `false` if it was already seen.
106
+ */
107
+ remember(n) {
108
+ if (this.entries.has(n))
109
+ return this.entries.delete(n), this.entries.add(n), !1;
110
+ if (this.entries.add(n), this.entries.size > this.capacity) {
111
+ const a = this.entries.values().next().value;
112
+ a !== void 0 && this.entries.delete(a);
113
+ }
114
+ return !0;
115
+ }
116
+ has(n) {
117
+ return this.entries.has(n);
118
+ }
119
+ delete(n) {
120
+ return this.entries.delete(n);
121
+ }
122
+ clear() {
123
+ this.entries.clear();
124
+ }
125
+ get size() {
126
+ return this.entries.size;
127
+ }
128
+ }
129
+ const ye = /* @__PURE__ */ new Set([
130
+ "consumer",
131
+ "partner",
132
+ "console"
133
+ ]);
134
+ function ne(e, n) {
135
+ if (typeof n != "string" || n.trim().length === 0)
136
+ throw new Y(
137
+ e,
138
+ `Structured multi-tab scope requires a non-empty "${e}" segment.`
139
+ );
140
+ return n.trim();
141
+ }
142
+ function be(e) {
143
+ if (typeof e == "number") {
144
+ if (!Number.isFinite(e))
145
+ throw new Y(
146
+ "authVersion",
147
+ 'Structured multi-tab scope requires a finite numeric or non-empty string "authVersion" segment.'
148
+ );
149
+ return String(e);
150
+ }
151
+ if (typeof e == "string" && e.trim().length > 0)
152
+ return e.trim();
153
+ throw new Y(
154
+ "authVersion",
155
+ 'Structured multi-tab scope requires a finite numeric or non-empty string "authVersion" segment.'
156
+ );
157
+ }
158
+ function pe(e) {
159
+ if (!e || typeof e != "object")
160
+ throw new Y(
161
+ "env",
162
+ "Structured multi-tab scope must be a non-null object."
163
+ );
164
+ const n = ne("env", e.env), a = ne("surface", e.surface);
165
+ if (!ye.has(a))
166
+ throw new Y(
167
+ "surface",
168
+ 'Structured multi-tab scope "surface" must be one of consumer, partner, or console.'
169
+ );
170
+ const I = ne("subjectId", e.subjectId), S = ne("tenantOrTarget", e.tenantOrTarget), E = be(e.authVersion);
171
+ return [
172
+ "v1",
173
+ `env=${encodeURIComponent(n)}`,
174
+ `surface=${encodeURIComponent(a)}`,
175
+ `sub=${encodeURIComponent(I)}`,
176
+ `tenant=${encodeURIComponent(S)}`,
177
+ `auth=${encodeURIComponent(E)}`
178
+ ].join("|");
179
+ }
180
+ function Ee(e) {
181
+ for (const n of [
182
+ "inboxRevision",
183
+ "inbox_revision",
184
+ "watermarkRevision",
185
+ "watermark_revision",
186
+ "revision"
187
+ ]) {
188
+ const a = e[n];
189
+ if (typeof a == "number" && Number.isFinite(a) && a >= 0)
190
+ return Math.floor(a);
191
+ }
192
+ return null;
193
+ }
194
+ function se(e) {
195
+ const n = (e.explicitEvent ?? e.event ?? "message").trim() || "message";
196
+ let a = null;
197
+ const I = e.data.trim();
198
+ if (I.length > 0)
199
+ try {
200
+ const S = JSON.parse(I);
201
+ S && typeof S == "object" && !Array.isArray(S) && (a = Ee(S));
202
+ } catch {
203
+ a = null;
204
+ }
205
+ return { inboxRevision: a, eventKind: n };
206
+ }
207
+ function Re(e) {
208
+ const n = e.trim();
209
+ if (!n) return "session_revoked";
210
+ try {
211
+ const a = JSON.parse(n);
212
+ if (a && typeof a == "object" && !Array.isArray(a)) {
213
+ const I = a, S = typeof I.code == "string" && I.code.trim().length > 0 ? I.code.trim() : typeof I.reason == "string" && I.reason.trim().length > 0 ? I.reason.trim() : null;
214
+ if (S) return JSON.stringify({ code: S });
215
+ }
216
+ } catch {
217
+ if (/^[a-z0-9_:-]{1,64}$/i.test(n))
218
+ return n;
219
+ }
220
+ return "session_revoked";
221
+ }
222
+ let oe = 0;
223
+ function Se() {
224
+ oe += 1;
225
+ const e = String(oe).padStart(8, "0"), n = Math.random().toString(36).slice(2, 10);
226
+ return `${e}-${n}`;
227
+ }
228
+ function Me(e, n) {
229
+ const a = `facto:notifications:stream:${e}`;
230
+ return n ? n(a) : typeof BroadcastChannel < "u" ? new BroadcastChannel(a) : null;
231
+ }
232
+ function we(e) {
233
+ const {
234
+ openLeaderStream: n,
235
+ handlers: a,
236
+ broadcastChannelFactory: I,
237
+ extractInvalidationHint: S
238
+ } = e, E = e.scope ? pe(e.scope) : e.scopeKey && e.scopeKey.trim().length > 0 ? e.scopeKey.trim() : (() => {
239
+ throw new Y(
240
+ "subjectId",
241
+ "Multi-tab coordinator requires a valid StructuredMultiTabScope or non-empty scopeKey."
242
+ );
243
+ })(), A = e.disclosureMode ?? (e.scope ? "minimal-invalidation" : "full-frame"), x = Math.max(10, e.electionTimeoutMs ?? 50), H = Math.max(50, e.heartbeatIntervalMs ?? 5e3), V = H * 3, M = Me(E, I);
244
+ if (!M)
245
+ return n(e.initialLastEventId, a);
246
+ const d = Se();
247
+ let f = "electing", s = null, o = "idle", r = e.initialLastEventId, c = !1, v = !1, g = null, F = null, C = null, U = null, N = null, L = !1;
248
+ function B(h) {
249
+ o !== h && (o = h, a.onStatusChange?.(h));
250
+ }
251
+ function D() {
252
+ C !== null && (clearTimeout(C), C = null);
253
+ }
254
+ function q() {
255
+ U !== null && (clearInterval(U), U = null);
256
+ }
257
+ function k() {
258
+ N !== null && (clearTimeout(N), N = null);
259
+ }
260
+ function w(h) {
261
+ if (!c)
262
+ try {
263
+ M.postMessage(h);
264
+ } catch {
265
+ }
266
+ }
267
+ function O() {
268
+ k(), !(c || v || f !== "follower") && (N = setTimeout(() => {
269
+ c || v || f !== "follower" || (s = null, T(x));
270
+ }, V));
271
+ }
272
+ function j() {
273
+ if (q(), F) {
274
+ const h = F;
275
+ F = null, h();
276
+ }
277
+ if (g) {
278
+ const h = g;
279
+ g = null, h.close();
280
+ }
281
+ }
282
+ function z() {
283
+ const h = g?.getLastEventId() ?? r;
284
+ r = h, D(), k(), q(), F = null;
285
+ const t = g;
286
+ g = null, f = "inactive", s = null, L = !1, t && t.close();
287
+ const y = o !== "closed";
288
+ o = "closed", w({
289
+ type: "leader-release",
290
+ leaderId: d,
291
+ lastEventId: h
292
+ }), y && o === "closed" && a.onStatusChange?.("closed");
293
+ }
294
+ function J(h, t) {
295
+ v || (v = !0, f = "inactive", s = null, D(), k(), t && w({
296
+ type: "stream-revoked",
297
+ leaderId: d,
298
+ rawData: A === "minimal-invalidation" ? Re(h) : h
299
+ }), j(), B("revoked"), a.onSessionRevoked?.(h));
300
+ }
301
+ function p() {
302
+ if (c || v || f === "leader" || f === "inactive") return;
303
+ D(), k(), f = "leader", s = d, L = !1, w({
304
+ type: "leader-announce",
305
+ leaderId: d,
306
+ status: "connecting",
307
+ lastEventId: r,
308
+ revoked: !1
309
+ });
310
+ let h = !1, t = !1;
311
+ F = () => {
312
+ h = !0;
313
+ };
314
+ const y = () => !c && !v && !h && !t && f === "leader", u = n(r, {
315
+ onOpen: () => {
316
+ if (!y()) return;
317
+ r = g?.getLastEventId() ?? r, w({ type: "stream-open", leaderId: d, lastEventId: r }), a.onOpen?.();
318
+ },
319
+ onFrame: (l) => {
320
+ if (y()) {
321
+ if (l.id !== void 0 && (r = l.id), A === "minimal-invalidation") {
322
+ const m = S ? S(l) : se(l);
323
+ if (m !== null) {
324
+ const b = m.eventKind?.trim() || (l.explicitEvent ?? l.event ?? "message").trim() || "message";
325
+ w({
326
+ type: "inbox-invalidation",
327
+ leaderId: d,
328
+ scopeKey: E,
329
+ inboxRevision: m.inboxRevision ?? null,
330
+ eventKind: b,
331
+ ...r !== void 0 ? { lastEventId: r } : {}
332
+ });
333
+ }
334
+ } else
335
+ w({
336
+ type: "stream-frame",
337
+ leaderId: d,
338
+ frame: l,
339
+ lastEventId: r
340
+ });
341
+ a.onFrame(l);
342
+ }
343
+ },
344
+ onLagged: (l, m) => {
345
+ y() && (w({
346
+ type: "stream-lagged",
347
+ leaderId: d,
348
+ droppedCount: l,
349
+ rawData: A === "minimal-invalidation" ? "" : m,
350
+ lastEventId: r
351
+ }), a.onLagged?.(l, m));
352
+ },
353
+ onResync: (l) => {
354
+ y() && (w({
355
+ type: "stream-resync",
356
+ leaderId: d,
357
+ reason: l,
358
+ lastEventId: r
359
+ }), a.onResync?.(l));
360
+ },
361
+ onSessionRevoked: (l) => {
362
+ c || v || h || J(l, !0);
363
+ },
364
+ onStatusChange: (l) => {
365
+ if (y()) {
366
+ if (l === "closed") {
367
+ t = !0, z();
368
+ return;
369
+ }
370
+ B(l), w({
371
+ type: "stream-status",
372
+ leaderId: d,
373
+ status: l,
374
+ lastEventId: r
375
+ });
376
+ }
377
+ },
378
+ onTransportError: (l) => {
379
+ c || v || h || a.onTransportError?.(l);
380
+ }
381
+ });
382
+ if (!y()) {
383
+ u.close();
384
+ return;
385
+ }
386
+ g = u, q(), U = setInterval(() => {
387
+ if (!y() || o === "closed") {
388
+ q();
389
+ return;
390
+ }
391
+ r = g?.getLastEventId() ?? r, w({
392
+ type: "leader-heartbeat",
393
+ leaderId: d,
394
+ status: o,
395
+ lastEventId: r
396
+ });
397
+ }, H);
398
+ }
399
+ function K(h, t, y) {
400
+ D(), f === "leader" && j(), f = "follower", s = h, y !== void 0 && (r = y), O(), t !== "idle" && (B(t), t === "open" && !L && (L = !0, a.onOpen?.()));
401
+ }
402
+ function T(h) {
403
+ c || v || f === "inactive" || (D(), k(), f = "electing", s = null, L = !1, B("connecting"), w({ type: "leader-query", tabId: d }), C = setTimeout(() => {
404
+ C = null, !(c || v || f !== "electing") && p();
405
+ }, h));
406
+ }
407
+ function R(h) {
408
+ if (c || v) return;
409
+ const t = h.data;
410
+ if (!(!t || typeof t != "object" || typeof t.type != "string"))
411
+ switch (t.type) {
412
+ case "leader-query": {
413
+ if (t.tabId === d) return;
414
+ f === "leader" && o !== "closed" ? w({
415
+ type: "leader-announce",
416
+ leaderId: d,
417
+ status: o,
418
+ lastEventId: g?.getLastEventId() ?? r,
419
+ revoked: v
420
+ }) : f === "electing" && (d < t.tabId ? w({ type: "leader-candidate", tabId: d }) : (D(), C = setTimeout(() => {
421
+ C = null, !c && !v && f === "electing" && p();
422
+ }, x * 3)));
423
+ break;
424
+ }
425
+ case "leader-candidate": {
426
+ if (t.tabId === d) return;
427
+ f === "electing" && t.tabId < d && (D(), C = setTimeout(() => {
428
+ C = null, !c && !v && f === "electing" && p();
429
+ }, x * 3));
430
+ break;
431
+ }
432
+ case "leader-announce": {
433
+ if (t.leaderId === d) return;
434
+ if (t.revoked) {
435
+ J("session_revoked", !1);
436
+ return;
437
+ }
438
+ if (f === "inactive") return;
439
+ if (t.status === "closed") {
440
+ f === "follower" && (s === null || s === t.leaderId) ? (t.lastEventId !== void 0 && (r = t.lastEventId), T(x)) : f === "electing" && r === void 0 && t.lastEventId !== void 0 && (r = t.lastEventId);
441
+ return;
442
+ }
443
+ f === "leader" ? t.leaderId < d ? K(t.leaderId, t.status, t.lastEventId) : o !== "closed" && w({
444
+ type: "leader-announce",
445
+ leaderId: d,
446
+ status: o,
447
+ lastEventId: g?.getLastEventId() ?? r,
448
+ revoked: v
449
+ }) : K(t.leaderId, t.status, t.lastEventId);
450
+ break;
451
+ }
452
+ case "leader-heartbeat": {
453
+ if (t.leaderId === d) return;
454
+ if (f === "follower" && (s === null || s === t.leaderId)) {
455
+ if (t.lastEventId !== void 0 && (r = t.lastEventId), t.status === "closed") {
456
+ T(x);
457
+ return;
458
+ }
459
+ s = t.leaderId, O(), t.status !== "idle" && B(t.status);
460
+ }
461
+ break;
462
+ }
463
+ case "leader-release": {
464
+ if (t.leaderId === d || f === "inactive") return;
465
+ t.lastEventId !== void 0 && (r = t.lastEventId), f === "follower" && (s === null || s === t.leaderId) && T(x);
466
+ break;
467
+ }
468
+ case "stream-open": {
469
+ if (t.leaderId === d || f !== "follower" || s !== null && t.leaderId !== s) return;
470
+ t.lastEventId !== void 0 && (r = t.lastEventId), O(), B("open"), L = !0, a.onOpen?.();
471
+ break;
472
+ }
473
+ case "stream-status": {
474
+ if (t.leaderId === d || f !== "follower" || s !== null && t.leaderId !== s) return;
475
+ if (t.lastEventId !== void 0 && (r = t.lastEventId), t.status === "closed") {
476
+ T(x);
477
+ return;
478
+ }
479
+ O(), B(t.status);
480
+ break;
481
+ }
482
+ case "stream-frame": {
483
+ if (t.leaderId === d || f !== "follower" || s !== null && t.leaderId !== s) return;
484
+ if (t.lastEventId !== void 0 ? r = t.lastEventId : t.frame.id !== void 0 && (r = t.frame.id), O(), A === "minimal-invalidation") {
485
+ const y = se(t.frame);
486
+ a.onInvalidation?.({
487
+ scopeKey: E,
488
+ inboxRevision: y.inboxRevision ?? null,
489
+ eventKind: y.eventKind,
490
+ ...r !== void 0 ? { lastEventId: r } : {}
491
+ });
492
+ break;
493
+ }
494
+ a.onFrame(t.frame);
495
+ break;
496
+ }
497
+ case "inbox-invalidation": {
498
+ if (t.leaderId === d || f !== "follower" || s !== null && t.leaderId !== s || t.scopeKey !== E) return;
499
+ t.lastEventId !== void 0 && (r = t.lastEventId), O();
500
+ const y = {
501
+ scopeKey: t.scopeKey,
502
+ inboxRevision: t.inboxRevision ?? null,
503
+ eventKind: t.eventKind,
504
+ ...t.lastEventId !== void 0 ? { lastEventId: t.lastEventId } : {}
505
+ };
506
+ a.onInvalidation?.(y);
507
+ break;
508
+ }
509
+ case "stream-lagged": {
510
+ if (t.leaderId === d || f !== "follower" || s !== null && t.leaderId !== s) return;
511
+ t.lastEventId !== void 0 && (r = t.lastEventId), O(), a.onLagged?.(t.droppedCount, t.rawData);
512
+ break;
513
+ }
514
+ case "stream-resync": {
515
+ if (t.leaderId === d || f !== "follower" || s !== null && t.leaderId !== s) return;
516
+ t.lastEventId !== void 0 && (r = t.lastEventId), O(), a.onResync?.(t.reason);
517
+ break;
518
+ }
519
+ case "stream-revoked": {
520
+ if (t.leaderId === d) return;
521
+ J(t.rawData, !1);
522
+ break;
523
+ }
524
+ }
525
+ }
526
+ M.onmessage = R, T(x);
527
+ function _() {
528
+ if (c) return;
529
+ const h = f === "leader", t = g?.getLastEventId() ?? r;
530
+ r = t, D(), k(), j(), h && !v && w({
531
+ type: "leader-release",
532
+ leaderId: d,
533
+ lastEventId: t
534
+ }), c = !0, f = "inactive", s = null, M.onmessage = null;
535
+ try {
536
+ M.close();
537
+ } catch {
538
+ }
539
+ v || B("closed");
540
+ }
541
+ return {
542
+ close: _,
543
+ getStatus: () => o,
544
+ getLastEventId: () => g?.getLastEventId() ?? r
545
+ };
546
+ }
547
+ function Ne(e = 0) {
548
+ let n = Number.isFinite(e) && e >= 0 ? Math.floor(e) : 0;
549
+ return {
550
+ current() {
551
+ return n;
552
+ },
553
+ bump() {
554
+ return n += 1, n;
555
+ },
556
+ capture() {
557
+ return n;
558
+ },
559
+ isCurrent(a) {
560
+ return Number.isFinite(a) && a === n;
561
+ }
562
+ };
563
+ }
564
+ function Te(e) {
565
+ const n = e.trim();
566
+ if (!n) return null;
567
+ if (/^\d+$/.test(n)) {
568
+ const a = Number.parseInt(n, 10);
569
+ return Number.isSafeInteger(a) ? a : null;
570
+ }
571
+ try {
572
+ const a = JSON.parse(n);
573
+ if (typeof a == "number" && Number.isFinite(a) && a >= 0)
574
+ return Math.floor(a);
575
+ if (a && typeof a == "object") {
576
+ const I = a;
577
+ for (const S of ["dropped", "droppedCount", "dropped_count", "count", "lagged"]) {
578
+ const E = I[S];
579
+ if (typeof E == "number" && Number.isFinite(E) && E >= 0)
580
+ return Math.floor(E);
581
+ }
582
+ }
583
+ } catch {
584
+ return null;
585
+ }
586
+ return null;
587
+ }
588
+ function le(e, n) {
589
+ const a = e.fetch ?? globalThis.fetch, I = e.credentials ?? "include", S = e.maxReconnectAttempts ?? 1 / 0, E = Math.max(10, e.reconnectBaseDelayMs ?? 500), A = Math.max(
590
+ E,
591
+ e.reconnectMaxDelayMs ?? 3e4
592
+ ), x = e.visibilityResyncThresholdMs ?? 15e3, H = e.now ?? (() => Date.now()), V = e.random ?? (() => Math.random()), M = e.documentRef ?? (typeof document < "u" ? document : void 0);
593
+ let d = "idle", f = e.lastEventId, s = !1, o = !1, r = !1, c = !1, v = 0, g, F = null, C = null, U = null;
594
+ function N(p) {
595
+ d !== p && (d = p, n.onStatusChange?.(p));
596
+ }
597
+ function L() {
598
+ F !== null && (clearTimeout(F), F = null);
599
+ }
600
+ function B() {
601
+ if (C) {
602
+ const p = C;
603
+ C = null, p.abort();
604
+ }
605
+ }
606
+ function D() {
607
+ if (!(!M || s || o)) {
608
+ if (M.visibilityState === "hidden") {
609
+ U = H();
610
+ return;
611
+ }
612
+ if (M.visibilityState === "visible" && U !== null) {
613
+ const p = H() - U;
614
+ U = null, p >= x && n.onResync?.("visibility");
615
+ }
616
+ }
617
+ }
618
+ M && (M.visibilityState === "hidden" && (U = H()), M.addEventListener("visibilitychange", D));
619
+ function q() {
620
+ M && M.removeEventListener("visibilitychange", D);
621
+ }
622
+ function k(p) {
623
+ const T = Math.min(
624
+ A,
625
+ (g ?? E) * 2 ** Math.max(0, p - 1)
626
+ ), R = 0.8 + 0.2 * Math.min(1, Math.max(0, V()));
627
+ return Math.min(
628
+ A,
629
+ Math.max(10, Math.round(T * R))
630
+ );
631
+ }
632
+ function w() {
633
+ if (s || o) return;
634
+ if (v >= S) {
635
+ s = !0, q(), N("closed");
636
+ return;
637
+ }
638
+ v += 1;
639
+ const p = k(v);
640
+ N("reconnecting"), L(), F = setTimeout(() => {
641
+ F = null, !s && !o && z();
642
+ }, p);
643
+ }
644
+ function O(p) {
645
+ o || (o = !0, s = !0, L(), q(), B(), N("revoked"), n.onSessionRevoked?.(p));
646
+ }
647
+ async function j() {
648
+ const p = typeof e.headers == "function" ? await e.headers() : e.headers, K = {}, T = (R, _) => {
649
+ const h = R.toLowerCase();
650
+ for (const t of Object.keys(K))
651
+ t.toLowerCase() === h && t !== R && delete K[t];
652
+ K[R] = _;
653
+ };
654
+ if (p instanceof Headers)
655
+ p.forEach((R, _) => {
656
+ T(_, R);
657
+ });
658
+ else if (Array.isArray(p))
659
+ for (const [R, _] of p)
660
+ T(R, _);
661
+ else if (p)
662
+ for (const [R, _] of Object.entries(p))
663
+ _ !== void 0 && T(R, _);
664
+ return T("Accept", "text/event-stream"), T("Cache-Control", "no-cache"), f !== void 0 && f !== "" && T("Last-Event-ID", f), K;
665
+ }
666
+ async function z() {
667
+ if (s || o) return;
668
+ N(r || c ? "reconnecting" : "connecting");
669
+ let p;
670
+ try {
671
+ p = await j();
672
+ } catch (R) {
673
+ if (s || o) return;
674
+ c = !0, n.onTransportError?.(R), w();
675
+ return;
676
+ }
677
+ if (s || o) return;
678
+ if (e.requireAuthHeader && !Object.entries(p).find(
679
+ ([h]) => h.toLowerCase() === "authorization"
680
+ )?.[1]?.trim()) {
681
+ const h = new te(
682
+ me,
683
+ "Authorization header is required to open the realtime stream."
684
+ );
685
+ s = !0, L(), q(), N("closed"), n.onTransportError?.(h);
686
+ return;
687
+ }
688
+ if (typeof a != "function") {
689
+ const R = new te(
690
+ "sse_fetch_unavailable",
691
+ "Fetch implementation is not available."
692
+ );
693
+ s = !0, q(), N("closed"), n.onTransportError?.(R);
694
+ return;
695
+ }
696
+ const K = new AbortController();
697
+ C = K;
698
+ let T = null;
699
+ try {
700
+ const R = await a(e.url, {
701
+ method: "GET",
702
+ headers: p,
703
+ credentials: I,
704
+ cache: "no-store",
705
+ signal: K.signal
706
+ });
707
+ if (s || o) return;
708
+ if (!R.ok)
709
+ throw new te(
710
+ ve,
711
+ `Realtime stream request failed with status ${R.status}`,
712
+ { status: R.status }
713
+ );
714
+ if (!R.body)
715
+ throw new te(
716
+ "sse_empty_body",
717
+ "Realtime stream response did not include a readable body."
718
+ );
719
+ const _ = r || c;
720
+ r = !0, c = !1, N("open"), n.onOpen?.(), _ && n.onResync?.("reconnect");
721
+ const h = new TextDecoder("utf-8"), t = ue({
722
+ onId: (y) => {
723
+ f = y;
724
+ },
725
+ onRetry: (y) => {
726
+ g = y;
727
+ },
728
+ onComment: () => {
729
+ v = 0;
730
+ },
731
+ onFrame: (y) => {
732
+ if (!(s || o)) {
733
+ if (v = 0, y.id !== void 0 && (f = y.id), y.retryMs !== void 0 && (g = y.retryMs), y.event === "session-revoked") {
734
+ O(y.data);
735
+ return;
736
+ }
737
+ if (y.event === "lagged") {
738
+ const i = Te(y.data);
739
+ n.onLagged?.(i, y.data), n.onResync?.("lagged"), n.onFrame(y);
740
+ return;
741
+ }
742
+ n.onFrame(y);
743
+ }
744
+ }
745
+ });
746
+ for (T = R.body.getReader(); !s && !o; ) {
747
+ const { done: y, value: i } = await T.read();
748
+ if (y) {
749
+ const u = h.decode();
750
+ u && t.feed(u);
751
+ break;
752
+ }
753
+ i && i.byteLength > 0 && t.feed(h.decode(i, { stream: !0 }));
754
+ }
755
+ !s && !o && w();
756
+ } catch (R) {
757
+ if (s || o) return;
758
+ c = !0, n.onTransportError?.(R), w();
759
+ } finally {
760
+ T && T.cancel().catch(() => {
761
+ }), C === K && (C = null);
762
+ }
763
+ }
764
+ z();
765
+ function J() {
766
+ s || (s = !0, L(), q(), B(), o || N("closed"));
767
+ }
768
+ return {
769
+ close: J,
770
+ getStatus: () => d,
771
+ getLastEventId: () => f
772
+ };
773
+ }
774
+ function De(e, n) {
775
+ return e.multiTab === !0 && (e.scope || e.scopeKey) ? we({
776
+ scope: e.scope,
777
+ scopeKey: e.scopeKey,
778
+ disclosureMode: e.multiTabDisclosureMode,
779
+ extractInvalidationHint: e.extractInvalidationHint,
780
+ initialLastEventId: e.lastEventId,
781
+ broadcastChannelFactory: e.broadcastChannelFactory,
782
+ electionTimeoutMs: e.multiTabElectionTimeoutMs,
783
+ heartbeatIntervalMs: e.multiTabHeartbeatIntervalMs,
784
+ openLeaderStream: (a, I) => le(
785
+ {
786
+ ...e,
787
+ lastEventId: a ?? e.lastEventId,
788
+ multiTab: !1
789
+ },
790
+ I
791
+ ),
792
+ handlers: n
793
+ }) : le(e, n);
794
+ }
795
+ const Ce = 50, xe = 20, re = 6e4, ie = 15e3, Fe = 500;
796
+ function X(e) {
797
+ return typeof e == "number" && Number.isFinite(e) && e >= 0;
798
+ }
799
+ function G(e) {
800
+ return Math.max(0, Math.floor(e));
801
+ }
802
+ function ce(e) {
803
+ return Math.max(0, Math.floor(e));
804
+ }
805
+ function _e(e = re, n = ie, a = () => Math.random()) {
806
+ const I = Number.isFinite(e) && e >= 0 ? e : re, S = Number.isFinite(n) && n >= 0 ? Math.min(I, n) : Math.min(I, ie), E = a(), x = (2 * (Number.isFinite(E) ? Math.min(1, Math.max(0, E)) : 0.5) - 1) * S;
807
+ return Math.max(0, Math.round(I + x));
808
+ }
809
+ function Ke(e) {
810
+ const n = Number.isFinite(e.limit) && (e.limit ?? 0) >= 1 ? Math.floor(e.limit) : Ce, a = Number.isFinite(e.maxPages) && (e.maxPages ?? 0) >= 1 ? Math.floor(e.maxPages) : xe, I = Number.isFinite(e.maxBufferedFrames) && (e.maxBufferedFrames ?? 0) >= 1 ? Math.floor(e.maxBufferedFrames) : Fe, S = e.calibrationIntervalMs ?? re, E = e.calibrationJitterMs ?? ie, A = e.random ?? (() => Math.random()), x = e.schedule ?? ((i, u) => setTimeout(i, u)), H = e.cancelSchedule ?? ((i) => {
811
+ clearTimeout(i);
812
+ }), V = e.documentRef ?? (typeof document < "u" ? document : void 0), M = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = new Ie(e.frameDedupeCapacity ?? 500), s = [];
813
+ let o = X(e.initialRevision) ? G(e.initialRevision) : null, r = X(e.initialUnreadCount) ? ce(e.initialUnreadCount) : 0, c = !1, v = !1, g = !1, F = null, C = null;
814
+ function U(i) {
815
+ const u = e.getItemAggregationKey?.(i)?.trim();
816
+ return u || null;
817
+ }
818
+ function N(i) {
819
+ const u = M.get(i);
820
+ if (!u) return;
821
+ M.delete(i);
822
+ const l = U(u);
823
+ l && d.get(l) === i && d.delete(l);
824
+ }
825
+ function L(i, u) {
826
+ const l = U(u);
827
+ if (l) {
828
+ const b = d.get(l);
829
+ b !== void 0 && b !== i && N(b);
830
+ }
831
+ const m = M.get(i);
832
+ if (m) {
833
+ const b = U(m);
834
+ b && b !== l && d.get(b) === i && d.delete(b);
835
+ }
836
+ M.set(i, u), l && d.set(l, i);
837
+ }
838
+ function B() {
839
+ if (!e.isItemUnread) return r;
840
+ let i = 0;
841
+ for (const u of M.values())
842
+ e.isItemUnread(u) && (i += 1);
843
+ return i;
844
+ }
845
+ function D(i) {
846
+ const u = r;
847
+ return X(i) ? r = ce(i) : e.isItemUnread && (r = B()), r !== u;
848
+ }
849
+ if (e.initialItems) {
850
+ for (const i of e.initialItems)
851
+ L(e.getItemId(i), i);
852
+ !X(e.initialUnreadCount) && e.isItemUnread && (r = B());
853
+ }
854
+ function q() {
855
+ return {
856
+ lastAppliedRevision: o,
857
+ itemsById: new Map(M),
858
+ unreadCount: r,
859
+ buffering: c,
860
+ bufferedFrames: [...s]
861
+ };
862
+ }
863
+ function k() {
864
+ g || e.onStateChange?.(q());
865
+ }
866
+ function w() {
867
+ return V ? V.visibilityState === "visible" : !0;
868
+ }
869
+ function O() {
870
+ if (F !== null) {
871
+ const i = F;
872
+ F = null, H(i);
873
+ }
874
+ }
875
+ function j() {
876
+ if (g || !v || !w() || F !== null) return;
877
+ const i = _e(
878
+ S,
879
+ E,
880
+ A
881
+ );
882
+ F = x(() => {
883
+ F = null, !(g || !v || !w()) && y().catch((u) => {
884
+ e.onCalibrationError?.(u);
885
+ }).finally(() => {
886
+ !g && v && w() && j();
887
+ });
888
+ }, i);
889
+ }
890
+ function z() {
891
+ g || (w() ? v && j() : O());
892
+ }
893
+ V && V.addEventListener("visibilitychange", z);
894
+ function J(i) {
895
+ if (e.getFrameDedupeKey) {
896
+ const u = e.getFrameDedupeKey(i);
897
+ return u || null;
898
+ }
899
+ return i.id && i.id.trim().length > 0 ? `id:${i.id}` : null;
900
+ }
901
+ function p(i, u) {
902
+ if (e.getFrameRevision && o !== null) {
903
+ const m = e.getFrameRevision(i);
904
+ if (X(m) && G(m) <= o)
905
+ return "stale";
906
+ }
907
+ const l = J(i);
908
+ return l !== null && !f.remember(l) ? "deduped" : (e.onFrame?.(i, { replayed: u }), "dispatched");
909
+ }
910
+ function K() {
911
+ if (!c && s.length === 0) return 0;
912
+ c = !1;
913
+ const i = s.splice(0);
914
+ let u = 0;
915
+ for (const l of i) {
916
+ if (g) break;
917
+ p(l, !0) === "dispatched" && (u += 1);
918
+ }
919
+ return u;
920
+ }
921
+ function T(i) {
922
+ if (i.length === 0) return 0;
923
+ const u = [...i].sort((m, b) => m.revision - b.revision);
924
+ let l = 0;
925
+ for (const m of u) {
926
+ if (m.changeKind === "dismiss")
927
+ N(m.itemId);
928
+ else if (m.changeKind === "read")
929
+ if (m.item != null)
930
+ L(m.itemId, m.item);
931
+ else {
932
+ const b = M.get(m.itemId);
933
+ b && e.markItemRead && L(m.itemId, e.markItemRead(b, m));
934
+ }
935
+ else m.changeKind === "upsert" && m.item != null && L(m.itemId, m.item);
936
+ e.onChangeApplied?.(m), l += 1;
937
+ }
938
+ return l;
939
+ }
940
+ function R(i) {
941
+ M.clear(), d.clear();
942
+ for (const l of i.items)
943
+ L(e.getItemId(l), l);
944
+ const u = G(i.watermarkRevision);
945
+ return o = u, D(i.unreadCount), u;
946
+ }
947
+ async function _(i, u, l, m) {
948
+ const b = await e.fetchSnapshot({ reason: i, page: u });
949
+ if (g)
950
+ return {
951
+ outcome: "snapshot_reset",
952
+ resetReason: i,
953
+ lastAppliedRevision: o,
954
+ watermarkRevision: o,
955
+ unreadCount: r,
956
+ pagesFetched: l,
957
+ changesApplied: m,
958
+ replayedFrames: 0
959
+ };
960
+ const P = R(b);
961
+ await e.onCommitRevision?.(P);
962
+ const Q = K();
963
+ return k(), {
964
+ outcome: "snapshot_reset",
965
+ resetReason: i,
966
+ lastAppliedRevision: P,
967
+ watermarkRevision: P,
968
+ unreadCount: r,
969
+ pagesFetched: l,
970
+ changesApplied: m,
971
+ replayedFrames: Q
972
+ };
973
+ }
974
+ async function h() {
975
+ if (o === null)
976
+ return _("initial_snapshot", void 0, 0, 0);
977
+ const i = o;
978
+ let u = i, l = 0, m = 0, b = await e.fetchDelta({ sinceRevision: u, limit: n });
979
+ if (l = 1, g)
980
+ return {
981
+ outcome: "noop",
982
+ lastAppliedRevision: o,
983
+ watermarkRevision: o,
984
+ unreadCount: r,
985
+ pagesFetched: l,
986
+ changesApplied: m,
987
+ replayedFrames: 0
988
+ };
989
+ if (b.resetRequired)
990
+ return _("server_reset_required", b, l, m);
991
+ const P = G(b.watermarkRevision), Q = G(b.nextRevision);
992
+ if (!b.hasMore && b.changes.length === 0 && Q <= u) {
993
+ const $ = D(b.unreadCount), W = c, ee = K();
994
+ return ($ || W || ee > 0) && k(), {
995
+ outcome: "noop",
996
+ lastAppliedRevision: o,
997
+ watermarkRevision: P,
998
+ unreadCount: r,
999
+ pagesFetched: l,
1000
+ changesApplied: 0,
1001
+ replayedFrames: ee
1002
+ };
1003
+ }
1004
+ let ae = u;
1005
+ m += T(b.changes);
1006
+ const Z = Math.max(u, Q), de = Z > u;
1007
+ for (u = Z, o = Z, D(b.unreadCount), (de || b.changes.length > 0) && await e.onCommitRevision?.(Z), k(); b.hasMore && l < a; ) {
1008
+ if (u <= ae)
1009
+ return _("non_monotonic_cursor", b, l, m);
1010
+ const $ = await e.fetchDelta({
1011
+ sinceRevision: u,
1012
+ upToRevision: P,
1013
+ limit: n
1014
+ });
1015
+ if (l += 1, g)
1016
+ return {
1017
+ outcome: "caught_up",
1018
+ lastAppliedRevision: o,
1019
+ watermarkRevision: P,
1020
+ unreadCount: r,
1021
+ pagesFetched: l,
1022
+ changesApplied: m,
1023
+ replayedFrames: 0
1024
+ };
1025
+ if ($.resetRequired)
1026
+ return _("server_reset_required", $, l, m);
1027
+ ae = u, m += T($.changes);
1028
+ const W = Math.max(u, G($.nextRevision)), ee = W > u;
1029
+ u = W, o = W, D($.unreadCount), (ee || $.changes.length > 0) && await e.onCommitRevision?.(W), k(), b = $;
1030
+ }
1031
+ if (b.hasMore)
1032
+ return _("max_pages_exceeded", b, l, m);
1033
+ const fe = K();
1034
+ return k(), {
1035
+ outcome: m === 0 && u === i ? "noop" : "caught_up",
1036
+ lastAppliedRevision: o,
1037
+ watermarkRevision: P,
1038
+ unreadCount: r,
1039
+ pagesFetched: l,
1040
+ changesApplied: m,
1041
+ replayedFrames: fe
1042
+ };
1043
+ }
1044
+ function t() {
1045
+ if (C) return C;
1046
+ const i = h().finally(() => {
1047
+ C === i && (C = null);
1048
+ });
1049
+ return C = i, i;
1050
+ }
1051
+ async function y() {
1052
+ return g ? null : t();
1053
+ }
1054
+ return {
1055
+ getState: q,
1056
+ beginBuffering() {
1057
+ g || c || (c = !0, k());
1058
+ },
1059
+ endBuffering() {
1060
+ c && (c = !1, s.length = 0, k());
1061
+ },
1062
+ handleSseFrame(i) {
1063
+ return g ? "deduped" : c ? (s.length >= I && s.shift(), s.push(i), "buffered") : p(i, !1);
1064
+ },
1065
+ catchUp: t,
1066
+ calibrateNow: y,
1067
+ applySnapshot(i) {
1068
+ g || (R(i), k());
1069
+ },
1070
+ setStreamOpen(i) {
1071
+ g || (v = i, v && w() ? j() : O());
1072
+ },
1073
+ setStreamStatus(i) {
1074
+ g || (v = i === "open", v && w() ? j() : O());
1075
+ },
1076
+ isCalibrationScheduled() {
1077
+ return F !== null;
1078
+ },
1079
+ dispose() {
1080
+ g || (g = !0, v = !1, c = !1, s.length = 0, O(), V && V.removeEventListener("visibilitychange", z));
1081
+ }
1082
+ };
1083
+ }
1084
+ export {
1085
+ re as DEFAULT_CALIBRATION_INTERVAL_MS,
1086
+ ie as DEFAULT_CALIBRATION_JITTER_MS,
1087
+ Fe as DEFAULT_MAX_BUFFERED_FRAMES,
1088
+ Ce as DEFAULT_REVISION_SYNC_LIMIT,
1089
+ xe as DEFAULT_REVISION_SYNC_MAX_PAGES,
1090
+ he as INVALID_MULTITAB_SCOPE,
1091
+ Y as InvalidMultiTabScopeError,
1092
+ Ie as LruDedupeSet,
1093
+ te as RealtimeStreamError,
1094
+ me as SSE_AUTH_HEADER_REQUIRED,
1095
+ ve as SSE_HTTP_ERROR,
1096
+ Le as SSE_SESSION_REVOKED,
1097
+ Ae as SSE_STREAM_LAGGED,
1098
+ pe as buildStructuredScopeKey,
1099
+ _e as computeCalibrationDelayMs,
1100
+ we as createMultiTabCoordinator,
1101
+ De as createRealtimeStream,
1102
+ Ke as createRevisionSyncEngine,
1103
+ Ne as createSessionGenerationGuard,
1104
+ ue as createSseParser,
1105
+ ke as parseSseText
1106
+ };