@terreno/api 57.9.0 → 57.11.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.
@@ -0,0 +1,357 @@
1
+ import {afterEach, beforeEach, describe, expect, it, type Mock, spyOn} from "bun:test";
2
+ import * as Sentry from "@sentry/bun";
3
+ import axios from "axios";
4
+
5
+ import {APIError, isAPIError} from "../errors";
6
+ import {
7
+ createSlackPrivateChannel,
8
+ findSlackChannelByName,
9
+ inviteSlackUsersToChannel,
10
+ normalizeSlackChannelName,
11
+ postSlackMessage,
12
+ } from "./slackWebApi";
13
+
14
+ describe("normalizeSlackChannelName", () => {
15
+ it("lowercases and trims a valid channel name", () => {
16
+ expect(normalizeSlackChannelName(" Case-Room_1 ")).toBe("case-room_1");
17
+ });
18
+
19
+ it("rejects names Slack will not accept", () => {
20
+ expect(() => normalizeSlackChannelName("case room")).toThrow(APIError);
21
+ expect(() => normalizeSlackChannelName("---")).toThrow(APIError);
22
+ });
23
+ });
24
+
25
+ describe("Slack Web API", () => {
26
+ let mockAxiosPost: Mock<typeof axios.post>;
27
+ let mockAxiosGet: Mock<typeof axios.get>;
28
+
29
+ beforeEach(() => {
30
+ mockAxiosPost = spyOn(axios, "post");
31
+ mockAxiosGet = spyOn(axios, "get");
32
+ process.env.SLACK_BOT_TOKEN = "xoxb-test";
33
+ (Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
34
+ });
35
+
36
+ afterEach(() => {
37
+ mockAxiosPost.mockRestore();
38
+ mockAxiosGet.mockRestore();
39
+ Reflect.deleteProperty(process.env, "SLACK_BOT_TOKEN");
40
+ });
41
+
42
+ it("creates a private channel, invites members, and posts the first message", async () => {
43
+ mockAxiosPost.mockImplementation(async (url: string, body: {name?: string; text?: string}) => {
44
+ if (String(url).endsWith("conversations.create")) {
45
+ return {
46
+ data: {channel: {id: "C012345678", is_private: true, name: body.name}, ok: true},
47
+ status: 200,
48
+ };
49
+ }
50
+ if (String(url).endsWith("conversations.invite")) {
51
+ return {data: {ok: true}, status: 200};
52
+ }
53
+ return {data: {channel: "C012345678", ok: true, ts: "1503435956.000247"}, status: 200};
54
+ });
55
+
56
+ const created = await createSlackPrivateChannel({
57
+ initialMessage: "Case opened",
58
+ mentionUserIds: ["U012ABCDEF"],
59
+ name: "Case-123",
60
+ userIds: ["U012ABCDEF", "not-a-slack-id"],
61
+ });
62
+
63
+ expect(created).toEqual({
64
+ channelId: "C012345678",
65
+ invites: {
66
+ alreadyMemberUserIds: [],
67
+ failures: [{error: "invalid_user_id", userId: "not-a-slack-id"}],
68
+ invitedUserIds: ["U012ABCDEF"],
69
+ },
70
+ messageTs: "1503435956.000247",
71
+ name: "case-123",
72
+ });
73
+ const createBody = mockAxiosPost.mock.calls[0]?.[1] as {is_private?: boolean; name?: string};
74
+ expect(createBody).toEqual({is_private: true, name: "case-123"});
75
+ const messageBody = mockAxiosPost.mock.calls[2]?.[1] as {text?: string};
76
+ expect(messageBody.text).toBe("<@U012ABCDEF> Case opened");
77
+ });
78
+
79
+ it("throws 409 when the channel name is taken", async () => {
80
+ mockAxiosPost.mockResolvedValue({data: {error: "name_taken", ok: false}, status: 200});
81
+
82
+ try {
83
+ await createSlackPrivateChannel({name: "case-123"});
84
+ throw new Error("Expected createSlackPrivateChannel to throw");
85
+ } catch (error) {
86
+ expect(isAPIError(error)).toBe(true);
87
+ expect((error as APIError).status).toBe(409);
88
+ expect((error as APIError).title).toBe("Slack channel name is already taken");
89
+ }
90
+ });
91
+
92
+ it("keeps the new channel id when the initial message fails", async () => {
93
+ mockAxiosPost.mockImplementation(async (url: string) => {
94
+ if (String(url).endsWith("conversations.create")) {
95
+ return {data: {channel: {id: "C012345678", name: "case-123"}, ok: true}, status: 200};
96
+ }
97
+ return {data: {error: "not_in_channel", ok: false}, status: 200};
98
+ });
99
+
100
+ try {
101
+ await createSlackPrivateChannel({initialMessage: "hello", name: "case-123"});
102
+ throw new Error("Expected createSlackPrivateChannel to throw");
103
+ } catch (error) {
104
+ expect(isAPIError(error)).toBe(true);
105
+ expect((error as APIError).title).toBe("Slack initial message failed");
106
+ expect((error as APIError).meta?.channelId).toBe("C012345678");
107
+ }
108
+ });
109
+
110
+ it("reports members who are already in the channel", async () => {
111
+ mockAxiosPost.mockResolvedValue({
112
+ data: {error: "already_in_channel", ok: false},
113
+ status: 200,
114
+ });
115
+
116
+ const result = await inviteSlackUsersToChannel({
117
+ channelId: "c012345678",
118
+ userIds: ["<@U012ABCDEF>", "U012ABCDEF"],
119
+ });
120
+
121
+ expect(result.alreadyMemberUserIds).toEqual(["U012ABCDEF"]);
122
+ expect(result.invitedUserIds).toEqual([]);
123
+ const body = mockAxiosPost.mock.calls[0]?.[1] as {channel?: string; users?: string};
124
+ expect(body).toEqual({channel: "C012345678", force: true, users: "U012ABCDEF"});
125
+ });
126
+
127
+ it("returns per-user invite failures without failing the whole call", async () => {
128
+ mockAxiosPost.mockResolvedValue({
129
+ data: {
130
+ error: "user_not_found",
131
+ errors: [{error: "user_not_found", user: "U012ABCDEF"}],
132
+ ok: false,
133
+ },
134
+ status: 200,
135
+ });
136
+
137
+ const result = await inviteSlackUsersToChannel({
138
+ channelId: "C012345678",
139
+ userIds: ["U012ABCDEF", "W0ENTERPR1"],
140
+ });
141
+
142
+ expect(result.failures).toEqual([{error: "user_not_found", userId: "U012ABCDEF"}]);
143
+ expect(result.invitedUserIds).toEqual([]);
144
+ });
145
+
146
+ it("throws when the bot is not in an existing private channel", async () => {
147
+ mockAxiosPost.mockResolvedValue({data: {error: "not_in_channel", ok: false}, status: 200});
148
+
149
+ try {
150
+ await inviteSlackUsersToChannel({channelId: "C012345678", userIds: ["U012ABCDEF"]});
151
+ throw new Error("Expected inviteSlackUsersToChannel to throw");
152
+ } catch (error) {
153
+ expect(isAPIError(error)).toBe(true);
154
+ expect((error as APIError).detail).toContain("not_in_channel");
155
+ }
156
+ });
157
+
158
+ it("posts blocks and mention tokens to a channel", async () => {
159
+ mockAxiosPost.mockResolvedValue({
160
+ data: {channel: "C012345678", ok: true, ts: "1.2"},
161
+ status: 200,
162
+ });
163
+
164
+ const posted = await postSlackMessage({
165
+ blocks: [{type: "section"}],
166
+ channelId: "C012345678",
167
+ mentionUserIds: ["U012ABCDEF"],
168
+ text: "Update",
169
+ });
170
+
171
+ expect(posted).toEqual({channelId: "C012345678", messageTs: "1.2"});
172
+ expect(mockAxiosPost.mock.calls[0]?.[1]).toEqual({
173
+ blocks: [{type: "section"}],
174
+ channel: "C012345678",
175
+ text: "<@U012ABCDEF> Update",
176
+ });
177
+ });
178
+
179
+ it("retries a rate-limited post and then succeeds", async () => {
180
+ const rateLimited = Object.assign(new Error("429"), {
181
+ isAxiosError: true,
182
+ response: {headers: {"retry-after": "0"}, status: 429},
183
+ });
184
+ mockAxiosPost
185
+ .mockRejectedValueOnce(rateLimited)
186
+ .mockResolvedValueOnce({data: {ok: true, ts: "9.9"}, status: 200});
187
+
188
+ const posted = await postSlackMessage({channelId: "C012345678", text: "again"});
189
+ expect(posted.messageTs).toBe("9.9");
190
+ expect(mockAxiosPost.mock.calls.length).toBe(2);
191
+ });
192
+
193
+ it("finds a channel on a later page", async () => {
194
+ mockAxiosGet
195
+ .mockResolvedValueOnce({
196
+ data: {
197
+ channels: [{id: "C000000001", name: "other"}],
198
+ ok: true,
199
+ response_metadata: {next_cursor: "page-2"},
200
+ },
201
+ status: 200,
202
+ })
203
+ .mockResolvedValueOnce({
204
+ data: {
205
+ channels: [{id: "C012345678", is_private: true, name_normalized: "case-123"}],
206
+ ok: true,
207
+ response_metadata: {next_cursor: ""},
208
+ },
209
+ status: 200,
210
+ });
211
+
212
+ const found = await findSlackChannelByName({name: "case-123"});
213
+ expect(found).toEqual({channelId: "C012345678", isPrivate: true, name: "case-123"});
214
+ const firstParams = mockAxiosGet.mock.calls[0]?.[1] as {params?: {types?: string}};
215
+ expect(firstParams.params?.types).toBe("public_channel,private_channel");
216
+ });
217
+
218
+ it("returns undefined when no visible channel has that name", async () => {
219
+ mockAxiosGet.mockResolvedValue({
220
+ data: {channels: [], ok: true, response_metadata: {next_cursor: ""}},
221
+ status: 200,
222
+ });
223
+
224
+ expect(await findSlackChannelByName({name: "missing"})).toBeUndefined();
225
+ });
226
+
227
+ it("throws when the bot token is missing", async () => {
228
+ Reflect.deleteProperty(process.env, "SLACK_BOT_TOKEN");
229
+
230
+ try {
231
+ await postSlackMessage({channelId: "C012345678", text: "hi"});
232
+ throw new Error("Expected postSlackMessage to throw");
233
+ } catch (error) {
234
+ expect(isAPIError(error)).toBe(true);
235
+ expect((error as APIError).title).toBe("SLACK_BOT_TOKEN is not set");
236
+ }
237
+ expect(mockAxiosPost.mock.calls.length).toBe(0);
238
+ });
239
+
240
+ it("returns the channel without posting when there is no initial message", async () => {
241
+ mockAxiosPost.mockResolvedValue({
242
+ data: {channel: {id: "C012345678", name: "case-123"}, ok: true},
243
+ status: 200,
244
+ });
245
+
246
+ const created = await createSlackPrivateChannel({name: "case-123"});
247
+ expect(created.messageTs).toBeUndefined();
248
+ expect(mockAxiosPost.mock.calls.length).toBe(1);
249
+ });
250
+
251
+ it("rejects invites that contain no Slack member ids", async () => {
252
+ await expect(
253
+ createSlackPrivateChannel({name: "case-123", userIds: ["jane@example.com"]})
254
+ ).rejects.toBeInstanceOf(APIError);
255
+ await expect(
256
+ inviteSlackUsersToChannel({channelId: "C012345678", userIds: ["jane"]})
257
+ ).rejects.toBeInstanceOf(APIError);
258
+ await expect(postSlackMessage({channelId: "not-a-channel", text: "hi"})).rejects.toBeInstanceOf(
259
+ APIError
260
+ );
261
+ await expect(postSlackMessage({channelId: "C012345678", text: " "})).rejects.toBeInstanceOf(
262
+ APIError
263
+ );
264
+ expect(mockAxiosPost.mock.calls.length).toBe(0);
265
+ });
266
+
267
+ it("keeps the channel id when inviting into the new channel fails", async () => {
268
+ mockAxiosPost.mockImplementation(async (url: string) => {
269
+ if (String(url).endsWith("conversations.create")) {
270
+ return {data: {channel: {id: "C012345678", name: "case-123"}, ok: true}, status: 200};
271
+ }
272
+ return {data: {error: "not_in_channel", ok: false}, status: 200};
273
+ });
274
+
275
+ try {
276
+ await createSlackPrivateChannel({name: "case-123", userIds: ["U012ABCDEF"]});
277
+ throw new Error("Expected createSlackPrivateChannel to throw");
278
+ } catch (error) {
279
+ expect((error as APIError).meta?.channelId).toBe("C012345678");
280
+ expect((error as APIError).detail).toContain("not_in_channel");
281
+ }
282
+ });
283
+
284
+ it("throws when Slack omits the new channel id or the message timestamp", async () => {
285
+ mockAxiosPost.mockResolvedValueOnce({data: {channel: {}, ok: true}, status: 200});
286
+ await expect(createSlackPrivateChannel({name: "case-123"})).rejects.toMatchObject({
287
+ title: "Slack API request failed",
288
+ });
289
+
290
+ mockAxiosPost.mockResolvedValueOnce({data: {ok: true}, status: 200});
291
+ await expect(postSlackMessage({channelId: "C012345678", text: "hi"})).rejects.toMatchObject({
292
+ code: "slack-message-missing",
293
+ });
294
+ });
295
+
296
+ it("counts partial invite results and skips blank error entries", async () => {
297
+ mockAxiosPost.mockResolvedValue({
298
+ data: {
299
+ errors: [
300
+ {error: "already_in_channel", user: "U012ABCDEF"},
301
+ {user: " "},
302
+ {user: "W0ENTERPR1"},
303
+ ],
304
+ ok: true,
305
+ },
306
+ status: 200,
307
+ });
308
+
309
+ const result = await inviteSlackUsersToChannel({
310
+ channelId: "C012345678",
311
+ userIds: ["U012ABCDEF", "W0ENTERPR1", "U33333333", "jane"],
312
+ });
313
+
314
+ expect(result.alreadyMemberUserIds).toEqual(["U012ABCDEF"]);
315
+ expect(result.failures).toEqual([
316
+ {error: "invalid_user_id", userId: "jane"},
317
+ {error: "unknown_error", userId: "W0ENTERPR1"},
318
+ ]);
319
+ expect(result.invitedUserIds).toEqual(["U33333333"]);
320
+ });
321
+
322
+ it("retries an HTTP 200 rate limit and a transport failure exhausts attempts", async () => {
323
+ mockAxiosPost
324
+ .mockResolvedValueOnce({
325
+ data: {error: "ratelimited", ok: false},
326
+ headers: {get: (name: string) => (name === "retry-after" ? "0.001" : undefined)},
327
+ status: 200,
328
+ })
329
+ .mockResolvedValueOnce({data: {ok: true, ts: "4.4"}, status: 200});
330
+
331
+ const posted = await postSlackMessage({
332
+ channelId: "C012345678",
333
+ mentionUserIds: ["not-an-id"],
334
+ text: "later",
335
+ });
336
+ expect(posted.messageTs).toBe("4.4");
337
+
338
+ mockAxiosPost.mockReset();
339
+ mockAxiosPost.mockRejectedValue(new Error("network down"));
340
+ await expect(postSlackMessage({channelId: "C012345678", text: "later"})).rejects.toMatchObject({
341
+ code: "slack-transport-failed",
342
+ });
343
+ expect(
344
+ (Sentry.captureException as Mock<typeof Sentry.captureException>).mock.calls.length
345
+ ).toBeGreaterThan(0);
346
+ });
347
+
348
+ it("stops paging when Slack never ends the channel list", async () => {
349
+ mockAxiosGet.mockResolvedValue({
350
+ data: {channels: [{name: "other"}], ok: true, response_metadata: {next_cursor: "next"}},
351
+ status: 200,
352
+ });
353
+
354
+ expect(await findSlackChannelByName({name: "case-123"})).toBeUndefined();
355
+ expect(mockAxiosGet.mock.calls.length).toBe(25);
356
+ });
357
+ });