@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/src/render/blocks.ts
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
emojiChar,
|
|
8
8
|
emojiFromUnicode,
|
|
9
9
|
escapeHtml,
|
|
10
|
+
markdownToHtml,
|
|
10
11
|
mrkdwnToHtml,
|
|
11
12
|
plainTextToHtml,
|
|
12
13
|
type RenderContext,
|
|
@@ -170,7 +171,10 @@ function richElement(v: unknown, ctx: RenderContext): string {
|
|
|
170
171
|
case "emoji": {
|
|
171
172
|
const char =
|
|
172
173
|
emojiChar(str(el.name)) ?? (el.unicode ? emojiFromUnicode(str(el.unicode)) : undefined);
|
|
173
|
-
|
|
174
|
+
// `unicode` is caller-supplied codepoints, so the decoded string can be markup.
|
|
175
|
+
return char
|
|
176
|
+
? escapeHtml(char)
|
|
177
|
+
: `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
|
|
174
178
|
}
|
|
175
179
|
case "date":
|
|
176
180
|
return plainTextToHtml(str(el.fallback) || str(el.timestamp));
|
|
@@ -268,6 +272,162 @@ function videoBlock(block: Rec, ctx: RenderContext): string {
|
|
|
268
272
|
return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
|
|
269
273
|
}
|
|
270
274
|
|
|
275
|
+
// ------------------------------------------------------- tables and charts
|
|
276
|
+
|
|
277
|
+
function tableCell(v: unknown, ctx: RenderContext): string {
|
|
278
|
+
const cell = rec(v);
|
|
279
|
+
if (!cell) return "";
|
|
280
|
+
if (str(cell.type) === "rich_text")
|
|
281
|
+
return arr(cell.elements)
|
|
282
|
+
.map((e) => richSection(e, ctx))
|
|
283
|
+
.join("");
|
|
284
|
+
if (str(cell.type) === "action_cell") {
|
|
285
|
+
const el = rec(cell.element);
|
|
286
|
+
return el && str(el.type) === "button" ? button(el, ctx) : tableCell(cell.fallback, ctx);
|
|
287
|
+
}
|
|
288
|
+
return plainTextToHtml(str(cell.text) || (cell.value === undefined ? "" : String(cell.value)));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** `table` and `data_table`. Only data_table documents the first row as a header row. */
|
|
292
|
+
function tableBlock(block: Rec, ctx: RenderContext): string {
|
|
293
|
+
const settings = arr(block.column_settings).map(rec);
|
|
294
|
+
const rows = arr(block.rows).map(arr);
|
|
295
|
+
// data_table pages at 5 rows unless page_size says otherwise; table never pages.
|
|
296
|
+
// Rendering also runs on unvalidated blocks, so an out-of-range page_size falls back to 5.
|
|
297
|
+
const ps = Number(block.page_size);
|
|
298
|
+
const pageSize = block.type === "data_table" ? (Number.isInteger(ps) && ps >= 1 ? ps : 5) : 0;
|
|
299
|
+
const head = block.type === "data_table" ? 1 : 0;
|
|
300
|
+
const body = rows.slice(head);
|
|
301
|
+
// Every page is rendered; pages after the first start hidden and the pager
|
|
302
|
+
// buttons (uiScript) flip them, so no row is out of reach.
|
|
303
|
+
const per = pageSize || body.length || 1;
|
|
304
|
+
const pages: unknown[][][] = [];
|
|
305
|
+
for (let i = 0; i < body.length || i === 0; i += per) pages.push(body.slice(i, i + per));
|
|
306
|
+
const row = (cells: unknown[], tag: "th" | "td") =>
|
|
307
|
+
`<tr>${cells
|
|
308
|
+
.map((c, i) => {
|
|
309
|
+
const align = str(settings[i]?.align);
|
|
310
|
+
const cls = [
|
|
311
|
+
align === "center" || align === "right" ? `sm-ta-${align}` : "",
|
|
312
|
+
settings[i]?.is_wrapped === true ? "sm-td-wrap" : "",
|
|
313
|
+
].filter(Boolean);
|
|
314
|
+
return `<${tag}${cls.length ? ` class="${cls.join(" ")}"` : ""}>${tableCell(c, ctx)}</${tag}>`;
|
|
315
|
+
})
|
|
316
|
+
.join("")}</tr>`;
|
|
317
|
+
const caption = str(block.caption)
|
|
318
|
+
? `<div class="sm-table-caption">${plainTextToHtml(str(block.caption))}</div>`
|
|
319
|
+
: "";
|
|
320
|
+
const paged = pages.length > 1;
|
|
321
|
+
const range = (p: number) =>
|
|
322
|
+
`${p * per + 1}–${p * per + (pages[p]?.length ?? 0)} of ${body.length}`;
|
|
323
|
+
const pager = paged
|
|
324
|
+
? `<div class="sm-table-pager"><button type="button" class="sm-pager-btn" data-step="-1" aria-label="Previous page" disabled>‹</button><span class="sm-pager-label">${range(0)}</span><button type="button" class="sm-pager-btn" data-step="1" aria-label="Next page">›</button></div>`
|
|
325
|
+
: "";
|
|
326
|
+
const tbodies = pages
|
|
327
|
+
.map(
|
|
328
|
+
(pg, p) =>
|
|
329
|
+
`<tbody${paged ? ` data-range="${range(p)}"` : ""}${p ? " hidden" : ""}>${pg.map((r) => row(r, "td")).join("")}</tbody>`,
|
|
330
|
+
)
|
|
331
|
+
.join("");
|
|
332
|
+
return `<div class="sm-block sm-table-block">${caption}<div class="sm-table-wrap"><table class="sm-bk-table">${head && rows.length ? `<thead>${row(rows[0] ?? [], "th")}</thead>` : ""}${tbodies}</table></div>${pager}</div>`;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const CHART_COLORS = ["#1264a3", "#2eb67d", "#ecb22e", "#e01e5a", "#36c5f0", "#7c3085"];
|
|
336
|
+
const color = (i: number) => CHART_COLORS[i % CHART_COLORS.length];
|
|
337
|
+
const num = (v: unknown) => (Number.isFinite(Number(v)) ? Number(v) : 0);
|
|
338
|
+
const svgText = (x: number, y: number, text: string, attrs = "") =>
|
|
339
|
+
`<text x="${x}" y="${y}" ${attrs}>${escapeHtml(text)}</text>`;
|
|
340
|
+
|
|
341
|
+
function legend(labels: string[]): string {
|
|
342
|
+
return `<div class="sm-chart-legend">${labels
|
|
343
|
+
.map(
|
|
344
|
+
(l, i) =>
|
|
345
|
+
`<span class="sm-chart-key"><i style="background:${color(i)}"></i>${escapeHtml(l)}</span>`,
|
|
346
|
+
)
|
|
347
|
+
.join("")}</div>`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function pieChart(chart: Rec): string {
|
|
351
|
+
const segments = arr(chart.segments).map(rec);
|
|
352
|
+
const total = segments.reduce((t, s) => t + Math.max(0, num(s?.value)), 0) || 1;
|
|
353
|
+
let angle = -Math.PI / 2;
|
|
354
|
+
const slices = segments.map((s, i) => {
|
|
355
|
+
const frac = Math.max(0, num(s?.value)) / total;
|
|
356
|
+
if (frac >= 0.9999) return `<circle cx="100" cy="100" r="90" fill="${color(i)}"/>`;
|
|
357
|
+
const a0 = angle;
|
|
358
|
+
angle += frac * 2 * Math.PI;
|
|
359
|
+
const p = (a: number) => `${100 + 90 * Math.cos(a)} ${100 + 90 * Math.sin(a)}`;
|
|
360
|
+
return `<path d="M100 100 L${p(a0)} A90 90 0 ${frac > 0.5 ? 1 : 0} 1 ${p(angle)} Z" fill="${color(i)}"/>`;
|
|
361
|
+
});
|
|
362
|
+
return `<svg class="sm-chart-svg" viewBox="0 0 200 200" width="200" height="200">${slices.join("")}</svg>${legend(segments.map((s) => `${str(s?.label)} (${num(s?.value)})`))}`;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** bar, line and area share axes: categories on x, a value scale on y that always spans 0. */
|
|
366
|
+
function seriesChart(chart: Rec, type: string): string {
|
|
367
|
+
const axis = rec(chart.axis_config) ?? {};
|
|
368
|
+
const series = arr(chart.series).map((s) => rec(s) ?? {});
|
|
369
|
+
const categories = arr(axis.categories).map(str);
|
|
370
|
+
const valueAt = (s: Rec, c: string) =>
|
|
371
|
+
num(rec(arr(s.data).find((p) => rec(p)?.label === c))?.value);
|
|
372
|
+
// Slack permits negative values, so the scale runs min..max and both include 0.
|
|
373
|
+
const values = series.flatMap((s) => categories.map((c) => valueAt(s, c)));
|
|
374
|
+
const min = Math.min(0, ...values);
|
|
375
|
+
const max = Math.max(min < 0 ? 0 : 1, ...values);
|
|
376
|
+
const [W, H, L, T, B] = [480, 220, 44, 10, 30];
|
|
377
|
+
const plotW = W - L - 10;
|
|
378
|
+
const plotH = H - T - B;
|
|
379
|
+
const y = (v: number) => T + plotH - ((v - min) / (max - min)) * plotH;
|
|
380
|
+
const zero = y(0);
|
|
381
|
+
const step = plotW / Math.max(1, categories.length);
|
|
382
|
+
const parts: string[] = [];
|
|
383
|
+
for (let k = 0; k <= 4; k++) {
|
|
384
|
+
const v = min + ((max - min) * k) / 4;
|
|
385
|
+
parts.push(
|
|
386
|
+
`<line x1="${L}" x2="${W - 10}" y1="${y(v)}" y2="${y(v)}" stroke="#e8e8e8"/>`,
|
|
387
|
+
svgText(L - 6, y(v) + 4, String(Math.round(v * 100) / 100), 'text-anchor="end"'),
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
categories.forEach((c, i) => {
|
|
391
|
+
parts.push(svgText(L + step * (i + 0.5), H - B + 16, c, 'text-anchor="middle"'));
|
|
392
|
+
});
|
|
393
|
+
series.forEach((s, si) => {
|
|
394
|
+
if (type === "bar") {
|
|
395
|
+
const bw = (step * 0.7) / Math.max(1, series.length);
|
|
396
|
+
categories.forEach((c, i) => {
|
|
397
|
+
const v = valueAt(s, c);
|
|
398
|
+
parts.push(
|
|
399
|
+
`<rect x="${L + step * i + step * 0.15 + bw * si}" y="${Math.min(zero, y(v))}" width="${bw}" height="${Math.abs(zero - y(v))}" fill="${color(si)}"/>`,
|
|
400
|
+
);
|
|
401
|
+
});
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const pts = categories.map((c, i) => `${L + step * (i + 0.5)},${y(valueAt(s, c))}`);
|
|
405
|
+
if (type === "area" && pts.length)
|
|
406
|
+
parts.push(
|
|
407
|
+
`<polygon points="${L + step * 0.5},${zero} ${pts.join(" ")} ${L + step * (categories.length - 0.5)},${zero}" fill="${color(si)}" fill-opacity=".25"/>`,
|
|
408
|
+
);
|
|
409
|
+
parts.push(
|
|
410
|
+
`<polyline points="${pts.join(" ")}" fill="none" stroke="${color(si)}" stroke-width="2"/>`,
|
|
411
|
+
);
|
|
412
|
+
});
|
|
413
|
+
const xLabel = str(axis.x_label);
|
|
414
|
+
const yLabel = str(axis.y_label);
|
|
415
|
+
const labels = `${yLabel ? `<div class="sm-chart-axis">${plainTextToHtml(yLabel)} ↑</div>` : ""}`;
|
|
416
|
+
return `${labels}<svg class="sm-chart-svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}">${parts.join("")}<line x1="${L}" x2="${W - 10}" y1="${zero}" y2="${zero}" stroke="#bbb"/></svg>${xLabel ? `<div class="sm-chart-axis sm-chart-axis-x">${plainTextToHtml(xLabel)} →</div>` : ""}${legend(series.map((s) => str(s.name)))}`;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function dataVisualizationBlock(block: Rec): string {
|
|
420
|
+
const chart = rec(block.chart) ?? {};
|
|
421
|
+
const type = str(chart.type);
|
|
422
|
+
const body =
|
|
423
|
+
type === "pie"
|
|
424
|
+
? pieChart(chart)
|
|
425
|
+
: type === "bar" || type === "line" || type === "area"
|
|
426
|
+
? seriesChart(chart, type)
|
|
427
|
+
: unsupported(`chart ${type}`);
|
|
428
|
+
return `<div class="sm-block sm-chart" data-chart="${escapeHtml(type)}"><div class="sm-chart-title">${plainTextToHtml(str(block.title))}</div>${body}</div>`;
|
|
429
|
+
}
|
|
430
|
+
|
|
271
431
|
function renderBlock(v: unknown, ctx: RenderContext): string {
|
|
272
432
|
const block = rec(v);
|
|
273
433
|
if (!block) return unsupported("block");
|
|
@@ -296,6 +456,13 @@ function renderBlock(v: unknown, ctx: RenderContext): string {
|
|
|
296
456
|
return `<div class="sm-block sm-file-block">📎 ${escapeHtml(str(block.external_id) || str(block.file_id) || "file")}</div>`;
|
|
297
457
|
case "video":
|
|
298
458
|
return videoBlock(block, ctx);
|
|
459
|
+
case "markdown":
|
|
460
|
+
return `<div class="sm-block sm-markdown">${markdownToHtml(str(block.text), ctx)}</div>`;
|
|
461
|
+
case "table":
|
|
462
|
+
case "data_table":
|
|
463
|
+
return tableBlock(block, ctx);
|
|
464
|
+
case "data_visualization":
|
|
465
|
+
return dataVisualizationBlock(block);
|
|
299
466
|
default:
|
|
300
467
|
return `<div class="sm-block">${unsupported(str(block.type))}</div>`;
|
|
301
468
|
}
|
package/src/render/index.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
displayName,
|
|
10
10
|
emojiChar,
|
|
11
11
|
escapeHtml,
|
|
12
|
+
markdownToHtml,
|
|
12
13
|
mrkdwnToHtml,
|
|
13
14
|
plainTextToHtml,
|
|
14
15
|
type RenderContext,
|
|
@@ -216,6 +217,25 @@ a:hover{text-decoration:underline}
|
|
|
216
217
|
.sm-video-title{font-size:14px;font-weight:700;margin-top:4px}
|
|
217
218
|
.sm-unsupported{display:inline-block;background:#f4f4f4;border:1px solid #ddd;border-radius:4px;padding:4px 8px;font-size:12px;color:#616061;font-family:Monaco,Menlo,monospace}
|
|
218
219
|
.sm-rt-section{margin:2px 0}
|
|
220
|
+
.sm-table-caption{font-size:13px;font-weight:700;color:#454245;margin-bottom:4px}
|
|
221
|
+
.sm-table-wrap{width:fit-content;overflow-x:auto;border:1px solid #ddd;border-radius:6px;max-width:100%}
|
|
222
|
+
.sm-bk-table{border-collapse:collapse;font-size:14px;line-height:20px}
|
|
223
|
+
.sm-bk-table th,.sm-bk-table td{padding:6px 12px;text-align:left;border-bottom:1px solid #e8e8e8;white-space:nowrap;vertical-align:top}
|
|
224
|
+
.sm-bk-table th{font-weight:700;background:#f8f8f8}
|
|
225
|
+
.sm-bk-table tr:last-child td{border-bottom:0}
|
|
226
|
+
.sm-bk-table .sm-ta-center{text-align:center}
|
|
227
|
+
.sm-bk-table .sm-ta-right{text-align:right}
|
|
228
|
+
.sm-bk-table .sm-td-wrap{white-space:normal}
|
|
229
|
+
.sm-table-pager{display:flex;align-items:center;gap:6px;font-size:12px;color:#616061;margin-top:4px}
|
|
230
|
+
.sm-pager-btn{border:1px solid #ddd;border-radius:4px;background:#fff;color:#1d1c1d;font-size:14px;line-height:16px;padding:0 6px;cursor:pointer}
|
|
231
|
+
.sm-pager-btn:disabled{color:#bbb;cursor:default}
|
|
232
|
+
.sm-chart{border:1px solid #ddd;border-radius:6px;padding:10px 12px;max-width:520px}
|
|
233
|
+
.sm-chart-title{font-size:14px;font-weight:700;margin-bottom:6px}
|
|
234
|
+
.sm-chart-svg{display:block;max-width:100%;height:auto;font-size:11px;fill:#616061}
|
|
235
|
+
.sm-chart-axis{font-size:11px;color:#616061}
|
|
236
|
+
.sm-chart-axis-x{text-align:center}
|
|
237
|
+
.sm-chart-legend{display:flex;flex-wrap:wrap;gap:4px 12px;font-size:12px;color:#454245;margin-top:6px}
|
|
238
|
+
.sm-chart-key i{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:4px;vertical-align:-1px}
|
|
219
239
|
|
|
220
240
|
.sm-atts{margin-top:4px}
|
|
221
241
|
.sm-att{border-left:4px solid #ddd;border-radius:2px;padding:2px 0 2px 12px;margin:6px 0;max-width:600px}
|
|
@@ -588,14 +608,18 @@ function renderMessage(
|
|
|
588
608
|
const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
|
|
589
609
|
const interactive = !opts.screenshot && !flags.ephemeral && humanUsers(store).length > 0;
|
|
590
610
|
const body: string[] = [];
|
|
591
|
-
if (m.streaming_state !== undefined) {
|
|
611
|
+
if (m.streaming_state !== undefined && !m.stream_replaced) {
|
|
592
612
|
// A streamed message (chat.startStream) keeps its Markdown body; the blocks handed to
|
|
593
|
-
// chat.stopStream are appended below it, like Slack does.
|
|
594
|
-
|
|
595
|
-
|
|
613
|
+
// chat.stopStream are appended below it, like Slack does. Once chat.update replaces the
|
|
614
|
+
// blocks (agent-swarm resends the answer as a `markdown` block), they carry the body and
|
|
615
|
+
// the message renders like a posted one.
|
|
616
|
+
if (m.text) body.push(`<div class="sm-text">${markdownToHtml(m.text, ctx)}</div>`);
|
|
596
617
|
if (blocks) body.push(renderBlocks(blocks, ctx));
|
|
597
618
|
} else if (blocks) body.push(renderBlocks(blocks, ctx));
|
|
598
|
-
else if (m.text)
|
|
619
|
+
else if (m.text)
|
|
620
|
+
body.push(
|
|
621
|
+
`<div class="sm-text">${m.text_format === "markdown" ? markdownToHtml(m.text, ctx) : mrkdwnToHtml(m.text, ctx)}</div>`,
|
|
622
|
+
);
|
|
599
623
|
if (m.edited) body.push(`<div class="sm-edited">(edited)</div>`);
|
|
600
624
|
if (m.attachments?.length) body.push(renderAttachments(m.attachments, ctx));
|
|
601
625
|
body.push(filesHtml(m.files, store.bot.token));
|
|
@@ -619,27 +643,6 @@ function renderMessage(
|
|
|
619
643
|
return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}" data-ts="${escapeHtml(m.ts)}" data-channel="${escapeHtml(m.channel)}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
|
|
620
644
|
}
|
|
621
645
|
|
|
622
|
-
/**
|
|
623
|
-
* Streamed messages carry Markdown (`markdown_text`), not mrkdwn. Convert the common
|
|
624
|
-
* constructs so the mrkdwn renderer shows them: **bold**, [label](url), headings and list
|
|
625
|
-
* bullets. Fenced code blocks pass through untouched.
|
|
626
|
-
*/
|
|
627
|
-
function markdownToMrkdwn(text: string): string {
|
|
628
|
-
return text
|
|
629
|
-
.split(/(```[\s\S]*?```)/)
|
|
630
|
-
.map((part, i) =>
|
|
631
|
-
i % 2 === 1
|
|
632
|
-
? part
|
|
633
|
-
: part
|
|
634
|
-
.replace(/\*\*(.+?)\*\*/g, "*$1*")
|
|
635
|
-
.replace(/__(.+?)__/g, "*$1*")
|
|
636
|
-
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, "<$2|$1>")
|
|
637
|
-
.replace(/^#{1,6}\s+(.+)$/gm, "*$1*")
|
|
638
|
-
.replace(/^(\s*)[-*]\s+/gm, "$1• "),
|
|
639
|
-
)
|
|
640
|
-
.join("");
|
|
641
|
-
}
|
|
642
|
-
|
|
643
646
|
function renderMessageList(
|
|
644
647
|
store: Store,
|
|
645
648
|
ctx: RenderContext,
|
|
@@ -894,6 +897,7 @@ function fitViewport(){if(viewport&&viewport.scale!==1)return;var style=document
|
|
|
894
897
|
fitViewport();addEventListener("resize",fitViewport);
|
|
895
898
|
if(viewport){viewport.addEventListener("resize",fitViewport);viewport.addEventListener("scroll",fitViewport)}
|
|
896
899
|
document.addEventListener("change",function(e){if(e.target.classList.contains("sm-channel-switch"))location.href=e.target.value});
|
|
900
|
+
document.addEventListener("click",function(e){var b=e.target.closest(".sm-pager-btn");if(!b)return;var block=b.closest(".sm-table-block"),pages=block.querySelectorAll("tbody"),cur=0;pages.forEach(function(t,i){if(!t.hidden)cur=i});var next=Math.min(Math.max(cur+Number(b.dataset.step),0),pages.length-1);pages.forEach(function(t,i){t.hidden=i!==next});block.querySelector(".sm-pager-label").textContent=pages[next].dataset.range;var btns=block.querySelectorAll(".sm-pager-btn");btns[0].disabled=next===0;btns[1].disabled=next===pages.length-1});
|
|
897
901
|
var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
|
|
898
902
|
${autoScroll ? 'function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}\nscroll();addEventListener("load",scroll);' : ""}
|
|
899
903
|
var handle=document.querySelector(".sm-resize");
|
package/src/render/mrkdwn.ts
CHANGED
|
@@ -319,3 +319,42 @@ export function plainTextToHtml(text: string): string {
|
|
|
319
319
|
if (!text) return "";
|
|
320
320
|
return renderEmoji(reEscape(text.replace(/\r\n/g, "\n"))).replace(/\n/g, "<br>");
|
|
321
321
|
}
|
|
322
|
+
|
|
323
|
+
const BOLD = "\uE002";
|
|
324
|
+
const CODE = /\uE003(\d+)\uE004/g;
|
|
325
|
+
|
|
326
|
+
/** Markdown inline styles and line markers -> mrkdwn, for one stretch of text outside code. */
|
|
327
|
+
function markdownProse(s: string): string {
|
|
328
|
+
return s
|
|
329
|
+
.replace(/^(\s*)[-*+]\s+/gm, "$1• ")
|
|
330
|
+
.replace(/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/gm, "──────────")
|
|
331
|
+
.replace(/\*\*(.+?)\*\*/g, `${BOLD}$1${BOLD}`)
|
|
332
|
+
.replace(/__(.+?)__/g, `${BOLD}$1${BOLD}`)
|
|
333
|
+
.replace(/(^|[^*\w])\*(?![\s*])([^*\n]*[^\s*])\*(?![*\w])/g, "$1_$2_")
|
|
334
|
+
.replace(/~~(.+?)~~/g, "~$1~")
|
|
335
|
+
.replace(/\[([^\]]+)\]\(((?:https?:\/\/|mailto:)[^)\s]+)\)/g, "<$2|$1>")
|
|
336
|
+
.replace(
|
|
337
|
+
/^ {0,3}#{1,6}\s+(.+?)\s*#*\s*$/gm,
|
|
338
|
+
(_m, title: string) => `${BOLD}${title.replaceAll(BOLD, "")}${BOLD}`,
|
|
339
|
+
)
|
|
340
|
+
.replaceAll(BOLD, "*");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Markdown (`markdown` blocks, `markdown_text` on streams) -> mrkdwn, so the mrkdwn renderer
|
|
345
|
+
* shows it: **bold**, *italic*, ~~strike~~, [label](url), headings, bullets and rules.
|
|
346
|
+
* Code spans and fenced code pass through untouched: they are held as placeholders while the
|
|
347
|
+
* enclosing heading, link or style is converted, then put back.
|
|
348
|
+
*/
|
|
349
|
+
export function markdownToMrkdwn(text: string): string {
|
|
350
|
+
const code: string[] = [];
|
|
351
|
+
const held = text
|
|
352
|
+
.replace(/\r\n/g, "\n")
|
|
353
|
+
.replace(/```[\s\S]*?```|`[^`\n]+`/g, (m) => `\uE003${code.push(m) - 1}\uE004`);
|
|
354
|
+
return markdownProse(held).replace(CODE, (_m, i: string) => code[Number(i)] ?? "");
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Render Markdown to HTML through the mrkdwn renderer. */
|
|
358
|
+
export function markdownToHtml(text: string, ctx: RenderContext): string {
|
|
359
|
+
return mrkdwnToHtml(markdownToMrkdwn(text), ctx);
|
|
360
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -15,6 +15,11 @@ import {
|
|
|
15
15
|
slashCommandPayload,
|
|
16
16
|
viewSubmissionPayload,
|
|
17
17
|
} from "./events.ts";
|
|
18
|
+
import {
|
|
19
|
+
HttpDelivery,
|
|
20
|
+
type HttpDeliveryOptions,
|
|
21
|
+
HttpDeliveryStoppedError,
|
|
22
|
+
} from "./http-delivery.ts";
|
|
18
23
|
import { slackId } from "./ids.ts";
|
|
19
24
|
import { renderPage } from "./render/index.ts";
|
|
20
25
|
import {
|
|
@@ -101,6 +106,11 @@ export interface SlackMockOptions extends StoreOptions {
|
|
|
101
106
|
* admin credential. `adminAuth` always implies it.
|
|
102
107
|
*/
|
|
103
108
|
presenterAuth?: string;
|
|
109
|
+
/**
|
|
110
|
+
* Deliver events, slash commands and interactivity as signed HTTP requests to the app's request
|
|
111
|
+
* URLs instead of over Socket Mode (Slack's HTTP mode). The app needs no WebSocket connection.
|
|
112
|
+
*/
|
|
113
|
+
httpDelivery?: HttpDeliveryOptions;
|
|
104
114
|
log?: boolean | ((msg: string) => void);
|
|
105
115
|
}
|
|
106
116
|
|
|
@@ -165,6 +175,11 @@ interface ResponseUrl {
|
|
|
165
175
|
export class SlackMock {
|
|
166
176
|
readonly store: Store;
|
|
167
177
|
readonly hub: SocketModeHub;
|
|
178
|
+
/** Where deliveries go: the HTTP request URLs when `httpDelivery` is set, else the Socket Mode hub. */
|
|
179
|
+
readonly delivery: Pick<
|
|
180
|
+
SocketModeHub,
|
|
181
|
+
"send" | "connectionCount" | "history" | "waitForConnection"
|
|
182
|
+
>;
|
|
168
183
|
readonly opts: SlackMockOptions;
|
|
169
184
|
private server!: Server<ConnData>;
|
|
170
185
|
private triggerIds = new Map<string, number>();
|
|
@@ -198,6 +213,9 @@ export class SlackMock {
|
|
|
198
213
|
maxRetries: opts.maxRetries,
|
|
199
214
|
log: this.log,
|
|
200
215
|
});
|
|
216
|
+
this.delivery = opts.httpDelivery
|
|
217
|
+
? new HttpDelivery({ log: this.log, ...opts.httpDelivery })
|
|
218
|
+
: this.hub;
|
|
201
219
|
this.subscribed = new Set(
|
|
202
220
|
opts.subscribedEvents ??
|
|
203
221
|
manifest?.settings?.event_subscriptions?.bot_events ??
|
|
@@ -318,7 +336,7 @@ export class SlackMock {
|
|
|
318
336
|
SLACK_BOT_TOKEN: this.store.bot.token,
|
|
319
337
|
SLACK_APP_TOKEN: this.store.bot.appToken,
|
|
320
338
|
SLACK_API_URL: this.apiUrl,
|
|
321
|
-
SLACK_SIGNING_SECRET: "mock-signing-secret",
|
|
339
|
+
SLACK_SIGNING_SECRET: this.opts.httpDelivery?.signingSecret ?? "mock-signing-secret",
|
|
322
340
|
};
|
|
323
341
|
}
|
|
324
342
|
|
|
@@ -327,7 +345,7 @@ export class SlackMock {
|
|
|
327
345
|
}
|
|
328
346
|
/** Number of Socket Mode connections the app currently holds. */
|
|
329
347
|
get connectionCount(): number {
|
|
330
|
-
return this.
|
|
348
|
+
return this.delivery.connectionCount;
|
|
331
349
|
}
|
|
332
350
|
|
|
333
351
|
get team() {
|
|
@@ -336,6 +354,7 @@ export class SlackMock {
|
|
|
336
354
|
|
|
337
355
|
async stop(): Promise<void> {
|
|
338
356
|
this.hub.shutdown();
|
|
357
|
+
if (this.delivery instanceof HttpDelivery) this.delivery.shutdown();
|
|
339
358
|
await Promise.allSettled([...this.inflight]);
|
|
340
359
|
this.server.stop(true);
|
|
341
360
|
}
|
|
@@ -460,7 +479,8 @@ export class SlackMock {
|
|
|
460
479
|
};
|
|
461
480
|
try {
|
|
462
481
|
const body = handler(ctx, args);
|
|
463
|
-
|
|
482
|
+
// A handler may return `ok: false` for a documented failure without an `error` code.
|
|
483
|
+
record(body.ok !== false);
|
|
464
484
|
return Response.json({ ok: true, ...body });
|
|
465
485
|
} catch (e) {
|
|
466
486
|
if (e instanceof SlackApiError) {
|
|
@@ -595,7 +615,7 @@ export class SlackMock {
|
|
|
595
615
|
const opts = {
|
|
596
616
|
screenshot,
|
|
597
617
|
refreshSec: Number.isFinite(refresh) && refresh > 0 ? refresh : undefined,
|
|
598
|
-
connections: this.
|
|
618
|
+
connections: this.delivery.connectionCount,
|
|
599
619
|
panelWidth: panel
|
|
600
620
|
? /^\d+$/.test(panel)
|
|
601
621
|
? `${panel}%`
|
|
@@ -684,7 +704,7 @@ export class SlackMock {
|
|
|
684
704
|
const wrapped = p.then(
|
|
685
705
|
() => {},
|
|
686
706
|
(e) => {
|
|
687
|
-
if (!(e instanceof SocketModeClosedError))
|
|
707
|
+
if (!(e instanceof SocketModeClosedError || e instanceof HttpDeliveryStoppedError))
|
|
688
708
|
this.log(`delivery failed: ${e instanceof Error ? e.message : e}`);
|
|
689
709
|
},
|
|
690
710
|
);
|
|
@@ -694,7 +714,7 @@ export class SlackMock {
|
|
|
694
714
|
}
|
|
695
715
|
|
|
696
716
|
private push(event: Record<string, unknown>): Promise<void> {
|
|
697
|
-
if (this.
|
|
717
|
+
if (this.delivery.connectionCount === 0) {
|
|
698
718
|
this.log(
|
|
699
719
|
`dropping ${event.type}${event.subtype ? `/${event.subtype}` : ""} event: no app connected`,
|
|
700
720
|
);
|
|
@@ -702,7 +722,7 @@ export class SlackMock {
|
|
|
702
722
|
}
|
|
703
723
|
const send = async () => {
|
|
704
724
|
if (this.opts.eventDelayMs) await Bun.sleep(this.opts.eventDelayMs);
|
|
705
|
-
await this.
|
|
725
|
+
await this.delivery.send("events_api", eventCallback(this.store, event));
|
|
706
726
|
};
|
|
707
727
|
return this.track(send());
|
|
708
728
|
}
|
|
@@ -961,7 +981,7 @@ export class SlackMock {
|
|
|
961
981
|
responseUrl,
|
|
962
982
|
triggerId: this.issueTriggerId(),
|
|
963
983
|
});
|
|
964
|
-
const ack = await this.
|
|
984
|
+
const ack = await this.delivery.send("slash_commands", payload, true);
|
|
965
985
|
let response: SlackMessage | undefined;
|
|
966
986
|
const body = ack.payload as
|
|
967
987
|
| { text?: string; blocks?: unknown[]; response_type?: string }
|
|
@@ -1023,7 +1043,7 @@ export class SlackMock {
|
|
|
1023
1043
|
},
|
|
1024
1044
|
],
|
|
1025
1045
|
});
|
|
1026
|
-
const ack = await this.
|
|
1046
|
+
const ack = await this.delivery.send("interactive", payload, true);
|
|
1027
1047
|
await this.flush();
|
|
1028
1048
|
return ack;
|
|
1029
1049
|
}
|
|
@@ -1050,7 +1070,7 @@ export class SlackMock {
|
|
|
1050
1070
|
values: input.values,
|
|
1051
1071
|
triggerId: this.issueTriggerId(),
|
|
1052
1072
|
});
|
|
1053
|
-
const ack = await this.
|
|
1073
|
+
const ack = await this.delivery.send("interactive", payload, true);
|
|
1054
1074
|
// Slack keeps the modal open on `errors`, swaps it on `update`, stacks on `push`, closes otherwise.
|
|
1055
1075
|
const response = (ack.payload ?? {}) as {
|
|
1056
1076
|
response_action?: string;
|
|
@@ -1107,7 +1127,7 @@ export class SlackMock {
|
|
|
1107
1127
|
const threadTs = root.ts;
|
|
1108
1128
|
if (this.isSubscribed("assistant_thread_started")) {
|
|
1109
1129
|
await this.track(
|
|
1110
|
-
this.
|
|
1130
|
+
this.delivery.send(
|
|
1111
1131
|
"events_api",
|
|
1112
1132
|
eventCallback(
|
|
1113
1133
|
this.store,
|
|
@@ -1128,7 +1148,7 @@ export class SlackMock {
|
|
|
1128
1148
|
const user = input.user ? this.user(input.user) : this.defaultHuman();
|
|
1129
1149
|
const dm = this.resolveChannel(input.channel);
|
|
1130
1150
|
await this.track(
|
|
1131
|
-
this.
|
|
1151
|
+
this.delivery.send(
|
|
1132
1152
|
"events_api",
|
|
1133
1153
|
eventCallback(
|
|
1134
1154
|
this.store,
|
|
@@ -1170,7 +1190,7 @@ export class SlackMock {
|
|
|
1170
1190
|
|
|
1171
1191
|
/** Every Socket Mode envelope pushed to the app, with ack status. */
|
|
1172
1192
|
deliveries(name?: string): DeliveryRecord[] {
|
|
1173
|
-
return name ? this.
|
|
1193
|
+
return name ? this.delivery.history.filter((d) => d.name === name) : [...this.delivery.history];
|
|
1174
1194
|
}
|
|
1175
1195
|
|
|
1176
1196
|
apiCalls(method?: string): ApiCall[] {
|
|
@@ -1255,7 +1275,7 @@ export class SlackMock {
|
|
|
1255
1275
|
}
|
|
1256
1276
|
|
|
1257
1277
|
waitForConnection(timeoutMs = 15_000): Promise<void> {
|
|
1258
|
-
return this.
|
|
1278
|
+
return this.delivery.waitForConnection(timeoutMs);
|
|
1259
1279
|
}
|
|
1260
1280
|
|
|
1261
1281
|
disconnectSockets(reason?: Parameters<SocketModeHub["disconnectAll"]>[0]): void {
|
|
@@ -1282,7 +1302,7 @@ export class SlackMock {
|
|
|
1282
1302
|
team: this.store.team,
|
|
1283
1303
|
app: this.store.app,
|
|
1284
1304
|
bot: { userId: this.store.bot.userId, botId: this.store.bot.botId },
|
|
1285
|
-
connections: this.
|
|
1305
|
+
connections: this.delivery.connectionCount,
|
|
1286
1306
|
users: [...this.store.users.values()],
|
|
1287
1307
|
channels: [...this.store.channels.values()],
|
|
1288
1308
|
});
|
package/src/socket-mode.ts
CHANGED
|
@@ -57,7 +57,7 @@ export interface DeliveryRecord {
|
|
|
57
57
|
ackPayload?: unknown;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
function envelopeName(type: EnvelopeType, payload: unknown): string {
|
|
60
|
+
export function envelopeName(type: EnvelopeType, payload: unknown): string {
|
|
61
61
|
const p = payload as Record<string, unknown>;
|
|
62
62
|
if (type === "events_api")
|
|
63
63
|
return String((p.event as Record<string, unknown> | undefined)?.type ?? "event");
|
package/src/store.ts
CHANGED
|
@@ -119,7 +119,14 @@ export class Store {
|
|
|
119
119
|
readonly apiCalls: ApiCall[] = [];
|
|
120
120
|
readonly assistantThreads = new Map<
|
|
121
121
|
string,
|
|
122
|
-
{
|
|
122
|
+
{
|
|
123
|
+
status?: string;
|
|
124
|
+
title?: string;
|
|
125
|
+
prompts?: unknown[];
|
|
126
|
+
promptsTitle?: string;
|
|
127
|
+
/** agents.sessions.setStatus: "active", "processing", "suspended" or "closed". */
|
|
128
|
+
sessionStatus?: string;
|
|
129
|
+
}
|
|
123
130
|
>();
|
|
124
131
|
private listeners = new Set<(change: Change) => void>();
|
|
125
132
|
private dataFile?: string;
|
|
@@ -359,6 +366,16 @@ export class Store {
|
|
|
359
366
|
return { alreadyMember: false };
|
|
360
367
|
}
|
|
361
368
|
|
|
369
|
+
leave(channelId: string, userId: string): { notInChannel: boolean } {
|
|
370
|
+
const channel = this.channel(channelId);
|
|
371
|
+
if (channel.is_archived) throw new SlackApiError("is_archived");
|
|
372
|
+
if (channel.is_general) throw new SlackApiError("cant_leave_general");
|
|
373
|
+
if (!channel.members.includes(userId)) return { notInChannel: true };
|
|
374
|
+
channel.members = channel.members.filter((m) => m !== userId);
|
|
375
|
+
this.emit({ kind: "channel.update", channel });
|
|
376
|
+
return { notInChannel: false };
|
|
377
|
+
}
|
|
378
|
+
|
|
362
379
|
archive(channelId: string): void {
|
|
363
380
|
const channel = this.channel(channelId);
|
|
364
381
|
if (channel.is_archived) throw new SlackApiError("already_archived");
|
|
@@ -656,7 +673,7 @@ function guessMime(ext: string): string {
|
|
|
656
673
|
|
|
657
674
|
/** Public (wire) form of a message: mock-only fields removed, file bytes dropped. */
|
|
658
675
|
export function wireMessage(m: SlackMessage): Record<string, unknown> {
|
|
659
|
-
const { ephemeral_user: _e, ...rest } = m;
|
|
676
|
+
const { ephemeral_user: _e, text_format: _f, stream_replaced: _r, ...rest } = m;
|
|
660
677
|
if (rest.files) rest.files = rest.files.map(wireFile);
|
|
661
678
|
return rest;
|
|
662
679
|
}
|
package/src/types.ts
CHANGED
|
@@ -103,6 +103,10 @@ export interface SlackMessage {
|
|
|
103
103
|
thumb_64?: string;
|
|
104
104
|
/** Mock-only: the user who can see an ephemeral message. Stripped on the wire. */
|
|
105
105
|
ephemeral_user?: string;
|
|
106
|
+
/** Mock-only: `text` came in as `markdown_text`, so the UI renders it as Markdown. Stripped on the wire. */
|
|
107
|
+
text_format?: "markdown";
|
|
108
|
+
/** Mock-only: chat.update replaced a streamed message's blocks, so they carry the body. Stripped on the wire. */
|
|
109
|
+
stream_replaced?: true;
|
|
106
110
|
}
|
|
107
111
|
|
|
108
112
|
export interface SlackView {
|