@noti-bot/sdk 0.13.0 → 0.15.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.md CHANGED
@@ -17,7 +17,7 @@ const kakao = new NotiBot({
17
17
 
18
18
  const rooms = await kakao.listRooms();
19
19
  const result = await kakao.sendMessage({
20
- roomId: process.env.KAKAO_ROOM_ID!,
20
+ roomId: process.env.NOTIBOT_ROOM_ID!,
21
21
  text: '배포가 완료되었습니다.',
22
22
  requestId: 'deploy:release-2026-10-10',
23
23
  });
@@ -48,7 +48,7 @@ const r = await kakao.getMessage('deploy:release-2026-10-10');
48
48
  import { mention } from '@noti-bot/sdk';
49
49
 
50
50
  await kakao.sendMessage({
51
- roomId: process.env.KAKAO_ROOM_ID!,
51
+ roomId: process.env.NOTIBOT_ROOM_ID!,
52
52
  text: `${mention(event.senderId!)} 접수했어요`,
53
53
  requestId: `ack:${event.event_id}`,
54
54
  });
@@ -60,7 +60,7 @@ await kakao.sendMessage({
60
60
 
61
61
  ```ts
62
62
  await kakao.sendMessage({
63
- roomId: process.env.KAKAO_ROOM_ID!,
63
+ roomId: process.env.NOTIBOT_ROOM_ID!,
64
64
  text: '확인했어요',
65
65
  replyTo: event.messageId,
66
66
  requestId: `ack:${event.event_id}`,
@@ -136,6 +136,28 @@ await bot.sendMessage({ room: event.room, text: answer, replyTo: event.messageId
136
136
  - `messages:send` 권한이 필요하고, 방마다 분당 30번까지입니다(넘으면 `429 rate_limited`, `body.scope: "room_typing"`). 아직 카톡 방과 연결되지 않은 방은 `409 typing_unsupported`.
137
137
  - 테스트 키는 `{ typing: false, test: true }`로 답하고 폰에 넘기지 않습니다.
138
138
 
139
+ ## 봇 넣기·빼기 (오픈채팅 링크, 나가기)
140
+
141
+ 카카오톡 오픈채팅은 친구 초대가 안 되므로 방 링크로 봇을 넣습니다. 봇폰이 처리하므로 접수만 하고, 결과는 `getRoomRequest`로 봅니다.
142
+
143
+ ```ts
144
+ const join = await bot.joinOpenChat({ url: "https://open.kakao.com/o/gAbCdEf1", code: "1234" }); // code 는 참여코드 방만
145
+ let r = join;
146
+ while (r.status === "queued" || r.status === "running") {
147
+ await new Promise((done) => setTimeout(done, 3000));
148
+ r = await bot.getRoomRequest(join.requestId);
149
+ }
150
+ if (r.status === "done") console.log(r.room?.name, r.connect); // connect: "pending" 이면 운영자 승인 대기
151
+ else console.log(r.reason, r.message); // 예: invalid_code, "코드를 잘못 입력했습니다."
152
+
153
+ await bot.leaveRoom({ roomSlug: "tf" }); // 또는 { roomId: "…" }
154
+ ```
155
+
156
+ - `rooms:manage` 권한이 있는 키가 필요합니다(기본 키에는 없습니다). 참여는 한 번에 하나, 하루 5번까지입니다.
157
+ - 들어간 뒤 처음 연결하는 방이면 운영자 승인을 기다립니다(`connect: "pending"`). 승인된 방이 있는 워크스페이스는 바로 연결됩니다.
158
+ - 나가면 방이 워크스페이스에서 풀립니다. 오픈채팅은 링크로 다시 넣을 수 있지만, 일반 그룹톡은 다시 초대해야 하고 1:1은 대화방이 지워집니다.
159
+ - 주요 `reason`: `invalid_link`, `code_required`, `invalid_code`, `phone_offline`, `kakao_status_<상태>`. `status: "unknown"`은 결과를 알 수 없다는 뜻이라 운영자가 확인합니다.
160
+
139
161
  ## 오류 처리
140
162
 
141
163
  모든 오류는 `NotiBotError`를 상속합니다. 한 번의 `catch`로 전부 받고, `name`이나 `instanceof`로 갈라 봅니다.
@@ -169,8 +191,25 @@ try {
169
191
  - 각 메서드의 두 번째 인자에 `{ signal }`을 넣어 취소할 수 있습니다.
170
192
  - `fetch`와 `timeoutMs`(기본 10초)를 생성자에서 주입할 수 있습니다.
171
193
 
194
+ ## API 버전
195
+
196
+ SDK는 모든 요청에 `NotiBot-Version` 헤더를 보냅니다. 값은 이 SDK가 만들어진 API 버전(`API_VERSION`, 지금은 `2026-12-01`)입니다.
197
+ 허브가 호환이 깨지는 변경을 새 날짜 버전으로 내도, SDK를 올리기 전에는 지금 받는 응답 모양이 그대로 유지됩니다.
198
+
199
+ ```ts
200
+ import { API_VERSION } from '@noti-bot/sdk';
201
+ console.log(API_VERSION); // "2026-12-01"
202
+ ```
203
+
204
+ - 경로의 `/v1`은 바뀌지 않습니다. 새 필드와 새 오류 코드는 버전을 올리지 않고 더해집니다.
205
+ - webhook 요청에도 같은 헤더가 붙습니다. 본문과 서명은 그대로입니다.
206
+ - 오래된 버전은 언젠가 종료됩니다. 종료하기 전에 릴리스 노트로 먼저 알립니다. 그때는 SDK를 올려야 합니다.
207
+ - 허브가 모르는 버전이면 `400 unsupported_api_version`(`NotiBotApiError`, `retryable: false`)입니다. 이 SDK보다 오래된 허브에 붙였을 때만 납니다.
208
+
172
209
  ## 변경 이력
173
210
 
211
+ - **0.15.0** — `joinOpenChat({ url, code? })`, `leaveRoom({ roomId | roomSlug })`, `getRoomRequest(requestId)`: 오픈채팅 링크로 봇 넣기·방에서 빼기(`rooms:manage`).
212
+ - **0.14.0** — 모든 요청에 `NotiBot-Version` 헤더를 보냅니다. `API_VERSION` export. 오류 코드 `unsupported_api_version`.
174
213
  - **0.13.0** — `setTyping({ room | roomId | roomSlug, durationSeconds? })`: 봇의 "입력 중" 표시(`POST /v1/typing`, `/v1/rooms/{slug}/typing`).
175
214
  - **0.9.0** — `getMessage(requestId)`: 보낸 메시지의 전달 결과(`GET /v1/messages/{requestId}`).
176
215
  - **0.8.0** — 워크스페이스 API 키(`nb_live_`/`nb_test_`). `kb_` 키는 더 이상 동작하지 않음. 콘솔에서 새로 발급해 교체하세요. `room_not_bound` 대신 `404 room_not_found`.
package/dist/errors.d.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  */
20
20
  export declare const NOTIBOT_ERROR_BRAND: unique symbol;
21
21
  /** 허브가 돌려주는 오류 코드. 서버 라우트(`src/outbound/routes.ts`)가 정본이다. */
22
- export declare const NOTIBOT_ERROR_CODES: readonly ["validation_error", "invalid_room_slug", "unauthorized", "plan_message_limit", "insufficient_scope", "room_not_found", "message_not_found", "room_inactive", "idempotency_conflict", "rate_limited", "kill_switch", "queue_full", "typing_unsupported", "request_failed"];
22
+ export declare const NOTIBOT_ERROR_CODES: readonly ["validation_error", "unsupported_api_version", "invalid_room_slug", "unauthorized", "plan_message_limit", "insufficient_scope", "room_not_found", "message_not_found", "room_inactive", "idempotency_conflict", "rate_limited", "kill_switch", "queue_full", "typing_unsupported", "request_failed"];
23
23
  export type NotiBotErrorCode = (typeof NOTIBOT_ERROR_CODES)[number];
24
24
  /**
25
25
  * 알려진 코드는 자동완성으로 뜨되, 허브가 새 코드를 추가해도 타입이 깨지지 않는다.
package/dist/errors.js CHANGED
@@ -21,6 +21,7 @@ export const NOTIBOT_ERROR_BRAND = Symbol.for("@noti-bot/sdk.error");
21
21
  /** 허브가 돌려주는 오류 코드. 서버 라우트(`src/outbound/routes.ts`)가 정본이다. */
22
22
  export const NOTIBOT_ERROR_CODES = [
23
23
  "validation_error",
24
+ "unsupported_api_version",
24
25
  "invalid_room_slug",
25
26
  "unauthorized",
26
27
  "plan_message_limit",
package/dist/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  export type { NotiBotErrorCode, NotiBotErrorCodeLike, NotiBotErrorJSON } from "./errors.js";
2
2
  export { isNotiBotError, NOTIBOT_ERROR_BRAND, NOTIBOT_ERROR_CODES, NotiBotApiError, NotiBotError, NotiBotProtocolError, NotiBotTimeoutError, NotiBotTransportError, } from "./errors.js";
3
+ /**
4
+ * The API version this SDK was built for. It is sent as `NotiBot-Version` on every request,
5
+ * so responses keep the shape this SDK knows until you upgrade the SDK.
6
+ */
7
+ export declare const API_VERSION = "2026-12-01";
3
8
  /**
4
9
  * Tag a member in `sendMessage` text: `` `${mention(ev.senderId)} 확인했어요` ``.
5
10
  * The bridge swaps it for `@표시이름` and sends a real Kakao mention (notification to that person).
@@ -176,6 +181,33 @@ export interface SetTypingResult {
176
181
  room?: string;
177
182
  test?: boolean;
178
183
  }
184
+ /** 봇 넣기(`join`)·빼기(`leave`) 요청의 상태. `queued`·`running` 이면 몇 초 뒤 `getRoomRequest` 로 다시 본다 */
185
+ export interface RoomRequest {
186
+ requestId: string;
187
+ kind: "join" | "leave";
188
+ /** done: 들어감/나감, failed: 카카오톡이 거절했거나 폰이 꺼져 있음, unknown: 결과를 알 수 없음 */
189
+ status: "queued" | "running" | "done" | "failed" | "unknown";
190
+ room: {
191
+ id: string;
192
+ name: string | null;
193
+ } | null;
194
+ /** join 이 끝난 뒤 연결 상태. `pending` 은 운영자 승인 대기 */
195
+ connect: "connected" | "pending" | "already_connected" | null;
196
+ /** 실패 사유(`code_required`, `invalid_code`, `invalid_link`, `phone_offline` …) */
197
+ reason: string | null;
198
+ /** 카카오톡이 보여 준 안내. 사용자에게 그대로 보여 줘도 된다 */
199
+ message: string | null;
200
+ createdAt: string;
201
+ finishedAt: string | null;
202
+ /** 테스트 키(`nb_test_`): 폰에 넘기지 않았다 */
203
+ test?: boolean;
204
+ }
205
+ export interface JoinOpenChatInput {
206
+ /** 오픈채팅 링크(`https://open.kakao.com/o/…`) */
207
+ url: string;
208
+ /** 참여코드(영문·숫자 4~8자). 코드가 걸린 방에서만 */
209
+ code?: string;
210
+ }
179
211
  export interface RequestOptions {
180
212
  signal?: AbortSignal;
181
213
  }
@@ -217,5 +249,22 @@ export declare class NotiBot {
217
249
  * 접수만 하고 기다리지 않으며, 상대에게 보였는지는 알 수 없다. `messages:send` 권한, 방마다 분당 30번.
218
250
  */
219
251
  setTyping(input: SetTypingInput, options?: RequestOptions): Promise<SetTypingResult>;
252
+ /**
253
+ * 오픈채팅 링크로 봇을 방에 넣는다(카카오톡 오픈채팅은 친구 초대가 안 된다). 폰이 처리하므로 접수만 하고,
254
+ * 결과는 `getRoomRequest(requestId)` 로 본다. 처음 연결하는 방이면 운영자 승인을 기다린다(`connect: "pending"`).
255
+ * `rooms:manage` 권한, 한 번에 하나, 하루 5번.
256
+ */
257
+ joinOpenChat(input: JoinOpenChatInput, options?: RequestOptions): Promise<RoomRequest>;
258
+ /**
259
+ * 봇이 방에서 나간다(카카오톡 "나가기"). 방은 이 워크스페이스에서 풀린다. 일반 그룹톡은 다시 초대해야 돌아오고,
260
+ * 1:1 은 대화방이 지워진다. 결과는 `getRoomRequest(requestId)`. `rooms:manage` 권한.
261
+ */
262
+ leaveRoom(room: {
263
+ roomId: string;
264
+ } | {
265
+ roomSlug: string;
266
+ }, options?: RequestOptions): Promise<RoomRequest>;
267
+ /** `joinOpenChat`·`leaveRoom` 요청의 현재 상태. `rooms:manage` 또는 `rooms:read` 권한 */
268
+ getRoomRequest(requestId: string, options?: RequestOptions): Promise<RoomRequest>;
220
269
  private request;
221
270
  }
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  export { isNotiBotError, NOTIBOT_ERROR_BRAND, NOTIBOT_ERROR_CODES, NotiBotApiError, NotiBotError, NotiBotProtocolError, NotiBotTimeoutError, NotiBotTransportError, } from "./errors.js";
2
2
  import { NotiBotApiError, NotiBotProtocolError, NotiBotTimeoutError, NotiBotTransportError, } from "./errors.js";
3
+ /**
4
+ * The API version this SDK was built for. It is sent as `NotiBot-Version` on every request,
5
+ * so responses keep the shape this SDK knows until you upgrade the SDK.
6
+ */
7
+ export const API_VERSION = "2026-12-01";
3
8
  /**
4
9
  * Tag a member in `sendMessage` text: `` `${mention(ev.senderId)} 확인했어요` ``.
5
10
  * The bridge swaps it for `@표시이름` and sends a real Kakao mention (notification to that person).
@@ -12,6 +17,50 @@ export function mention(kakaoUserId) {
12
17
  }
13
18
  /** Largest original image the hub accepts. */
14
19
  const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
20
+ const ROOM_REQUEST_STATUSES = ["queued", "running", "done", "failed", "unknown"];
21
+ function parseRoomRequest(data) {
22
+ if (!object(data))
23
+ throw new NotiBotProtocolError();
24
+ if (data.test === true && (data.kind === "join" || data.kind === "leave"))
25
+ return {
26
+ requestId: "",
27
+ kind: data.kind,
28
+ status: "queued",
29
+ room: null,
30
+ connect: null,
31
+ reason: null,
32
+ message: null,
33
+ createdAt: new Date().toISOString(),
34
+ finishedAt: null,
35
+ test: true,
36
+ };
37
+ const room = data.room;
38
+ if (typeof data.request_id !== "string" ||
39
+ (data.kind !== "join" && data.kind !== "leave") ||
40
+ !ROOM_REQUEST_STATUSES.includes(data.status) ||
41
+ (room !== null &&
42
+ !(object(room) &&
43
+ typeof room.id === "string" &&
44
+ (room.name === null || typeof room.name === "string"))) ||
45
+ typeof data.created_at !== "string")
46
+ throw new NotiBotProtocolError();
47
+ const str = (v) => (typeof v === "string" ? v : null);
48
+ return {
49
+ requestId: data.request_id,
50
+ kind: data.kind,
51
+ status: data.status,
52
+ room: room === null
53
+ ? null
54
+ : { id: room.id, name: str(room.name) },
55
+ connect: ["connected", "pending", "already_connected"].includes(data.connect)
56
+ ? data.connect
57
+ : null,
58
+ reason: str(data.reason),
59
+ message: str(data.message),
60
+ createdAt: data.created_at,
61
+ finishedAt: str(data.finished_at),
62
+ };
63
+ }
15
64
  function object(value) {
16
65
  return !!value && typeof value === "object" && !Array.isArray(value);
17
66
  }
@@ -206,6 +255,38 @@ export class NotiBot {
206
255
  ...(data.test === true ? { test: true } : {}),
207
256
  };
208
257
  }
258
+ /**
259
+ * 오픈채팅 링크로 봇을 방에 넣는다(카카오톡 오픈채팅은 친구 초대가 안 된다). 폰이 처리하므로 접수만 하고,
260
+ * 결과는 `getRoomRequest(requestId)` 로 본다. 처음 연결하는 방이면 운영자 승인을 기다린다(`connect: "pending"`).
261
+ * `rooms:manage` 권한, 한 번에 하나, 하루 5번.
262
+ */
263
+ async joinOpenChat(input, options = {}) {
264
+ if (!/^https:\/\/open\.kakao\.com\/o\/[A-Za-z0-9]{4,32}\/?$/.test(input.url?.trim() ?? ""))
265
+ throw new TypeError("url must be an open chat link (https://open.kakao.com/o/…).");
266
+ if (input.code !== undefined && !/^[A-Za-z0-9]{4,8}$/.test(input.code))
267
+ throw new TypeError("code must be 4 to 8 letters or digits.");
268
+ const data = await this.request("/v1/rooms/join", "POST", { url: input.url.trim(), ...(input.code ? { code: input.code } : {}) }, options.signal);
269
+ return parseRoomRequest(data);
270
+ }
271
+ /**
272
+ * 봇이 방에서 나간다(카카오톡 "나가기"). 방은 이 워크스페이스에서 풀린다. 일반 그룹톡은 다시 초대해야 돌아오고,
273
+ * 1:1 은 대화방이 지워진다. 결과는 `getRoomRequest(requestId)`. `rooms:manage` 권한.
274
+ */
275
+ async leaveRoom(room, options = {}) {
276
+ if ("roomId" in room ? !room.roomId?.trim() : !room.roomSlug?.trim())
277
+ throw new TypeError("roomId or roomSlug is required.");
278
+ const data = await this.request("roomId" in room
279
+ ? `/v1/rooms/id/${encodeURIComponent(room.roomId)}/leave`
280
+ : `/v1/rooms/${encodeURIComponent(room.roomSlug)}/leave`, "POST", {}, options.signal);
281
+ return parseRoomRequest(data);
282
+ }
283
+ /** `joinOpenChat`·`leaveRoom` 요청의 현재 상태. `rooms:manage` 또는 `rooms:read` 권한 */
284
+ async getRoomRequest(requestId, options = {}) {
285
+ if (!requestId?.trim())
286
+ throw new TypeError("requestId is required.");
287
+ const data = await this.request(`/v1/rooms/requests/${encodeURIComponent(requestId)}`, "GET", undefined, options.signal);
288
+ return parseRoomRequest(data);
289
+ }
209
290
  async request(path, method, body, signal, requestId) {
210
291
  const timeout = AbortSignal.timeout(this.timeoutMs);
211
292
  const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
@@ -217,6 +298,7 @@ export class NotiBot {
217
298
  headers: {
218
299
  Authorization: `Bearer ${this.apiKey}`,
219
300
  Accept: "application/json",
301
+ "NotiBot-Version": API_VERSION,
220
302
  // multipart: fetch sets the Content-Type with its boundary
221
303
  ...(body === undefined || body instanceof FormData
222
304
  ? {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noti-bot/sdk",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Typed server-side client for the NotiBot API",
5
5
  "license": "MIT",
6
6
  "author": "Jeongmin Lee",