@kispi/chat 0.3.1 → 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 CHANGED
@@ -70,24 +70,25 @@ 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. Never touches the count |
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
- | `typing()` | Typing indicator. Does not throw |
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 `''` |
91
+ | `typing({threadId?})` | Typing indicator. Does not throw. Pass `threadId` while writing a thread reply |
91
92
  | `join()` / `leave()` | Membership |
92
93
  | `presenceList()` | Who is in this room right now |
93
94
 
@@ -97,10 +98,10 @@ Event names are **exactly the wire names**, and the payloads are in the type dec
97
98
  |---|---|
98
99
  | `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
99
100
  | `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
100
- | `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 |
101
102
  | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
102
103
  | `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
103
- | `typing` | `{userId}` |
104
+ | `typing` | `{userId, threadId?}` -- `threadId` is the thread **root** id, absent for the main timeline |
104
105
  | `read` | `{userId, seq, threadId?}` |
105
106
  | `member.joined` / `member.left` | `{userId, role?}` |
106
107
  | `room.updated` | The room object (`unknown` — the server's own representation) |
@@ -139,8 +140,27 @@ room.on('messages', m => (messages.value = m))
139
140
  - **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
140
141
  doesn't touch the list, so merging and deduplicating fall to you.
141
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
+ ```
142
155
  - **The connection comes back on its own.** It reconnects with exponential backoff, so don't
143
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.
144
164
  - **The SDK handles token expiry.** When REST gets a 401 it calls `token()` again and retries
145
165
  once. There's no need to reconnect periodically.
146
166
  - **Throwing a `ChatError` from `token()` stops the client.** That is how you say a failure,
@@ -148,6 +168,33 @@ room.on('messages', m => (messages.value = m))
148
168
  - **After a nickname or avatar change, `reconnect()`.** The server reads those values from the
149
169
  token claims once, when the socket authenticates.
150
170
 
171
+ ### `text` is untrusted plain text
172
+
173
+ Message `text`, and user-supplied display names/nicknames (`name`), are **plain text
174
+ the engine does not HTML-escape or sanitize.** This is by design — escaping depends on
175
+ the output context you render into (an HTML text node, an attribute, some other
176
+ format), which the engine cannot decide on your behalf. The engine only **validates**
177
+ (size, shape).
178
+
179
+ So consumers must render it as text — `textContent`, or your framework's text binding
180
+ (React's `{text}`, Svelte's `{text}`, Vue's `{{ text }}`). **Never pass it straight into
181
+ `innerHTML` or `v-html`.** If you add linkification or markup, don't build an HTML
182
+ string with a regex replace — build DOM from text nodes instead.
183
+
184
+ ```ts
185
+ // Don't — builds an HTML string with a regex
186
+ el.innerHTML = text.replace(urlRegex, '<a href="$1">$1</a>')
187
+
188
+ // Do — builds DOM from text nodes
189
+ for (const part of splitByUrl(text)) {
190
+ el.appendChild(part.isUrl ? makeAnchor(part.text) : document.createTextNode(part.text))
191
+ }
192
+ ```
193
+
194
+ Bad-word filtering and similar moderation is not escaping — it's a **tenant policy**.
195
+ The engine only opens the mechanism (the `before_publish` hook); the consumer decides
196
+ (see the `before_publish` section in `docs/protocol.md`).
197
+
151
198
  ### Using it in the browser
152
199
 
153
200
  You **must add the page's origin** to the `pk_`'s allowed origins. That's the only thing —
@@ -241,12 +288,17 @@ spaces don't overlap.
241
288
 
242
289
  | Group | Methods |
243
290
  |---|---|
244
- | `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` |
245
292
  | `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
246
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?})` |
247
294
  | `events` | `list({after?, limit?})` — catches up on missed webhook events |
248
295
  | `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
249
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
+
250
302
  `rooms.ensure` is get-or-create — it returns the room as-is if it exists, so it's fine to call
251
303
  on every page load.
252
304
 
package/README.md CHANGED
@@ -70,24 +70,25 @@ 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
- | `typing()` | 입력 중. 던지지 않는다 |
90
+ | `reads({userId?, cursor?, limit?})` | 읽음 커서 목록. `{reads: [{userId?, seq, threadId?, withdrawn?}], cursor}`. **`userId`로 한 사람만** — 자기 스레드별 커서를 되찾을 때 `reads({userId: chat.user.id})`. `cursor`가 `''`이면 끝 |
91
+ | `typing({threadId?})` | 입력 중. 던지지 않는다. 스레드 답글을 쓰는 중이면 `threadId` |
91
92
  | `join()` / `leave()` | 멤버십 |
