@desplega.ai/slack-mock 0.1.2 → 0.3.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 CHANGED
@@ -72,6 +72,39 @@ What tests can do:
72
72
  The same operations exist over HTTP under `/mock/*` for use from another
73
73
  process (see `docs/design.md`).
74
74
 
75
+ ## Frames from a journal
76
+
77
+ A run recorded with `dataFile` can be replayed into one PNG per event that touched a
78
+ thread (or, without a thread, a channel): the view after each `message.add`,
79
+ `message.update`, `message.delete`, `reaction.add` and `reaction.remove` line, in journal
80
+ order, plus `final-thread.png` (a copy of the last frame) and `final-desktop.png` (the full
81
+ UI with the thread panel, 1280x900). Nothing is served: the journal is replayed in memory and
82
+ each page is screenshotted from a temp file by the same headless Chrome helper as
83
+ `screenshot`. A `file.add` line carries no message, so a shared file first appears in the
84
+ frame of the message that shares it.
85
+
86
+ ```bash
87
+ slack-mock frames --journal run.jsonl --channel C0GENERAL0 --thread 1788518410.672000 --out ./frames
88
+ # 5 message.add /abs/frames/01-message.add.png
89
+ # 6 reaction.add /abs/frames/02-reaction.add.png
90
+ # ...
91
+ # final-thread=/abs/frames/final-thread.png
92
+ # final-desktop=/abs/frames/final-desktop.png
93
+ ```
94
+
95
+ Leave out `--thread` for the channel view. `--manifest app.json` (bot display name),
96
+ `--width`, `--height` and `--no-desktop` are optional. The same from code:
97
+
98
+ ```ts
99
+ import { frames } from "@desplega.ai/slack-mock";
100
+
101
+ const result = await frames({ journal: "run.jsonl", channel: "general", thread: ask.ts, out: "./frames" });
102
+ // result.frames[1] = { index: 6, kind: "reaction.add", path: "/abs/frames/02-reaction.add.png" }
103
+ // result.finalThread, result.finalDesktop
104
+ ```
105
+
106
+ Stitch the PNGs into a GIF with ffmpeg if you want motion; the mock only produces frames.
107
+
75
108
  ## Slack behaviour that is modelled
76
109
 
77
110
  - Socket Mode: `apps.connections.open`, `hello`, envelopes for `events_api`,
package/dist/cli.js CHANGED
@@ -1,11 +1,12 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
3
  import {
4
- SlackMock
5
- } from "./index-hqq20tz9.js";
4
+ SlackMock2,
5
+ frames2
6
+ } from "./index-fhjq5qns.js";
6
7
  import {
7
- screenshot
8
- } from "./index-v7mbr1cx.js";
8
+ screenshot2
9
+ } from "./index-v2hesj4s.js";
9
10
 
10
11
  // src/cli.ts
11
12
  import { parseArgs } from "util";
@@ -15,6 +16,11 @@ Usage:
15
16
  slack-mock serve [--port 4040] [--host 127.0.0.1] [--data ./data/slack.jsonl] [--manifest app.json]
16
17
  [--no-seed] [--quiet] [--panel 50] [--auth user:pass] [--public-url https://mock.example.com]
17
18
  slack-mock screenshot <url> --out shot.png [--width 800] [--height 1000]
19
+ slack-mock frames --journal data.jsonl --channel C0GENERAL0 [--thread 1788516626.286000] --out ./frames
20
+ [--manifest app.json] [--width 800] [--height 700] [--no-desktop]
21
+
22
+ frames renders the thread (or, without --thread, the channel) as it looked after every journal
23
+ line that touched it: one PNG per line, then final-thread.png and final-desktop.png.
18
24
 
19
25
  serve prints the env vars to give your bot (SLACK_BOT_TOKEN, SLACK_APP_TOKEN, SLACK_API_URL)
20
26
  and the URLs of the HTML views. Inject messages with the admin API, e.g.
@@ -38,7 +44,7 @@ async function main(argv) {
38
44
  "public-url": { type: "string" }
39
45
  }
40
46
  });
