@desplega.ai/slack-mock 0.4.1 → 0.6.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 +42 -5
- package/dist/block-limits.d.ts +2 -0
- package/dist/cli.js +19 -2
- package/dist/http-delivery.d.ts +61 -0
- package/dist/{index-86bw4z6k.js → index-5hsxaq74.js} +543 -39
- package/dist/index.d.ts +2 -0
- package/dist/index.js +10 -2
- package/dist/render/mrkdwn.d.ts +9 -0
- package/dist/server.d.ts +9 -0
- package/dist/socket-mode.d.ts +1 -0
- package/dist/store.d.ts +7 -0
- package/dist/types.d.ts +4 -0
- package/package.json +1 -1
- package/src/block-limits.ts +170 -0
- package/src/cli.ts +21 -0
- package/src/http-delivery.ts +240 -0
- package/src/index.ts +7 -0
- package/src/render/blocks.ts +168 -1
- package/src/render/index.ts +30 -26
- package/src/render/mrkdwn.ts +39 -0
- package/src/server.ts +35 -15
- package/src/socket-mode.ts +1 -1
- package/src/store.ts +19 -2
- package/src/types.ts +4 -0
- package/src/web-api.ts +49 -11
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export type { Frame, FramesOptions, FramesResult } from "./frames.ts";
|
|
2
2
|
export { frames } from "./frames.ts";
|
|
3
|
+
export type { HttpDeliveryOptions } from "./http-delivery.ts";
|
|
4
|
+
export { HttpDelivery, HttpDeliveryError, HttpDeliveryStoppedError, slackSignature, } from "./http-delivery.ts";
|
|
3
5
|
export { findChrome, screenshot } from "./screenshot.ts";
|
|
4
6
|
export type { Fault, MessageQuery, PostMessageInput, SlackManifest, SlackMockOptions, } from "./server.ts";
|
|
5
7
|
export { SlackApiError, SlackMock } from "./server.ts";
|
package/dist/index.js
CHANGED
|
@@ -2,18 +2,26 @@
|
|
|
2
2
|
import {
|
|
3
3
|
SlackApiError2,
|
|
4
4
|
Store2,
|
|
5
|
+
slackSignature2,
|
|
6
|
+
HttpDeliveryError2,
|
|
7
|
+
HttpDeliveryStoppedError2,
|
|
8
|
+
HttpDelivery2,
|
|
5
9
|
SlackMock2,
|
|
6
10
|
frames2
|
|
7
|
-
} from "./index-
|
|
11
|
+
} from "./index-5hsxaq74.js";
|
|
8
12
|
import {
|
|
9
13
|
findChrome2,
|
|
10
14
|
screenshot2
|
|
11
15
|
} from "./index-xs37gskt.js";
|
|
12
16
|
export {
|
|
17
|
+
HttpDelivery2 as HttpDelivery,
|
|
18
|
+
HttpDeliveryError2 as HttpDeliveryError,
|
|
19
|
+
HttpDeliveryStoppedError2 as HttpDeliveryStoppedError,
|
|
13
20
|
SlackApiError2 as SlackApiError,
|
|
14
21
|
SlackMock2 as SlackMock,
|
|
15
22
|
Store2 as Store,
|
|
16
23
|
findChrome2 as findChrome,
|
|
17
24
|
frames2 as frames,
|
|
18
|
-
screenshot2 as screenshot
|
|
25
|
+
screenshot2 as screenshot,
|
|
26
|
+
slackSignature2 as slackSignature
|
|
19
27
|
};
|
package/dist/render/mrkdwn.d.ts
CHANGED
|
@@ -14,3 +14,12 @@ export declare function displayName(user: SlackUser): string;
|
|
|
14
14
|
export declare function mrkdwnToHtml(text: string, ctx: RenderContext): string;
|
|
15
15
|
/** plain_text objects: escaping and emoji only, no formatting. */
|
|
16
16
|
export declare function plainTextToHtml(text: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Markdown (`markdown` blocks, `markdown_text` on streams) -> mrkdwn, so the mrkdwn renderer
|
|
19
|
+
* shows it: **bold**, *italic*, ~~strike~~, [label](url), headings, bullets and rules.
|
|
20
|
+
* Code spans and fenced code pass through untouched: they are held as placeholders while the
|
|
21
|
+
* enclosing heading, link or style is converted, then put back.
|
|
22
|
+
*/
|
|
23
|
+
export declare function markdownToMrkdwn(text: string): string;
|
|
24
|
+
/** Render Markdown to HTML through the mrkdwn renderer. */
|
|
25
|
+
export declare function markdownToHtml(text: string, ctx: RenderContext): string;
|
package/dist/server.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type HttpDeliveryOptions } from "./http-delivery.ts";
|
|
1
2
|
import { type AckResult, type DeliveryRecord, SocketModeHub } from "./socket-mode.ts";
|
|
2
3
|
import { type AddChannelInput, type AddUserInput, SlackApiError, Store, type StoreOptions } from "./store.ts";
|
|
3
4
|
import type { ApiCall, Change, SlackChannel, SlackMessage, SlackUser } from "./types.ts";
|
|
@@ -66,6 +67,11 @@ export interface SlackMockOptions extends StoreOptions {
|
|
|
66
67
|
* admin credential. `adminAuth` always implies it.
|
|
67
68
|
*/
|
|
68
69
|
presenterAuth?: string;
|
|
70
|
+
/**
|
|
71
|
+
* Deliver events, slash commands and interactivity as signed HTTP requests to the app's request
|
|
72
|
+
* URLs instead of over Socket Mode (Slack's HTTP mode). The app needs no WebSocket connection.
|
|
73
|
+
*/
|
|
74
|
+
httpDelivery?: HttpDeliveryOptions;
|
|
69
75
|
log?: boolean | ((msg: string) => void);
|
|
70
76
|
}
|
|
71
77
|
export interface PostMessageInput {
|
|
@@ -110,6 +116,8 @@ export interface Fault {
|
|
|
110
116
|
export declare class SlackMock {
|
|
111
117
|
readonly store: Store;
|
|
112
118
|
readonly hub: SocketModeHub;
|
|
119
|
+
/** Where deliveries go: the HTTP request URLs when `httpDelivery` is set, else the Socket Mode hub. */
|
|
120
|
+
readonly delivery: Pick<SocketModeHub, "send" | "connectionCount" | "history" | "waitForConnection">;
|
|
113
121
|
readonly opts: SlackMockOptions;
|
|
114
122
|
private server;
|
|
115
123
|
private triggerIds;
|
|
@@ -265,6 +273,7 @@ export declare class SlackMock {
|
|
|
265
273
|
title?: string;
|
|
266
274
|
prompts?: unknown[];
|
|
267
275
|
promptsTitle?: string;
|
|
276
|
+
sessionStatus?: string;
|
|
268
277
|
};
|
|
269
278
|
messages(channel: string): SlackMessage[];
|
|
270
279
|
thread(channel: string, ts: string): SlackMessage[];
|
package/dist/socket-mode.d.ts
CHANGED
|
@@ -41,6 +41,7 @@ export interface DeliveryRecord {
|
|
|
41
41
|
acked: boolean;
|
|
42
42
|
ackPayload?: unknown;
|
|
43
43
|
}
|
|
44
|
+
export declare function envelopeName(type: EnvelopeType, payload: unknown): string;
|
|
44
45
|
/**
|
|
45
46
|
* The Socket Mode side of the mock: tracks app connections, pushes envelopes,
|
|
46
47
|
* waits for acks, redelivers on timeout and keeps the link alive with pings.
|
package/dist/store.d.ts
CHANGED
|
@@ -90,6 +90,8 @@ export declare class Store {
|
|
|
90
90
|
title?: string;
|
|
91
91
|
prompts?: unknown[];
|
|
92
92
|
promptsTitle?: string;
|
|
93
|
+
/** agents.sessions.setStatus: "active", "processing", "suspended" or "closed". */
|
|
94
|
+
sessionStatus?: string;
|
|
93
95
|
}>;
|
|
94
96
|
private listeners;
|
|
95
97
|
private dataFile?;
|
|
@@ -114,6 +116,9 @@ export declare class Store {
|
|
|
114
116
|
join(channelId: string, userId: string, inviter?: string): {
|
|
115
117
|
alreadyMember: boolean;
|
|
116
118
|
};
|
|
119
|
+
leave(channelId: string, userId: string): {
|
|
120
|
+
notInChannel: boolean;
|
|
121
|
+
};
|
|
117
122
|
archive(channelId: string): void;
|
|
118
123
|
private insertMessage;
|
|
119
124
|
findMessage(channelId: string, ts: string): SlackMessage | undefined;
|
|
@@ -155,6 +160,8 @@ export declare class Store {
|
|
|
155
160
|
title?: string;
|
|
156
161
|
prompts?: unknown[];
|
|
157
162
|
promptsTitle?: string;
|
|
163
|
+
/** agents.sessions.setStatus: "active", "processing", "suspended" or "closed". */
|
|
164
|
+
sessionStatus?: string;
|
|
158
165
|
};
|
|
159
166
|
}
|
|
160
167
|
/** Public (wire) form of a message: mock-only fields removed, file bytes dropped. */
|
package/dist/types.d.ts
CHANGED
|
@@ -116,6 +116,10 @@ export interface SlackMessage {
|
|
|
116
116
|
thumb_64?: string;
|
|
117
117
|
/** Mock-only: the user who can see an ephemeral message. Stripped on the wire. */
|
|
118
118
|
ephemeral_user?: string;
|
|
119
|
+
/** Mock-only: `text` came in as `markdown_text`, so the UI renders it as Markdown. Stripped on the wire. */
|
|
120
|
+
text_format?: "markdown";
|
|
121
|
+
/** Mock-only: chat.update replaced a streamed message's blocks, so they carry the body. Stripped on the wire. */
|
|
122
|
+
stream_replaced?: true;
|
|
119
123
|
}
|
|
120
124
|
export interface SlackView {
|
|
121
125
|
id: string;
|
package/package.json
CHANGED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Block Kit limits Slack enforces at post time, for the blocks agent cards emit.
|
|
2
|
+
// Source: docs.slack.dev block reference (table, data_table, data_visualization).
|
|
3
|
+
// Slack documents the limits but not the error strings, so the messages here are
|
|
4
|
+
// the mock's own wording in Slack's "[ERROR] ... [json-pointer:...]" shape.
|
|
5
|
+
|
|
6
|
+
import { SlackApiError } from "./store.ts";
|
|
7
|
+
|
|
8
|
+
type Rec = Record<string, unknown>;
|
|
9
|
+
const rec = (v: unknown): Rec | undefined =>
|
|
10
|
+
typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Rec) : undefined;
|
|
11
|
+
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
|
|
12
|
+
const str = (v: unknown): string => (typeof v === "string" ? v : "");
|
|
13
|
+
|
|
14
|
+
/** Characters a cell contributes to the table budget. data_table docs: an action_cell's button text counts. */
|
|
15
|
+
function cellChars(v: unknown): number {
|
|
16
|
+
const cell = rec(v);
|
|
17
|
+
if (!cell) return 0;
|
|
18
|
+
if (cell.type === "action_cell") return str(rec(rec(cell.element)?.text)?.text).length;
|
|
19
|
+
if (typeof cell.text === "string") return cell.text.length;
|
|
20
|
+
return arr(cell.elements).reduce<number>((n, e) => n + cellChars(e), 0);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Issues for one table block, plus its cell characters for the per-message budget. */
|
|
24
|
+
function tableIssues(b: Rec, at: string, data: boolean): { out: string[]; chars: number } {
|
|
25
|
+
const out: string[] = [];
|
|
26
|
+
const rows = arr(b.rows);
|
|
27
|
+
const [minRows, maxRows, maxChars] = data ? [2, 201, 20000] : [1, 100, 10000];
|
|
28
|
+
if (rows.length < minRows || rows.length > maxRows)
|
|
29
|
+
out.push(`rows must have between ${minRows} and ${maxRows} items [json-pointer:${at}/rows]`);
|
|
30
|
+
const cellTypes = data
|
|
31
|
+
? ["raw_text", "raw_number", "rich_text", "action_cell"]
|
|
32
|
+
: ["raw_text", "raw_number", "rich_text"];
|
|
33
|
+
let chars = 0;
|
|
34
|
+
rows.forEach((r, i) => {
|
|
35
|
+
const cells = arr(r);
|
|
36
|
+
if (!Array.isArray(r) || cells.length < 1 || cells.length > 20)
|
|
37
|
+
out.push(`row must have between 1 and 20 cells [json-pointer:${at}/rows/${i}]`);
|
|
38
|
+
if (data && cells.length !== arr(rows[0]).length)
|
|
39
|
+
out.push(`all rows must have the same number of cells [json-pointer:${at}/rows/${i}]`);
|
|
40
|
+
cells.forEach((c, j) => {
|
|
41
|
+
const type = str(rec(c)?.type);
|
|
42
|
+
// data_table docs exclude only rich_text from the header row.
|
|
43
|
+
if (!cellTypes.includes(type) || (data && i === 0 && type === "rich_text"))
|
|
44
|
+
out.push(`invalid cell type "${type}" [json-pointer:${at}/rows/${i}/${j}]`);
|
|
45
|
+
else if (type === "action_cell" && str(rec(rec(c)?.element)?.type) !== "button")
|
|
46
|
+
out.push(
|
|
47
|
+
`action_cell element must be a button [json-pointer:${at}/rows/${i}/${j}/element]`,
|
|
48
|
+
);
|
|
49
|
+
chars += cellChars(c);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
if (chars > maxChars)
|
|
53
|
+
out.push(`cells must have at most ${maxChars} characters in total [json-pointer:${at}/rows]`);
|
|
54
|
+
if (data) {
|
|
55
|
+
if (!str(b.caption)) out.push(`caption is required [json-pointer:${at}/caption]`);
|
|
56
|
+
const page = b.page_size;
|
|
57
|
+
if (
|
|
58
|
+
page !== undefined &&
|
|
59
|
+
!(Number.isInteger(page) && (page as number) >= 1 && (page as number) <= 100)
|
|
60
|
+
)
|
|
61
|
+
out.push(`page_size must be an integer between 1 and 100 [json-pointer:${at}/page_size]`);
|
|
62
|
+
} else if (arr(b.column_settings).length > 20) {
|
|
63
|
+
out.push(`column_settings must have at most 20 items [json-pointer:${at}/column_settings]`);
|
|
64
|
+
}
|
|
65
|
+
return { out, chars };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const label = (v: unknown) => str(v).length >= 1 && str(v).length <= 20;
|
|
69
|
+
|
|
70
|
+
function chartIssues(b: Rec, at: string): string[] {
|
|
71
|
+
const out: string[] = [];
|
|
72
|
+
const title = str(b.title);
|
|
73
|
+
if (title.length < 1 || title.length > 50)
|
|
74
|
+
out.push(`title must have between 1 and 50 characters [json-pointer:${at}/title]`);
|
|
75
|
+
const chart = rec(b.chart);
|
|
76
|
+
const type = str(chart?.type);
|
|
77
|
+
if (type === "pie") {
|
|
78
|
+
const segments = arr(chart?.segments);
|
|
79
|
+
if (segments.length < 1 || segments.length > 12)
|
|
80
|
+
out.push(`segments must have between 1 and 12 items [json-pointer:${at}/chart/segments]`);
|
|
81
|
+
segments.forEach((s, i) => {
|
|
82
|
+
const seg = rec(s);
|
|
83
|
+
if (!label(seg?.label) || !(typeof seg?.value === "number" && seg.value > 0))
|
|
84
|
+
out.push(
|
|
85
|
+
`segment needs a 1-20 character label and a value above 0 [json-pointer:${at}/chart/segments/${i}]`,
|
|
86
|
+
);
|
|
87
|
+
});
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
if (!["bar", "line", "area"].includes(type))
|
|
91
|
+
return [...out, `chart type must be pie, bar, line or area [json-pointer:${at}/chart/type]`];
|
|
92
|
+
const axis = rec(chart?.axis_config);
|
|
93
|
+
const categories = arr(axis?.categories).map(str);
|
|
94
|
+
if (!categories.length)
|
|
95
|
+
out.push(`axis_config.categories is required [json-pointer:${at}/chart/axis_config]`);
|
|
96
|
+
categories.forEach((c, i) => {
|
|
97
|
+
if (c.length > 20)
|
|
98
|
+
out.push(
|
|
99
|
+
`category must have at most 20 characters [json-pointer:${at}/chart/axis_config/categories/${i}]`,
|
|
100
|
+
);
|
|
101
|
+
});
|
|
102
|
+
for (const k of ["x_label", "y_label"])
|
|
103
|
+
if (str(axis?.[k]).length > 50)
|
|
104
|
+
out.push(`${k} must have at most 50 characters [json-pointer:${at}/chart/axis_config/${k}]`);
|
|
105
|
+
const series = arr(chart?.series);
|
|
106
|
+
if (series.length < 1 || series.length > 12)
|
|
107
|
+
out.push(`series must have between 1 and 12 items [json-pointer:${at}/chart/series]`);
|
|
108
|
+
const names = new Set<string>();
|
|
109
|
+
series.forEach((s, i) => {
|
|
110
|
+
const sr = rec(s);
|
|
111
|
+
const name = str(sr?.name);
|
|
112
|
+
if (!label(name) || names.has(name))
|
|
113
|
+
out.push(
|
|
114
|
+
`series name must be unique and 1-20 characters [json-pointer:${at}/chart/series/${i}/name]`,
|
|
115
|
+
);
|
|
116
|
+
names.add(name);
|
|
117
|
+
const data = arr(sr?.data).map((p) => rec(p));
|
|
118
|
+
const labels = data.map((p) => str(p?.label));
|
|
119
|
+
if (data.length < 1 || data.length > 20)
|
|
120
|
+
out.push(`data must have between 1 and 20 items [json-pointer:${at}/chart/series/${i}/data]`);
|
|
121
|
+
if (data.some((p) => !label(p?.label) || typeof p?.value !== "number"))
|
|
122
|
+
out.push(
|
|
123
|
+
`data points need a 1-20 character label and a number value [json-pointer:${at}/chart/series/${i}/data]`,
|
|
124
|
+
);
|
|
125
|
+
// "Must contain exactly one entry for every label in axis_config.categories."
|
|
126
|
+
const count = (c: string) => labels.filter((l) => l === c).length;
|
|
127
|
+
if (labels.some((l) => !categories.includes(l)) || categories.some((c) => count(c) !== 1))
|
|
128
|
+
out.push(
|
|
129
|
+
`data labels must match axis_config.categories [json-pointer:${at}/chart/series/${i}/data]`,
|
|
130
|
+
);
|
|
131
|
+
});
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Throws `invalid_blocks` the way Slack does when a message's blocks break a limit. */
|
|
136
|
+
export function validateBlocks(blocks: unknown[] | undefined): void {
|
|
137
|
+
if (!blocks) return;
|
|
138
|
+
const issues: string[] = [];
|
|
139
|
+
if (blocks.length > 50) issues.push("must have at most 50 blocks");
|
|
140
|
+
let charts = 0;
|
|
141
|
+
// Per-message cell budgets. Each doc states its own aggregate limit
|
|
142
|
+
// (table 10,000, data_table 20,000), so each type is summed on its own.
|
|
143
|
+
const budget = { table: 0, data_table: 0 };
|
|
144
|
+
blocks.forEach((v, i) => {
|
|
145
|
+
const b = rec(v);
|
|
146
|
+
const at = `/blocks/${i}`;
|
|
147
|
+
switch (str(b?.type)) {
|
|
148
|
+
case "table":
|
|
149
|
+
case "data_table": {
|
|
150
|
+
const t = tableIssues(b as Rec, at, b?.type === "data_table");
|
|
151
|
+
issues.push(...t.out);
|
|
152
|
+
budget[b?.type as keyof typeof budget] += t.chars;
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case "data_visualization":
|
|
156
|
+
if (++charts > 2)
|
|
157
|
+
issues.push(`at most 2 data_visualization blocks per message [json-pointer:${at}]`);
|
|
158
|
+
issues.push(...chartIssues(b as Rec, at));
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
if (budget.table > 10000)
|
|
163
|
+
issues.push("table cells must have at most 10000 characters in total per message");
|
|
164
|
+
if (budget.data_table > 20000)
|
|
165
|
+
issues.push("data_table cells must have at most 20000 characters in total per message");
|
|
166
|
+
if (issues.length)
|
|
167
|
+
throw new SlackApiError("invalid_blocks", {
|
|
168
|
+
response_metadata: { messages: issues.map((m) => `[ERROR] ${m}`) },
|
|
169
|
+
});
|
|
170
|
+
}
|
package/src/cli.ts
CHANGED
|
@@ -9,6 +9,8 @@ const USAGE = `slack-mock: a mock Slack server (Web API + Socket Mode) for testi
|
|
|
9
9
|
Usage:
|
|
10
10
|
slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json]
|
|
11
11
|
[--no-seed] [--quiet] [--panel 50] [--auth user:pass] [--public-url https://mock.example.com]
|
|
12
|
+
[--http-events-url URL --signing-secret SECRET [--http-interactivity-url URL]
|
|
13
|
+
[--http-commands-url URL] [--http-retry-delays-ms 1000,5000,30000]]
|
|
12
14
|
slack-mock screenshot <url> --out shot.png [--width 800] [--height 1000]
|
|
13
15
|
slack-mock frames --journal data.jsonl --channel C0GENERAL0 [--thread 1788516626.286000] --out ./frames
|
|
14
16
|
[--manifest app.json] [--width 800] [--height 700] [--no-desktop]
|
|
@@ -37,9 +39,28 @@ async function main(argv: string[]): Promise<void> {
|
|
|
37
39
|
panel: { type: "string" },
|
|
38
40
|
auth: { type: "string" },
|
|
39
41
|
"public-url": { type: "string" },
|
|
42
|
+
"http-events-url": { type: "string" },
|
|
43
|
+
"http-interactivity-url": { type: "string" },
|
|
44
|
+
"http-commands-url": { type: "string" },
|
|
45
|
+
"http-retry-delays-ms": { type: "string" },
|
|
46
|
+
"signing-secret": { type: "string" },
|
|
40
47
|
},
|
|
41
48
|
});
|
|
49
|
+
const eventsUrl = values["http-events-url"];
|
|
50
|
+
if (eventsUrl && !values["signing-secret"])
|
|
51
|
+
throw new Error("--http-events-url needs --signing-secret");
|
|
42
52
|
const mock = await SlackMock.start({
|
|
53
|
+
httpDelivery: eventsUrl
|
|
54
|
+
? {
|
|
55
|
+
eventsUrl,
|
|
56
|
+
interactivityUrl: values["http-interactivity-url"],
|
|
57
|
+
commandsUrl: values["http-commands-url"],
|
|
58
|
+
signingSecret: values["signing-secret"] as string,
|
|
59
|
+
retryDelaysMs: values["http-retry-delays-ms"]
|
|
60
|
+
? values["http-retry-delays-ms"].split(",").map(Number)
|
|
61
|
+
: undefined,
|
|
62
|
+
}
|
|
63
|
+
: undefined,
|
|
43
64
|
panelWidth: values.panel,
|
|
44
65
|
adminAuth: values.auth,
|
|
45
66
|
publicUrl: values["public-url"],
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
type AckResult,
|
|
4
|
+
type DeliveryRecord,
|
|
5
|
+
type EnvelopeType,
|
|
6
|
+
envelopeName,
|
|
7
|
+
} from "./socket-mode.ts";
|
|
8
|
+
|
|
9
|
+
export interface HttpDeliveryOptions {
|
|
10
|
+
/** Events API "Request URL". Receives `events_api` payloads as signed JSON. */
|
|
11
|
+
eventsUrl: string;
|
|
12
|
+
/** Interactivity "Request URL" (block_actions, view_submission). Default: `eventsUrl`. */
|
|
13
|
+
interactivityUrl?: string;
|
|
14
|
+
/** Slash command "Request URL". Default: `eventsUrl`. */
|
|
15
|
+
commandsUrl?: string;
|
|
16
|
+
/** The app's signing secret. Every request is signed with it, like Slack. */
|
|
17
|
+
signingSecret: string;
|
|
18
|
+
/** Wait before each Events API redelivery (Slack: about 1 minute, 5 minutes, 30 minutes). */
|
|
19
|
+
retryDelaysMs?: number[];
|
|
20
|
+
/** How long to wait for the HTTP response before counting a timeout (Slack: 3s). */
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
log?: (msg: string) => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `v0=` + hex HMAC-SHA256 of `v0:<timestamp>:<raw body>`, the `X-Slack-Signature` value. */
|
|
26
|
+
export function slackSignature(secret: string, timestamp: string | number, body: string): string {
|
|
27
|
+
return `v0=${createHmac("sha256", secret).update(`v0:${timestamp}:${body}`).digest("hex")}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class HttpDeliveryError extends Error {}
|
|
31
|
+
|
|
32
|
+
/** Thrown by a delivery cut short by `shutdown()`; the mock treats it as a clean stop. */
|
|
33
|
+
export class HttpDeliveryStoppedError extends HttpDeliveryError {
|
|
34
|
+
constructor() {
|
|
35
|
+
super("mock stopped");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type Attempt = { ok: true; payload?: unknown } | { ok: false; reason: string };
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The HTTP side of the mock: the same deliveries as Socket Mode, posted to the
|
|
43
|
+
* app's request URLs and signed with its signing secret. Events API requests are
|
|
44
|
+
* redelivered with `X-Slack-Retry-Num` / `X-Slack-Retry-Reason` when the app does
|
|
45
|
+
* not answer 2xx in time; slash commands and interactivity are posted once, as
|
|
46
|
+
* Slack does, and the response body is the ack payload.
|
|
47
|
+
*/
|
|
48
|
+
export class HttpDelivery {
|
|
49
|
+
/** Every request sent, in order, with its ack status. */
|
|
50
|
+
readonly history: DeliveryRecord[] = [];
|
|
51
|
+
readonly opts: Required<Omit<HttpDeliveryOptions, "log" | "interactivityUrl" | "commandsUrl">> & {
|
|
52
|
+
interactivityUrl: string;
|
|
53
|
+
commandsUrl: string;
|
|
54
|
+
log: (msg: string) => void;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
private readonly stopController = new AbortController();
|
|
58
|
+
private retryTimers = new Set<{ timer: ReturnType<typeof setTimeout>; wake: () => void }>();
|
|
59
|
+
|
|
60
|
+
constructor(opts: HttpDeliveryOptions) {
|
|
61
|
+
this.opts = {
|
|
62
|
+
eventsUrl: opts.eventsUrl,
|
|
63
|
+
interactivityUrl: opts.interactivityUrl ?? opts.eventsUrl,
|
|
64
|
+
commandsUrl: opts.commandsUrl ?? opts.eventsUrl,
|
|
65
|
+
signingSecret: opts.signingSecret,
|
|
66
|
+
retryDelaysMs: opts.retryDelaysMs ?? [60_000, 300_000, 1_800_000],
|
|
67
|
+
timeoutMs: opts.timeoutMs ?? 3_000,
|
|
68
|
+
log: opts.log ?? (() => {}),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Cancel everything pending: abort in-flight requests, wake every retry wait so its
|
|
74
|
+
* `send` rejects with `HttpDeliveryStoppedError`, and refuse new requests.
|
|
75
|
+
*/
|
|
76
|
+
shutdown(): void {
|
|
77
|
+
this.stopController.abort();
|
|
78
|
+
for (const t of this.retryTimers) {
|
|
79
|
+
clearTimeout(t.timer);
|
|
80
|
+
t.wake();
|
|
81
|
+
}
|
|
82
|
+
this.retryTimers.clear();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private get stopped(): boolean {
|
|
86
|
+
return this.stopController.signal.aborted;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Wait `ms` before a redelivery; `shutdown()` ends the wait early. */
|
|
90
|
+
private waitToRetry(ms: number): Promise<void> {
|
|
91
|
+
return new Promise((resolve) => {
|
|
92
|
+
const entry = {
|
|
93
|
+
timer: setTimeout(() => {
|
|
94
|
+
this.retryTimers.delete(entry);
|
|
95
|
+
resolve();
|
|
96
|
+
}, ms),
|
|
97
|
+
wake: resolve,
|
|
98
|
+
};
|
|
99
|
+
this.retryTimers.add(entry);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** An HTTP app is always "connected": nothing to wait for. */
|
|
104
|
+
get connectionCount(): number {
|
|
105
|
+
return 1;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
waitForConnection(): Promise<void> {
|
|
109
|
+
return Promise.resolve();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Slack's URL verification: POST a `url_verification` challenge and expect it echoed back. */
|
|
113
|
+
async verifyUrl(): Promise<boolean> {
|
|
114
|
+
const challenge = crypto.randomUUID();
|
|
115
|
+
const body = JSON.stringify({
|
|
116
|
+
token: "mock-verification-token",
|
|
117
|
+
challenge,
|
|
118
|
+
type: "url_verification",
|
|
119
|
+
});
|
|
120
|
+
const res = await this.post(this.opts.eventsUrl, body, "application/json", {});
|
|
121
|
+
if (!res.ok) return false;
|
|
122
|
+
return (
|
|
123
|
+
(res.payload as { challenge?: string } | undefined)?.challenge === challenge ||
|
|
124
|
+
res.text === challenge
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async send(
|
|
129
|
+
type: EnvelopeType,
|
|
130
|
+
payload: unknown,
|
|
131
|
+
_acceptsResponsePayload = false,
|
|
132
|
+
): Promise<AckResult> {
|
|
133
|
+
if (this.stopped) throw new HttpDeliveryStoppedError();
|
|
134
|
+
const record: DeliveryRecord = {
|
|
135
|
+
envelope_id: crypto.randomUUID(),
|
|
136
|
+
type,
|
|
137
|
+
name: envelopeName(type, payload),
|
|
138
|
+
sentAt: new Date().toISOString(),
|
|
139
|
+
attempts: 0,
|
|
140
|
+
acked: false,
|
|
141
|
+
};
|
|
142
|
+
this.history.push(record);
|
|
143
|
+
const { url, body, contentType } = this.encode(type, payload);
|
|
144
|
+
const delays = type === "events_api" ? this.opts.retryDelaysMs : [];
|
|
145
|
+
let retry: { num: number; reason: string } | undefined;
|
|
146
|
+
for (let attempt = 0; ; attempt++) {
|
|
147
|
+
record.attempts = attempt + 1;
|
|
148
|
+
const res = await this.post(url, body, contentType, retry ? this.retryHeaders(retry) : {});
|
|
149
|
+
if (this.stopped) throw new HttpDeliveryStoppedError();
|
|
150
|
+
if (res.ok) {
|
|
151
|
+
record.acked = true;
|
|
152
|
+
record.ackPayload = res.payload;
|
|
153
|
+
return { envelope_id: record.envelope_id, payload: res.payload, attempts: record.attempts };
|
|
154
|
+
}
|
|
155
|
+
const delay = delays[attempt];
|
|
156
|
+
if (delay === undefined) {
|
|
157
|
+
throw new HttpDeliveryError(
|
|
158
|
+
`${record.name} not acknowledged (${res.reason}) after ${record.attempts} attempt(s)`,
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
this.opts.log(`${record.name} to ${url}: ${res.reason}; retry ${attempt + 1} in ${delay}ms`);
|
|
162
|
+
await this.waitToRetry(delay);
|
|
163
|
+
if (this.stopped) throw new HttpDeliveryStoppedError();
|
|
164
|
+
retry = { num: attempt + 1, reason: res.reason };
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private retryHeaders(retry: { num: number; reason: string }): Record<string, string> {
|
|
169
|
+
return { "X-Slack-Retry-Num": String(retry.num), "X-Slack-Retry-Reason": retry.reason };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Events go as JSON; slash commands as a form; interactivity as a form with one `payload` field. */
|
|
173
|
+
private encode(
|
|
174
|
+
type: EnvelopeType,
|
|
175
|
+
payload: unknown,
|
|
176
|
+
): { url: string; body: string; contentType: string } {
|
|
177
|
+
if (type === "events_api") {
|
|
178
|
+
return {
|
|
179
|
+
url: this.opts.eventsUrl,
|
|
180
|
+
body: JSON.stringify(payload),
|
|
181
|
+
contentType: "application/json",
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const form = new URLSearchParams();
|
|
185
|
+
if (type === "interactive") {
|
|
186
|
+
form.set("payload", JSON.stringify(payload));
|
|
187
|
+
} else {
|
|
188
|
+
for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {
|
|
189
|
+
if (value !== undefined && value !== null) form.set(key, String(value));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
url: type === "interactive" ? this.opts.interactivityUrl : this.opts.commandsUrl,
|
|
194
|
+
body: form.toString(),
|
|
195
|
+
contentType: "application/x-www-form-urlencoded",
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private async post(
|
|
200
|
+
url: string,
|
|
201
|
+
body: string,
|
|
202
|
+
contentType: string,
|
|
203
|
+
extraHeaders: Record<string, string>,
|
|
204
|
+
): Promise<Attempt & { text?: string }> {
|
|
205
|
+
if (this.stopped) return { ok: false, reason: "stopped" };
|
|
206
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
207
|
+
try {
|
|
208
|
+
const res = await fetch(url, {
|
|
209
|
+
method: "POST",
|
|
210
|
+
headers: {
|
|
211
|
+
"Content-Type": contentType,
|
|
212
|
+
"X-Slack-Request-Timestamp": String(timestamp),
|
|
213
|
+
"X-Slack-Signature": slackSignature(this.opts.signingSecret, timestamp, body),
|
|
214
|
+
"User-Agent": "Slackbot 1.0 (+https://api.slack.com/robots)",
|
|
215
|
+
...extraHeaders,
|
|
216
|
+
},
|
|
217
|
+
body,
|
|
218
|
+
signal: AbortSignal.any([
|
|
219
|
+
AbortSignal.timeout(this.opts.timeoutMs),
|
|
220
|
+
this.stopController.signal,
|
|
221
|
+
]),
|
|
222
|
+
});
|
|
223
|
+
if (!res.ok) {
|
|
224
|
+
await res.body?.cancel();
|
|
225
|
+
return { ok: false, reason: "http_error" };
|
|
226
|
+
}
|
|
227
|
+
const text = await res.text();
|
|
228
|
+
let payload: unknown;
|
|
229
|
+
try {
|
|
230
|
+
payload = text ? JSON.parse(text) : undefined;
|
|
231
|
+
} catch {
|
|
232
|
+
payload = undefined;
|
|
233
|
+
}
|
|
234
|
+
return { ok: true, payload, text };
|
|
235
|
+
} catch (e) {
|
|
236
|
+
const timedOut = e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
|
|
237
|
+
return { ok: false, reason: timedOut ? "http_timeout" : "connection_failed" };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
export type { Frame, FramesOptions, FramesResult } from "./frames.ts";
|
|
2
2
|
export { frames } from "./frames.ts";
|
|
3
|
+
export type { HttpDeliveryOptions } from "./http-delivery.ts";
|
|
4
|
+
export {
|
|
5
|
+
HttpDelivery,
|
|
6
|
+
HttpDeliveryError,
|
|
7
|
+
HttpDeliveryStoppedError,
|
|
8
|
+
slackSignature,
|
|
9
|
+
} from "./http-delivery.ts";
|
|
3
10
|
export { findChrome, screenshot } from "./screenshot.ts";
|
|
4
11
|
export type {
|
|
5
12
|
Fault,
|