@kispi/chat 0.3.0 → 0.4.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 +80 -225
- package/README.md +68 -214
- package/dist/index.cjs +37 -2
- package/dist/index.d.cts +47 -2
- package/dist/index.d.ts +47 -2
- package/dist/index.js +37 -2
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -11,7 +11,7 @@ npm install @kispi/chat
|
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
This document covers **the entire surface**. Anything not here is internal and
|
|
14
|
-
changes without notice.
|
|
14
|
+
changes without notice.
|
|
15
15
|
|
|
16
16
|
---
|
|
17
17
|
|
|
@@ -29,12 +29,6 @@ changes without notice. How to get started is here too.
|
|
|
29
29
|
Do not create `token` in the browser. Signing requires the `sk_`, and if the `sk_`
|
|
30
30
|
is in the browser, the whole app is open.
|
|
31
31
|
|
|
32
|
-
**You do not configure the address.** There is one engine, `wss://api.chat.gravex.app`,
|
|
33
|
-
and the SDK holds it as a constant (readable as `ChatEndpoint`). REST is the same
|
|
34
|
-
place with the scheme swapped. To separate development from production, **create a
|
|
35
|
-
separate app in the console**: different apps have different `pk_`/`sk_`, rooms and
|
|
36
|
-
users, which is the separation you actually want.
|
|
37
|
-
|
|
38
32
|
### `ChatClient`
|
|
39
33
|
|
|
40
34
|
| Property | |
|
|
@@ -50,7 +44,7 @@ users, which is the separation you actually want.
|
|
|
50
44
|
| `close()` | Disconnects. This one does not reconnect. Call `connect()` to come back |
|
|
51
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) |
|
|
52
46
|
| `room(roomId)` | Room handle. Same id, same object |
|
|
53
|
-
| `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`
|
|
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()` |
|
|
54
48
|
| `rooms.list({cursor?, limit?})` | Rooms I'm a member of + unread + last message |
|
|
55
49
|
| `rooms.discover({type?, cursor?, limit?})` | Browse public rooms |
|
|
56
50
|
| `rooms.members(roomId).list/add/remove` | Member management |
|
|
@@ -80,7 +74,7 @@ off()
|
|
|
80
74
|
| `id` / `key` | Room identifiers. If opened by key, `id` is absent until you subscribe |
|
|
81
75
|
| `lastSeq` | The room's last seq as reported by the server |
|
|
82
76
|
| `presence` | `{count, users?, capped?}` |
|
|
83
|
-
| `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
|
|
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` |
|
|
84
78
|
|
|
85
79
|
| Method | |
|
|
86
80
|
|---|---|
|
|
@@ -93,12 +87,12 @@ off()
|
|
|
93
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 |
|
|
94
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 |
|
|
95
89
|
| `markRead(seq, {threadId?})` | Read cursor |
|
|
96
|
-
| `
|
|
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 |
|
|
97
92
|
| `join()` / `leave()` | Membership |
|
|
98
93
|
| `presenceList()` | Who is in this room right now |
|
|
99
94
|
|
|
100
|
-
Event names are **exactly the wire names**, and the payloads are
|
|
101
|
-
shapes in `docs/protocol.md`.
|
|
95
|
+
Event names are **exactly the wire names**, and the payloads are in the type declarations.
|
|
102
96
|
|
|
103
97
|
| Event | Payload |
|
|
104
98
|
|---|---|
|
|
@@ -107,7 +101,7 @@ shapes in `docs/protocol.md`.
|
|
|
107
101
|
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
108
102
|
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
109
103
|
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
|
|
110
|
-
| `typing` | `{userId}` |
|
|
104
|
+
| `typing` | `{userId, threadId?}` -- `threadId` is the thread **root** id, absent for the main timeline |
|
|
111
105
|
| `read` | `{userId, seq, threadId?}` |
|
|
112
106
|
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
113
107
|
| `room.updated` | The room object (`unknown` — the server's own representation) |
|
|
@@ -119,18 +113,13 @@ The SDK emits three more that have no wire counterpart.
|
|
|
119
113
|
| Event | When |
|
|
120
114
|
|---|---|
|
|
121
115
|
| `messages` | Every time the list changes. **A new array each time; an emitted array is never touched again** |
|
|
122
|
-
| `error` | Reading history or filling a gap failed. **The room resubscribes itself
|
|
116
|
+
| `error` | Reading history or filling a gap failed. **The room resubscribes itself.** The retry button for a person is `subscribe()` |
|
|
123
117
|
| `reset` | The cursor was older than the retention period, so the list was discarded and refilled. **You must discard what you rendered** |
|
|
124
118
|
|
|
125
119
|
### Things to know
|
|
126
120
|
|
|
127
|
-
**`messages`
|
|
128
|
-
|
|
129
|
-
can put it straight into state that compares by reference. Rows follow the same rule: only a
|
|
130
|
-
row an event changed (edit, delete, reaction, thread) is a new object, and the others keep
|
|
131
|
-
their reference — **same reference means unchanged**, so row-level memoization is safe. The
|
|
132
|
-
converse is not promised: `reload()` and reconnect catch-up fetch rows from the server again,
|
|
133
|
-
so a different reference can carry the same content.
|
|
121
|
+
**`messages` is a new array every time, and only changed rows are new objects.** Put it
|
|
122
|
+
straight into state that compares by reference.
|
|
134
123
|
|
|
135
124
|
```ts
|
|
136
125
|
// Svelte 5
|
|
@@ -146,173 +135,60 @@ const messages = shallowRef<Message[]>([])
|
|
|
146
135
|
room.on('messages', m => (messages.value = m))
|
|
147
136
|
```
|
|
148
137
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
**
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
time. A message joins the list when its `message.created` arrives. A "sending…" indicator is
|
|
176
|
-
your own view state, and unlike a reaction the SDK cannot decide it for you.
|
|
177
|
-
|
|
178
|
-
**Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
|
|
179
|
-
doesn't touch the list, so merging its results with the live list, filtering duplicates, and
|
|
180
|
-
handling `reset` and reconnects all fall to the consumer. `loadOlder()` puts those rows into
|
|
181
|
-
`messages`, so ordering, deduplication, deletion, reactions, and reconnects apply to them just
|
|
182
|
-
like any other row. Calling it several times concurrently still makes one request, and if
|
|
183
|
-
`hasMore` is `false` you're at the start of the room (or of the retention period).
|
|
184
|
-
`reset` or `reload()` discards the attached past as well.
|
|
185
|
-
|
|
186
|
-
**`hasOlder` and `loadOlder()` describe the SDK's list, not your window.** The SDK never trims
|
|
187
|
-
`room.messages` — if it holds 500 rows, all 500 are there. So if you render a 100-row slice of
|
|
188
|
-
the array you were handed, the other 400 are in `room.messages`, not on the server, and
|
|
189
|
-
`hasOlder === false` is the right answer (it means you are at the start of the room). Widening
|
|
190
|
-
the window is a re-read of `room.messages`; asking the server comes after that.
|
|
191
|
-
|
|
192
|
-
```ts
|
|
193
|
-
showLoadMore(room.hasOlder)
|
|
194
|
-
const { hasMore } = await room.loadOlder()
|
|
195
|
-
```
|
|
196
|
-
|
|
197
|
-
**It's safe to send once `await room.subscribe()` has finished.** That said, you may
|
|
198
|
-
`send` without waiting — if a subscription is in progress, `send` (and `react`, `markRead`,
|
|
199
|
-
`loadOlder`, etc.) waits for it before going out. If the subscription fails, it rejects with
|
|
200
|
-
that error. A `roomByKey` room that was never subscribed doesn't know its id, so it rejects
|
|
201
|
-
immediately with `closed`. Publishing while `chat.state` is `reconnecting` also rejects with
|
|
202
|
-
`closed` — the SDK does not queue things to send.
|
|
203
|
-
|
|
204
|
-
**Opening by key does not create a room.** `roomByKey(key).subscribe()` only looks up an
|
|
205
|
-
existing room, and if there is none it's `not_found`. Rooms are created by the backend with
|
|
206
|
-
the `sk_` (`rooms.ensure({key, type})` in `@kispi/chat/server` — it's get-or-create, returning
|
|
207
|
-
the room as-is if it exists, so it's fine to call on every page load). There is an app setting
|
|
208
|
-
that lets user tokens create rooms, but it is off by default and can't be turned on from the
|
|
209
|
-
console — since the `pk_` is public, turning it on opens a door through which anyone can stamp
|
|
210
|
-
out rooms.
|
|
211
|
-
|
|
212
|
-
**The connection comes back on its own.** If the socket drops or `token()` throws, it
|
|
213
|
-
reconnects with exponential backoff (0.5 s up to 30 s, with jitter). **The first `connect()`
|
|
214
|
-
is the same** — on failure the `await` rejects so the caller knows, and retries continue in
|
|
215
|
-
the background (`state` is `reconnecting`, then `open` once it connects). The server's
|
|
216
|
-
connection limit (`rate_limited`) and server failures (`internal`) take the same path (a
|
|
217
|
-
limit waits as long as the server says). So there's no need to write your own retry loop.
|
|
218
|
-
|
|
219
|
-
**Subscribe rooms first; don't wait for the connection.** `subscribe()` waits until the
|
|
220
|
-
client is connected and then goes out, so even if the first `connect()` fails, the room fills
|
|
221
|
-
the moment a background retry connects. Putting `subscribe()` after `await chat.connect()`
|
|
222
|
-
means a rejected connect never reaches the subscribe line.
|
|
138
|
+
- **Don't ignore `reset`.** If you keep appending to the old list, you're left with a gap
|
|
139
|
+
that nobody fills.
|
|
140
|
+
- **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
|
|
141
|
+
doesn't touch the list, so merging and deduplicating fall to you.
|
|
142
|
+
- **`typing` is also delivered to the sender.** If you render "X is typing", skip your own `userId`.
|
|
143
|
+
- **The connection comes back on its own.** It reconnects with exponential backoff, so don't
|
|
144
|
+
write your own retry loop.
|
|
145
|
+
- **The SDK handles token expiry.** When REST gets a 401 it calls `token()` again and retries
|
|
146
|
+
once. There's no need to reconnect periodically.
|
|
147
|
+
- **Throwing a `ChatError` from `token()` stops the client.** That is how you say a failure,
|
|
148
|
+
like a ban, is not worth retrying.
|
|
149
|
+
- **After a nickname or avatar change, `reconnect()`.** The server reads those values from the
|
|
150
|
+
token claims once, when the socket authenticates.
|
|
151
|
+
|
|
152
|
+
### `text` is untrusted plain text
|
|
153
|
+
|
|
154
|
+
Message `text`, and user-supplied display names/nicknames (`name`), are **plain text
|
|
155
|
+
the engine does not HTML-escape or sanitize.** This is by design — escaping depends on
|
|
156
|
+
the output context you render into (an HTML text node, an attribute, some other
|
|
157
|
+
format), which the engine cannot decide on your behalf. The engine only **validates**
|
|
158
|
+
(size, shape).
|
|
159
|
+
|
|
160
|
+
So consumers must render it as text — `textContent`, or your framework's text binding
|
|
161
|
+
(React's `{text}`, Svelte's `{text}`, Vue's `{{ text }}`). **Never pass it straight into
|
|
162
|
+
`innerHTML` or `v-html`.** If you add linkification or markup, don't build an HTML
|
|
163
|
+
string with a regex replace — build DOM from text nodes instead.
|
|
223
164
|
|
|
224
165
|
```ts
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
chat.connect().catch(showOffline) // retries continue even on failure
|
|
228
|
-
await room.subscribe() // settles once connected
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
Three things stop it: `close()`, the server refusing authentication (`unauthorized`,
|
|
232
|
-
`forbidden` — repeating the same token would just be hammering the server), and **`token()`
|
|
233
|
-
throwing a `ChatError`**. That is how you say a failure is not worth retrying, like a ban or
|
|
234
|
-
an ended session:
|
|
166
|
+
// Don't — builds an HTML string with a regex
|
|
167
|
+
el.innerHTML = text.replace(urlRegex, '<a href="$1">$1</a>')
|
|
235
168
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
if (res.status === 403) throw new ChatError('forbidden', 'banned') // not retried
|
|
240
|
-
if (!res.ok) throw new Error(`token ${res.status}`) // retried with backoff
|
|
241
|
-
return (await res.json()).token
|
|
169
|
+
// Do — builds DOM from text nodes
|
|
170
|
+
for (const part of splitByUrl(text)) {
|
|
171
|
+
el.appendChild(part.isUrl ? makeAnchor(part.text) : document.createTextNode(part.text))
|
|
242
172
|
}
|
|
243
173
|
```
|
|
244
174
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
**After a nickname change, `reconnect()`.** The server reads the name and avatar from the
|
|
250
|
-
token's claims once, when the socket authenticates. So after your backend changes the name,
|
|
251
|
-
the next message on this connection still carries the old one. `reconnect()` calls `token()`
|
|
252
|
-
again, re-authenticates with the new claims, and the rooms carry on from what they hold.
|
|
253
|
-
`close()` + `connect()` works too, but passes through `closed` (your offline screen flashes)
|
|
254
|
-
and removes the page listeners. Frames still awaiting an ack on the old socket reject with
|
|
255
|
-
`closed`. When it resolves, `chat.user` is the new identity.
|
|
256
|
-
|
|
257
|
-
```ts
|
|
258
|
-
await api.updateNickname(name) // so your backend puts the new name in the next token()
|
|
259
|
-
await chat.reconnect()
|
|
260
|
-
chat.user?.name // the new name
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
**The SDK handles token expiry.** The socket authenticates only once on connect, so it stays
|
|
264
|
-
fine even when the token expires, but REST checks the token on every request. When REST gets a
|
|
265
|
-
401, the SDK calls `token()` again and retries **once**. A second 401 (origin, revoked token,
|
|
266
|
-
ban) is thrown as-is. There's no need to reconnect periodically.
|
|
267
|
-
|
|
268
|
-
The SDK neither caches the token nor hands it out. Cache inside `token()` (there's no need to
|
|
269
|
-
hit your backend on every call). **Don't reuse this token as the credential for your own
|
|
270
|
-
backend's API** — it is made to be presented to the chat engine, and mixing the two turns a
|
|
271
|
-
token leaked on one side into a key for the other. Use your own session for your own API.
|
|
272
|
-
|
|
273
|
-
**The SDK handles ordering and gap filling.** If frames arrive out of order or a reconnect
|
|
274
|
-
misses a range, it fills them in via REST. Gaps larger than one page (100) are filled
|
|
275
|
-
completely too.
|
|
276
|
-
|
|
277
|
-
**Reconnecting only recovers messages.** Because the history route covers messages only,
|
|
278
|
-
reactions on **older messages** or room renames that happened while disconnected are not
|
|
279
|
-
reflected. In that case, `await room.reload()`.
|
|
280
|
-
|
|
281
|
-
**`typing` is also delivered to the sender.** If you render "X is typing", skip your own
|
|
282
|
-
`userId`.
|
|
283
|
-
|
|
284
|
-
**Don't ignore `reset`.** If you keep appending to the old list, you're left with a gap that
|
|
285
|
-
nobody fills.
|
|
175
|
+
Bad-word filtering and similar moderation is not escaping — it's a **tenant policy**.
|
|
176
|
+
The engine only opens the mechanism (the `before_publish` hook); the consumer decides
|
|
177
|
+
(see the `before_publish` section in `docs/protocol.md`).
|
|
286
178
|
|
|
287
179
|
### Using it in the browser
|
|
288
180
|
|
|
289
|
-
You **must add the page's origin** to the `pk_`'s
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
```sh
|
|
293
|
-
chat-server app create my-app --origins https://example.com
|
|
294
|
-
chat-server key create <app-id> pk --origins https://staging.example.com
|
|
295
|
-
```
|
|
296
|
-
|
|
297
|
-
Scheme, host, and port must match **exactly**. `https://example.com` and
|
|
298
|
-
`https://www.example.com` are different origins, and so are `http://localhost:3000` and
|
|
299
|
-
`http://127.0.0.1:3000`. Add development origins separately.
|
|
300
|
-
|
|
301
|
-
**In Node it works without this setting.** WHATWG `fetch` and `WebSocket` don't send
|
|
302
|
-
`Origin` outside the browser, and the engine lets requests without an `Origin` through. That's
|
|
303
|
-
how code that's green in Node can return 401 only in the browser — this section is the reason.
|
|
181
|
+
You **must add the page's origin** to the `pk_`'s allowed origins. That's the only thing —
|
|
182
|
+
the server emits CORS headers itself, so there's no proxy to touch. Origins are edited on the
|
|
183
|
+
key screen in the console.
|
|
304
184
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
309
|
-
```
|
|
185
|
+
Scheme, host and port must match **exactly**. `https://example.com` and
|
|
186
|
+
`https://www.example.com`, `http://localhost:3000` and `http://127.0.0.1:3000` are different
|
|
187
|
+
origins. Add development origins separately.
|
|
310
188
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
authentication refusal is a failure the SDK doesn't retry, so the client stops at `closed`.
|
|
315
|
-
The reason arrives on `chat.on('error')`.
|
|
189
|
+
From an origin that isn't on the list it isn't just REST that fails — **the connection itself
|
|
190
|
+
is a 401.** An authentication refusal is a failure the SDK doesn't retry, so the client stops
|
|
191
|
+
at `closed`, and the reason arrives on `chat.on('error')`.
|
|
316
192
|
|
|
317
193
|
### Errors
|
|
318
194
|
|
|
@@ -351,10 +227,6 @@ const chat = createChatServer({
|
|
|
351
227
|
})
|
|
352
228
|
```
|
|
353
229
|
|
|
354
|
-
One key is all it takes. The value that tells the server which key signed a token
|
|
355
|
-
(`kid`) lives inside the `sk_`, so the SDK reads it from there — you do not pass
|
|
356
|
-
the console's key ID separately. The address is a constant here too.
|
|
357
|
-
|
|
358
230
|
### `chat.token(input): string`
|
|
359
231
|
|
|
360
232
|
A local signature that doesn't touch the network.
|
|
@@ -380,23 +252,15 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
380
252
|
})
|
|
381
253
|
```
|
|
382
254
|
|
|
383
|
-
**Never sign a `userId` handed back by the browser as-is.**
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
means nothing once the value is public.
|
|
388
|
-
|
|
389
|
-
`guest()` has the browser hold a **credential** instead of the id. It is
|
|
390
|
-
`g1.<userId>.<MAC>`, with the MAC made from `guestSecret`. If the returned credential
|
|
391
|
-
verifies, it signs with the id inside it; if it's missing or invalid, it signs a new guest
|
|
392
|
-
(`g_` + 22 random characters, `created: true`). Where possible, keep it in an `httpOnly`
|
|
393
|
-
cookie so page scripts can't read it.
|
|
255
|
+
**Never sign a `userId` handed back by the browser as-is.** `guest()` has the browser hold a
|
|
256
|
+
**credential** instead of the id — if it verifies, it signs with the id inside it; if it's
|
|
257
|
+
missing or invalid, it signs a new guest (`created: true`). Keep it in an `httpOnly` cookie
|
|
258
|
+
where you can.
|
|
394
259
|
|
|
395
260
|
| | |
|
|
396
261
|
|---|---|
|
|
397
|
-
| `guestSecret` | At least 32 characters. Keep it on the backend only. **Don't derive it from the `sk_`**
|
|
262
|
+
| `guestSecret` | At least 32 characters. Keep it on the backend only. **Don't derive it from the `sk_`** |
|
|
398
263
|
| Rotation | Pass an array: `[new, old]`. Signs with the first and verifies with all. A credential verified with an old one is re-signed with the same `userId` and returned, so it migrates on the next visit |
|
|
399
|
-
| Leak | If the secret leaks, anyone can become any guest. **Removing** the old one from the list turns every guest into a new person — losing identity is better than impersonation |
|
|
400
264
|
|
|
401
265
|
Guest ids start with `g_`. As long as logged-in users' ids don't start with `g_`, the two
|
|
402
266
|
spaces don't overlap.
|
|
@@ -408,40 +272,35 @@ spaces don't overlap.
|
|
|
408
272
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
409
273
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
410
274
|
| `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?})` |
|
|
411
|
-
| `events` | `list({after?, limit?})` —
|
|
275
|
+
| `events` | `list({after?, limit?})` — catches up on missed webhook events |
|
|
412
276
|
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
|
|
413
277
|
|
|
278
|
+
`rooms.ensure` is get-or-create — it returns the room as-is if it exists, so it's fine to call
|
|
279
|
+
on every page load.
|
|
280
|
+
|
|
414
281
|
`rooms.presence(roomId)` is `{count}`; with `{full: true}` it adds `users` (at most 1000,
|
|
415
282
|
`capped: true` when cut). An empty room is `{count: 0}`, not a 404.
|
|
416
283
|
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
284
|
+
`rooms.custom(roomId, payload)` is a **control signal that is not stored**. `payload` is a JSON
|
|
285
|
+
object and arrives as-is at `room.on('custom', ...)`. It leaves no history, no unread and no
|
|
286
|
+
webhook, so send a signal that must survive a reconnect with
|
|
287
|
+
`messages.send(roomId, {kind:'system', ...})` instead.
|
|
288
|
+
|
|
289
|
+
`users.ban`'s `until` is **unix milliseconds and required.** For an indefinite ban, pick a
|
|
290
|
+
far-future time yourself.
|
|
291
|
+
|
|
292
|
+
`users.purgeMessages(userId)` clears that user's messages **without withdrawing them.** It does
|
|
293
|
+
a bounded amount per call, so call again while `purgeCapped` is `true`, and for spam **ban first**.
|
|
422
294
|
|
|
423
295
|
```ts
|
|
424
296
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
425
297
|
while ((await chat.users.purgeMessages(userId)).purgeCapped) {}
|
|
426
298
|
```
|
|
427
299
|
|
|
428
|
-
`users.
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
existence by connecting.
|
|
433
|
-
|
|
434
|
-
`users.list` is for the console. Reverse uid order, `limit` defaults to 50, max 100, `cursor`
|
|
435
|
-
is an opaque string and an empty string marks the last page. **Deleted users are included too,
|
|
436
|
-
and `deletedAt` marks them** — filter on it if you only want live users. This is the opposite of
|
|
437
|
-
the in-room lists (members, reactions, reads) hiding deleted users' ids, because those are lists
|
|
438
|
-
read by **other users**, whereas this one requires the `sk_`, so the reader is the very backend
|
|
439
|
-
that issued those ids.
|
|
440
|
-
|
|
441
|
-
`rooms.custom(roomId, payload)` is a **control signal that is not stored**. `payload` is a JSON
|
|
442
|
-
object and arrives as-is at `room.on('custom', ...)`. It leaves no history, no unread, and no
|
|
443
|
-
webhook, so anyone not connected at that moment never learns of it — for a signal that must be
|
|
444
|
-
received even after reconnecting, use `messages.send(roomId, {kind:'system', ...})`.
|
|
300
|
+
`users.list` is newest first, `limit` defaults to 50 and maxes at 100, and `cursor` is
|
|
301
|
+
an opaque string where an empty string marks the last page. **Withdrawn users are included too,
|
|
302
|
+
and `deletedAt` marks them.** `users.*` works only **after the person has connected at least
|
|
303
|
+
once** — users come into existence by connecting.
|
|
445
304
|
|
|
446
305
|
### Webhooks
|
|
447
306
|
|
|
@@ -454,15 +313,11 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
|
|
|
454
313
|
})
|
|
455
314
|
```
|
|
456
315
|
|
|
457
|
-
**It must be the raw body.**
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
**The signature covers the headers too.** The canonical string is
|
|
461
|
-
`` `${t}\n${event}\n${delivery}\n${rawBody}` `` and the order is fixed. So
|
|
462
|
-
`verify` reads `X-Chat-Event` and `X-Chat-Delivery` **before verifying**, and a replay with only
|
|
463
|
-
the headers swapped won't pass — `X-Chat-Delivery` is the deduplication key, so if it were
|
|
464
|
-
outside the signature, a single captured delivery could be counted as any number of new events.
|
|
316
|
+
**It must be the raw body.** Something parsed and re-serialized is a different string and
|
|
317
|
+
fails verification.
|
|
465
318
|
|
|
466
319
|
Keep three things. `verify` checks the signature and the timestamp (default 5 minutes),
|
|
467
320
|
**deduplication is on you** (by `delivery`), and you must respond with a 2xx within 10 seconds.
|
|
468
321
|
Going over counts as a failure and backoff begins.
|
|
322
|
+
|
|
323
|
+
The signature spec for other languages is in the [webhooks guide](https://chat.gravex.app/docs/webhooks).
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ npm install @kispi/chat
|
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
이 문서가 **표면 전체**를 적는다. 여기 없는 것은 내부 구현이고, 다음 버전에
|
|
14
|
-
말 없이 바뀐다.
|
|
14
|
+
말 없이 바뀐다.
|
|
15
15
|
|
|
16
16
|
---
|
|
17
17
|
|
|
@@ -29,11 +29,6 @@ npm install @kispi/chat
|
|
|
29
29
|
`token`을 브라우저에서 만들지 않는다. 서명에 `sk_`가 필요하고, `sk_`가
|
|
30
30
|
브라우저에 있으면 그 앱 전체가 열린다.
|
|
31
31
|
|
|
32
|
-
**주소는 설정하지 않는다.** 엔진은 `wss://api.chat.gravex.app` 하나이고
|
|
33
|
-
SDK가 상수로 들고 있다(`ChatEndpoint`로 읽을 수 있다). REST도 같은 곳이다 —
|
|
34
|
-
스킴만 바뀐다. 개발용과 운영용을 나누려면 **콘솔에서 앱을 따로 만든다**:
|
|
35
|
-
앱이 다르면 `pk_`·`sk_`·방·유저가 전부 다르고, 그것이 실제로 원하는 분리다.
|
|
36
|
-
|
|
37
32
|
### `ChatClient`
|
|
38
33
|
|
|
39
34
|
| 프로퍼티 | |
|
|
@@ -49,7 +44,7 @@ SDK가 상수로 들고 있다(`ChatEndpoint`로 읽을 수 있다). REST도 같
|
|
|
49
44
|
| `close()` | 끊는다. 이건 재접속하지 않는다. 다시 붙으려면 `connect()` |
|
|
50
45
|
| `reconnect()` | **다시 인증한다**: `token()`을 다시 불러 소켓을 바꾼다. 방 핸들과 구독, `messages`는 그대로이고 상태는 `open → reconnecting → open`이다(`closed`를 거치지 않는다). 닉네임·아바타를 바꾼 뒤에 쓴다(아래) |
|
|
51
46
|
| `room(roomId)` | 방 핸들. 같은 id면 같은 객체 |
|
|
52
|
-
| `roomByKey(key)` | 키로 여는 방 핸들. 구독할 때 서버가 id를 알려 준다. **방을 만들지 않는다** — 없는 키면 `subscribe()`가 `not_found`로
|
|
47
|
+
| `roomByKey(key)` | 키로 여는 방 핸들. 구독할 때 서버가 id를 알려 준다. **방을 만들지 않는다** — 없는 키면 `subscribe()`가 `not_found`로 거절한다. 방은 백엔드가 `rooms.ensure()`로 만든다 |
|
|
53
48
|
| `rooms.list({cursor?, limit?})` | 내가 멤버인 방 + unread + 마지막 메시지 |
|
|
54
49
|
| `rooms.discover({type?, cursor?, limit?})` | 공개 방 탐색 |
|
|
55
50
|
| `rooms.members(roomId).list/add/remove` | 멤버 관리 |
|
|
@@ -79,7 +74,7 @@ off()
|
|
|
79
74
|
| `id` / `key` | 방 식별자. 키로 열었으면 구독 전까지 `id`가 없다 |
|
|
80
75
|
| `lastSeq` | 서버가 알려 준 방의 마지막 seq |
|
|
81
76
|
| `presence` | `{count, users?, capped?}` |
|
|
82
|
-
| `hasOlder` | `loadOlder()`로 더 읽을 과거가 있는지. 첫 `loadOlder()` 전에 "이전 메시지" 버튼을 그릴지 정할 때 쓴다. `loadOlder()`의 `hasMore`와 같은
|
|
77
|
+
| `hasOlder` | `loadOlder()`로 더 읽을 과거가 있는지. 첫 `loadOlder()` 전에 "이전 메시지" 버튼을 그릴지 정할 때 쓴다. `loadOlder()`의 `hasMore`와 같은 판정이고, 목록이 비었으면 `false`. `messages` 이벤트 때 다시 읽는다 |
|
|
83
78
|
|
|
84
79
|
| 메서드 | |
|
|
85
80
|
|---|---|
|
|
@@ -92,12 +87,12 @@ off()
|
|
|
92
87
|
| `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등. **프레임보다 먼저** 그 행의 `myReactions`를 고치고, 서버가 거절하면 되돌린다. 개수는 건드리지 않는다 |
|
|
93
88
|
| `reactionsOf(messageId, {emoji?, cursor?, limit?})` | 누가 눌렀는지. **한 행은 (유저, 이모지) 쌍**이라 한 사람이 여러 줄일 수 있다. `limit` 기본 50 최대 100, 마지막 페이지의 `cursor`는 빈 문자열 |
|
|
94
89
|
| `markRead(seq, {threadId?})` | 읽음 커서 |
|
|
95
|
-
| `
|
|
90
|
+
| `reads({userId?, cursor?, limit?})` | 읽음 커서 목록. `{reads: [{userId?, seq, threadId?, withdrawn?}], cursor}`. **`userId`로 한 사람만** — 자기 스레드별 커서를 되찾을 때 `reads({userId: chat.user.id})`. `cursor`가 `''`이면 끝 |
|
|
91
|
+
| `typing({threadId?})` | 입력 중. 던지지 않는다. 스레드 답글을 쓰는 중이면 `threadId` |
|
|
96
92
|
| `join()` / `leave()` | 멤버십 |
|
|
97
93
|
| `presenceList()` | 지금 이 방에 있는 사람 |
|
|
98
94
|
|
|
99
|
-
이벤트 이름은 **와이어의 이름
|
|
100
|
-
모양대로 타입이 붙어 있다.
|
|
95
|
+
이벤트 이름은 **와이어의 이름 그대로**이고, 페이로드는 타입 선언에 있다.
|
|
101
96
|
|
|
102
97
|
| 이벤트 | 페이로드 |
|
|
103
98
|
|---|---|
|
|
@@ -106,7 +101,7 @@ off()
|
|
|
106
101
|
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
107
102
|
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
108
103
|
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
|
|
109
|
-
| `typing` | `{userId}` |
|
|
104
|
+
| `typing` | `{userId, threadId?}` — `threadId`는 스레드 **루트** id, 본 타임라인이면 없다 |
|
|
110
105
|
| `read` | `{userId, seq, threadId?}` |
|
|
111
106
|
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
112
107
|
| `room.updated` | 방 객체(`unknown` — 서버 표현 그대로다) |
|
|
@@ -118,17 +113,12 @@ off()
|
|
|
118
113
|
| 이벤트 | 언제 |
|
|
119
114
|
|---|---|
|
|
120
115
|
| `messages` | 목록이 바뀔 때마다. **매번 새 배열이고, 내보낸 배열은 다시 건드리지 않는다** |
|
|
121
|
-
| `error` | 히스토리를 읽거나 구멍을 메우는 데 실패했다. **방이 스스로 다시
|
|
116
|
+
| `error` | 히스토리를 읽거나 구멍을 메우는 데 실패했다. **방이 스스로 다시 구독한다.** 사람이 누를 재시도 버튼은 `subscribe()` |
|
|
122
117
|
| `reset` | 커서가 보존 기간보다 오래돼 목록을 버리고 다시 채웠다. **렌더한 것을 버려야 한다** |
|
|
123
118
|
|
|
124
119
|
### 알아 둘 것
|
|
125
120
|
|
|
126
|
-
**`messages`는
|
|
127
|
-
배열과 그 안의 행 객체는 이후에 고쳐지지 않는다. 그래서 참조로 비교하는 상태에 그대로
|
|
128
|
-
넣으면 된다. 행도 마찬가지로, 이벤트(수정, 삭제, 리액션, 스레드)가 바꾼 행만 새 객체이고
|
|
129
|
-
나머지 행은 참조가 그대로다 — **참조가 같으면 바뀌지 않은 것**이니 행 단위 memo에 써도
|
|
130
|
-
된다. 반대는 약속하지 않는다: `reload()`와 재접속 따라잡기는 같은 내용의 행을 서버에서
|
|
131
|
-
새로 받아 오므로, 참조가 달라도 내용은 같을 수 있다.
|
|
121
|
+
**`messages`는 매번 새 배열이고, 바뀐 행만 새 객체다.** 참조로 비교하는 상태에 그대로 넣는다.
|
|
132
122
|
|
|
133
123
|
```ts
|
|
134
124
|
// Svelte 5
|
|
@@ -144,162 +134,53 @@ const messages = shallowRef<Message[]>([])
|
|
|
144
134
|
room.on('messages', m => (messages.value = m))
|
|
145
135
|
```
|
|
146
136
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
있어서(이모지 필터, 링크 치환) 미리 그릴 값이 클라이언트에 없다. 메시지는
|
|
170
|
-
`message.created`가 올 때 목록에 들어간다. 보내는 중 표시가 필요하면 그것은 소비자의
|
|
171
|
-
화면 상태이고, 리액션과 달리 SDK가 대신 정해 줄 수 없다.
|
|
172
|
-
|
|
173
|
-
**과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는
|
|
174
|
-
직접 읽기라, 그 결과를 라이브 목록과 합치고 중복을 거르고 `reset`과 재접속을
|
|
175
|
-
처리하는 일이 전부 소비자 몫이 된다. `loadOlder()`는 그 행들을 `messages`에 넣으므로
|
|
176
|
-
정렬·중복 제거·삭제·리액션·재접속이 다른 행과 똑같이 적용된다. 동시에 여러 번
|
|
177
|
-
불러도 요청은 하나이고, `hasMore`가 `false`면 방(또는 보존 기간)의 맨 앞이다.
|
|
178
|
-
`reset`이나 `reload()`는 붙인 과거도 함께 버린다.
|
|
179
|
-
|
|
180
|
-
**`hasOlder`와 `loadOlder()`는 SDK의 목록을 말한다, 당신의 창이 아니라.** SDK는
|
|
181
|
-
`room.messages`를 줄이지 않는다 — 500건을 들고 있으면 500건이 다 거기 있다. 화면
|
|
182
|
-
성능 때문에 받은 배열을 100건으로 잘라 그리고 있다면, 더 보여 줄 400건은 서버가
|
|
183
|
-
아니라 `room.messages`에 있다. 그때 `hasOlder`가 `false`인 것은 맞는 답이다(방의
|
|
184
|
-
맨 앞이라는 뜻이다). 창을 넓히는 일은 `room.messages`를 다시 읽는 것이고, 서버에
|
|
185
|
-
묻는 것은 그 다음이다.
|
|
137
|
+
- **`reset`을 무시하면 안 된다.** 옛 목록에 이어 붙이면 아무도 메우지 않는 구멍이 남는다.
|
|
138
|
+
- **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는 직접
|
|
139
|
+
읽기이므로 합치고 중복을 거르는 일이 소비자 몫이 된다.
|
|
140
|
+
- **`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를 건너뛴다.
|
|
141
|
+
- **연결은 알아서 돌아온다.** 끊기면 지수 백오프로 다시 붙으니 재시도 루프를 짜지 않는다.
|
|
142
|
+
- **토큰 만료는 SDK가 처리한다.** REST가 401을 받으면 `token()`을 다시 불러 한 번
|
|
143
|
+
재시도한다. 주기적으로 재접속할 필요가 없다.
|
|
144
|
+
- **`token()`이 `ChatError`를 던지면 멈춘다.** 밴처럼 다시 해도 소용없는 실패를 그렇게 알린다.
|
|
145
|
+
- **닉네임·아바타를 바꿨으면 `reconnect()`.** 서버는 그 값을 접속할 때 토큰 claim에서
|
|
146
|
+
한 번 읽는다.
|
|
147
|
+
|
|
148
|
+
### `text`는 신뢰할 수 없는 평문이다
|
|
149
|
+
|
|
150
|
+
메시지 `text`와 유저가 넣는 표시 이름·닉네임(`name`)은 **엔진이 HTML 이스케이프하거나
|
|
151
|
+
정제하지 않은 평문**이다. 의도적이다 — 이스케이프는 렌더링하는 출력 컨텍스트(HTML
|
|
152
|
+
텍스트 노드인지, 속성인지, 다른 포맷인지)에 달려 있어 엔진이 대신 정할 수 없다.
|
|
153
|
+
엔진은 크기·형식 같은 **검증**만 한다.
|
|
154
|
+
|
|
155
|
+
그래서 소비자가 렌더할 때 텍스트로 다뤄야 한다 — `textContent`나 프레임워크의 텍스트
|
|
156
|
+
바인딩(React의 `{text}`, Svelte의 `{text}`, Vue의 `{{ text }}`). **`innerHTML`이나
|
|
157
|
+
`v-html`에 그대로 꽂으면 안 된다.** 링크 자동 인식이나 마크업을 더하고 싶으면 문자열을
|
|
158
|
+
HTML로 만들어 정규식으로 치환하지 말고, 텍스트 노드를 만들어 DOM에 직접 붙인다.
|
|
186
159
|
|
|
187
160
|
```ts
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
**보내도 되는 때는 `await room.subscribe()`가 끝난 때다.** 다만 기다리지 않고
|
|
193
|
-
`send`해도 된다 — 구독이 진행 중이면 `send`(와 `react`, `markRead`, `loadOlder` 등)가
|
|
194
|
-
그것을 기다렸다가 나간다. 구독이 실패하면 그 에러로 거절한다. 구독한 적도 없는
|
|
195
|
-
`roomByKey` 방은 id를 모르므로 곧바로 `closed`로 거절한다. `chat.state`가
|
|
196
|
-
`reconnecting`인 동안의 발행도 `closed`로 거절한다 — SDK는 보낼 것을 쌓아 두지 않는다.
|
|
197
|
-
|
|
198
|
-
**키로 연다고 방이 생기지 않는다.** `roomByKey(key).subscribe()`는 있는 방을 찾기만
|
|
199
|
-
하고, 없으면 `not_found`다. 방은 백엔드가 `sk_`로 만든다
|
|
200
|
-
(`@kispi/chat/server`의 `rooms.ensure({key, type})` — 있으면 그대로 돌려주는
|
|
201
|
-
get-or-create라 페이지를 열 때마다 불러도 된다). 유저 토큰으로 방을 만들게 하는 앱 설정도
|
|
202
|
-
있지만 기본은 꺼져 있고 콘솔에서 켤 수 없다 — `pk_`는 공개값이라, 켜면 누구나 방을
|
|
203
|
-
찍어낼 수 있는 문이 된다.
|
|
204
|
-
|
|
205
|
-
**연결은 알아서 돌아온다.** 소켓이 끊기거나 `token()`이 던지면 지수 백오프(0.5초에서
|
|
206
|
-
30초까지, 지터)로 다시 붙는다. **첫 `connect()`도 같다** — 실패하면 `await`는 거절해서
|
|
207
|
-
호출자가 알게 하고, 재시도는 백그라운드에서 이어진다(`state`가 `reconnecting`, 붙으면
|
|
208
|
-
`open`). 서버의 접속 한도(`rate_limited`)와 서버 장애(`internal`)도 같은 길로 다시
|
|
209
|
-
붙는다(한도는 서버가 말한 만큼 기다린다). 그래서 재시도 루프를 직접 짤 필요가 없다.
|
|
210
|
-
|
|
211
|
-
방은 **연결을 기다리지 말고 먼저 구독해 둔다.** `subscribe()`는 붙을 때까지 기다렸다가
|
|
212
|
-
나가므로, 첫 `connect()`가 실패해도 백그라운드 재시도가 붙는 순간 방이 채워진다.
|
|
213
|
-
`await chat.connect()` 뒤에 `subscribe()`를 두면 connect가 거절될 때 구독 줄에 닿지
|
|
214
|
-
않는다.
|
|
161
|
+
// 하면 안 된다 — 정규식으로 HTML 문자열을 만든다
|
|
162
|
+
el.innerHTML = text.replace(urlRegex, '<a href="$1">$1</a>')
|
|
215
163
|
|
|
216
|
-
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
chat.connect().catch(showOffline) // 실패해도 재시도는 계속된다
|
|
220
|
-
await room.subscribe() // 붙은 뒤 끝난다
|
|
221
|
-
```
|
|
222
|
-
|
|
223
|
-
멈추는 것은 셋이다. `close()`, 서버의 인증 거절(`unauthorized`, `forbidden` — 같은
|
|
224
|
-
토큰을 반복하는 것은 서버를 두드리는 일이다), 그리고 **`token()`이 `ChatError`를 던질
|
|
225
|
-
때**다. 밴이나 끝난 세션처럼 다시 해도 소용없는 실패는 그렇게 알린다:
|
|
226
|
-
|
|
227
|
-
```ts
|
|
228
|
-
token: async () => {
|
|
229
|
-
const res = await fetch('/api/chat-token')
|
|
230
|
-
if (res.status === 403) throw new ChatError('forbidden', 'banned') // 다시 하지 않는다
|
|
231
|
-
if (!res.ok) throw new Error(`token ${res.status}`) // 백오프로 다시 한다
|
|
232
|
-
return (await res.json()).token
|
|
164
|
+
// 이렇게 — 텍스트 노드로 DOM을 만든다
|
|
165
|
+
for (const part of splitByUrl(text)) {
|
|
166
|
+
el.appendChild(part.isUrl ? makeAnchor(part.text) : document.createTextNode(part.text))
|
|
233
167
|
}
|
|
234
168
|
```
|
|
235
169
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
**닉네임을 바꾸면 `reconnect()`.** 서버는 이름·아바타를 접속할 때 토큰 claim에서
|
|
240
|
-
한 번 읽는다. 그래서 백엔드에서 이름을 바꿔도 이 접속의 다음 메시지는 옛 이름이다.
|
|
241
|
-
`reconnect()`는 `token()`을 다시 불러 새 claim으로 다시 인증하고, 방은 가진 것에서
|
|
242
|
-
이어서 따라잡는다. `close()` + `connect()`도 되지만 `closed`를 거쳐(오프라인 화면이
|
|
243
|
-
깜빡인다) 페이지 리스너까지 떼어 낸다. 옛 소켓에서 ack를 기다리던 프레임은 `closed`로
|
|
244
|
-
거절된다. 끝나면 `chat.user`가 새 신원이다.
|
|
245
|
-
|
|
246
|
-
```ts
|
|
247
|
-
await api.updateNickname(name) // 백엔드가 다음 token()에 새 이름을 싣게 한다
|
|
248
|
-
await chat.reconnect()
|
|
249
|
-
chat.user?.name // 새 이름
|
|
250
|
-
```
|
|
251
|
-
|
|
252
|
-
**토큰 만료는 SDK가 처리한다.** 소켓은 접속할 때 한 번만 인증하므로 토큰이 만료돼도
|
|
253
|
-
멀쩡하지만, REST는 요청마다 토큰을 본다. REST가 401을 받으면 SDK가 `token()`을 다시
|
|
254
|
-
불러 **한 번** 재시도한다. 두 번째 401(오리진, 폐기된 토큰, 밴)은 그대로 던진다.
|
|
255
|
-
주기적으로 재접속할 필요가 없다.
|
|
256
|
-
|
|
257
|
-
SDK는 토큰을 캐시하지도, 꺼내 주지도 않는다. 캐시는 `token()` 안에서 한다(부를
|
|
258
|
-
때마다 백엔드를 칠 필요는 없다). **이 토큰을 자기 백엔드 API의 인증으로 다시 쓰지
|
|
259
|
-
않는다** — 채팅 엔진에 내라고 만든 것이고, 둘을 섞으면 한쪽에 새어 나간 토큰이 다른
|
|
260
|
-
쪽의 열쇠가 된다. 자기 API에는 자기 세션을 쓴다.
|
|
261
|
-
|
|
262
|
-
**정렬과 구멍 메우기는 SDK가 한다.** 프레임이 순서 없이 오거나 재접속으로 구간을
|
|
263
|
-
놓치면 REST로 채운다. 한 페이지(100)를 넘는 구멍도 전부 채운다.
|
|
264
|
-
|
|
265
|
-
**재접속이 복구하는 것은 메시지뿐이다.** 히스토리 라우트가 메시지 하나라서,
|
|
266
|
-
끊긴 동안 **오래된 메시지**에 달린 리액션이나 바뀐 방 이름은 반영되지 않는다.
|
|
267
|
-
그럴 때는 `await room.reload()`.
|
|
268
|
-
|
|
269
|
-
**`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를
|
|
270
|
-
건너뛴다.
|
|
271
|
-
|
|
272
|
-
**`reset`을 무시하면 안 된다.** 옛 목록에 이어 붙이면 아무도 메우지 않는 구멍이
|
|
273
|
-
남는다.
|
|
170
|
+
욕설 같은 금칙어 처리는 이스케이프가 아니라 **테넌트 정책**이다 — 엔진은
|
|
171
|
+
`before_publish` 훅이라는 기전만 열어 주고, 판정은 소비자가 한다(`docs/protocol.md`의
|
|
172
|
+
`before_publish` 절).
|
|
274
173
|
|
|
275
174
|
### 브라우저에서 쓸 때
|
|
276
175
|
|
|
277
|
-
`pk_`의
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
```sh
|
|
281
|
-
chat-server app create my-app --origins https://example.com
|
|
282
|
-
chat-server key create <app-id> pk --origins https://staging.example.com
|
|
283
|
-
```
|
|
284
|
-
|
|
285
|
-
스킴·호스트·포트가 **정확히** 맞아야 한다. `https://example.com`과
|
|
286
|
-
`https://www.example.com`은 다른 오리진이고, `http://localhost:3000`과
|
|
287
|
-
`http://127.0.0.1:3000`도 다른 오리진이다. 개발용 오리진은 따로 넣는다.
|
|
176
|
+
`pk_`의 허용 오리진에 **페이지의 오리진을 넣어야 한다.** 이것 하나다 — 서버가 CORS 헤더를
|
|
177
|
+
직접 내므로 프록시를 건드릴 일은 없다. 오리진은 콘솔의 키 화면에서 편집한다.
|
|
288
178
|
|
|
289
|
-
|
|
290
|
-
`
|
|
291
|
-
초록이던 코드가 브라우저에서만 401이 나는 일이 생긴다 — 이 절이 그 이유다.
|
|
292
|
-
|
|
293
|
-
목록에 없으면 REST가 401로 거절하고, 메시지가 원인을 말한다:
|
|
294
|
-
|
|
295
|
-
```
|
|
296
|
-
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
297
|
-
```
|
|
179
|
+
스킴·호스트·포트가 **정확히** 맞아야 한다. `https://example.com`과 `https://www.example.com`,
|
|
180
|
+
`http://localhost:3000`과 `http://127.0.0.1:3000`이 서로 다른 오리진이다. 개발용은 따로 넣는다.
|
|
298
181
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
오리진에서는 REST만이 아니라 접속부터 막히고, 인증 거절은 SDK가 다시 시도하지 않는
|
|
302
|
-
실패라 클라이언트가 `closed`에서 멈춘다 — 이유는 `chat.on('error')`로 온다.
|
|
182
|
+
목록에 없는 오리진에서는 REST만이 아니라 **접속부터 401이다.** 인증 거절은 SDK가 다시
|
|
183
|
+
시도하지 않으므로 클라이언트가 `closed`에서 멈추고, 이유는 `chat.on('error')`로 온다.
|
|
303
184
|
|
|
304
185
|
### 에러
|
|
305
186
|
|
|
@@ -338,10 +219,6 @@ const chat = createChatServer({
|
|
|
338
219
|
})
|
|
339
220
|
```
|
|
340
221
|
|
|
341
|
-
키 하나면 된다. 어느 키로 서명했는지를 서버에 알리는 값(`kid`)은 `sk_`
|
|
342
|
-
안에 들어 있어서 SDK가 거기서 읽는다 — 콘솔의 키 ID를 따로 넣지 않는다.
|
|
343
|
-
주소도 클라이언트와 같이 상수다.
|
|
344
|
-
|
|
345
222
|
### `chat.token(input): string`
|
|
346
223
|
|
|
347
224
|
네트워크를 타지 않는 로컬 서명이다.
|
|
@@ -367,25 +244,16 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
367
244
|
})
|
|
368
245
|
```
|
|
369
246
|
|
|
370
|
-
**브라우저가 돌려준 `userId`를 그대로
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
형식 검사(`g_` + UUID 정규식)는 이것을 막지 못한다. UUID가 추측하기 어려운 것은
|
|
374
|
-
공개된 값 앞에서는 아무 의미가 없다.
|
|
375
|
-
|
|
376
|
-
`guest()`는 브라우저가 id 대신 **자격증명**을 들게 한다. `g1.<userId>.<MAC>`이고 MAC은
|
|
377
|
-
`guestSecret`으로 만든다. 돌아온 자격증명이 검증되면 그 안의 id로, 없거나 틀리면
|
|
378
|
-
새 게스트(`g_` + 무작위 22자, `created: true`)로 서명한다. 가능하면 `httpOnly` 쿠키에
|
|
379
|
-
두어 페이지의 스크립트가 읽지 못하게 한다.
|
|
247
|
+
**브라우저가 돌려준 `userId`를 그대로 서명하지 않는다.** `guest()`는 브라우저가 id 대신
|
|
248
|
+
**자격증명**을 들게 한다 — 검증되면 그 안의 id로, 없거나 틀리면 새 게스트(`created: true`)로
|
|
249
|
+
서명한다. 가능하면 `httpOnly` 쿠키에 둔다.
|
|
380
250
|
|
|
381
251
|
| | |
|
|
382
252
|
|---|---|
|
|
383
|
-
| `guestSecret` | 32자 이상. 백엔드에만 둔다. **`sk_`에서 유도하지 않는다**
|
|
253
|
+
| `guestSecret` | 32자 이상. 백엔드에만 둔다. **`sk_`에서 유도하지 않는다** |
|
|
384
254
|
| 교체 | 배열로 준다: `[새것, 옛것]`. 첫 번째로 서명하고 전부로 검증한다. 옛것으로 검증된 자격증명은 같은 `userId`로 새로 서명해 돌려주므로 다음 방문에 옮겨 간다 |
|
|
385
|
-
| 유출 | 비밀이 새면 누구든 아무 게스트가 될 수 있다. 옛것을 목록에서 **빼면** 모든 게스트가 새 사람이 된다 — 신원을 잃는 것이 사칭보다 낫다 |
|
|
386
255
|
|
|
387
|
-
게스트 id는 `g_`로 시작한다. 로그인 유저의 id
|
|
388
|
-
겹치지 않는다.
|
|
256
|
+
게스트 id는 `g_`로 시작한다. 로그인 유저의 id를 `g_`로 시작하지 않게 하면 겹치지 않는다.
|
|
389
257
|
|
|
390
258
|
### 나머지
|
|
391
259
|
|
|
@@ -394,39 +262,31 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
394
262
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
395
263
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
396
264
|
| `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?})` |
|
|
397
|
-
| `events` | `list({after?, limit?})` —
|
|
265
|
+
| `events` | `list({after?, limit?})` — 놓친 웹훅 이벤트를 따라잡는다 |
|
|
398
266
|
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance`는 밀리초 |
|
|
399
267
|
|
|
268
|
+
`rooms.ensure`는 get-or-create다 — 있으면 그대로 돌려주므로 페이지를 열 때마다 불러도 된다.
|
|
269
|
+
|
|
400
270
|
`rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
|
|
401
271
|
`capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
|
|
402
272
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
`
|
|
273
|
+
`rooms.custom(roomId, payload)`은 **저장되지 않는 제어 신호**다. `payload`는 JSON 객체이고
|
|
274
|
+
그대로 `room.on('custom', ...)`에 도착한다. 히스토리도 unread도 웹훅도 남지 않으니, 재접속해도
|
|
275
|
+
받아야 하는 신호는 `messages.send(roomId, {kind:'system', ...})`으로 보낸다.
|
|
276
|
+
|
|
277
|
+
`users.ban`의 `until`은 **unix 밀리초이고 필수다.** 무기한 밴은 먼 미래 시각을 직접 고른다.
|
|
278
|
+
|
|
279
|
+
`users.purgeMessages(userId)`는 그 유저의 메시지를 거두되 **탈퇴시키지 않는다.** 한 번에
|
|
280
|
+
상한만큼만 하므로 `purgeCapped`가 `true`인 동안 다시 부르고, 스팸이면 **밴을 먼저** 한다.
|
|
408
281
|
|
|
409
282
|
```ts
|
|
410
283
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
411
284
|
while ((await chat.users.purgeMessages(userId)).purgeCapped) {}
|
|
412
285
|
```
|
|
413
286
|
|
|
414
|
-
`users.
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
`users.*`는 그 사람이 **한 번이라도 접속한 뒤에만** 통한다. 유저는 접속으로
|
|
418
|
-
생긴다.
|
|
419
|
-
|
|
420
|
-
`users.list`는 콘솔용이다. uid 역순, `limit` 기본 50 최대 100, `cursor`는 불투명
|
|
421
|
-
문자열이고 빈 문자열이 마지막 페이지다. **탈퇴한 유저도 나오고 `deletedAt`이 그
|
|
422
|
-
표시다** — 살아 있는 유저만 원하면 그것으로 거른다. 방 안의 목록들(멤버·리액션·읽음)이
|
|
423
|
-
탈퇴자의 id를 감추는 것과 반대인데, 그쪽은 **다른 유저**가 읽는 목록이고 이쪽은
|
|
424
|
-
`sk_`가 있어야 하므로 상대가 그 id를 발급한 백엔드 자신이기 때문이다.
|
|
425
|
-
|
|
426
|
-
`rooms.custom(roomId, payload)`은 **저장되지 않는 제어 신호**다. `payload`는 JSON
|
|
427
|
-
객체이고 그대로 `room.on('custom', ...)`에 도착한다. 히스토리도 unread도 웹훅도
|
|
428
|
-
남지 않으니, 그 순간 접속해 있지 않은 사람은 영영 모른다 — 재접속해도 받아야 하는
|
|
429
|
-
신호라면 `messages.send(roomId, {kind:'system', ...})`이다.
|
|
287
|
+
`users.list`는 최신순이고 `limit` 기본 50 최대 100, `cursor`는 불투명 문자열이며 빈
|
|
288
|
+
문자열이 마지막 페이지다. **탈퇴한 유저도 나오고 `deletedAt`이 그 표시다.**
|
|
289
|
+
`users.*`는 그 사람이 **한 번이라도 접속한 뒤에만** 통한다 — 유저는 접속으로 생긴다.
|
|
430
290
|
|
|
431
291
|
### 웹훅
|
|
432
292
|
|
|
@@ -439,15 +299,9 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
|
|
|
439
299
|
})
|
|
440
300
|
```
|
|
441
301
|
|
|
442
|
-
**raw 바디여야 한다.**
|
|
443
|
-
직렬화한 것은 다른 문자열이다.
|
|
302
|
+
**raw 바디여야 한다.** 파싱했다가 다시 직렬화한 것은 다른 문자열이라 검증에 실패한다.
|
|
444
303
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
`verify`는 `X-Chat-Event`와 `X-Chat-Delivery`를 **검증 전에** 읽고, 헤더만
|
|
448
|
-
바꿔치기한 재전송은 통과하지 못한다 — `X-Chat-Delivery`가 중복 제거 키이므로
|
|
449
|
-
그것이 서명 밖에 있으면 캡처한 배달 하나가 얼마든지 새 이벤트로 셀 수 있다.
|
|
304
|
+
세 가지를 지킨다. `verify`가 서명과 시각(기본 5분)을 보고, **중복 제거는 직접** 해야 하며
|
|
305
|
+
(`delivery`로), 10초 안에 2xx로 답해야 한다. 넘기면 실패로 치고 백오프가 시작된다.
|
|
450
306
|
|
|
451
|
-
|
|
452
|
-
해야 하며(`delivery`로), 10초 안에 2xx로 답해야 한다. 넘기면 실패로 치고 백오프가
|
|
453
|
-
시작된다.
|
|
307
|
+
다른 언어로 검증하는 규격은 [웹훅 문서](https://chat.gravex.app/docs/webhooks)에 있다.
|
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
|
-
|
|
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
|
-
/**
|
|
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(
|
|
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
|
-
/**
|
|
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(
|
|
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
|
-
|
|
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
|
}
|