@kispi/chat 0.5.1 → 0.7.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
@@ -42,7 +42,7 @@ is in the browser, the whole app is open.
42
42
  |---|---|
43
43
  | `connect()` | Connects. If already connected or connecting, it joins that attempt. Rejects on failure, but **retries continue in the background** (see below) |
44
44
  | `close()` | Disconnects. This one does not reconnect. Call `connect()` to come back |
45
- | `reconnect()` | **Re-authenticates**: calls `token()` again and replaces the socket. Room handles, subscriptions and `messages` are kept, and the state goes `open → reconnecting → open` (never `closed`). Use it after a nickname or avatar change (below) |
45
+ | `reconnect()` | **Re-authenticates**: calls `token()` again and replaces the socket. Room handles, subscriptions and `messages` are kept (**when the user changes, `messages` is dropped and refilled**), and the state goes `open → reconnecting → open` (never `closed`). Use it after a nickname or avatar change, and **when logging in or out switches the user** (below) |
46
46
  | `room(roomId)` | Room handle. Same id, same object |
47
47
  | `roomByKey(key)` | Handle for a room opened by key. The server tells you the id when you subscribe. **Does not create the room** — for a key that doesn't exist, `subscribe()` rejects with `not_found`. Rooms are created by the backend with `rooms.ensure()` |
48
48
  | `rooms.list({cursor?, limit?})` | Rooms I'm a member of + unread + last message |
@@ -114,7 +114,7 @@ The SDK emits three more that have no wire counterpart.
114
114
  |---|---|
115
115
  | `messages` | Every time the list changes. **A new array each time; an emitted array is never touched again** |
116
116
  | `error` | Reading history or filling a gap failed. **The room resubscribes itself.** The retry button for a person is `subscribe()` |
117
- | `reset` | The cursor was older than the retention period, so the list was discarded and refilled. **You must discard what you rendered** |
117
+ | `reset` | The list was discarded and refilled — the cursor was older than the retention period, or **the client reconnected as a different user** (below). **You must discard what you rendered** |
118
118
 
119
119
  ### Things to know
120
120
 
@@ -167,6 +167,15 @@ room.on('messages', m => (messages.value = m))
167
167
  like a ban, is not worth retrying.
168
168
  - **After a nickname or avatar change, `reconnect()`.** The server reads those values from the
169
169
  token claims once, when the socket authenticates.
170
+ - **Logging in or out is `reconnect()` too.** When `token()` returns a different user the SDK
171
+ notices: every room drops the list it held, reads recent history again as the new user and
172
+ emits `reset` (the rows' `myReactions` were the previous user's). A send, reaction or read still
173
+ waiting for the previous user is rejected with `closed` instead of going out under the new
174
+ name, so send as the new user after `reconnect()` resolves. `close()` then `connect()` behaves
175
+ the same. There is no need to create a new client. A room the new user cannot subscribe to (a
176
+ private room only the previous user was in) emits `error` instead of `reset` and stays empty.
177
+ **Call `reconnect()` whenever the login state changes** — the REST path that refreshes a token
178
+ on a 401 does not check whether the user changed.
170
179
 
171
180
  ### `text` is untrusted plain text
172
181
 
