@noverachat/sdk-web 0.0.3

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/index.cjs ADDED
@@ -0,0 +1,1737 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ErrorCode: () => ErrorCode,
24
+ NoveraChat: () => NoveraChat,
25
+ NoveraChatError: () => NoveraChatError,
26
+ Room: () => Room
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+
30
+ // src/errors.ts
31
+ var ErrorCode = {
32
+ INTERNAL: "NC-GEN-001",
33
+ NOT_FOUND: "NC-GEN-002",
34
+ VALIDATION: "NC-GEN-003",
35
+ FORBIDDEN: "NC-GEN-004",
36
+ UNAUTHORIZED: "NC-AUTH-001",
37
+ TOKEN_EXPIRED: "NC-AUTH-002",
38
+ TOKEN_INVALID: "NC-AUTH-003",
39
+ TOKEN_REVOKED: "NC-AUTH-004",
40
+ APP_INACTIVE: "NC-APP-001",
41
+ APP_NOT_FOUND: "NC-APP-002",
42
+ USER_BANNED: "NC-USER-001",
43
+ USER_NOT_FOUND: "NC-USER-002",
44
+ ROOM_NOT_FOUND: "NC-ROOM-001",
45
+ ROOM_FROZEN: "NC-ROOM-002",
46
+ NOT_A_MEMBER: "NC-ROOM-003",
47
+ MESSAGE_TOO_LARGE: "NC-MSG-001",
48
+ MESSAGE_NOT_FOUND: "NC-MSG-002",
49
+ MESSAGE_EDIT_FORBID: "NC-MSG-003",
50
+ RATE_LIMITED: "NC-RATE-001"
51
+ };
52
+ var NoveraChatError = class _NoveraChatError extends Error {
53
+ code;
54
+ status;
55
+ details;
56
+ constructor(message, code = ErrorCode.INTERNAL, status = 0, details) {
57
+ super(message);
58
+ this.name = "NoveraChatError";
59
+ this.code = code;
60
+ this.status = status;
61
+ if (details !== void 0) this.details = details;
62
+ }
63
+ static fromResponse(status, body) {
64
+ const rec = body;
65
+ const code = rec?.error?.code ?? ErrorCode.INTERNAL;
66
+ const msg = rec?.error?.message ?? `HTTP ${status}`;
67
+ const details = rec?.error?.details;
68
+ return details !== void 0 ? new _NoveraChatError(msg, code, status, details) : new _NoveraChatError(msg, code, status);
69
+ }
70
+ };
71
+
72
+ // src/transport/http.ts
73
+ var HttpClient = class {
74
+ constructor(opts) {
75
+ this.opts = opts;
76
+ }
77
+ opts;
78
+ async request(method, path, body, query) {
79
+ const token = await this.opts.tokenProvider();
80
+ const url = this.buildUrl(path, query);
81
+ const init = {
82
+ method,
83
+ headers: {
84
+ "Authorization": `Bearer ${token}`,
85
+ "X-Noverachat-App-Id": this.opts.appId,
86
+ ...body != null ? { "Content-Type": "application/json" } : {}
87
+ }
88
+ };
89
+ if (body != null) init.body = JSON.stringify(body);
90
+ const fetchFn = this.opts.fetch ?? globalThis.fetch;
91
+ this.opts.logger?.(
92
+ "debug",
93
+ `rest_req ${method} ${path}`,
94
+ body != null ? { body, query } : { query }
95
+ );
96
+ const startedAt = Date.now();
97
+ const res = await fetchFn(url, init);
98
+ const elapsedMs = Date.now() - startedAt;
99
+ if (res.status === 204) {
100
+ this.opts.logger?.(
101
+ "debug",
102
+ `rest_res ${method} ${path} 204 ${elapsedMs}ms`
103
+ );
104
+ return void 0;
105
+ }
106
+ const text = await res.text();
107
+ const parsed = text ? JSON.parse(text) : null;
108
+ this.opts.logger?.(
109
+ "debug",
110
+ `rest_res ${method} ${path} ${res.status} ${elapsedMs}ms`,
111
+ parsed
112
+ );
113
+ if (!res.ok) {
114
+ throw NoveraChatError.fromResponse(res.status, parsed);
115
+ }
116
+ return parsed;
117
+ }
118
+ buildUrl(path, query) {
119
+ const base = this.opts.baseUrl.replace(/\/+$/, "");
120
+ const url = new URL(base + path);
121
+ if (query) {
122
+ for (const [k, v] of Object.entries(query)) {
123
+ if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
124
+ }
125
+ }
126
+ return url.toString();
127
+ }
128
+ };
129
+
130
+ // src/transport/ws.ts
131
+ var NO_RECONNECT = /* @__PURE__ */ new Set([1008, 4001, 4002, 4003]);
132
+ var ReconnectingWs = class _ReconnectingWs {
133
+ constructor(opts) {
134
+ this.opts = opts;
135
+ }
136
+ opts;
137
+ ws = null;
138
+ state = "idle";
139
+ attempt = 0;
140
+ pingTimer = null;
141
+ explicitClose = false;
142
+ // Outbound buffer used while the socket is transiently down (reconnect
143
+ // window between a server-side close and the next successful open). FIFO.
144
+ // Capped to avoid an unbounded queue if the server is hard-down — chat_send
145
+ // bursts past the cap are dropped (caller sees `send -> false` the usual
146
+ // way). Pings and typing frames are NOT queued: pings are stateless
147
+ // heartbeats and a stale typing event is worse than no event.
148
+ outboundQueue = [];
149
+ static OUTBOUND_QUEUE_CAP = 200;
150
+ get currentState() {
151
+ return this.state;
152
+ }
153
+ async connect() {
154
+ this.explicitClose = false;
155
+ await this.openOnce();
156
+ }
157
+ close() {
158
+ this.explicitClose = true;
159
+ this.setState("closed");
160
+ if (this.pingTimer) clearInterval(this.pingTimer);
161
+ this.pingTimer = null;
162
+ this.outboundQueue = [];
163
+ this.ws?.close(1e3, "client close");
164
+ this.ws = null;
165
+ }
166
+ send(msg) {
167
+ if (this.ws && this.ws.readyState === 1) {
168
+ this.ws.send(JSON.stringify(msg));
169
+ this.opts.logger?.("debug", `ws_send ${msg.type}`, msg);
170
+ return true;
171
+ }
172
+ if (msg.type === "ping" || msg.type === "typing") return false;
173
+ if (this.explicitClose || this.state === "closed") return false;
174
+ if (this.outboundQueue.length >= _ReconnectingWs.OUTBOUND_QUEUE_CAP) {
175
+ this.opts.logger?.(
176
+ "warn",
177
+ "ws_outbound_queue_full",
178
+ { cap: _ReconnectingWs.OUTBOUND_QUEUE_CAP, dropping: msg.type }
179
+ );
180
+ return false;
181
+ }
182
+ this.outboundQueue.push(msg);
183
+ this.opts.logger?.(
184
+ "debug",
185
+ `ws_send_queued ${msg.type}`,
186
+ { queueLen: this.outboundQueue.length }
187
+ );
188
+ return true;
189
+ }
190
+ async openOnce() {
191
+ this.setState(this.attempt === 0 ? "connecting" : "reconnecting");
192
+ const WSImpl = this.opts.WebSocketImpl ?? globalThis.WebSocket;
193
+ if (!WSImpl) throw new Error("No WebSocket implementation available");
194
+ let url;
195
+ try {
196
+ url = await this.opts.urlBuilder();
197
+ } catch (err) {
198
+ this.opts.logger?.("error", "url_builder_failed", err);
199
+ this.scheduleReconnect();
200
+ return;
201
+ }
202
+ const ws = new WSImpl(url);
203
+ this.ws = ws;
204
+ ws.onopen = () => {
205
+ this.attempt = 0;
206
+ this.setState("open");
207
+ this.startPings();
208
+ if (this.outboundQueue.length > 0) {
209
+ const drained = this.outboundQueue;
210
+ this.outboundQueue = [];
211
+ this.opts.logger?.("info", "ws_outbound_drained", { count: drained.length });
212
+ for (const m of drained) {
213
+ try {
214
+ ws.send(JSON.stringify(m));
215
+ } catch (err) {
216
+ this.opts.logger?.("warn", "ws_outbound_drain_failed", err);
217
+ }
218
+ }
219
+ }
220
+ this.opts.onOpen?.();
221
+ };
222
+ ws.onmessage = (ev) => {
223
+ try {
224
+ const data = typeof ev.data === "string" ? ev.data : ev.data.toString();
225
+ const parsed = JSON.parse(data);
226
+ this.opts.logger?.(
227
+ "debug",
228
+ `ws_recv ${parsed.type ?? "?"}`,
229
+ parsed
230
+ );
231
+ this.opts.onMessage(parsed);
232
+ } catch (err) {
233
+ this.opts.logger?.("warn", "ws_parse_failed", err);
234
+ }
235
+ };
236
+ ws.onerror = (ev) => {
237
+ this.opts.logger?.("warn", "ws_error", ev);
238
+ };
239
+ ws.onclose = (ev) => {
240
+ this.stopPings();
241
+ this.ws = null;
242
+ if (this.explicitClose) {
243
+ this.setState("closed");
244
+ return;
245
+ }
246
+ if (NO_RECONNECT.has(ev.code)) {
247
+ this.opts.logger?.("warn", "ws_fatal_close", { code: ev.code, reason: ev.reason });
248
+ this.setState("closed");
249
+ return;
250
+ }
251
+ if (this.opts.autoReconnect) this.scheduleReconnect();
252
+ else this.setState("closed");
253
+ };
254
+ }
255
+ scheduleReconnect() {
256
+ this.attempt += 1;
257
+ const base = 500;
258
+ const cap = this.opts.maxReconnectDelayMs;
259
+ const exp = Math.min(cap, base * 2 ** (this.attempt - 1));
260
+ const jitter = Math.floor(Math.random() * base);
261
+ const delay = exp + jitter;
262
+ this.opts.logger?.("info", "ws_reconnect_scheduled", { attempt: this.attempt, delay });
263
+ this.setState("reconnecting");
264
+ setTimeout(() => {
265
+ void this.openOnce();
266
+ }, delay);
267
+ }
268
+ startPings() {
269
+ this.stopPings();
270
+ this.pingTimer = setInterval(() => {
271
+ this.send({ type: "ping", client_ts: Date.now() });
272
+ }, this.opts.pingIntervalMs);
273
+ }
274
+ stopPings() {
275
+ if (this.pingTimer) clearInterval(this.pingTimer);
276
+ this.pingTimer = null;
277
+ }
278
+ setState(s) {
279
+ if (s === this.state) return;
280
+ this.state = s;
281
+ this.opts.onStateChange?.(s);
282
+ }
283
+ };
284
+
285
+ // src/internal/event-bus.ts
286
+ var EventBus = class {
287
+ handlers = {};
288
+ on(event, fn) {
289
+ let set = this.handlers[event];
290
+ if (!set) {
291
+ set = /* @__PURE__ */ new Set();
292
+ this.handlers[event] = set;
293
+ }
294
+ set.add(fn);
295
+ return () => this.off(event, fn);
296
+ }
297
+ off(event, fn) {
298
+ this.handlers[event]?.delete(fn);
299
+ }
300
+ emit(event, payload) {
301
+ const set = this.handlers[event];
302
+ if (!set) return;
303
+ for (const h of set) {
304
+ try {
305
+ h(payload);
306
+ } catch {
307
+ }
308
+ }
309
+ }
310
+ removeAll() {
311
+ this.handlers = {};
312
+ }
313
+ };
314
+
315
+ // src/internal/temp-id.ts
316
+ function tempId() {
317
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
318
+ return `tmp_${crypto.randomUUID()}`;
319
+ }
320
+ const bytes = Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
321
+ return "tmp_" + bytes.map((b) => b.toString(16).padStart(2, "0")).join("");
322
+ }
323
+
324
+ // src/features/room.ts
325
+ function toMessageOut(r) {
326
+ const dataObj = r.data ?? null;
327
+ const customMeta = dataObj && typeof dataObj === "object" && "_customMeta" in dataObj ? dataObj._customMeta : null;
328
+ return {
329
+ appId: r.app_id,
330
+ roomId: r.room_id,
331
+ messageId: r.message_id,
332
+ sender: r.sender ? {
333
+ userId: r.sender.user_id,
334
+ nickname: r.sender.nickname ?? null,
335
+ profileImageUrl: r.sender.profile_image_url ?? null
336
+ } : null,
337
+ senderId: r.sender_id ?? null,
338
+ messageType: r.message_type,
339
+ customType: r.custom_type ?? null,
340
+ content: r.content ?? null,
341
+ data: dataObj,
342
+ meta: r.meta ?? null,
343
+ customMeta,
344
+ fileId: r.file_id ?? null,
345
+ file: r.file ? {
346
+ id: r.file.id,
347
+ kind: r.file.kind,
348
+ mime: r.file.mime,
349
+ size: r.file.size,
350
+ name: r.file.name ?? null,
351
+ width: r.file.width ?? null,
352
+ height: r.file.height ?? null,
353
+ durationSec: r.file.duration_sec ?? null,
354
+ thumbnailStatus: r.file.thumbnail_status,
355
+ forwardBlocked: Boolean(r.file.forward_blocked)
356
+ } : null,
357
+ files: r.files && r.files.length > 0 ? r.files.map((f) => ({
358
+ id: f.id,
359
+ kind: f.kind,
360
+ mime: f.mime,
361
+ size: f.size,
362
+ name: f.name ?? null,
363
+ width: f.width ?? null,
364
+ height: f.height ?? null,
365
+ durationSec: f.duration_sec ?? null,
366
+ thumbnailStatus: f.thumbnail_status,
367
+ forwardBlocked: Boolean(f.forward_blocked)
368
+ })) : null,
369
+ replyToId: r.reply_to_id ?? null,
370
+ reactions: (r.reactions ?? []).map((x) => ({
371
+ key: x.key,
372
+ userIds: x.user_ids,
373
+ updatedAt: x.updated_at
374
+ })),
375
+ createdAt: r.created_at,
376
+ createdAtMs: r.created_at_ms,
377
+ updatedAt: r.updated_at ?? null,
378
+ updatedAtMs: r.updated_at_ms ?? null,
379
+ deletedAt: r.deleted_at ?? null,
380
+ deletedByUserId: r.deleted_by_user_id ?? null,
381
+ deleteScope: r.delete_scope ?? null,
382
+ editedCount: r.edited_count ?? 0
383
+ };
384
+ }
385
+ var Room = class _Room {
386
+ constructor(roomId, http, ws, readDebounceMs) {
387
+ this.roomId = roomId;
388
+ this.http = http;
389
+ this.ws = ws;
390
+ this.readDebounceMs = readDebounceMs;
391
+ }
392
+ roomId;
393
+ http;
394
+ ws;
395
+ bus = new EventBus();
396
+ // tempId → resolver pair. We keep `reject` alongside `resolve` so an
397
+ // incoming `error` frame carrying the offending temp_id (e.g.
398
+ // NC-RATE-001) can fail the send immediately rather than letting the
399
+ // 15s ack timeout fire — without correlation, a user hitting the
400
+ // per-tenant rate limit sees the chat hang on "PENDING…" forever.
401
+ //
402
+ // `payload` and `retries` enable transparent auto-retry of rate-limited
403
+ // sends: client.ts re-fires the same WS frame (same temp_id) with
404
+ // exponential backoff up to `MAX_RETRIES` instead of immediately failing
405
+ // the user's promise. Same temp_id keeps self-echo dedup correct in
406
+ // case the server actually processed the first attempt.
407
+ pendingAcks = /* @__PURE__ */ new Map();
408
+ // Retry policy for rate-limited (NC-RATE-001) sends. We cap at 1
409
+ // automatic retry — enough to swallow the normal jitter-induced spillover
410
+ // at the per-second token bucket boundary, but anything beyond that is
411
+ // a sustained rate-limit problem that the SDK shouldn't silently paper
412
+ // over. Subsequent failures bubble up to the caller so the UI can offer
413
+ // an explicit "Retry" button — manual retry is the right UX once we
414
+ // know the auto path didn't fix it.
415
+ // Backoff: ~300ms — long enough to land in a fresh 1s token bucket.
416
+ static MAX_RATE_LIMIT_RETRIES = 1;
417
+ static RATE_LIMIT_BACKOFF_MS = [300];
418
+ // Highest id we've sent via `read_watermark`. Used to drop redundant
419
+ // frames inside the debounce window. Compared via BigInt.
420
+ lastReadSent = null;
421
+ // Pending read_watermark — set by markRead, flushed after readDebounceMs
422
+ // OR immediately on flushMarkRead().
423
+ pendingReadMid = null;
424
+ readDebounceTimer = null;
425
+ readDebounceMs;
426
+ /**
427
+ * Every temp_id we've sent this session. The server echoes the same
428
+ * temp_id back on `chat_receive` for the sender's own sessions, so the
429
+ * client can dedup against its optimistic bubble regardless of whether
430
+ * the `ack` or the `chat_receive` arrives first. Unbounded growth is
431
+ * fine in practice (small strings, cleared on `chat.disconnect()`).
432
+ */
433
+ mySentTempIds = /* @__PURE__ */ new Set();
434
+ _sendPendingMarkRead() {
435
+ const mid = this.pendingReadMid;
436
+ if (!mid) return;
437
+ if (this.lastReadSent !== null) {
438
+ try {
439
+ if (BigInt(mid) <= BigInt(this.lastReadSent)) {
440
+ this.pendingReadMid = null;
441
+ return;
442
+ }
443
+ } catch {
444
+ if (mid <= this.lastReadSent) {
445
+ this.pendingReadMid = null;
446
+ return;
447
+ }
448
+ }
449
+ }
450
+ const ok = this.ws.send({
451
+ type: "read_watermark",
452
+ room_id: this.roomId,
453
+ last_read_message_id: mid
454
+ });
455
+ if (ok) {
456
+ this.lastReadSent = mid;
457
+ this.pendingReadMid = null;
458
+ }
459
+ }
460
+ // -------- outgoing --------
461
+ async send(params) {
462
+ const p = typeof params === "string" ? { content: params } : params;
463
+ const tempId2 = tempId();
464
+ const hasBundle = Array.isArray(p.fileIds) && p.fileIds.length > 0;
465
+ const messageType = p.messageType ?? (hasBundle || p.fileId ? "FILE" : "TEXT");
466
+ const baseData = p.data ?? {};
467
+ let outData = hasBundle ? {
468
+ ...baseData,
469
+ kind: "file_group",
470
+ file_ids: p.fileIds,
471
+ forward_blocked: Boolean(p.forwardBlocked)
472
+ } : p.data ?? null;
473
+ if (p.customMeta) {
474
+ outData = { ...outData ?? {}, _customMeta: p.customMeta };
475
+ }
476
+ const payload = {
477
+ type: "chat_send",
478
+ room_id: this.roomId,
479
+ message_type: messageType,
480
+ content: p.content ?? null,
481
+ custom_type: p.customType ?? null,
482
+ data: outData,
483
+ meta: p.meta ?? null,
484
+ // Bundle path sends file_id=null; the ids live in data.file_ids.
485
+ file_id: hasBundle ? null : p.fileId ?? null,
486
+ reply_to_id: p.replyToId ?? null,
487
+ forward_of_message_id: p.forwardOfMessageId ?? null,
488
+ temp_id: tempId2,
489
+ client_ts: Date.now()
490
+ };
491
+ this.mySentTempIds.add(tempId2);
492
+ const messageId = new Promise((resolve, reject) => {
493
+ const timer = setTimeout(() => {
494
+ this.pendingAcks.delete(tempId2);
495
+ this.mySentTempIds.delete(tempId2);
496
+ reject(new Error("ack timeout"));
497
+ }, 15e3);
498
+ this.pendingAcks.set(tempId2, {
499
+ resolve: (id) => {
500
+ clearTimeout(timer);
501
+ resolve(id);
502
+ },
503
+ reject: (err) => {
504
+ clearTimeout(timer);
505
+ reject(err);
506
+ },
507
+ payload,
508
+ retries: 0,
509
+ timer
510
+ });
511
+ });
512
+ const sent = this.ws.send(payload);
513
+ if (!sent) {
514
+ this.pendingAcks.delete(tempId2);
515
+ this.mySentTempIds.delete(tempId2);
516
+ throw new Error("ws not open");
517
+ }
518
+ return { tempId: tempId2, messageId };
519
+ }
520
+ /**
521
+ * Send an admin-uploaded emoticon as a STICKER-like message.
522
+ *
523
+ * Thin wrapper over ``send()``: stamps ``messageType: "EMOTICON"`` and
524
+ * fills ``data`` with the pack / item identifiers + a stable URL so the
525
+ * receiving client can render the bubble without a separate fetch.
526
+ *
527
+ * Pass either an ``EmoticonItem``-shaped object (matching the response
528
+ * of ``GET /v1/emoticon-packs``) or the raw ids + url. ``caption`` is
529
+ * optional — KakaoTalk-style sticker bubbles render fine without one.
530
+ */
531
+ async sendEmoticon(item, caption) {
532
+ return this.send({
533
+ content: caption ?? "",
534
+ messageType: "EMOTICON",
535
+ data: {
536
+ source: "emoticon",
537
+ pack_id: item.packId,
538
+ item_id: item.itemId,
539
+ file_id: item.fileId ?? "",
540
+ url: item.url
541
+ }
542
+ });
543
+ }
544
+ /**
545
+ * Send a file as a message. Wraps the three-step file pipeline:
546
+ *
547
+ * 1. ``POST /files`` to presign an S3 PUT
548
+ * 2. ``PUT`` the bytes direct to S3 (XHR — so we can report
549
+ * progress; ``fetch`` has no upload progress event)
550
+ * 3. ``POST /files/{id}/commit`` to flip the row to ``committed``
551
+ * and enqueue the thumbnail worker
552
+ * 4. ``room.send({ fileId, messageType: "FILE" })`` to broadcast
553
+ * the message to the room
554
+ *
555
+ * Returns the same ``{ tempId, messageId }`` shape as ``send()`` —
556
+ * callers reconcile the optimistic bubble against the eventual ack
557
+ * the same way text messages do.
558
+ *
559
+ * On any error before the final ``send()`` (upload aborted, S3
560
+ * rejected, commit failed) the row in ``files`` stays at
561
+ * ``upload_status=pending`` and the background cleanup worker
562
+ * reclaims it within ``FILE_PENDING_UPLOAD_TTL_SEC`` (24h default)
563
+ * — no client-side cleanup needed.
564
+ */
565
+ async sendFile(file, opts = {}) {
566
+ const kind = opts.kind ?? (file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "file");
567
+ const name = opts.name ?? file.name;
568
+ const presign = await this.http.request("POST", "/api/v1/files", {
569
+ kind,
570
+ mime: file.type || "application/octet-stream",
571
+ size: file.size,
572
+ original_name: name,
573
+ // 파일 전달 제한 — uploader-set at presign time. When true,
574
+ // other users can't forward this file to a different room.
575
+ forward_blocked: Boolean(opts.forwardBlocked)
576
+ });
577
+ const presigned = {
578
+ fileId: presign.file_id,
579
+ uploadUrl: presign.upload_url,
580
+ headers: presign.headers,
581
+ expiresAtMs: presign.expires_at_ms
582
+ };
583
+ await new Promise((resolve, reject) => {
584
+ const xhr = new XMLHttpRequest();
585
+ xhr.open("PUT", presigned.uploadUrl);
586
+ for (const [k, v] of Object.entries(presigned.headers)) {
587
+ xhr.setRequestHeader(k, v);
588
+ }
589
+ if (opts.onProgress) {
590
+ xhr.upload.addEventListener("progress", (e) => {
591
+ if (!e.lengthComputable) return;
592
+ opts.onProgress({
593
+ loaded: e.loaded,
594
+ total: e.total,
595
+ ratio: e.total > 0 ? e.loaded / e.total : 0
596
+ });
597
+ });
598
+ }
599
+ xhr.onload = () => {
600
+ if (xhr.status >= 200 && xhr.status < 300) {
601
+ opts.onProgress?.({ loaded: file.size, total: file.size, ratio: 1 });
602
+ resolve();
603
+ } else {
604
+ reject(new Error(`S3 PUT failed: ${xhr.status} ${xhr.statusText}`));
605
+ }
606
+ };
607
+ xhr.onerror = () => reject(new Error("S3 PUT network error"));
608
+ xhr.onabort = () => reject(new Error("S3 PUT aborted"));
609
+ xhr.send(file);
610
+ });
611
+ await this.http.request(
612
+ "POST",
613
+ `/api/v1/files/${presigned.fileId}/commit`,
614
+ {}
615
+ );
616
+ const sendResult = await this.send({
617
+ fileId: presigned.fileId,
618
+ messageType: "FILE",
619
+ ...opts.customMeta ? { customMeta: opts.customMeta } : {}
620
+ });
621
+ return { ...sendResult, fileId: presigned.fileId };
622
+ }
623
+ /**
624
+ * Upload a file (presign → S3 PUT → commit) WITHOUT emitting a chat
625
+ * message. Returns the committed ``file_id`` so callers can gather
626
+ * several ids and bundle them into ONE ``room.send({ fileIds: [...] })``
627
+ * for the multi-file "file_group" message pattern.
628
+ *
629
+ * Same 3-step pipeline as ``sendFile()`` minus step 4. Errors before
630
+ * commit leave the file at ``upload_status=pending`` — the cleanup
631
+ * worker reclaims it within ``FILE_PENDING_UPLOAD_TTL_SEC``.
632
+ */
633
+ async uploadFileOnly(file, opts = {}) {
634
+ const kind = opts.kind ?? (file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "file");
635
+ const name = opts.name ?? file.name;
636
+ const presign = await this.http.request("POST", "/api/v1/files", {
637
+ kind,
638
+ mime: file.type || "application/octet-stream",
639
+ size: file.size,
640
+ original_name: name,
641
+ forward_blocked: Boolean(opts.forwardBlocked)
642
+ });
643
+ await new Promise((resolve, reject) => {
644
+ const xhr = new XMLHttpRequest();
645
+ xhr.open("PUT", presign.upload_url);
646
+ for (const [k, v] of Object.entries(presign.headers)) {
647
+ xhr.setRequestHeader(k, v);
648
+ }
649
+ if (opts.onProgress) {
650
+ xhr.upload.addEventListener("progress", (e) => {
651
+ if (!e.lengthComputable) return;
652
+ opts.onProgress({
653
+ loaded: e.loaded,
654
+ total: e.total,
655
+ ratio: e.total > 0 ? e.loaded / e.total : 0
656
+ });
657
+ });
658
+ }
659
+ xhr.onload = () => {
660
+ if (xhr.status >= 200 && xhr.status < 300) {
661
+ opts.onProgress?.({ loaded: file.size, total: file.size, ratio: 1 });
662
+ resolve();
663
+ } else {
664
+ reject(new Error(`S3 PUT failed: ${xhr.status} ${xhr.statusText}`));
665
+ }
666
+ };
667
+ xhr.onerror = () => reject(new Error("S3 PUT network error"));
668
+ xhr.onabort = () => reject(new Error("S3 PUT aborted"));
669
+ xhr.send(file);
670
+ });
671
+ await this.http.request(
672
+ "POST",
673
+ `/api/v1/files/${presign.file_id}/commit`,
674
+ {}
675
+ );
676
+ return presign.file_id;
677
+ }
678
+ /**
679
+ * List files shared in this room — newest-first, paginated.
680
+ *
681
+ * One entry per non-deleted message that carries a ``file_id`` —
682
+ * forwarded files (same file_id, multiple messages) appear once
683
+ * per occurrence. The history-visibility floor is applied so files
684
+ * attached to messages older than the caller's ``last_cleared_at``
685
+ * (or the post-rejoin cutoff for grouprooms) are filtered out.
686
+ *
687
+ * Use ``before`` with the smallest ``messageId`` of the previous
688
+ * page to paginate.
689
+ */
690
+ async listFiles(opts = {}) {
691
+ const raw = await this.http.request(
692
+ "GET",
693
+ `/api/v1/rooms/${encodeURIComponent(this.roomId)}/files`,
694
+ void 0,
695
+ {
696
+ limit: opts.limit ?? 50,
697
+ ...opts.before ? { before: opts.before } : {}
698
+ }
699
+ );
700
+ return {
701
+ items: raw.items.map((r) => ({
702
+ messageId: r.message_id,
703
+ senderId: r.sender_id,
704
+ createdAtMs: r.created_at_ms,
705
+ file: {
706
+ id: r.file.id,
707
+ kind: r.file.kind,
708
+ mime: r.file.mime,
709
+ size: r.file.size_bytes,
710
+ name: r.file.original_name ?? null,
711
+ width: r.file.width ?? null,
712
+ height: r.file.height ?? null,
713
+ durationSec: r.file.duration_sec ?? null,
714
+ thumbnailStatus: r.file.thumbnail_status,
715
+ forwardBlocked: Boolean(r.file.forward_blocked)
716
+ }
717
+ })),
718
+ nextCursor: raw.next_cursor,
719
+ hasMore: raw.has_more
720
+ };
721
+ }
722
+ markRead(messageId) {
723
+ if (this.pendingReadMid !== null) {
724
+ try {
725
+ if (BigInt(messageId) <= BigInt(this.pendingReadMid)) return;
726
+ } catch {
727
+ if (messageId <= this.pendingReadMid) return;
728
+ }
729
+ }
730
+ this.pendingReadMid = messageId;
731
+ if (this.readDebounceTimer) return;
732
+ this.readDebounceTimer = setTimeout(() => {
733
+ this.readDebounceTimer = null;
734
+ this._sendPendingMarkRead();
735
+ }, this.readDebounceMs);
736
+ }
737
+ /**
738
+ * Bypass the read_watermark debounce and send the pending watermark
739
+ * immediately. Use on critical UX boundaries (user leaves room,
740
+ * client disconnects, page unload) so the server's per-user unread
741
+ * count is correct by the time any other device / admin / push
742
+ * service queries it. No-op when nothing is pending.
743
+ */
744
+ flushMarkRead() {
745
+ if (this.readDebounceTimer) {
746
+ clearTimeout(this.readDebounceTimer);
747
+ this.readDebounceTimer = null;
748
+ }
749
+ this._sendPendingMarkRead();
750
+ }
751
+ setTyping(isTyping) {
752
+ this.ws.send({ type: "typing", room_id: this.roomId, is_typing: isTyping });
753
+ }
754
+ async edit(messageId, patch) {
755
+ return this.http.request(
756
+ "PUT",
757
+ `/api/v1/rooms/${this.roomId}/messages/${messageId}`,
758
+ patch
759
+ );
760
+ }
761
+ async delete(messageId, scope = "ALL") {
762
+ await this.http.request(
763
+ "DELETE",
764
+ `/api/v1/rooms/${this.roomId}/messages/${messageId}`,
765
+ void 0,
766
+ { scope }
767
+ );
768
+ }
769
+ /** Per-user "Clear chat". Hides every existing message in this room
770
+ * from the calling user (via `room_members.last_cleared_at = now()`).
771
+ * Other members are unaffected — this is local history hiding, not
772
+ * a destructive bulk delete. Irreversible from the caller's side. */
773
+ async clearHistory() {
774
+ await this.http.request(
775
+ "POST",
776
+ `/api/v1/rooms/${this.roomId}/clear`
777
+ );
778
+ }
779
+ /** Leave this room (self). Deletes the caller's membership row — the room
780
+ * drops out of `unreadSummary()` and they stop receiving its messages.
781
+ * Other members get a `MEMBER_LEFT` [`roomEvent`](../reference/noverachat.md#events).
782
+ * Idempotent if already a non-member; throws 409 if the caller was KICKED
783
+ * (ask an operator to restore first). For GROUP/SUPER_GROUP, re-entry needs
784
+ * an operator add; for ONE, re-creating the 1:1 rejoins with history kept. */
785
+ async leave() {
786
+ await this.http.request(
787
+ "POST",
788
+ `/api/v1/rooms/${this.roomId}/leave`
789
+ );
790
+ }
791
+ /**
792
+ * Set the caller's per-room push preference — like long-pressing a
793
+ * chat and tapping "notifications off".
794
+ * "ALL" — push for every message (default)
795
+ * "MENTION_ONLY" — push only when the message @-mentions the caller
796
+ * "OFF" — mute this room's push entirely
797
+ * Scoped to the calling user; throws if they're not a room member.
798
+ */
799
+ async setPushTrigger(trigger) {
800
+ await this.http.request(
801
+ "PATCH",
802
+ `/api/v1/rooms/${this.roomId}/push-trigger`,
803
+ { push_trigger: trigger }
804
+ );
805
+ }
806
+ /**
807
+ * **DESTRUCTIVE, operator-only.** Soft-deletes every currently-undeleted
808
+ * message in the room — visible to all members instantly via a
809
+ * `messagesCleared` event (subscribe via `room.on("messagesCleared", ...)`).
810
+ * Server enforces the operator check; throws 403 for regular members.
811
+ * Returns the cleared count plus the cutoff `message_id` so callers can
812
+ * hide rendered messages up to (and including) that id.
813
+ */
814
+ async deleteAllMessages() {
815
+ const raw = await this.http.request("DELETE", `/api/v1/rooms/${this.roomId}/messages`);
816
+ return {
817
+ cleared: raw.cleared,
818
+ upToMessageId: raw.up_to_message_id
819
+ };
820
+ }
821
+ async react(messageId, key) {
822
+ await this.http.request(
823
+ "POST",
824
+ `/api/v1/rooms/${this.roomId}/messages/${messageId}/reactions`,
825
+ { key }
826
+ );
827
+ }
828
+ async unreact(messageId, key) {
829
+ await this.http.request(
830
+ "DELETE",
831
+ `/api/v1/rooms/${this.roomId}/messages/${messageId}/reactions/${encodeURIComponent(key)}`
832
+ );
833
+ }
834
+ async listSince(sinceMessageId, limit = 100) {
835
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/messages`, void 0, {
836
+ since: String(sinceMessageId),
837
+ limit
838
+ });
839
+ return {
840
+ items: raw.items.map(toMessageOut),
841
+ nextCursor: raw.next_cursor,
842
+ hasMore: raw.has_more
843
+ };
844
+ }
845
+ /**
846
+ * Load the latest `limit` messages of the room — what to render when the
847
+ * user just opens the chat. Returns ASC (oldest → newest within the
848
+ * page) so callers don't need to reverse. Use `room.listBefore(cursor)`
849
+ * to paginate further back.
850
+ */
851
+ async listRecent(limit = 50) {
852
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/messages`, void 0, { limit });
853
+ return {
854
+ items: raw.items.map(toMessageOut),
855
+ nextCursor: raw.next_cursor,
856
+ hasMore: raw.has_more
857
+ };
858
+ }
859
+ /**
860
+ * Scrollback. Fetches the page of `limit` messages immediately preceding
861
+ * `beforeMessageId` (exclusive), in ASC order. The returned
862
+ * `nextCursor` is the oldest id in this page — feed it back to keep
863
+ * scrolling up.
864
+ */
865
+ async listBefore(beforeMessageId, limit = 50) {
866
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/messages`, void 0, {
867
+ before: beforeMessageId,
868
+ limit
869
+ });
870
+ return {
871
+ items: raw.items.map(toMessageOut),
872
+ nextCursor: raw.next_cursor,
873
+ hasMore: raw.has_more
874
+ };
875
+ }
876
+ /** Phase D #2 — 방 내 메시지 검색.
877
+ *
878
+ * ``content`` 필드에 대한 대소문자 무시 부분 문자열 매칭 (ILIKE). 삭제된
879
+ * 메시지는 제외. 결과는 최신순 (message_id DESC) 으로 반환되고, ``before``
880
+ * 커서로 뒤로 페이지네이션. 스티커/파일/이모티콘 등 ``content`` 가 없는
881
+ * 메시지는 검색 대상 X.
882
+ *
883
+ * @param q 검색어 (필수, 1~200자, whitespace-only 는 서버가 빈 결과 반환)
884
+ * @param opts.before 이전 페이지 마지막 message_id (다음 페이지 커서)
885
+ * @param opts.limit 페이지 크기 (기본 30, 최대 100)
886
+ */
887
+ async search(q, opts) {
888
+ const params = {
889
+ q,
890
+ limit: opts?.limit ?? 30
891
+ };
892
+ if (opts?.before) params.before = opts.before;
893
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/messages/search`, void 0, params);
894
+ return {
895
+ items: raw.items.map(toMessageOut),
896
+ nextCursor: raw.next_cursor,
897
+ hasMore: raw.has_more
898
+ };
899
+ }
900
+ /** List this room's members (with each one's role). Handy for UIs that
901
+ * want to conditionally enable destructive operator-only actions like
902
+ * `room.deleteAllMessages()`. Server gates by membership for non-public
903
+ * rooms, so the caller must already be a member to read this.
904
+ */
905
+ async listMembers() {
906
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/members`);
907
+ return raw.map((m) => ({
908
+ userId: m.user_id,
909
+ nickname: m.nickname ?? null,
910
+ role: m.role,
911
+ pushTrigger: m.push_trigger,
912
+ lastReadMessageId: m.last_read_message_id,
913
+ joinedAt: m.joined_at,
914
+ isOnline: m.is_online ?? null,
915
+ mutedUntil: m.muted_until ?? null
916
+ }));
917
+ }
918
+ // -------- mute --------
919
+ /** OPERATOR-only: mute a member so they can't send messages in this
920
+ * room. `durationMinutes=null` → indefinite (until an explicit unmute).
921
+ * Emits a `MEMBER_MUTED` [`roomEvent`](../reference/noverachat.md#events)
922
+ * + a SYSTEM chat message. Non-operator callers get 403. Server also
923
+ * refuses self-mute and muting another OPERATOR. */
924
+ async muteMember(userId, durationMinutes) {
925
+ await this.http.request(
926
+ "POST",
927
+ `/api/v1/rooms/${this.roomId}/members/${encodeURIComponent(userId)}/mute`,
928
+ { duration_minutes: durationMinutes }
929
+ );
930
+ }
931
+ /** OPERATOR-only: clear a member's mute. Idempotent — no-op + no
932
+ * broadcast when the target wasn't muted. Emits a `MEMBER_UNMUTED`
933
+ * roomEvent + SYSTEM chat message otherwise. */
934
+ async unmuteMember(userId) {
935
+ await this.http.request(
936
+ "POST",
937
+ `/api/v1/rooms/${this.roomId}/members/${encodeURIComponent(userId)}/unmute`
938
+ );
939
+ }
940
+ /** Server-side unread state for this room: exact COUNT(*) of messages
941
+ * newer than the caller's `read_watermark`, plus the room's
942
+ * `last_message_id` so the UI can show a "•" dot regardless of count. */
943
+ async unread() {
944
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/unread`);
945
+ return {
946
+ roomId: raw.room_id,
947
+ unreadCount: raw.unread_count,
948
+ lastReadMessageId: raw.last_read_message_id,
949
+ lastMessageId: raw.last_message_id
950
+ };
951
+ }
952
+ // -------- freeze --------
953
+ /** OPERATOR-only moderation: freeze this room. Non-admin messages are
954
+ * blocked server-side with NC-ROOM-FROZEN while frozen. All members'
955
+ * clients receive a `roomEvent` with `event: "ROOM_FROZEN"` in real
956
+ * time, plus a SYSTEM chat message "방이 얼려졌습니다."
957
+ * Idempotent — no-op if already frozen. Non-operator callers get 403. */
958
+ async freeze() {
959
+ await this.http.request(
960
+ "POST",
961
+ `/api/v1/rooms/${this.roomId}/freeze`
962
+ );
963
+ }
964
+ /** Mirror of `freeze()` — reopens the room to chat_send. Emits a
965
+ * `ROOM_UNFROZEN` roomEvent + a "방이 녹여졌습니다." SYSTEM message. */
966
+ async unfreeze() {
967
+ await this.http.request(
968
+ "POST",
969
+ `/api/v1/rooms/${this.roomId}/unfreeze`
970
+ );
971
+ }
972
+ /** OPERATOR-only: toggle room visibility. `true` → 공개방 (open chat,
973
+ * anyone can join). `false` → 비공개방 (invite-only, join requires
974
+ * approval). Auto-inserts a SYSTEM chat message and broadcasts a
975
+ * `ROOM_VISIBILITY_CHANGED` roomEvent so peers update in real time. */
976
+ async setPublic(isPublic) {
977
+ await this.http.request(
978
+ "PATCH",
979
+ `/api/v1/rooms/${this.roomId}/visibility`,
980
+ { is_public: isPublic }
981
+ );
982
+ }
983
+ // -------- announcements --------
984
+ async listAnnouncements() {
985
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/announcements`);
986
+ return raw.map((a) => ({
987
+ id: a.id,
988
+ roomId: a.room_id,
989
+ content: a.content,
990
+ createdBy: a.created_by,
991
+ createdAt: a.created_at,
992
+ updatedAt: a.updated_at
993
+ }));
994
+ }
995
+ async getCurrentAnnouncement() {
996
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/announcements/current`);
997
+ if (!raw) return null;
998
+ return {
999
+ id: raw.id,
1000
+ roomId: raw.room_id,
1001
+ content: raw.content,
1002
+ createdBy: raw.created_by,
1003
+ createdAt: raw.created_at,
1004
+ updatedAt: raw.updated_at
1005
+ };
1006
+ }
1007
+ async postAnnouncement(content) {
1008
+ const raw = await this.http.request("POST", `/api/v1/rooms/${this.roomId}/announcements`, { content });
1009
+ return {
1010
+ id: raw.id,
1011
+ roomId: raw.room_id,
1012
+ content: raw.content,
1013
+ createdBy: raw.created_by,
1014
+ createdAt: raw.created_at,
1015
+ updatedAt: raw.updated_at
1016
+ };
1017
+ }
1018
+ async updateAnnouncement(id, content) {
1019
+ const raw = await this.http.request("PATCH", `/api/v1/rooms/${this.roomId}/announcements/${id}`, { content });
1020
+ return {
1021
+ id: raw.id,
1022
+ roomId: raw.room_id,
1023
+ content: raw.content,
1024
+ createdBy: raw.created_by,
1025
+ createdAt: raw.created_at,
1026
+ updatedAt: raw.updated_at
1027
+ };
1028
+ }
1029
+ async deleteAnnouncement(id) {
1030
+ await this.http.request(
1031
+ "DELETE",
1032
+ `/api/v1/rooms/${this.roomId}/announcements/${id}`
1033
+ );
1034
+ }
1035
+ // -------- invite links --------
1036
+ /**
1037
+ * OPERATOR-only: mint a new invite link for this room. Default:
1038
+ * expires in 7 days, unlimited uses. Pass `expiresInHours: null`
1039
+ * for a link that never expires, or `maxUses: 1` for a one-shot.
1040
+ *
1041
+ * Returns the raw `InviteToken` — build the shareable URL yourself
1042
+ * (e.g. `${location.origin}/#invite/${token.token}`) so you control
1043
+ * the format your app uses to consume it.
1044
+ */
1045
+ async createInvite(opts) {
1046
+ const body = {};
1047
+ if (opts && "expiresInHours" in opts) body.expires_in_hours = opts.expiresInHours;
1048
+ if (opts && "maxUses" in opts) body.max_uses = opts.maxUses;
1049
+ const raw = await this.http.request("POST", `/api/v1/rooms/${this.roomId}/invites`, body);
1050
+ return {
1051
+ token: raw.token,
1052
+ roomId: raw.room_id,
1053
+ createdBy: raw.created_by,
1054
+ createdAt: raw.created_at,
1055
+ expiresAt: raw.expires_at,
1056
+ maxUses: raw.max_uses,
1057
+ usedCount: raw.used_count,
1058
+ revokedAt: raw.revoked_at
1059
+ };
1060
+ }
1061
+ /** OPERATOR-only: list all invite tokens for this room (including
1062
+ * revoked / expired / exhausted), newest first. */
1063
+ async listInvites() {
1064
+ const raw = await this.http.request("GET", `/api/v1/rooms/${this.roomId}/invites`);
1065
+ return raw.map((r) => ({
1066
+ token: r.token,
1067
+ roomId: r.room_id,
1068
+ createdBy: r.created_by,
1069
+ createdAt: r.created_at,
1070
+ expiresAt: r.expires_at,
1071
+ maxUses: r.max_uses,
1072
+ usedCount: r.used_count,
1073
+ revokedAt: r.revoked_at
1074
+ }));
1075
+ }
1076
+ /** OPERATOR-only: revoke a token immediately. Idempotent — revoking
1077
+ * an already-revoked token returns 204 as well. */
1078
+ async revokeInvite(token) {
1079
+ await this.http.request(
1080
+ "DELETE",
1081
+ `/api/v1/rooms/${this.roomId}/invites/${encodeURIComponent(token)}`
1082
+ );
1083
+ }
1084
+ // -------- internal dispatch --------
1085
+ on(event, fn) {
1086
+ return this.bus.on(event, fn);
1087
+ }
1088
+ off(event, fn) {
1089
+ this.bus.off(event, fn);
1090
+ }
1091
+ _dispatchAnnouncement(msg) {
1092
+ this.bus.emit("announcement", msg);
1093
+ }
1094
+ _dispatchAck(tempId2, messageId) {
1095
+ if (!tempId2) return;
1096
+ const entry = this.pendingAcks.get(tempId2);
1097
+ if (entry) {
1098
+ entry.resolve(messageId);
1099
+ this.pendingAcks.delete(tempId2);
1100
+ this.mySentTempIds.delete(tempId2);
1101
+ this.bus.emit("ack", { tempId: tempId2, messageId });
1102
+ }
1103
+ }
1104
+ /** True iff this room has a still-pending send with this temp_id. */
1105
+ _hasPendingTempId(tempId2) {
1106
+ return this.pendingAcks.has(tempId2);
1107
+ }
1108
+ /** Reject the pending send for tempId with the given error. Used by the
1109
+ * client when a server `error` frame echoes back our temp_id so we can
1110
+ * fail the matching outbound promise immediately instead of waiting
1111
+ * for the 15s ack timeout. */
1112
+ _rejectPending(tempId2, err) {
1113
+ const entry = this.pendingAcks.get(tempId2);
1114
+ if (!entry) return;
1115
+ entry.reject(err);
1116
+ this.pendingAcks.delete(tempId2);
1117
+ this.mySentTempIds.delete(tempId2);
1118
+ }
1119
+ /**
1120
+ * Try to re-send a pending frame after a transient server reject
1121
+ * (currently only NC-RATE-001 — the tenant's per-second token bucket
1122
+ * spilled). Reuses the same temp_id so:
1123
+ * 1. ack matching on success still works,
1124
+ * 2. self-echo dedup still recognizes the frame as ours,
1125
+ * 3. *if* the server's first attempt secretly succeeded (we got an
1126
+ * error frame but the message was already persisted) the second
1127
+ * attempt's `chat_receive` self-echo collapses cleanly.
1128
+ *
1129
+ * Returns true if a retry was scheduled; false if we've already used
1130
+ * up the retry budget and the caller should fall back to rejecting
1131
+ * the promise.
1132
+ */
1133
+ _retryPending(tempId2) {
1134
+ const entry = this.pendingAcks.get(tempId2);
1135
+ if (!entry) return false;
1136
+ if (entry.retries >= _Room.MAX_RATE_LIMIT_RETRIES) return false;
1137
+ const idx = entry.retries;
1138
+ entry.retries += 1;
1139
+ const delay = _Room.RATE_LIMIT_BACKOFF_MS[idx] ?? 1200;
1140
+ setTimeout(() => {
1141
+ if (!this.pendingAcks.has(tempId2)) return;
1142
+ const ok = this.ws.send(entry.payload);
1143
+ if (!ok) {
1144
+ this._rejectPending(tempId2, new Error("ws closed during retry"));
1145
+ }
1146
+ }, delay);
1147
+ return true;
1148
+ }
1149
+ /** True if this room originated a `chat_send` with the given temp_id
1150
+ * during the current session. Used by the client dispatcher to detect
1151
+ * self-echo chat_receive frames. */
1152
+ _isMySentTempId(tempId2) {
1153
+ return this.mySentTempIds.has(tempId2);
1154
+ }
1155
+ /** Forget a self-sent temp_id once both the ack and the echo are reconciled. */
1156
+ _forgetMySentTempId(tempId2) {
1157
+ this.mySentTempIds.delete(tempId2);
1158
+ }
1159
+ _dispatchInbound(msg) {
1160
+ switch (msg.type) {
1161
+ case "chat_receive":
1162
+ this.bus.emit("message", msg);
1163
+ return;
1164
+ case "message_updated":
1165
+ this.bus.emit("messageUpdated", msg);
1166
+ return;
1167
+ case "message_deleted":
1168
+ this.bus.emit("messageDeleted", msg);
1169
+ return;
1170
+ case "messages_cleared":
1171
+ this.bus.emit("messagesCleared", msg);
1172
+ return;
1173
+ case "reaction_added":
1174
+ this.bus.emit("reactionAdded", msg);
1175
+ return;
1176
+ case "reaction_removed":
1177
+ this.bus.emit("reactionRemoved", msg);
1178
+ return;
1179
+ case "sync_tick":
1180
+ this.bus.emit("syncTick", msg);
1181
+ return;
1182
+ case "typing":
1183
+ this.bus.emit("typing", msg);
1184
+ return;
1185
+ }
1186
+ }
1187
+ };
1188
+
1189
+ // src/client.ts
1190
+ function idGreater(a, b) {
1191
+ if (!a) return false;
1192
+ if (!b) return true;
1193
+ try {
1194
+ return BigInt(a) > BigInt(b);
1195
+ } catch {
1196
+ return a > b;
1197
+ }
1198
+ }
1199
+ var NoveraChat = class {
1200
+ constructor(opts) {
1201
+ this.opts = opts;
1202
+ if (!opts.appId) throw new Error("appId required");
1203
+ if (!opts.endpoint) throw new Error("endpoint required");
1204
+ if (!opts.tokenProvider) throw new Error("tokenProvider required");
1205
+ this.readDebounceMs = opts.readWatermarkDebounceMs ?? 400;
1206
+ this.logger = opts.logger;
1207
+ if (opts.initialLastMessageIds) {
1208
+ for (const [roomId, id] of Object.entries(opts.initialLastMessageIds)) {
1209
+ const sid = typeof id === "number" ? String(id) : id;
1210
+ if (sid && sid !== "0") {
1211
+ this.lastMessageIdByRoom.set(roomId, sid);
1212
+ }
1213
+ }
1214
+ }
1215
+ this.http = new HttpClient({
1216
+ baseUrl: opts.endpoint,
1217
+ appId: opts.appId,
1218
+ tokenProvider: opts.tokenProvider,
1219
+ ...opts.fetch ? { fetch: opts.fetch } : {},
1220
+ // Same structured sink as the WS transport — the SDK is one source
1221
+ // of truth for both pipes' traces. Debug-level lines (rest_req /
1222
+ // rest_res) are off by default at the consumer side (e.g. the demo
1223
+ // filters them behind a "Verbose" toggle).
1224
+ ...this.logger ? { logger: this.logger } : {}
1225
+ });
1226
+ const wsBase = opts.wsEndpoint ?? opts.endpoint.replace(/^http/, "ws");
1227
+ this.ws = new ReconnectingWs({
1228
+ urlBuilder: async () => {
1229
+ const token = await opts.tokenProvider();
1230
+ const since = this.highestKnownMessageId();
1231
+ const u = new URL(wsBase.replace(/\/+$/, "") + `/ws/${opts.appId}`);
1232
+ u.searchParams.set("token", token);
1233
+ if (since) u.searchParams.set("since", since);
1234
+ return u.toString();
1235
+ },
1236
+ onMessage: (msg) => this.dispatch(msg),
1237
+ onOpen: () => {
1238
+ if (this.connectedOnce) {
1239
+ void this.backfillAllRooms();
1240
+ } else {
1241
+ this.connectedOnce = true;
1242
+ }
1243
+ },
1244
+ onStateChange: (s) => this.logger?.("info", `ws_state=${s}`),
1245
+ autoReconnect: opts.autoReconnect ?? true,
1246
+ pingIntervalMs: opts.pingIntervalMs ?? 2e4,
1247
+ maxReconnectDelayMs: opts.maxReconnectDelayMs ?? 3e4,
1248
+ ...opts.WebSocketImpl ? { WebSocketImpl: opts.WebSocketImpl } : {},
1249
+ ...opts.logger ? { logger: opts.logger } : {}
1250
+ });
1251
+ }
1252
+ opts;
1253
+ http;
1254
+ ws;
1255
+ rooms = /* @__PURE__ */ new Map();
1256
+ bus = new EventBus();
1257
+ readDebounceMs;
1258
+ logger;
1259
+ connectedOnce = false;
1260
+ lastMessageIdByRoom = /* @__PURE__ */ new Map();
1261
+ /** Most recently dispatched presence event key, `${userId}:${at}:${online}`.
1262
+ * Used to drop the N-1 shared-room copies of a single online/offline
1263
+ * transition — the server fans out one publish per room, and we don't
1264
+ * want the caller's listener firing N times for one UX event. */
1265
+ lastPresenceKey = null;
1266
+ async connect() {
1267
+ await this.ws.connect();
1268
+ }
1269
+ disconnect() {
1270
+ this.ws.close();
1271
+ this.rooms.clear();
1272
+ }
1273
+ room(roomId) {
1274
+ let r = this.rooms.get(roomId);
1275
+ if (!r) {
1276
+ r = new Room(roomId, this.http, this.ws, this.readDebounceMs);
1277
+ this.rooms.set(roomId, r);
1278
+ }
1279
+ return r;
1280
+ }
1281
+ /** Subscribe to client-level events. Currently `roomEvent` — membership /
1282
+ * room-lifecycle changes for ANY room (added, kicked, restored, frozen,
1283
+ * …), including rooms the caller hasn't opened. Returns an unsubscribe fn.
1284
+ * Use this to refresh a channel list the instant you're added to a new
1285
+ * room, rather than waiting for a poll. */
1286
+ on(event, fn) {
1287
+ return this.bus.on(event, fn);
1288
+ }
1289
+ off(event, fn) {
1290
+ this.bus.off(event, fn);
1291
+ }
1292
+ /**
1293
+ * Manually fetch all messages newer than the highest known `message_id`
1294
+ * for each room and surface them as regular `room.on("message", ...)`
1295
+ * events. Useful at cold start (after `chat.connect()`) to pull the
1296
+ * "unread since last session" tail — the WS reconnect path calls this
1297
+ * automatically, but the first connect does not.
1298
+ *
1299
+ * No-op for rooms with no seeded id.
1300
+ */
1301
+ async backfill() {
1302
+ await this.backfillAllRooms();
1303
+ }
1304
+ /** Highest `message_id` the client has seen for a given room, or null. */
1305
+ lastSeenMessageId(roomId) {
1306
+ return this.lastMessageIdByRoom.get(roomId) ?? null;
1307
+ }
1308
+ /**
1309
+ * Monotonically advance the per-room "highest-seen message_id" anchor.
1310
+ * Used by callers that learn a newer watermark from out-of-band sources —
1311
+ * typically the server's own `last_read_message_id` (via the unread
1312
+ * endpoint) so the next `backfill()` doesn't re-pull messages the user
1313
+ * already marked read on another device. Never moves the value backward;
1314
+ * a smaller `messageId` is silently ignored. Accepts either the string
1315
+ * form (preferred) or a number (legacy / convenience).
1316
+ */
1317
+ setLastSeen(roomId, messageId) {
1318
+ const sid = typeof messageId === "number" ? String(messageId) : messageId;
1319
+ if (!sid || sid === "0") return;
1320
+ const cur = this.lastMessageIdByRoom.get(roomId);
1321
+ if (idGreater(sid, cur)) this.lastMessageIdByRoom.set(roomId, sid);
1322
+ }
1323
+ /** Server-side aggregate unread state: total count + per-room breakdown
1324
+ * for the authenticated user. Single REST call; cheap enough to poll
1325
+ * every few seconds for a badge, or just refresh on focus + after
1326
+ * receiving new messages. */
1327
+ /** Client-facing feature flags for the caller's app. Cheap (one row
1328
+ * read on the server) — fetch once on connect to decide which
1329
+ * destructive buttons to expose. */
1330
+ async appPolicy() {
1331
+ const raw = await this.http.request("GET", "/api/v1/app/policy");
1332
+ return {
1333
+ appId: raw.app_id,
1334
+ allowMemberBulkDelete: raw.allow_member_bulk_delete,
1335
+ readReceiptsEnabled: raw.read_receipts_enabled ?? true,
1336
+ typingIndicatorsEnabled: raw.typing_indicators_enabled ?? true,
1337
+ deleteAnyMessageEnabled: raw.allow_member_delete_any_message ?? false
1338
+ };
1339
+ }
1340
+ // ---- device tokens (push) ----
1341
+ /**
1342
+ * Register (or refresh) this device's push token. Call after login and
1343
+ * whenever the platform hands you a rotated FCM/APNS token. Idempotent
1344
+ * on `deviceId` — the server upserts, so re-registering is cheap and
1345
+ * safe. Returns the stored device record (token shown only as a prefix).
1346
+ */
1347
+ async registerDevice(params) {
1348
+ const raw = await this.http.request("POST", "/api/v1/users/me/devices", {
1349
+ device_id: params.deviceId,
1350
+ token: params.token,
1351
+ token_type: params.tokenType,
1352
+ os: params.os ?? null,
1353
+ app_version: params.appVersion ?? null
1354
+ });
1355
+ return this._toDeviceInfo(raw);
1356
+ }
1357
+ /** List the devices registered for the authenticated user. */
1358
+ async listDevices() {
1359
+ const raw = await this.http.request("GET", "/api/v1/users/me/devices");
1360
+ return raw.items.map((d) => this._toDeviceInfo(d));
1361
+ }
1362
+ /**
1363
+ * Turn push delivery on/off for one device without unregistering it —
1364
+ * the token stays stored, the push pipeline just skips it. Use for an
1365
+ * in-app "notifications" toggle.
1366
+ */
1367
+ async setDevicePushEnabled(deviceId, enabled) {
1368
+ await this.http.request(
1369
+ "PATCH",
1370
+ `/api/v1/users/me/devices/${encodeURIComponent(deviceId)}`,
1371
+ { push_enabled: enabled }
1372
+ );
1373
+ }
1374
+ /** Unregister a device — call on logout so the user stops receiving
1375
+ * push on a device they're no longer signed into. */
1376
+ async unregisterDevice(deviceId) {
1377
+ await this.http.request(
1378
+ "DELETE",
1379
+ `/api/v1/users/me/devices/${encodeURIComponent(deviceId)}`
1380
+ );
1381
+ }
1382
+ // ---- global push preference (user-level kill switch) ----
1383
+ /**
1384
+ * Read the caller's GLOBAL push preference. When `pushEnabled` is
1385
+ * false the push worker skips this user entirely — every per-room
1386
+ * `push_trigger` setting is ignored. Fail-open: an unknown user
1387
+ * comes back as `pushEnabled: true`.
1388
+ *
1389
+ * Two levels of push control:
1390
+ * 1. **Per-room** — `room.setPushTrigger("ALL" | "MENTION_ONLY" | "OFF")`.
1391
+ * 2. **Global (this)** — overrides all rooms when off.
1392
+ */
1393
+ async getPushPreferences() {
1394
+ const raw = await this.http.request(
1395
+ "GET",
1396
+ "/api/v1/users/me/push-preferences"
1397
+ );
1398
+ return { pushEnabled: Boolean(raw.push_enabled) };
1399
+ }
1400
+ /**
1401
+ * Flip the caller's global push kill switch. Pass `false` to mute
1402
+ * every push notification for this user across every room; pass
1403
+ * `true` to restore normal delivery. Idempotent.
1404
+ */
1405
+ async setPushEnabled(enabled) {
1406
+ const raw = await this.http.request(
1407
+ "PATCH",
1408
+ "/api/v1/users/me/push-preferences",
1409
+ { push_enabled: enabled }
1410
+ );
1411
+ return { pushEnabled: Boolean(raw.push_enabled) };
1412
+ }
1413
+ // -------------------------------------------------------------------------
1414
+ // User blocks — KakaoTalk-style one-way block.
1415
+ //
1416
+ // The block is directional: `chat.blockUser(otherId)` stops `otherId`'s
1417
+ // messages from reaching the caller. The blocked side is NEVER notified;
1418
+ // their sends still ack. There's no admin escape hatch or "who blocked
1419
+ // me" query — that's the whole point of a one-way block.
1420
+ // -------------------------------------------------------------------------
1421
+ /**
1422
+ * Block a user (one-way). Idempotent — repeated calls return the
1423
+ * existing row without changing `createdAt` or `reason`.
1424
+ *
1425
+ * @param userId The user to block. `chat.blockUser(myUserId)` throws
1426
+ * a validation error server-side.
1427
+ * @param reason Optional local note ≤500 chars.
1428
+ */
1429
+ async blockUser(userId, reason) {
1430
+ const raw = await this.http.request(
1431
+ "POST",
1432
+ `/api/v1/users/me/blocks/${encodeURIComponent(userId)}`,
1433
+ { reason: reason ?? null }
1434
+ );
1435
+ return {
1436
+ blockedUserId: raw.blocked_user_id,
1437
+ reason: raw.reason,
1438
+ createdAt: raw.created_at
1439
+ };
1440
+ }
1441
+ /** Unblock a user. Idempotent — resolves either way. */
1442
+ async unblockUser(userId) {
1443
+ await this.http.request(
1444
+ "DELETE",
1445
+ `/api/v1/users/me/blocks/${encodeURIComponent(userId)}`
1446
+ );
1447
+ }
1448
+ /** List every user the caller has blocked, newest first. */
1449
+ async listBlocks() {
1450
+ const raw = await this.http.request("GET", "/api/v1/users/me/blocks");
1451
+ return raw.map((r) => ({
1452
+ blockedUserId: r.blocked_user_id,
1453
+ reason: r.reason,
1454
+ createdAt: r.created_at
1455
+ }));
1456
+ }
1457
+ _toDeviceInfo(raw) {
1458
+ return {
1459
+ deviceId: raw.device_id,
1460
+ tokenType: raw.token_type,
1461
+ tokenPreview: raw.token_preview,
1462
+ os: raw.os,
1463
+ appVersion: raw.app_version,
1464
+ pushEnabled: raw.push_enabled,
1465
+ lastActiveAt: raw.last_active_at,
1466
+ createdAt: raw.created_at
1467
+ };
1468
+ }
1469
+ /**
1470
+ * Authorization-gated URL for downloading a file attachment.
1471
+ *
1472
+ * The backend runs the request through the authorization gate (caller
1473
+ * must be a non-KICKED member of some room with a non-deleted,
1474
+ * post-cutoff message referencing this file) and then 302-redirects
1475
+ * to a short-lived signed S3 URL. ``<img src=...>`` / ``<video
1476
+ * src=...>`` / ``<a href=...>`` consumers transparently follow the
1477
+ * redirect.
1478
+ *
1479
+ * Why the optional ``token`` argument? Browsers don't let
1480
+ * ``<img>``/``<video>`` tags carry custom Authorization headers —
1481
+ * so URLs destined for those elements have to embed credentials in
1482
+ * the URL itself. The backend's ``require_user`` dep accepts
1483
+ * ``?token=...&app_id=...`` query params as a fallback for exactly
1484
+ * this case (it still prefers headers when present). Pass the same
1485
+ * JWT the SDK was constructed with; ``app_id`` is filled in
1486
+ * automatically from the client options. Omit the token when you're
1487
+ * going to ``fetch()`` the URL yourself with the Authorization
1488
+ * header set (e.g. server-side preview).
1489
+ *
1490
+ * Note: each call returns a fresh URL but the URL embeds a JWT — its
1491
+ * lifetime is the JWT's TTL (~24h by default), not the few-seconds
1492
+ * window of the S3 signed URL the backend redirects to. Don't log it.
1493
+ */
1494
+ fileUrl(fileId, token) {
1495
+ const base = this.opts.endpoint.replace(/\/+$/, "");
1496
+ const u = new URL(`${base}/api/v1/files/${encodeURIComponent(fileId)}`);
1497
+ if (token) {
1498
+ u.searchParams.set("token", token);
1499
+ u.searchParams.set("app_id", this.opts.appId);
1500
+ }
1501
+ return u.toString();
1502
+ }
1503
+ /**
1504
+ * Thumbnail URL for an image / video attachment. Returns 404 when
1505
+ * the thumbnail isn't ready yet (poll ``getFileMeta`` then re-render
1506
+ * once ``thumbnailStatus === "ready"``). Same token-in-query rule
1507
+ * as ``fileUrl()``.
1508
+ */
1509
+ fileThumbnailUrl(fileId, token) {
1510
+ const base = this.opts.endpoint.replace(/\/+$/, "");
1511
+ const u = new URL(`${base}/api/v1/files/${encodeURIComponent(fileId)}/thumbnail`);
1512
+ if (token) {
1513
+ u.searchParams.set("token", token);
1514
+ u.searchParams.set("app_id", this.opts.appId);
1515
+ }
1516
+ return u.toString();
1517
+ }
1518
+ /**
1519
+ * Fetch a file's metadata without committing to a download. Useful
1520
+ * when ``Message.file`` (the inline copy) is missing — e.g. for
1521
+ * messages loaded from REST history that predate the inline-meta
1522
+ * shipping date.
1523
+ */
1524
+ async getFileMeta(fileId) {
1525
+ const raw = await this.http.request("GET", `/api/v1/files/${encodeURIComponent(fileId)}/meta`);
1526
+ return {
1527
+ id: raw.id,
1528
+ kind: raw.kind,
1529
+ mime: raw.mime,
1530
+ size: raw.size_bytes,
1531
+ name: raw.original_name ?? null,
1532
+ width: raw.width ?? null,
1533
+ height: raw.height ?? null,
1534
+ durationSec: raw.duration_sec ?? null,
1535
+ thumbnailStatus: raw.thumbnail_status,
1536
+ forwardBlocked: Boolean(raw.forward_blocked)
1537
+ };
1538
+ }
1539
+ async unreadSummary() {
1540
+ const raw = await this.http.request("GET", "/api/v1/users/me/unread");
1541
+ return {
1542
+ total: raw.total,
1543
+ rooms: raw.rooms.map((r) => ({
1544
+ roomId: r.room_id,
1545
+ name: r.name,
1546
+ roomType: r.room_type ?? null,
1547
+ unreadCount: r.unread_count,
1548
+ lastMessageId: r.last_message_id,
1549
+ lastMessagePreview: r.last_message_preview ?? null,
1550
+ lastReadMessageId: r.last_read_message_id,
1551
+ memberCount: r.member_count ?? 0,
1552
+ members: (r.members_preview ?? []).map((m) => ({
1553
+ userId: m.user_id,
1554
+ nickname: m.nickname ?? null,
1555
+ profileImageUrl: m.profile_image_url ?? null,
1556
+ isOnline: m.is_online ?? null
1557
+ }))
1558
+ }))
1559
+ };
1560
+ }
1561
+ /**
1562
+ * Accept an invite link — call this in flows where you receive a
1563
+ * shareable URL (e.g. after parsing a deep link like
1564
+ * `#invite/<token>`). Consumes one use of the token and joins the
1565
+ * caller to the target room; peers already in the room receive a
1566
+ * `MEMBER_JOINED` roomEvent and a SYSTEM chat message.
1567
+ *
1568
+ * Idempotent: if the caller is already an active member the call
1569
+ * succeeds with `wasAlreadyMember: true` and does NOT decrement the
1570
+ * token's remaining uses — safe to call again on every app open.
1571
+ *
1572
+ * Throws (via HttpClient's `NoveraChatError`) when the token is
1573
+ * invalid, expired, revoked, exhausted, or when the caller has been
1574
+ * kicked from the target room.
1575
+ */
1576
+ async acceptInvite(token) {
1577
+ const raw = await this.http.request("POST", `/api/v1/invites/${encodeURIComponent(token)}/accept`);
1578
+ return {
1579
+ roomId: raw.room_id,
1580
+ roomName: raw.room_name,
1581
+ wasAlreadyMember: raw.was_already_member
1582
+ };
1583
+ }
1584
+ // ---- internal ----
1585
+ dispatch(msg) {
1586
+ switch (msg.type) {
1587
+ case "connected":
1588
+ return;
1589
+ case "pong":
1590
+ return;
1591
+ case "error": {
1592
+ this.logger?.("warn", "ws_error_frame", msg);
1593
+ const tempId2 = msg.details && typeof msg.details === "object" ? msg.details.temp_id : void 0;
1594
+ if (typeof tempId2 === "string" && tempId2.length > 0) {
1595
+ let target = null;
1596
+ for (const room of this.rooms.values()) {
1597
+ if (room._hasPendingTempId(tempId2)) {
1598
+ target = room;
1599
+ break;
1600
+ }
1601
+ }
1602
+ if (target) {
1603
+ const code = msg.code || "WS_ERROR";
1604
+ if (code === "NC-RATE-001" && target._retryPending(tempId2)) {
1605
+ this.logger?.("info", "ws_send_retry_scheduled", {
1606
+ temp_id: tempId2,
1607
+ code
1608
+ });
1609
+ return;
1610
+ }
1611
+ const details = msg.details ?? void 0;
1612
+ const err = details !== void 0 ? new NoveraChatError(
1613
+ msg.message || "server rejected frame",
1614
+ code,
1615
+ 0,
1616
+ details
1617
+ ) : new NoveraChatError(
1618
+ msg.message || "server rejected frame",
1619
+ code
1620
+ );
1621
+ target._rejectPending(tempId2, err);
1622
+ }
1623
+ }
1624
+ return;
1625
+ }
1626
+ case "close_notice":
1627
+ this.logger?.("warn", "ws_close_notice", msg);
1628
+ return;
1629
+ case "room_event": {
1630
+ this.bus.emit("roomEvent", msg);
1631
+ return;
1632
+ }
1633
+ case "presence": {
1634
+ const key = `${msg.user_id}:${msg.at}:${msg.online ? 1 : 0}`;
1635
+ if (this.lastPresenceKey === key) return;
1636
+ this.lastPresenceKey = key;
1637
+ this.bus.emit("presence", msg);
1638
+ return;
1639
+ }
1640
+ case "ack": {
1641
+ if (idGreater(msg.message_id, this.lastMessageIdByRoom.get(msg.room_id))) {
1642
+ this.lastMessageIdByRoom.set(msg.room_id, msg.message_id);
1643
+ }
1644
+ const room = this.rooms.get(msg.room_id);
1645
+ room?._dispatchAck(msg.temp_id, msg.message_id);
1646
+ return;
1647
+ }
1648
+ case "announcement_event": {
1649
+ const room = this.rooms.get(msg.room_id);
1650
+ room?._dispatchAnnouncement(msg);
1651
+ return;
1652
+ }
1653
+ default: {
1654
+ const roomId = "room_id" in msg ? msg.room_id : void 0;
1655
+ if (!roomId) return;
1656
+ const room = this.rooms.get(roomId);
1657
+ if (!room) return;
1658
+ if (msg.type === "chat_receive" && idGreater(msg.message_id, this.lastMessageIdByRoom.get(roomId))) {
1659
+ this.lastMessageIdByRoom.set(roomId, msg.message_id);
1660
+ }
1661
+ if (msg.type === "chat_receive") {
1662
+ const tid = msg.temp_id ?? null;
1663
+ if (tid && room._isMySentTempId(tid)) {
1664
+ room._dispatchAck(tid, msg.message_id);
1665
+ room._forgetMySentTempId(tid);
1666
+ return;
1667
+ }
1668
+ }
1669
+ room._dispatchInbound(msg);
1670
+ }
1671
+ }
1672
+ }
1673
+ highestKnownMessageId() {
1674
+ let max = null;
1675
+ for (const v of this.lastMessageIdByRoom.values()) {
1676
+ if (idGreater(v, max)) max = v;
1677
+ }
1678
+ return max;
1679
+ }
1680
+ async backfillAllRooms() {
1681
+ for (const [roomId, lastSeen] of this.lastMessageIdByRoom) {
1682
+ try {
1683
+ const room = this.rooms.get(roomId);
1684
+ if (!room) continue;
1685
+ const { items } = await room.listSince(lastSeen, 200);
1686
+ for (const m of items) {
1687
+ room._dispatchInbound({
1688
+ type: "chat_receive",
1689
+ room_id: roomId,
1690
+ message_id: m.messageId,
1691
+ sender_id: m.senderId ?? null,
1692
+ message_type: m.messageType,
1693
+ custom_type: m.customType ?? null,
1694
+ content: m.content ?? null,
1695
+ data: m.data ?? null,
1696
+ meta: m.meta ?? null,
1697
+ file_id: m.fileId ?? null,
1698
+ // Inline file metadata loaded via REST has the same shape as
1699
+ // the WS frame's `file` field — pass through if the history
1700
+ // entry carries it; otherwise null and the UI calls
1701
+ // ``chat.getFileMeta(fileId)`` to fetch on demand.
1702
+ file: m.file ? {
1703
+ id: m.file.id,
1704
+ kind: m.file.kind,
1705
+ mime: m.file.mime,
1706
+ size: m.file.size,
1707
+ name: m.file.name ?? null,
1708
+ width: m.file.width ?? null,
1709
+ height: m.file.height ?? null,
1710
+ duration_sec: m.file.durationSec ?? null,
1711
+ thumbnail_status: m.file.thumbnailStatus
1712
+ } : null,
1713
+ reply_to_id: m.replyToId ?? null,
1714
+ created_at: m.createdAtMs,
1715
+ server_ts: Date.now()
1716
+ });
1717
+ if (idGreater(m.messageId, this.lastMessageIdByRoom.get(roomId))) {
1718
+ this.lastMessageIdByRoom.set(roomId, m.messageId);
1719
+ }
1720
+ }
1721
+ } catch (err) {
1722
+ if (err instanceof NoveraChatError) {
1723
+ this.logger?.("warn", `backfill_failed room=${roomId}`, err);
1724
+ } else {
1725
+ throw err;
1726
+ }
1727
+ }
1728
+ }
1729
+ }
1730
+ };
1731
+ // Annotate the CommonJS export names for ESM import in node:
1732
+ 0 && (module.exports = {
1733
+ ErrorCode,
1734
+ NoveraChat,
1735
+ NoveraChatError,
1736
+ Room
1737
+ });