@kispi/chat 0.2.2 → 0.3.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 +74 -48
- package/README.md +70 -47
- package/dist/{chunk-5QQRM7BH.js → chunk-WSBOTTBM.js} +21 -3
- package/dist/index.cjs +183 -46
- package/dist/index.d.cts +172 -328
- package/dist/index.d.ts +172 -328
- package/dist/index.js +166 -42
- package/dist/server/index.cjs +37 -9
- package/dist/server/index.d.cts +20 -14
- package/dist/server/index.d.ts +20 -14
- package/dist/server/index.js +22 -8
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -10,7 +10,8 @@ There are two entry points. `@kispi/chat` is the client for the browser and Node
|
|
|
10
10
|
npm install @kispi/chat
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
This document covers **the entire surface**.
|
|
13
|
+
This document covers **the entire surface**. Anything not here is internal and
|
|
14
|
+
changes without notice. How to get started is here too.
|
|
14
15
|
|
|
15
16
|
---
|
|
16
17
|
|
|
@@ -20,17 +21,20 @@ This document covers **the entire surface**. How to get started is here too.
|
|
|
20
21
|
|
|
21
22
|
| Option | Type | |
|
|
22
23
|
|---|---|---|
|
|
23
|
-
| `url` | `string` | **Required.** Pass the origin only. The SDK appends `/v1/ws?v=1` |
|
|
24
24
|
| `key` | `string` | **Required.** A `pk_`. It is public, so it is fine to put in the browser |
|
|
25
25
|
| `token` | `() => string \| Promise<string>` | **Required.** A user token signed by your backend. Called again on every connect and whenever REST gets a 401, so an expired one is never reused. A throw is retried with backoff; **throwing a `ChatError` means do not retry** (see below) |
|
|
26
|
-
| `
|
|
27
|
-
| `externalToken` | `() => string \| Promise<string>` | External mode. If given, it **takes precedence over `token`** (same order the server checks in). **The server still rejects it, so there is no use for it today** |
|
|
28
|
-
| `WebSocket` | `new (url) => WebSocketLike` | Implementation to use instead of the global. Injected in tests |
|
|
26
|
+
| `WebSocket` | `new (url) => WebSocketLike` | Implementation to use instead of the global |
|
|
29
27
|
| `fetch` | `typeof fetch` | Same as above |
|
|
30
28
|
|
|
31
29
|
Do not create `token` in the browser. Signing requires the `sk_`, and if the `sk_`
|
|
32
30
|
is in the browser, the whole app is open.
|
|
33
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
|
+
|
|
34
38
|
### `ChatClient`
|
|
35
39
|
|
|
36
40
|
| Property | |
|
|
@@ -38,7 +42,7 @@ is in the browser, the whole app is open.
|
|
|
38
42
|
| `state` | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` |
|
|
39
43
|
| `user` | The connected user. `{id, name, avatar?}` — **the identity the server accepted from the token** (what `hello` carried). Use this instead of parsing your token response. Set once `connect()`/`reconnect()` resolves |
|
|
40
44
|
| `connectionId` | Identifier used for support requests and forced disconnects |
|
|
41
|
-
| `hello` | Everything the server sent on connect (
|
|
45
|
+
| `hello` | Everything the server sent on connect: `limits` (effective), `unread` (`{total, mentions, roomsCapped?}` — **absent is not zero, it means the count could not be read**, so recover with `unread()`), `warnings`, `serverTime`, `heartbeatMs` |
|
|
42
46
|
|
|
43
47
|
| Method | |
|
|
44
48
|
|---|---|
|
|
@@ -50,9 +54,8 @@ is in the browser, the whole app is open.
|
|
|
50
54
|
| `rooms.list({cursor?, limit?})` | Rooms I'm a member of + unread + last message |
|
|
51
55
|
| `rooms.discover({type?, cursor?, limit?})` | Browse public rooms |
|
|
52
56
|
| `rooms.members(roomId).list/add/remove` | Member management |
|
|
53
|
-
| `unread()` |
|
|
57
|
+
| `unread()` | `{total, mentions, roomsCapped?, rooms}` — the **same field names** as `chat.hello?.unread` |
|
|
54
58
|
| `updateMe(meta)` | My `meta`. **`name` and `avatar` come from the token claims** |
|
|
55
|
-
| `send(type, data?, timeoutMs?)` | Raw frame. Only for calling things not on the surface |
|
|
56
59
|
|
|
57
60
|
| Event | |
|
|
58
61
|
|---|---|
|
|
@@ -87,18 +90,29 @@ off()
|
|
|
87
90
|
| `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 |
|
|
88
91
|
| `history({before?, after?, limit?, view?})` | Reads the past directly. **Independent of `messages`.** `view` is `'main'`, `'all'`, or `{thread: id}` |
|
|
89
92
|
| `reload()` | Re-reads the latest page |
|
|
90
|
-
| `react(messageId, emoji)` / `unreact(...)` | Reactions. Idempotent.
|
|
93
|
+
| `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 |
|
|
91
94
|
| `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 |
|
|
92
95
|
| `markRead(seq, {threadId?})` | Read cursor |
|
|
93
96
|
| `typing()` | Typing indicator. Does not throw |
|
|
94
97
|
| `join()` / `leave()` | Membership |
|
|
95
98
|
| `presenceList()` | Who is in this room right now |
|
|
96
|
-
| `resume()` | Resubscribes after reconnecting. The SDK calls it for you |
|
|
97
99
|
|
|
98
|
-
Event names are **exactly the wire names
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
100
|
+
Event names are **exactly the wire names**, and the payloads are typed after the
|
|
101
|
+
shapes in `docs/protocol.md`.
|
|
102
|
+
|
|
103
|
+
| Event | Payload |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
|
|
106
|
+
| `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
|
|
107
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
108
|
+
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
109
|
+
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
|
|
110
|
+
| `typing` | `{userId}` |
|
|
111
|
+
| `read` | `{userId, seq, threadId?}` |
|
|
112
|
+
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
113
|
+
| `room.updated` | The room object (`unknown` — the server's own representation) |
|
|
114
|
+
| `room.deleted` | `{roomId}` |
|
|
115
|
+
| `custom` | Exactly the object `rooms.custom(roomId, payload)` sent |
|
|
102
116
|
|
|
103
117
|
The SDK emits three more that have no wire counterpart.
|
|
104
118
|
|
|
@@ -132,17 +146,35 @@ const messages = shallowRef<Message[]>([])
|
|
|
132
146
|
room.on('messages', m => (messages.value = m))
|
|
133
147
|
```
|
|
134
148
|
|
|
135
|
-
Wrapping it in `$state` (a deep proxy) or `ref` works, but does unnecessary work.
|
|
136
|
-
modified the same array in place and emitted it again, so on the reference-comparing side
|
|
137
|
-
the screen froze.
|
|
149
|
+
Wrapping it in `$state` (a deep proxy) or `ref` works, but does unnecessary work.
|
|
138
150
|
|
|
139
151
|
**Reactions: `reactions` is everyone's counts, `myReactions` is the emoji you pressed.**
|
|
140
152
|
The SDK keeps both live — counts from the `count` on `reaction.*` events, `myReactions` from
|
|
141
153
|
those events when their `userId` is `chat.user.id` (including presses from your other tabs and
|
|
142
|
-
devices) and from
|
|
154
|
+
devices) and from your own `react()`/`unreact()`. Both are overwrites, not
|
|
143
155
|
increments, so getting the event and the ack never counts twice. Only the changed row is a new
|
|
144
156
|
object.
|
|
145
157
|
|
|
158
|
+
**`myReactions` moves the moment you press.** `react()`/`unreact()` update that row's
|
|
159
|
+
`myReactions` and emit `messages` **before** the frame goes out, so the press does not feel a
|
|
160
|
+
round trip late — the value is already determined by (you, emoji) and the server is idempotent,
|
|
161
|
+
so the ack has nothing new to say. If the server refuses (a limit, permissions) or the ack never
|
|
162
|
+
arrives (timeout, a dropped connection), the SDK rolls it back — unless something newer has
|
|
163
|
+
taken that spot in the meantime. A later press, a `reaction.*` event carrying your own `userId`,
|
|
164
|
+
and a page from `reload()` or a reconnect all beat a pending optimistic value, and a refusal
|
|
165
|
+
never resurrects a stale one. **The SDK owns this field**: an optimistic layer of your own on
|
|
166
|
+
top of it would give it two owners.
|
|
167
|
+
|
|
168
|
+
**The count (`reactions[].count`) is always the server's.** It is never moved locally. If
|
|
169
|
+
somebody else presses the same emoji while your ack is in flight, a local ±1 disagrees with the
|
|
170
|
+
number the server sends, and the event that would have corrected it has already gone by. Counts
|
|
171
|
+
move on `reaction.*` events only.
|
|
172
|
+
|
|
173
|
+
**Publishing (`send()`) is deliberately not optimistic.** A `before_publish` hook may rewrite
|
|
174
|
+
the body (an emoji filter, a link rewrite), so there is no value on the client to draw ahead of
|
|
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
|
+
|
|
146
178
|
**Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
|
|
147
179
|
doesn't touch the list, so merging its results with the live list, filtering duplicates, and
|
|
148
180
|
handling `reset` and reconnects all fall to the consumer. `loadOlder()` puts those rows into
|
|
@@ -151,6 +183,12 @@ like any other row. Calling it several times concurrently still makes one reques
|
|
|
151
183
|
`hasMore` is `false` you're at the start of the room (or of the retention period).
|
|
152
184
|
`reset` or `reload()` discards the attached past as well.
|
|
153
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
|
+
|
|
154
192
|
```ts
|
|
155
193
|
showLoadMore(room.hasOlder)
|
|
156
194
|
const { hasMore } = await room.loadOlder()
|
|
@@ -166,10 +204,10 @@ immediately with `closed`. Publishing while `chat.state` is `reconnecting` also
|
|
|
166
204
|
**Opening by key does not create a room.** `roomByKey(key).subscribe()` only looks up an
|
|
167
205
|
existing room, and if there is none it's `not_found`. Rooms are created by the backend with
|
|
168
206
|
the `sk_` (`rooms.ensure({key, type})` in `@kispi/chat/server` — it's get-or-create, returning
|
|
169
|
-
the room as-is if it exists, so it's fine to call on every page load).
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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.
|
|
173
211
|
|
|
174
212
|
**The connection comes back on its own.** If the socket drops or `token()` throws, it
|
|
175
213
|
reconnects with exponential backoff (0.5 s up to 30 s, with jitter). **The first `connect()`
|
|
@@ -270,10 +308,11 @@ If the origin isn't on the list, REST rejects with 401, and the message states t
|
|
|
270
308
|
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
271
309
|
```
|
|
272
310
|
|
|
273
|
-
**
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
311
|
+
**The connection consults the same list.** WebSocket isn't subject to browser CORS, but the
|
|
312
|
+
engine checks the `pk_`'s `allowed_origins` itself during the handshake. So from an origin
|
|
313
|
+
that isn't on the list, it isn't just REST that fails — the connection is refused too, and an
|
|
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')`.
|
|
277
316
|
|
|
278
317
|
### Errors
|
|
279
318
|
|
|
@@ -291,7 +330,7 @@ try {
|
|
|
291
330
|
|
|
292
331
|
| Field | |
|
|
293
332
|
|---|---|
|
|
294
|
-
| `code` | `unauthorized`, `
|
|
333
|
+
| `code` | A union of the known values (`ChatErrorCode`), so a typo fails to compile. From the server: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. From the SDK: `timeout`, `closed`. A code the server adds later still type-checks |
|
|
295
334
|
| `retryAfterMs` | Wait time reported by the server when you hit a limit |
|
|
296
335
|
| `appCode` | Consumer-side code attached by a `before_publish` webhook when rejecting |
|
|
297
336
|
| `status` | HTTP status, if the error came from a REST call |
|
|
@@ -306,14 +345,16 @@ Uses the `sk_`. **Never put it in the browser.**
|
|
|
306
345
|
import { createChatServer } from '@kispi/chat/server'
|
|
307
346
|
|
|
308
347
|
const chat = createChatServer({
|
|
309
|
-
|
|
310
|
-
secretKey: process.env.CHAT_SECRET_KEY!,
|
|
311
|
-
keyId: process.env.CHAT_KEY_ID!,
|
|
348
|
+
secretKey: process.env.CHAT_SECRET_KEY!, // sk_…
|
|
312
349
|
webhookSecret: process.env.CHAT_WEBHOOK_SECRET,
|
|
313
350
|
guestSecret: process.env.CHAT_GUEST_SECRET, // only if you use guest()
|
|
314
351
|
})
|
|
315
352
|
```
|
|
316
353
|
|
|
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
|
+
|
|
317
358
|
### `chat.token(input): string`
|
|
318
359
|
|
|
319
360
|
A local signature that doesn't touch the network.
|
|
@@ -366,9 +407,9 @@ spaces don't overlap.
|
|
|
366
407
|
|---|---|
|
|
367
408
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
368
409
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
369
|
-
| `users` | `list({cursor?, limit?})`, `update`, `
|
|
410
|
+
| `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?})` |
|
|
370
411
|
| `events` | `list({after?, limit?})` — the outbox. Catches up on missed webhooks |
|
|
371
|
-
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` |
|
|
412
|
+
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
|
|
372
413
|
|
|
373
414
|
`rooms.presence(roomId)` is `{count}`; with `{full: true}` it adds `users` (at most 1000,
|
|
374
415
|
`capped: true` when cut). An empty room is `{count: 0}`, not a 404.
|
|
@@ -377,7 +418,7 @@ spaces don't overlap.
|
|
|
377
418
|
app (tombstones: seq is untouched, and watching clients get `message.deleted`) **without
|
|
378
419
|
withdrawing them.** The name stays. For spam, **ban first**, then call it — a message posted
|
|
379
420
|
while it runs is not in its listing. It does a bounded amount per call, so call again while
|
|
380
|
-
`purgeCapped` is `true`. A withdrawn user is a 404 (use `
|
|
421
|
+
`purgeCapped` is `true`. A withdrawn user is a 404 (use `withdraw(userId, {purgeMessages: true})`).
|
|
381
422
|
|
|
382
423
|
```ts
|
|
383
424
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
@@ -425,18 +466,3 @@ outside the signature, a single captured delivery could be counted as any number
|
|
|
425
466
|
Keep three things. `verify` checks the signature and the timestamp (default 5 minutes),
|
|
426
467
|
**deduplication is on you** (by `delivery`), and you must respond with a 2xx within 10 seconds.
|
|
427
468
|
Going over counts as a failure and backoff begins.
|
|
428
|
-
|
|
429
|
-
---
|
|
430
|
-
|
|
431
|
-
## Development
|
|
432
|
-
|
|
433
|
-
```sh
|
|
434
|
-
pnpm install
|
|
435
|
-
pnpm build # ESM + CJS + type declarations
|
|
436
|
-
pnpm exec vitest run
|
|
437
|
-
pnpm exec tsc --noEmit
|
|
438
|
-
```
|
|
439
|
-
|
|
440
|
-
Tests use **injection**, not mocks. Swapping in `WebSocket` and `fetch` means there's no need to
|
|
441
|
-
imitate the server, and the integration-style files connect to a **live server** outright.
|
|
442
|
-
Running them requires Postgres and Redis.
|
package/README.md
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
npm install @kispi/chat
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
이 문서가 **표면 전체**를 적는다.
|
|
13
|
+
이 문서가 **표면 전체**를 적는다. 여기 없는 것은 내부 구현이고, 다음 버전에
|
|
14
|
+
말 없이 바뀐다. 시작하는 법도 여기 있다.
|
|
14
15
|
|
|
15
16
|
---
|
|
16
17
|
|
|
@@ -20,17 +21,19 @@ npm install @kispi/chat
|
|
|
20
21
|
|
|
21
22
|
| 옵션 | 타입 | |
|
|
22
23
|
|---|---|---|
|
|
23
|
-
| `url` | `string` | **필수.** 오리진만 준다. SDK가 `/v1/ws?v=1`을 붙인다 |
|
|
24
24
|
| `key` | `string` | **필수.** `pk_`. 공개값이라 브라우저에 넣어도 된다 |
|
|
25
25
|
| `token` | `() => string \| Promise<string>` | **필수.** 백엔드가 서명한 유저 토큰. 접속할 때마다, 그리고 REST가 401을 받을 때 다시 부르므로 만료된 것이 재사용되지 않는다. 던지면 백오프로 다시 부르고, **`ChatError`를 던지면 다시 부르지 않는다**(아래) |
|
|
26
|
-
| `
|
|
27
|
-
| `externalToken` | `() => string \| Promise<string>` | external 모드. 주면 **`token`보다 우선한다**(서버의 판정 순서와 같다). **서버가 아직 거절하므로 오늘은 쓸 곳이 없다** |
|
|
28
|
-
| `WebSocket` | `new (url) => WebSocketLike` | 전역 대신 쓸 구현. 테스트에서 주입한다 |
|
|
26
|
+
| `WebSocket` | `new (url) => WebSocketLike` | 전역 대신 쓸 구현 |
|
|
29
27
|
| `fetch` | `typeof fetch` | 위와 같음 |
|
|
30
28
|
|
|
31
29
|
`token`을 브라우저에서 만들지 않는다. 서명에 `sk_`가 필요하고, `sk_`가
|
|
32
30
|
브라우저에 있으면 그 앱 전체가 열린다.
|
|
33
31
|
|
|
32
|
+
**주소는 설정하지 않는다.** 엔진은 `wss://api.chat.gravex.app` 하나이고
|
|
33
|
+
SDK가 상수로 들고 있다(`ChatEndpoint`로 읽을 수 있다). REST도 같은 곳이다 —
|
|
34
|
+
스킴만 바뀐다. 개발용과 운영용을 나누려면 **콘솔에서 앱을 따로 만든다**:
|
|
35
|
+
앱이 다르면 `pk_`·`sk_`·방·유저가 전부 다르고, 그것이 실제로 원하는 분리다.
|
|
36
|
+
|
|
34
37
|
### `ChatClient`
|
|
35
38
|
|
|
36
39
|
| 프로퍼티 | |
|
|
@@ -38,7 +41,7 @@ npm install @kispi/chat
|
|
|
38
41
|
| `state` | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` |
|
|
39
42
|
| `user` | 접속한 사람. `{id, name, avatar?}` — **서버가 토큰에서 받아들인 신원**(hello가 준 것)이다. 토큰 응답을 따로 파싱하지 말고 이것을 쓴다. `connect()`/`reconnect()`가 끝나면 채워져 있다 |
|
|
40
43
|
| `connectionId` | 지원 문의와 강제 종료에 쓰는 식별자 |
|
|
41
|
-
| `hello` | 서버가 접속 때 준 것
|
|
44
|
+
| `hello` | 서버가 접속 때 준 것 전부. `limits`(실효 한도), `unread`(`{total, mentions, roomsCapped?}`, **없는 것은 0이 아니라 '못 셌다'이니 `unread()`로 복구한다**), `warnings`, `serverTime`, `heartbeatMs` |
|
|
42
45
|
|
|
43
46
|
| 메서드 | |
|
|
44
47
|
|---|---|
|
|
@@ -50,9 +53,8 @@ npm install @kispi/chat
|
|
|
50
53
|
| `rooms.list({cursor?, limit?})` | 내가 멤버인 방 + unread + 마지막 메시지 |
|
|
51
54
|
| `rooms.discover({type?, cursor?, limit?})` | 공개 방 탐색 |
|
|
52
55
|
| `rooms.members(roomId).list/add/remove` | 멤버 관리 |
|
|
53
|
-
| `unread()` |
|
|
56
|
+
| `unread()` | `{total, mentions, roomsCapped?, rooms}`. `chat.hello?.unread`와 **같은 이름**이다 |
|
|
54
57
|
| `updateMe(meta)` | 내 `meta`. **`name`과 `avatar`는 토큰 claim에서 온다** |
|
|
55
|
-
| `send(type, data?, timeoutMs?)` | 날 프레임. 표면에 없는 것을 부를 때만 |
|
|
56
58
|
|
|
57
59
|
| 이벤트 | |
|
|
58
60
|
|---|---|
|
|
@@ -87,18 +89,29 @@ off()
|
|
|
87
89
|
| `loadOlder({limit?})` | 가장 오래된 메시지 앞 페이지(기본 100)를 읽어 **`messages` 앞에 붙인다.** `{messages, hasMore}`. 스크롤을 올릴 때 쓴다. 목록이 비어 있으면(구독 전) 아무것도 읽지 않는다 |
|
|
88
90
|
| `history({before?, after?, limit?, view?})` | 과거를 직접 읽는다. **`messages`와 따로 논다.** `view`는 `'main'`, `'all'`, `{thread: id}` |
|
|
89
91
|
| `reload()` | 최근 페이지를 다시 읽는다 |
|
|
90
|
-
| `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등.
|
|
92
|
+
| `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등. **프레임보다 먼저** 그 행의 `myReactions`를 고치고, 서버가 거절하면 되돌린다. 개수는 건드리지 않는다 |
|
|
91
93
|
| `reactionsOf(messageId, {emoji?, cursor?, limit?})` | 누가 눌렀는지. **한 행은 (유저, 이모지) 쌍**이라 한 사람이 여러 줄일 수 있다. `limit` 기본 50 최대 100, 마지막 페이지의 `cursor`는 빈 문자열 |
|
|
92
94
|
| `markRead(seq, {threadId?})` | 읽음 커서 |
|
|
93
95
|
| `typing()` | 입력 중. 던지지 않는다 |
|
|
94
96
|
| `join()` / `leave()` | 멤버십 |
|
|
95
97
|
| `presenceList()` | 지금 이 방에 있는 사람 |
|
|
96
|
-
| `resume()` | 재접속 후 다시 구독. SDK가 알아서 부른다 |
|
|
97
98
|
|
|
98
|
-
이벤트 이름은 **와이어의 이름 그대로**다.
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
99
|
+
이벤트 이름은 **와이어의 이름 그대로**다. 페이로드는 `docs/protocol.md`의
|
|
100
|
+
모양대로 타입이 붙어 있다.
|
|
101
|
+
|
|
102
|
+
| 이벤트 | 페이로드 |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있다 |
|
|
105
|
+
| `message.deleted` | `{id, seq}`. `seq`는 그 메시지가 **발행될 때** 받은 값이다 |
|
|
106
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
107
|
+
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
108
|
+
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
|
|
109
|
+
| `typing` | `{userId}` |
|
|
110
|
+
| `read` | `{userId, seq, threadId?}` |
|
|
111
|
+
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
112
|
+
| `room.updated` | 방 객체(`unknown` — 서버 표현 그대로다) |
|
|
113
|
+
| `room.deleted` | `{roomId}` |
|
|
114
|
+
| `custom` | `rooms.custom(roomId, payload)`이 보낸 객체 그대로 |
|
|
102
115
|
|
|
103
116
|
와이어에 대응물이 없는 셋을 SDK가 더 낸다.
|
|
104
117
|
|
|
@@ -131,15 +144,32 @@ const messages = shallowRef<Message[]>([])
|
|
|
131
144
|
room.on('messages', m => (messages.value = m))
|
|
132
145
|
```
|
|
133
146
|
|
|
134
|
-
`$state`(깊은 프록시)나 `ref`로 감싸도 동작하지만 필요 없는 일을 한다.
|
|
135
|
-
배열을 제자리에서 고쳐 다시 내보내서, 참조로 비교하는 쪽에서는 화면이 멈췄다.
|
|
147
|
+
`$state`(깊은 프록시)나 `ref`로 감싸도 동작하지만 필요 없는 일을 한다.
|
|
136
148
|
|
|
137
149
|
**리액션: `reactions`는 모두의 개수, `myReactions`는 내가 누른 이모지다.** 둘 다
|
|
138
150
|
SDK가 라이브로 맞춘다 — 개수는 `reaction.*` 이벤트의 `count`로, `myReactions`는 그
|
|
139
151
|
이벤트의 `userId`가 `chat.user.id`일 때(다른 탭·기기에서 누른 것 포함)와 내
|
|
140
|
-
`react()`/`unreact()
|
|
152
|
+
`react()`/`unreact()`로. 둘 다 더하기가 아니라 덮어쓰기라 이벤트와 ack가 모두
|
|
141
153
|
와도 두 번 세지 않는다. 바뀐 행만 새 객체다.
|
|
142
154
|
|
|
155
|
+
**`myReactions`는 누른 즉시 바뀐다.** `react()`/`unreact()`는 프레임을 보내기 **전에**
|
|
156
|
+
그 행의 `myReactions`를 고치고 `messages`를 내보낸다. 그래서 누른 느낌이 왕복만큼
|
|
157
|
+
늦지 않는다 — 누른 값은 (나, 이모지)로 이미 정해져 있고 서버는 멱등이라, ack가
|
|
158
|
+
새로 알려 줄 것이 없다. 서버가 거절하거나(한도, 권한) ack가 못 오면(타임아웃,
|
|
159
|
+
끊김) 되돌린다. 단, 그 사이 더 새로운 값이 자리를 차지했으면 그대로 둔다: 뒤에 누른
|
|
160
|
+
값, 내 `userId`가 실린 `reaction.*` 이벤트, `reload()`나 재접속이 가져온 페이지가
|
|
161
|
+
모두 대기 중인 낙관값을 이긴다. 거절이 낡은 값을 되살리는 일은 없다.
|
|
162
|
+
**이 필드의 주인은 SDK다** — 위에 자기 낙관 계층을 덧대면 주인이 둘이 된다.
|
|
163
|
+
|
|
164
|
+
**개수(`reactions[].count`)는 늘 서버 값이다.** 로컬에서 ±1하지 않는다. ack를
|
|
165
|
+
기다리는 사이 남이 같은 이모지를 누르면 로컬 계산은 서버가 보낼 수와 어긋나고,
|
|
166
|
+
그 차이를 고쳐 줄 이벤트는 이미 지나갔다. 개수는 `reaction.*` 이벤트가 옮긴다.
|
|
167
|
+
|
|
168
|
+
**발행(`send()`)은 일부러 낙관적이지 않다.** `before_publish` 훅이 본문을 바꿀 수
|
|
169
|
+
있어서(이모지 필터, 링크 치환) 미리 그릴 값이 클라이언트에 없다. 메시지는
|
|
170
|
+
`message.created`가 올 때 목록에 들어간다. 보내는 중 표시가 필요하면 그것은 소비자의
|
|
171
|
+
화면 상태이고, 리액션과 달리 SDK가 대신 정해 줄 수 없다.
|
|
172
|
+
|
|
143
173
|
**과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는
|
|
144
174
|
직접 읽기라, 그 결과를 라이브 목록과 합치고 중복을 거르고 `reset`과 재접속을
|
|
145
175
|
처리하는 일이 전부 소비자 몫이 된다. `loadOlder()`는 그 행들을 `messages`에 넣으므로
|
|
@@ -147,6 +177,13 @@ SDK가 라이브로 맞춘다 — 개수는 `reaction.*` 이벤트의 `count`로
|
|
|
147
177
|
불러도 요청은 하나이고, `hasMore`가 `false`면 방(또는 보존 기간)의 맨 앞이다.
|
|
148
178
|
`reset`이나 `reload()`는 붙인 과거도 함께 버린다.
|
|
149
179
|
|
|
180
|
+
**`hasOlder`와 `loadOlder()`는 SDK의 목록을 말한다, 당신의 창이 아니라.** SDK는
|
|
181
|
+
`room.messages`를 줄이지 않는다 — 500건을 들고 있으면 500건이 다 거기 있다. 화면
|
|
182
|
+
성능 때문에 받은 배열을 100건으로 잘라 그리고 있다면, 더 보여 줄 400건은 서버가
|
|
183
|
+
아니라 `room.messages`에 있다. 그때 `hasOlder`가 `false`인 것은 맞는 답이다(방의
|
|
184
|
+
맨 앞이라는 뜻이다). 창을 넓히는 일은 `room.messages`를 다시 읽는 것이고, 서버에
|
|
185
|
+
묻는 것은 그 다음이다.
|
|
186
|
+
|
|
150
187
|
```ts
|
|
151
188
|
showLoadMore(room.hasOlder)
|
|
152
189
|
const { hasMore } = await room.loadOlder()
|
|
@@ -161,10 +198,9 @@ const { hasMore } = await room.loadOlder()
|
|
|
161
198
|
**키로 연다고 방이 생기지 않는다.** `roomByKey(key).subscribe()`는 있는 방을 찾기만
|
|
162
199
|
하고, 없으면 `not_found`다. 방은 백엔드가 `sk_`로 만든다
|
|
163
200
|
(`@kispi/chat/server`의 `rooms.ensure({key, type})` — 있으면 그대로 돌려주는
|
|
164
|
-
get-or-create라 페이지를 열 때마다 불러도 된다).
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
끄는 쪽을 권한다.
|
|
201
|
+
get-or-create라 페이지를 열 때마다 불러도 된다). 유저 토큰으로 방을 만들게 하는 앱 설정도
|
|
202
|
+
있지만 기본은 꺼져 있고 콘솔에서 켤 수 없다 — `pk_`는 공개값이라, 켜면 누구나 방을
|
|
203
|
+
찍어낼 수 있는 문이 된다.
|
|
168
204
|
|
|
169
205
|
**연결은 알아서 돌아온다.** 소켓이 끊기거나 `token()`이 던지면 지수 백오프(0.5초에서
|
|
170
206
|
30초까지, 지터)로 다시 붙는다. **첫 `connect()`도 같다** — 실패하면 `await`는 거절해서
|
|
@@ -260,10 +296,10 @@ chat-server key create <app-id> pk --origins https://staging.example.com
|
|
|
260
296
|
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
261
297
|
```
|
|
262
298
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
REST
|
|
266
|
-
|
|
299
|
+
**접속도 같은 목록을 본다.** WebSocket은 브라우저 CORS의 대상이 아니지만, 엔진이
|
|
300
|
+
핸드셰이크에서 `pk_`의 `allowed_origins`를 직접 검사한다. 그래서 목록에 없는
|
|
301
|
+
오리진에서는 REST만이 아니라 접속부터 막히고, 인증 거절은 SDK가 다시 시도하지 않는
|
|
302
|
+
실패라 클라이언트가 `closed`에서 멈춘다 — 이유는 `chat.on('error')`로 온다.
|
|
267
303
|
|
|
268
304
|
### 에러
|
|
269
305
|
|
|
@@ -281,7 +317,7 @@ try {
|
|
|
281
317
|
|
|
282
318
|
| 필드 | |
|
|
283
319
|
|---|---|
|
|
284
|
-
| `code` | `unauthorized`, `
|
|
320
|
+
| `code` | 알려진 값의 유니온(`ChatErrorCode`)이라 오타가 컴파일에서 잡힌다. 서버: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. SDK: `timeout`, `closed`. 서버가 새 코드를 내도 좁혀 놓은 타입이 막지 않는다 |
|
|
285
321
|
| `retryAfterMs` | 한도에 걸렸을 때 서버가 알려 준 대기 시간 |
|
|
286
322
|
| `appCode` | `before_publish` 웹훅이 거절하며 붙인 소비자 쪽 코드 |
|
|
287
323
|
| `status` | REST 호출에서 난 에러면 HTTP 상태 |
|
|
@@ -296,14 +332,16 @@ try {
|
|
|
296
332
|
import { createChatServer } from '@kispi/chat/server'
|
|
297
333
|
|
|
298
334
|
const chat = createChatServer({
|
|
299
|
-
|
|
300
|
-
secretKey: process.env.CHAT_SECRET_KEY!,
|
|
301
|
-
keyId: process.env.CHAT_KEY_ID!,
|
|
335
|
+
secretKey: process.env.CHAT_SECRET_KEY!, // sk_…
|
|
302
336
|
webhookSecret: process.env.CHAT_WEBHOOK_SECRET,
|
|
303
337
|
guestSecret: process.env.CHAT_GUEST_SECRET, // guest()를 쓸 때만
|
|
304
338
|
})
|
|
305
339
|
```
|
|
306
340
|
|
|
341
|
+
키 하나면 된다. 어느 키로 서명했는지를 서버에 알리는 값(`kid`)은 `sk_`
|
|
342
|
+
안에 들어 있어서 SDK가 거기서 읽는다 — 콘솔의 키 ID를 따로 넣지 않는다.
|
|
343
|
+
주소도 클라이언트와 같이 상수다.
|
|
344
|
+
|
|
307
345
|
### `chat.token(input): string`
|
|
308
346
|
|
|
309
347
|
네트워크를 타지 않는 로컬 서명이다.
|
|
@@ -355,9 +393,9 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
355
393
|
|---|---|
|
|
356
394
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
357
395
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
358
|
-
| `users` | `list({cursor?, limit?})`, `update`, `
|
|
396
|
+
| `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?})` |
|
|
359
397
|
| `events` | `list({after?, limit?})` — outbox. 놓친 웹훅을 따라잡는다 |
|
|
360
|
-
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` |
|
|
398
|
+
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance`는 밀리초 |
|
|
361
399
|
|
|
362
400
|
`rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
|
|
363
401
|
`capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
|
|
@@ -366,7 +404,7 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
366
404
|
전부 지우되(tombstone: seq는 그대로, 보고 있는 클라이언트에는 `message.deleted`가
|
|
367
405
|
간다) **탈퇴시키지 않는다.** 이름도 남는다. 스팸이면 **밴을 먼저** 하고 부른다 — 도는
|
|
368
406
|
사이에 올라온 메시지는 목록에 없다. 한 번에 상한만큼만 하므로 `purgeCapped`가
|
|
369
|
-
`true`인 동안 다시 부른다. 탈퇴한 유저는 404다(그때는 `
|
|
407
|
+
`true`인 동안 다시 부른다. 탈퇴한 유저는 404다(그때는 `withdraw(userId, {purgeMessages: true})`).
|
|
370
408
|
|
|
371
409
|
```ts
|
|
372
410
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
@@ -413,18 +451,3 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
|
|
|
413
451
|
세 가지를 지킨다. `verify`가 서명과 시각(기본 5분)을 보고, **중복 제거는 직접**
|
|
414
452
|
해야 하며(`delivery`로), 10초 안에 2xx로 답해야 한다. 넘기면 실패로 치고 백오프가
|
|
415
453
|
시작된다.
|
|
416
|
-
|
|
417
|
-
---
|
|
418
|
-
|
|
419
|
-
## 개발
|
|
420
|
-
|
|
421
|
-
```sh
|
|
422
|
-
pnpm install
|
|
423
|
-
pnpm build # ESM + CJS + 타입 선언
|
|
424
|
-
pnpm exec vitest run
|
|
425
|
-
pnpm exec tsc --noEmit
|
|
426
|
-
```
|
|
427
|
-
|
|
428
|
-
테스트는 목이 아니라 **주입**을 쓴다. `WebSocket`과 `fetch`를 갈아 끼우면 서버를
|
|
429
|
-
흉내 낼 필요가 없고, 통합 계열 파일은 아예 **살아 있는 서버**에 붙는다. 실행에는
|
|
430
|
-
Postgres와 Redis가 필요하다.
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
// src/endpoint.ts
|
|
2
|
+
var ChatEndpoint = "wss://api.chat.gravex.app";
|
|
3
|
+
function restURLFrom(socketURL) {
|
|
4
|
+
if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
|
|
5
|
+
if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
|
|
6
|
+
return socketURL;
|
|
7
|
+
}
|
|
8
|
+
|
|
1
9
|
// src/errors.ts
|
|
2
10
|
var ChatError = class extends Error {
|
|
3
11
|
code;
|
|
@@ -5,7 +13,13 @@ var ChatError = class extends Error {
|
|
|
5
13
|
retryAfterMs;
|
|
6
14
|
/** The consumer's own code, when a before_publish hook denied this. */
|
|
7
15
|
appCode;
|
|
8
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The HTTP status, when this came from a REST call.
|
|
18
|
+
*
|
|
19
|
+
* 읽기 전용이다. 이 값은 실패를 만든 응답의 성질이지 나중에 붙이는
|
|
20
|
+
* 꼬리표가 아니고, 쓸 수 있게 두면 소비자가 고쳐 쓴 상태가 SDK가
|
|
21
|
+
* 붙인 것과 구별되지 않는다.
|
|
22
|
+
*/
|
|
9
23
|
status;
|
|
10
24
|
constructor(code, message, extra) {
|
|
11
25
|
super(message);
|
|
@@ -13,9 +27,10 @@ var ChatError = class extends Error {
|
|
|
13
27
|
this.code = code;
|
|
14
28
|
if (extra?.retryAfterMs !== void 0) this.retryAfterMs = extra.retryAfterMs;
|
|
15
29
|
if (extra?.appCode !== void 0) this.appCode = extra.appCode;
|
|
30
|
+
if (extra?.status !== void 0) this.status = extra.status;
|
|
16
31
|
}
|
|
17
32
|
};
|
|
18
|
-
function errorFrom(data, fallback = "the server refused the request") {
|
|
33
|
+
function errorFrom(data, fallback = "the server refused the request", status) {
|
|
19
34
|
if (typeof data === "object" && data !== null) {
|
|
20
35
|
const d = data;
|
|
21
36
|
const inner = d["error"] ?? d;
|
|
@@ -24,12 +39,15 @@ function errorFrom(data, fallback = "the server refused the request") {
|
|
|
24
39
|
const extra = {};
|
|
25
40
|
if (typeof inner["retryAfterMs"] === "number") extra.retryAfterMs = inner["retryAfterMs"];
|
|
26
41
|
if (typeof inner["appCode"] === "string") extra.appCode = inner["appCode"];
|
|
42
|
+
if (status !== void 0) extra.status = status;
|
|
27
43
|
return new ChatError(code, message, extra);
|
|
28
44
|
}
|
|
29
|
-
return new ChatError("internal", fallback);
|
|
45
|
+
return new ChatError("internal", fallback, status === void 0 ? void 0 : { status });
|
|
30
46
|
}
|
|
31
47
|
|
|
32
48
|
export {
|
|
49
|
+
ChatEndpoint,
|
|
50
|
+
restURLFrom,
|
|
33
51
|
ChatError,
|
|
34
52
|
errorFrom
|
|
35
53
|
};
|