@kispi/chat 0.5.0 → 0.6.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.
package/README.en.md CHANGED
@@ -225,11 +225,13 @@ try {
225
225
 
226
226
  | Field | |
227
227
  |---|---|
228
- | `code` | A union of the known values (`ChatErrorCode`), so a typo fails to compile. From the server: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. From the SDK: `timeout`, `closed`. A code the server adds later still type-checks |
228
+ | `code` | A union of the known values (`ChatErrorCode`), so a typo fails to compile. From the server: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `quota_exceeded`, `internal`. From the SDK: `timeout`, `closed`. A code the server adds later still type-checks |
229
229
  | `retryAfterMs` | Wait time reported by the server when you hit a limit |
230
230
  | `appCode` | Consumer-side code attached by a `before_publish` webhook when rejecting |
231
231
  | `status` | HTTP status, if the error came from a REST call |
232
232
 
233
+ `quota_exceeded` means the app's storage quota (`limits.maxStoredMessages`) is full. Only new messages are refused (403 over REST); edits, deletes and reactions still work. Deleting messages does not free space (deleted messages are still counted) -- it clears when the app operator raises the quota or purges rooms. Waiting does not clear it, so there is no `retryAfterMs` and the SDK does not resend -- show "storage is full" instead of retrying.
234
+
233
235
  ---
234
236
 
235
237
  ## `@kispi/chat/server` — backend
package/README.md CHANGED
@@ -215,11 +215,13 @@ try {
215
215
 
216
216
  | 필드 | |
217
217
  |---|---|
218
- | `code` | 알려진 값의 유니온(`ChatErrorCode`)이라 오타가 컴파일에서 잡힌다. 서버: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. SDK: `timeout`, `closed`. 서버가 새 코드를 내도 좁혀 놓은 타입이 막지 않는다 |
218
+ | `code` | 알려진 값의 유니온(`ChatErrorCode`)이라 오타가 컴파일에서 잡힌다. 서버: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `quota_exceeded`, `internal`. SDK: `timeout`, `closed`. 서버가 새 코드를 내도 좁혀 놓은 타입이 막지 않는다 |
219
219
  | `retryAfterMs` | 한도에 걸렸을 때 서버가 알려 준 대기 시간 |
220
220
  | `appCode` | `before_publish` 웹훅이 거절하며 붙인 소비자 쪽 코드 |
221
221
  | `status` | REST 호출에서 난 에러면 HTTP 상태 |
222
222
 
223
+ `quota_exceeded`는 앱의 저장 쿼터(`limits.maxStoredMessages`)가 찼다는 뜻이다. 새 메시지만 거절되고(REST는 403) 편집·삭제·리액션은 된다. 메시지를 지워도 공간은 비지 않는다(삭제된 메시지도 센다) — 풀리는 길은 앱 운영자가 쿼터를 올리거나 방을 purge하는 것이다. 기다려서 풀리지 않으므로 `retryAfterMs`가 없고 SDK도 다시 보내지 않는다 — 재시도 루프를 짜지 말고 "저장 공간이 찼다"를 보여 준다.
224
+
223
225
  ---
224
226
 
225
227
  ## `@kispi/chat/server` — 백엔드
package/dist/index.cjs CHANGED
@@ -621,6 +621,15 @@ var Room = class extends Emitter {
621
621
  key;
622
622
  /** The last seq the server reported for this room. */
623
623
  lastSeq = 0;
624
+ /**
625
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
626
+ *
627
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
628
+ * and carries no `users`, so holding the frame itself dropped the list
629
+ * the moment anyone came or went. The SDK folds increments into the list
630
+ * it holds; `users` is absent when it does not know the list (a room over
631
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
632
+ */
624
633
  presence;
625
634
  chat;
626
635
  rest;
@@ -842,7 +851,7 @@ var Room = class extends Emitter {
842
851
  messageId,
843
852
  emoji,
844
853
  op: mine ? "add" : "remove"
845
- });
854
+ }, void 0, { resendOnDrop: true });
846
855
  } catch (err) {
847
856
  if (press !== void 0) this.timeline.settleReaction(press, false);
848
857
  throw err;
@@ -860,7 +869,7 @@ var Room = class extends Emitter {
860
869
  async markRead(seq, options = {}) {
861
870
  const data = { roomId: await this.resolveId("marking read"), seq };
862
871
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
863
- return await this.chat.sendFrame("read", data);
872
+ return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true });
864
873
  }
