@noti-bot/sdk 0.6.0 → 0.8.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
@@ -1,20 +1,18 @@
1
1
  # @noti-bot/sdk
2
2
 
3
- Kakao Bot Hub용 서버 측 TypeScript SDK입니다. 허브 주소는 `https://kakao-api.jeongmin.dev`, 서비스 API 키는 콘솔(`https://tok.jeongmin.dev`) 개발자 메뉴에서 발급합니다.
3
+ NotiBot용 서버 측 TypeScript SDK입니다. 허브 주소는 `https://api.notibot.xyz`, API 키(`nb_live_…` / `nb_test_…`)는 콘솔(`https://notibot.xyz`) API 키 화면에서 워크스페이스 단위로 발급합니다. 키 하나로 그 워크스페이스의 연결된 톡방 전체에 보낼 수 있고, 서비스·바인딩은 필요 없습니다.
4
4
 
5
5
  ```sh
6
6
  npm install @noti-bot/sdk
7
7
  # pnpm add @noti-bot/sdk
8
8
  ```
9
9
 
10
- > 0.5.0 까지는 `@kakao-bot/sdk` 이름으로 게시됐습니다. API는 같으니 패키지 이름과 import 경로만 바꾸면 됩니다.
11
-
12
10
  ```ts
13
- import { KakaoBot, KakaoApiError, KakaoTransportError } from '@noti-bot/sdk';
11
+ import { NotiBot, NotiBotApiError, NotiBotTransportError } from '@noti-bot/sdk';
14
12
 
15
- const kakao = new KakaoBot({
16
- baseUrl: process.env.KAKAO_HUB_URL ?? 'https://kakao-api.jeongmin.dev',
17
- apiKey: process.env.KAKAO_SERVICE_API_KEY!,
13
+ const kakao = new NotiBot({
14
+ baseUrl: process.env.NOTIBOT_URL ?? 'https://api.notibot.xyz',
15
+ apiKey: process.env.NOTIBOT_API_KEY!,
18
16
  });
19
17
 
20
18
  const rooms = await kakao.listRooms();
@@ -25,11 +23,11 @@ const result = await kakao.sendMessage({
25
23
  });
26
24
  ```
27
25
 
28
- Node.js 20 이상, ESM을 지원합니다. 서비스 키는 브라우저 번들에 넣지 마세요. SDK용 서비스 키와 개인 MCP 토큰은 별도입니다.
26
+ Node.js 20 이상, ESM을 지원합니다. API 키는 브라우저 번들에 넣지 마세요. SDK용 API 키(`nb_live_`/`nb_test_`)와 개인 MCP 토큰(`nbp_`)은 별도이며, 생성자는 `nb_live_`/`nb_test_`로 시작하지 않는 키를 `TypeError`로 거절합니다.
29
27
 
30
- `listRooms()`에서 방의 `id`, `slug`, `canReply`를 확인합니다. `roomId` 대신 `roomSlug: 'deploy-alerts'`도 사용할 수 있습니다. slug는 워크스페이스 안에서 고유하며 변경 시 이전 주소는 사용할 수 없습니다. 고정 ID 연동은 slug 변경 후에도 유지됩니다. 두 방식 모두 해당 API 키의 서비스에 연결된 방만 허용합니다.
28
+ `listRooms()`에서 방의 `id`, `slug`, `canReply`를 확인합니다. `roomId` 대신 `roomSlug: 'deploy-alerts'`도 사용할 수 있습니다. slug는 워크스페이스 안에서 고유하며 변경 시 이전 주소는 사용할 수 없습니다. 고정 ID 연동은 slug 변경 후에도 유지됩니다. 두 방식 모두 해당 API 키의 워크스페이스에 속한 active 방만 허용하며, 그 밖의 방은 `404 room_not_found`입니다.
31
29
 
32
- `queued: true`는 접수이며 실제 전달 성공이 아닙니다. 서버는 서비스별 `requestId`로 중복을 방지합니다. 같은 논리적 발송에는 같은 ID를 사용하세요. **SDK는 POST 또는 GET을 자동 재시도하지 않습니다.** 타임아웃은 이미 접수된 요청일 수 있으므로 새 ID로 재시도하면 중복 발송됩니다. `KakaoTransportError.requestId`로 요청을 식별하고 대시보드 로그를 확인하세요.
30
+ `queued: true`는 접수이며 실제 전달 성공이 아닙니다. 서버는 API 키별 `requestId`로 중복을 방지합니다. 같은 논리적 발송에는 같은 ID를 사용하세요. **SDK는 POST 또는 GET을 자동 재시도하지 않습니다.** 타임아웃은 이미 접수된 요청일 수 있으므로 새 ID로 재시도하면 중복 발송됩니다. `NotiBotTransportError.requestId`로 요청을 식별하고 대시보드 로그를 확인하세요.
33
31
 
34
32
  ## 멘션
35
33
 
@@ -47,7 +45,7 @@ await kakao.sendMessage({
47
45
  });
