@kispi/chat 0.2.3 → 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/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
+ ChatEndpoint,
2
3
  ChatError,
3
- errorFrom
4
- } from "./chunk-5QQRM7BH.js";
4
+ errorFrom,
5
+ restURLFrom
6
+ } from "./chunk-WSBOTTBM.js";
5
7
 
6
8
  // src/emitter.ts
7
9
  var Emitter = class {
@@ -87,9 +89,7 @@ var Rest = class {
87
89
  const text = await res.text();
88
90
  const parsed = text === "" ? void 0 : JSON.parse(text);
89
91
  if (!res.ok) {
90
- const err = errorFrom(parsed, `${method} ${path} failed with ${res.status}`);
91
- err.status = res.status;
92
- throw err;
92
+ throw errorFrom(parsed, `${method} ${path} failed with ${res.status}`, res.status);
93
93
  }
94
94
  return parsed;
95
95
  }
@@ -103,11 +103,6 @@ function queryString(query) {
103
103
  const s = params.toString();
104
104
  return s === "" ? "" : `?${s}`;
105
105
  }
106
- function restURLFrom(socketURL) {
107
- if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
108
- if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
109
- return socketURL;
110
- }
111
106
 
112
107
  // src/timeline.ts
113
108
  var MaxPageSize = 100;
@@ -772,7 +767,7 @@ var Room = class extends Emitter {
772
767
  async toggleReaction(messageId, emoji, mine) {
773
768
  const press = this.timeline.pressReaction(messageId, emoji, mine);
774
769
  try {
775
- await this.chat.send("react", {
770
+ await this.chat.sendFrame("react", {
776
771
  roomId: await this.resolveId("reacting"),
777
772
  messageId,
778
773
  emoji,
@@ -795,7 +790,7 @@ var Room = class extends Emitter {
795
790
  async markRead(seq, options = {}) {
796
791
  const data = { roomId: await this.resolveId("marking read"), seq };
797
792
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
798
- return await this.chat.send("read", data);
793
+ return await this.chat.sendFrame("read", data);
799
794
  }
800
795
  /**
801
796
  * Says this user is typing.
@@ -813,7 +808,7 @@ var Room = class extends Emitter {
813
808
  */
814
809
  typing() {
815
810
  try {
816
- void this.chat.send("typing", { roomId: this.requireId("typing") }).catch(() => {
811
+ void this.chat.sendFrame("typing", { roomId: this.requireId("typing") }).catch(() => {
817
812
  });
818
813
  } catch {
819
814
  }
@@ -847,6 +842,7 @@ var Room = class extends Emitter {
847
842
  });
848
843
  }
849
844
  /**
845
+ * @internal
850
846
  * Re-subscribes after a reconnect. Called by the client.
851
847
  *
852
848
  * The test is "was this room ever asked for", not "did the last
@@ -864,6 +860,7 @@ var Room = class extends Emitter {
864
860
  await this.subscribe();
865
861
  }
866
862
  /**
863
+ * @internal
867
864
  * Reports a failure no caller was waiting for, and repairs.
868
865
  *
869
866
  * 백그라운드 실패(재접속 뒤 다시 구독, 구멍 메우기)에는 거절을 받을 호출자가
@@ -894,13 +891,13 @@ var Room = class extends Emitter {
894
891
  */
895
892
  async subscribeFrame(data) {
896
893
  try {
897
- return { ack: await this.chat.send("subscribe", data), wasReset: false };
894
+ return { ack: await this.chat.sendFrame("subscribe", data), wasReset: false };
898
895
  } catch (err) {
899
896
  if (err.code !== "cursor_too_old") throw err;
900
897
  this.timeline.discard();
901
898
  const retry = { ...data };
902
899
  delete retry["since"];
903
- return { ack: await this.chat.send("subscribe", retry), wasReset: true };
900
+ return { ack: await this.chat.sendFrame("subscribe", retry), wasReset: true };
904
901
  }
905
902
  }
906
903
  async unsubscribe() {
@@ -909,7 +906,7 @@ var Room = class extends Emitter {
909
906
  this.subscribed = false;
910
907
  this.generation++;
911
908
  this.subscribing = void 0;
912
- await this.chat.send("unsubscribe", { roomId: this.id });
909
+ await this.chat.sendFrame("unsubscribe", { roomId: this.id });
913
910
  }
914
911
  /**
915
912
  * The room's id, or a refusal.
@@ -954,9 +951,9 @@ var Room = class extends Emitter {
954
951
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
955
952
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
956
953
  if (input.meta !== void 0) frame["meta"] = input.meta;
957
- return await this.chat.send("publish", frame);
954
+ return await this.chat.sendFrame("publish", frame);
958
955
  }
959
- /** Routes a frame the client decided belongs to this room. */
956
+ /** @internal Routes a frame the client decided belongs to this room. */
960
957
  handle(type, data) {
961
958
  switch (type) {
962
959
  case "message.created":
@@ -1029,6 +1026,8 @@ var ChatClient = class extends Emitter {
1029
1026
  connectionId;
1030
1027
  hello;
1031
1028
  options;
1029
+ /** 소켓 주소. 상수이고, 테스트만 `endpoint`로 바꾼다. */
1030
+ socketURL;
1032
1031
  makeSocket;
1033
1032
  socket;
1034
1033
  heartbeat;
@@ -1067,6 +1066,7 @@ var ChatClient = class extends Emitter {
1067
1066
  constructor(options) {
1068
1067
  super();
1069
1068
  this.options = options;
1069
+ this.socketURL = options.endpoint ?? ChatEndpoint;
1070
1070
  const ctor = options.WebSocket ?? globalThis.WebSocket;
1071
1071
  if (ctor === void 0) {
1072
1072
  throw new TypeError(
@@ -1075,7 +1075,7 @@ var ChatClient = class extends Emitter {
1075
1075
  }
1076
1076
  this.makeSocket = ctor;
1077
1077
  this.rest = new Rest({
1078
- url: options.restURL ?? restURLFrom(options.url),
1078
+ url: restURLFrom(this.socketURL),
1079
1079
  key: options.key,
1080
1080
  token: async () => this.lastToken,
1081
1081
  refreshToken: () => this.refreshToken(),
@@ -1150,17 +1150,23 @@ var ChatClient = class extends Emitter {
1150
1150
  /**
1151
1151
  * The unread totals across every room this user is a member of.
1152
1152
  *
1153
- * The field names are the route's own: `unread` and `unreadMentions`,
1154
- * **not** the `total`/`mentions` that `hello.unread` uses for the same
1155
- * two numbers. The server says it both ways and the SDK does not pick
1156
- * a third; renaming here would mean a consumer reading the protocol
1157
- * document finds a name that does not exist in either place.
1153
+ * `{total, mentions}` — `chat.hello.unread`와 **같은 이름**이다. 와이어는
1154
+ * 같은 두 숫자를 두 가지로 부르고(hello는 `total`/`mentions`, 이 라우트는
1155
+ * `unread`/`unreadMentions`), 그것을 그대로 넘기면 배지 하나를 그리는
1156
+ * 코드가 어디서 읽었느냐에 따라 다른 필드를 봐야 한다. 두 출처가 한 타입
1157
+ * (`UnreadCounts`)이면 그 분기가 아예 없다.
1158
1158
  *
1159
1159
  * `roomsCapped` means the totals cover a subset -- this route does not
1160
1160
  * page, so past 500 rooms it stops counting and says so.
1161
1161
  */
1162
1162
  async unread() {
1163
- return this.rest.get("/v1/me/unread");
1163
+ const body = await this.rest.get("/v1/me/unread");
1164
+ return {
1165
+ total: body.unread,
1166
+ mentions: body.unreadMentions,
1167
+ ...body.roomsCapped === void 0 ? {} : { roomsCapped: body.roomsCapped },
1168
+ rooms: (body.rooms ?? []).map((r) => ({ roomId: r.roomId, total: r.unread, mentions: r.unreadMentions }))
1169
+ };
1164
1170
  }
1165
1171
  /**
1166
1172
  * Updates this user's own profile.
@@ -1201,6 +1207,7 @@ var ChatClient = class extends Emitter {
1201
1207
  return room;
1202
1208
  }
1203
1209
  /**
1210
+ * @internal
1204
1211
  * Files a room under its id once `subscribe` has resolved one.
1205
1212
  *
1206
1213
  * A room addressed by key is filed under `key:<key>`, and every push
@@ -1324,6 +1331,7 @@ var ChatClient = class extends Emitter {
1324
1331
  this.emit("error", err);
1325
1332
  }
1326
1333
  /**
1334
+ * @internal
1327
1335
  * Resolves once the connection is open. Used by `Room.subscribe`.
1328
1336
  *
1329
1337
  * 연결 전에 부른 `subscribe()`를 `closed`로 거절하면 소비자는 "언제 다시
@@ -1345,8 +1353,16 @@ var ChatClient = class extends Emitter {
1345
1353
  else w.reject(err);
1346
1354
  }
1347
1355
  }
1348
- /** Sends a frame and resolves with its ack, or rejects with its error. */
1349
- send(type, data, timeoutMs = 15e3) {
1356
+ /**
1357
+ * @internal
1358
+ * Sends a raw frame and resolves with its ack, or rejects with its error.
1359
+ *
1360
+ * `Room`이 자기 프레임을 내보내는 통로다. 예전 이름은 `chat.send()`였고,
1361
+ * 그 이름은 `room.send()`(메시지 발행) 옆에서 "이걸로도 보낼 수 있나"로
1362
+ * 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
1363
+ * 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
1364
+ */
1365
+ sendFrame(type, data, timeoutMs = 15e3) {
1350
1366
  const socket = this.socket;
1351
1367
  if (socket === void 0 || this.state !== "open") {
1352
1368
  return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
@@ -1400,7 +1416,7 @@ var ChatClient = class extends Emitter {
1400
1416
  if (this.stopped) {
1401
1417
  throw new ChatError("closed", "the client was closed while connecting");
1402
1418
  }
1403
- const socket = new this.makeSocket(`${this.options.url}/v1/ws?v=1`);
1419
+ const socket = new this.makeSocket(`${this.socketURL}/v1/ws?v=1`);
1404
1420
  this.socket = socket;
1405
1421
  return new Promise((resolve, reject) => {
1406
1422
  let settled = false;
@@ -1562,10 +1578,6 @@ var ChatClient = class extends Emitter {
1562
1578
  }
1563
1579
  async authData() {
1564
1580
  const data = { key: this.options.key };
1565
- if (this.options.externalToken !== void 0) {
1566
- data["externalToken"] = await this.options.externalToken();
1567
- return data;
1568
- }
1569
1581
  const token = await this.options.token();
1570
1582
  this.lastToken = token;
1571
1583
  data["token"] = token;
@@ -1580,7 +1592,6 @@ var ChatClient = class extends Emitter {
1580
1592
  * 각자 부르지 않도록 진행 중인 것 하나를 나눠 쓴다.
1581
1593
  */
1582
1594
  refreshToken() {
1583
- if (this.options.externalToken !== void 0) return Promise.resolve(void 0);
1584
1595
  this.refreshing ??= (async () => {
1585
1596
  try {
1586
1597
  const token = await this.options.token();
@@ -1618,9 +1629,8 @@ function createChatClient(options) {
1618
1629
  }
1619
1630
  export {
1620
1631
  ChatClient,
1632
+ ChatEndpoint,
1621
1633
  ChatError,
1622
1634
  Room,
1623
- Timeline,
1624
- createChatClient,
1625
- createTimeline
1635
+ createChatClient
1626
1636
  };
@@ -28,6 +28,14 @@ __export(server_exports, {
28
28
  });
29
29
  module.exports = __toCommonJS(server_exports);
30
30
 
31
+ // src/endpoint.ts
32
+ var ChatEndpoint = "wss://api.chat.gravex.app";
33
+ function restURLFrom(socketURL) {
34
+ if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
35
+ if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
36
+ return socketURL;
37
+ }
38
+
31
39
  // src/errors.ts
32
40
  var ChatError = class extends Error {
33
41
  code;
@@ -35,7 +43,13 @@ var ChatError = class extends Error {
35
43
  retryAfterMs;
36
44
  /** The consumer's own code, when a before_publish hook denied this. */
37
45
  appCode;
38
- /** The HTTP status, when this came from a REST call. */
46
+ /**
47
+ * The HTTP status, when this came from a REST call.
48
+ *
49
+ * 읽기 전용이다. 이 값은 실패를 만든 응답의 성질이지 나중에 붙이는
50
+ * 꼬리표가 아니고, 쓸 수 있게 두면 소비자가 고쳐 쓴 상태가 SDK가
51
+ * 붙인 것과 구별되지 않는다.
52
+ */
39
53
  status;
40
54
  constructor(code, message, extra) {
41
55
  super(message);
@@ -43,9 +57,10 @@ var ChatError = class extends Error {
43
57
  this.code = code;
44
58
  if (extra?.retryAfterMs !== void 0) this.retryAfterMs = extra.retryAfterMs;
45
59
  if (extra?.appCode !== void 0) this.appCode = extra.appCode;
60
+ if (extra?.status !== void 0) this.status = extra.status;
46
61
  }
47
62
  };
48
- function errorFrom(data, fallback = "the server refused the request") {
63
+ function errorFrom(data, fallback = "the server refused the request", status) {
49
64
  if (typeof data === "object" && data !== null) {
50
65
  const d = data;
51
66
  const inner = d["error"] ?? d;
@@ -54,9 +69,10 @@ function errorFrom(data, fallback = "the server refused the request") {
54
69
  const extra = {};
55
70
  if (typeof inner["retryAfterMs"] === "number") extra.retryAfterMs = inner["retryAfterMs"];
56
71
  if (typeof inner["appCode"] === "string") extra.appCode = inner["appCode"];
72
+ if (status !== void 0) extra.status = status;
57
73
  return new ChatError(code, message, extra);
58
74
  }
59
- return new ChatError("internal", fallback);
75
+ return new ChatError("internal", fallback, status === void 0 ? void 0 : { status });
60
76
  }
61
77
 
62
78
  // src/server/api.ts
@@ -235,17 +251,23 @@ function createChatServer(options) {
235
251
  if (!options.secretKey.startsWith("sk_")) {
236
252
  throw new TypeError("secretKey must be an sk_ key; a pk_ cannot sign tokens or reach server routes");
237
253
  }
238
- if (options.keyId === "") {
239
- throw new TypeError("keyId is required: it becomes the token's kid, which tells the server which key signed it");
240
- }
241
- const rest = new ServerRest(options.url, options.secretKey, options.fetch ?? globalThis.fetch.bind(globalThis));
254
+ const keyId = keyIdFrom(options.secretKey);
255
+ const rest = new ServerRest(
256
+ restURLFrom(options.endpoint ?? ChatEndpoint),
257
+ options.secretKey,
258
+ options.fetch ?? globalThis.fetch.bind(globalThis)
259
+ );
242
260
  const guestSecrets = options.guestSecret === void 0 ? [] : typeof options.guestSecret === "string" ? [options.guestSecret] : options.guestSecret;
243
261
  for (const secret of guestSecrets) {
244
262
  if (secret.length < MinGuestSecretLength) {
245
263
  throw new RangeError(`guestSecret must be at least ${MinGuestSecretLength} characters`);
246
264
  }
247
265
  }
248
- const sign = (input) => signHS256({ alg: "HS256", typ: "JWT", kid: options.keyId }, tokenClaims(input, /* @__PURE__ */ new Date()), options.secretKey);
266
+ const sign = (input) => signHS256(
267
+ { alg: "HS256", typ: "JWT", ...keyId === void 0 ? {} : { kid: keyId } },
268
+ tokenClaims(input, /* @__PURE__ */ new Date()),
269
+ options.secretKey
270
+ );
249
271
  return {
250
272
  token: sign,
251
273
  guest(input) {
@@ -320,7 +342,7 @@ function createChatServer(options) {
320
342
  // with 200 and `purgedMessages: 0`, the identity anonymized and
321
343
  // the messages left standing. Nothing failed; the caller was told
322
344
  // it had worked.
323
- delete: (userId, o) => rest.call("DELETE", `/v1/users/${userId}${rest.query({ purge_messages: o?.purgeMessages ? "true" : void 0 })}`),
345
+ withdraw: (userId, o) => rest.call("DELETE", `/v1/users/${userId}${rest.query({ purge_messages: o?.purgeMessages ? "true" : void 0 })}`),
324
346
  purgeMessages: (userId) => rest.call("DELETE", `/v1/users/${userId}/messages`),
325
347
  revokeTokens: async (userId) => {
326
348
  await rest.call("POST", `/v1/users/${userId}/revoke-tokens`);
@@ -352,6 +374,12 @@ function createChatServer(options) {
352
374
  }
353
375
  };
354
376
  }
377
+ function keyIdFrom(secretKey) {
378
+ const parts = secretKey.split("_");
379
+ if (parts.length < 3) return void 0;
380
+ const id = parts[1];
381
+ return id !== void 0 && /^[0-9A-HJKMNP-TV-Z]{13}$/.test(id) ? id : void 0;
382
+ }
355
383
  // Annotate the CommonJS export names for ESM import in node:
356
384
  0 && (module.exports = {
357
385
  DefaultTokenTtlSeconds,
@@ -58,20 +58,15 @@ type VerifyOptions = {
58
58
  declare const GuestIdPrefix = "g_";
59
59
 
60
60
  type ChatServerOptions = {
61
- /** The chat server's base URL, e.g. `https://chat.example.com`. */
62
- url: string;
63
- /** An `sk_` key. Never ship this to a browser. */
64
- secretKey: string;
65
61
  /**
66
- * The id of the row that `secretKey` came from, printed by
67
- * `chat-server app create --json`.
62
+ * An `sk_` key. Never ship this to a browser.
68
63
  *
69
- * It goes in the token's `kid`, which tells the server which key to
70
- * verify with. Without it the server tries every unrevoked `sk_` the
71
- * app has -- which works, and is the compatibility path for tokens
72
- * minted before this SDK existed, not a mode to choose.
64
+ * 키가 자기 id를 안에 들고 있다(`sk_<id>_<토큰>`). 그래서 토큰의
65
+ * `kid`를 이것에서 뽑는다 — 키 id를 따로 받던 옵션이 있던 동안, 그
66
+ * 둘이 어긋난 배포(키는 돌렸는데 id는 옛것)는 "서명은 맞는데 401"로만
67
+ * 보였고 그 둘을 대조할 방법이 소비자 쪽에 없었다.
73
68
  */
74
- keyId: string;
69
+ secretKey: string;
75
70
  /** Needed only by `webhooks.verify`. */
76
71
  webhookSecret?: string;
77
72
  /**
@@ -251,11 +246,22 @@ type ChatServer = {
251
246
  * Ban first (`ban`), then call this: a message posted while it runs is
252
247
  * not in its listing. Bounded per call -- loop while `purgeCapped`.
253
248
  * A withdrawn user is 404; their messages go with
254
- * `delete(userId, { purgeMessages: true })`.
249
+ * `withdraw(userId, { purgeMessages: true })`.
255
250
  */
256
251
  purgeMessages: (userId: string) => Promise<PurgeMessagesResult>;
257
- /** Withdrawal: anonymises rather than deleting rows. */
258
- delete: (userId: string, options?: {
252
+ /**
253
+ * 탈퇴. 행을 지우는 것이 아니라 **익명화**한다.
254
+ *
255
+ * 이름이 `delete`였을 때 그것은 옆의 `rooms.delete`·`messages.delete`와
256
+ * 같은 말로 읽혔고, 그 둘은 정말로 없앤다. 여기서 남는 것은 메시지다
257
+ * — `purgeMessages: true`를 주지 않으면 그 사람이 쓴 글은 그대로
258
+ * 있고, 그 차이를 이름이 감추고 있었다. `withdraw`는 무엇이 일어나는지
259
+ * 말하고, 지우는 쪽을 고르라고 한다.
260
+ *
261
+ * `purgeMessages: true`는 상한까지만 지운다. 끝까지 지우려면
262
+ * `purgeMessages(userId)`를 `purgeCapped`가 `false`가 될 때까지 부른다.
263
+ */
264
+ withdraw: (userId: string, options?: {
259
265
  purgeMessages?: boolean;
260
266
  }) => Promise<unknown>;
261
267
  revokeTokens: (userId: string) => Promise<void>;
@@ -58,20 +58,15 @@ type VerifyOptions = {
58
58
  declare const GuestIdPrefix = "g_";
59
59
 
60
60
  type ChatServerOptions = {
61
- /** The chat server's base URL, e.g. `https://chat.example.com`. */
62
- url: string;
63
- /** An `sk_` key. Never ship this to a browser. */
64
- secretKey: string;
65
61
  /**
66
- * The id of the row that `secretKey` came from, printed by
67
- * `chat-server app create --json`.
62
+ * An `sk_` key. Never ship this to a browser.
68
63
  *
69
- * It goes in the token's `kid`, which tells the server which key to
70
- * verify with. Without it the server tries every unrevoked `sk_` the
71
- * app has -- which works, and is the compatibility path for tokens
72
- * minted before this SDK existed, not a mode to choose.
64
+ * 키가 자기 id를 안에 들고 있다(`sk_<id>_<토큰>`). 그래서 토큰의
65
+ * `kid`를 이것에서 뽑는다 — 키 id를 따로 받던 옵션이 있던 동안, 그
66
+ * 둘이 어긋난 배포(키는 돌렸는데 id는 옛것)는 "서명은 맞는데 401"로만
67
+ * 보였고 그 둘을 대조할 방법이 소비자 쪽에 없었다.
73
68
  */
74
- keyId: string;
69
+ secretKey: string;
75
70
  /** Needed only by `webhooks.verify`. */
76
71
  webhookSecret?: string;
77
72
  /**
@@ -251,11 +246,22 @@ type ChatServer = {
251
246
  * Ban first (`ban`), then call this: a message posted while it runs is
252
247
  * not in its listing. Bounded per call -- loop while `purgeCapped`.
253
248
  * A withdrawn user is 404; their messages go with
254
- * `delete(userId, { purgeMessages: true })`.
249
+ * `withdraw(userId, { purgeMessages: true })`.
255
250
  */
256
251
  purgeMessages: (userId: string) => Promise<PurgeMessagesResult>;
257
- /** Withdrawal: anonymises rather than deleting rows. */
258
- delete: (userId: string, options?: {
252
+ /**
253
+ * 탈퇴. 행을 지우는 것이 아니라 **익명화**한다.
254
+ *
255
+ * 이름이 `delete`였을 때 그것은 옆의 `rooms.delete`·`messages.delete`와
256
+ * 같은 말로 읽혔고, 그 둘은 정말로 없앤다. 여기서 남는 것은 메시지다
257
+ * — `purgeMessages: true`를 주지 않으면 그 사람이 쓴 글은 그대로
258
+ * 있고, 그 차이를 이름이 감추고 있었다. `withdraw`는 무엇이 일어나는지
259
+ * 말하고, 지우는 쪽을 고르라고 한다.
260
+ *
261
+ * `purgeMessages: true`는 상한까지만 지운다. 끝까지 지우려면
262
+ * `purgeMessages(userId)`를 `purgeCapped`가 `false`가 될 때까지 부른다.
263
+ */
264
+ withdraw: (userId: string, options?: {
259
265
  purgeMessages?: boolean;
260
266
  }) => Promise<unknown>;
261
267
  revokeTokens: (userId: string) => Promise<void>;
@@ -1,6 +1,8 @@
1
1
  import {
2
- errorFrom
3
- } from "../chunk-5QQRM7BH.js";
2
+ ChatEndpoint,
3
+ errorFrom,
4
+ restURLFrom
5
+ } from "../chunk-WSBOTTBM.js";
4
6
 
5
7
  // src/server/api.ts
6
8
  var ServerRest = class {
@@ -178,17 +180,23 @@ function createChatServer(options) {
178
180
  if (!options.secretKey.startsWith("sk_")) {
179
181
  throw new TypeError("secretKey must be an sk_ key; a pk_ cannot sign tokens or reach server routes");
180
182
  }
181
- if (options.keyId === "") {
182
- throw new TypeError("keyId is required: it becomes the token's kid, which tells the server which key signed it");
183
- }
184
- const rest = new ServerRest(options.url, options.secretKey, options.fetch ?? globalThis.fetch.bind(globalThis));
183
+ const keyId = keyIdFrom(options.secretKey);
184
+ const rest = new ServerRest(
185
+ restURLFrom(options.endpoint ?? ChatEndpoint),
186
+ options.secretKey,
187
+ options.fetch ?? globalThis.fetch.bind(globalThis)
188
+ );
185
189
  const guestSecrets = options.guestSecret === void 0 ? [] : typeof options.guestSecret === "string" ? [options.guestSecret] : options.guestSecret;
186
190
  for (const secret of guestSecrets) {
187
191
  if (secret.length < MinGuestSecretLength) {
188
192
  throw new RangeError(`guestSecret must be at least ${MinGuestSecretLength} characters`);
189
193
  }
190
194
  }
191
- const sign = (input) => signHS256({ alg: "HS256", typ: "JWT", kid: options.keyId }, tokenClaims(input, /* @__PURE__ */ new Date()), options.secretKey);
195
+ const sign = (input) => signHS256(
196
+ { alg: "HS256", typ: "JWT", ...keyId === void 0 ? {} : { kid: keyId } },
197
+ tokenClaims(input, /* @__PURE__ */ new Date()),
198
+ options.secretKey
199
+ );
192
200
  return {
193
201
  token: sign,
194
202
  guest(input) {
@@ -263,7 +271,7 @@ function createChatServer(options) {
263
271
  // with 200 and `purgedMessages: 0`, the identity anonymized and
264
272
  // the messages left standing. Nothing failed; the caller was told
265
273
  // it had worked.
266
- delete: (userId, o) => rest.call("DELETE", `/v1/users/${userId}${rest.query({ purge_messages: o?.purgeMessages ? "true" : void 0 })}`),
274
+ withdraw: (userId, o) => rest.call("DELETE", `/v1/users/${userId}${rest.query({ purge_messages: o?.purgeMessages ? "true" : void 0 })}`),
267
275
  purgeMessages: (userId) => rest.call("DELETE", `/v1/users/${userId}/messages`),
268
276
  revokeTokens: async (userId) => {
269
277
  await rest.call("POST", `/v1/users/${userId}/revoke-tokens`);
@@ -295,6 +303,12 @@ function createChatServer(options) {
295
303
  }
296
304
  };
297
305
  }
306
+ function keyIdFrom(secretKey) {
307
+ const parts = secretKey.split("_");
308
+ if (parts.length < 3) return void 0;
309
+ const id = parts[1];
310
+ return id !== void 0 && /^[0-9A-HJKMNP-TV-Z]{13}$/.test(id) ? id : void 0;
311
+ }
298
312
  export {
299
313
  DefaultTokenTtlSeconds,
300
314
  GuestIdPrefix,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
5
5
  "license": "MIT",
6
6
  "type": "module",