865
874
  /**
866
875
  * Lists read cursors in this room, one page at a time.
@@ -913,7 +922,7 @@ var Room = class extends Emitter {
913
922
  try {
914
923
  const data = { roomId: this.requireId("typing") };
915
924
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
916
- void this.chat.sendFrame("typing", data).catch(() => {
925
+ void this.chat.sendFrame("typing", data, void 0, { wait: false }).catch(() => {
917
926
  });
918
927
  } catch {
919
928
  }
@@ -1011,7 +1020,7 @@ var Room = class extends Emitter {
1011
1020
  this.subscribed = false;
1012
1021
  this.generation++;
1013
1022
  this.subscribing = void 0;
1014
- await this.chat.sendFrame("unsubscribe", { roomId: this.id });
1023
+ await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
1015
1024
  }
1016
1025
  /**
1017
1026
  * The room's id, or a refusal.
@@ -1056,7 +1065,7 @@ var Room = class extends Emitter {
1056
1065
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
1057
1066
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
1058
1067
  if (input.meta !== void 0) frame["meta"] = input.meta;
1059
- return await this.chat.sendFrame("publish", frame);
1068
+ return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true });
1060
1069
  }
1061
1070
  /** @internal Routes a frame the client decided belongs to this room. */
1062
1071
  handle(type, data) {
@@ -1091,7 +1100,7 @@ var Room = class extends Emitter {
1091
1100
  break;
1092
1101
  }
1093
1102
  case "presence":
1094
- this.presence = data;
1103
+ this.presence = foldPresence(this.presence, data);
1095
1104
  break;
1096
1105
  default:
1097
1106
  break;
@@ -1116,6 +1125,20 @@ var Room = class extends Emitter {
1116
1125
  this.timeline.reset(page.messages);
1117
1126
  }
1118
1127
  };
