@kispi/chat 0.4.0 → 0.5.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 +30 -6
- package/README.md +27 -6
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -70,21 +70,21 @@ off()
|
|
|
70
70
|
|
|
71
71
|
| Property | |
|
|
72
72
|
|---|---|
|
|
73
|
-
| `messages` | Ascending by seq. **The SDK handles ordering and gap filling.** A new array on every change |
|
|
73
|
+
| `messages` | Ascending by seq. **The SDK handles ordering and gap filling.** A new array on every change. **Thread replies are included** (rows with a `threadId`) — to draw the main timeline only, keep the rows without one |
|
|
74
74
|
| `id` / `key` | Room identifiers. If opened by key, `id` is absent until you subscribe |
|
|
75
75
|
| `lastSeq` | The room's last seq as reported by the server |
|
|
76
|
-
| `presence` | `{count, users?, capped?}` |
|
|
76
|
+
| `presence` | `{count, users?, capped?}` — who is in this room now. **The SDK folds** the subscribe ack and the increments of `presence` events into it. `users` is there **only for rooms of 100 or fewer**; larger, or unknown, it is absent — use `presenceList()` then |
|
|
77
77
|
| `hasOlder` | Whether `loadOlder()` has more past to read. Lets you decide whether to draw "load earlier" before the first `loadOlder()`. The same test as `loadOlder()`'s `hasMore`; `false` while the list is empty. Re-read it on `messages` |
|
|
78
78
|
|
|
79
79
|
| Method | |
|
|
80
80
|
|---|---|
|
|
81
81
|
| `subscribe()` | Turns on the live feed and reads the latest 100. Does nothing if already caught up. **Fine to call before connecting** — it waits until connected (rejects with `closed` on `close()`) |
|
|
82
82
|
| `unsubscribe()` | Stops viewing this room. It is not resubscribed on reconnect |
|
|
83
|
-
| `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | Publish. Acked with `{messageId, seq}`. If a subscription is in progress, it waits for it |
|
|
83
|
+
| `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | Publish. Acked with `{messageId, seq}`. If a subscription is in progress, it waits for it. **While reconnecting it waits for the connection, then sends** (below) |
|
|
84
84
|
| `loadOlder({limit?})` | Reads the page before the oldest message (default 100) and **prepends it to `messages`.** Returns `{messages, hasMore}`. Use it when scrolling up. If the list is empty (before subscribing), it reads nothing |
|
|
85
85
|
| `history({before?, after?, limit?, view?})` | Reads the past directly. **Independent of `messages`.** `view` is `'main'`, `'all'`, or `{thread: id}` |
|
|
86
86
|
| `reload()` | Re-reads the latest page |
|
|
87
|
-
| `react(messageId, emoji)` / `unreact(...)` | Reactions. Idempotent. Updates that row's `myReactions` **before the frame goes out**, and rolls it back if the server refuses.
|
|
87
|
+
| `react(messageId, emoji)` / `unreact(...)` | Reactions. Idempotent. Updates that row's `myReactions` **before the frame goes out**, and rolls it back if the server refuses. The count is not moved optimistically; **it is set to the server's value when the `reaction.*` event arrives** (below) |
|
|
88
88
|
| `reactionsOf(messageId, {emoji?, cursor?, limit?})` | Who reacted. **Each row is a (user, emoji) pair**, so one person can appear on several rows. `limit` defaults to 50, max 100; the last page's `cursor` is an empty string |
|
|
89
89
|
| `markRead(seq, {threadId?})` | Read cursor |
|
|
90
90
|
| `reads({userId?, cursor?, limit?})` | Read cursors, paged. `{reads: [{userId?, seq, threadId?, withdrawn?}], cursor}`. **`userId` narrows to one person** -- `reads({userId: chat.user.id})` recovers your own per-thread cursors. Stop when `cursor` is `''` |
|
|
@@ -98,7 +98,7 @@ Event names are **exactly the wire names**, and the payloads are in the type dec
|
|
|
98
98
|
|---|---|
|
|
99
99
|
| `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
|
|
100
100
|
| `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
|
|
101
|
-
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
101
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. The SDK has already updated that row's `reactions` count in `messages` (and `myReactions` if it was yours). **Rows outside the list**, such as ones read with `history()`, are the consumer's to update |
|
|
102
102
|
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
103
103
|
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
|
|
104
104
|
| `typing` | `{userId, threadId?}` -- `threadId` is the thread **root** id, absent for the main timeline |
|
|
@@ -140,8 +140,27 @@ room.on('messages', m => (messages.value = m))
|
|
|
140
140
|
- **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
|
|
141
141
|
doesn't touch the list, so merging and deduplicating fall to you.
|
|
142
142
|
- **`typing` is also delivered to the sender.** If you render "X is typing", skip your own `userId`.
|
|
143
|
+
- **`typing` carries no name.** Look the name up in `room.presence.users` — whoever is
|
|
144
|
+
watching the room is there. Collecting names from message senders misses anyone who has not
|
|
145
|
+
spoken yet. If `users` is absent (a room over 100), fetch it once with `presenceList()`, and fall
|
|
146
|
+
back to a placeholder if the name is still missing.
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
room.on('typing', ({ userId }) => {
|
|
150
|
+
if (userId === chat.user?.id) return
|
|
151
|
+
const name = room.presence?.users?.find(u => u.id === userId)?.name
|
|
152
|
+
showTyping(userId, name ?? 'Someone') // clearing it after a few seconds is yours to do
|
|
153
|
+
})
|
|
154
|
+
```
|
|
143
155
|
- **The connection comes back on its own.** It reconnects with exponential backoff, so don't
|
|
144
156
|
write your own retry loop.
|
|
157
|
+
- **What you send while reconnecting waits, then goes out.** `send`, `react`, `unreact` and
|
|
158
|
+
`markRead` skip the backoff when the state is `connecting`/`reconnecting`, wait for the
|
|
159
|
+
connection, and send. If the socket drops before the ack, **the same frame is sent once more**
|
|
160
|
+
— the server dedups on `clientMessageId`, and reactions and reads are idempotent, so nothing
|
|
161
|
+
lands twice. Waiting plus the ack is capped at 15 seconds, then `timeout`. `closed` now comes
|
|
162
|
+
only from a **stopped client** (`close()`, an auth refusal, or never `connect()`ed).
|
|
163
|
+
`typing()` does not wait; it is dropped.
|
|
145
164
|
- **The SDK handles token expiry.** When REST gets a 401 it calls `token()` again and retries
|
|
146
165
|
once. There's no need to reconnect periodically.
|
|
147
166
|
- **Throwing a `ChatError` from `token()` stops the client.** That is how you say a failure,
|
|
@@ -269,12 +288,17 @@ spaces don't overlap.
|
|
|
269
288
|
|
|
270
289
|
| Group | Methods |
|
|
271
290
|
|---|---|
|
|
272
|
-
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
291
|
+
| `rooms` | `list({type?, cursor?, limit?})`, `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
273
292
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
274
293
|
| `users` | `list({cursor?, limit?})`, `update(userId, {name?, avatar?, meta?})`, `withdraw(userId, {purgeMessages?})`, `purgeMessages(userId)`, `ban(userId, {until, reason?})`, `unban(userId)`, `revokeTokens(userId)`, `disconnect(userId, {connectionId?, reason?})` |
|
|
275
294
|
| `events` | `list({after?, limit?})` — catches up on missed webhook events |
|
|
276
295
|
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
|
|
277
296
|
|
|
297
|
+
`rooms.list` returns the app's rooms, newest first. With no `type` it is the public listing
|
|
298
|
+
(`public` and `channel`); pass e.g. `type: ['private', 'dm']` for private rooms and DMs. `limit`
|
|
299
|
+
defaults to 50 (max 100), an empty `cursor` is the last page, and **the cursor does not carry
|
|
300
|
+
`type`** — start over when the filter changes.
|
|
301
|
+
|
|
278
302
|
`rooms.ensure` is get-or-create — it returns the room as-is if it exists, so it's fine to call
|
|
279
303
|
on every page load.
|
|
280
304
|
|
package/README.md
CHANGED
|
@@ -70,21 +70,21 @@ off()
|
|
|
70
70
|
|
|
71
71
|
| 프로퍼티 | |
|
|
72
72
|
|---|---|
|
|
73
|
-
| `messages` | seq 오름차순. **정렬과 구멍 메우기는 SDK가 한다.** 바뀔 때마다 새
|
|
73
|
+
| `messages` | seq 오름차순. **정렬과 구멍 메우기는 SDK가 한다.** 바뀔 때마다 새 배열이다. **스레드 답글도 섞여 있다**(`threadId`가 있는 행) — 본 타임라인만 그리려면 `threadId`가 없는 행만 고른다 |
|
|
74
74
|
| `id` / `key` | 방 식별자. 키로 열었으면 구독 전까지 `id`가 없다 |
|
|
75
75
|
| `lastSeq` | 서버가 알려 준 방의 마지막 seq |
|
|
76
|
-
| `presence` | `{count, users?, capped?}` |
|
|
76
|
+
| `presence` | `{count, users?, capped?}` — 지금 이 방에 누가 있나. 구독 ack와 `presence` 이벤트의 증분을 **SDK가 합쳐 둔 값**이다. `users`는 **100명 이하 방에서만** 있고, 그보다 크거나 모르면 없다 — 그때는 `presenceList()` |
|
|
77
77
|
| `hasOlder` | `loadOlder()`로 더 읽을 과거가 있는지. 첫 `loadOlder()` 전에 "이전 메시지" 버튼을 그릴지 정할 때 쓴다. `loadOlder()`의 `hasMore`와 같은 판정이고, 목록이 비었으면 `false`. `messages` 이벤트 때 다시 읽는다 |
|
|
78
78
|
|
|
79
79
|
| 메서드 | |
|
|
80
80
|
|---|---|
|
|
81
81
|
| `subscribe()` | 라이브 피드를 켜고 최근 100건을 읽는다. 이미 따라잡혔으면 아무것도 안 한다. **연결 전에 불러도 된다** — 붙을 때까지 기다린다(`close()`면 `closed`로 거절) |
|
|
82
82
|
| `unsubscribe()` | 이 방 보기를 그만둔다. 재접속해도 다시 구독하지 않는다 |
|
|
83
|
-
| `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | 발행. ack로 `{messageId, seq}`. 구독이 진행 중이면 그것을
|
|
83
|
+
| `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | 발행. ack로 `{messageId, seq}`. 구독이 진행 중이면 그것을 기다린다. **재접속 중이면 붙을 때까지 기다렸다가 보낸다**(아래) |
|
|
84
84
|
| `loadOlder({limit?})` | 가장 오래된 메시지 앞 페이지(기본 100)를 읽어 **`messages` 앞에 붙인다.** `{messages, hasMore}`. 스크롤을 올릴 때 쓴다. 목록이 비어 있으면(구독 전) 아무것도 읽지 않는다 |
|
|
85
85
|
| `history({before?, after?, limit?, view?})` | 과거를 직접 읽는다. **`messages`와 따로 논다.** `view`는 `'main'`, `'all'`, `{thread: id}` |
|
|
86
86
|
| `reload()` | 최근 페이지를 다시 읽는다 |
|
|
87
|
-
| `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등. **프레임보다 먼저** 그 행의 `myReactions`를 고치고, 서버가 거절하면 되돌린다. 개수는
|
|
87
|
+
| `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등. **프레임보다 먼저** 그 행의 `myReactions`를 고치고, 서버가 거절하면 되돌린다. 개수는 낙관적으로 올리지 않고 **`reaction.*` 이벤트가 올 때 서버 값으로 고친다**(아래) |
|
|
88
88
|
| `reactionsOf(messageId, {emoji?, cursor?, limit?})` | 누가 눌렀는지. **한 행은 (유저, 이모지) 쌍**이라 한 사람이 여러 줄일 수 있다. `limit` 기본 50 최대 100, 마지막 페이지의 `cursor`는 빈 문자열 |
|
|
89
89
|
| `markRead(seq, {threadId?})` | 읽음 커서 |
|
|
90
90
|
| `reads({userId?, cursor?, limit?})` | 읽음 커서 목록. `{reads: [{userId?, seq, threadId?, withdrawn?}], cursor}`. **`userId`로 한 사람만** — 자기 스레드별 커서를 되찾을 때 `reads({userId: chat.user.id})`. `cursor`가 `''`이면 끝 |
|
|
@@ -98,7 +98,7 @@ off()
|
|
|
98
98
|
|---|---|
|
|
99
99
|
| `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있다 |
|
|
100
100
|
| `message.deleted` | `{id, seq}`. `seq`는 그 메시지가 **발행될 때** 받은 값이다 |
|
|
101
|
-
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
101
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. SDK가 `messages` 안의 그 행의 `reactions` 개수를(내 것이면 `myReactions`도) 이미 고쳐 두었다. `history()`로 따로 읽은 행처럼 **목록 밖의 행은 소비자가 고친다** |
|
|
102
102
|
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
103
103
|
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
|
|
104
104
|
| `typing` | `{userId, threadId?}` — `threadId`는 스레드 **루트** id, 본 타임라인이면 없다 |
|
|
@@ -138,7 +138,24 @@ room.on('messages', m => (messages.value = m))
|
|
|
138
138
|
- **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는 직접
|
|
139
139
|
읽기이므로 합치고 중복을 거르는 일이 소비자 몫이 된다.
|
|
140
140
|
- **`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를 건너뛴다.
|
|
141
|
+
- **`typing`은 이름을 싣지 않는다.** 이름은 `room.presence.users`에서 찾는다 — 방을 보고 있는
|
|
142
|
+
사람이 거기 있다. 메시지 발신자에서 이름을 모으면 아직 말하지 않은 사람을 모른다.
|
|
143
|
+
`users`가 없으면(100명 넘는 방) `presenceList()`로 한 번 받아 오고, 그래도 없으면 대체 이름을 쓴다.
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
room.on('typing', ({ userId }) => {
|
|
147
|
+
if (userId === chat.user?.id) return
|
|
148
|
+
const name = room.presence?.users?.find(u => u.id === userId)?.name
|
|
149
|
+
showTyping(userId, name ?? '누군가') // 몇 초 뒤 지우는 것은 소비자 몫이다
|
|
150
|
+
})
|
|
151
|
+
```
|
|
141
152
|
- **연결은 알아서 돌아온다.** 끊기면 지수 백오프로 다시 붙으니 재시도 루프를 짜지 않는다.
|
|
153
|
+
- **재접속 중에 보낸 것은 기다렸다가 나간다.** `send`·`react`·`unreact`·`markRead`는 상태가
|
|
154
|
+
`connecting`/`reconnecting`이면 백오프를 건너뛰고 붙기를 기다려 보낸다. ack 전에 소켓이
|
|
155
|
+
끊기면 **같은 프레임을 한 번 더** 보낸다 — 서버가 `clientMessageId`로 중복을 거르고 리액션·읽음은
|
|
156
|
+
멱등이라 두 번 반영되지 않는다. 대기와 ack를 합쳐 15초가 넘으면 `timeout`이다.
|
|
157
|
+
`closed`는 이제 **멈춘 클라이언트**(`close()`, 인증 거절, 한 번도 `connect()`하지 않음)에서만
|
|
158
|
+
온다. `typing()`은 기다리지 않고 버린다.
|
|
142
159
|
- **토큰 만료는 SDK가 처리한다.** REST가 401을 받으면 `token()`을 다시 불러 한 번
|
|
143
160
|
재시도한다. 주기적으로 재접속할 필요가 없다.
|
|
144
161
|
- **`token()`이 `ChatError`를 던지면 멈춘다.** 밴처럼 다시 해도 소용없는 실패를 그렇게 알린다.
|
|
@@ -259,7 +276,7 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
259
276
|
|
|
260
277
|
| 그룹 | 메서드 |
|
|
261
278
|
|---|---|
|
|
262
|
-
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
279
|
+
| `rooms` | `list({type?, cursor?, limit?})`, `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
263
280
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
264
281
|
| `users` | `list({cursor?, limit?})`, `update(userId, {name?, avatar?, meta?})`, `withdraw(userId, {purgeMessages?})`, `purgeMessages(userId)`, `ban(userId, {until, reason?})`, `unban(userId)`, `revokeTokens(userId)`, `disconnect(userId, {connectionId?, reason?})` |
|
|
265
282
|
| `events` | `list({after?, limit?})` — 놓친 웹훅 이벤트를 따라잡는다 |
|
|
@@ -267,6 +284,10 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
267
284
|
|
|
268
285
|
`rooms.ensure`는 get-or-create다 — 있으면 그대로 돌려주므로 페이지를 열 때마다 불러도 된다.
|
|
269
286
|
|
|
287
|
+
`rooms.list`는 앱의 방을 최신순으로 준다. `type`이 없으면 공개 목록(`public`·`channel`)이고,
|
|
288
|
+
`type: ['private', 'dm']`처럼 주면 비공개 방과 DM도 나온다. `limit` 기본 50 최대 100, 빈 `cursor`가
|
|
289
|
+
마지막 페이지이고, **커서는 `type`을 싣지 않으므로** 필터를 바꾸면 처음부터 받는다.
|
|
290
|
+
|
|
270
291
|
`rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
|
|
271
292
|
`capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
|
|
272
293
|
|