@kispi/chat 0.2.3 → 0.3.1

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/dist/index.cjs CHANGED
@@ -21,11 +21,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
23
  ChatClient: () => ChatClient,
24
+ ChatEndpoint: () => ChatEndpoint,
24
25
  ChatError: () => ChatError,
25
26
  Room: () => Room,
26
- Timeline: () => Timeline,
27
- createChatClient: () => createChatClient,
28
- createTimeline: () => createTimeline
27
+ createChatClient: () => createChatClient
29
28
  });
30
29
  module.exports = __toCommonJS(src_exports);
31
30
 
@@ -60,6 +59,14 @@ var Emitter = class {
60
59
  }
61
60
  };
62
61
 
62
+ // src/endpoint.ts
63
+ var ChatEndpoint = "wss://api.chat.gravex.app";
64
+ function restURLFrom(socketURL) {
65
+ if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
66
+ if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
67
+ return socketURL;
68
+ }
69
+
63
70
  // src/errors.ts
64
71
  var ChatError = class extends Error {
65
72
  code;
@@ -67,7 +74,13 @@ var ChatError = class extends Error {
67
74
  retryAfterMs;
68
75
  /** The consumer's own code, when a before_publish hook denied this. */
69
76
  appCode;
70
- /** The HTTP status, when this came from a REST call. */
77
+ /**
78
+ * The HTTP status, when this came from a REST call.
79
+ *
80
+ * 읽기 전용이다. 이 값은 실패를 만든 응답의 성질이지 나중에 붙이는
81
+ * 꼬리표가 아니고, 쓸 수 있게 두면 소비자가 고쳐 쓴 상태가 SDK가
82
+ * 붙인 것과 구별되지 않는다.
83
+ */
71
84
  status;
72
85
  constructor(code, message, extra) {
73
86
  super(message);
@@ -75,9 +88,10 @@ var ChatError = class extends Error {
75
88
  this.code = code;
76
89
  if (extra?.retryAfterMs !== void 0) this.retryAfterMs = extra.retryAfterMs;
77
90
  if (extra?.appCode !== void 0) this.appCode = extra.appCode;
91
+ if (extra?.status !== void 0) this.status = extra.status;
78
92
  }
79
93
  };
80
- function errorFrom(data, fallback = "the server refused the request") {
94
+ function errorFrom(data, fallback = "the server refused the request", status) {
81
95
  if (typeof data === "object" && data !== null) {
82
96
  const d = data;
83
97
  const inner = d["error"] ?? d;
@@ -86,9 +100,10 @@ function errorFrom(data, fallback = "the server refused the request") {
86
100
  const extra = {};
87
101
  if (typeof inner["retryAfterMs"] === "number") extra.retryAfterMs = inner["retryAfterMs"];
88
102
  if (typeof inner["appCode"] === "string") extra.appCode = inner["appCode"];
103
+ if (status !== void 0) extra.status = status;
89
104
  return new ChatError(code, message, extra);
90
105
  }
91
- return new ChatError("internal", fallback);
106
+ return new ChatError("internal", fallback, status === void 0 ? void 0 : { status });
92
107
  }
93
108
 
94
109
  // src/rest.ts
@@ -144,9 +159,7 @@ var Rest = class {
144
159
  const text = await res.text();
145
160
  const parsed = text === "" ? void 0 : JSON.parse(text);
146
161
  if (!res.ok) {
147
- const err = errorFrom(parsed, `${method} ${path} failed with ${res.status}`);
148
- err.status = res.status;
149
- throw err;
162
+ throw errorFrom(parsed, `${method} ${path} failed with ${res.status}`, res.status);
150
163
  }
151
164
  return parsed;
152
165
  }
@@ -160,11 +173,6 @@ function queryString(query) {
160
173
  const s = params.toString();
161
174
  return s === "" ? "" : `?${s}`;
162
175
  }
163
- function restURLFrom(socketURL) {
164
- if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
165
- if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
166
- return socketURL;
167
- }
168
176
 
169
177
  // src/timeline.ts
170
178
  var MaxPageSize = 100;
@@ -829,7 +837,7 @@ var Room = class extends Emitter {
829
837
  async toggleReaction(messageId, emoji, mine) {
830
838
  const press = this.timeline.pressReaction(messageId, emoji, mine);
831
839
  try {
832
- await this.chat.send("react", {
840
+ await this.chat.sendFrame("react", {
833
841
  roomId: await this.resolveId("reacting"),
834
842
  messageId,
835
843
  emoji,
@@ -852,7 +860,7 @@ var Room = class extends Emitter {
852
860
  async markRead(seq, options = {}) {
853
861
  const data = { roomId: await this.resolveId("marking read"), seq };
854
862
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
855
- return await this.chat.send("read", data);
863
+ return await this.chat.sendFrame("read", data);
856
864
  }
857
865
  /**
858
866
  * Says this user is typing.
@@ -870,7 +878,7 @@ var Room = class extends Emitter {
870
878
  */
871
879
  typing() {
872
880
  try {
873
- void this.chat.send("typing", { roomId: this.requireId("typing") }).catch(() => {
881
+ void this.chat.sendFrame("typing", { roomId: this.requireId("typing") }).catch(() => {
874
882
  });
875
883
  } catch {
876
884
  }
@@ -904,6 +912,7 @@ var Room = class extends Emitter {
904
912
  });
905
913
  }
906
914
  /**
915
+ * @internal
907
916
  * Re-subscribes after a reconnect. Called by the client.
908
917
  *
909
918
  * The test is "was this room ever asked for", not "did the last
@@ -921,6 +930,7 @@ var Room = class extends Emitter {
921
930
  await this.subscribe();
922
931
  }
923
932
  /**
933
+ * @internal
924
934
  * Reports a failure no caller was waiting for, and repairs.
925
935
  *
926
936
  * 백그라운드 실패(재접속 뒤 다시 구독, 구멍 메우기)에는 거절을 받을 호출자가
@@ -951,13 +961,13 @@ var Room = class extends Emitter {
951
961
  */
952
962
  async subscribeFrame(data) {
953
963
  try {
954
- return { ack: await this.chat.send("subscribe", data), wasReset: false };
964
+ return { ack: await this.chat.sendFrame("subscribe", data), wasReset: false };
955
965
  } catch (err) {
956
966
  if (err.code !== "cursor_too_old") throw err;
957
967
  this.timeline.discard();
958
968
  const retry = { ...data };
959
969
  delete retry["since"];
960
- return { ack: await this.chat.send("subscribe", retry), wasReset: true };
970
+ return { ack: await this.chat.sendFrame("subscribe", retry), wasReset: true };
961
971
  }
962
972
  }
963
973
  async unsubscribe() {
@@ -966,7 +976,7 @@ var Room = class extends Emitter {
966
976
  this.subscribed = false;
967
977
  this.generation++;
968
978
  this.subscribing = void 0;
969
- await this.chat.send("unsubscribe", { roomId: this.id });
979
+ await this.chat.sendFrame("unsubscribe", { roomId: this.id });
970
980
  }
971
981
  /**
972
982
  * The room's id, or a refusal.
@@ -1011,9 +1021,9 @@ var Room = class extends Emitter {
1011
1021
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
1012
1022
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
1013
1023
  if (input.meta !== void 0) frame["meta"] = input.meta;
1014
- return await this.chat.send("publish", frame);
1024
+ return await this.chat.sendFrame("publish", frame);
1015
1025
  }
1016
- /** Routes a frame the client decided belongs to this room. */
1026
+ /** @internal Routes a frame the client decided belongs to this room. */
1017
1027
  handle(type, data) {
1018
1028
  switch (type) {
1019
1029
  case "message.created":
@@ -1086,6 +1096,8 @@ var ChatClient = class extends Emitter {
1086
1096
  connectionId;
1087
1097
  hello;
1088
1098
  options;
1099
+ /** 소켓 주소. 상수이고, 테스트만 `endpoint`로 바꾼다. */
1100
+ socketURL;
1089
1101
  makeSocket;
1090
1102
  socket;
1091
1103
  heartbeat;
@@ -1124,6 +1136,7 @@ var ChatClient = class extends Emitter {
1124
1136
  constructor(options) {
1125
1137
  super();
1126
1138
  this.options = options;
1139
+ this.socketURL = options.endpoint ?? ChatEndpoint;
1127
1140
  const ctor = options.WebSocket ?? globalThis.WebSocket;
1128
1141
  if (ctor === void 0) {
1129
1142
  throw new TypeError(
@@ -1132,7 +1145,7 @@ var ChatClient = class extends Emitter {
1132
1145
  }
1133
1146
  this.makeSocket = ctor;
1134
1147
  this.rest = new Rest({
1135
- url: options.restURL ?? restURLFrom(options.url),
1148
+ url: restURLFrom(this.socketURL),
1136
1149
  key: options.key,
1137
1150
  token: async () => this.lastToken,
1138
1151
  refreshToken: () => this.refreshToken(),
@@ -1207,17 +1220,23 @@ var ChatClient = class extends Emitter {
1207
1220
  /**
1208
1221
  * The unread totals across every room this user is a member of.
1209
1222
  *
1210
- * The field names are the route's own: `unread` and `unreadMentions`,
1211
- * **not** the `total`/`mentions` that `hello.unread` uses for the same
1212
- * two numbers. The server says it both ways and the SDK does not pick
1213
- * a third; renaming here would mean a consumer reading the protocol
1214
- * document finds a name that does not exist in either place.
1223
+ * `{total, mentions}` — `chat.hello.unread`와 **같은 이름**이다. 와이어는
1224
+ * 같은 두 숫자를 두 가지로 부르고(hello는 `total`/`mentions`, 이 라우트는
1225
+ * `unread`/`unreadMentions`), 그것을 그대로 넘기면 배지 하나를 그리는
1226
+ * 코드가 어디서 읽었느냐에 따라 다른 필드를 봐야 한다. 두 출처가 한 타입
1227
+ * (`UnreadCounts`)이면 그 분기가 아예 없다.
1215
1228
  *
1216
1229
  * `roomsCapped` means the totals cover a subset -- this route does not
1217
1230
  * page, so past 500 rooms it stops counting and says so.
1218
1231
  */
1219
1232
  async unread() {
1220
- return this.rest.get("/v1/me/unread");
1233
+ const body = await this.rest.get("/v1/me/unread");
1234
+ return {
1235
+ total: body.unread,
1236
+ mentions: body.unreadMentions,
1237
+ ...body.roomsCapped === void 0 ? {} : { roomsCapped: body.roomsCapped },
1238
+ rooms: (body.rooms ?? []).map((r) => ({ roomId: r.roomId, total: r.unread, mentions: r.unreadMentions }))
1239
+ };
1221
1240
  }
1222
1241
  /**
1223
1242
  * Updates this user's own profile.
@@ -1258,6 +1277,7 @@ var ChatClient = class extends Emitter {
1258
1277
  return room;
1259
1278
  }
1260
1279
  /**
1280
+ * @internal
1261
1281
  * Files a room under its id once `subscribe` has resolved one.
1262
1282
  *
1263
1283
  * A room addressed by key is filed under `key:<key>`, and every push
@@ -1381,6 +1401,7 @@ var ChatClient = class extends Emitter {
1381
1401
  this.emit("error", err);
1382
1402
  }
1383
1403
  /**
1404
+ * @internal
1384
1405
  * Resolves once the connection is open. Used by `Room.subscribe`.
1385
1406
  *
1386
1407
  * 연결 전에 부른 `subscribe()`를 `closed`로 거절하면 소비자는 "언제 다시
@@ -1402,8 +1423,16 @@ var ChatClient = class extends Emitter {
1402
1423
  else w.reject(err);
1403
1424
  }
1404
1425
  }
1405
- /** Sends a frame and resolves with its ack, or rejects with its error. */
1406
- send(type, data, timeoutMs = 15e3) {
1426
+ /**
1427
+ * @internal
1428
+ * Sends a raw frame and resolves with its ack, or rejects with its error.
1429
+ *
1430
+ * `Room`이 자기 프레임을 내보내는 통로다. 예전 이름은 `chat.send()`였고,
1431
+ * 그 이름은 `room.send()`(메시지 발행) 옆에서 "이걸로도 보낼 수 있나"로
1432
+ * 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
1433
+ * 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
1434
+ */
1435
+ sendFrame(type, data, timeoutMs = 15e3) {
1407
1436
  const socket = this.socket;
1408
1437
  if (socket === void 0 || this.state !== "open") {
1409
1438
  return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
@@ -1457,7 +1486,7 @@ var ChatClient = class extends Emitter {
1457
1486
  if (this.stopped) {
1458
1487
  throw new ChatError("closed", "the client was closed while connecting");
1459
1488
  }
1460
- const socket = new this.makeSocket(`${this.options.url}/v1/ws?v=1`);
1489
+ const socket = new this.makeSocket(`${this.socketURL}/v1/ws?v=1`);
1461
1490
  this.socket = socket;
1462
1491
  return new Promise((resolve, reject) => {
1463
1492
  let settled = false;
@@ -1619,10 +1648,6 @@ var ChatClient = class extends Emitter {
1619
1648
  }
1620
1649
  async authData() {
1621
1650
  const data = { key: this.options.key };
1622
- if (this.options.externalToken !== void 0) {
1623
- data["externalToken"] = await this.options.externalToken();
1624
- return data;
1625
- }
1626
1651
  const token = await this.options.token();
1627
1652
  this.lastToken = token;
1628
1653
  data["token"] = token;
@@ -1637,7 +1662,6 @@ var ChatClient = class extends Emitter {
1637
1662
  * 각자 부르지 않도록 진행 중인 것 하나를 나눠 쓴다.
1638
1663
  */
1639
1664
  refreshToken() {
1640
- if (this.options.externalToken !== void 0) return Promise.resolve(void 0);
1641
1665
  this.refreshing ??= (async () => {
1642
1666
  try {
1643
1667
  const token = await this.options.token();
@@ -1676,9 +1700,8 @@ function createChatClient(options) {
1676
1700
  // Annotate the CommonJS export names for ESM import in node:
1677
1701
  0 && (module.exports = {
1678
1702
  ChatClient,
1703
+ ChatEndpoint,
1679
1704
  ChatError,
1680
1705
  Room,
1681
- Timeline,
1682
- createChatClient,
1683
- createTimeline
1706
+ createChatClient
1684
1707
  });