92
93
  | `presenceList()` | 지금 이 방에 있는 사람 |
93
94
 
@@ -97,10 +98,10 @@ off()
97
98
  |---|---|
98
99
  | `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있다 |
99
100
  | `message.deleted` | `{id, seq}`. `seq`는 그 메시지가 **발행될 때** 받은 값이다 |
100
- | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
101
+ | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. SDK가 `messages` 안의 그 행의 `reactions` 개수를(내 것이면 `myReactions`도) 이미 고쳐 두었다. `history()`로 따로 읽은 행처럼 **목록 밖의 행은 소비자가 고친다** |
101
102
  | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
102
103
  | `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
103
- | `typing` | `{userId}` |
104
+ | `typing` | `{userId, threadId?}` — `threadId`는 스레드 **루트** id, 본 타임라인이면 없다 |
104
105
  | `read` | `{userId, seq, threadId?}` |
105
106
  | `member.joined` / `member.left` | `{userId, role?}` |
106
107
  | `room.updated` | 방 객체(`unknown` — 서버 표현 그대로다) |
@@ -137,13 +138,56 @@ room.on('messages', m => (messages.value = m))
137
138
  - **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는 직접
138
139
  읽기이므로 합치고 중복을 거르는 일이 소비자 몫이 된다.
139
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
+ ```
140
152
  - **연결은 알아서 돌아온다.** 끊기면 지수 백오프로 다시 붙으니 재시도 루프를 짜지 않는다.
153
+ - **재접속 중에 보낸 것은 기다렸다가 나간다.** `send`·`react`·`unreact`·`markRead`는 상태가
154
+ `connecting`/`reconnecting`이면 백오프를 건너뛰고 붙기를 기다려 보낸다. ack 전에 소켓이
155
+ 끊기면 **같은 프레임을 한 번 더** 보낸다 — 서버가 `clientMessageId`로 중복을 거르고 리액션·읽음은
156
+ 멱등이라 두 번 반영되지 않는다. 대기와 ack를 합쳐 15초가 넘으면 `timeout`이다.
157
+ `closed`는 이제 **멈춘 클라이언트**(`close()`, 인증 거절, 한 번도 `connect()`하지 않음)에서만
158
+ 온다. `typing()`은 기다리지 않고 버린다.
141
159
  - **토큰 만료는 SDK가 처리한다.** REST가 401을 받으면 `token()`을 다시 불러 한 번
142
160
  재시도한다. 주기적으로 재접속할 필요가 없다.
143
161
  - **`token()`이 `ChatError`를 던지면 멈춘다.** 밴처럼 다시 해도 소용없는 실패를 그렇게 알린다.
144
162
  - **닉네임·아바타를 바꿨으면 `reconnect()`.** 서버는 그 값을 접속할 때 토큰 claim에서
145
163
  한 번 읽는다.
146
164
 
165
+ ### `text`는 신뢰할 수 없는 평문이다
166
+
167
+ 메시지 `text`와 유저가 넣는 표시 이름·닉네임(`name`)은 **엔진이 HTML 이스케이프하거나
168
+ 정제하지 않은 평문**이다. 의도적이다 — 이스케이프는 렌더링하는 출력 컨텍스트(HTML
169
+ 텍스트 노드인지, 속성인지, 다른 포맷인지)에 달려 있어 엔진이 대신 정할 수 없다.
170
+ 엔진은 크기·형식 같은 **검증**만 한다.
171
+
172
+ 그래서 소비자가 렌더할 때 텍스트로 다뤄야 한다 — `textContent`나 프레임워크의 텍스트
173
+ 바인딩(React의 `{text}`, Svelte의 `{text}`, Vue의 `{{ text }}`). **`innerHTML`이나
174
+ `v-html`에 그대로 꽂으면 안 된다.** 링크 자동 인식이나 마크업을 더하고 싶으면 문자열을
175
+ HTML로 만들어 정규식으로 치환하지 말고, 텍스트 노드를 만들어 DOM에 직접 붙인다.
176
+
177
+ ```ts
178
+ // 하면 안 된다 — 정규식으로 HTML 문자열을 만든다
179
+ el.innerHTML = text.replace(urlRegex, '<a href="$1">$1</a>')
180
+
181
+ // 이렇게 — 텍스트 노드로 DOM을 만든다
182
+ for (const part of splitByUrl(text)) {
183
+ el.appendChild(part.isUrl ? makeAnchor(part.text) : document.createTextNode(part.text))
184
+ }
185
+ ```
186
+
187
+ 욕설 같은 금칙어 처리는 이스케이프가 아니라 **테넌트 정책**이다 — 엔진은
188
+ `before_publish` 훅이라는 기전만 열어 주고, 판정은 소비자가 한다(`docs/protocol.md`의
189
+ `before_publish` 절).
190
+
147
191
  ### 브라우저에서 쓸 때
148
192
 
149
193
  `pk_`의 허용 오리진에 **페이지의 오리진을 넣어야 한다.** 이것 하나다 — 서버가 CORS 헤더를
@@ -232,7 +276,7 @@ app.post('/api/chat-token', (req, res) => {
232
276
 
233
277
  | 그룹 | 메서드 |
234
278
  |---|---|
235
- | `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` |
236
280
  | `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
