@neta-art/cohub 2.7.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,818 @@
1
+ import { a as getRealtimeSpaceRoom, i as WS_ROOM_SUBSCRIPTION_CAPABILITY, o as getSessionTurnPatchStreamKey, r as WS_COMPACT_STREAM_CAPABILITY, s as normalizeRealtimeRooms, t as HttpError } from "./transport.js";
2
+ import { c as resolveWebsocketUrl } from "./environment.js";
3
+ //#region src/http-error.ts
4
+ /** Shared HTTP error code for every plan entitlement gate (402). */
5
+ const FEATURE_NOT_ENTITLED_ERROR_CODE = "feature_not_entitled";
6
+ /** Shared HTTP error code for a blocked usage gate (negative balance limit, 402). */
7
+ const BILLING_ACCESS_BLOCKED_ERROR_CODE = "billing_credit_limit_exceeded";
8
+ function isHttpErrorCode(error, code) {
9
+ return error instanceof HttpError && error.code === code;
10
+ }
11
+ function isFeatureNotEntitledError(error) {
12
+ return isHttpErrorCode(error, FEATURE_NOT_ENTITLED_ERROR_CODE);
13
+ }
14
+ function isBillingAccessBlockedError(error) {
15
+ return isHttpErrorCode(error, BILLING_ACCESS_BLOCKED_ERROR_CODE);
16
+ }
17
+ function isBillingAccessBlockedCode(code) {
18
+ return code === BILLING_ACCESS_BLOCKED_ERROR_CODE;
19
+ }
20
+ const isRecord$1 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
21
+ function isBillingConversionIntent(value) {
22
+ if (!isRecord$1(value)) return false;
23
+ return (value.level === "soft" || value.level === "hard") && typeof value.title === "string" && typeof value.message === "string" && isRecord$1(value.primaryAction) && value.primaryAction.action === "open_billing_conversion";
24
+ }
25
+ /**
26
+ * Extracts the standard `billing` payload from a response body, an
27
+ * `HttpError`, or a bare billing payload (e.g. a realtime error event's
28
+ * `billing` field). Returns `null` unless it carries a valid conversion
29
+ * intent.
30
+ */
31
+ function extractBillingPayload(source) {
32
+ const root = source instanceof HttpError ? source.body : source;
33
+ if (!isRecord$1(root)) return null;
34
+ const billing = isRecord$1(root.billing) ? root.billing : root;
35
+ if (!isBillingConversionIntent(billing.conversion)) return null;
36
+ return billing;
37
+ }
38
+ //#endregion
39
+ //#region src/websocket.ts
40
+ const createEventMap = () => ({
41
+ connecting: /* @__PURE__ */ new Set(),
42
+ reconnecting: /* @__PURE__ */ new Set(),
43
+ open: /* @__PURE__ */ new Set(),
44
+ close: /* @__PURE__ */ new Set(),
45
+ error: /* @__PURE__ */ new Set(),
46
+ event: /* @__PURE__ */ new Set(),
47
+ ready: /* @__PURE__ */ new Set(),
48
+ auth: /* @__PURE__ */ new Set(),
49
+ messageAccepted: /* @__PURE__ */ new Set(),
50
+ serverError: /* @__PURE__ */ new Set(),
51
+ subscribed: /* @__PURE__ */ new Set(),
52
+ subscribeError: /* @__PURE__ */ new Set(),
53
+ pong: /* @__PURE__ */ new Set()
54
+ });
55
+ const toWebSocketUrl = (input, env) => resolveWebsocketUrl({
56
+ url: input,
57
+ env
58
+ });
59
+ const normalizeOptions = (options = {}) => ({
60
+ url: toWebSocketUrl(options.url, options.env),
61
+ autoReconnect: options.autoReconnect !== false,
62
+ reconnectBaseDelayMs: options.reconnectBaseDelayMs ?? 1e3,
63
+ reconnectMaxDelayMs: options.reconnectMaxDelayMs ?? 15e3,
64
+ pingIntervalMs: options.pingIntervalMs ?? 2e4,
65
+ pongTimeoutMs: options.pongTimeoutMs ?? 15e3,
66
+ debug: options.debug === true
67
+ });
68
+ const formatCloseMessage = (code, reason) => `WebSocket closed: ${code ?? 0} ${reason || ""}`.trim();
69
+ const isRetryableCloseCode = (code) => {
70
+ if (code === 1e3) return false;
71
+ if (code === 4003) return false;
72
+ return true;
73
+ };
74
+ const AUTH_CLOSE_REASON = "authentication failed";
75
+ const PATCH_STREAM_BUFFER_MAX_PENDING = 128;
76
+ const isRecord = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
77
+ const isRealtimeCompactFrame = (value) => {
78
+ if (!isRecord(value)) return false;
79
+ if (value.t !== "d" && value.t !== "p") return false;
80
+ if (typeof value.sid !== "string" || !value.sid) return false;
81
+ if (typeof value.s !== "number" || !Number.isInteger(value.s) || value.s < 0) return false;
82
+ if (typeof value.b !== "number" || !Number.isInteger(value.b) || value.b < 0) return false;
83
+ if (value.t === "d") return "v" in value;
84
+ return (value.o === "append" || value.o === "replace" || value.o === "add" || value.o === "merge" || value.o === "remove") && typeof value.p === "string" && value.p.length > 0;
85
+ };
86
+ const isRealtimeEnvelope = (value) => {
87
+ if (!isRecord(value)) return false;
88
+ if (typeof value.id !== "string") return false;
89
+ if (typeof value.timestamp !== "number") return false;
90
+ if (value.domain !== "system" && value.domain !== "session" && value.domain !== "space" && value.domain !== "label") return false;
91
+ if (typeof value.type !== "string") return false;
92
+ if (!isRecord(value.payload)) return false;
93
+ return true;
94
+ };
95
+ const compactFrameToPatchOperation = (frame) => {
96
+ if (frame.t === "d") return { v: frame.v };
97
+ if (frame.o === "remove") return {
98
+ o: "remove",
99
+ p: frame.p
100
+ };
101
+ if (frame.o === "merge") return isRecord(frame.v) ? {
102
+ o: "merge",
103
+ p: frame.p,
104
+ v: frame.v
105
+ } : null;
106
+ if (!("v" in frame)) return null;
107
+ switch (frame.o) {
108
+ case "append": return {
109
+ o: "append",
110
+ p: frame.p,
111
+ v: frame.v
112
+ };
113
+ case "replace": return {
114
+ o: "replace",
115
+ p: frame.p,
116
+ v: frame.v
117
+ };
118
+ case "add": return {
119
+ o: "add",
120
+ p: frame.p,
121
+ v: frame.v
122
+ };
123
+ default: return null;
124
+ }
125
+ };
126
+ var WebsocketAuthError = class extends Error {
127
+ constructor(message) {
128
+ super(message);
129
+ this.name = "WebsocketAuthError";
130
+ }
131
+ };
132
+ var WebsocketClient = class {
133
+ url;
134
+ autoReconnect;
135
+ reconnectBaseDelayMs;
136
+ reconnectMaxDelayMs;
137
+ pingIntervalMs;
138
+ pongTimeoutMs;
139
+ debug;
140
+ getAccessToken;
141
+ WebSocketImpl;
142
+ ws = null;
143
+ pingTimer = null;
144
+ reconnectTimer = null;
145
+ reconnectTimerResolver = null;
146
+ reconnectAttempt = 0;
147
+ manuallyClosed = false;
148
+ connectPromise = null;
149
+ authWaiter = null;
150
+ awaitingPong = false;
151
+ lastPingRequestId = null;
152
+ pongDeadlineAt = 0;
153
+ compactStreamContexts = /* @__PURE__ */ new Map();
154
+ patchStreamBuffers = /* @__PURE__ */ new Map();
155
+ roomSubscriptions = /* @__PURE__ */ new Map();
156
+ state = "idle";
157
+ connectionId = null;
158
+ listeners = createEventMap();
159
+ constructor(options = {}) {
160
+ const normalized = normalizeOptions(options);
161
+ this.url = normalized.url;
162
+ this.autoReconnect = normalized.autoReconnect;
163
+ this.reconnectBaseDelayMs = normalized.reconnectBaseDelayMs;
164
+ this.reconnectMaxDelayMs = normalized.reconnectMaxDelayMs;
165
+ this.pingIntervalMs = normalized.pingIntervalMs;
166
+ this.pongTimeoutMs = normalized.pongTimeoutMs;
167
+ this.debug = normalized.debug;
168
+ this.getAccessToken = options.getAccessToken;
169
+ this.WebSocketImpl = options.WebSocketImpl ?? WebSocket;
170
+ }
171
+ on(type, handler) {
172
+ this.listeners[type].add(handler);
173
+ return () => this.off(type, handler);
174
+ }
175
+ off(type, handler) {
176
+ this.listeners[type].delete(handler);
177
+ }
178
+ emit(type, payload) {
179
+ for (const handler of this.listeners[type]) handler(payload);
180
+ }
181
+ log(...args) {
182
+ if (this.debug) console.log("[WebsocketClient]", ...args);
183
+ }
184
+ async connect() {
185
+ if (this.connectPromise) return this.connectPromise;
186
+ if (this.state === "open" && this.ws?.readyState === WebSocket.OPEN) return;
187
+ const isReconnect = this.reconnectAttempt > 0 || this.state === "reconnecting";
188
+ this.manuallyClosed = false;
189
+ this.clearReconnectTimer();
190
+ this.state = isReconnect ? "reconnecting" : "connecting";
191
+ this.emit("connecting", {
192
+ isReconnect,
193
+ attempt: this.reconnectAttempt
194
+ });
195
+ this.connectPromise = new Promise((resolve, reject) => {
196
+ const ws = new this.WebSocketImpl(this.url);
197
+ this.ws = ws;
198
+ let settled = false;
199
+ const rejectOnce = (error) => {
200
+ if (settled) return;
201
+ settled = true;
202
+ this.connectPromise = null;
203
+ reject(error);
204
+ };
205
+ const resolveOnce = () => {
206
+ if (settled) return;
207
+ settled = true;
208
+ this.connectPromise = null;
209
+ resolve();
210
+ };
211
+ ws.onopen = async () => {
212
+ try {
213
+ this.log("connected", {
214
+ url: this.url,
215
+ isReconnect,
216
+ attempt: this.reconnectAttempt
217
+ });
218
+ this.startPingLoop();
219
+ await this.authenticate();
220
+ this.state = "open";
221
+ this.reconnectAttempt = 0;
222
+ this.emit("open", { connectionId: this.connectionId });
223
+ resolveOnce();
224
+ } catch (error) {
225
+ const authError = error instanceof Error ? error : /* @__PURE__ */ new Error("authentication failed");
226
+ this.emit("error", {
227
+ error: authError,
228
+ recoverable: false
229
+ });
230
+ rejectOnce(authError);
231
+ ws.close(4003, AUTH_CLOSE_REASON);
232
+ }
233
+ };
234
+ ws.onmessage = (event) => {
235
+ this.handleMessage(event.data);
236
+ };
237
+ ws.onerror = (error) => {
238
+ this.emit("error", {
239
+ error,
240
+ recoverable: !this.manuallyClosed
241
+ });
242
+ };
243
+ ws.onclose = (event) => {
244
+ this.stopPingLoop();
245
+ const wasConnecting = this.state === "connecting" || this.state === "reconnecting";
246
+ this.state = "closed";
247
+ this.ws = null;
248
+ this.compactStreamContexts.clear();
249
+ this.patchStreamBuffers.clear();
250
+ const closeError = new Error(formatCloseMessage(event.code, event.reason));
251
+ this.rejectAuthWaiter(closeError);
252
+ const willReconnect = !this.manuallyClosed && this.autoReconnect && isRetryableCloseCode(event.code);
253
+ this.log("closed", {
254
+ code: event.code,
255
+ reason: event.reason,
256
+ willReconnect,
257
+ wasConnecting
258
+ });
259
+ this.emit("close", {
260
+ code: event.code,
261
+ reason: event.reason,
262
+ willReconnect
263
+ });
264
+ if (wasConnecting) rejectOnce(closeError);
265
+ if (willReconnect) this.scheduleReconnect(event.code, event.reason);
266
+ };
267
+ });
268
+ return this.connectPromise;
269
+ }
270
+ async disconnect(code = 1e3, reason = "manual") {
271
+ this.manuallyClosed = true;
272
+ this.clearReconnectTimer();
273
+ this.stopPingLoop();
274
+ this.state = "closed";
275
+ this.rejectAuthWaiter(/* @__PURE__ */ new Error("disconnected"));
276
+ this.ws?.close(code, reason);
277
+ this.ws = null;
278
+ this.connectPromise = null;
279
+ this.compactStreamContexts.clear();
280
+ this.patchStreamBuffers.clear();
281
+ for (const state of this.roomSubscriptions.values()) {
282
+ state.subscribed = false;
283
+ state.pending = false;
284
+ }
285
+ }
286
+ async sendCanvasTransaction(input) {
287
+ await this.ensureOpen();
288
+ this.send({
289
+ type: "canvas.tx",
290
+ requestId: input.requestId,
291
+ payload: {
292
+ spaceId: input.spaceId,
293
+ documentId: input.documentId,
294
+ txId: input.txId,
295
+ baseVersion: input.baseVersion ?? null,
296
+ clientId: input.clientId ?? null,
297
+ undoGroupId: input.undoGroupId ?? null,
298
+ ops: input.ops
299
+ }
300
+ });
301
+ }
302
+ async updatePresence(input) {
303
+ await this.ensureOpen();
304
+ this.send({
305
+ type: "presence.update",
306
+ requestId: input.requestId,
307
+ payload: {
308
+ spaceId: input.spaceId,
309
+ meta: input.meta ?? null
310
+ }
311
+ });
312
+ }
313
+ async sendMessage(input) {
314
+ await this.ensureOpen();
315
+ this.send({
316
+ type: "session.message.create",
317
+ requestId: input.requestId,
318
+ payload: {
319
+ spaceId: input.spaceId,
320
+ sessionId: input.sessionId,
321
+ content: input.content,
322
+ clientMessageId: input.clientMessageId,
323
+ model: input.model,
324
+ provider: input.provider
325
+ }
326
+ });
327
+ }
328
+ retainRooms(rooms) {
329
+ const normalized = normalizeRealtimeRooms(rooms);
330
+ if (normalized.length === 0) return () => void 0;
331
+ for (const room of normalized) {
332
+ const state = this.roomSubscriptions.get(room) ?? {
333
+ refCount: 0,
334
+ subscribed: false,
335
+ pending: false
336
+ };
337
+ state.refCount += 1;
338
+ this.roomSubscriptions.set(room, state);
339
+ }
340
+ this.flushRoomSubscriptions();
341
+ if (this.state !== "open" && this.state !== "connecting" && this.state !== "reconnecting") this.connect().then(() => this.flushRoomSubscriptions()).catch((error) => this.emit("error", {
342
+ error,
343
+ recoverable: true
344
+ }));
345
+ let released = false;
346
+ return () => {
347
+ if (released) return;
348
+ released = true;
349
+ const roomsToRelease = [];
350
+ for (const room of normalized) {
351
+ const state = this.roomSubscriptions.get(room);
352
+ if (!state) continue;
353
+ state.refCount -= 1;
354
+ if (state.refCount > 0) {
355
+ this.roomSubscriptions.set(room, state);
356
+ continue;
357
+ }
358
+ this.roomSubscriptions.delete(room);
359
+ if (state.subscribed) roomsToRelease.push(room);
360
+ }
361
+ if (roomsToRelease.length === 0) return;
362
+ if (this.ws?.readyState === WebSocket.OPEN) this.send({
363
+ type: "unsubscribe",
364
+ payload: { rooms: roomsToRelease }
365
+ });
366
+ };
367
+ }
368
+ subscribeRooms(rooms) {
369
+ return this.retainRooms(rooms);
370
+ }
371
+ subscribeSpace(spaceId) {
372
+ return this.retainRooms([getRealtimeSpaceRoom(spaceId)]);
373
+ }
374
+ ack(eventId, requestId) {
375
+ this.send({
376
+ type: "ack",
377
+ requestId,
378
+ payload: eventId ? { eventId } : void 0
379
+ });
380
+ }
381
+ ping(requestId) {
382
+ const effectiveRequestId = requestId ?? `ping-${Date.now()}`;
383
+ this.awaitingPong = true;
384
+ this.lastPingRequestId = effectiveRequestId;
385
+ this.pongDeadlineAt = Date.now() + this.pongTimeoutMs;
386
+ this.send({
387
+ type: "ping",
388
+ requestId: effectiveRequestId,
389
+ payload: {}
390
+ });
391
+ }
392
+ async ensureOpen() {
393
+ if (this.state === "open" && this.ws?.readyState === WebSocket.OPEN) return;
394
+ await this.connect();
395
+ }
396
+ send(event) {
397
+ const ws = this.ws;
398
+ if (!ws || ws.readyState !== WebSocket.OPEN) throw new Error("websocket is not open");
399
+ ws.send(JSON.stringify(event));
400
+ }
401
+ async authenticate() {
402
+ const token = this.getAccessToken ? await this.getAccessToken() : null;
403
+ if (!token) throw new WebsocketAuthError("missing access token");
404
+ const waiter = this.createAuthWaiter();
405
+ this.send({
406
+ type: "auth",
407
+ payload: {
408
+ token,
409
+ capabilities: [WS_COMPACT_STREAM_CAPABILITY, WS_ROOM_SUBSCRIPTION_CAPABILITY]
410
+ }
411
+ });
412
+ await waiter.promise;
413
+ await this.restoreRoomSubscriptions();
414
+ }
415
+ flushRoomSubscriptions() {
416
+ if (this.ws?.readyState !== WebSocket.OPEN) return;
417
+ const rooms = [...this.roomSubscriptions.entries()].filter(([, state]) => state.refCount > 0 && !state.subscribed && !state.pending).map(([room]) => room);
418
+ if (rooms.length === 0) return;
419
+ this.send({
420
+ type: "subscribe",
421
+ payload: { rooms }
422
+ });
423
+ for (const room of rooms) {
424
+ const state = this.roomSubscriptions.get(room);
425
+ if (state) state.pending = true;
426
+ }
427
+ }
428
+ async restoreRoomSubscriptions() {
429
+ for (const state of this.roomSubscriptions.values()) state.subscribed = false;
430
+ this.flushRoomSubscriptions();
431
+ }
432
+ createAuthWaiter() {
433
+ this.rejectAuthWaiter(/* @__PURE__ */ new Error("superseded auth waiter"));
434
+ let resolve;
435
+ let reject;
436
+ const promise = new Promise((res, rej) => {
437
+ resolve = res;
438
+ reject = rej;
439
+ });
440
+ this.authWaiter = {
441
+ promise,
442
+ resolve,
443
+ reject
444
+ };
445
+ return this.authWaiter;
446
+ }
447
+ resolveAuthWaiter() {
448
+ if (!this.authWaiter) return;
449
+ this.authWaiter.resolve();
450
+ this.authWaiter = null;
451
+ }
452
+ rejectAuthWaiter(error) {
453
+ if (!this.authWaiter) return;
454
+ this.authWaiter.reject(error);
455
+ this.authWaiter = null;
456
+ }
457
+ handleMessage(raw) {
458
+ let parsed;
459
+ try {
460
+ parsed = typeof raw === "string" ? JSON.parse(raw) : JSON.parse(String(raw));
461
+ } catch {
462
+ this.emit("error", {
463
+ error: /* @__PURE__ */ new Error("invalid websocket payload"),
464
+ recoverable: true
465
+ });
466
+ return;
467
+ }
468
+ if (isRealtimeCompactFrame(parsed)) {
469
+ this.handleCompactFrame(parsed);
470
+ return;
471
+ }
472
+ if (!isRealtimeEnvelope(parsed)) {
473
+ this.emit("error", {
474
+ error: /* @__PURE__ */ new Error("invalid realtime envelope"),
475
+ recoverable: true
476
+ });
477
+ return;
478
+ }
479
+ const envelope = parsed;
480
+ this.rememberCompactStreamContext(envelope);
481
+ if (envelope.type === "session.turn.patch") {
482
+ this.handlePatchEnvelope(envelope);
483
+ return;
484
+ }
485
+ switch (envelope.type) {
486
+ case "system.ready": {
487
+ const connectionId = typeof envelope.payload.connectionId === "string" ? envelope.payload.connectionId : null;
488
+ if (connectionId) {
489
+ this.connectionId = connectionId;
490
+ this.emit("ready", { connectionId });
491
+ }
492
+ this.emit("event", envelope);
493
+ return;
494
+ }
495
+ case "system.auth.ok": {
496
+ const connectionId = typeof envelope.payload.connectionId === "string" ? envelope.payload.connectionId : this.connectionId;
497
+ const user = envelope.payload.user && typeof envelope.payload.user === "object" ? envelope.payload.user : {};
498
+ if (connectionId) {
499
+ this.connectionId = connectionId;
500
+ this.emit("auth", {
501
+ connectionId,
502
+ user
503
+ });
504
+ }
505
+ this.resolveAuthWaiter();
506
+ this.emit("event", envelope);
507
+ return;
508
+ }
509
+ case "system.request.error": {
510
+ const message = typeof envelope.payload.message === "string" ? envelope.payload.message : "request failed";
511
+ const code = typeof envelope.payload.code === "string" ? envelope.payload.code : void 0;
512
+ const error = new WebsocketAuthError(message);
513
+ this.rejectAuthWaiter(error);
514
+ this.emit("serverError", {
515
+ code,
516
+ message,
517
+ requestId: envelope.requestId ?? null,
518
+ sessionId: envelope.sessionId ?? null,
519
+ spaceId: envelope.spaceId ?? null
520
+ });
521
+ this.emit("event", envelope);
522
+ return;
523
+ }
524
+ case "session.request.accepted": {
525
+ const payload = envelope.payload;
526
+ this.emit("messageAccepted", {
527
+ requestId: envelope.requestId ?? null,
528
+ sessionId: envelope.sessionId ?? null,
529
+ spaceId: envelope.spaceId ?? null,
530
+ clientMessageId: typeof payload.clientMessageId === "string" ? payload.clientMessageId : null,
531
+ turnId: typeof payload.turnId === "string" ? payload.turnId : null,
532
+ userMessageId: typeof payload.userMessageId === "string" ? payload.userMessageId : null,
533
+ traceId: typeof payload.traceId === "string" ? payload.traceId : null
534
+ });
535
+ this.emit("event", envelope);
536
+ return;
537
+ }
538
+ case "session.request.error": {
539
+ const payload = envelope.payload;
540
+ this.emit("serverError", {
541
+ code: typeof payload.code === "string" ? payload.code : void 0,
542
+ message: typeof payload.message === "string" ? payload.message : void 0,
543
+ requestId: envelope.requestId ?? null,
544
+ sessionId: envelope.sessionId ?? null,
545
+ spaceId: envelope.spaceId ?? null,
546
+ clientMessageId: typeof payload.clientMessageId === "string" ? payload.clientMessageId : null,
547
+ billing: extractBillingPayload(payload.billing)
548
+ });
549
+ this.emit("event", envelope);
550
+ return;
551
+ }
552
+ case "system.pong": {
553
+ const requestId = envelope.requestId ?? null;
554
+ if (!requestId || requestId === this.lastPingRequestId) {
555
+ this.awaitingPong = false;
556
+ this.lastPingRequestId = null;
557
+ this.pongDeadlineAt = 0;
558
+ }
559
+ this.emit("pong", { requestId });
560
+ return;
561
+ }
562
+ case "system.subscribe.ok": {
563
+ const payload = envelope.payload;
564
+ const rooms = normalizeRealtimeRooms(Array.isArray(payload.rooms) ? payload.rooms.filter((room) => typeof room === "string") : []);
565
+ for (const room of rooms) {
566
+ const state = this.roomSubscriptions.get(room);
567
+ if (state) {
568
+ state.subscribed = true;
569
+ state.pending = false;
570
+ }
571
+ }
572
+ this.emit("subscribed", {
573
+ rooms,
574
+ requestId: envelope.requestId ?? null
575
+ });
576
+ this.emit("event", envelope);
577
+ return;
578
+ }
579
+ case "system.subscribe.error": {
580
+ const payload = envelope.payload;
581
+ const rejected = Array.isArray(payload.rejected) ? payload.rejected.filter((entry) => Boolean(entry && typeof entry === "object")).map((entry) => ({
582
+ room: typeof entry.room === "string" ? entry.room : "",
583
+ code: typeof entry.code === "string" ? entry.code : "UNKNOWN",
584
+ message: typeof entry.message === "string" ? entry.message : "Subscription failed"
585
+ })).filter((entry) => entry.room) : [];
586
+ for (const item of rejected) {
587
+ const room = normalizeRealtimeRooms([item.room])[0];
588
+ if (!room) continue;
589
+ this.roomSubscriptions.delete(room);
590
+ }
591
+ this.emit("subscribeError", {
592
+ rejected,
593
+ requestId: envelope.requestId ?? null
594
+ });
595
+ this.emit("event", envelope);
596
+ return;
597
+ }
598
+ case "system.ack.ok": return;
599
+ default:
600
+ this.emit("event", envelope);
601
+ return;
602
+ }
603
+ }
604
+ rememberCompactStreamContext(envelope) {
605
+ if (envelope.type === "session.turn.patch") {
606
+ const payload = envelope.payload;
607
+ const turnId = typeof payload.turnId === "string" ? payload.turnId : null;
608
+ const messageId = typeof payload.messageId === "string" ? payload.messageId : null;
609
+ const realtimeMeta = payload._rt && typeof payload._rt === "object" ? payload._rt : null;
610
+ const sid = typeof realtimeMeta?.sid === "string" && realtimeMeta.sid.trim() ? realtimeMeta.sid : turnId ?? messageId;
611
+ if (!sid) return;
612
+ this.compactStreamContexts.set(sid, {
613
+ spaceId: envelope.spaceId ?? null,
614
+ sessionId: envelope.sessionId ?? null,
615
+ turnId,
616
+ messageId,
617
+ messageOrdinal: typeof payload.messageOrdinal === "number" ? payload.messageOrdinal : null,
618
+ anchorUserMessageId: typeof payload.anchorUserMessageId === "string" ? payload.anchorUserMessageId : null
619
+ });
620
+ return;
621
+ }
622
+ if (envelope.type !== "session.message.persisted") return;
623
+ const message = envelope.payload.message;
624
+ if (!message || typeof message !== "object") return;
625
+ const meta = message.meta;
626
+ const turnId = typeof meta?.turnId === "string" ? meta.turnId : null;
627
+ if (!turnId) return;
628
+ for (const [sid, context] of this.compactStreamContexts.entries()) if (context.turnId === turnId) {
629
+ this.compactStreamContexts.delete(sid);
630
+ this.patchStreamBuffers.delete(sid);
631
+ }
632
+ }
633
+ getPatchStreamBufferKey(envelope) {
634
+ if (envelope.type !== "session.turn.patch") return null;
635
+ const payload = envelope.payload;
636
+ const realtimeMeta = payload._rt && typeof payload._rt === "object" ? payload._rt : null;
637
+ if (typeof realtimeMeta?.sid === "string" && realtimeMeta.sid.trim()) return realtimeMeta.sid;
638
+ return getSessionTurnPatchStreamKey(payload, { includeSessionFallback: true });
639
+ }
640
+ handlePatchEnvelope(envelope) {
641
+ const payload = envelope.payload;
642
+ if (typeof payload.seq !== "number" || typeof payload.baseSeq !== "number" || !Number.isInteger(payload.seq) || !Number.isInteger(payload.baseSeq) || payload.seq < 0 || payload.baseSeq < 0) {
643
+ this.emit("event", envelope);
644
+ return;
645
+ }
646
+ const key = this.getPatchStreamBufferKey(envelope);
647
+ if (!key) {
648
+ this.emit("event", envelope);
649
+ return;
650
+ }
651
+ if (payload.baseSeq === 0) {
652
+ const buffer = {
653
+ nextSeq: payload.seq + 1,
654
+ pending: /* @__PURE__ */ new Map()
655
+ };
656
+ this.patchStreamBuffers.set(key, buffer);
657
+ this.emit("event", envelope);
658
+ this.flushPatchStreamBuffer(buffer);
659
+ return;
660
+ }
661
+ const buffer = this.patchStreamBuffers.get(key);
662
+ if (!buffer) {
663
+ const newBuffer = {
664
+ nextSeq: payload.baseSeq + 1,
665
+ pending: new Map([[payload.seq, envelope]])
666
+ };
667
+ this.patchStreamBuffers.set(key, newBuffer);
668
+ this.flushPatchStreamBuffer(newBuffer);
669
+ return;
670
+ }
671
+ if (payload.seq < buffer.nextSeq) return;
672
+ buffer.pending.set(payload.seq, envelope);
673
+ if (!this.enforcePatchStreamBufferLimit(key, buffer)) return;
674
+ this.flushPatchStreamBuffer(buffer);
675
+ }
676
+ enforcePatchStreamBufferLimit(key, buffer) {
677
+ if (buffer.pending.size <= PATCH_STREAM_BUFFER_MAX_PENDING) return true;
678
+ this.patchStreamBuffers.delete(key);
679
+ this.emit("error", {
680
+ error: /* @__PURE__ */ new Error(`patch stream buffer overflow: ${key}`),
681
+ recoverable: true
682
+ });
683
+ return false;
684
+ }
685
+ flushPatchStreamBuffer(buffer) {
686
+ while (true) {
687
+ const envelope = buffer.pending.get(buffer.nextSeq);
688
+ if (!envelope) return;
689
+ const seq = envelope.payload.seq;
690
+ if (typeof seq !== "number" || !Number.isInteger(seq)) return;
691
+ buffer.pending.delete(buffer.nextSeq);
692
+ buffer.nextSeq = seq + 1;
693
+ this.emit("event", envelope);
694
+ }
695
+ }
696
+ handleCompactFrame(frame) {
697
+ const context = this.compactStreamContexts.get(frame.sid);
698
+ if (!context?.sessionId) {
699
+ this.emit("error", {
700
+ error: /* @__PURE__ */ new Error(`unknown compact stream: ${frame.sid}`),
701
+ recoverable: true
702
+ });
703
+ return;
704
+ }
705
+ const op = compactFrameToPatchOperation(frame);
706
+ if (!op) {
707
+ this.emit("error", {
708
+ error: /* @__PURE__ */ new Error(`invalid compact stream frame: ${frame.sid}`),
709
+ recoverable: true
710
+ });
711
+ return;
712
+ }
713
+ const envelope = {
714
+ id: `compact:${frame.sid}:${frame.s}`,
715
+ timestamp: Date.now(),
716
+ domain: "session",
717
+ type: "session.turn.patch",
718
+ spaceId: context.spaceId,
719
+ sessionId: context.sessionId,
720
+ payload: {
721
+ turnId: context.turnId,
722
+ messageId: context.messageId,
723
+ messageOrdinal: context.messageOrdinal,
724
+ sourceMessageId: context.messageId,
725
+ anchorUserMessageId: context.anchorUserMessageId,
726
+ seq: frame.s,
727
+ baseSeq: frame.b,
728
+ ops: [op],
729
+ _rt: { sid: frame.sid }
730
+ }
731
+ };
732
+ this.handlePatchEnvelope(envelope);
733
+ }
734
+ startPingLoop() {
735
+ this.stopPingLoop();
736
+ this.pingTimer = setInterval(() => {
737
+ if (this.ws?.readyState !== WebSocket.OPEN) return;
738
+ if (this.awaitingPong && this.pongDeadlineAt > 0 && Date.now() > this.pongDeadlineAt) {
739
+ this.emit("error", {
740
+ error: /* @__PURE__ */ new Error("websocket pong timeout"),
741
+ recoverable: true
742
+ });
743
+ this.ws.close(4002, "pong timeout");
744
+ return;
745
+ }
746
+ this.ping();
747
+ }, this.pingIntervalMs);
748
+ }
749
+ stopPingLoop() {
750
+ if (this.pingTimer) {
751
+ clearInterval(this.pingTimer);
752
+ this.pingTimer = null;
753
+ }
754
+ this.awaitingPong = false;
755
+ this.lastPingRequestId = null;
756
+ this.pongDeadlineAt = 0;
757
+ }
758
+ clearReconnectTimer() {
759
+ if (this.reconnectTimer) {
760
+ clearTimeout(this.reconnectTimer);
761
+ this.reconnectTimer = null;
762
+ }
763
+ if (this.reconnectTimerResolver) {
764
+ const resolve = this.reconnectTimerResolver;
765
+ this.reconnectTimerResolver = null;
766
+ resolve();
767
+ }
768
+ }
769
+ async scheduleReconnect(code, reason) {
770
+ this.clearReconnectTimer();
771
+ const attempt = this.reconnectAttempt + 1;
772
+ const delay = Math.min(this.reconnectBaseDelayMs * 2 ** this.reconnectAttempt, this.reconnectMaxDelayMs);
773
+ this.reconnectAttempt = attempt;
774
+ this.state = "reconnecting";
775
+ this.log("schedule reconnect", {
776
+ attempt,
777
+ delay,
778
+ code,
779
+ reason
780
+ });
781
+ this.emit("reconnecting", {
782
+ attempt,
783
+ delayMs: delay,
784
+ code,
785
+ reason
786
+ });
787
+ await new Promise((resolve) => {
788
+ this.reconnectTimerResolver = resolve;
789
+ this.reconnectTimer = setTimeout(() => {
790
+ this.reconnectTimer = null;
791
+ this.reconnectTimerResolver = null;
792
+ resolve();
793
+ }, delay);
794
+ });
795
+ if (this.manuallyClosed) return;
796
+ if (typeof navigator !== "undefined" && navigator.onLine === false) {
797
+ await new Promise((resolve) => {
798
+ const fallbackTimer = setTimeout(resolve, this.reconnectMaxDelayMs);
799
+ const handleOnline = () => {
800
+ clearTimeout(fallbackTimer);
801
+ globalThis.removeEventListener?.("online", handleOnline);
802
+ resolve();
803
+ };
804
+ globalThis.addEventListener?.("online", handleOnline, { once: true });
805
+ });
806
+ if (this.manuallyClosed) return;
807
+ }
808
+ await this.connect().catch((error) => {
809
+ this.emit("error", {
810
+ error,
811
+ recoverable: true
812
+ });
813
+ });
814
+ }
815
+ };
816
+ const createWebsocketClient = (options) => new WebsocketClient(options);
817
+ //#endregion
818
+ export { extractBillingPayload as a, isFeatureNotEntitledError as c, FEATURE_NOT_ENTITLED_ERROR_CODE as i, isHttpErrorCode as l, createWebsocketClient as n, isBillingAccessBlockedCode as o, BILLING_ACCESS_BLOCKED_ERROR_CODE as r, isBillingAccessBlockedError as s, WebsocketClient as t };