48
46
  ```
49
47
 
50
- 이름만 알면 `mentions`로 태그할 수 있습니다. 그 방 참여자 한 명으로 정해져야 보내고, 없거나 여럿이면 `KakaoApiError`(`mention_name_unknown` / `mention_name_ambiguous`, `body.candidates`)로 거절됩니다.
48
+ 이름만 알면 `mentions`로 태그할 수 있습니다. 그 방 참여자 한 명으로 정해져야 보내고, 없거나 여럿이면 `NotiBotApiError`(`mention_name_unknown` / `mention_name_ambiguous`, `body.candidates`)로 거절됩니다.
51
49
 
52
50
  ```ts
53
51
  await bot.sendMessage({ roomSlug: "tf", text: "@이현근 확인 부탁해요", mentions: ["이현근"] });
@@ -68,15 +66,15 @@ if (target) await bot.sendMessage({ roomSlug: "tf", text: `${target.mention} 확
68
66
 
69
67
  ## 오류 처리
70
68
 
71
- 모든 오류는 `KakaoError`를 상속합니다. 한 번의 `catch`로 전부 받고, `name`이나 `instanceof`로 갈라 봅니다.
69
+ 모든 오류는 `NotiBotError`를 상속합니다. 한 번의 `catch`로 전부 받고, `name`이나 `instanceof`로 갈라 봅니다.
72
70
 
73
71
  ```ts
74
- import { isKakaoError, KakaoApiError, KakaoTimeoutError } from '@noti-bot/sdk';
72
+ import { isNotiBotError, NotiBotApiError, NotiBotTimeoutError } from '@noti-bot/sdk';
75
73
 
76
74
  try {
77
75
  await kakao.sendMessage({ roomSlug: 'deploy-alerts', text: '배포 완료', requestId: 'deploy:42' });
78
76
  } catch (error) {
79
- if (!isKakaoError(error)) throw error; // 내 코드의 버그는 그대로 올려보냅니다
77
+ if (!isNotiBotError(error)) throw error; // 내 코드의 버그는 그대로 올려보냅니다
80
78
  logger.error(error.toJSON()); // 로그 한 줄로 바로 적을 수 있는 평평한 객체
81
79
  if (error.retryable) await scheduleRetry('deploy:42', error); // 같은 requestId 로만
82
80
  }
@@ -84,41 +82,45 @@ try {
84
82
 
85
83
  | 클래스 | 뜻 | `retryable` |
86
84
  |---|---|---|
87
- | `KakaoApiError` | 허브가 응답했지만 2xx가 아님 | 429·5xx는 `true`, 그 외 4xx는 `false` |
88
- | `KakaoTransportError` | 허브에 닿지 못함 | `true` |
89
- | `KakaoTimeoutError` | 제한 시간 초과 (`KakaoTransportError`의 하위) | `true` |
90
- | `KakaoProtocolError` | 2xx인데 본문이 계약과 다름 | `false` |
85
+ | `NotiBotApiError` | 허브가 응답했지만 2xx가 아님 | 429·5xx는 `true`, 그 외 4xx는 `false` |
86
+ | `NotiBotTransportError` | 허브에 닿지 못함 | `true` |
87
+ | `NotiBotTimeoutError` | 제한 시간 초과 (`NotiBotTransportError`의 하위) | `true` |
88
+ | `NotiBotProtocolError` | 2xx인데 본문이 계약과 다름 | `false` |
91
89
 
92
90
  - **`retryable`은 "다시 보내도 안전한가"이지 "자동으로 재시도하라"가 아닙니다.** SDK는 어떤 경우에도 스스로 재시도하지 않습니다. 재시도할 때는 **반드시 같은 `requestId`** 를 쓰세요 — 새 ID로 바꾸면 중복 발송됩니다. `409 idempotency_conflict`만은 `retryable: false`인데, 이미 접수된 건이라 다시 보내면 방에 두 번 올라가기 때문입니다.
93
- - `KakaoApiError`는 `status`·`code`·`body`·`retryAfterMs`를 싣습니다. `body`에 허브의 원본 응답이 그대로 들어 있어 `402`의 `upgrade` 링크나 `429`의 `scope`(room/global/test)를 읽을 수 있습니다.
94
- - `code`는 알려진 코드가 자동완성되지만 임의 문자열도 허용합니다 — 허브가 코드를 추가해도 타입이 깨지지 않습니다. 목록은 `KAKAO_ERROR_CODES`.
91
+ - `NotiBotApiError`는 `status`·`code`·`body`·`retryAfterMs`를 싣습니다. `body`에 허브의 원본 응답이 그대로 들어 있어 `402`의 `upgrade` 링크나 `429`의 `scope`(room/global/test)를 읽을 수 있습니다.
92
+ - `code`는 알려진 코드가 자동완성되지만 임의 문자열도 허용합니다 — 허브가 코드를 추가해도 타입이 깨지지 않습니다. 목록은 `NOTIBOT_ERROR_CODES`.
95
93
  - `retryAfterMs`는 본문 `retry_after_ms`를 우선 쓰고, 없으면 `Retry-After` 헤더(초 또는 HTTP-date)를 읽습니다.
96
94
  - 전송 실패는 원인을 표준 `Error.cause`로 물고 옵니다.
97
95
  - **호출자가 `signal`로 취소하면 `signal.reason`이 그대로 올라옵니다** — `fetch`와 같은 동작이라 기존 `AbortError` 처리가 그대로 먹습니다. SDK 오류로 감싸지 않습니다.
98
- - `isKakaoError()`는 SDK가 중복 설치돼 `instanceof`가 조용히 실패하는 환경에서도 동작합니다.
96
+ - `isNotiBotError()`는 SDK가 중복 설치돼 `instanceof`가 조용히 실패하는 환경에서도 동작합니다.
99
97
  - 각 메서드의 두 번째 인자에 `{ signal }`을 넣어 취소할 수 있습니다.
100
98
  - `fetch`와 `timeoutMs`(기본 10초)를 생성자에서 주입할 수 있습니다.
101
99
 
100
+ ## 변경 이력
101
+
102
+ - **0.8.0** — 워크스페이스 API 키(`nb_live_`/`nb_test_`). `kb_` 키는 더 이상 동작하지 않음. 콘솔에서 새로 발급해 교체하세요. `room_not_bound` 대신 `404 room_not_found`.
103
+
102
104
  ## 릴리스
103
105
 
104
106
  ```sh
105
107
  pnpm --filter @noti-bot/sdk build
106
- pnpm --filter @noti-bot/sdk pack --pack-destination /tmp/kakao-sdk-release
108
+ pnpm --filter @noti-bot/sdk pack --pack-destination /tmp/notibot-sdk-release
107
109
  ```
108
110
 
109
111
  `packages/sdk/package.json`의 `version`을 올려 `main`에 머지하면 GitHub Actions(`publish-sdk.yml`)가 npm에 없는 버전인지 확인한 뒤 테스트하고 게시하며, `sdk-v<version>` 태그와 GitHub Release를 자동 생성합니다. 이미 게시된 버전이면 아무것도 하지 않습니다. 저장소 시크릿 `NPM_TOKEN`(Granular Access Token, `@noti-bot` 스코프 쓰기)이 필요합니다.
110
112
 
111
113
  ## 키 권한
112
114
 
113
- 대시보드에서 키 이름과 허용 작업을 선택합니다. `listRooms()`는 `rooms:read`, `sendMessage()`는 `messages:send`가 필요하며 부족하면 `403 insufficient_scope`가 반환됩니다. 키 권한은 서비스에 연결된 방의 범위를 넓히지 않습니다. 기존 키는 두 권한을 유지합니다. 권한을 바꾸려면 새 키를 발급하고 연동을 교체한 뒤 이전 키를 폐기하세요.
115
+ 대시보드에서 키 이름과 허용 작업을 선택합니다. `listRooms()`는 `rooms:read`, `sendMessage()`는 `messages:send`가 필요하며 부족하면 `403 insufficient_scope`가 반환됩니다. 키 권한은 워크스페이스의 방 범위를 넓히지 않습니다. 권한을 바꾸려면 새 키를 발급하고 연동을 교체한 뒤 이전 키를 폐기하세요.
114
116
 
115
117
  ## 실제 발송 없는 테스트 키
116
118
 
117
- 대시보드에서 키 환경을 **테스트**로 선택하세요. 같은 SDK·API 주소를 사용하며 서버가 키에 저장된 환경을 판별합니다. 클라이언트 요청으로 운영 키로 전환할 수 없습니다. 성공 응답은 HTTP 200, `test: true`, `queued: false`입니다. 입력값·권한·활성 방 연결을 검증하지만 폰 전달, 운영 발송 제한, 월 한도는 검증하지 않습니다. 테스트는 발송 큐·메시지 로그·과금 사용량을 생성하지 않으며 서비스당 분당 60회로 제한됩니다. 실제 방 목록과 연결 설정을 사용하는 검증 모드이며 별도 데이터 샌드박스는 아닙니다.
119
+ 대시보드에서 키 환경을 **테스트**로 선택하세요. 같은 SDK·API 주소를 사용하며 서버가 키에 저장된 환경을 판별합니다. 클라이언트 요청으로 운영 키로 전환할 수 없습니다. 성공 응답은 HTTP 200, `test: true`, `queued: false`입니다. 입력값·권한·워크스페이스의 활성 방을 검증하지만 폰 전달, 운영 발송 제한, 월 한도는 검증하지 않습니다. 테스트는 발송 큐·메시지 로그·과금 사용량을 생성하지 않으며 키당 분당 60회로 제한됩니다. 실제 방 목록과 연결 설정을 사용하는 검증 모드이며 별도 데이터 샌드박스는 아닙니다.
118
120
 
119
121
  테스트 요청 ID는 저장하지 않습니다. 같은 ID의 테스트를 반복해도 매번 검증하며, 이후 운영 키에서 같은 ID로 실제 발송할 수 있습니다. 운영 전환은 운영 키를 새로 발급해 서버 환경변수를 교체하세요. 기존 키는 운영 키로 유지됩니다.
120
122
 
121
- 동일 서비스에서 이미 접수한 `requestId`의 방 ID 또는 본문을 바꾸면 `409 idempotency_conflict`를 반환합니다. 동일한 방·본문은 중복으로 처리하며 추가 큐/사용량을 만들지 않습니다. slug/방 표시명 변경은 고정 방 ID가 같으면 충돌로 보지 않습니다. 기존 기록 중 본문 검증값이 없는 건은 방 변경만 검출하고 재발송하지 않습니다. 검증값은 서버 비밀키로 보호하므로 비밀키 교체 후 이전 요청의 재시도는 충돌할 수 있습니다.
123
+ 동일 API 키로 이미 접수한 `requestId`의 방 ID 또는 본문을 바꾸면 `409 idempotency_conflict`를 반환합니다. 동일한 방·본문은 중복으로 처리하며 추가 큐/사용량을 만들지 않습니다. slug/방 표시명 변경은 고정 방 ID가 같으면 충돌로 보지 않습니다. 기존 기록 중 본문 검증값이 없는 건은 방 변경만 검출하고 재발송하지 않습니다. 검증값은 서버 비밀키로 보호하므로 비밀키 교체 후 이전 요청의 재시도는 충돌할 수 있습니다.
122
124
 
123
125
  ### Iris migration
124
126
 
@@ -129,6 +131,6 @@ hub, not delivered to a recipient, and uncertain sends must not be retried blind
129
131
 
130
132
  `InboundWebhookEvent` describes signed webhook events, including optional
131
133
  `roomExternalId`, `senderId`, and `imageBase64` from Iris. Treat IDs as strings;
132
- Kakao IDs may exceed JavaScript's safe integer range. Check `X-Kakao-Hub-Signature`
134
+ Kakao IDs may exceed JavaScript's safe integer range. Check `X-NotiBot-Signature`
133
135
  against the raw request body before parsing. Images are only included for rooms
134
136
  explicitly enabled by the owner.
package/dist/errors.d.ts CHANGED
@@ -16,21 +16,18 @@
16
16
  * `instanceof` 는 같은 클래스의 사본이 둘 이상 로드되면(pnpm 중첩 설치, 번들러가 ESM/CJS 를
17
17
  * 각각 끌어오는 경우) 조용히 false 가 된다. `Symbol.for` 는 realm 전역 레지스트리라 사본이
18
18
  * 몇 개든 같은 심볼을 가리킨다. 내부용이지만 d.ts 에 이름이 필요해 export 한다.
19
- *
20
- * 키 문자열은 옛 패키지 이름(`@kakao-bot/sdk`)을 그대로 쓴다. `@noti-bot/sdk` 로 이름을
21
- * 바꾼 뒤에도 옛 패키지와 함께 설치된 곳에서 서로의 에러를 식별하려면 바꾸면 안 된다.
22
19
  */
23
- export declare const KAKAO_ERROR_BRAND: unique symbol;
20
+ export declare const NOTIBOT_ERROR_BRAND: unique symbol;
24
21
  /** 허브가 돌려주는 오류 코드. 서버 라우트(`src/outbound/routes.ts`)가 정본이다. */
25
- export declare const KAKAO_ERROR_CODES: readonly ["validation_error", "invalid_room_slug", "unauthorized", "plan_message_limit", "insufficient_scope", "room_not_bound", "room_inactive", "idempotency_conflict", "rate_limited", "kill_switch", "queue_full", "request_failed"];
26
- export type KakaoErrorCode = (typeof KAKAO_ERROR_CODES)[number];
22
+ export declare const NOTIBOT_ERROR_CODES: readonly ["validation_error", "invalid_room_slug", "unauthorized", "plan_message_limit", "insufficient_scope", "room_not_found", "room_inactive", "idempotency_conflict", "rate_limited", "kill_switch", "queue_full", "request_failed"];
23
+ export type NotiBotErrorCode = (typeof NOTIBOT_ERROR_CODES)[number];
27
24
  /**
28
25
  * 알려진 코드는 자동완성으로 뜨되, 허브가 새 코드를 추가해도 타입이 깨지지 않는다.
29
26
  * `(string & {})` 는 유니온이 `string` 으로 뭉개지는 것을 막는 관용구다.
30
27
  */
31
- export type KakaoErrorCodeLike = KakaoErrorCode | (string & {});
28
+ export type NotiBotErrorCodeLike = NotiBotErrorCode | (string & {});
32
29
  /** 로그에 그대로 적기 좋은 평평한 모양. `toJSON()` 의 결과. */
33
- export interface KakaoErrorJSON {
30
+ export interface NotiBotErrorJSON {
34
31
  name: string;
35
32
  message: string;
36
33
  retryable: boolean;
@@ -40,9 +37,9 @@ export interface KakaoErrorJSON {
40
37
  retryAfterMs?: number;
41
38
  timeoutMs?: number;
42
39
  }
43
- /** 모든 허브 오류의 베이스. `catch` 에서 `isKakaoError(e)` 한 번으로 전부 잡는다. */
44
- export declare abstract class KakaoError extends Error {
45
- readonly [KAKAO_ERROR_BRAND]: true;
40
+ /** 모든 허브 오류의 베이스. `catch` 에서 `isNotiBotError(e)` 한 번으로 전부 잡는다. */
41
+ export declare abstract class NotiBotError extends Error {
42
+ readonly [NOTIBOT_ERROR_BRAND]: true;
46
43
  /** 서브클래스를 구분하는 판별자. `instanceof` 가 막히는 환경에서도 읽을 수 있다. */
47
44
  abstract readonly name: string;
48
45
  /**
@@ -54,7 +51,7 @@ export declare abstract class KakaoError extends Error {
54
51
  constructor(message: string, requestId?: string, options?: {
55
52
  cause?: unknown;
56
53
  });
57
- toJSON(): KakaoErrorJSON;
54
+ toJSON(): NotiBotErrorJSON;
58
55
  }
59
56
  /**
60
57
  * 허브가 응답은 했지만 2xx 가 아니었다.
@@ -62,21 +59,21 @@ export declare abstract class KakaoError extends Error {
62
59
  * 본문을 통째로 `body` 에 보관한다 — 402 는 `upgrade` 링크를, 429 는 `scope`(test/global/room)를
63
60
  * 함께 싣는데, `error` 필드만 빼고 버리면 그 안내가 사라진다.
64
61
  */
65
- export declare class KakaoApiError extends KakaoError {
66
- readonly name = "KakaoApiError";
62
+ export declare class NotiBotApiError extends NotiBotError {
63
+ readonly name = "NotiBotApiError";
67
64
  readonly status: number;
68
- readonly code: KakaoErrorCodeLike;
65
+ readonly code: NotiBotErrorCodeLike;
69
66
  readonly retryable: boolean;
70
67
  /** 파싱된 응답 본문. JSON 이 아니었으면 `null`. */
71
68
  readonly body: unknown;
72
69
  /** `Retry-After` 또는 본문 `retry_after_ms` 에서 읽은 대기 시간. 없으면 `undefined`. */
73
70
  readonly retryAfterMs?: number;
74
- constructor(status: number, code: KakaoErrorCodeLike, requestId?: string, options?: {
71
+ constructor(status: number, code: NotiBotErrorCodeLike, requestId?: string, options?: {
75
72
  body?: unknown;
76
73
  retryAfterMs?: number;
77
74
  cause?: unknown;
78
75
  });
79
- toJSON(): KakaoErrorJSON;
76
+ toJSON(): NotiBotErrorJSON;
80
77
  }
81
78
  /**
82
79
  * 응답을 받지 못했다. 허브에 닿기 전에 끊겼다는 뜻이고, 발송 여부는 알 수 없다.
@@ -84,8 +81,8 @@ export declare class KakaoApiError extends KakaoError {
84
81
  * 같은 `requestId` 로 다시 보내면 허브가 중복을 막아 주므로 재시도가 안전하다 —
85
82
  * **새 id 로 바꿔 보내면 중복 발송된다.**
86
83
  */
87
- export declare class KakaoTransportError extends KakaoError {
88
- readonly name: "KakaoTransportError" | "KakaoTimeoutError";
84
+ export declare class NotiBotTransportError extends NotiBotError {
85
+ readonly name: "NotiBotTransportError" | "NotiBotTimeoutError";
89
86
  readonly retryable = true;
90
87
  constructor(requestId?: string, options?: {
91
88
  cause?: unknown;
@@ -93,23 +90,23 @@ export declare class KakaoTransportError extends KakaoError {
93
90
  });
94
91
  }
95
92
  /**
96
- * 제한 시간 안에 응답이 오지 않았다. `KakaoTransportError` 의 하위라
97
- * 기존 `catch (e) { if (e instanceof KakaoTransportError) … }` 가 그대로 잡는다.
93
+ * 제한 시간 안에 응답이 오지 않았다. `NotiBotTransportError` 의 하위라
94
+ * 기존 `catch (e) { if (e instanceof NotiBotTransportError) … }` 가 그대로 잡는다.
98
95
  */
99
- export declare class KakaoTimeoutError extends KakaoTransportError {
100
- readonly name = "KakaoTimeoutError";
96
+ export declare class NotiBotTimeoutError extends NotiBotTransportError {
97
+ readonly name = "NotiBotTimeoutError";
101
98
  readonly timeoutMs: number;
102
99
  constructor(timeoutMs: number, requestId?: string, options?: {
103
100
  cause?: unknown;
104
101
  });
105
- toJSON(): KakaoErrorJSON;
102
+ toJSON(): NotiBotErrorJSON;
106
103
  }
107
104
  /**
108
105
  * 2xx 를 받았지만 본문이 계약과 달랐다. 허브는 받았을 가능성이 크므로 재시도하지 않는다 —
109
106
  * 사람이 대시보드 로그를 보고 판단해야 한다.
110
107
  */
111
- export declare class KakaoProtocolError extends KakaoError {
112
- readonly name = "KakaoProtocolError";
108
+ export declare class NotiBotProtocolError extends NotiBotError {
109
+ readonly name = "NotiBotProtocolError";
113
110
  readonly retryable = false;
114
111
  constructor(requestId?: string, options?: {
115
112
  cause?: unknown;
@@ -118,4 +115,4 @@ export declare class KakaoProtocolError extends KakaoError {
118
115
  /**
119
116
  * 허브 오류인지 판별한다. 중복 설치로 `instanceof` 가 막힌 환경에서도 동작한다.
120
117
  */
121
- export declare function isKakaoError(value: unknown): value is KakaoError;
118
+ export declare function isNotiBotError(value: unknown): value is NotiBotError;
package/dist/errors.js CHANGED
@@ -16,19 +16,16 @@
16
16
  * `instanceof` 는 같은 클래스의 사본이 둘 이상 로드되면(pnpm 중첩 설치, 번들러가 ESM/CJS 를
17
17
  * 각각 끌어오는 경우) 조용히 false 가 된다. `Symbol.for` 는 realm 전역 레지스트리라 사본이
18
18
  * 몇 개든 같은 심볼을 가리킨다. 내부용이지만 d.ts 에 이름이 필요해 export 한다.
19
- *
20
- * 키 문자열은 옛 패키지 이름(`@kakao-bot/sdk`)을 그대로 쓴다. `@noti-bot/sdk` 로 이름을
21
- * 바꾼 뒤에도 옛 패키지와 함께 설치된 곳에서 서로의 에러를 식별하려면 바꾸면 안 된다.
22
19
  */
23
- export const KAKAO_ERROR_BRAND = Symbol.for("@kakao-bot/sdk.error");
20
+ export const NOTIBOT_ERROR_BRAND = Symbol.for("@noti-bot/sdk.error");
24
21
  /** 허브가 돌려주는 오류 코드. 서버 라우트(`src/outbound/routes.ts`)가 정본이다. */
25
- export const KAKAO_ERROR_CODES = [
22
+ export const NOTIBOT_ERROR_CODES = [
26
23
  "validation_error",
27
24
  "invalid_room_slug",
28
25
  "unauthorized",
29
26
  "plan_message_limit",
30
27
  "insufficient_scope",
31
- "room_not_bound",
28
+ "room_not_found",
32
29
  "room_inactive",
33
30
  "idempotency_conflict",
34
31
  "rate_limited",
@@ -36,9 +33,9 @@ export const KAKAO_ERROR_CODES = [
36
33
  "queue_full",
37
34
  "request_failed",
38
35
  ];
39
- /** 모든 허브 오류의 베이스. `catch` 에서 `isKakaoError(e)` 한 번으로 전부 잡는다. */
40
- export class KakaoError extends Error {
41
- [KAKAO_ERROR_BRAND] = true;
36
+ /** 모든 허브 오류의 베이스. `catch` 에서 `isNotiBotError(e)` 한 번으로 전부 잡는다. */
37
+ export class NotiBotError extends Error {
38
+ [NOTIBOT_ERROR_BRAND] = true;
42
39
  requestId;
43
40
  constructor(message, requestId, options) {
44
41
  super(message, options);
@@ -59,8 +56,8 @@ export class KakaoError extends Error {
59
56
  * 본문을 통째로 `body` 에 보관한다 — 402 는 `upgrade` 링크를, 429 는 `scope`(test/global/room)를
60
57
  * 함께 싣는데, `error` 필드만 빼고 버리면 그 안내가 사라진다.
61
58
  */
62
- export class KakaoApiError extends KakaoError {
63
- name = "KakaoApiError";
59
+ export class NotiBotApiError extends NotiBotError {
60
+ name = "NotiBotApiError";
64
61
  status;
65
62
  code;
66
63
  retryable;
@@ -69,7 +66,7 @@ export class KakaoApiError extends KakaoError {
69
66
  /** `Retry-After` 또는 본문 `retry_after_ms` 에서 읽은 대기 시간. 없으면 `undefined`. */
70
67
  retryAfterMs;
71
68
  constructor(status, code, requestId, options) {
72
- super(`Kakao Bot API returned ${status} (${code})`, requestId, options);
69
+ super(`NotiBot API returned ${status} (${code})`, requestId, options);
73
70
  this.status = status;
74
71
  this.code = code;
75
72
  this.body = options?.body ?? null;
@@ -91,25 +88,25 @@ export class KakaoApiError extends KakaoError {
91
88
  * 같은 `requestId` 로 다시 보내면 허브가 중복을 막아 주므로 재시도가 안전하다 —
92
89
  * **새 id 로 바꿔 보내면 중복 발송된다.**
93
90
  */
94
- export class KakaoTransportError extends KakaoError {
95
- name = "KakaoTransportError";
91
+ export class NotiBotTransportError extends NotiBotError {
92
+ name = "NotiBotTransportError";
96
93
  retryable = true;
97
94
  constructor(requestId, options) {
98
95
  super(options?.message ??
99
- "Kakao Bot request did not complete. Delivery state is unknown; retry with the same request ID.", requestId, options);
96
+ "NotiBot request did not complete. Delivery state is unknown; retry with the same request ID.", requestId, options);
100
97
  }
101
98
  }
102
99
  /**
103
- * 제한 시간 안에 응답이 오지 않았다. `KakaoTransportError` 의 하위라
104
- * 기존 `catch (e) { if (e instanceof KakaoTransportError) … }` 가 그대로 잡는다.
100
+ * 제한 시간 안에 응답이 오지 않았다. `NotiBotTransportError` 의 하위라
101
+ * 기존 `catch (e) { if (e instanceof NotiBotTransportError) … }` 가 그대로 잡는다.
105
102
  */
106
- export class KakaoTimeoutError extends KakaoTransportError {
107
- name = "KakaoTimeoutError";
103
+ export class NotiBotTimeoutError extends NotiBotTransportError {
104
+ name = "NotiBotTimeoutError";
108
105
  timeoutMs;
109
106
  constructor(timeoutMs, requestId, options) {
110
107
  super(requestId, {
111
108
  ...options,
112
- message: `Kakao Bot request timed out after ${timeoutMs}ms. Delivery state is unknown; retry with the same request ID.`,
109
+ message: `NotiBot request timed out after ${timeoutMs}ms. Delivery state is unknown; retry with the same request ID.`,
113
110
  });
114
111
  this.timeoutMs = timeoutMs;
115
112
  }
@@ -121,11 +118,11 @@ export class KakaoTimeoutError extends KakaoTransportError {
121
118
  * 2xx 를 받았지만 본문이 계약과 달랐다. 허브는 받았을 가능성이 크므로 재시도하지 않는다 —
122
119
  * 사람이 대시보드 로그를 보고 판단해야 한다.
123
120
  */
124
- export class KakaoProtocolError extends KakaoError {
125
- name = "KakaoProtocolError";
121
+ export class NotiBotProtocolError extends NotiBotError {
122
+ name = "NotiBotProtocolError";
126
123
  retryable = false;
127
124
  constructor(requestId, options) {
128
- super("Kakao Bot returned an unexpected response.", requestId, options);
125
+ super("NotiBot returned an unexpected response.", requestId, options);
129
126
  }
130
127
  }
131
128
  /**
@@ -143,8 +140,8 @@ function isRetryableStatus(status, code) {
143
140
  /**
144
141
  * 허브 오류인지 판별한다. 중복 설치로 `instanceof` 가 막힌 환경에서도 동작한다.
145
142
  */
146
- export function isKakaoError(value) {
143
+ export function isNotiBotError(value) {
147
144
  return (!!value &&
148
145
  typeof value === "object" &&
149
- value[KAKAO_ERROR_BRAND] === true);
146
+ value[NOTIBOT_ERROR_BRAND] === true);
150
147
  }
package/dist/index.d.ts CHANGED
@@ -1,15 +1,15 @@
1
- export type { KakaoErrorCode, KakaoErrorCodeLike, KakaoErrorJSON } from "./errors.js";
2
- export { isKakaoError, KAKAO_ERROR_BRAND, KAKAO_ERROR_CODES, KakaoApiError, KakaoError, KakaoProtocolError, KakaoTimeoutError, KakaoTransportError, } from "./errors.js";
1
+ export type { NotiBotErrorCode, NotiBotErrorCodeLike, NotiBotErrorJSON } from "./errors.js";
2
+ export { isNotiBotError, NOTIBOT_ERROR_BRAND, NOTIBOT_ERROR_CODES, NotiBotApiError, NotiBotError, NotiBotProtocolError, NotiBotTimeoutError, NotiBotTransportError, } from "./errors.js";
3
3
  /**
4
4
  * Tag a member in `sendMessage` text: `` `${mention(ev.senderId)} 확인했어요` ``.
5
5
  * The bridge swaps it for `@표시이름` and sends a real Kakao mention (notification to that person).
6
6
  * Use the stable ID from `InboundWebhookEvent.senderId` or `mentions[].userId`, never a display name.
7
7
  */
8
8
  export declare function mention(kakaoUserId: string): string;
9
- export interface KakaoBotOptions {
9
+ export interface NotiBotOptions {
10
10
  /** Hub origin, e.g. https://hub.example.com. Never use the phone's private endpoint. */
11
11
  baseUrl: string;
12
- /** Service API key issued from the dashboard. Keep on your server. */
12
+ /** Workspace API key (nb_live_… / nb_test_…) issued from the console. Keep on your server. */
13
13
  apiKey: string;
14
14
  timeoutMs?: number;
15
15
  fetch?: typeof globalThis.fetch;
@@ -99,15 +99,15 @@ export interface InboundWebhookEvent {
99
99
  export interface RequestOptions {
100
100
  signal?: AbortSignal;
101
101
  }
102
- export declare class KakaoBot {
102
+ export declare class NotiBot {
103
103
  private readonly baseUrl;
104
104
  private readonly apiKey;
105
105
  private readonly timeoutMs;
106
106
  private readonly fetchFn;
107
- constructor(options: KakaoBotOptions);
107
+ constructor(options: NotiBotOptions);
108
108
  sendMessage(input: SendMessageInput, options?: RequestOptions): Promise<SendMessageResult>;
109
109
  listRooms(options?: RequestOptions): Promise<Room[]>;
110
- /** Members of a room bound to this service. Requires the `rooms:read` scope. */
110
+ /** Members of a room in this workspace. Requires the `rooms:read` scope. */
111
111
  listRoomMembers(room: {
112
112
  roomId: string;
113
113
  } | {
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { isKakaoError, KAKAO_ERROR_BRAND, KAKAO_ERROR_CODES, KakaoApiError, KakaoError, KakaoProtocolError, KakaoTimeoutError, KakaoTransportError, } from "./errors.js";
2
- import { KakaoApiError, KakaoProtocolError, KakaoTimeoutError, KakaoTransportError, } from "./errors.js";
1
+ export { isNotiBotError, NOTIBOT_ERROR_BRAND, NOTIBOT_ERROR_CODES, NotiBotApiError, NotiBotError, NotiBotProtocolError, NotiBotTimeoutError, NotiBotTransportError, } from "./errors.js";
2
+ import { NotiBotApiError, NotiBotProtocolError, NotiBotTimeoutError, NotiBotTransportError, } from "./errors.js";
3
3
  /**
4
4
  * Tag a member in `sendMessage` text: `` `${mention(ev.senderId)} 확인했어요` ``.
5
5
  * The bridge swaps it for `@표시이름` and sends a real Kakao mention (notification to that person).
@@ -13,7 +13,7 @@ export function mention(kakaoUserId) {
13
13
  function object(value) {
14
14
  return !!value && typeof value === "object" && !Array.isArray(value);
15
15
  }
16
- export class KakaoBot {
16
+ export class NotiBot {
17
17
  baseUrl;
18
18
  apiKey;
19
19
  timeoutMs;
@@ -26,8 +26,8 @@ export class KakaoBot {
26
26
  url.search ||
27
27
  url.hash)
28
28
  throw new TypeError("baseUrl must be an HTTP(S) URL without credentials, query or fragment.");
29
- if (!options.apiKey.trim() || /[\r\n]/.test(options.apiKey))
30
- throw new TypeError("A non-empty service API key is required.");
29
+ if (!/^nb_(live|test)_[^\s]+$/.test(options.apiKey))
30
+ throw new TypeError("A NotiBot API key (nb_live_… or nb_test_…) is required.");
31
31
  this.baseUrl = url.toString().replace(/\/+$/, "");
32
32
  this.apiKey = options.apiKey;
33
33
  this.timeoutMs = options.timeoutMs ?? 10000;
@@ -66,7 +66,7 @@ export class KakaoBot {
66
66
  (data.test !== undefined && (typeof data.test !== "boolean" || (data.test && data.queued))) ||
67
67
  (data.duplicate !== undefined && typeof data.duplicate !== "boolean") ||
68
68
  (data.room !== undefined && typeof data.room !== "string"))
69
- throw new KakaoProtocolError(requestId);
69
+ throw new NotiBotProtocolError(requestId);
70
70
  return data;
71
71
  }
72
72
  async listRooms(options = {}) {
@@ -79,10 +79,10 @@ export class KakaoBot {
79
79
  typeof room.name === "string" &&
80
80
  ["pending", "active", "suspended"].includes(String(room.status)) &&
81
81
  typeof room.canReply === "boolean"))
82
- throw new KakaoProtocolError();
82
+ throw new NotiBotProtocolError();
83
83
  return data.rooms;
84
84
  }
85
- /** Members of a room bound to this service. Requires the `rooms:read` scope. */
85
+ /** Members of a room in this workspace. Requires the `rooms:read` scope. */
86
86
  async listRoomMembers(room, options = {}) {
87
87
  return (await this.getRoomMembers(room, options)).members;
88
88
  }
@@ -103,7 +103,7 @@ export class KakaoBot {
103
103
  /^\d+$/.test(member.userId) &&
104
104
  (member.name === null || typeof member.name === "string") &&
105
105
  member.mention === `<@${member.userId}>`))
106
- throw new KakaoProtocolError();
106
+ throw new NotiBotProtocolError();
107
107
  return {
108
108
  members: data.members,
109
109
  known: typeof data.known === "number" ? data.known : data.members.length,
@@ -127,7 +127,7 @@ export class KakaoBot {
127
127
  },
128
128
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
129
129
  signal: combined,
130
- // Service keys must never be forwarded to a redirected origin.
130
+ // API keys must never be forwarded to a redirected origin.
131
131
  redirect: "error",
132
132
  });
133
133
  data = await response.json().catch(() => null);
@@ -138,14 +138,14 @@ export class KakaoBot {
138
138
  if (signal?.aborted)
139
139
  throw signal.reason;
140
140
  if (timeout.aborted)
141
- throw new KakaoTimeoutError(this.timeoutMs, requestId, { cause });
142
- throw new KakaoTransportError(requestId, { cause });
141
+ throw new NotiBotTimeoutError(this.timeoutMs, requestId, { cause });
142
+ throw new NotiBotTransportError(requestId, { cause });
143
143
  }
144
144
  if (!response.ok) {
145
145
  const code = object(data) && typeof data.error === "string" && /^[a-z0-9_]{1,80}$/.test(data.error)
146
146
  ? data.error
147
147
  : "request_failed";
148
- throw new KakaoApiError(response.status, code, requestId, {
148
+ throw new NotiBotApiError(response.status, code, requestId, {
149
149
  body: data,
150
150
  retryAfterMs: retryAfterMs(response, data),
151
151
  });
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@noti-bot/sdk",
3
- "version": "0.6.0",
4
- "description": "Typed server-side client for the Kakao Bot Hub API",
3
+ "version": "0.8.0",
4
+ "description": "Typed server-side client for the NotiBot API",
5
5
  "license": "MIT",
6
6
  "author": "Jeongmin Lee",
7
- "homepage": "https://github.com/froggy1014/kakao-bot/tree/main/packages/sdk#readme",
7
+ "homepage": "https://github.com/froggy1014/noti-bot/tree/main/packages/sdk#readme",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/froggy1014/kakao-bot.git",
10
+ "url": "git+https://github.com/froggy1014/noti-bot.git",
11
11
  "directory": "packages/sdk"
12
12
  },
13
- "bugs": "https://github.com/froggy1014/kakao-bot/issues",
13
+ "bugs": "https://github.com/froggy1014/noti-bot/issues",
14
14
  "keywords": [
15
15
  "kakao",
16
16
  "kakaotalk",