@kispi/chat 0.7.1 → 0.7.3

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
@@ -1,7 +1,10 @@
1
1
  # @kispi/chat
2
2
 
3
- Client SDK for the chat server. Many rooms over one socket, history in the right order.
4
- **Zero runtime dependencies**, both ESM and CJS, type declarations included.
3
+ Client SDK for [GravEx Chat](https://chat.gravex.app/en?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme), a managed realtime chat API.
4
+ Many rooms over one socket, history in the right order. **Zero runtime dependencies**, both ESM and CJS, type declarations included.
5
+
6
+ - **Get keys:** sign up in the [console](https://console.chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme) to get a `ck_`; your code creates apps and `pk_`/`sk_` keys through the console API.
7
+ - **Hand it to your AI:** example prompts at [/docs/ai](https://chat.gravex.app/en/docs/ai?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme), agent summary at [llms.txt](https://chat.gravex.app/llms.txt).
5
8
 
6
9
  There are two entry points. `@kispi/chat` is the client for the browser and Node;
7
10
  `@kispi/chat/server` is for the consumer backend that holds the `sk_`.
@@ -96,10 +99,10 @@ Event names are **exactly the wire names**, and the payloads are in the type dec
96
99
 
97
100
  | Event | Payload |
98
101
  |---|---|
99
- | `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
102
+ | `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent, `reactions` is empty, and **the SDK fills `myReactions` with `[]`** (the wire carries none) |
100
103
  | `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
101
104
  | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. The SDK has already updated that row's `reactions` count in `messages` (and `myReactions` if it was yours). **Rows outside the list**, such as ones read with `history()`, are the consumer's to update |
102
- | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
105
+ | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}`. The SDK has already updated **the root row's `thread`** (`count`, `lastSeq`, `lastAt`) in `messages`. A root outside the list is the consumer's to update |
103
106
  | `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
104
107
  | `typing` | `{userId, threadId?}` -- `threadId` is the thread **root** id, absent for the main timeline |
105
108
  | `read` | `{userId, seq, threadId?}` |
@@ -139,6 +142,21 @@ room.on('messages', m => (messages.value = m))
139
142
  that nobody fills.
140
143
  - **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
141
144
  doesn't touch the list, so merging and deduplicating fall to you.
145
+ - **Draw reaction chips from `reactions` and `myReactions` together.** `react()` moves
146
+ `myReactions` first and waits for `reaction.added` for the count, so an emoji you are the first
147
+ to add sits briefly in `myReactions` only. Draw that chip as **the highlighted emoji alone** (no
148
+ count) rather than inventing a `1` — someone else may have pressed it in between.
149
+ - **Each message has a cap on distinct emoji** (`hello.limits.maxDistinctEmojiPerMessage`, 20 by
150
+ default). A new emoji past it is refused with `invalid` and the SDK rolls `myReactions` back.
151
+ Pressing an emoji already on the message is never capped. To disable a picker, check that
152
+ `reactions.length` has reached the cap and the emoji is not among them.
153
+ - **A thread panel merges two sources.** `messages` holds replies only for the range the SDK has
154
+ read (it is the whole room's stream, so an old thread's replies are not in it). Read past replies
155
+ with `history({view: {thread: rootId}})`, pick new ones from `messages` by
156
+ `threadId === rootId`, and **merge by id.** Rows read with `history()` are outside the list, so
157
+ **you apply** `reaction.added`/`removed` (the count, and `myReactions` when `userId` is yours),
158
+ `message.updated` and `message.deleted` to them yourself — miss it and only the older replies'
159
+ reactions look frozen. Read again on `reset`.
142
160
  - **`typing` is also delivered to the sender.** If you render "X is typing", skip your own `userId`.
143
161
  - **`typing` carries no name.** Look the name up in `room.presence.users` — whoever is
144
162
  watching the room is there. Collecting names from message senders misses anyone who has not
@@ -226,6 +244,12 @@ From an origin that isn't on the list it isn't just REST that fails — **the co
226
244
  is a 401.** An authentication refusal is a failure the SDK doesn't retry, so the client stops
227
245
  at `closed`, and the reason arrives on `chat.on('error')`.
228
246
 
247
+ **On Node (bots, tests) there is no origin to add.** The server accepts a request with **no**
248
+ `Origin` header without an origin check — Node's global `WebSocket` and `fetch` don't send one,
249
+ so they connect as is. If you set the header yourself, its value must be on the allowed list.
250
+ The origin list only stops another site from using your `pk_` in a visitor's browser (a `pk_` is
251
+ public). A user token is required everywhere.
252
+
229
253
  ### Errors
230
254
 
231
255
  Failures are `ChatError`.
package/README.md CHANGED
@@ -1,7 +1,10 @@
1
1
  # @kispi/chat
2
2
 
3
- 채팅 서버의 클라이언트 SDK. 소켓 하나에 방 여러 개, 순서가 맞는 히스토리.
4
- **런타임 의존성 0개**, ESM과 CJS 둘 다, 타입 선언 포함.
3
+ [GravEx Chat](https://chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme)(관리형 실시간 채팅 API)의 클라이언트 SDK.
4
+ 소켓 하나에 방 여러 개, 순서가 맞는 히스토리. **런타임 의존성 0개**, ESM과 CJS 둘 다, 타입 선언 포함.
5
+
6
+ - **키 받기:** [콘솔](https://console.chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme)에서 가입하면 `ck_`가 나오고, 앱과 `pk_`·`sk_`는 콘솔 API로 코드가 만든다.
7
+ - **AI에게 시키기:** [/docs/ai](https://chat.gravex.app/docs/ai?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme)의 예시 프롬프트, 에이전트용 요약은 [llms.txt](https://chat.gravex.app/llms.txt).
5
8
 
6
9
  진입점이 둘이다. `@kispi/chat`은 브라우저와 Node에서 쓰는 클라이언트,
7
10
  `@kispi/chat/server`는 `sk_`를 들고 도는 소비자 백엔드용이다.
@@ -96,10 +99,10 @@ off()
96
99
 
97
100
  | 이벤트 | 페이로드 |
98
101
  |---|---|
99
- | `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있다 |
102
+ | `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있으며, `myReactions`는 **SDK가 `[]`로 채운다**(와이어에는 없다) |
100
103
  | `message.deleted` | `{id, seq}`. `seq`는 그 메시지가 **발행될 때** 받은 값이다 |
101
104
  | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. SDK가 `messages` 안의 그 행의 `reactions` 개수를(내 것이면 `myReactions`도) 이미 고쳐 두었다. `history()`로 따로 읽은 행처럼 **목록 밖의 행은 소비자가 고친다** |
102
- | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
105
+ | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}`. SDK가 `messages` 안의 **루트 행 `thread`**(`count`·`lastSeq`·`lastAt`)를 이미 고쳐 두었다. 목록 밖의 루트는 소비자가 고친다 |
103
106
  | `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
104
107
  | `typing` | `{userId, threadId?}` — `threadId`는 스레드 **루트** id, 본 타임라인이면 없다 |
105
108
  | `read` | `{userId, seq, threadId?}` |
@@ -137,6 +140,17 @@ room.on('messages', m => (messages.value = m))
137
140
  - **`reset`을 무시하면 안 된다.** 옛 목록에 이어 붙이면 아무도 메우지 않는 구멍이 남는다.
138
141
  - **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는 직접
139
142
  읽기이므로 합치고 중복을 거르는 일이 소비자 몫이 된다.
143
+ - **리액션 칩은 `reactions`와 `myReactions`를 합쳐 그린다.** `react()`는 `myReactions`를 먼저 옮기고
144
+ 개수는 `reaction.added`를 기다리므로, 처음 다는 이모지는 잠깐 `myReactions`에만 있다. 그 칩은
145
+ **강조한 이모지만**(개수 없이) 그리고, `1`을 지어내지 않는다 — 그 사이 남이 눌렀으면 틀린 숫자다.
146
+ - **이모지 종류에는 메시지당 상한이 있다**(`hello.limits.maxDistinctEmojiPerMessage`, 기본 20). 넘는 새
147
+ 이모지는 `invalid`로 거절되고 SDK가 `myReactions`를 되돌린다. 이미 달린 이모지를 누르는 것은 상한과
148
+ 무관하다. 피커를 막으려면 `reactions.length`가 상한에 닿았고 그 이모지가 없을 때 비활성화한다.
149
+ - **스레드 패널은 두 곳을 합친다.** `messages`에는 SDK가 읽은 구간의 답글만 있다(방 전체 스트림이라
150
+ 오래된 스레드의 답글은 없다). 지난 답글은 `history({view: {thread: rootId}})`로 읽고, 새 답글은
151
+ `messages`에서 `threadId === rootId`로 골라 **id로 합친다.** `history()`로 읽은 행은 목록 밖이라
152
+ `reaction.added`/`removed`(개수, 내 `userId`면 `myReactions`)와 `message.updated`·`message.deleted`를
153
+ **소비자가 직접 반영한다** — 빠뜨리면 지난 답글만 리액션이 멈춰 보인다. `reset`이면 다시 읽는다.
140
154
  - **`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를 건너뛴다.
141
155
  - **`typing`은 이름을 싣지 않는다.** 이름은 `room.presence.users`에서 찾는다 — 방을 보고 있는
142
156
  사람이 거기 있다. 메시지 발신자에서 이름을 모으면 아직 말하지 않은 사람을 모른다.
@@ -213,6 +227,11 @@ for (const part of splitByUrl(text)) {
213
227
  목록에 없는 오리진에서는 REST만이 아니라 **접속부터 401이다.** 인증 거절은 SDK가 다시
214
228
  시도하지 않으므로 클라이언트가 `closed`에서 멈추고, 이유는 `chat.on('error')`로 온다.
215
229
 
230
+ **Node(봇·테스트)에서는 오리진을 넣지 않는다.** 서버는 `Origin` 헤더가 **없는** 요청을 오리진
231
+ 검사 없이 받는다 — Node의 전역 `WebSocket`·`fetch`는 그 헤더를 보내지 않으므로 그대로 붙는다.
232
+ 헤더를 직접 붙이면 그 값은 허용 오리진에 있어야 한다. 오리진 목록은 남의 사이트가 방문자의 브라우저에서
233
+ 당신의 `pk_`를 쓰는 것만 막는다(`pk_`는 공개값이다). 유저 토큰은 어디서나 필요하다.
234
+
216
235
  ### 에러
217
236
 
218
237
  실패는 `ChatError`다.
package/dist/index.cjs CHANGED
@@ -460,13 +460,21 @@ var Timeline = class {
460
460
  this.items[at] = next;
461
461
  this.changed();
462
462
  }
463
- /** Applies a `thread.updated` to the root message's aggregate. */
464
- thread(rootId, count, lastSeq) {
463
+ /**
464
+ * Applies a `thread.updated` to the root message's aggregate.
465
+ *
466
+ * `lastAt`도 옮긴다. 히스토리 행의 `thread`는 `{count, lastSeq, lastAt}`이라,
467
+ * 빼고 바꾸면 "마지막 답글 3분 전"을 그리던 화면이 답글이 달리는 순간 그 값을 잃는다.
468
+ */
469
+ thread(rootId, count, lastSeq, lastAt) {
465
470
  const at = this.items.findIndex((m) => m.id === rootId);
466
471
  if (at === -1) return;
467
472
  const current = this.items[at];
473
+ const thread = { count };
474
+ if (lastSeq !== void 0) thread.lastSeq = lastSeq;
475
+ if (lastAt !== void 0) thread.lastAt = lastAt;
468
476
  this.own();
469
- this.items[at] = { ...current, thread: lastSeq === void 0 ? { count } : { count, lastSeq } };
477
+ this.items[at] = { ...current, thread };
470
478
  this.changed();
471
479
  }
472
480
  /** Applies a `message.deleted`, remembering it if the row is not here. */
@@ -1101,6 +1109,7 @@ var Room = class extends Emitter {
1101
1109
  switch (type) {
1102
1110
  case "message.created":
1103
1111
  if (data.seq > this.lastSeq) this.lastSeq = data.seq;
1112
+ if (data.myReactions === void 0) data = { ...data, myReactions: [] };
1104
1113
  this.timeline.add(data).catch((err) => {
1105
1114
  this.subscribed = false;
1106
1115
  this.failed(err);
@@ -1125,7 +1134,7 @@ var Room = class extends Emitter {
1125
1134
  }
1126
1135
  case "thread.updated": {
1127
1136
  const t = data;
1128
- this.timeline.thread(t.rootId, t.count, t.lastSeq);
1137
+ this.timeline.thread(t.rootId, t.count, t.lastSeq, t.lastAt);
1129
1138
  break;
1130
1139
  }
1131
1140
  case "presence":
package/dist/index.d.cts CHANGED
@@ -190,18 +190,25 @@ type Message = {
190
190
  * Filled by history reads and kept in step by the SDK afterwards: a
191
191
  * `reaction.*` event whose `userId` is `chat.user.id` updates it, and
192
192
  * this client's own `react()`/`unreact()` update it **before the frame
193
- * goes out**, rolling back if the server refuses. Absent on a row the
194
- * server rendered without a viewer (a live `message.created` has none
195
- * yet, which is the same as empty).
193
+ * goes out**, rolling back if the server refuses. A live
194
+ * `message.created` carries none on the wire (a room frame is the same
195
+ * bytes for every viewer), so the SDK fills it with `[]`: a message
196
+ * that was just published has no reactions, and an absent field reads
197
+ * as "no viewer", which is what it means on a REST row.
196
198
  *
197
199
  * The SDK owns this field, so a consumer does not need -- and should
198
200
  * not add -- an optimistic layer of its own on top of it. The count in
199
201
  * `reactions` is the opposite: always the server's, never moved locally.
200
202
  */
201
203
  myReactions?: string[];
204
+ /**
205
+ * The root's reply summary. The SDK keeps it current from
206
+ * `thread.updated` (count, `lastSeq`, `lastAt`) on rows in `messages`.
207
+ */
202
208
  thread?: {
203
209
  count: number;
204
210
  lastSeq?: number;
211
+ lastAt?: number;
205
212
  };
206
213
  };
207
214
  type ReactionUser = {
package/dist/index.d.ts CHANGED
@@ -190,18 +190,25 @@ type Message = {
190
190
  * Filled by history reads and kept in step by the SDK afterwards: a
191
191
  * `reaction.*` event whose `userId` is `chat.user.id` updates it, and
192
192
  * this client's own `react()`/`unreact()` update it **before the frame
193
- * goes out**, rolling back if the server refuses. Absent on a row the
194
- * server rendered without a viewer (a live `message.created` has none
195
- * yet, which is the same as empty).
193
+ * goes out**, rolling back if the server refuses. A live
194
+ * `message.created` carries none on the wire (a room frame is the same
195
+ * bytes for every viewer), so the SDK fills it with `[]`: a message
196
+ * that was just published has no reactions, and an absent field reads
197
+ * as "no viewer", which is what it means on a REST row.
196
198
  *
197
199
  * The SDK owns this field, so a consumer does not need -- and should
198
200
  * not add -- an optimistic layer of its own on top of it. The count in
199
201
  * `reactions` is the opposite: always the server's, never moved locally.
200
202
  */
201
203
  myReactions?: string[];
204
+ /**
205
+ * The root's reply summary. The SDK keeps it current from
206
+ * `thread.updated` (count, `lastSeq`, `lastAt`) on rows in `messages`.
207
+ */
202
208
  thread?: {
203
209
  count: number;
204
210
  lastSeq?: number;
211
+ lastAt?: number;
205
212
  };
206
213
  };
207
214
  type ReactionUser = {
package/dist/index.js CHANGED
@@ -390,13 +390,21 @@ var Timeline = class {
390
390
  this.items[at] = next;
391
391
  this.changed();
392
392
  }
393
- /** Applies a `thread.updated` to the root message's aggregate. */
394
- thread(rootId, count, lastSeq) {
393
+ /**
394
+ * Applies a `thread.updated` to the root message's aggregate.
395
+ *
396
+ * `lastAt`도 옮긴다. 히스토리 행의 `thread`는 `{count, lastSeq, lastAt}`이라,
397
+ * 빼고 바꾸면 "마지막 답글 3분 전"을 그리던 화면이 답글이 달리는 순간 그 값을 잃는다.
398
+ */
399
+ thread(rootId, count, lastSeq, lastAt) {
395
400
  const at = this.items.findIndex((m) => m.id === rootId);
396
401
  if (at === -1) return;
397
402
  const current = this.items[at];
403
+ const thread = { count };
404
+ if (lastSeq !== void 0) thread.lastSeq = lastSeq;
405
+ if (lastAt !== void 0) thread.lastAt = lastAt;
398
406
  this.own();
399
- this.items[at] = { ...current, thread: lastSeq === void 0 ? { count } : { count, lastSeq } };
407
+ this.items[at] = { ...current, thread };
400
408
  this.changed();
401
409
  }
402
410
  /** Applies a `message.deleted`, remembering it if the row is not here. */
@@ -1031,6 +1039,7 @@ var Room = class extends Emitter {
1031
1039
  switch (type) {
1032
1040
  case "message.created":
1033
1041
  if (data.seq > this.lastSeq) this.lastSeq = data.seq;
1042
+ if (data.myReactions === void 0) data = { ...data, myReactions: [] };
1034
1043
  this.timeline.add(data).catch((err) => {
1035
1044
  this.subscribed = false;
1036
1045
  this.failed(err);
@@ -1055,7 +1064,7 @@ var Room = class extends Emitter {
1055
1064
  }
1056
1065
  case "thread.updated": {
1057
1066
  const t = data;
1058
- this.timeline.thread(t.rootId, t.count, t.lastSeq);
1067
+ this.timeline.thread(t.rootId, t.count, t.lastSeq, t.lastAt);
1059
1068
  break;
1060
1069
  }
1061
1070
  case "presence":
package/package.json CHANGED
@@ -1,7 +1,18 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.7.1",
4
- "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
3
+ "version": "0.7.3",
4
+ "description": "GravEx Chat SDK: managed realtime chat API. One WebSocket, many rooms, ordered history. Get an API key at chat.gravex.app.",
5
+ "homepage": "https://chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme",
6
+ "keywords": [
7
+ "chat",
8
+ "chat-sdk",
9
+ "websocket",
10
+ "realtime",
11
+ "messaging",
12
+ "chat-api",
13
+ "typescript",
14
+ "agent-first"
15
+ ],
5
16
  "license": "MIT",
6
17
  "type": "module",
7
18
  "sideEffects": false,
@@ -41,7 +52,7 @@
41
52
  "@types/node": "^22.20.2",
42
53
  "tsup": "^8.5.0",
43
54
  "typescript": "^5.9.2",
44
- "vitest": "^4.1.11"
55
+ "vitest": "^4.1.12"
45
56
  },
46
57
  "engines": {
47
58
  "node": ">=22"