@@ -225,11 +234,13 @@ try {
225
234
 
226
235
  | Field | |
227
236
  |---|---|
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 |
237
+ | `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
238
  | `retryAfterMs` | Wait time reported by the server when you hit a limit |
230
239
  | `appCode` | Consumer-side code attached by a `before_publish` webhook when rejecting |
231
240
  | `status` | HTTP status, if the error came from a REST call |
232
241
 
242
+ `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.
243
+
233
244
  ---
234
245
 
235
246
  ## `@kispi/chat/server` — backend
package/README.md CHANGED
@@ -42,7 +42,7 @@ npm install @kispi/chat
42
42
  |---|---|
43
43
  | `connect()` | 붙는다. 이미 붙어 있거나 붙는 중이면 그 시도에 합류한다. 실패하면 거절하지만 **재시도는 백그라운드에서 계속된다**(아래) |
44
44
  | `close()` | 끊는다. 이건 재접속하지 않는다. 다시 붙으려면 `connect()` |
45
- | `reconnect()` | **다시 인증한다**: `token()`을 다시 불러 소켓을 바꾼다. 방 핸들과 구독, `messages`는 그대로이고 상태는 `open → reconnecting → open`이다(`closed`를 거치지 않는다). 닉네임·아바타를 바꾼 뒤에 쓴다(아래) |
45
+ | `reconnect()` | **다시 인증한다**: `token()`을 다시 불러 소켓을 바꾼다. 방 핸들과 구독, `messages`는 그대로이고(**사람이 바뀌면 `messages`는 버리고 다시 채운다**) 상태는 `open → reconnecting → open`이다(`closed`를 거치지 않는다). 닉네임·아바타를 바꾼 뒤, 그리고 **로그인·로그아웃으로 사람이 바뀔 때** 쓴다(아래) |
46
46
  | `room(roomId)` | 방 핸들. 같은 id면 같은 객체 |
47
47
  | `roomByKey(key)` | 키로 여는 방 핸들. 구독할 때 서버가 id를 알려 준다. **방을 만들지 않는다** — 없는 키면 `subscribe()`가 `not_found`로 거절한다. 방은 백엔드가 `rooms.ensure()`로 만든다 |
48
48
  | `rooms.list({cursor?, limit?})` | 내가 멤버인 방 + unread + 마지막 메시지 |
@@ -114,7 +114,7 @@ off()
114
114
  |---|---|
115
115
  | `messages` | 목록이 바뀔 때마다. **매번 새 배열이고, 내보낸 배열은 다시 건드리지 않는다** |
116
116
  | `error` | 히스토리를 읽거나 구멍을 메우는 데 실패했다. **방이 스스로 다시 구독한다.** 사람이 누를 재시도 버튼은 `subscribe()` |
117
- | `reset` | 커서가 보존 기간보다 오래돼 목록을 버리고 다시 채웠다. **렌더한 것을 버려야 한다** |
117
+ | `reset` | 목록을 버리고 다시 채웠다 — 커서가 보존 기간보다 오래됐거나, **다른 사람으로 다시 붙었다**(아래). **렌더한 것을 버려야 한다** |
118
118
 
119
119
  ### 알아 둘 것
120
120
 
@@ -161,6 +161,14 @@ room.on('messages', m => (messages.value = m))
161
161
  - **`token()`이 `ChatError`를 던지면 멈춘다.** 밴처럼 다시 해도 소용없는 실패를 그렇게 알린다.
162
162
  - **닉네임·아바타를 바꿨으면 `reconnect()`.** 서버는 그 값을 접속할 때 토큰 claim에서
163
163
  한 번 읽는다.
164
+ - **로그인·로그아웃도 `reconnect()`다.** `token()`이 다른 사람을 돌려주면 SDK가 알아챈다 —
165
+ 방마다 들고 있던 목록을 버리고 새 사람의 눈으로 최근 히스토리를 다시 읽어 `reset`을 낸다
166
+ (행의 `myReactions`가 이전 사람의 것이었다). 이전 사람으로 기다리던 전송·리액션·읽음은 새
167
+ 사람 이름으로 나가지 않고 `closed`로 거절되므로, 새 사람의 전송은 `reconnect()`를 기다린 뒤에 한다.
168
+ `close()` 뒤의 `connect()`도 같다. 클라이언트를 새로 만들 필요는 없다. 새 사람으로 다시 구독할 수
169
+ 없는 방(이전 사람만 멤버였던 private 방)은 `reset` 대신 `error`이고 목록은 빈 채로 남는다.
170
+ **로그인 상태가 바뀌면 반드시 `reconnect()`를 부른다** — REST가 401에서 토큰을 갱신하는 길은
171
+ 사람이 바뀌었는지 보지 않는다.
164
172
 
165
173
  ### `text`는 신뢰할 수 없는 평문이다
166
174
 
@@ -215,11 +223,13 @@ try {
215
223
 
216
224
  | 필드 | |
217
225
  |---|---|
218
- | `code` | 알려진 값의 유니온(`ChatErrorCode`)이라 오타가 컴파일에서 잡힌다. 서버: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. SDK: `timeout`, `closed`. 서버가 새 코드를 내도 좁혀 놓은 타입이 막지 않는다 |
226
+ | `code` | 알려진 값의 유니온(`ChatErrorCode`)이라 오타가 컴파일에서 잡힌다. 서버: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `quota_exceeded`, `internal`. SDK: `timeout`, `closed`. 서버가 새 코드를 내도 좁혀 놓은 타입이 막지 않는다 |
219
227
  | `retryAfterMs` | 한도에 걸렸을 때 서버가 알려 준 대기 시간 |
220
228
  | `appCode` | `before_publish` 웹훅이 거절하며 붙인 소비자 쪽 코드 |
221
229
  | `status` | REST 호출에서 난 에러면 HTTP 상태 |
222
230
 
231
+ `quota_exceeded`는 앱의 저장 쿼터(`limits.maxStoredMessages`)가 찼다는 뜻이다. 새 메시지만 거절되고(REST는 403) 편집·삭제·리액션은 된다. 메시지를 지워도 공간은 비지 않는다(삭제된 메시지도 센다) — 풀리는 길은 앱 운영자가 쿼터를 올리거나 방을 purge하는 것이다. 기다려서 풀리지 않으므로 `retryAfterMs`가 없고 SDK도 다시 보내지 않는다 — 재시도 루프를 짜지 말고 "저장 공간이 찼다"를 보여 준다.
232
+
223
233
  ---
224
234
 
225
235
  ## `@kispi/chat/server` — 백엔드
package/dist/index.cjs CHANGED
@@ -660,6 +660,8 @@ var Room = class extends Emitter {
660
660
  * silently, which is worse than the failure that started it.
661
661
  */
662
662
  wanted = false;
663
+ /** 신원이 바뀌어 버린 목록을 다음 구독이 다시 채우고 `reset`으로 알려야 한다. */
664
+ rebuildPending = false;
663
665
  subscribing;
664
666
  /** Self-repair: the armed retry, and how many have run since the last success. */
665
667
  repairTimer;
@@ -770,9 +772,10 @@ var Room = class extends Emitter {
770
772
  this.lastSeq = ack.lastSeq;
771
773
  if (typeof ack.minSeq === "number") this.timeline.setFloor(ack.minSeq);
772
774
  if (ack.presence !== void 0) this.presence = ack.presence;
773
- if (attempt.wasReset) {
775
+ if (attempt.wasReset || this.rebuildPending) {
774
776
  await this.loadRecent(current);
775
777
  if (!current()) return;
778
+ this.rebuildPending = false;
776
779
  this.subscribed = true;
777
780
  this.emit("reset", this.timeline.messages);
778
781
  return;
@@ -845,13 +848,14 @@ var Room = class extends Emitter {
845
848
  */
846
849
  async toggleReaction(messageId, emoji, mine) {
847
850
  const press = this.timeline.pressReaction(messageId, emoji, mine);
851
+ const owner = this.chat.user?.id;
848
852
  try {
849
853
  await this.chat.sendFrame("react", {
850
854
  roomId: await this.resolveId("reacting"),
851
855
  messageId,
852
856
  emoji,
853
857
  op: mine ? "add" : "remove"
854
- }, void 0, { resendOnDrop: true });
858
+ }, void 0, { resendOnDrop: true, owner });
855
859
  } catch (err) {
856
860
  if (press !== void 0) this.timeline.settleReaction(press, false);
857
861
  throw err;
@@ -867,9 +871,10 @@ var Room = class extends Emitter {
867
871
  * way to know what happened. It is returned rather than swallowed.
868
872
  */
869
873
  async markRead(seq, options = {}) {
874
+ const owner = this.chat.user?.id;
870
875
  const data = { roomId: await this.resolveId("marking read"), seq };
871
876
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
872
- return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true });
877
+ return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true, owner });
873
878
  }
874
879
  /**
875
880
  * Lists read cursors in this room, one page at a time.
@@ -965,7 +970,11 @@ var Room = class extends Emitter {
965
970
  * transient 500 takes a room out of the live feed for the life of the
966
971
  * page.
967
972
  */
968
- async resume(restart = true) {
973
+ async resume(restart = true, userChanged = false) {
974
+ if (userChanged) {
975
+ this.timeline.discard();
976
+ if (this.wanted) this.rebuildPending = true;
977
+ }
969
978
  if (!this.wanted) return;
970
979
  if (!restart) return this.subscribe();
971
980
  this.generation++;
@@ -1018,6 +1027,7 @@ var Room = class extends Emitter {
1018
1027
  if (this.id === void 0) return;
1019
1028
  this.wanted = false;
1020
1029
  this.subscribed = false;
1030
+ this.rebuildPending = false;
1021
1031
  this.generation++;
1022
1032
  this.subscribing = void 0;
1023
1033
  await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
@@ -1052,6 +1062,7 @@ var Room = class extends Emitter {
1052
1062
  }
1053
1063
  /** Publishes and resolves when the server acks. */
1054
1064
  async send(input, options = {}) {
1065
+ const owner = this.chat.user?.id;
1055
1066
  const roomId = await this.resolveId("sending");
1056
1067
  const body = {};
1057
1068
  if (input.text !== void 0) body["text"] = input.text;
@@ -1065,7 +1076,7 @@ var Room = class extends Emitter {
1065
1076
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
1066
1077
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
1067
1078
  if (input.meta !== void 0) frame["meta"] = input.meta;
1068
- return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true });
1079
+ return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true, owner });
1069
1080
  }
1070
1081
  /** @internal Routes a frame the client decided belongs to this room. */
1071
1082
  handle(type, data) {
@@ -1375,13 +1386,21 @@ var ChatClient = class extends Emitter {
1375
1386
  * does that too, but passes through `closed` (a consumer's "you are
1376
1387
  * offline" screen) and tears down the page listeners.
1377
1388
  *
1378
- * States: `open` → `reconnecting` → `open`, never `closed`. Rooms
1379
- * resubscribe from what they hold and catch up the gap, as after any
1380
- * drop; `messages` is kept. Frames awaiting an ack on the old socket are
1381
- * rejected with `closed`. `chat.user` is the new identity once this
1382
- * resolves. If `token()` fails the client keeps retrying in the
1383
- * background like any reconnect (and this rejects); a `ChatError` from
1384
- * `token()` stops it at `closed`, as on connect.
1389
+ * States: `open` → `reconnecting` → `open`, never `closed`. For the same
1390
+ * user, rooms resubscribe from what they hold and catch up the gap, as
1391
+ * after any drop; `messages` is kept. Frames awaiting an ack on the old
1392
+ * socket are rejected with `closed`. `chat.user` is the new identity
1393
+ * once this resolves. If `token()` fails the client keeps retrying in
1394
+ * the background like any reconnect (and this rejects); a `ChatError`
1395
+ * from `token()` stops it at `closed`, as on connect.
1396
+ *
1397
+ * **Logging in or out is this too.** When the new token names a
1398
+ * different user, every room drops what it held, reloads recent
1399
+ * history for the new user, and emits `reset` -- the rows carried the
1400
+ * old user's `myReactions`. A frame the old user started and that is
1401
+ * still waiting (a send pressed while reconnecting, a resend after a
1402
+ * drop) is rejected with `closed` instead of going out under the new
1403
+ * name, so send as the new user after this resolves.
1385
1404
  *
1386
1405
  * On a client that is not connected (never connected, or `close()`d) it
1387
1406
  * is `connect()`.
@@ -1493,6 +1512,7 @@ var ChatClient = class extends Emitter {
1493
1512
  sendFrame(type, data, timeoutMs = 15e3, options = {}) {
1494
1513
  const deadline = Date.now() + timeoutMs;
1495
1514
  const wait = options.wait ?? true;
1515
+ const owner = options.owner ?? this.user?.id;
1496
1516
  const run = async (resends) => {
1497
1517
  if (this.socket === void 0 || this.state !== "open") {
1498
1518
  if (!wait || this.stopped || this.state === "closed") {
@@ -1505,6 +1525,9 @@ var ChatClient = class extends Emitter {
1505
1525
  }
1506
1526
  await this.untilOpen(type, deadline);
1507
1527
  }
1528
+ if (owner !== void 0 && this.user?.id !== owner) {
1529
+ throw new ChatError("closed", `cannot send ${type}: the user changed while it was waiting`);
1530
+ }
1508
1531
  try {
1509
1532
  return await this.sendOnSocket(type, data, Math.max(0, deadline - Date.now()));
1510
1533
  } catch (err) {
@@ -1646,6 +1669,7 @@ var ChatClient = class extends Emitter {
1646
1669
  });
1647
1670
  }
1648
1671
  onHello(hello) {
1672
+ const userChanged = this.user !== void 0 && this.user.id !== hello.user.id;
1649
1673
  this.hello = hello;
1650
1674
  this.user = hello.user;
1651
1675
  this.connectionId = hello.connectionId;
@@ -1656,7 +1680,7 @@ var ChatClient = class extends Emitter {
1656
1680
  this.setState("open");
1657
1681
  this.settleOpenWaiters();
1658
1682
  for (const room of this.handles.values()) {
1659
- void room.resume(reconnected).catch((err) => {
1683
+ void room.resume(reconnected, userChanged).catch((err) => {
1660
1684
  room.failed(err);
1661
1685
  });
1662
1686
  }
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가 낸다: 연결이 없거나 닫혔다. */
@@ -274,8 +280,10 @@ type RoomEvents = {
274
280
  */
275
281
  error: Error;
276
282
  /**
277
- * The timeline was thrown away and rebuilt, because the server said
278
- * this client's cursor was older than the room's retention.
283
+ * The timeline was thrown away and rebuilt: the server said this
284
+ * client's cursor was older than the room's retention, or the client
285
+ * reconnected as **a different user** (`myReactions` on the rows it held
286
+ * was the previous user's).
279
287
  *
280
288
  * A consumer holding rendered messages has to drop them: the list is
281
289
  * new, and quietly appending to the old one leaves a gap that no fill
@@ -391,6 +399,8 @@ declare class Room extends Emitter<RoomEvents> {
391
399
  * silently, which is worse than the failure that started it.
392
400
  */
393
401
  private wanted;
402
+ /** 신원이 바뀌어 버린 목록을 다음 구독이 다시 채우고 `reset`으로 알려야 한다. */
403
+ private rebuildPending;
394
404
  private subscribing;
395
405
  /** Self-repair: the armed retry, and how many have run since the last success. */
396
406
  private repairTimer;
@@ -838,13 +848,21 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
838
848
  * does that too, but passes through `closed` (a consumer's "you are
839
849
  * offline" screen) and tears down the page listeners.
840
850
  *
841
- * States: `open` → `reconnecting` → `open`, never `closed`. Rooms
842
- * resubscribe from what they hold and catch up the gap, as after any
843
- * drop; `messages` is kept. Frames awaiting an ack on the old socket are
844
- * rejected with `closed`. `chat.user` is the new identity once this
845
- * resolves. If `token()` fails the client keeps retrying in the
846
- * background like any reconnect (and this rejects); a `ChatError` from
847
- * `token()` stops it at `closed`, as on connect.
851
+ * States: `open` → `reconnecting` → `open`, never `closed`. For the same
852
+ * user, rooms resubscribe from what they hold and catch up the gap, as
853
+ * after any drop; `messages` is kept. Frames awaiting an ack on the old
854
+ * socket are rejected with `closed`. `chat.user` is the new identity
855
+ * once this resolves. If `token()` fails the client keeps retrying in
856
+ * the background like any reconnect (and this rejects); a `ChatError`
857
+ * from `token()` stops it at `closed`, as on connect.
858
+ *
859
+ * **Logging in or out is this too.** When the new token names a
860
+ * different user, every room drops what it held, reloads recent
861
+ * history for the new user, and emits `reset` -- the rows carried the
862
+ * old user's `myReactions`. A frame the old user started and that is
863
+ * still waiting (a send pressed while reconnecting, a resend after a
864
+ * drop) is rejected with `closed` instead of going out under the new
865
+ * name, so send as the new user after this resolves.
848
866
  *
849
867
  * On a client that is not connected (never connected, or `close()`d) it
850
868
  * is `connect()`.
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가 낸다: 연결이 없거나 닫혔다. */
@@ -274,8 +280,10 @@ type RoomEvents = {
274
280
  */
275
281
  error: Error;
276
282
  /**
277
- * The timeline was thrown away and rebuilt, because the server said
278
- * this client's cursor was older than the room's retention.
283
+ * The timeline was thrown away and rebuilt: the server said this
284
+ * client's cursor was older than the room's retention, or the client
285
+ * reconnected as **a different user** (`myReactions` on the rows it held
286
+ * was the previous user's).
279
287
  *
280
288
  * A consumer holding rendered messages has to drop them: the list is
281
289
  * new, and quietly appending to the old one leaves a gap that no fill
@@ -391,6 +399,8 @@ declare class Room extends Emitter<RoomEvents> {
391
399
  * silently, which is worse than the failure that started it.
392
400
  */
393
401
  private wanted;
402
+ /** 신원이 바뀌어 버린 목록을 다음 구독이 다시 채우고 `reset`으로 알려야 한다. */
403
+ private rebuildPending;
394
404
  private subscribing;
395
405
  /** Self-repair: the armed retry, and how many have run since the last success. */
396
406
  private repairTimer;
@@ -838,13 +848,21 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
838
848
  * does that too, but passes through `closed` (a consumer's "you are
839
849
  * offline" screen) and tears down the page listeners.
840
850
  *
841
- * States: `open` → `reconnecting` → `open`, never `closed`. Rooms
842
- * resubscribe from what they hold and catch up the gap, as after any
843
- * drop; `messages` is kept. Frames awaiting an ack on the old socket are
844
- * rejected with `closed`. `chat.user` is the new identity once this
845
- * resolves. If `token()` fails the client keeps retrying in the
846
- * background like any reconnect (and this rejects); a `ChatError` from
847
- * `token()` stops it at `closed`, as on connect.
851
+ * States: `open` → `reconnecting` → `open`, never `closed`. For the same
852
+ * user, rooms resubscribe from what they hold and catch up the gap, as
853
+ * after any drop; `messages` is kept. Frames awaiting an ack on the old
854
+ * socket are rejected with `closed`. `chat.user` is the new identity
855
+ * once this resolves. If `token()` fails the client keeps retrying in
856
+ * the background like any reconnect (and this rejects); a `ChatError`
857
+ * from `token()` stops it at `closed`, as on connect.
858
+ *
859
+ * **Logging in or out is this too.** When the new token names a
860
+ * different user, every room drops what it held, reloads recent
861
+ * history for the new user, and emits `reset` -- the rows carried the
862
+ * old user's `myReactions`. A frame the old user started and that is
863
+ * still waiting (a send pressed while reconnecting, a resend after a
864
+ * drop) is rejected with `closed` instead of going out under the new
865
+ * name, so send as the new user after this resolves.
848
866
  *
849
867
  * On a client that is not connected (never connected, or `close()`d) it
850
868
  * is `connect()`.
package/dist/index.js CHANGED
@@ -590,6 +590,8 @@ var Room = class extends Emitter {
590
590
  * silently, which is worse than the failure that started it.
591
591
  */
592
592
  wanted = false;
593
+ /** 신원이 바뀌어 버린 목록을 다음 구독이 다시 채우고 `reset`으로 알려야 한다. */
594
+ rebuildPending = false;
593
595
  subscribing;
594
596
  /** Self-repair: the armed retry, and how many have run since the last success. */
595
597
  repairTimer;
@@ -700,9 +702,10 @@ var Room = class extends Emitter {
700
702
  this.lastSeq = ack.lastSeq;
701
703
  if (typeof ack.minSeq === "number") this.timeline.setFloor(ack.minSeq);
702
704
  if (ack.presence !== void 0) this.presence = ack.presence;
703
- if (attempt.wasReset) {
705
+ if (attempt.wasReset || this.rebuildPending) {
704
706
  await this.loadRecent(current);
705
707
  if (!current()) return;
708
+ this.rebuildPending = false;
706
709
  this.subscribed = true;
707
710
  this.emit("reset", this.timeline.messages);
708
711
  return;
@@ -775,13 +778,14 @@ var Room = class extends Emitter {
775
778
  */
776
779
  async toggleReaction(messageId, emoji, mine) {
777
780
  const press = this.timeline.pressReaction(messageId, emoji, mine);
781
+ const owner = this.chat.user?.id;
778
782
  try {
779
783
  await this.chat.sendFrame("react", {
780
784
  roomId: await this.resolveId("reacting"),
781
785
  messageId,
782
786
  emoji,
783
787
  op: mine ? "add" : "remove"
784
- }, void 0, { resendOnDrop: true });
788
+ }, void 0, { resendOnDrop: true, owner });
785
789
  } catch (err) {
786
790
  if (press !== void 0) this.timeline.settleReaction(press, false);
787
791
  throw err;
@@ -797,9 +801,10 @@ var Room = class extends Emitter {
797
801
  * way to know what happened. It is returned rather than swallowed.
798
802
  */
799
803
  async markRead(seq, options = {}) {
804
+ const owner = this.chat.user?.id;
800
805
  const data = { roomId: await this.resolveId("marking read"), seq };
801
806
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
802
- return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true });
807
+ return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true, owner });
803
808
  }
804
809
  /**
805
810
  * Lists read cursors in this room, one page at a time.
@@ -895,7 +900,11 @@ var Room = class extends Emitter {
895
900
  * transient 500 takes a room out of the live feed for the life of the
896
901
  * page.
897
902
  */
898
- async resume(restart = true) {
903
+ async resume(restart = true, userChanged = false) {
904
+ if (userChanged) {
905
+ this.timeline.discard();
906
+ if (this.wanted) this.rebuildPending = true;
907
+ }
899
908
  if (!this.wanted) return;
900
909
  if (!restart) return this.subscribe();
901
910
  this.generation++;
@@ -948,6 +957,7 @@ var Room = class extends Emitter {
948
957
  if (this.id === void 0) return;
949
958
  this.wanted = false;
950
959
  this.subscribed = false;
960
+ this.rebuildPending = false;
951
961
  this.generation++;
952
962
  this.subscribing = void 0;
953
963
  await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
@@ -982,6 +992,7 @@ var Room = class extends Emitter {
982
992
  }
983
993
  /** Publishes and resolves when the server acks. */
984
994
  async send(input, options = {}) {
995
+ const owner = this.chat.user?.id;
985
996
  const roomId = await this.resolveId("sending");
986
997
  const body = {};
987
998
  if (input.text !== void 0) body["text"] = input.text;
@@ -995,7 +1006,7 @@ var Room = class extends Emitter {
995
1006
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
996
1007
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
997
1008
  if (input.meta !== void 0) frame["meta"] = input.meta;
998
- return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true });
1009
+ return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true, owner });
999
1010
  }
1000
1011
  /** @internal Routes a frame the client decided belongs to this room. */
1001
1012
  handle(type, data) {
@@ -1305,13 +1316,21 @@ var ChatClient = class extends Emitter {
1305
1316
  * does that too, but passes through `closed` (a consumer's "you are
1306
1317
  * offline" screen) and tears down the page listeners.
1307
1318
  *
1308
- * States: `open` → `reconnecting` → `open`, never `closed`. Rooms
1309
- * resubscribe from what they hold and catch up the gap, as after any
1310
- * drop; `messages` is kept. Frames awaiting an ack on the old socket are
1311
- * rejected with `closed`. `chat.user` is the new identity once this
1312
- * resolves. If `token()` fails the client keeps retrying in the
1313
- * background like any reconnect (and this rejects); a `ChatError` from
1314
- * `token()` stops it at `closed`, as on connect.
1319
+ * States: `open` → `reconnecting` → `open`, never `closed`. For the same
1320
+ * user, rooms resubscribe from what they hold and catch up the gap, as
1321
+ * after any drop; `messages` is kept. Frames awaiting an ack on the old
1322
+ * socket are rejected with `closed`. `chat.user` is the new identity
1323
+ * once this resolves. If `token()` fails the client keeps retrying in
1324
+ * the background like any reconnect (and this rejects); a `ChatError`
1325
+ * from `token()` stops it at `closed`, as on connect.
1326
+ *
1327
+ * **Logging in or out is this too.** When the new token names a
1328
+ * different user, every room drops what it held, reloads recent
1329
+ * history for the new user, and emits `reset` -- the rows carried the
1330
+ * old user's `myReactions`. A frame the old user started and that is
1331
+ * still waiting (a send pressed while reconnecting, a resend after a
1332
+ * drop) is rejected with `closed` instead of going out under the new
1333
+ * name, so send as the new user after this resolves.
1315
1334
  *
1316
1335
  * On a client that is not connected (never connected, or `close()`d) it
1317
1336
  * is `connect()`.
@@ -1423,6 +1442,7 @@ var ChatClient = class extends Emitter {
1423
1442
  sendFrame(type, data, timeoutMs = 15e3, options = {}) {
1424
1443
  const deadline = Date.now() + timeoutMs;
1425
1444
  const wait = options.wait ?? true;
1445
+ const owner = options.owner ?? this.user?.id;
1426
1446
  const run = async (resends) => {
1427
1447
  if (this.socket === void 0 || this.state !== "open") {
1428
1448
  if (!wait || this.stopped || this.state === "closed") {
@@ -1435,6 +1455,9 @@ var ChatClient = class extends Emitter {
1435
1455
  }
1436
1456
  await this.untilOpen(type, deadline);
1437
1457
  }
1458
+ if (owner !== void 0 && this.user?.id !== owner) {
1459
+ throw new ChatError("closed", `cannot send ${type}: the user changed while it was waiting`);
1460
+ }
1438
1461
  try {
1439
1462
  return await this.sendOnSocket(type, data, Math.max(0, deadline - Date.now()));
1440
1463
  } catch (err) {
@@ -1576,6 +1599,7 @@ var ChatClient = class extends Emitter {
1576
1599
  });
1577
1600
  }
1578
1601
  onHello(hello) {
1602
+ const userChanged = this.user !== void 0 && this.user.id !== hello.user.id;
1579
1603
  this.hello = hello;
1580
1604
  this.user = hello.user;
1581
1605
  this.connectionId = hello.connectionId;
@@ -1586,7 +1610,7 @@ var ChatClient = class extends Emitter {
1586
1610
  this.setState("open");
1587
1611
  this.settleOpenWaiters();
1588
1612
  for (const room of this.handles.values()) {
1589
- void room.resume(reconnected).catch((err) => {
1613
+ void room.resume(reconnected, userChanged).catch((err) => {
1590
1614
  room.failed(err);
1591
1615
  });
1592
1616
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.5.1",
3
+ "version": "0.7.0",
4
4
  "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
5
5
  "license": "MIT",
6
6
  "type": "module",