237
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?})` |
238
282
  | `events` | `list({after?, limit?})` — 놓친 웹훅 이벤트를 따라잡는다 |
@@ -240,6 +284,10 @@ app.post('/api/chat-token', (req, res) => {
240
284
 
241
285
  `rooms.ensure`는 get-or-create다 — 있으면 그대로 돌려주므로 페이지를 열 때마다 불러도 된다.
242
286
 
287
+ `rooms.list`는 앱의 방을 최신순으로 준다. `type`이 없으면 공개 목록(`public`·`channel`)이고,
288
+ `type: ['private', 'dm']`처럼 주면 비공개 방과 DM도 나온다. `limit` 기본 50 최대 100, 빈 `cursor`가
289
+ 마지막 페이지이고, **커서는 `type`을 싣지 않으므로** 필터를 바꾸면 처음부터 받는다.
290
+
243
291
  `rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
244
292
  `capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
245
293
 
package/dist/index.cjs CHANGED
@@ -862,6 +862,32 @@ var Room = class extends Emitter {
862
862
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
863
863
  return await this.chat.sendFrame("read", data);
864
864
  }
865
+ /**
866
+ * Lists read cursors in this room, one page at a time.
867
+ *
868
+ * A row is one (user, scope) pair: the main timeline has no `threadId`,
869
+ * and each thread a user has read is its own row, keyed by the thread's
870
+ * root id. `withdrawn: true` rows carry no `userId`.
871
+ *
872
+ * **`userId` narrows the page to one user**, which is how a client gets
873
+ * its own per-thread positions back after a reload or on another device
874
+ * -- `markRead` writes them, and this reads them:
875
+ *
876
+ * ```ts
877
+ * const mine = await room.reads({ userId: chat.user!.id })
878
+ * ```
879
+ *
880
+ * An id that names no live user returns an empty page. Keep calling
881
+ * with the returned `cursor` while it is non-empty; the last page's
882
+ * cursor is `''`.
883
+ */
884
+ async reads(options = {}) {
885
+ return this.rest.get(`/v1/rooms/${await this.resolveId("reading read cursors")}/reads`, {
886
+ userId: options.userId,
887
+ cursor: options.cursor,
888
+ limit: options.limit
889
+ });
890
+ }
865
891
  /**
866
892
  * Says this user is typing.
867
893
  *
@@ -875,10 +901,19 @@ var Room = class extends Emitter {
875
901
  * filter it out, because a room view that shows every typist and one
876
902
  * that shows everyone else are both legitimate and only the consumer
877
903
  * knows which it is drawing.
904
+ *
905
+ * Pass `threadId` while composing a thread reply. The event carries the
906
+ * thread's **root** id -- a reply's id is normalized to its root, as
907
+ * `send` and `markRead` do -- so a thread panel shows its own typists
908
+ * and the main view can skip them. The server keeps one throttle slot
909
+ * per user per room, not per thread: switching between the main box
910
+ * and a thread is heard up to three seconds late.
878
911
  */
879
- typing() {
912
+ typing(options = {}) {
880
913
  try {
881
- void this.chat.sendFrame("typing", { roomId: this.requireId("typing") }).catch(() => {
914
+ const data = { roomId: this.requireId("typing") };
915
+ if (options.threadId !== void 0) data["threadId"] = options.threadId;
916
+ void this.chat.sendFrame("typing", data).catch(() => {
882
917
  });
883
918
  } catch {
884
919
  }
package/dist/index.d.cts CHANGED
@@ -306,9 +306,13 @@ type RoomEvents = {
306
306
  lastAt?: number;
307
307
  };
308
308
  presence: PresenceEvent;
309
- /** **보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 id를 건너뛴다. */
309
+ /**
310
+ * **보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 id를 건너뛴다.
311
+ * `threadId`는 그 스레드의 **루트** id이고, 본 타임라인에서 입력 중이면 없다.
312
+ */
310
313
  typing: {
311
314
  userId: string;
315
+ threadId?: string;
312
316
  };
313
317
  read: {
314
318
  userId: string;
@@ -503,6 +507,38 @@ declare class Room extends Emitter<RoomEvents> {
503
507
  seq: number;
504
508
  advanced: boolean;
505
509
  }>;
510
+ /**
511
+ * Lists read cursors in this room, one page at a time.
512
+ *
513
+ * A row is one (user, scope) pair: the main timeline has no `threadId`,
514
+ * and each thread a user has read is its own row, keyed by the thread's
515
+ * root id. `withdrawn: true` rows carry no `userId`.
516
+ *
517
+ * **`userId` narrows the page to one user**, which is how a client gets
518
+ * its own per-thread positions back after a reload or on another device
519
+ * -- `markRead` writes them, and this reads them:
520
+ *
521
+ * ```ts
522
+ * const mine = await room.reads({ userId: chat.user!.id })
523
+ * ```
524
+ *
525
+ * An id that names no live user returns an empty page. Keep calling
526
+ * with the returned `cursor` while it is non-empty; the last page's
527
+ * cursor is `''`.
528
+ */
529
+ reads(options?: {
530
+ userId?: string;
531
+ cursor?: string;
532
+ limit?: number;
533
+ }): Promise<{
534
+ reads: {
535
+ userId?: string;
536
+ seq: number;
537
+ threadId?: string;
538
+ withdrawn?: boolean;
539
+ }[];
540
+ cursor: string;
541
+ }>;
506
542
  /**
507
543
  * Says this user is typing.
508
544
  *
@@ -516,8 +552,17 @@ declare class Room extends Emitter<RoomEvents> {
516
552
  * filter it out, because a room view that shows every typist and one
517
553
  * that shows everyone else are both legitimate and only the consumer
518
554
  * knows which it is drawing.
555
+ *
556
+ * Pass `threadId` while composing a thread reply. The event carries the
557
+ * thread's **root** id -- a reply's id is normalized to its root, as
558
+ * `send` and `markRead` do -- so a thread panel shows its own typists
559
+ * and the main view can skip them. The server keeps one throttle slot
560
+ * per user per room, not per thread: switching between the main box
561
+ * and a thread is heard up to three seconds late.
519
562
  */
520
- typing(): void;
563
+ typing(options?: {
564
+ threadId?: string;
565
+ }): void;
521
566
  /** Joins a public or channel room. Idempotent. */
522
567
  join(): Promise<void>;
523
568
  /** Leaves. Idempotent from the caller's side. */
package/dist/index.d.ts CHANGED
@@ -306,9 +306,13 @@ type RoomEvents = {
306
306
  lastAt?: number;
307
307
  };
308
308
  presence: PresenceEvent;
309
- /** **보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 id를 건너뛴다. */
309
+ /**
310
+ * **보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 id를 건너뛴다.
311
+ * `threadId`는 그 스레드의 **루트** id이고, 본 타임라인에서 입력 중이면 없다.
312
+ */
310
313
  typing: {
311
314
  userId: string;
315
+ threadId?: string;
312
316
  };
313
317
  read: {
314
318
  userId: string;
@@ -503,6 +507,38 @@ declare class Room extends Emitter<RoomEvents> {
503
507
  seq: number;
504
508
  advanced: boolean;
505
509
  }>;
510
+ /**
511
+ * Lists read cursors in this room, one page at a time.
512
+ *
513
+ * A row is one (user, scope) pair: the main timeline has no `threadId`,
514
+ * and each thread a user has read is its own row, keyed by the thread's
515
+ * root id. `withdrawn: true` rows carry no `userId`.
516
+ *
517
+ * **`userId` narrows the page to one user**, which is how a client gets
518
+ * its own per-thread positions back after a reload or on another device
519
+ * -- `markRead` writes them, and this reads them:
520
+ *
521
+ * ```ts
522
+ * const mine = await room.reads({ userId: chat.user!.id })
523
+ * ```
524
+ *
525
+ * An id that names no live user returns an empty page. Keep calling
526
+ * with the returned `cursor` while it is non-empty; the last page's
527
+ * cursor is `''`.
528
+ */
529
+ reads(options?: {
530
+ userId?: string;
531
+ cursor?: string;
532
+ limit?: number;
533
+ }): Promise<{
534
+ reads: {
535
+ userId?: string;
536
+ seq: number;
537
+ threadId?: string;
538
+ withdrawn?: boolean;
539
+ }[];
540
+ cursor: string;
541
+ }>;
506
542
  /**
507
543
  * Says this user is typing.
508
544
  *
@@ -516,8 +552,17 @@ declare class Room extends Emitter<RoomEvents> {
516
552
  * filter it out, because a room view that shows every typist and one
517
553
  * that shows everyone else are both legitimate and only the consumer
518
554
  * knows which it is drawing.
555
+ *
556
+ * Pass `threadId` while composing a thread reply. The event carries the
557
+ * thread's **root** id -- a reply's id is normalized to its root, as
558
+ * `send` and `markRead` do -- so a thread panel shows its own typists
559
+ * and the main view can skip them. The server keeps one throttle slot
560
+ * per user per room, not per thread: switching between the main box
561
+ * and a thread is heard up to three seconds late.
519
562
  */
520
- typing(): void;
563
+ typing(options?: {
564
+ threadId?: string;
565
+ }): void;
521
566
  /** Joins a public or channel room. Idempotent. */
522
567
  join(): Promise<void>;
523
568
  /** Leaves. Idempotent from the caller's side. */
package/dist/index.js CHANGED
@@ -792,6 +792,32 @@ var Room = class extends Emitter {
792
792
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
793
793
  return await this.chat.sendFrame("read", data);
794
794
  }
795
+ /**
796
+ * Lists read cursors in this room, one page at a time.
797
+ *
798
+ * A row is one (user, scope) pair: the main timeline has no `threadId`,
799
+ * and each thread a user has read is its own row, keyed by the thread's
800
+ * root id. `withdrawn: true` rows carry no `userId`.
801
+ *
802
+ * **`userId` narrows the page to one user**, which is how a client gets
803
+ * its own per-thread positions back after a reload or on another device
804
+ * -- `markRead` writes them, and this reads them:
805
+ *
806
+ * ```ts
807
+ * const mine = await room.reads({ userId: chat.user!.id })
808
+ * ```
809
+ *
810
+ * An id that names no live user returns an empty page. Keep calling
811
+ * with the returned `cursor` while it is non-empty; the last page's
812
+ * cursor is `''`.
813
+ */
814
+ async reads(options = {}) {
815
+ return this.rest.get(`/v1/rooms/${await this.resolveId("reading read cursors")}/reads`, {
816
+ userId: options.userId,
817
+ cursor: options.cursor,
818
+ limit: options.limit
819
+ });
820
+ }
795
821
  /**
796
822
  * Says this user is typing.
797
823
  *
@@ -805,10 +831,19 @@ var Room = class extends Emitter {
805
831
  * filter it out, because a room view that shows every typist and one
806
832
  * that shows everyone else are both legitimate and only the consumer
807
833
  * knows which it is drawing.
834
+ *
835
+ * Pass `threadId` while composing a thread reply. The event carries the
836
+ * thread's **root** id -- a reply's id is normalized to its root, as
837
+ * `send` and `markRead` do -- so a thread panel shows its own typists
838
+ * and the main view can skip them. The server keeps one throttle slot
839
+ * per user per room, not per thread: switching between the main box
840
+ * and a thread is heard up to three seconds late.
808
841
  */
809
- typing() {
842
+ typing(options = {}) {
810
843
  try {
811
- void this.chat.sendFrame("typing", { roomId: this.requireId("typing") }).catch(() => {
844
+ const data = { roomId: this.requireId("typing") };
845
+ if (options.threadId !== void 0) data["threadId"] = options.threadId;
846
+ void this.chat.sendFrame("typing", data).catch(() => {
812
847
  });
813
848
  } catch {
814
849
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
5
5
  "license": "MIT",
6
6
  "type": "module",