@desplega.ai/slack-mock 0.1.1 → 0.2.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.
@@ -1,5 +1,7 @@
1
1
  /** Locate a Chrome/Chromium binary for headless screenshots, or undefined. */
2
2
  export declare function findChrome(): string | undefined;
3
+ /** Like `findChrome`, but throws when no binary is found. */
4
+ export declare function requireChrome(): string;
3
5
  export interface ScreenshotOptions {
4
6
  out: string;
5
7
  width?: number;
@@ -1,9 +1,11 @@
1
1
  // @bun
2
2
  import {
3
- findChrome,
4
- screenshot
5
- } from "./index-v7mbr1cx.js";
3
+ findChrome2,
4
+ requireChrome2,
5
+ screenshot2
6
+ } from "./index-v2hesj4s.js";
6
7
  export {
7
- findChrome,
8
- screenshot
8
+ findChrome2 as findChrome,
9
+ requireChrome2 as requireChrome,
10
+ screenshot2 as screenshot
9
11
  };
package/dist/server.d.ts CHANGED
@@ -20,6 +20,10 @@ export interface SlackManifest {
20
20
  };
21
21
  };
22
22
  }
23
+ /** Read a manifest given as a path or an object. */
24
+ export declare function loadManifest(manifest: string | SlackManifest | undefined): SlackManifest | undefined;
25
+ /** The bot display name a manifest declares, if any. */
26
+ export declare function manifestAppName(manifest: SlackManifest | undefined): string | undefined;
23
27
  export interface SlackMockOptions extends StoreOptions {
24
28
  /** 0 picks a free port. */
25
29
  port?: number;
package/dist/store.d.ts CHANGED
@@ -7,6 +7,8 @@ export declare class SlackApiError extends Error {
7
7
  export interface StoreOptions {
8
8
  /** Append every change as one JSON line to this file and replay it on start. */
9
9
  dataFile?: string;
10
+ /** Changes to apply on construction, as if read from `dataFile`. Nothing is written. */
11
+ replay?: Change[];
10
12
  teamId?: string;
11
13
  teamName?: string;
12
14
  teamDomain?: string;
@@ -48,6 +50,13 @@ export interface Page<T> {
48
50
  has_more: boolean;
49
51
  next_cursor: string;
50
52
  }
53
+ /** One parsed journal line and its 1-based line number. */
54
+ export interface JournalEntry {
55
+ line: number;
56
+ change: Change;
57
+ }
58
+ /** Parse a JSONL journal. Corrupt lines are skipped with a warning; blank lines are ignored. */
59
+ export declare function parseJournal(text: string, source?: string): JournalEntry[];
51
60
  /** In-memory Slack workspace with an optional append-only JSONL journal. */
52
61
  export declare class Store {
53
62
  readonly team: {
@@ -115,7 +124,9 @@ export declare class Store {
115
124
  addMessage(input: Omit<SlackMessage, "type" | "team" | "ts"> & {
116
125
  ts?: string;
117
126
  }): SlackMessage;
118
- updateMessage(channelId: string, ts: string, patch: Partial<SlackMessage>, editor: string): SlackMessage;
127
+ updateMessage(channelId: string, ts: string, patch: Partial<SlackMessage>, editor: string, opts?: {
128
+ markEdited?: boolean;
129
+ }): SlackMessage;
119
130
  deleteMessage(channelId: string, ts: string): SlackMessage;
120
131
  addReaction(channelId: string, ts: string, name: string, userId: string): SlackMessage;
121
132
  removeReaction(channelId: string, ts: string, name: string, userId: string): SlackMessage;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@desplega.ai/slack-mock",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Mock Slack server (Web API + Socket Mode) for end-to-end testing Slack bots",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  import { parseArgs } from "node:util";
3
+ import { frames } from "./frames.ts";
3
4
  import { screenshot } from "./screenshot.ts";
4
5
  import { SlackMock } from "./server.ts";
5
6
 
@@ -9,6 +10,11 @@ Usage:
9
10
  slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json]
10
11
  [--no-seed] [--quiet] [--panel 50] [--auth user:pass] [--public-url https://mock.example.com]
11
12
  slack-mock screenshot <url> --out shot.png [--width 800] [--height 1000]
13
+ slack-mock frames --journal data.jsonl --channel C0GENERAL0 [--thread 1788516626.286000] --out ./frames
14
+ [--manifest app.json] [--width 800] [--height 700] [--no-desktop]
15
+
16
+ frames renders the thread (or, without --thread, the channel) as it looked after every journal
17
+ line that touched it: one PNG per line, then final-thread.png and final-desktop.png.
12
18
 
13
19
  serve prints the env vars to give your bot (SLACK_BOT_TOKEN, SLACK_APP_TOKEN, SLACK_API_URL)
14
20
  and the URLs of the HTML views. Inject messages with the admin API, e.g.
@@ -84,6 +90,37 @@ async function main(argv: string[]): Promise<void> {
84
90
  console.log(out);
85
91
  return;
86
92
  }
93
+ if (command === "frames") {
94
+ const { values } = parseArgs({
95
+ args: rest,
96
+ options: {
97
+ journal: { type: "string" },
98
+ channel: { type: "string" },
99
+ thread: { type: "string" },
100
+ out: { type: "string" },
101
+ manifest: { type: "string" },
102
+ width: { type: "string", default: "800" },
103
+ height: { type: "string", default: "700" },
104
+ "no-desktop": { type: "boolean", default: false },
105
+ },
106
+ });
107
+ if (!values.journal || !values.channel || !values.out)
108
+ throw new Error("frames needs --journal, --channel and --out");
109
+ const result = await frames({
110
+ journal: values.journal,
111
+ channel: values.channel,
112
+ thread: values.thread,
113
+ out: values.out,
114
+ manifest: values.manifest,
115
+ width: Number(values.width),
116
+ height: Number(values.height),
117
+ desktop: !values["no-desktop"],
118
+ });
119
+ for (const f of result.frames) console.log(`${f.index}\t${f.kind}\t${f.path}`);
120
+ console.log(`final-thread=${result.finalThread}`);
121
+ if (result.finalDesktop) console.log(`final-desktop=${result.finalDesktop}`);
122
+ return;
123
+ }
87
124
  console.log(USAGE);
88
125
  if (command && command !== "help" && command !== "--help") process.exit(1);
89
126
  }
package/src/frames.ts ADDED
@@ -0,0 +1,128 @@
1
+ // Render a thread (or a channel) as it looked after each journal line that touched it: one PNG
2
+ // per line. The journal is replayed in memory and each page is written to a temp file that
3
+ // headless Chrome opens over file://, so no server is started.
4
+
5
+ import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join, resolve } from "node:path";
8
+ import { type RenderOptions, renderPage, type View } from "./render/index.ts";
9
+ import { requireChrome, screenshot } from "./screenshot.ts";
10
+ import { loadManifest, manifestAppName, type SlackManifest } from "./server.ts";
11
+ import { type JournalEntry, parseJournal, Store } from "./store.ts";
12
+
13
+ export interface FramesOptions {
14
+ /** Path to a JSONL journal written by `dataFile`. */
15
+ journal: string;
16
+ /** Channel id or name. */
17
+ channel: string;
18
+ /** Thread root ts. When absent, render the channel view instead of the thread view. */
19
+ thread?: string;
20
+ /** Output directory. Created when missing. */
21
+ out: string;
22
+ /** Slack app manifest path or object, same as `SlackMockOptions.manifest`. */
23
+ manifest?: string | SlackManifest;
24
+ /** Viewport width in px. Default 800. */
25
+ width?: number;
26
+ /** Viewport height in px. Default 700. */
27
+ height?: number;
28
+ /** Also render `final-desktop.png` (`?screenshot=0`, 1280x900). Default true. */
29
+ desktop?: boolean;
30
+ }
31
+
32
+ export interface Frame {
33
+ /** 1-based journal line number the frame was rendered after. */
34
+ index: number;
35
+ /** Journal `kind` of that line. */
36
+ kind: string;
37
+ /** Absolute PNG path. */
38
+ path: string;
39
+ }
40
+
41
+ export interface FramesResult {
42
+ frames: Frame[];
43
+ /** Copy of the last frame. */
44
+ finalThread: string;
45
+ /** Present when `desktop` is true. */
46
+ finalDesktop?: string;
47
+ }
48
+
49
+ const FRAME_KINDS = new Set([
50
+ "message.add",
51
+ "message.update",
52
+ "message.delete",
53
+ "reaction.add",
54
+ "reaction.remove",
55
+ "file.add",
56
+ ]);
57
+
58
+ /**
59
+ * Journal entries that change what the thread (or, without `thread`, the channel) shows.
60
+ * `file.add` carries no message, so a file only shows up with the message that shares it.
61
+ */
62
+ export function selectFrames(
63
+ entries: JournalEntry[],
64
+ channel: string,
65
+ thread?: string,
66
+ ): JournalEntry[] {
67
+ return entries.filter(({ change }) => {
68
+ if (!FRAME_KINDS.has(change.kind) || !("message" in change)) return false;
69
+ const m = change.message;
70
+ if (m.channel !== channel) return false;
71
+ return thread ? m.ts === thread || m.thread_ts === thread : true;
72
+ });
73
+ }
74
+
75
+ export async function frames(opts: FramesOptions): Promise<FramesResult> {
76
+ const entries = parseJournal(readFileSync(opts.journal, "utf8"), opts.journal);
77
+ const appName = manifestAppName(loadManifest(opts.manifest));
78
+ const storeAfter = (line: number) =>
79
+ new Store({ replay: entries.filter((e) => e.line <= line).map((e) => e.change), appName });
80
+ const full = storeAfter(Number.POSITIVE_INFINITY);
81
+ const channel = full.channels.get(opts.channel) ?? full.channelByName(opts.channel);
82
+ if (!channel) throw new Error(`channel ${opts.channel} not found in ${opts.journal}`);
83
+ const what = opts.thread ? `thread ${opts.thread} in ${channel.id}` : `channel ${channel.id}`;
84
+ const selected = selectFrames(entries, channel.id, opts.thread);
85
+ if (!selected.length) throw new Error(`no line of ${opts.journal} touches ${what}`);
86
+ requireChrome();
87
+
88
+ const view: View = opts.thread
89
+ ? { kind: "thread", channel: channel.id, ts: opts.thread }
90
+ : { kind: "channel", channel: channel.id };
91
+ const out = resolve(opts.out);
92
+ mkdirSync(out, { recursive: true });
93
+ const tmp = mkdtempSync(join(tmpdir(), "slack-mock-frames-"));
94
+ const html = join(tmp, "frame.html");
95
+ const shoot = async (
96
+ store: Store,
97
+ file: string,
98
+ render: RenderOptions,
99
+ size: { width: number; height: number },
100
+ ) => {
101
+ writeFileSync(html, renderPage(store, view, render));
102
+ await screenshot(Bun.pathToFileURL(html).href, { out: file, ...size });
103
+ };
104
+ try {
105
+ const frames: Frame[] = [];
106
+ const size = { width: opts.width ?? 800, height: opts.height ?? 700 };
107
+ for (const [i, { line, change }] of selected.entries()) {
108
+ const path = join(out, `${String(i + 1).padStart(2, "0")}-${change.kind}.png`);
109
+ await shoot(storeAfter(line), path, { screenshot: true }, size);
110
+ frames.push({ index: line, kind: change.kind, path });
111
+ }
112
+ const finalThread = join(out, "final-thread.png");
113
+ copyFileSync(frames[frames.length - 1]!.path, finalThread);
114
+ let finalDesktop: string | undefined;
115
+ if (opts.desktop !== false) {
116
+ finalDesktop = join(out, "final-desktop.png");
117
+ await shoot(
118
+ full,
119
+ finalDesktop,
120
+ { screenshot: false, live: false },
121
+ { width: 1280, height: 900 },
122
+ );
123
+ }
124
+ return { frames, finalThread, finalDesktop };
125
+ } finally {
126
+ rmSync(tmp, { recursive: true, force: true });
127
+ }
128
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export type { Frame, FramesOptions, FramesResult } from "./frames.ts";
2
+ export { frames } from "./frames.ts";
1
3
  export { findChrome, screenshot } from "./screenshot.ts";
2
4
  export type {
3
5
  Fault,
@@ -455,7 +455,13 @@ function renderMessage(
455
455
  const isApp = Boolean(m.bot_id);
456
456
  const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
457
457
  const body: string[] = [];
458
- if (blocks) body.push(renderBlocks(blocks, ctx));
458
+ if (m.streaming_state !== undefined) {
459
+ // A streamed message (chat.startStream) keeps its Markdown body; the blocks handed to
460
+ // chat.stopStream are appended below it, like Slack does.
461
+ if (m.text)
462
+ body.push(`<div class="sm-text">${mrkdwnToHtml(markdownToMrkdwn(m.text), ctx)}</div>`);
463
+ if (blocks) body.push(renderBlocks(blocks, ctx));
464
+ } else if (blocks) body.push(renderBlocks(blocks, ctx));
459
465
  else if (m.text) body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
460
466
  if (m.edited) body.push(`<div class="sm-edited">(edited)</div>`);
461
467
  if (m.attachments?.length) body.push(renderAttachments(m.attachments, ctx));
@@ -479,6 +485,27 @@ function renderMessage(
479
485
  return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}" data-ts="${escapeHtml(m.ts)}">${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>`;
480
486
  }
481
487
 
488
+ /**
489
+ * Streamed messages carry Markdown (`markdown_text`), not mrkdwn. Convert the common
490
+ * constructs so the mrkdwn renderer shows them: **bold**, [label](url), headings and list
491
+ * bullets. Fenced code blocks pass through untouched.
492
+ */
493
+ function markdownToMrkdwn(text: string): string {
494
+ return text
495
+ .split(/(```[\s\S]*?```)/)
496
+ .map((part, i) =>
497
+ i % 2 === 1
498
+ ? part
499
+ : part
500
+ .replace(/\*\*(.+?)\*\*/g, "*$1*")
501
+ .replace(/__(.+?)__/g, "*$1*")
502
+ .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, "<$2|$1>")
503
+ .replace(/^#{1,6}\s+(.+)$/gm, "*$1*")
504
+ .replace(/^(\s*)[-*]\s+/gm, "$1• "),
505
+ )
506
+ .join("");
507
+ }
508
+
482
509
  function renderMessageList(
483
510
  store: Store,
484
511
  ctx: RenderContext,
package/src/screenshot.ts CHANGED
@@ -17,6 +17,14 @@ export function findChrome(): string | undefined {
17
17
  return fromPath ?? undefined;
18
18
  }
19
19
 
20
+ /** Like `findChrome`, but throws when no binary is found. */
21
+ export function requireChrome(): string {
22
+ const chrome = findChrome();
23
+ if (!chrome)
24
+ throw new Error("no Chrome/Chromium binary found; set SLACK_MOCK_CHROME=/path/to/chrome");
25
+ return chrome;
26
+ }
27
+
20
28
  export interface ScreenshotOptions {
21
29
  out: string;
22
30
  width?: number;
@@ -29,9 +37,7 @@ export interface ScreenshotOptions {
29
37
  * mock's pages drop their navigation chrome.
30
38
  */
31
39
  export async function screenshot(url: string, opts: ScreenshotOptions): Promise<string> {
32
- const chrome = findChrome();
33
- if (!chrome)
34
- throw new Error("no Chrome/Chromium binary found; set SLACK_MOCK_CHROME=/path/to/chrome");
40
+ const chrome = requireChrome();
35
41
  const target = new URL(url);
36
42
  if (!target.searchParams.has("screenshot")) target.searchParams.set("screenshot", "1");
37
43
  const proc = Bun.spawn(
package/src/server.ts CHANGED
@@ -45,6 +45,20 @@ export interface SlackManifest {
45
45
  settings?: { event_subscriptions?: { bot_events?: string[] } };
46
46
  }
47
47
 
48
+ /** Read a manifest given as a path or an object. */
49
+ export function loadManifest(
50
+ manifest: string | SlackManifest | undefined,
51
+ ): SlackManifest | undefined {
52
+ return typeof manifest === "string"
53
+ ? (JSON.parse(readFileSync(manifest, "utf8")) as SlackManifest)
54
+ : manifest;
55
+ }
56
+
57
+ /** The bot display name a manifest declares, if any. */
58
+ export function manifestAppName(manifest: SlackManifest | undefined): string | undefined {
59
+ return manifest?.features?.bot_user?.display_name ?? manifest?.display_information?.name;
60
+ }
61
+
48
62
  export interface SlackMockOptions extends StoreOptions {
49
63
  /** 0 picks a free port. */
50
64
  port?: number;
@@ -165,14 +179,8 @@ export class SlackMock {
165
179
  static Error = SlackApiError;
166
180
 
167
181
  constructor(opts: SlackMockOptions = {}) {
168
- const manifest =
169
- typeof opts.manifest === "string"
170
- ? (JSON.parse(readFileSync(opts.manifest, "utf8")) as SlackManifest)
171
- : opts.manifest;
172
- const appName =
173
- opts.appName ??
174
- manifest?.features?.bot_user?.display_name ??
175
- manifest?.display_information?.name;
182
+ const manifest = loadManifest(opts.manifest);
183
+ const appName = opts.appName ?? manifestAppName(manifest);
176
184
  this.opts = { ...opts, appName };
177
185
  this.log =
178
186
  typeof opts.log === "function"
package/src/store.ts CHANGED
@@ -24,6 +24,8 @@ export class SlackApiError extends Error {
24
24
  export interface StoreOptions {
25
25
  /** Append every change as one JSON line to this file and replay it on start. */
26
26
  dataFile?: string;
27
+ /** Changes to apply on construction, as if read from `dataFile`. Nothing is written. */
28
+ replay?: Change[];
27
29
  teamId?: string;
28
30
  teamName?: string;
29
31
  teamDomain?: string;
@@ -70,6 +72,30 @@ export interface Page<T> {
70
72
  next_cursor: string;
71
73
  }
72
74
 
75
+ /** One parsed journal line and its 1-based line number. */
76
+ export interface JournalEntry {
77
+ line: number;
78
+ change: Change;
79
+ }
80
+
81
+ /** Parse a JSONL journal. Corrupt lines are skipped with a warning; blank lines are ignored. */
82
+ export function parseJournal(text: string, source = "journal"): JournalEntry[] {
83
+ const entries: JournalEntry[] = [];
84
+ let line = 0;
85
+ for (const raw of text.split("\n")) {
86
+ line += 1;
87
+ if (!raw.trim()) continue;
88
+ try {
89
+ entries.push({ line, change: JSON.parse(raw) as Change });
90
+ } catch (e) {
91
+ console.warn(
92
+ `[slack-mock] skipping corrupt journal line ${line} in ${source}: ${e instanceof Error ? e.message : e}`,
93
+ );
94
+ }
95
+ }
96
+ return entries;
97
+ }
98
+
73
99
  /** In-memory Slack workspace with an optional append-only JSONL journal. */
74
100
  export class Store {
75
101
  readonly team: { id: string; name: string; domain: string };
@@ -112,7 +138,11 @@ export class Store {
112
138
  userToken: opts.userToken,
113
139
  };
114
140
  this.dataFile = opts.dataFile;
115
- if (this.dataFile && existsSync(this.dataFile)) this.replay(this.dataFile);
141
+ if (this.dataFile && existsSync(this.dataFile))
142
+ this.replay(
143
+ parseJournal(readFileSync(this.dataFile, "utf8"), this.dataFile).map((e) => e.change),
144
+ );
145
+ if (opts.replay) this.replay(opts.replay);
116
146
  if (!this.users.has(this.bot.userId)) {
117
147
  this.addUser({
118
148
  id: this.bot.userId,
@@ -145,21 +175,10 @@ export class Store {
145
175
  for (const l of this.listeners) l(change);
146
176
  }
147
177
 
148
- private replay(file: string): void {
178
+ private replay(changes: Change[]): void {
149
179
  this.replaying = true;
150
180
  try {
151
- let lineNo = 0;
152
- for (const line of readFileSync(file, "utf8").split("\n")) {
153
- lineNo += 1;
154
- if (!line.trim()) continue;
155
- try {
156
- this.applyReplayed(JSON.parse(line) as Change);
157
- } catch (e) {
158
- console.warn(
159
- `[slack-mock] skipping corrupt journal line ${lineNo} in ${file}: ${e instanceof Error ? e.message : e}`,
160
- );
161
- }
162
- }
181
+ for (const change of changes) this.applyReplayed(change);
163
182
  } finally {
164
183
  this.replaying = false;
165
184
  }
@@ -421,10 +440,15 @@ export class Store {
421
440
  ts: string,
422
441
  patch: Partial<SlackMessage>,
423
442
  editor: string,
443
+ opts: { markEdited?: boolean } = {},
424
444
  ): SlackMessage {
425
445
  const message = this.message(channelId, ts);
426
446
  const previous = structuredClone(message);
427
- Object.assign(message, patch, { edited: { user: editor, ts: nextTs() } });
447
+ Object.assign(
448
+ message,
449
+ patch,
450
+ opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } },
451
+ );
428
452
  this.emit({ kind: "message.update", message, previous });
429
453
  return message;
430
454
  }
package/src/web-api.ts CHANGED
@@ -242,11 +242,13 @@ export const handlers: Record<string, Handler> = {
242
242
  const existing = ctx.store.message(channel.id, ts);
243
243
  if (existing.streaming_state !== "in_progress")
244
244
  throw new SlackApiError("message_not_in_streaming_state");
245
+ // Streaming appends are not edits: Slack shows no "(edited)" marker for them.
245
246
  const message = ctx.store.updateMessage(
246
247
  channel.id,
247
248
  ts,
248
249
  { text: existing.text + streamText(args) },
249
250
  ctx.actor.userId,
251
+ { markEdited: false },
250
252
  );
251
253
  return { channel: channel.id, ts: message.ts };
252
254
  },
@@ -262,7 +264,9 @@ export const handlers: Record<string, Handler> = {
262
264
  text: existing.text + streamText(args),
263
265
  };
264
266
  if (Array.isArray(args.blocks)) patch.blocks = args.blocks as unknown[];
265
- const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId);
267
+ const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId, {
268
+ markEdited: false,
269
+ });
266
270
  return { channel: channel.id, ts, message: wireMessage(message) };
267
271
  },
268
272