1128
+ function foldPresence(held, frame) {
1129
+ if (frame.users !== void 0) {
1130
+ return frame.capped === void 0 ? { count: frame.count, users: frame.users } : { count: frame.count, users: frame.users, capped: frame.capped };
1131
+ }
1132
+ const list = held?.users;
1133
+ if (list === void 0 || frame.joined === void 0 && frame.left === void 0) {
1134
+ return { count: frame.count };
1135
+ }
1136
+ const gone = new Set(frame.left ?? []);
1137
+ const arrived = frame.joined ?? [];
1138
+ const fresh = new Set(arrived.map((u) => u.id));
1139
+ const users = [...list.filter((u) => !gone.has(u.id) && !fresh.has(u.id)), ...arrived];
1140
+ return { count: frame.count, users };
1141
+ }
1119
1142
  function newClientMessageId() {
1120
1143
  const c = globalThis.crypto;
1121
1144
  if (c?.randomUUID !== void 0) return `cm-${c.randomUUID()}`;
@@ -1467,7 +1490,57 @@ var ChatClient = class extends Emitter {
1467
1490
  * 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
1468
1491
  * 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
1469
1492
  */
1470
- sendFrame(type, data, timeoutMs = 15e3) {
1493
+ sendFrame(type, data, timeoutMs = 15e3, options = {}) {
1494
+ const deadline = Date.now() + timeoutMs;
1495
+ const wait = options.wait ?? true;
1496
+ const run = async (resends) => {
1497
+ if (this.socket === void 0 || this.state !== "open") {
1498
+ if (!wait || this.stopped || this.state === "closed") {
1499
+ throw new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`);
1500
+ }
1501
+ const serverSaidWait = this.serverDelayUntil !== void 0 && Date.now() < this.serverDelayUntil;
1502
+ if (this.state === "reconnecting" && this.opening === void 0 && !serverSaidWait) {
1503
+ void this.resume().catch(() => {
1504
+ });
1505
+ }
1506
+ await this.untilOpen(type, deadline);
1507
+ }
1508
+ try {
1509
+ return await this.sendOnSocket(type, data, Math.max(0, deadline - Date.now()));
1510
+ } catch (err) {
1511
+ if (options.resendOnDrop === true && resends === 0 && isChatError(err) && err.code === "closed" && !this.stopped && Date.now() < deadline) {
1512
+ return run(resends + 1);
1513
+ }
1514
+ throw err;
1515
+ }
1516
+ };
1517
+ return run(0);
1518
+ }
1519
+ // whenOpen, bounded by the frame's deadline: running out is `timeout`, not `closed`.
1520
+ // The waiter leaves the list when it times out, so a long offline spell of
1521
+ // repeated sends does not pile closures up until the next hello.
1522
+ untilOpen(type, deadline) {
1523
+ if (this.state === "open" && this.socket !== void 0) return Promise.resolve();
1524
+ if (this.stopped) return Promise.reject(new ChatError("closed", "the connection is closed"));
1525
+ return new Promise((resolve, reject) => {
1526
+ const waiter = {
1527
+ resolve: () => {
1528
+ clearTimeout(timer);
1529
+ resolve();
1530
+ },
1531
+ reject: (err) => {
1532
+ clearTimeout(timer);
1533
+ reject(err);
1534
+ }
1535
+ };
1536
+ const timer = setTimeout(() => {
1537
+ this.openWaiters = this.openWaiters.filter((w) => w !== waiter);
1538
+ reject(new ChatError("timeout", `cannot send ${type}: the connection did not reopen in time`));
1539
+ }, Math.max(0, deadline - Date.now()));
1540
+ this.openWaiters.push(waiter);
1541
+ });
1542
+ }
1543
+ sendOnSocket(type, data, timeoutMs) {
1471
1544
  const socket = this.socket;
1472
1545
  if (socket === void 0 || this.state !== "open") {
1473
1546
  return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
@@ -1645,6 +1718,8 @@ var ChatClient = class extends Emitter {
1645
1718
  room.handle(event, push?.data);
1646
1719
  }
1647
1720
  plannedDelayMs;
1721
+ // When a server-directed delay (drain, rate limit) ends; a send does not cut it short.
1722
+ serverDelayUntil;
1648
1723
  startHeartbeat(intervalMs) {
1649
1724
  this.clearHeartbeat();
1650
1725
  this.heartbeat = setInterval(() => {
@@ -1676,6 +1751,7 @@ var ChatClient = class extends Emitter {
1676
1751
  nextDelay() {
1677
1752
  const planned = this.plannedDelayMs;
1678
1753
  this.plannedDelayMs = void 0;
1754
+ this.serverDelayUntil = planned === void 0 ? void 0 : Date.now() + planned;
1679
1755
  if (planned !== void 0) return planned;
1680
1756
  const ceiling = Math.min(MaxBackoffMs, MinBackoffMs * 2 ** this.attempt);
1681
1757
  this.attempt++;
package/dist/index.d.cts CHANGED
@@ -22,7 +22,13 @@ declare class Emitter<Events extends Record<string, unknown>> {
22
22
  * 사실은 한도에 실제로 걸리는 날에야 드러난다. 목록은
23
23
  * `docs/protocol.md`의 "에러 코드"가 정본이다.
24
24
  */
25
- type ChatErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'invalid' | 'too_large' | 'rate_limited' | 'banned' | 'moderation_denied' | 'cursor_too_old' | 'internal'
25
+ type ChatErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'invalid' | 'too_large' | 'rate_limited' | 'banned' | 'moderation_denied' | 'cursor_too_old'
26
+ /**
27
+ * 앱의 저장 쿼터(`limits.maxStoredMessages`)가 찼다. 기다려서 풀리지 않으므로
28
+ * `retryAfterMs`가 없고 SDK도 재시도하지 않는다. 메시지를 지워도 비지 않는다
29
+ * (삭제된 메시지도 센다) — 앱 운영자가 쿼터를 올리거나 방을 purge해야 한다.
30
+ */
31
+ | 'quota_exceeded' | 'internal'
26
32
  /** SDK가 낸다: ack가 제 시간에 오지 않았다. */
27
33
  | 'timeout'
28
34
  /** SDK가 낸다: 연결이 없거나 닫혔다. */
@@ -352,6 +358,15 @@ declare class Room extends Emitter<RoomEvents> {
352
358
  readonly key: string | undefined;
353
359
  /** The last seq the server reported for this room. */
354
360
  lastSeq: number;
361
+ /**
362
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
363
+ *
364
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
365
+ * and carries no `users`, so holding the frame itself dropped the list
366
+ * the moment anyone came or went. The SDK folds increments into the list
367
+ * it holds; `users` is absent when it does not know the list (a room over
368
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
369
+ */
355
370
  presence: PresenceEvent | undefined;
356
371
  private readonly chat;
357
372
  private readonly rest;
@@ -862,6 +877,8 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
862
877
  private stop;
863
878
  private openWaiters;
864
879
  private settleOpenWaiters;
880
+ private untilOpen;
881
+ private sendOnSocket;
865
882
  /**
866
883
  * Frames waiting for an ack, by frame id.
867
884
  *
@@ -888,6 +905,7 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
888
905
  */
889
906
  private onPush;
890
907
  private plannedDelayMs;
908
+ private serverDelayUntil;
891
909
  private startHeartbeat;
892
910
  private scheduleReconnect;
893
911
  /**
package/dist/index.d.ts CHANGED
@@ -22,7 +22,13 @@ declare class Emitter<Events extends Record<string, unknown>> {
22
22
  * 사실은 한도에 실제로 걸리는 날에야 드러난다. 목록은
23
23
  * `docs/protocol.md`의 "에러 코드"가 정본이다.
24
24
  */
25
- type ChatErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'invalid' | 'too_large' | 'rate_limited' | 'banned' | 'moderation_denied' | 'cursor_too_old' | 'internal'
25
+ type ChatErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'invalid' | 'too_large' | 'rate_limited' | 'banned' | 'moderation_denied' | 'cursor_too_old'
26
+ /**
27
+ * 앱의 저장 쿼터(`limits.maxStoredMessages`)가 찼다. 기다려서 풀리지 않으므로
28
+ * `retryAfterMs`가 없고 SDK도 재시도하지 않는다. 메시지를 지워도 비지 않는다
29
+ * (삭제된 메시지도 센다) — 앱 운영자가 쿼터를 올리거나 방을 purge해야 한다.
30
+ */
31
+ | 'quota_exceeded' | 'internal'
26
32
  /** SDK가 낸다: ack가 제 시간에 오지 않았다. */
27
33
  | 'timeout'
28
34
  /** SDK가 낸다: 연결이 없거나 닫혔다. */
@@ -352,6 +358,15 @@ declare class Room extends Emitter<RoomEvents> {
352
358
  readonly key: string | undefined;
353
359
  /** The last seq the server reported for this room. */
354
360
  lastSeq: number;
361
+ /**
362
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
363
+ *
364
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
365
+ * and carries no `users`, so holding the frame itself dropped the list
366
+ * the moment anyone came or went. The SDK folds increments into the list
367
+ * it holds; `users` is absent when it does not know the list (a room over
368
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
369
+ */
355
370
  presence: PresenceEvent | undefined;
356
371
  private readonly chat;
357
372
  private readonly rest;
@@ -862,6 +877,8 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
862
877
  private stop;
863
878
  private openWaiters;
864
879
  private settleOpenWaiters;
880
+ private untilOpen;
881
+ private sendOnSocket;
865
882
  /**
866
883
  * Frames waiting for an ack, by frame id.
867
884
  *
@@ -888,6 +905,7 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
888
905
  */
889
906
  private onPush;
890
907
  private plannedDelayMs;
908
+ private serverDelayUntil;
891
909
  private startHeartbeat;
892
910
  private scheduleReconnect;
893
911
  /**
package/dist/index.js CHANGED
@@ -551,6 +551,15 @@ var Room = class extends Emitter {
551
551
  key;
552
552
  /** The last seq the server reported for this room. */
553
553
  lastSeq = 0;
554
+ /**
555
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
556
+ *
557
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
558
+ * and carries no `users`, so holding the frame itself dropped the list
559
+ * the moment anyone came or went. The SDK folds increments into the list
560
+ * it holds; `users` is absent when it does not know the list (a room over
561
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
562
+ */
554
563
  presence;
555
564
  chat;
556
565
  rest;
@@ -772,7 +781,7 @@ var Room = class extends Emitter {
772
781
  messageId,
773
782
  emoji,
774
783
  op: mine ? "add" : "remove"
775
- });
784
+ }, void 0, { resendOnDrop: true });
776
785
  } catch (err) {
777
786
  if (press !== void 0) this.timeline.settleReaction(press, false);
778
787
  throw err;
@@ -790,7 +799,7 @@ var Room = class extends Emitter {
790
799
  async markRead(seq, options = {}) {
791
800
  const data = { roomId: await this.resolveId("marking read"), seq };
792
801
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
793
- return await this.chat.sendFrame("read", data);
802
+ return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true });
794
803
  }
795
804
  /**
796
805
  * Lists read cursors in this room, one page at a time.
@@ -843,7 +852,7 @@ var Room = class extends Emitter {
843
852
  try {
844
853
  const data = { roomId: this.requireId("typing") };
845
854
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
846
- void this.chat.sendFrame("typing", data).catch(() => {
855
+ void this.chat.sendFrame("typing", data, void 0, { wait: false }).catch(() => {
847
856
  });
848
857
  } catch {
849
858
  }
@@ -941,7 +950,7 @@ var Room = class extends Emitter {
941
950
  this.subscribed = false;
942
951
  this.generation++;
943
952
  this.subscribing = void 0;
944
- await this.chat.sendFrame("unsubscribe", { roomId: this.id });
953
+ await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
945
954
  }
946
955
  /**
947
956
  * The room's id, or a refusal.
@@ -986,7 +995,7 @@ var Room = class extends Emitter {
986
995
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
987
996
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
988
997
  if (input.meta !== void 0) frame["meta"] = input.meta;
989
- return await this.chat.sendFrame("publish", frame);
998
+ return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true });
990
999
  }
991
1000
  /** @internal Routes a frame the client decided belongs to this room. */
992
1001
  handle(type, data) {
@@ -1021,7 +1030,7 @@ var Room = class extends Emitter {
1021
1030
  break;
1022
1031
  }
1023
1032
  case "presence":
1024
- this.presence = data;
1033
+ this.presence = foldPresence(this.presence, data);
1025
1034
  break;
1026
1035
  default:
1027
1036
  break;
@@ -1046,6 +1055,20 @@ var Room = class extends Emitter {
1046
1055
  this.timeline.reset(page.messages);
1047
1056
  }
1048
1057
  };
1058
+ function foldPresence(held, frame) {
1059
+ if (frame.users !== void 0) {
1060
+ return frame.capped === void 0 ? { count: frame.count, users: frame.users } : { count: frame.count, users: frame.users, capped: frame.capped };
1061
+ }
1062
+ const list = held?.users;
1063
+ if (list === void 0 || frame.joined === void 0 && frame.left === void 0) {
1064
+ return { count: frame.count };
1065
+ }
1066
+ const gone = new Set(frame.left ?? []);
1067
+ const arrived = frame.joined ?? [];
1068
+ const fresh = new Set(arrived.map((u) => u.id));
1069
+ const users = [...list.filter((u) => !gone.has(u.id) && !fresh.has(u.id)), ...arrived];
1070
+ return { count: frame.count, users };
1071
+ }
1049
1072
  function newClientMessageId() {
1050
1073
  const c = globalThis.crypto;
1051
1074
  if (c?.randomUUID !== void 0) return `cm-${c.randomUUID()}`;
@@ -1397,7 +1420,57 @@ var ChatClient = class extends Emitter {
1397
1420
  * 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
1398
1421
  * 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
1399
1422
  */
1400
- sendFrame(type, data, timeoutMs = 15e3) {
1423
+ sendFrame(type, data, timeoutMs = 15e3, options = {}) {
1424
+ const deadline = Date.now() + timeoutMs;
1425
+ const wait = options.wait ?? true;
1426
+ const run = async (resends) => {
1427
+ if (this.socket === void 0 || this.state !== "open") {
1428
+ if (!wait || this.stopped || this.state === "closed") {
1429
+ throw new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`);
1430
+ }
1431
+ const serverSaidWait = this.serverDelayUntil !== void 0 && Date.now() < this.serverDelayUntil;
1432
+ if (this.state === "reconnecting" && this.opening === void 0 && !serverSaidWait) {
1433
+ void this.resume().catch(() => {
1434
+ });
1435
+ }
1436
+ await this.untilOpen(type, deadline);
1437
+ }
1438
+ try {
1439
+ return await this.sendOnSocket(type, data, Math.max(0, deadline - Date.now()));
1440
+ } catch (err) {
1441
+ if (options.resendOnDrop === true && resends === 0 && isChatError(err) && err.code === "closed" && !this.stopped && Date.now() < deadline) {
1442
+ return run(resends + 1);
1443
+ }
1444
+ throw err;
1445
+ }
1446
+ };
1447
+ return run(0);
1448
+ }
1449
+ // whenOpen, bounded by the frame's deadline: running out is `timeout`, not `closed`.
1450
+ // The waiter leaves the list when it times out, so a long offline spell of
1451
+ // repeated sends does not pile closures up until the next hello.
1452
+ untilOpen(type, deadline) {
1453
+ if (this.state === "open" && this.socket !== void 0) return Promise.resolve();
1454
+ if (this.stopped) return Promise.reject(new ChatError("closed", "the connection is closed"));
1455
+ return new Promise((resolve, reject) => {
1456
+ const waiter = {
1457
+ resolve: () => {
1458
+ clearTimeout(timer);
1459
+ resolve();
1460
+ },
1461
+ reject: (err) => {
1462
+ clearTimeout(timer);
1463
+ reject(err);
1464
+ }
1465
+ };
1466
+ const timer = setTimeout(() => {
1467
+ this.openWaiters = this.openWaiters.filter((w) => w !== waiter);
1468
+ reject(new ChatError("timeout", `cannot send ${type}: the connection did not reopen in time`));
1469
+ }, Math.max(0, deadline - Date.now()));
1470
+ this.openWaiters.push(waiter);
1471
+ });
1472
+ }
1473
+ sendOnSocket(type, data, timeoutMs) {
1401
1474
  const socket = this.socket;
1402
1475
  if (socket === void 0 || this.state !== "open") {
1403
1476
  return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
@@ -1575,6 +1648,8 @@ var ChatClient = class extends Emitter {
1575
1648
  room.handle(event, push?.data);
1576
1649
  }
1577
1650
  plannedDelayMs;
1651
+ // When a server-directed delay (drain, rate limit) ends; a send does not cut it short.
1652
+ serverDelayUntil;
1578
1653
  startHeartbeat(intervalMs) {
1579
1654
  this.clearHeartbeat();
1580
1655
  this.heartbeat = setInterval(() => {
@@ -1606,6 +1681,7 @@ var ChatClient = class extends Emitter {
1606
1681
  nextDelay() {
1607
1682
  const planned = this.plannedDelayMs;
1608
1683
  this.plannedDelayMs = void 0;
1684
+ this.serverDelayUntil = planned === void 0 ? void 0 : Date.now() + planned;
1609
1685
  if (planned !== void 0) return planned;
1610
1686
  const ceiling = Math.min(MaxBackoffMs, MinBackoffMs * 2 ** this.attempt);
1611
1687
  this.attempt++;
@@ -286,6 +286,14 @@ function createChatServer(options) {
286
286
  };
287
287
  },
288
288
  rooms: {
289
+ list: (o) => rest.call(
290
+ "GET",
291
+ `/v1/rooms${rest.query({
292
+ type: Array.isArray(o?.type) ? o.type.join(",") : o?.type,
293
+ cursor: o?.cursor,
294
+ limit: o?.limit
295
+ })}`
296
+ ),
289
297
  ensure: (input) => rest.call("PUT", "/v1/rooms", input),
290
298
  ensureDM: (members) => rest.call("PUT", "/v1/rooms", { type: "dm", members }),
291
299
  get: (roomId) => rest.call("GET", `/v1/rooms/${roomId}`),
@@ -151,6 +151,21 @@ type ChatServer = {
151
151
  */
152
152
  guest: (input: GuestInput) => GuestIdentity;
153
153
  rooms: {
154
+ /**
155
+ * The app's rooms, newest first. With no `type` it is the public
156
+ * listing (`public` and `channel`) -- the same page a client's
157
+ * `rooms.discover()` gets; name `private` and `dm` to find the rest.
158
+ * `cursor` is opaque, empty on the last page, and does not carry
159
+ * `type`: start over when the filter changes.
160
+ */
161
+ list: (options?: {
162
+ type?: EnsureRoomInput['type'] | EnsureRoomInput['type'][];
163
+ cursor?: string;
164
+ limit?: number;
165
+ }) => Promise<{
166
+ rooms: unknown[];
167
+ cursor: string;
168
+ }>;
154
169
  /** get-or-create. The same call whether the room exists or not. */
155
170
  ensure: (input: EnsureRoomInput) => Promise<{
156
171
  id: string;
@@ -151,6 +151,21 @@ type ChatServer = {
151
151
  */
152
152
  guest: (input: GuestInput) => GuestIdentity;
153
153
  rooms: {
154
+ /**
155
+ * The app's rooms, newest first. With no `type` it is the public
156
+ * listing (`public` and `channel`) -- the same page a client's
157
+ * `rooms.discover()` gets; name `private` and `dm` to find the rest.
158
+ * `cursor` is opaque, empty on the last page, and does not carry
159
+ * `type`: start over when the filter changes.
160
+ */
161
+ list: (options?: {
162
+ type?: EnsureRoomInput['type'] | EnsureRoomInput['type'][];
163
+ cursor?: string;
164
+ limit?: number;
165
+ }) => Promise<{
166
+ rooms: unknown[];
167
+ cursor: string;
168
+ }>;
154
169
  /** get-or-create. The same call whether the room exists or not. */
155
170
  ensure: (input: EnsureRoomInput) => Promise<{
156
171
  id: string;
@@ -215,6 +215,14 @@ function createChatServer(options) {
215
215
  };
216
216
  },
217
217
  rooms: {
218
+ list: (o) => rest.call(
219
+ "GET",
220
+ `/v1/rooms${rest.query({
221
+ type: Array.isArray(o?.type) ? o.type.join(",") : o?.type,
222
+ cursor: o?.cursor,
223
+ limit: o?.limit
224
+ })}`
225
+ ),
218
226
  ensure: (input) => rest.call("PUT", "/v1/rooms", input),
219
227
  ensureDM: (members) => rest.call("PUT", "/v1/rooms", { type: "dm", members }),
220
228
  get: (roomId) => rest.call("GET", `/v1/rooms/${roomId}`),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,6 +33,7 @@
33
33
  },
34
34
  "scripts": {
35
35
  "build": "tsup",
36
+ "prepack": "npm run build",
36
37
  "test": "vitest run",
37
38
  "typecheck": "tsc --noEmit"
38
39
  },