@desplega.ai/slack-mock 0.1.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 +113 -0
- package/dist/body.d.ts +6 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +94 -0
- package/dist/events.d.ts +36 -0
- package/dist/ids.d.ts +8 -0
- package/dist/index-thgwpw70.js +3693 -0
- package/dist/index-v7mbr1cx.js +48 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +17 -0
- package/dist/render/blocks.d.ts +7 -0
- package/dist/render/index.d.ts +25 -0
- package/dist/render/mrkdwn.d.ts +16 -0
- package/dist/screenshot.d.ts +13 -0
- package/dist/screenshot.js +9 -0
- package/dist/server.d.ts +240 -0
- package/dist/socket-mode.d.ts +73 -0
- package/dist/store.d.ts +150 -0
- package/dist/types.d.ts +211 -0
- package/dist/web-api.d.ts +26 -0
- package/package.json +60 -0
- package/src/body.ts +84 -0
- package/src/cli.ts +89 -0
- package/src/events.ts +281 -0
- package/src/ids.ts +29 -0
- package/src/index.ts +13 -0
- package/src/render/blocks.ts +392 -0
- package/src/render/index.ts +846 -0
- package/src/render/mrkdwn.ts +321 -0
- package/src/screenshot.ts +59 -0
- package/src/server.ts +1198 -0
- package/src/socket-mode.ts +261 -0
- package/src/store.ts +654 -0
- package/src/types.ts +159 -0
- package/src/web-api.ts +694 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,1198 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import type { Server } from "bun";
|
|
3
|
+
import { type Args, bearerToken, parseArgs } from "./body.ts";
|
|
4
|
+
import {
|
|
5
|
+
appMentionEvent,
|
|
6
|
+
assistantThreadContextChangedEvent,
|
|
7
|
+
assistantThreadStartedEvent,
|
|
8
|
+
blockActionsPayload,
|
|
9
|
+
eventCallback,
|
|
10
|
+
memberJoinedEvent,
|
|
11
|
+
messageChangedEvent,
|
|
12
|
+
messageDeletedEvent,
|
|
13
|
+
messageEvent,
|
|
14
|
+
reactionEvent,
|
|
15
|
+
slashCommandPayload,
|
|
16
|
+
viewSubmissionPayload,
|
|
17
|
+
} from "./events.ts";
|
|
18
|
+
import { slackId } from "./ids.ts";
|
|
19
|
+
import { renderPage } from "./render/index.ts";
|
|
20
|
+
import {
|
|
21
|
+
type AckResult,
|
|
22
|
+
type ConnData,
|
|
23
|
+
type DeliveryRecord,
|
|
24
|
+
SocketModeClosedError,
|
|
25
|
+
SocketModeHub,
|
|
26
|
+
} from "./socket-mode.ts";
|
|
27
|
+
import {
|
|
28
|
+
type AddChannelInput,
|
|
29
|
+
type AddUserInput,
|
|
30
|
+
ensureDir,
|
|
31
|
+
SlackApiError,
|
|
32
|
+
Store,
|
|
33
|
+
type StoreOptions,
|
|
34
|
+
wireMessage,
|
|
35
|
+
} from "./store.ts";
|
|
36
|
+
import type { ApiCall, Change, SlackChannel, SlackMessage, SlackUser } from "./types.ts";
|
|
37
|
+
import { type Actor, type ApiContext, handlers, newTriggerId } from "./web-api.ts";
|
|
38
|
+
|
|
39
|
+
export interface SlackManifest {
|
|
40
|
+
display_information?: { name?: string };
|
|
41
|
+
features?: {
|
|
42
|
+
bot_user?: { display_name?: string };
|
|
43
|
+
slash_commands?: Array<{ command: string; description?: string }>;
|
|
44
|
+
};
|
|
45
|
+
settings?: { event_subscriptions?: { bot_events?: string[] } };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface SlackMockOptions extends StoreOptions {
|
|
49
|
+
/** 0 picks a free port. */
|
|
50
|
+
port?: number;
|
|
51
|
+
host?: string;
|
|
52
|
+
/** Path to a Slack app manifest JSON, or the parsed manifest. Sets app name, commands and event subscriptions. */
|
|
53
|
+
manifest?: string | SlackManifest;
|
|
54
|
+
/** Create a default workspace (#general, two humans). Default true. */
|
|
55
|
+
seed?: boolean;
|
|
56
|
+
/** Deliver the bot's own messages back as events, like Slack does. Default true. */
|
|
57
|
+
echoBotMessages?: boolean;
|
|
58
|
+
/** Event types (manifest style, e.g. "message.channels") to push to the app. */
|
|
59
|
+
subscribedEvents?: string[];
|
|
60
|
+
pingIntervalMs?: number;
|
|
61
|
+
ackTimeoutMs?: number;
|
|
62
|
+
maxRetries?: number;
|
|
63
|
+
/** How long a trigger_id stays valid for views.open (Slack: 3s). */
|
|
64
|
+
triggerIdTtlMs?: number;
|
|
65
|
+
/** Delay before each event is pushed (emulates Slack latency). */
|
|
66
|
+
eventDelayMs?: number;
|
|
67
|
+
/** Default width of the thread side panel in the HTML UI, e.g. "50%" or "640px". `?panel=` overrides per request. */
|
|
68
|
+
panelWidth?: string;
|
|
69
|
+
log?: boolean | ((msg: string) => void);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface PostMessageInput {
|
|
73
|
+
channel: string;
|
|
74
|
+
/** Sending user id; defaults to the first seeded human. */
|
|
75
|
+
user?: string;
|
|
76
|
+
text: string;
|
|
77
|
+
thread_ts?: string;
|
|
78
|
+
blocks?: unknown[];
|
|
79
|
+
files?: Array<{ name: string; content: string | Uint8Array; title?: string; mimetype?: string }>;
|
|
80
|
+
reply_broadcast?: boolean;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface MessageQuery {
|
|
84
|
+
channel?: string;
|
|
85
|
+
thread_ts?: string;
|
|
86
|
+
/** "bot", "human", or a user id. */
|
|
87
|
+
from?: string;
|
|
88
|
+
text?: string | RegExp;
|
|
89
|
+
/** Match against message.metadata.event_type. */
|
|
90
|
+
event_type?: string;
|
|
91
|
+
/** Include ephemeral messages (default false). */
|
|
92
|
+
ephemeral?: boolean;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const DEFAULT_EVENTS = [
|
|
96
|
+
"message.channels",
|
|
97
|
+
"message.groups",
|
|
98
|
+
"message.im",
|
|
99
|
+
"message.mpim",
|
|
100
|
+
"app_mention",
|
|
101
|
+
"assistant_thread_started",
|
|
102
|
+
"assistant_thread_context_changed",
|
|
103
|
+
"reaction_added",
|
|
104
|
+
"reaction_removed",
|
|
105
|
+
"member_joined_channel",
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
export interface Fault {
|
|
109
|
+
/** Web API method to fail, e.g. "chat.postMessage". */
|
|
110
|
+
method: string;
|
|
111
|
+
/** Slack error code to return, e.g. "ratelimited" or "missing_scope". */
|
|
112
|
+
error: string;
|
|
113
|
+
/** How many calls to fail (default 1). */
|
|
114
|
+
times?: number;
|
|
115
|
+
/** HTTP status (default 200, like Slack). Use 429 with retryAfterSec to test rate limiting. */
|
|
116
|
+
httpStatus?: number;
|
|
117
|
+
retryAfterSec?: number;
|
|
118
|
+
/** Extra body fields, e.g. { needed: "chat:write" }. */
|
|
119
|
+
extra?: Record<string, unknown>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
interface ResponseUrl {
|
|
123
|
+
channel: string;
|
|
124
|
+
user: string;
|
|
125
|
+
/** The message that owns the response_url (for replace_original). */
|
|
126
|
+
messageTs?: string;
|
|
127
|
+
expires: number;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export class SlackMock {
|
|
131
|
+
readonly store: Store;
|
|
132
|
+
readonly hub: SocketModeHub;
|
|
133
|
+
readonly opts: SlackMockOptions;
|
|
134
|
+
private server!: Server<ConnData>;
|
|
135
|
+
private triggerIds = new Map<string, number>();
|
|
136
|
+
private pendingUploads: ApiContext["pendingUploads"] = new Map();
|
|
137
|
+
private responseUrls = new Map<string, ResponseUrl>();
|
|
138
|
+
private inflight = new Set<Promise<void>>();
|
|
139
|
+
private subscribed: Set<string>;
|
|
140
|
+
private commands: Set<string> | null = null;
|
|
141
|
+
private faults: Array<Fault & { remaining: number }> = [];
|
|
142
|
+
private lastRequestAt = 0;
|
|
143
|
+
private log: (msg: string) => void;
|
|
144
|
+
/** Slack-facing errors with the same shape Slack returns. */
|
|
145
|
+
static Error = SlackApiError;
|
|
146
|
+
|
|
147
|
+
constructor(opts: SlackMockOptions = {}) {
|
|
148
|
+
const manifest =
|
|
149
|
+
typeof opts.manifest === "string"
|
|
150
|
+
? (JSON.parse(readFileSync(opts.manifest, "utf8")) as SlackManifest)
|
|
151
|
+
: opts.manifest;
|
|
152
|
+
const appName =
|
|
153
|
+
opts.appName ??
|
|
154
|
+
manifest?.features?.bot_user?.display_name ??
|
|
155
|
+
manifest?.display_information?.name;
|
|
156
|
+
this.opts = { ...opts, appName };
|
|
157
|
+
this.log =
|
|
158
|
+
typeof opts.log === "function"
|
|
159
|
+
? opts.log
|
|
160
|
+
: opts.log
|
|
161
|
+
? (m) => console.log(`[slack-mock] ${m}`)
|
|
162
|
+
: () => {};
|
|
163
|
+
if (opts.dataFile) ensureDir(opts.dataFile);
|
|
164
|
+
this.store = new Store({ ...opts, appName });
|
|
165
|
+
this.hub = new SocketModeHub({
|
|
166
|
+
appId: this.store.app.id,
|
|
167
|
+
pingIntervalMs: opts.pingIntervalMs,
|
|
168
|
+
ackTimeoutMs: opts.ackTimeoutMs,
|
|
169
|
+
maxRetries: opts.maxRetries,
|
|
170
|
+
log: this.log,
|
|
171
|
+
});
|
|
172
|
+
this.subscribed = new Set(
|
|
173
|
+
opts.subscribedEvents ??
|
|
174
|
+
manifest?.settings?.event_subscriptions?.bot_events ??
|
|
175
|
+
DEFAULT_EVENTS,
|
|
176
|
+
);
|
|
177
|
+
if (manifest?.features?.slash_commands)
|
|
178
|
+
this.commands = new Set(manifest.features.slash_commands.map((c) => c.command));
|
|
179
|
+
if (opts.seed !== false && this.store.channels.size === 0) this.seed();
|
|
180
|
+
this.store.onChange((change) => this.dispatch(change));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
static async start(opts: SlackMockOptions = {}): Promise<SlackMock> {
|
|
184
|
+
const mock = new SlackMock(opts);
|
|
185
|
+
mock.listen();
|
|
186
|
+
return mock;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
private seed(): void {
|
|
190
|
+
const alice = this.store.addUser({
|
|
191
|
+
id: "U0ALICE000",
|
|
192
|
+
name: "alice",
|
|
193
|
+
real_name: "Alice Example",
|
|
194
|
+
email: "alice@example.com",
|
|
195
|
+
is_admin: true,
|
|
196
|
+
});
|
|
197
|
+
const bob = this.store.addUser({
|
|
198
|
+
id: "U0BOB00000",
|
|
199
|
+
name: "bob",
|
|
200
|
+
real_name: "Bob Example",
|
|
201
|
+
email: "bob@example.com",
|
|
202
|
+
});
|
|
203
|
+
this.store.addChannel({
|
|
204
|
+
id: "C0GENERAL0",
|
|
205
|
+
name: "general",
|
|
206
|
+
creator: alice.id,
|
|
207
|
+
members: [alice.id, bob.id, this.store.bot.userId],
|
|
208
|
+
purpose: "Company-wide announcements",
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// --------------------------------------------------------------- server
|
|
213
|
+
|
|
214
|
+
listen(): void {
|
|
215
|
+
const host = this.opts.host ?? "127.0.0.1";
|
|
216
|
+
this.server = Bun.serve<ConnData>({
|
|
217
|
+
hostname: host,
|
|
218
|
+
port: this.opts.port ?? 0,
|
|
219
|
+
fetch: (req, server) => this.fetch(req, server),
|
|
220
|
+
websocket: {
|
|
221
|
+
open: (ws) => this.hub.open(ws),
|
|
222
|
+
message: (ws, msg) => this.hub.message(ws, msg),
|
|
223
|
+
close: (ws) => this.hub.close(ws),
|
|
224
|
+
ping: () => {},
|
|
225
|
+
pong: () => {},
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
this.log(`listening on ${this.baseUrl}`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
get baseUrl(): string {
|
|
232
|
+
return `http://${this.server.hostname}:${this.server.port}`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
get apiUrl(): string {
|
|
236
|
+
return `${this.baseUrl}/api/`;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
get port(): number {
|
|
240
|
+
return this.server.port ?? 0;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Environment variables a Bolt app needs to talk to this mock. */
|
|
244
|
+
get env(): Record<string, string> {
|
|
245
|
+
return {
|
|
246
|
+
SLACK_BOT_TOKEN: this.store.bot.token,
|
|
247
|
+
SLACK_APP_TOKEN: this.store.bot.appToken,
|
|
248
|
+
SLACK_API_URL: this.apiUrl,
|
|
249
|
+
SLACK_SIGNING_SECRET: "mock-signing-secret",
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
get bot() {
|
|
254
|
+
return this.store.bot;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
get team() {
|
|
258
|
+
return this.store.team;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async stop(): Promise<void> {
|
|
262
|
+
this.hub.shutdown();
|
|
263
|
+
await Promise.allSettled([...this.inflight]);
|
|
264
|
+
this.server.stop(true);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private async fetch(req: Request, server: Server<ConnData>): Promise<Response | undefined> {
|
|
268
|
+
const url = new URL(req.url);
|
|
269
|
+
const path = url.pathname;
|
|
270
|
+
this.lastRequestAt = Date.now();
|
|
271
|
+
try {
|
|
272
|
+
if (path.startsWith("/link/") || path === "/link") {
|
|
273
|
+
const ticket = url.searchParams.get("ticket") ?? "";
|
|
274
|
+
if (!this.hub.tickets.has(ticket)) return new Response("invalid ticket", { status: 403 });
|
|
275
|
+
this.hub.tickets.delete(ticket);
|
|
276
|
+
if (server.upgrade(req, { data: { id: slackId("S", 6), ticket } })) return undefined;
|
|
277
|
+
return new Response("upgrade failed", { status: 400 });
|
|
278
|
+
}
|
|
279
|
+
if (path.startsWith("/api/")) return await this.handleApi(req, path.slice(5));
|
|
280
|
+
if (path.startsWith("/upload/v1/"))
|
|
281
|
+
return await this.handleUpload(req, path.slice("/upload/v1/".length));
|
|
282
|
+
if (path.startsWith("/files-pri/")) return this.handleDownload(req, path);
|
|
283
|
+
if (path.startsWith("/actions/"))
|
|
284
|
+
return await this.handleResponseUrl(req, path.slice("/actions/".length));
|
|
285
|
+
if (path.startsWith("/mock/")) return await this.handleAdmin(req, path.slice(6), url);
|
|
286
|
+
return this.handleUi(path, url);
|
|
287
|
+
} catch (e) {
|
|
288
|
+
this.log(`unhandled error on ${req.method} ${path}: ${e instanceof Error ? e.stack : e}`);
|
|
289
|
+
return new Response(String(e), { status: 500 });
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private actorFor(token: string | undefined): Actor | null {
|
|
294
|
+
if (!token) return null;
|
|
295
|
+
if (token === this.store.bot.token || token === this.store.bot.appToken)
|
|
296
|
+
return { userId: this.store.bot.userId, isBot: true };
|
|
297
|
+
if (this.store.bot.userToken && token === this.store.bot.userToken) {
|
|
298
|
+
const human = [...this.store.users.values()].find((u) => !u.is_bot);
|
|
299
|
+
return human ? { userId: human.id, isBot: false } : null;
|
|
300
|
+
}
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private async handleApi(req: Request, method: string): Promise<Response> {
|
|
305
|
+
let args: Args = {};
|
|
306
|
+
try {
|
|
307
|
+
args = await parseArgs(req);
|
|
308
|
+
} catch (e) {
|
|
309
|
+
return slackError("invalid_form_data", { detail: String(e) });
|
|
310
|
+
}
|
|
311
|
+
const token = bearerToken(req, args);
|
|
312
|
+
const actor = this.actorFor(token);
|
|
313
|
+
const record = (ok: boolean, error?: string) => {
|
|
314
|
+
const { token: _t, ...rest } = args;
|
|
315
|
+
const call: ApiCall = {
|
|
316
|
+
at: new Date().toISOString(),
|
|
317
|
+
method,
|
|
318
|
+
args: rest,
|
|
319
|
+
ok,
|
|
320
|
+
...(error ? { error } : {}),
|
|
321
|
+
};
|
|
322
|
+
this.store.recordApiCall(call);
|
|
323
|
+
};
|
|
324
|
+
if (!token) {
|
|
325
|
+
record(false, "not_authed");
|
|
326
|
+
return slackError("not_authed");
|
|
327
|
+
}
|
|
328
|
+
if (!actor) {
|
|
329
|
+
record(false, "invalid_auth");
|
|
330
|
+
return slackError("invalid_auth");
|
|
331
|
+
}
|
|
332
|
+
if (method === "apps.connections.open" && token !== this.store.bot.appToken) {
|
|
333
|
+
record(false, "not_allowed_token_type");
|
|
334
|
+
return slackError("not_allowed_token_type");
|
|
335
|
+
}
|
|
336
|
+
const fault = this.faults.find((f) => f.method === method && f.remaining > 0);
|
|
337
|
+
if (fault) {
|
|
338
|
+
fault.remaining -= 1;
|
|
339
|
+
record(false, fault.error);
|
|
340
|
+
this.log(`${method} -> injected ${fault.error}`);
|
|
341
|
+
return Response.json(
|
|
342
|
+
{
|
|
343
|
+
ok: false,
|
|
344
|
+
error: fault.error,
|
|
345
|
+
...(fault.retryAfterSec ? { retry_after: fault.retryAfterSec } : {}),
|
|
346
|
+
...fault.extra,
|
|
347
|
+
},
|
|
348
|
+
{
|
|
349
|
+
status: fault.httpStatus ?? 200,
|
|
350
|
+
headers: fault.retryAfterSec ? { "retry-after": String(fault.retryAfterSec) } : {},
|
|
351
|
+
},
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
const handler = handlers[method];
|
|
355
|
+
if (!handler) {
|
|
356
|
+
record(false, "unknown_method");
|
|
357
|
+
return slackError("unknown_method", { req_method: method });
|
|
358
|
+
}
|
|
359
|
+
const ctx: ApiContext = {
|
|
360
|
+
store: this.store,
|
|
361
|
+
hub: this.hub,
|
|
362
|
+
baseUrl: this.baseUrl,
|
|
363
|
+
wsUrl: this.baseUrl.replace(/^http/, "ws"),
|
|
364
|
+
actor,
|
|
365
|
+
triggerIds: this.triggerIds,
|
|
366
|
+
pendingUploads: this.pendingUploads,
|
|
367
|
+
};
|
|
368
|
+
try {
|
|
369
|
+
const body = handler(ctx, args);
|
|
370
|
+
record(true);
|
|
371
|
+
return Response.json({ ok: true, ...body });
|
|
372
|
+
} catch (e) {
|
|
373
|
+
if (e instanceof SlackApiError) {
|
|
374
|
+
record(false, e.code);
|
|
375
|
+
this.log(`${method} -> ${e.code}`);
|
|
376
|
+
return slackError(e.code, e.extra);
|
|
377
|
+
}
|
|
378
|
+
throw e;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private async handleUpload(req: Request, fileId: string): Promise<Response> {
|
|
383
|
+
const pending = this.pendingUploads.get(fileId);
|
|
384
|
+
if (!pending) return new Response("unknown upload", { status: 404 });
|
|
385
|
+
let bytes: Uint8Array;
|
|
386
|
+
const contentType = req.headers.get("content-type") ?? "";
|
|
387
|
+
if (contentType.includes("multipart/form-data")) {
|
|
388
|
+
const form = await req.formData();
|
|
389
|
+
let part: File | undefined;
|
|
390
|
+
form.forEach((v) => {
|
|
391
|
+
if (typeof v !== "string" && !part) part = v;
|
|
392
|
+
});
|
|
393
|
+
bytes = part ? new Uint8Array(await part.arrayBuffer()) : new Uint8Array();
|
|
394
|
+
} else {
|
|
395
|
+
bytes = new Uint8Array(await req.arrayBuffer());
|
|
396
|
+
}
|
|
397
|
+
this.pendingUploads.delete(fileId);
|
|
398
|
+
this.store.addFile({
|
|
399
|
+
id: fileId,
|
|
400
|
+
name: pending.name,
|
|
401
|
+
user: pending.user,
|
|
402
|
+
bytes,
|
|
403
|
+
baseUrl: this.baseUrl,
|
|
404
|
+
});
|
|
405
|
+
return new Response("OK");
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
private handleDownload(req: Request, path: string): Response {
|
|
409
|
+
const m = /^\/files-pri\/[A-Z0-9]+-([A-Z0-9]+)\/(?:download\/)?/.exec(path);
|
|
410
|
+
const file = m ? this.store.files.get(m[1]!) : undefined;
|
|
411
|
+
if (!file) return new Response("not found", { status: 404 });
|
|
412
|
+
const token = bearerToken(req, {}) ?? new URL(req.url).searchParams.get("t") ?? undefined;
|
|
413
|
+
if (!this.actorFor(token)) return new Response("authentication required", { status: 401 });
|
|
414
|
+
return new Response(Buffer.from(file.bytes ?? new Uint8Array()), {
|
|
415
|
+
headers: {
|
|
416
|
+
"content-type": file.mimetype,
|
|
417
|
+
"content-disposition": `attachment; filename="${file.name}"`,
|
|
418
|
+
"content-length": String(file.size),
|
|
419
|
+
},
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
private async handleResponseUrl(req: Request, id: string): Promise<Response> {
|
|
424
|
+
const target = this.responseUrls.get(id);
|
|
425
|
+
if (!target) return new Response("invalid response_url", { status: 404 });
|
|
426
|
+
if (Date.now() > target.expires) return new Response("expired_url", { status: 410 });
|
|
427
|
+
let body: {
|
|
428
|
+
text?: string;
|
|
429
|
+
blocks?: unknown[];
|
|
430
|
+
attachments?: unknown[];
|
|
431
|
+
response_type?: string;
|
|
432
|
+
replace_original?: boolean | string;
|
|
433
|
+
delete_original?: boolean | string;
|
|
434
|
+
thread_ts?: string;
|
|
435
|
+
};
|
|
436
|
+
try {
|
|
437
|
+
body = (await parseArgs(req)) as typeof body;
|
|
438
|
+
} catch (e) {
|
|
439
|
+
return Response.json(
|
|
440
|
+
{ ok: false, error: "invalid_payload", detail: String(e) },
|
|
441
|
+
{ status: 400 },
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
const isTrue = (v: unknown) => v === true || v === "true";
|
|
445
|
+
try {
|
|
446
|
+
if (isTrue(body.delete_original) && target.messageTs) {
|
|
447
|
+
if (this.store.findMessage(target.channel, target.messageTs))
|
|
448
|
+
this.store.deleteMessage(target.channel, target.messageTs);
|
|
449
|
+
else this.store.deleteEphemeral(target.channel, target.messageTs);
|
|
450
|
+
return new Response("ok");
|
|
451
|
+
}
|
|
452
|
+
if (isTrue(body.replace_original) && target.messageTs) {
|
|
453
|
+
const patch = { text: body.text ?? "", blocks: body.blocks, attachments: body.attachments };
|
|
454
|
+
if (this.store.findMessage(target.channel, target.messageTs))
|
|
455
|
+
this.store.updateMessage(target.channel, target.messageTs, patch, this.store.bot.userId);
|
|
456
|
+
else this.store.updateEphemeral(target.channel, target.messageTs, patch);
|
|
457
|
+
return new Response("ok");
|
|
458
|
+
}
|
|
459
|
+
} catch (e) {
|
|
460
|
+
if (e instanceof SlackApiError) return Response.json({ ok: false, error: e.code });
|
|
461
|
+
throw e;
|
|
462
|
+
}
|
|
463
|
+
this.postAsBot({
|
|
464
|
+
channel: target.channel,
|
|
465
|
+
text: body.text ?? "",
|
|
466
|
+
blocks: body.blocks,
|
|
467
|
+
attachments: body.attachments,
|
|
468
|
+
thread_ts: body.thread_ts,
|
|
469
|
+
ephemeral_user: body.response_type === "in_channel" ? undefined : target.user,
|
|
470
|
+
});
|
|
471
|
+
return new Response("ok");
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
private postAsBot(input: {
|
|
475
|
+
channel: string;
|
|
476
|
+
text: string;
|
|
477
|
+
blocks?: unknown[];
|
|
478
|
+
attachments?: unknown[];
|
|
479
|
+
thread_ts?: string;
|
|
480
|
+
ephemeral_user?: string;
|
|
481
|
+
}): SlackMessage {
|
|
482
|
+
return this.store.addMessage({
|
|
483
|
+
channel: input.channel,
|
|
484
|
+
user: this.store.bot.userId,
|
|
485
|
+
text: input.text,
|
|
486
|
+
blocks: input.blocks,
|
|
487
|
+
attachments: input.attachments,
|
|
488
|
+
...(input.thread_ts ? { thread_ts: input.thread_ts } : {}),
|
|
489
|
+
...(input.ephemeral_user ? { ephemeral_user: input.ephemeral_user } : {}),
|
|
490
|
+
bot_id: this.store.bot.botId,
|
|
491
|
+
app_id: this.store.app.id,
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
private handleUi(path: string, url: URL): Response {
|
|
496
|
+
const screenshotParam = url.searchParams.get("screenshot");
|
|
497
|
+
const screenshot =
|
|
498
|
+
screenshotParam !== null && screenshotParam !== "0" && screenshotParam !== "false";
|
|
499
|
+
const refresh = Number(url.searchParams.get("refresh"));
|
|
500
|
+
const panel = url.searchParams.get("panel") ?? this.opts.panelWidth;
|
|
501
|
+
const opts = {
|
|
502
|
+
screenshot,
|
|
503
|
+
refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
|
|
504
|
+
connections: this.hub.connectionCount,
|
|
505
|
+
panelWidth: panel
|
|
506
|
+
? /^\d+$/.test(panel)
|
|
507
|
+
? `${panel}%`
|
|
508
|
+
: /^\d+(px|%|vw|rem)$/.test(panel)
|
|
509
|
+
? panel
|
|
510
|
+
: undefined
|
|
511
|
+
: undefined,
|
|
512
|
+
threadView: url.searchParams.has("full") ? ("full" as const) : ("panel" as const),
|
|
513
|
+
};
|
|
514
|
+
let html: string;
|
|
515
|
+
if (path === "/" || path === "") html = renderPage(this.store, { kind: "index" }, opts);
|
|
516
|
+
else {
|
|
517
|
+
const m = /^\/c\/([^/]+)(?:\/t\/([^/]+))?\/?$/.exec(path);
|
|
518
|
+
if (!m) return new Response("not found", { status: 404 });
|
|
519
|
+
const channel = this.store.channelByName(m[1]!)?.id ?? m[1]!;
|
|
520
|
+
if (!this.store.channels.has(channel))
|
|
521
|
+
return new Response("channel not found", { status: 404 });
|
|
522
|
+
html = m[2]
|
|
523
|
+
? renderPage(this.store, { kind: "thread", channel, ts: m[2] }, opts)
|
|
524
|
+
: renderPage(this.store, { kind: "channel", channel }, opts);
|
|
525
|
+
}
|
|
526
|
+
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// -------------------------------------------------- event dispatching
|
|
530
|
+
|
|
531
|
+
private isSubscribed(type: string): boolean {
|
|
532
|
+
return this.subscribed.has(type);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Manifest event name for a message in this channel: message.channels / groups / im / mpim. */
|
|
536
|
+
private messageEventName(channel: SlackChannel): string {
|
|
537
|
+
const t = this.store.channelType(channel);
|
|
538
|
+
return `message.${t === "channel" ? "channels" : t === "group" ? "groups" : t}`;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
private track(p: Promise<unknown>): Promise<void> {
|
|
542
|
+
const wrapped = p.then(
|
|
543
|
+
() => {},
|
|
544
|
+
(e) => {
|
|
545
|
+
if (!(e instanceof SocketModeClosedError))
|
|
546
|
+
this.log(`delivery failed: ${e instanceof Error ? e.message : e}`);
|
|
547
|
+
},
|
|
548
|
+
);
|
|
549
|
+
this.inflight.add(wrapped);
|
|
550
|
+
wrapped.finally(() => this.inflight.delete(wrapped));
|
|
551
|
+
return wrapped;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
private push(event: Record<string, unknown>): Promise<void> {
|
|
555
|
+
if (this.hub.connectionCount === 0) {
|
|
556
|
+
this.log(
|
|
557
|
+
`dropping ${event.type}${event.subtype ? `/${event.subtype}` : ""} event: no app connected`,
|
|
558
|
+
);
|
|
559
|
+
return Promise.resolve();
|
|
560
|
+
}
|
|
561
|
+
const send = async () => {
|
|
562
|
+
if (this.opts.eventDelayMs) await Bun.sleep(this.opts.eventDelayMs);
|
|
563
|
+
await this.hub.send("events_api", eventCallback(this.store, event));
|
|
564
|
+
};
|
|
565
|
+
return this.track(send());
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
private botInChannel(channel: SlackChannel): boolean {
|
|
569
|
+
return channel.members.includes(this.store.bot.userId);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
private dispatch(change: Change): void {
|
|
573
|
+
switch (change.kind) {
|
|
574
|
+
case "message.add": {
|
|
575
|
+
const m = change.message;
|
|
576
|
+
if (m.ephemeral_user || m.subtype === "assistant_app_thread") return;
|
|
577
|
+
const channel = this.store.channel(m.channel);
|
|
578
|
+
if (!this.botInChannel(channel)) return;
|
|
579
|
+
const fromBot = this.store.isBotUser(m.user);
|
|
580
|
+
if (fromBot && this.opts.echoBotMessages === false) return;
|
|
581
|
+
const mentionsBot = !fromBot && m.text.includes(`<@${this.store.bot.userId}>`);
|
|
582
|
+
if (mentionsBot && this.isSubscribed("app_mention"))
|
|
583
|
+
this.push(appMentionEvent(this.store, m));
|
|
584
|
+
if (this.isSubscribed(this.messageEventName(channel)))
|
|
585
|
+
this.push(messageEvent(this.store, m, channel));
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
case "message.update": {
|
|
589
|
+
const channel = this.store.channel(change.message.channel);
|
|
590
|
+
if (this.botInChannel(channel) && this.isSubscribed(this.messageEventName(channel))) {
|
|
591
|
+
this.push(messageChangedEvent(this.store, change.message, change.previous));
|
|
592
|
+
}
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
case "message.delete": {
|
|
596
|
+
const channel = this.store.channel(change.message.channel);
|
|
597
|
+
if (this.botInChannel(channel) && this.isSubscribed(this.messageEventName(channel))) {
|
|
598
|
+
this.push(messageDeletedEvent(this.store, change.message));
|
|
599
|
+
}
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
case "reaction.add":
|
|
603
|
+
case "reaction.remove": {
|
|
604
|
+
const kind = change.kind === "reaction.add" ? "reaction_added" : "reaction_removed";
|
|
605
|
+
if (
|
|
606
|
+
this.isSubscribed(kind) &&
|
|
607
|
+
this.botInChannel(this.store.channel(change.message.channel))
|
|
608
|
+
) {
|
|
609
|
+
this.push(reactionEvent(kind, change.message, change.name, change.user));
|
|
610
|
+
}
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
case "member.join": {
|
|
614
|
+
if (this.isSubscribed("member_joined_channel") && this.botInChannel(change.channel)) {
|
|
615
|
+
this.push(memberJoinedEvent(this.store, change.channel, change.user, change.inviter));
|
|
616
|
+
}
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
default:
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Wait until every event pushed so far has been acked (or dropped) and the app
|
|
626
|
+
* has been quiet on the HTTP side for `settleMs` (so respond() calls that follow
|
|
627
|
+
* an ack have landed). Bounded by `maxMs`.
|
|
628
|
+
*/
|
|
629
|
+
async flush(settleMs = 100, maxMs = 3000): Promise<void> {
|
|
630
|
+
const start = Date.now();
|
|
631
|
+
for (;;) {
|
|
632
|
+
while (this.inflight.size > 0) await Promise.allSettled([...this.inflight]);
|
|
633
|
+
const quietSince = Math.max(this.lastRequestAt, start);
|
|
634
|
+
const quiet = Date.now() - quietSince;
|
|
635
|
+
if (quiet >= settleMs || Date.now() - start > maxMs) return;
|
|
636
|
+
await Bun.sleep(settleMs - quiet + 5);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// --------------------------------------------------- test-facing API
|
|
641
|
+
|
|
642
|
+
addUser(input: AddUserInput): SlackUser {
|
|
643
|
+
return this.store.addUser(input);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
addChannel(input: AddChannelInput & { withBot?: boolean }): SlackChannel {
|
|
647
|
+
const members = [...(input.members ?? [])];
|
|
648
|
+
if (input.withBot !== false) members.push(this.store.bot.userId);
|
|
649
|
+
const creator =
|
|
650
|
+
input.creator ??
|
|
651
|
+
(input.withBot === false ? (members[0] ?? this.defaultHuman().id) : this.store.bot.userId);
|
|
652
|
+
return this.store.addChannel({ ...input, creator, members });
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
openDm(user: string): SlackChannel {
|
|
656
|
+
return this.store.openDm(user);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
invite(channel: string, users: string[], inviter?: string): void {
|
|
660
|
+
for (const u of users) this.store.join(this.resolveChannel(channel).id, u, inviter);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
user(idOrName: string): SlackUser {
|
|
664
|
+
const byId = this.store.users.get(idOrName);
|
|
665
|
+
if (byId) return byId;
|
|
666
|
+
for (const u of this.store.users.values()) if (u.name === idOrName) return u;
|
|
667
|
+
throw new SlackApiError("user_not_found");
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
channel(idOrName: string): SlackChannel {
|
|
671
|
+
return this.resolveChannel(idOrName);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
private resolveChannel(idOrName: string): SlackChannel {
|
|
675
|
+
return (
|
|
676
|
+
this.store.channels.get(idOrName) ??
|
|
677
|
+
this.store.channelByName(idOrName) ??
|
|
678
|
+
this.store.channel(idOrName)
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
private defaultHuman(): SlackUser {
|
|
683
|
+
const u = [...this.store.users.values()].find((x) => !x.is_bot);
|
|
684
|
+
if (!u) throw new Error("no human user in the workspace; call addUser first");
|
|
685
|
+
return u;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/** Turn `@name` and `@here` / `@channel` in human-typed text into Slack mention syntax. */
|
|
689
|
+
resolveMentions(text: string): string {
|
|
690
|
+
const byName = new Map<string, string>();
|
|
691
|
+
for (const u of this.store.users.values()) byName.set(u.name.toLowerCase(), u.id);
|
|
692
|
+
return text.replace(/(^|[^<\w])@([\w.-]+)/g, (whole, lead: string, name: string) => {
|
|
693
|
+
const lower = name.toLowerCase();
|
|
694
|
+
if (lower === "here" || lower === "channel" || lower === "everyone")
|
|
695
|
+
return `${lead}<!${lower}>`;
|
|
696
|
+
const id = byName.get(lower);
|
|
697
|
+
return id ? `${lead}<@${id}>` : whole;
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/** A human posts a message; resolves once the app acked the resulting events. */
|
|
702
|
+
async postMessage(input: PostMessageInput): Promise<SlackMessage> {
|
|
703
|
+
const channel = this.resolveChannel(input.channel);
|
|
704
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
705
|
+
if (!channel.members.includes(user.id)) this.store.join(channel.id, user.id);
|
|
706
|
+
const files = input.files?.map((f) =>
|
|
707
|
+
this.store.addFile({
|
|
708
|
+
name: f.name,
|
|
709
|
+
title: f.title,
|
|
710
|
+
mimetype: f.mimetype,
|
|
711
|
+
user: user.id,
|
|
712
|
+
bytes: typeof f.content === "string" ? new TextEncoder().encode(f.content) : f.content,
|
|
713
|
+
baseUrl: this.baseUrl,
|
|
714
|
+
}),
|
|
715
|
+
);
|
|
716
|
+
for (const f of files ?? []) f.channels.push(channel.id);
|
|
717
|
+
const before = new Set(this.inflight);
|
|
718
|
+
const message = this.store.addMessage({
|
|
719
|
+
channel: channel.id,
|
|
720
|
+
user: user.id,
|
|
721
|
+
text: input.text,
|
|
722
|
+
client_msg_id: crypto.randomUUID(),
|
|
723
|
+
...(input.thread_ts ? { thread_ts: input.thread_ts } : {}),
|
|
724
|
+
...(input.reply_broadcast && input.thread_ts ? { subtype: "thread_broadcast" } : {}),
|
|
725
|
+
...(input.blocks ? { blocks: input.blocks } : {}),
|
|
726
|
+
...(files?.length ? { files, subtype: "file_share" } : {}),
|
|
727
|
+
});
|
|
728
|
+
await Promise.allSettled([...this.inflight].filter((p) => !before.has(p)));
|
|
729
|
+
return message;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** A human edits their message. */
|
|
733
|
+
async editMessage(channel: string, ts: string, text: string): Promise<SlackMessage> {
|
|
734
|
+
const c = this.resolveChannel(channel);
|
|
735
|
+
const existing = this.store.message(c.id, ts);
|
|
736
|
+
const message = this.store.updateMessage(
|
|
737
|
+
c.id,
|
|
738
|
+
ts,
|
|
739
|
+
{ text },
|
|
740
|
+
existing.user ?? this.defaultHuman().id,
|
|
741
|
+
);
|
|
742
|
+
await this.flush();
|
|
743
|
+
return message;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
async deleteMessage(channel: string, ts: string): Promise<void> {
|
|
747
|
+
this.store.deleteMessage(this.resolveChannel(channel).id, ts);
|
|
748
|
+
await this.flush();
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
async addReaction(input: {
|
|
752
|
+
channel: string;
|
|
753
|
+
ts: string;
|
|
754
|
+
name: string;
|
|
755
|
+
user?: string;
|
|
756
|
+
}): Promise<void> {
|
|
757
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
758
|
+
this.store.addReaction(this.resolveChannel(input.channel).id, input.ts, input.name, user.id);
|
|
759
|
+
await this.flush();
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
private issueResponseUrl(target: Omit<ResponseUrl, "expires">): string {
|
|
763
|
+
const id = `${this.store.team.id}/${slackId("", 10)}/${slackId("", 24).toLowerCase()}`;
|
|
764
|
+
this.responseUrls.set(id, { ...target, expires: Date.now() + 30 * 60_000 });
|
|
765
|
+
return `${this.baseUrl}/actions/${id}`;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
private issueTriggerId(): string {
|
|
769
|
+
const id = newTriggerId();
|
|
770
|
+
this.triggerIds.set(id, Date.now() + (this.opts.triggerIdTtlMs ?? 3000));
|
|
771
|
+
return id;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** A human runs a slash command. Resolves with the app's ack payload and any message it produced. */
|
|
775
|
+
async slashCommand(input: {
|
|
776
|
+
command: string;
|
|
777
|
+
text?: string;
|
|
778
|
+
user?: string;
|
|
779
|
+
channel?: string;
|
|
780
|
+
}): Promise<{ ack: AckResult; response?: SlackMessage }> {
|
|
781
|
+
if (this.commands && !this.commands.has(input.command))
|
|
782
|
+
throw new Error(
|
|
783
|
+
`unknown slash command ${input.command}; manifest declares ${[...this.commands].join(", ")}`,
|
|
784
|
+
);
|
|
785
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
786
|
+
const channel = input.channel
|
|
787
|
+
? this.resolveChannel(input.channel)
|
|
788
|
+
: (this.store.channelByName("general") ?? this.openDm(user.id));
|
|
789
|
+
const responseUrl = this.issueResponseUrl({ channel: channel.id, user: user.id });
|
|
790
|
+
const payload = slashCommandPayload(this.store, {
|
|
791
|
+
command: input.command,
|
|
792
|
+
text: input.text ?? "",
|
|
793
|
+
user,
|
|
794
|
+
channel,
|
|
795
|
+
responseUrl,
|
|
796
|
+
triggerId: this.issueTriggerId(),
|
|
797
|
+
});
|
|
798
|
+
const ack = await this.hub.send("slash_commands", payload, true);
|
|
799
|
+
let response: SlackMessage | undefined;
|
|
800
|
+
const body = ack.payload as
|
|
801
|
+
| { text?: string; blocks?: unknown[]; response_type?: string }
|
|
802
|
+
| undefined;
|
|
803
|
+
if (body && (body.text || body.blocks)) {
|
|
804
|
+
response = this.postAsBot({
|
|
805
|
+
channel: channel.id,
|
|
806
|
+
text: body.text ?? "",
|
|
807
|
+
blocks: body.blocks,
|
|
808
|
+
ephemeral_user: body.response_type === "in_channel" ? undefined : user.id,
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
await this.flush();
|
|
812
|
+
return { ack, response };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** A human clicks a button on a message. */
|
|
816
|
+
async clickButton(input: {
|
|
817
|
+
channel: string;
|
|
818
|
+
ts: string;
|
|
819
|
+
action_id: string;
|
|
820
|
+
user?: string;
|
|
821
|
+
value?: string;
|
|
822
|
+
block_id?: string;
|
|
823
|
+
text?: string;
|
|
824
|
+
}): Promise<AckResult> {
|
|
825
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
826
|
+
const channel = this.resolveChannel(input.channel);
|
|
827
|
+
const message =
|
|
828
|
+
this.store.findMessage(channel.id, input.ts) ??
|
|
829
|
+
this.store.ephemerals.find((m) => m.channel === channel.id && m.ts === input.ts);
|
|
830
|
+
if (!message) throw new SlackApiError("message_not_found");
|
|
831
|
+
const found = findButton(message.blocks, input.action_id);
|
|
832
|
+
if (!found && !input.value && !input.block_id)
|
|
833
|
+
throw new Error(`no button with action_id ${input.action_id} on message ${input.ts}`);
|
|
834
|
+
const responseUrl = this.issueResponseUrl({
|
|
835
|
+
channel: channel.id,
|
|
836
|
+
user: user.id,
|
|
837
|
+
messageTs: message.ts,
|
|
838
|
+
});
|
|
839
|
+
const payload = blockActionsPayload(this.store, {
|
|
840
|
+
user,
|
|
841
|
+
channel,
|
|
842
|
+
message,
|
|
843
|
+
responseUrl,
|
|
844
|
+
triggerId: this.issueTriggerId(),
|
|
845
|
+
actions: [
|
|
846
|
+
{
|
|
847
|
+
type: "button",
|
|
848
|
+
action_id: input.action_id,
|
|
849
|
+
block_id: input.block_id ?? found?.block_id ?? slackId("", 5),
|
|
850
|
+
text: found?.text ?? {
|
|
851
|
+
type: "plain_text",
|
|
852
|
+
text: input.text ?? input.action_id,
|
|
853
|
+
emoji: true,
|
|
854
|
+
},
|
|
855
|
+
value: input.value ?? found?.value,
|
|
856
|
+
...(found?.style ? { style: found.style } : {}),
|
|
857
|
+
},
|
|
858
|
+
],
|
|
859
|
+
});
|
|
860
|
+
const ack = await this.hub.send("interactive", payload, true);
|
|
861
|
+
await this.flush();
|
|
862
|
+
return ack;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** A human submits the most recently opened modal (or the one with the given id / callback_id). */
|
|
866
|
+
async submitView(input: {
|
|
867
|
+
values: Record<string, Record<string, unknown>>;
|
|
868
|
+
user?: string;
|
|
869
|
+
view_id?: string;
|
|
870
|
+
callback_id?: string;
|
|
871
|
+
}): Promise<AckResult> {
|
|
872
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
873
|
+
const views = [...this.store.views.values()];
|
|
874
|
+
const view = input.view_id
|
|
875
|
+
? this.store.views.get(input.view_id)
|
|
876
|
+
: input.callback_id
|
|
877
|
+
? views.reverse().find((v) => v.callback_id === input.callback_id)
|
|
878
|
+
: views.at(-1);
|
|
879
|
+
if (!view) throw new Error("no open view to submit");
|
|
880
|
+
view.state = { values: input.values };
|
|
881
|
+
const payload = viewSubmissionPayload(this.store, {
|
|
882
|
+
user,
|
|
883
|
+
view,
|
|
884
|
+
values: input.values,
|
|
885
|
+
triggerId: this.issueTriggerId(),
|
|
886
|
+
});
|
|
887
|
+
const ack = await this.hub.send("interactive", payload, true);
|
|
888
|
+
// Slack keeps the modal open on `errors`, swaps it on `update`, stacks on `push`, closes otherwise.
|
|
889
|
+
const response = (ack.payload ?? {}) as {
|
|
890
|
+
response_action?: string;
|
|
891
|
+
view?: Record<string, unknown>;
|
|
892
|
+
errors?: Record<string, string>;
|
|
893
|
+
};
|
|
894
|
+
if (response.response_action === "errors") {
|
|
895
|
+
view.state = { values: input.values };
|
|
896
|
+
} else if (response.response_action === "update" && response.view) {
|
|
897
|
+
Object.assign(view, {
|
|
898
|
+
callback_id: response.view.callback_id ?? view.callback_id,
|
|
899
|
+
private_metadata: response.view.private_metadata ?? view.private_metadata,
|
|
900
|
+
title: response.view.title ?? view.title,
|
|
901
|
+
submit: response.view.submit ?? view.submit,
|
|
902
|
+
blocks: Array.isArray(response.view.blocks) ? response.view.blocks : view.blocks,
|
|
903
|
+
});
|
|
904
|
+
} else if (response.response_action === "push" && response.view) {
|
|
905
|
+
this.store.openView({
|
|
906
|
+
type: "modal",
|
|
907
|
+
callback_id: response.view.callback_id as string | undefined,
|
|
908
|
+
private_metadata: (response.view.private_metadata as string | undefined) ?? "",
|
|
909
|
+
title: response.view.title,
|
|
910
|
+
submit: response.view.submit,
|
|
911
|
+
close: response.view.close,
|
|
912
|
+
blocks: Array.isArray(response.view.blocks) ? response.view.blocks : [],
|
|
913
|
+
opened_by: user.id,
|
|
914
|
+
trigger_id: payload.trigger_id as string,
|
|
915
|
+
state: { values: {} },
|
|
916
|
+
clear_on_close: false,
|
|
917
|
+
notify_on_close: false,
|
|
918
|
+
});
|
|
919
|
+
} else if (response.response_action === "clear") {
|
|
920
|
+
this.store.views.clear();
|
|
921
|
+
} else {
|
|
922
|
+
this.store.views.delete(view.id);
|
|
923
|
+
}
|
|
924
|
+
await this.flush();
|
|
925
|
+
return ack;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** A human opens the app's assistant pane; returns the DM thread to talk in. */
|
|
929
|
+
async startAssistantThread(
|
|
930
|
+
input: { user?: string; context?: Record<string, unknown> } = {},
|
|
931
|
+
): Promise<{ channel: string; thread_ts: string }> {
|
|
932
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
933
|
+
const dm = this.store.openDm(user.id);
|
|
934
|
+
// Slack roots every assistant thread with a hidden "New chat" message the user owns.
|
|
935
|
+
const root = this.store.addMessage({
|
|
936
|
+
channel: dm.id,
|
|
937
|
+
user: user.id,
|
|
938
|
+
subtype: "assistant_app_thread",
|
|
939
|
+
text: "New chat",
|
|
940
|
+
});
|
|
941
|
+
const threadTs = root.ts;
|
|
942
|
+
if (this.isSubscribed("assistant_thread_started")) {
|
|
943
|
+
await this.track(
|
|
944
|
+
this.hub.send(
|
|
945
|
+
"events_api",
|
|
946
|
+
eventCallback(
|
|
947
|
+
this.store,
|
|
948
|
+
assistantThreadStartedEvent(this.store, dm, user.id, threadTs, input.context),
|
|
949
|
+
),
|
|
950
|
+
),
|
|
951
|
+
);
|
|
952
|
+
}
|
|
953
|
+
return { channel: dm.id, thread_ts: threadTs };
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
async changeAssistantContext(input: {
|
|
957
|
+
channel: string;
|
|
958
|
+
thread_ts: string;
|
|
959
|
+
context: Record<string, unknown>;
|
|
960
|
+
user?: string;
|
|
961
|
+
}): Promise<void> {
|
|
962
|
+
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
963
|
+
const dm = this.resolveChannel(input.channel);
|
|
964
|
+
await this.track(
|
|
965
|
+
this.hub.send(
|
|
966
|
+
"events_api",
|
|
967
|
+
eventCallback(
|
|
968
|
+
this.store,
|
|
969
|
+
assistantThreadContextChangedEvent(
|
|
970
|
+
this.store,
|
|
971
|
+
dm,
|
|
972
|
+
user.id,
|
|
973
|
+
input.thread_ts,
|
|
974
|
+
input.context,
|
|
975
|
+
),
|
|
976
|
+
),
|
|
977
|
+
),
|
|
978
|
+
);
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
assistantThread(channel: string, thread_ts: string) {
|
|
982
|
+
return this.store.assistantThreads.get(`${this.resolveChannel(channel).id}:${thread_ts}`) ?? {};
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// ----------------------------------------------------------- queries
|
|
986
|
+
|
|
987
|
+
messages(channel: string): SlackMessage[] {
|
|
988
|
+
return [...(this.store.messages.get(this.resolveChannel(channel).id) ?? [])];
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
thread(channel: string, ts: string): SlackMessage[] {
|
|
992
|
+
return this.store.replies(this.resolveChannel(channel).id, ts, { limit: 1000 }).items;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
ephemeralMessages(channel?: string): SlackMessage[] {
|
|
996
|
+
const id = channel ? this.resolveChannel(channel).id : undefined;
|
|
997
|
+
return this.store.ephemerals.filter((m) => !id || m.channel === id);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/** Make the next call(s) to a Web API method fail with a Slack error. */
|
|
1001
|
+
injectFault(fault: Fault): void {
|
|
1002
|
+
this.faults.push({ ...fault, remaining: fault.times ?? 1 });
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
/** Every Socket Mode envelope pushed to the app, with ack status. */
|
|
1006
|
+
deliveries(name?: string): DeliveryRecord[] {
|
|
1007
|
+
return name ? this.hub.history.filter((d) => d.name === name) : [...this.hub.history];
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
apiCalls(method?: string): ApiCall[] {
|
|
1011
|
+
return method
|
|
1012
|
+
? this.store.apiCalls.filter((c) => c.method === method)
|
|
1013
|
+
: [...this.store.apiCalls];
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
private matches(m: SlackMessage, q: MessageQuery): boolean {
|
|
1017
|
+
if (m.ephemeral_user && !q.ephemeral) return false;
|
|
1018
|
+
if (q.channel && m.channel !== this.resolveChannel(q.channel).id) return false;
|
|
1019
|
+
if (q.thread_ts && m.thread_ts !== q.thread_ts && m.ts !== q.thread_ts) return false;
|
|
1020
|
+
if (q.from === "bot" && !this.store.isBotUser(m.user)) return false;
|
|
1021
|
+
if (q.from === "human" && this.store.isBotUser(m.user)) return false;
|
|
1022
|
+
if (q.from && q.from !== "bot" && q.from !== "human" && m.user !== this.user(q.from).id)
|
|
1023
|
+
return false;
|
|
1024
|
+
if (q.event_type && m.metadata?.event_type !== q.event_type) return false;
|
|
1025
|
+
if (typeof q.text === "string" && !m.text.includes(q.text)) return false;
|
|
1026
|
+
if (q.text instanceof RegExp && !q.text.test(m.text)) return false;
|
|
1027
|
+
return true;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
findMessages(q: MessageQuery): SlackMessage[] {
|
|
1031
|
+
const all = [...this.store.messages.values()]
|
|
1032
|
+
.flat()
|
|
1033
|
+
.concat(q.ephemeral ? this.store.ephemerals : []);
|
|
1034
|
+
return all.filter((m) => this.matches(m, q));
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/** Resolve with the first message (existing or future) that matches. */
|
|
1038
|
+
waitForMessage(
|
|
1039
|
+
q: MessageQuery | ((m: SlackMessage) => boolean),
|
|
1040
|
+
opts: { timeoutMs?: number; after?: string } = {},
|
|
1041
|
+
): Promise<SlackMessage> {
|
|
1042
|
+
const test = typeof q === "function" ? q : (m: SlackMessage) => this.matches(m, q);
|
|
1043
|
+
const after = opts.after ? Number(opts.after) : -1;
|
|
1044
|
+
const existing = [...this.store.messages.values()]
|
|
1045
|
+
.flat()
|
|
1046
|
+
.concat(this.store.ephemerals)
|
|
1047
|
+
.find((m) => Number(m.ts) > after && test(m));
|
|
1048
|
+
if (existing) return Promise.resolve(existing);
|
|
1049
|
+
return new Promise((resolve, reject) => {
|
|
1050
|
+
const timer = setTimeout(() => {
|
|
1051
|
+
off();
|
|
1052
|
+
reject(
|
|
1053
|
+
new Error(`timed out after ${opts.timeoutMs ?? 10_000}ms waiting for a matching message`),
|
|
1054
|
+
);
|
|
1055
|
+
}, opts.timeoutMs ?? 10_000);
|
|
1056
|
+
const off = this.store.onChange((c) => {
|
|
1057
|
+
if (
|
|
1058
|
+
(c.kind === "message.add" || c.kind === "message.update") &&
|
|
1059
|
+
Number(c.message.ts) > after &&
|
|
1060
|
+
test(c.message)
|
|
1061
|
+
) {
|
|
1062
|
+
clearTimeout(timer);
|
|
1063
|
+
off();
|
|
1064
|
+
resolve(c.message);
|
|
1065
|
+
}
|
|
1066
|
+
});
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
waitForApiCall(
|
|
1071
|
+
method: string,
|
|
1072
|
+
opts: { timeoutMs?: number; where?: (c: ApiCall) => boolean } = {},
|
|
1073
|
+
): Promise<ApiCall> {
|
|
1074
|
+
const found = this.store.apiCalls.find((c) => c.method === method && (opts.where?.(c) ?? true));
|
|
1075
|
+
if (found) return Promise.resolve(found);
|
|
1076
|
+
return new Promise((resolve, reject) => {
|
|
1077
|
+
const timer = setTimeout(() => {
|
|
1078
|
+
off();
|
|
1079
|
+
reject(new Error(`timed out waiting for ${method}`));
|
|
1080
|
+
}, opts.timeoutMs ?? 10_000);
|
|
1081
|
+
const off = this.store.onChange((c) => {
|
|
1082
|
+
if (c.kind === "api.call" && c.call.method === method && (opts.where?.(c.call) ?? true)) {
|
|
1083
|
+
clearTimeout(timer);
|
|
1084
|
+
off();
|
|
1085
|
+
resolve(c.call);
|
|
1086
|
+
}
|
|
1087
|
+
});
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
waitForConnection(timeoutMs = 15_000): Promise<void> {
|
|
1092
|
+
return this.hub.waitForConnection(timeoutMs);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
disconnectSockets(reason?: Parameters<SocketModeHub["disconnectAll"]>[0]): void {
|
|
1096
|
+
this.hub.disconnectAll(reason);
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
onChange(listener: (change: Change) => void): () => void {
|
|
1100
|
+
return this.store.onChange(listener);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// ------------------------------------------------------------ admin
|
|
1104
|
+
|
|
1105
|
+
private async handleAdmin(req: Request, path: string, url: URL): Promise<Response> {
|
|
1106
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
1107
|
+
const body =
|
|
1108
|
+
req.method === "POST"
|
|
1109
|
+
? ((await req.json().catch(() => ({}))) as Record<string, unknown>)
|
|
1110
|
+
: {};
|
|
1111
|
+
try {
|
|
1112
|
+
if (path === "state") {
|
|
1113
|
+
return json({
|
|
1114
|
+
team: this.store.team,
|
|
1115
|
+
app: this.store.app,
|
|
1116
|
+
bot: { userId: this.store.bot.userId, botId: this.store.bot.botId },
|
|
1117
|
+
connections: this.hub.connectionCount,
|
|
1118
|
+
users: [...this.store.users.values()],
|
|
1119
|
+
channels: [...this.store.channels.values()],
|
|
1120
|
+
});
|
|
1121
|
+
}
|
|
1122
|
+
if (path === "channels" && req.method === "POST")
|
|
1123
|
+
return json(this.addChannel(body as unknown as AddChannelInput));
|
|
1124
|
+
if (path === "users" && req.method === "POST")
|
|
1125
|
+
return json(this.addUser(body as unknown as AddUserInput));
|
|
1126
|
+
if (path === "messages" && req.method === "POST") {
|
|
1127
|
+
const input = body as unknown as PostMessageInput;
|
|
1128
|
+
return json(
|
|
1129
|
+
wireMessage(
|
|
1130
|
+
await this.postMessage({ ...input, text: this.resolveMentions(input.text ?? "") }),
|
|
1131
|
+
),
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
if (path === "messages" && req.method === "GET") {
|
|
1135
|
+
const q: MessageQuery = Object.fromEntries(url.searchParams) as MessageQuery;
|
|
1136
|
+
return json(this.findMessages(q).map(wireMessage));
|
|
1137
|
+
}
|
|
1138
|
+
if (path === "commands" && req.method === "POST") {
|
|
1139
|
+
const r = await this.slashCommand(body as { command: string });
|
|
1140
|
+
return json({ ack: r.ack, response: r.response ? wireMessage(r.response) : undefined });
|
|
1141
|
+
}
|
|
1142
|
+
if (path === "actions" && req.method === "POST")
|
|
1143
|
+
return json(
|
|
1144
|
+
await this.clickButton(body as { channel: string; ts: string; action_id: string }),
|
|
1145
|
+
);
|
|
1146
|
+
if (path === "views/submit" && req.method === "POST")
|
|
1147
|
+
return json(
|
|
1148
|
+
await this.submitView(body as { values: Record<string, Record<string, unknown>> }),
|
|
1149
|
+
);
|
|
1150
|
+
if (path === "assistant/start" && req.method === "POST")
|
|
1151
|
+
return json(await this.startAssistantThread(body));
|
|
1152
|
+
if (path === "reactions" && req.method === "POST") {
|
|
1153
|
+
await this.addReaction(body as { channel: string; ts: string; name: string });
|
|
1154
|
+
return json({ ok: true });
|
|
1155
|
+
}
|
|
1156
|
+
if (path === "api-calls")
|
|
1157
|
+
return json(this.apiCalls(url.searchParams.get("method") ?? undefined));
|
|
1158
|
+
if (path === "disconnect" && req.method === "POST") {
|
|
1159
|
+
this.disconnectSockets(body.reason as "refresh_requested" | undefined);
|
|
1160
|
+
return json({ ok: true });
|
|
1161
|
+
}
|
|
1162
|
+
const m = /^channels\/([^/]+)(?:\/threads\/([^/]+))?$/.exec(path);
|
|
1163
|
+
if (m) return json((m[2] ? this.thread(m[1]!, m[2]) : this.messages(m[1]!)).map(wireMessage));
|
|
1164
|
+
return json({ ok: false, error: "unknown_admin_route" }, 404);
|
|
1165
|
+
} catch (e) {
|
|
1166
|
+
return json({ ok: false, error: e instanceof SlackApiError ? e.code : String(e) }, 400);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
function slackError(code: string, extra: Record<string, unknown> = {}): Response {
|
|
1172
|
+
return Response.json({ ok: false, error: code, ...extra });
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function findButton(
|
|
1176
|
+
blocks: unknown[] | undefined,
|
|
1177
|
+
actionId: string,
|
|
1178
|
+
): { block_id?: string; text?: unknown; value?: string; style?: string } | undefined {
|
|
1179
|
+
for (const b of (blocks ?? []) as Array<Record<string, unknown>>) {
|
|
1180
|
+
const elements = [
|
|
1181
|
+
...(Array.isArray(b.elements) ? (b.elements as Array<Record<string, unknown>>) : []),
|
|
1182
|
+
...(b.accessory ? [b.accessory as Record<string, unknown>] : []),
|
|
1183
|
+
];
|
|
1184
|
+
for (const el of elements) {
|
|
1185
|
+
if (el.type === "button" && el.action_id === actionId) {
|
|
1186
|
+
return {
|
|
1187
|
+
block_id: b.block_id as string | undefined,
|
|
1188
|
+
text: el.text,
|
|
1189
|
+
value: el.value as string | undefined,
|
|
1190
|
+
style: el.style as string | undefined,
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
return undefined;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
export { SlackApiError };
|