41
- const mock = await SlackMock.start({
47
+ const mock = await SlackMock2.start({
42
48
  panelWidth: values.panel,
43
49
  adminAuth: values.auth,
44
50
  publicUrl: values["public-url"],
@@ -81,7 +87,7 @@ async function main(argv) {
81
87
  const url = positionals[0];
82
88
  if (!url)
83
89
  throw new Error("screenshot needs a URL");
84
- const out = await screenshot(url, {
90
+ const out = await screenshot2(url, {
85
91
  out: values.out,
86
92
  width: Number(values.width),
87
93
  height: Number(values.height)
@@ -89,6 +95,39 @@ async function main(argv) {
89
95
  console.log(out);
90
96
  return;
91
97
  }
98
+ if (command === "frames") {
99
+ const { values } = parseArgs({
100
+ args: rest,
101
+ options: {
102
+ journal: { type: "string" },
103
+ channel: { type: "string" },
104
+ thread: { type: "string" },
105
+ out: { type: "string" },
106
+ manifest: { type: "string" },
107
+ width: { type: "string", default: "800" },
108
+ height: { type: "string", default: "700" },
109
+ "no-desktop": { type: "boolean", default: false }
110
+ }
111
+ });
112
+ if (!values.journal || !values.channel || !values.out)
113
+ throw new Error("frames needs --journal, --channel and --out");
114
+ const result = await frames2({
115
+ journal: values.journal,
116
+ channel: values.channel,
117
+ thread: values.thread,
118
+ out: values.out,
119
+ manifest: values.manifest,
120
+ width: Number(values.width),
121
+ height: Number(values.height),
122
+ desktop: !values["no-desktop"]
123
+ });
124
+ for (const f of result.frames)
125
+ console.log(`${f.index} ${f.kind} ${f.path}`);
126
+ console.log(`final-thread=${result.finalThread}`);
127
+ if (result.finalDesktop)
128
+ console.log(`final-desktop=${result.finalDesktop}`);
129
+ return;
130
+ }
92
131
  console.log(USAGE);
93
132
  if (command && command !== "help" && command !== "--help")
94
133
  process.exit(1);
@@ -0,0 +1,41 @@
1
+ import { type SlackManifest } from "./server.ts";
2
+ import { type JournalEntry } from "./store.ts";
3
+ export interface FramesOptions {
4
+ /** Path to a JSONL journal written by `dataFile`. */
5
+ journal: string;
6
+ /** Channel id or name. */
7
+ channel: string;
8
+ /** Thread root ts. When absent, render the channel view instead of the thread view. */
9
+ thread?: string;
10
+ /** Output directory. Created when missing. */
11
+ out: string;
12
+ /** Slack app manifest path or object, same as `SlackMockOptions.manifest`. */
13
+ manifest?: string | SlackManifest;
14
+ /** Viewport width in px. Default 800. */
15
+ width?: number;
16
+ /** Viewport height in px. Default 700. */
17
+ height?: number;
18
+ /** Also render `final-desktop.png` (`?screenshot=0`, 1280x900). Default true. */
19
+ desktop?: boolean;
20
+ }
21
+ export interface Frame {
22
+ /** 1-based journal line number the frame was rendered after. */
23
+ index: number;
24
+ /** Journal `kind` of that line. */
25
+ kind: string;
26
+ /** Absolute PNG path. */
27
+ path: string;
28
+ }
29
+ export interface FramesResult {
30
+ frames: Frame[];
31
+ /** Copy of the last frame. */
32
+ finalThread: string;
33
+ /** Present when `desktop` is true. */
34
+ finalDesktop?: string;
35
+ }
36
+ /**
37
+ * Journal entries that change what the thread (or, without `thread`, the channel) shows.
38
+ * `file.add` carries no message, so a file only shows up with the message that shares it.
39
+ */
40
+ export declare function selectFrames(entries: JournalEntry[], channel: string, thread?: string): JournalEntry[];
41
+ export declare function frames(opts: FramesOptions): Promise<FramesResult>;
@@ -1,4 +1,9 @@
1
1
  // @bun
2
+ import {
3
+ requireChrome2,
4
+ screenshot2
5
+ } from "./index-v2hesj4s.js";
6
+
2
7
  // src/store.ts
3
8
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
4
9
  import { dirname } from "path";
@@ -26,7 +31,7 @@ function nowUnix() {
26
31
  }
27
32
 
28
33
  // src/store.ts
29
- class SlackApiError extends Error {
34
+ class SlackApiError2 extends Error {
30
35
  code;
31
36
  extra;
32
37
  constructor(code, extra = {}) {
@@ -35,8 +40,24 @@ class SlackApiError extends Error {
35
40
  this.extra = extra;
36
41
  }
37
42
  }
43
+ function parseJournal(text, source = "journal") {
44
+ const entries = [];
45
+ let line = 0;
46
+ for (const raw of text.split(`
47
+ `)) {
48
+ line += 1;
49
+ if (!raw.trim())
50
+ continue;
51
+ try {
52
+ entries.push({ line, change: JSON.parse(raw) });
53
+ } catch (e) {
54
+ console.warn(`[slack-mock] skipping corrupt journal line ${line} in ${source}: ${e instanceof Error ? e.message : e}`);
55
+ }
56
+ }
57
+ return entries;
58
+ }
38
59
 
39
- class Store {
60
+ class Store2 {
40
61
  team;
41
62
  app;
42
63
  bot;
@@ -67,7 +88,9 @@ class Store {
67
88
  };
68
89
  this.dataFile = opts.dataFile;
69
90
  if (this.dataFile && existsSync(this.dataFile))
70
- this.replay(this.dataFile);
91
+ this.replay(parseJournal(readFileSync(this.dataFile, "utf8"), this.dataFile).map((e) => e.change));
92
+ if (opts.replay)
93
+ this.replay(opts.replay);
71
94
  if (!this.users.has(this.bot.userId)) {
72
95
  this.addUser({
73
96
  id: this.bot.userId,
@@ -92,21 +115,11 @@ class Store {
92
115
  for (const l of this.listeners)
93
116
  l(change);
94
117
  }
95
- replay(file) {
118
+ replay(changes) {
96
119
  this.replaying = true;
97
120
  try {
98
- let lineNo = 0;
99
- for (const line of readFileSync(file, "utf8").split(`
100
- `)) {
101
- lineNo += 1;
102
- if (!line.trim())
103
- continue;
104
- try {
105
- this.applyReplayed(JSON.parse(line));
106
- } catch (e) {
107
- console.warn(`[slack-mock] skipping corrupt journal line ${lineNo} in ${file}: ${e instanceof Error ? e.message : e}`);
108
- }
109
- }
121
+ for (const change of changes)
122
+ this.applyReplayed(change);
110
123
  } finally {
111
124
  this.replaying = false;
112
125
  }
@@ -171,6 +184,7 @@ class Store {
171
184
  real_name_normalized: realName,
172
185
  display_name_normalized: input.name,
173
186
  email: input.email,
187
+ title: input.title,
174
188
  team: this.team.id
175
189
  }
176
190
  };
@@ -181,7 +195,7 @@ class Store {
181
195
  user(id) {
182
196
  const u = this.users.get(id);
183
197
  if (!u)
184
- throw new SlackApiError("user_not_found");
198
+ throw new SlackApiError2("user_not_found");
185
199
  return u;
186
200
  }
187
201
  userByEmail(email) {
@@ -197,7 +211,7 @@ class Store {
197
211
  const name = input.name.replace(/^#/, "");
198
212
  for (const c of this.channels.values()) {
199
213
  if (c.name === name && !c.is_im)
200
- throw new SlackApiError("name_taken");
214
+ throw new SlackApiError2("name_taken");
201
215
  }
202
216
  const id = input.id ?? slackId(input.is_private ? "G" : "C");
203
217
  const creator = input.creator ?? this.bot.userId;
@@ -254,7 +268,7 @@ class Store {
254
268
  channel(id) {
255
269
  const c = this.channels.get(id);
256
270
  if (!c)
257
- throw new SlackApiError("channel_not_found");
271
+ throw new SlackApiError2("channel_not_found");
258
272
  return c;
259
273
  }
260
274
  channelByName(name) {
@@ -276,7 +290,7 @@ class Store {
276
290
  join(channelId, userId, inviter) {
277
291
  const channel = this.channel(channelId);
278
292
  if (channel.is_archived)
279
- throw new SlackApiError("is_archived");
293
+ throw new SlackApiError2("is_archived");
280
294
  if (channel.members.includes(userId))
281
295
  return { alreadyMember: true };
282
296
  channel.members.push(userId);
@@ -286,9 +300,9 @@ class Store {
286
300
  archive(channelId) {
287
301
  const channel = this.channel(channelId);
288
302
  if (channel.is_archived)
289
- throw new SlackApiError("already_archived");
303
+ throw new SlackApiError2("already_archived");
290
304
  if (channel.is_general)
291
- throw new SlackApiError("cant_archive_general");
305
+ throw new SlackApiError2("cant_archive_general");
292
306
  channel.is_archived = true;
293
307
  this.emit({ kind: "channel.update", channel });
294
308
  }
@@ -323,28 +337,28 @@ class Store {
323
337
  updateEphemeral(channelId, ts, patch) {
324
338
  const m = this.ephemerals.find((x) => x.channel === channelId && x.ts === ts);
325
339
  if (!m)
326
- throw new SlackApiError("message_not_found");
340
+ throw new SlackApiError2("message_not_found");
327
341
  Object.assign(m, patch);
328
342
  return m;
329
343
  }
330
344
  deleteEphemeral(channelId, ts) {
331
345
  const i = this.ephemerals.findIndex((x) => x.channel === channelId && x.ts === ts);
332
346
  if (i < 0)
333
- throw new SlackApiError("message_not_found");
347
+ throw new SlackApiError2("message_not_found");
334
348
  this.ephemerals.splice(i, 1);
335
349
  }
336
350
  message(channelId, ts) {
337
351
  const m = this.findMessage(channelId, ts);
338
352
  if (!m)
339
- throw new SlackApiError("message_not_found");
353
+ throw new SlackApiError2("message_not_found");
340
354
  return m;
341
355
  }
342
356
  addMessage(input) {
343
357
  const channel = this.channel(input.channel);
344
358
  if (channel.is_archived)
345
- throw new SlackApiError("is_archived");
359
+ throw new SlackApiError2("is_archived");
346
360
  if (input.thread_ts && !this.findMessage(input.channel, input.thread_ts)) {
347
- throw new SlackApiError("thread_not_found");
361
+ throw new SlackApiError2("thread_not_found");
348
362
  }
349
363
  const message = {
350
364
  type: "message",
@@ -370,7 +384,7 @@ class Store {
370
384
  const list = this.messages.get(channelId);
371
385
  const i = list?.findIndex((m) => m.ts === ts) ?? -1;
372
386
  if (!list || i < 0)
373
- throw new SlackApiError("message_not_found");
387
+ throw new SlackApiError2("message_not_found");
374
388
  const [message] = list.splice(i, 1);
375
389
  if (message.thread_ts && message.thread_ts !== ts) {
376
390
  const parent = this.findMessage(channelId, message.thread_ts);
@@ -385,7 +399,7 @@ class Store {
385
399
  message.reactions ??= [];
386
400
  let reaction = message.reactions.find((r) => r.name === name);
387
401
  if (reaction?.users.includes(userId))
388
- throw new SlackApiError("already_reacted");
402
+ throw new SlackApiError2("already_reacted");
389
403
  if (!reaction) {
390
404
  reaction = { name, users: [], count: 0 };
391
405
  message.reactions.push(reaction);
@@ -399,7 +413,7 @@ class Store {
399
413
  const message = this.message(channelId, ts);
400
414
  const reaction = message.reactions?.find((r) => r.name === name);
401
415
  if (!reaction?.users.includes(userId))
402
- throw new SlackApiError("no_reaction");
416
+ throw new SlackApiError2("no_reaction");
403
417
  reaction.users = reaction.users.filter((u) => u !== userId);
404
418
  reaction.count = reaction.users.length;
405
419
  message.reactions = message.reactions.filter((r) => r.count > 0);
@@ -458,7 +472,7 @@ class Store {
458
472
  file(id) {
459
473
  const f = this.files.get(id);
460
474
  if (!f)
461
- throw new SlackApiError("file_not_found");
475
+ throw new SlackApiError2("file_not_found");
462
476
  return f;
463
477
  }
464
478
  openView(view) {
@@ -590,9 +604,9 @@ async function parseArgs(req) {
590
604
  return args;
591
605
  const contentType = req.headers.get("content-type") ?? "";
592
606
  if (contentType.includes("application/json")) {
593
- const text2 = await req.text();
594
- if (text2.trim())
595
- Object.assign(args, JSON.parse(text2));
607
+ const text = await req.text();
608
+ if (text.trim())
609
+ Object.assign(args, JSON.parse(text));
596
610
  return args;
597
611
  }
598
612
  if (contentType.includes("multipart/form-data")) {
@@ -1887,12 +1901,12 @@ function indexView(store, opts) {
1887
1901
  const count = store.messages.get(c.id)?.length ?? 0;
1888
1902
  return `<tr><td><a href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a></td><td><span class="sm-tag">${channelKind(c)}</span></td><td class="sm-muted">${c.id}</td><td>${count}</td></tr>`;
1889
1903
  }).join("");
1890
- const userRows = [...store.users.values()].map((u) => `<tr><td>${escapeHtml(u.name)}</td><td>${escapeHtml(u.real_name)}</td><td class="sm-muted">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted">${u.id}</td><td>${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`).join("");
1904
+ const userRows = [...store.users.values()].map((u) => `<tr><td>${escapeHtml(u.name)}</td><td>${escapeHtml(u.real_name)}</td><td class="sm-muted">${escapeHtml(u.profile.title ?? "")}</td><td class="sm-muted">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted">${u.id}</td><td>${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`).join("");
1891
1905
  const main = `<div class="sm-cards">${cards}</div>
1892
1906
  <div class="sm-h2">Channels</div>
1893
1907
  ${channels.length ? `<table class="sm-table"><tr><th>Name</th><th>Type</th><th>Id</th><th>Messages</th></tr>${channelRows}</table>` : `<div class="sm-empty">No channels yet</div>`}
1894
1908
  <div class="sm-h2">Users</div>
1895
- <table class="sm-table"><tr><th>Name</th><th>Real name</th><th>Email</th><th>Id</th><th></th></tr>${userRows}</table>`;
1909
+ <table class="sm-table"><tr><th>Name</th><th>Real name</th><th>Title</th><th>Email</th><th>Id</th><th></th></tr>${userRows}</table>`;
1896
1910
  return shell(store, opts, {
1897
1911
  title: `${store.team.name} \xB7 slack-mock`,
1898
1912
  header: topbar(escapeHtml(store.team.name), "slack-mock workspace"),
@@ -2308,7 +2322,7 @@ class SocketModeHub {
2308
2322
  function required(args, key) {
2309
2323
  const v = str(args, key);
2310
2324
  if (!v)
2311
- throw new SlackApiError("invalid_arguments", {
2325
+ throw new SlackApiError2("invalid_arguments", {
2312
2326
  response_metadata: { messages: [`[ERROR] missing required field: ${key}`] }
2313
2327
  });
2314
2328
  return v;
@@ -2317,7 +2331,7 @@ function resolveChannel(store, raw) {
2317
2331
  if (raw.startsWith("#")) {
2318
2332
  const c = store.channelByName(raw);
2319
2333
  if (!c)
2320
- throw new SlackApiError("channel_not_found");
2334
+ throw new SlackApiError2("channel_not_found");
2321
2335
  return c;
2322
2336
  }
2323
2337
  if (raw.startsWith("U") || raw.startsWith("W"))
@@ -2326,7 +2340,7 @@ function resolveChannel(store, raw) {
2326
2340
  }
2327
2341
  function requireMember(channel, actor) {
2328
2342
  if (!channel.members.includes(actor.userId))
2329
- throw new SlackApiError("not_in_channel");
2343
+ throw new SlackApiError2("not_in_channel");
2330
2344
  }
2331
2345
  function botFields(ctx) {
2332
2346
  if (!ctx.actor.isBot)
@@ -2348,9 +2362,9 @@ function messageContent(args) {
2348
2362
  const blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
2349
2363
  const attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
2350
2364
  if (!text && !blocks?.length && !attachments?.length)
2351
- throw new SlackApiError("no_text");
2365
+ throw new SlackApiError2("no_text");
2352
2366
  if (blocks && blocks.length > 50)
2353
- throw new SlackApiError("invalid_blocks", {
2367
+ throw new SlackApiError2("invalid_blocks", {
2354
2368
  response_metadata: { messages: ["[ERROR] must have at most 50 blocks"] }
2355
2369
  });
2356
2370
  const metadata = args.metadata && typeof args.metadata === "object" ? args.metadata : undefined;
@@ -2451,7 +2465,7 @@ var handlers = {
2451
2465
  const ts = required(args, "ts");
2452
2466
  const existing = ctx.store.message(channel.id, ts);
2453
2467
  if (existing.user !== ctx.actor.userId && !ctx.actor.isBot)
2454
- throw new SlackApiError("cant_update_message");
2468
+ throw new SlackApiError2("cant_update_message");
2455
2469
  const patch = {};
2456
2470
  if (args.text !== undefined)
2457
2471
  patch.text = str(args, "text") ?? "";
@@ -2462,7 +2476,7 @@ var handlers = {
2462
2476
  if (args.metadata !== undefined)
2463
2477
  patch.metadata = args.metadata;
2464
2478
  if (patch.text === "" && !patch.blocks?.length && !patch.attachments?.length && !existing.blocks?.length)
2465
- throw new SlackApiError("no_text");
2479
+ throw new SlackApiError2("no_text");
2466
2480
  const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId);
2467
2481
  return { channel: channel.id, ts, text: message.text, message: wireMessage(message) };
2468
2482
  },
@@ -2493,7 +2507,7 @@ var handlers = {
2493
2507
  const ts = required(args, "ts");
2494
2508
  const existing = ctx.store.message(channel.id, ts);
2495
2509
  if (existing.streaming_state !== "in_progress")
2496
- throw new SlackApiError("message_not_in_streaming_state");
2510
+ throw new SlackApiError2("message_not_in_streaming_state");
2497
2511
  const message = ctx.store.updateMessage(channel.id, ts, { text: existing.text + streamText(args) }, ctx.actor.userId, { markEdited: false });
2498
2512
  return { channel: channel.id, ts: message.ts };
2499
2513
  },
@@ -2502,7 +2516,7 @@ var handlers = {
2502
2516
  const ts = required(args, "ts");
2503
2517
  const existing = ctx.store.message(channel.id, ts);
2504
2518
  if (existing.streaming_state !== "in_progress")
2505
- throw new SlackApiError("message_not_in_streaming_state");
2519
+ throw new SlackApiError2("message_not_in_streaming_state");
2506
2520
  const patch = {
2507
2521
  streaming_state: "completed",
2508
2522
  text: existing.text + streamText(args)
@@ -2553,7 +2567,7 @@ var handlers = {
2553
2567
  "conversations.create": (ctx, args) => {
2554
2568
  const name = required(args, "name");
2555
2569
  if (!/^[a-z0-9_-]{1,80}$/.test(name))
2556
- throw new SlackApiError("invalid_name_specials");
2570
+ throw new SlackApiError2("invalid_name_specials");
2557
2571
  const channel = ctx.store.addChannel({
2558
2572
  name,
2559
2573
  is_private: bool(args, "is_private") ?? false,
@@ -2564,7 +2578,7 @@ var handlers = {
2564
2578
  "conversations.join": (ctx, args) => {
2565
2579
  const channel = ctx.store.channel(required(args, "channel"));
2566
2580
  if (channel.is_private)
2567
- throw new SlackApiError("method_not_supported_for_channel_type");
2581
+ throw new SlackApiError2("method_not_supported_for_channel_type");
2568
2582
  const { alreadyMember } = ctx.store.join(channel.id, ctx.actor.userId);
2569
2583
  return {
2570
2584
  channel: channelInfo(ctx.store, channel, ctx.actor),
@@ -2585,7 +2599,7 @@ var handlers = {
2585
2599
  errors.push({ user: u, ok: false, error: "already_in_channel" });
2586
2600
  }
2587
2601
  if (errors.length === users.length)
2588
- throw new SlackApiError(String(errors[0].error), { errors });
2602
+ throw new SlackApiError2(String(errors[0].error), { errors });
2589
2603
  return {
2590
2604
  channel: channelInfo(ctx.store, channel, ctx.actor),
2591
2605
  ...errors.length ? { errors } : {}
@@ -2602,7 +2616,7 @@ var handlers = {
2602
2616
  "conversations.open": (ctx, args) => {
2603
2617
  const users = (str(args, "users") ?? "").split(",").map((u) => u.trim()).filter(Boolean);
2604
2618
  if (users.length !== 1)
2605
- throw new SlackApiError("users_list_not_supplied");
2619
+ throw new SlackApiError2("users_list_not_supplied");
2606
2620
  const dm = ctx.store.openDm(users[0]);
2607
2621
  return { channel: { id: dm.id, is_im: true, user: dm.user, created: dm.created } };
2608
2622
  },
@@ -2628,7 +2642,7 @@ var handlers = {
2628
2642
  requireMember(channel, ctx.actor);
2629
2643
  const ts = required(args, "ts");
2630
2644
  if (!ctx.store.findMessage(channel.id, ts))
2631
- throw new SlackApiError("thread_not_found");
2645
+ throw new SlackApiError2("thread_not_found");
2632
2646
  const p = ctx.store.replies(channel.id, ts, {
2633
2647
  oldest: str(args, "oldest"),
2634
2648
  latest: str(args, "latest"),
@@ -2650,7 +2664,7 @@ var handlers = {
2650
2664
  "users.lookupByEmail": (ctx, args) => {
2651
2665
  const user = ctx.store.userByEmail(required(args, "email"));
2652
2666
  if (!user)
2653
- throw new SlackApiError("users_not_found");
2667
+ throw new SlackApiError2("users_not_found");
2654
2668
  return { user };
2655
2669
  },
2656
2670
  "users.conversations": (ctx, args) => {
@@ -2684,7 +2698,7 @@ var handlers = {
2684
2698
  const filename = required(args, "filename");
2685
2699
  const length = num(args, "length", -1);
2686
2700
  if (length < 0)
2687
- throw new SlackApiError("invalid_arguments", {
2701
+ throw new SlackApiError2("invalid_arguments", {
2688
2702
  response_metadata: { messages: ["[ERROR] missing required field: length"] }
2689
2703
  });
2690
2704
  const id = slackId("F");
@@ -2699,7 +2713,7 @@ var handlers = {
2699
2713
  "files.completeUploadExternal": (ctx, args) => {
2700
2714
  const list = Array.isArray(args.files) ? args.files : [];
2701
2715
  if (list.length === 0)
2702
- throw new SlackApiError("invalid_arguments", {
2716
+ throw new SlackApiError2("invalid_arguments", {
2703
2717
  response_metadata: { messages: ["[ERROR] missing required field: files"] }
2704
2718
  });
2705
2719
  const files = list.map(({ id, title }) => {
@@ -2737,13 +2751,13 @@ var handlers = {
2737
2751
  const triggerId = required(args, "trigger_id");
2738
2752
  const expires = ctx.triggerIds.get(triggerId);
2739
2753
  if (expires === undefined)
2740
- throw new SlackApiError("invalid_trigger_id");
2754
+ throw new SlackApiError2("invalid_trigger_id");
2741
2755
  ctx.triggerIds.delete(triggerId);
2742
2756
  if (Date.now() > expires)
2743
- throw new SlackApiError("expired_trigger_id");
2757
+ throw new SlackApiError2("expired_trigger_id");
2744
2758
  const view = viewArg(args);
2745
2759
  if (view.type !== "modal")
2746
- throw new SlackApiError("invalid_arguments", {
2760
+ throw new SlackApiError2("invalid_arguments", {
2747
2761
  response_metadata: { messages: ["[ERROR] view type must be modal"] }
2748
2762
  });
2749
2763
  const stored = ctx.store.openView({
@@ -2767,7 +2781,7 @@ var handlers = {
2767
2781
  const id = required(args, "view_id");
2768
2782
  const existing = ctx.store.views.get(id);
2769
2783
  if (!existing)
2770
- throw new SlackApiError("not_found");
2784
+ throw new SlackApiError2("not_found");
2771
2785
  const view = viewArg(args);
2772
2786
  Object.assign(existing, {
2773
2787
  callback_id: str(view, "callback_id") ?? existing.callback_id,
@@ -2848,14 +2862,14 @@ function viewArg(args) {
2848
2862
  try {
2849
2863
  return JSON.parse(v);
2850
2864
  } catch {
2851
- throw new SlackApiError("invalid_arguments", {
2865
+ throw new SlackApiError2("invalid_arguments", {
2852
2866
  response_metadata: { messages: ["[ERROR] view must be valid JSON"] }
2853
2867
  });
2854
2868
  }
2855
2869
  }
2856
2870
  if (v && typeof v === "object")
2857
2871
  return v;
2858
- throw new SlackApiError("invalid_arguments", {
2872
+ throw new SlackApiError2("invalid_arguments", {
2859
2873
  response_metadata: { messages: ["[ERROR] missing required field: view"] }
2860
2874
  });
2861
2875
  }
@@ -2876,6 +2890,12 @@ function newTriggerId() {
2876
2890
  }
2877
2891
 
2878
2892
  // src/server.ts
2893
+ function loadManifest(manifest) {
2894
+ return typeof manifest === "string" ? JSON.parse(readFileSync2(manifest, "utf8")) : manifest;
2895
+ }
2896
+ function manifestAppName(manifest) {
2897
+ return manifest?.features?.bot_user?.display_name ?? manifest?.display_information?.name;
2898
+ }
2879
2899
  var DEFAULT_EVENTS = [
2880
2900
  "message.channels",
2881
2901
  "message.groups",
@@ -2889,7 +2909,7 @@ var DEFAULT_EVENTS = [
2889
2909
  "member_joined_channel"
2890
2910
  ];
2891
2911
 
2892
- class SlackMock {
2912
+ class SlackMock2 {
2893
2913
  store;
2894
2914
  hub;
2895
2915
  opts;
@@ -2903,15 +2923,15 @@ class SlackMock {
2903
2923
  faults = [];
2904
2924
  lastRequestAt = 0;
2905
2925
  log;
2906
- static Error = SlackApiError;
2926
+ static Error = SlackApiError2;
2907
2927
  constructor(opts = {}) {
2908
- const manifest = typeof opts.manifest === "string" ? JSON.parse(readFileSync2(opts.manifest, "utf8")) : opts.manifest;
2909
- const appName = opts.appName ?? manifest?.features?.bot_user?.display_name ?? manifest?.display_information?.name;
2928
+ const manifest = loadManifest(opts.manifest);
2929
+ const appName = opts.appName ?? manifestAppName(manifest);
2910
2930
  this.opts = { ...opts, appName };
2911
2931
  this.log = typeof opts.log === "function" ? opts.log : opts.log ? (m) => console.log(`[slack-mock] ${m}`) : () => {};
2912
2932
  if (opts.dataFile)
2913
2933
  ensureDir(opts.dataFile);
2914
- this.store = new Store({ ...opts, appName });
2934
+ this.store = new Store2({ ...opts, appName });
2915
2935
  this.hub = new SocketModeHub({
2916
2936
  appId: this.store.app.id,
2917
2937
  pingIntervalMs: opts.pingIntervalMs,
@@ -2927,7 +2947,7 @@ class SlackMock {
2927
2947
  this.store.onChange((change) => this.dispatch(change));
2928
2948
  }
2929
2949
  static async start(opts = {}) {
2930
- const mock = new SlackMock(opts);
2950
+ const mock = new SlackMock2(opts);
2931
2951
  mock.listen();
2932
2952
  return mock;
2933
2953
  }
@@ -3150,7 +3170,7 @@ class SlackMock {
3150
3170
  record(true);
3151
3171
  return Response.json({ ok: true, ...body });
3152
3172
  } catch (e) {
3153
- if (e instanceof SlackApiError) {
3173
+ if (e instanceof SlackApiError2) {
3154
3174
  record(false, e.code);
3155
3175
  this.log(`${method} -> ${e.code}`);
3156
3176
  return slackError(e.code, e.extra);
@@ -3232,7 +3252,7 @@ class SlackMock {
3232
3252
  return new Response("ok");
3233
3253
  }
3234
3254
  } catch (e) {
3235
- if (e instanceof SlackApiError)
3255
+ if (e instanceof SlackApiError2)
3236
3256
  return Response.json({ ok: false, error: e.code });
3237
3257
  throw e;
3238
3258
  }
@@ -3452,7 +3472,7 @@ data: ${JSON.stringify(data)}
3452
3472
  for (const u of this.store.users.values())
3453
3473
  if (u.name === idOrName)
3454
3474
  return u;
3455
- throw new SlackApiError("user_not_found");
3475
+ throw new SlackApiError2("user_not_found");
3456
3476
  }
3457
3477
  channel(idOrName) {
3458
3478
  return this.resolveChannel(idOrName);
@@ -3573,7 +3593,7 @@ data: ${JSON.stringify(data)}
3573
3593
  const channel = this.resolveChannel(input.channel);
3574
3594
  const message = this.store.findMessage(channel.id, input.ts) ?? this.store.ephemerals.find((m) => m.channel === channel.id && m.ts === input.ts);
3575
3595
  if (!message)
3576
- throw new SlackApiError("message_not_found");
3596
+ throw new SlackApiError2("message_not_found");
3577
3597
  const found = findButton(message.blocks, input.action_id);
3578
3598
  if (!found && !input.value && !input.block_id)
3579
3599
  throw new Error(`no button with action_id ${input.action_id} on message ${input.ts}`);
@@ -3770,7 +3790,7 @@ data: ${JSON.stringify(data)}
3770
3790
  return this.store.onChange(listener);
3771
3791
  }
3772
3792
  async handleAdmin(req, path, url) {
3773
- const json = (body2, status = 200) => Response.json(body2, { status });
3793
+ const json = (body, status = 200) => Response.json(body, { status });
3774
3794
  const body = req.method === "POST" ? await req.json().catch(() => ({})) : {};
3775
3795
  try {
3776
3796
  if (path === "presenter")
@@ -3822,7 +3842,7 @@ data: ${JSON.stringify(data)}
3822
3842
  return json((m[2] ? this.thread(m[1], m[2]) : this.messages(m[1])).map(wireMessage));
3823
3843
  return json({ ok: false, error: "unknown_admin_route" }, 404);
3824
3844
  } catch (e) {
3825
- return json({ ok: false, error: e instanceof SlackApiError ? e.code : String(e) }, 400);
3845
+ return json({ ok: false, error: e instanceof SlackApiError2 ? e.code : String(e) }, 400);
3826
3846
  }
3827
3847
  }
3828
3848
  }
@@ -3874,4 +3894,69 @@ function denied(req, path) {
3874
3894
  });
3875
3895
  }
3876
3896
 
3877
- export { SlackApiError, Store, SlackMock };
3897
+ // src/frames.ts
3898
+ import { copyFileSync, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync } from "fs";
3899
+ import { tmpdir } from "os";
3900
+ import { join, resolve } from "path";
3901
+ var FRAME_KINDS = new Set([
3902
+ "message.add",
3903
+ "message.update",
3904
+ "message.delete",
3905
+ "reaction.add",
3906
+ "reaction.remove",
3907
+ "file.add"
3908
+ ]);
3909
+ function selectFrames(entries, channel, thread) {
3910
+ return entries.filter(({ change }) => {
3911
+ if (!FRAME_KINDS.has(change.kind) || !("message" in change))
3912
+ return false;
3913
+ const m = change.message;
3914
+ if (m.channel !== channel)
3915
+ return false;
3916
+ return thread ? m.ts === thread || m.thread_ts === thread : true;
3917
+ });
3918
+ }
3919
+ async function frames2(opts) {
3920
+ const entries = parseJournal(readFileSync3(opts.journal, "utf8"), opts.journal);
3921
+ const appName = manifestAppName(loadManifest(opts.manifest));
3922
+ const storeAfter = (line) => new Store2({ replay: entries.filter((e) => e.line <= line).map((e) => e.change), appName });
3923
+ const full = storeAfter(Number.POSITIVE_INFINITY);
3924
+ const channel = full.channels.get(opts.channel) ?? full.channelByName(opts.channel);
3925
+ if (!channel)
3926
+ throw new Error(`channel ${opts.channel} not found in ${opts.journal}`);
3927
+ const what = opts.thread ? `thread ${opts.thread} in ${channel.id}` : `channel ${channel.id}`;
3928
+ const selected = selectFrames(entries, channel.id, opts.thread);
3929
+ if (!selected.length)
3930
+ throw new Error(`no line of ${opts.journal} touches ${what}`);
3931
+ requireChrome2();
3932
+ const view = opts.thread ? { kind: "thread", channel: channel.id, ts: opts.thread } : { kind: "channel", channel: channel.id };
3933
+ const out = resolve(opts.out);
3934
+ mkdirSync2(out, { recursive: true });
3935
+ const tmp = mkdtempSync(join(tmpdir(), "slack-mock-frames-"));
3936
+ const html = join(tmp, "frame.html");
3937
+ const shoot = async (store, file, render, size) => {
3938
+ writeFileSync(html, renderPage(store, view, render));
3939
+ await screenshot2(Bun.pathToFileURL(html).href, { out: file, ...size });
3940
+ };
3941
+ try {
3942
+ const frames = [];
3943
+ const size = { width: opts.width ?? 800, height: opts.height ?? 700 };
3944
+ for (const [i, { line, change }] of selected.entries()) {
3945
+ const path = join(out, `${String(i + 1).padStart(2, "0")}-${change.kind}.png`);
3946
+ await shoot(storeAfter(line), path, { screenshot: true }, size);
3947
+ frames.push({ index: line, kind: change.kind, path });
3948
+ }
3949
+ const finalThread = join(out, "final-thread.png");
3950
+ copyFileSync(frames[frames.length - 1].path, finalThread);
3951
+ let finalDesktop;
3952
+ if (opts.desktop !== false) {
3953
+ finalDesktop = join(out, "final-desktop.png");
3954
+ await shoot(full, finalDesktop, { screenshot: false, live: false }, { width: 1280, height: 900 });
3955
+ }
3956
+ return { frames, finalThread, finalDesktop };
3957
+ } finally {
3958
+ rmSync(tmp, { recursive: true, force: true });
3959
+ }
3960
+ }
3961
+
3962
+ export { SlackApiError2, Store2, SlackMock2, frames2 };
@@ -10,17 +10,21 @@ var CHROME_CANDIDATES = [
10
10
  "/usr/bin/chromium",
11
11
  "/usr/bin/chromium-browser"
12
12
  ];
13
- function findChrome() {
13
+ function findChrome2() {
14
14
  for (const c of CHROME_CANDIDATES)
15
15
  if (c && existsSync(c))
16
16
  return c;
17
17
  const fromPath = Bun.which("google-chrome") ?? Bun.which("chromium") ?? Bun.which("chrome");
18
18
  return fromPath ?? undefined;
19
19
  }
20
- async function screenshot(url, opts) {
21
- const chrome = findChrome();
20
+ function requireChrome2() {
21
+ const chrome = findChrome2();
22
22
  if (!chrome)
23
23
  throw new Error("no Chrome/Chromium binary found; set SLACK_MOCK_CHROME=/path/to/chrome");
24
+ return chrome;
25
+ }
26
+ async function screenshot2(url, opts) {
27
+ const chrome = requireChrome2();
24
28
  const target = new URL(url);
25
29
  if (!target.searchParams.has("screenshot"))
26
30
  target.searchParams.set("screenshot", "1");
@@ -45,4 +49,4 @@ async function screenshot(url, opts) {
45
49
  return opts.out;
46
50
  }
47
51
 
48
- export { findChrome, screenshot };
52
+ export { findChrome2, requireChrome2, screenshot2 };
package/dist/index.d.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 { Fault, MessageQuery, PostMessageInput, SlackManifest, SlackMockOptions, } from "./server.ts";
3
5
  export { SlackApiError, SlackMock } from "./server.ts";
package/dist/index.js CHANGED
@@ -1,17 +1,19 @@
1
1
  // @bun
2
2
  import {
3
- SlackApiError,
4
- SlackMock,
5
- Store
6
- } from "./index-hqq20tz9.js";
3
+ SlackApiError2,
4
+ Store2,
5
+ SlackMock2,
6
+ frames2
7
+ } from "./index-fhjq5qns.js";
7
8
  import {
8
- findChrome,
9
- screenshot
10
- } from "./index-v7mbr1cx.js";
9
+ findChrome2,
10
+ screenshot2
11
+ } from "./index-v2hesj4s.js";
11
12
  export {
12
- SlackApiError,
13
- SlackMock,
14
- Store,
15
- findChrome,
16
- screenshot
13
+ SlackApiError2 as SlackApiError,
14
+ SlackMock2 as SlackMock,
15
+ Store2 as Store,
16
+ findChrome2 as findChrome,
17
+ frames2 as frames,
18
+ screenshot2 as screenshot
17
19
  };
@@ -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;
@@ -23,6 +25,7 @@ export interface AddUserInput {
23
25
  name: string;
24
26
  real_name?: string;
25
27
  email?: string;
28
+ title?: string;
26
29
  is_admin?: boolean;
27
30
  is_bot?: boolean;
28
31
  tz?: string;
@@ -48,6 +51,13 @@ export interface Page<T> {
48
51
  has_more: boolean;
49
52
  next_cursor: string;
50
53
  }
54
+ /** One parsed journal line and its 1-based line number. */
55
+ export interface JournalEntry {
56
+ line: number;
57
+ change: Change;
58
+ }
59
+ /** Parse a JSONL journal. Corrupt lines are skipped with a warning; blank lines are ignored. */
60
+ export declare function parseJournal(text: string, source?: string): JournalEntry[];
51
61
  /** In-memory Slack workspace with an optional append-only JSONL journal. */
52
62
  export declare class Store {
53
63
  readonly team: {
package/dist/types.d.ts CHANGED
@@ -16,6 +16,7 @@ export interface SlackUser {
16
16
  email?: string;
17
17
  image_72?: string;
18
18
  team: string;
19
+ title?: string;
19
20
  };
20
21
  }
21
22
  export interface SlackChannel {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@desplega.ai/slack-mock",
3
- "version": "0.1.2",
3
+ "version": "0.3.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,
@@ -611,7 +611,7 @@ function indexView(store: Store, opts: RenderOptions): string {
611
611
  const userRows = [...store.users.values()]
612
612
  .map(
613
613
  (u) =>
614
- `<tr><td>${escapeHtml(u.name)}</td><td>${escapeHtml(u.real_name)}</td><td class="sm-muted">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted">${u.id}</td><td>${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`,
614
+ `<tr><td>${escapeHtml(u.name)}</td><td>${escapeHtml(u.real_name)}</td><td class="sm-muted">${escapeHtml(u.profile.title ?? "")}</td><td class="sm-muted">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted">${u.id}</td><td>${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`,
615
615
  )
616
616
  .join("");
617
617
 
@@ -623,7 +623,7 @@ ${
623
623
  : `<div class="sm-empty">No channels yet</div>`
624
624
  }
625
625
  <div class="sm-h2">Users</div>
626
- <table class="sm-table"><tr><th>Name</th><th>Real name</th><th>Email</th><th>Id</th><th></th></tr>${userRows}</table>`;
626
+ <table class="sm-table"><tr><th>Name</th><th>Real name</th><th>Title</th><th>Email</th><th>Id</th><th></th></tr>${userRows}</table>`;
627
627
 
628
628
  return shell(store, opts, {
629
629
  title: `${store.team.name} · slack-mock`,
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;
@@ -41,6 +43,7 @@ export interface AddUserInput {
41
43
  name: string;
42
44
  real_name?: string;
43
45
  email?: string;
46
+ title?: string;
44
47
  is_admin?: boolean;
45
48
  is_bot?: boolean;
46
49
  tz?: string;
@@ -70,6 +73,30 @@ export interface Page<T> {
70
73
  next_cursor: string;
71
74
  }
72
75
 
76
+ /** One parsed journal line and its 1-based line number. */
77
+ export interface JournalEntry {
78
+ line: number;
79
+ change: Change;
80
+ }
81
+
82
+ /** Parse a JSONL journal. Corrupt lines are skipped with a warning; blank lines are ignored. */
83
+ export function parseJournal(text: string, source = "journal"): JournalEntry[] {
84
+ const entries: JournalEntry[] = [];
85
+ let line = 0;
86
+ for (const raw of text.split("\n")) {
87
+ line += 1;
88
+ if (!raw.trim()) continue;
89
+ try {
90
+ entries.push({ line, change: JSON.parse(raw) as Change });
91
+ } catch (e) {
92
+ console.warn(
93
+ `[slack-mock] skipping corrupt journal line ${line} in ${source}: ${e instanceof Error ? e.message : e}`,
94
+ );
95
+ }
96
+ }
97
+ return entries;
98
+ }
99
+
73
100
  /** In-memory Slack workspace with an optional append-only JSONL journal. */
74
101
  export class Store {
75
102
  readonly team: { id: string; name: string; domain: string };
@@ -112,7 +139,11 @@ export class Store {
112
139
  userToken: opts.userToken,
113
140
  };
114
141
  this.dataFile = opts.dataFile;
115
- if (this.dataFile && existsSync(this.dataFile)) this.replay(this.dataFile);
142
+ if (this.dataFile && existsSync(this.dataFile))
143
+ this.replay(
144
+ parseJournal(readFileSync(this.dataFile, "utf8"), this.dataFile).map((e) => e.change),
145
+ );
146
+ if (opts.replay) this.replay(opts.replay);
116
147
  if (!this.users.has(this.bot.userId)) {
117
148
  this.addUser({
118
149
  id: this.bot.userId,
@@ -145,21 +176,10 @@ export class Store {
145
176
  for (const l of this.listeners) l(change);
146
177
  }
147
178
 
148
- private replay(file: string): void {
179
+ private replay(changes: Change[]): void {
149
180
  this.replaying = true;
150
181
  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
- }
182
+ for (const change of changes) this.applyReplayed(change);
163
183
  } finally {
164
184
  this.replaying = false;
165
185
  }
@@ -225,6 +245,7 @@ export class Store {
225
245
  real_name_normalized: realName,
226
246
  display_name_normalized: input.name,
227
247
  email: input.email,
248
+ title: input.title,
228
249
  team: this.team.id,
229
250
  },
230
251
  };
package/src/types.ts CHANGED
@@ -19,6 +19,7 @@ export interface SlackUser {
19
19
  email?: string;
20
20
  image_72?: string;
21
21
  team: string;
22
+ title?: string;
22
23
  };
23
24
  }
24
25