@desplega.ai/slack-mock 0.2.0 → 0.4.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/src/screenshot.ts CHANGED
@@ -32,6 +32,118 @@ export interface ScreenshotOptions {
32
32
  timeoutMs?: number;
33
33
  }
34
34
 
35
+ /** Set the viewport before navigation because Chrome clamps narrow CLI windows to 500px. */
36
+ async function screenshotWithCdp(
37
+ chrome: string,
38
+ target: URL,
39
+ opts: ScreenshotOptions,
40
+ width: number,
41
+ height: number,
42
+ ): Promise<string> {
43
+ const proc = Bun.spawn(
44
+ [
45
+ chrome,
46
+ "--headless=new",
47
+ "--disable-gpu",
48
+ "--hide-scrollbars",
49
+ "--no-first-run",
50
+ "--no-default-browser-check",
51
+ "--remote-debugging-port=0",
52
+ "about:blank",
53
+ ],
54
+ { stdout: "ignore", stderr: "pipe" },
55
+ );
56
+ const timer = setTimeout(() => proc.kill(), opts.timeoutMs ?? 30_000);
57
+ let socket: WebSocket | undefined;
58
+ const reader = proc.stderr.getReader();
59
+ try {
60
+ const decoder = new TextDecoder();
61
+ let stderr = "";
62
+ let endpoint: RegExpExecArray | null = null;
63
+ while (!endpoint) {
64
+ const { value, done } = await reader.read();
65
+ if (done) throw new Error("Chrome closed before opening DevTools");
66
+ stderr += decoder.decode(value, { stream: true });
67
+ endpoint = /DevTools listening on (ws:\/\/[^\s]+)/.exec(stderr);
68
+ }
69
+ socket = new WebSocket(endpoint[1]!);
70
+ await new Promise<void>((resolve, reject) => {
71
+ socket!.addEventListener("open", () => resolve(), { once: true });
72
+ socket!.addEventListener(
73
+ "error",
74
+ () => reject(new Error("Cannot connect to Chrome DevTools")),
75
+ { once: true },
76
+ );
77
+ socket!.addEventListener("close", () => reject(new Error("Chrome DevTools closed")), {
78
+ once: true,
79
+ });
80
+ });
81
+ let nextId = 0;
82
+ let sessionId: string | undefined;
83
+ const pending = new Map<
84
+ number,
85
+ {
86
+ resolve: (value: Record<string, unknown>) => void;
87
+ reject: (error: Error) => void;
88
+ }
89
+ >();
90
+ let pageLoaded = () => {};
91
+ let loadFailed = (_error: Error) => {};
92
+ socket.onmessage = (event) => {
93
+ const message = JSON.parse(String(event.data));
94
+ if (message.method === "Page.loadEventFired" && message.sessionId === sessionId) pageLoaded();
95
+ const request = pending.get(message.id);
96
+ if (!request) return;
97
+ pending.delete(message.id);
98
+ if (message.error) request.reject(new Error(message.error.message));
99
+ else request.resolve(message.result ?? {});
100
+ };
101
+ socket.onclose = socket.onerror = () => {
102
+ const error = new Error("Chrome DevTools closed before capture completed");
103
+ for (const request of pending.values()) request.reject(error);
104
+ pending.clear();
105
+ loadFailed(error);
106
+ };
107
+ const command = (method: string, params: Record<string, unknown> = {}) => {
108
+ const id = ++nextId;
109
+ return new Promise<Record<string, unknown>>((resolve, reject) => {
110
+ pending.set(id, { resolve, reject });
111
+ socket!.send(JSON.stringify({ id, method, params, sessionId }));
112
+ });
113
+ };
114
+ const { targetId } = await command("Target.createTarget", { url: "about:blank" });
115
+ const attached = await command("Target.attachToTarget", { targetId, flatten: true });
116
+ if (typeof attached.sessionId !== "string") throw new Error("Chrome returned no page session");
117
+ sessionId = attached.sessionId;
118
+ await command("Page.enable");
119
+ await command("Emulation.setDeviceMetricsOverride", {
120
+ width,
121
+ height,
122
+ deviceScaleFactor: 1,
123
+ mobile: false,
124
+ });
125
+ const loaded = new Promise<void>((resolve, reject) => {
126
+ pageLoaded = resolve;
127
+ loadFailed = reject;
128
+ });
129
+ await Promise.all([command("Page.navigate", { url: target.toString() }), loaded]);
130
+ await command("Runtime.evaluate", { expression: "document.fonts.ready", awaitPromise: true });
131
+ const { data } = await command("Page.captureScreenshot", {
132
+ format: "png",
133
+ captureBeyondViewport: false,
134
+ });
135
+ if (typeof data !== "string") throw new Error("Chrome returned no screenshot data");
136
+ await Bun.write(opts.out, Buffer.from(data, "base64"));
137
+ return opts.out;
138
+ } finally {
139
+ socket?.close();
140
+ clearTimeout(timer);
141
+ reader.releaseLock();
142
+ if (proc.exitCode === null) proc.kill();
143
+ await proc.exited;
144
+ }
145
+ }
146
+
35
147
  /**
36
148
  * Render a URL to a PNG with headless Chrome. Appends `screenshot=1` so the
37
149
  * mock's pages drop their navigation chrome.
@@ -40,6 +152,9 @@ export async function screenshot(url: string, opts: ScreenshotOptions): Promise<
40
152
  const chrome = requireChrome();
41
153
  const target = new URL(url);
42
154
  if (!target.searchParams.has("screenshot")) target.searchParams.set("screenshot", "1");
155
+ const width = opts.width ?? 800;
156
+ const height = opts.height ?? 1000;
157
+ if (width < 500) return screenshotWithCdp(chrome, target, opts, width, height);
43
158
  const proc = Bun.spawn(
44
159
  [
45
160
  chrome,
@@ -48,7 +163,7 @@ export async function screenshot(url: string, opts: ScreenshotOptions): Promise<
48
163
  "--hide-scrollbars",
49
164
  "--no-first-run",
50
165
  "--no-default-browser-check",
51
- `--window-size=${opts.width ?? 800},${opts.height ?? 1000}`,
166
+ `--window-size=${width},${height}`,
52
167
  `--screenshot=${opts.out}`,
53
168
  target.toString(),
54
169
  ],
package/src/server.ts CHANGED
@@ -95,9 +95,10 @@ export interface SlackMockOptions extends StoreOptions {
95
95
  */
96
96
  publicUi?: boolean;
97
97
  /**
98
- * "user:password" that may only post messages (`POST /mock/messages`) and check its role
99
- * (`GET /mock/presenter`). With `publicUi` the HTML composer shows a sign-in for it, so a presenter
100
- * can drive a public-read workspace without the admin credential. `adminAuth` always implies it.
98
+ * "user:password" that may post messages (`POST /mock/messages`), mutate reactions
99
+ * (`POST /mock/reactions`), and check its role (`GET /mock/presenter`). With `publicUi` the HTML
100
+ * composer shows a sign-in for it, so a presenter can drive a public-read workspace without the
101
+ * admin credential. `adminAuth` always implies it.
101
102
  */
102
103
  presenterAuth?: string;
103
104
  log?: boolean | ((msg: string) => void);
@@ -291,7 +292,7 @@ export class SlackMock {
291
292
  return basicAuthMatches(req, expected);
292
293
  }
293
294
 
294
- /** `presenterAuth` (or `adminAuth`) may post messages and read its role, nothing else. */
295
+ /** `presenterAuth` (or `adminAuth`) may post messages, mutate reactions, and read its role. */
295
296
  private authorizedPresenter(req: Request): boolean {
296
297
  if (this.authorizedAdmin(req)) return true;
297
298
  const expected = this.opts.presenterAuth;
@@ -347,7 +348,8 @@ export class SlackMock {
347
348
  const isUiSurface = path === "/" || path === "" || path.startsWith("/c/");
348
349
  const isAdminSurface = path.startsWith("/mock/") || (isUiSurface && !this.opts.publicUi);
349
350
  const isPresenterRoute =
350
- (path === "/mock/messages" && req.method === "POST") || path === "/mock/presenter";
351
+ ((path === "/mock/messages" || path === "/mock/reactions") && req.method === "POST") ||
352
+ path === "/mock/presenter";
351
353
  const allowed = isPresenterRoute ? this.authorizedPresenter(req) : this.authorizedAdmin(req);
352
354
  if (isAdminSurface && !allowed) return denied(req, path);
353
355
  if (path.startsWith("/link/") || path === "/link") {
@@ -912,6 +914,17 @@ export class SlackMock {
912
914
  await this.flush();
913
915
  }
914
916
 
917
+ async removeReaction(input: {
918
+ channel: string;
919
+ ts: string;
920
+ name: string;
921
+ user?: string;
922
+ }): Promise<void> {
923
+ const user = input.user ? this.user(input.user) : this.defaultHuman();
924
+ this.store.removeReaction(this.resolveChannel(input.channel).id, input.ts, input.name, user.id);
925
+ await this.flush();
926
+ }
927
+
915
928
  private issueResponseUrl(target: Omit<ResponseUrl, "expires">): string {
916
929
  const id = `${this.store.team.id}/${slackId("", 10)}/${slackId("", 24).toLowerCase()}`;
917
930
  this.responseUrls.set(id, { ...target, expires: Date.now() + 30 * 60_000 });
@@ -1305,7 +1318,17 @@ export class SlackMock {
1305
1318
  if (path === "assistant/start" && req.method === "POST")
1306
1319
  return json(await this.startAssistantThread(body));
1307
1320
  if (path === "reactions" && req.method === "POST") {
1308
- await this.addReaction(body as { channel: string; ts: string; name: string });
1321
+ const input = body as {
1322
+ channel: string;
1323
+ ts: string;
1324
+ name: string;
1325
+ user?: string;
1326
+ action?: string;
1327
+ };
1328
+ if (input.action !== undefined && input.action !== "add" && input.action !== "remove")
1329
+ throw new SlackApiError("invalid_arguments");
1330
+ if (input.action === "remove") await this.removeReaction(input);
1331
+ else await this.addReaction(input);
1309
1332
  return json({ ok: true });
1310
1333
  }
1311
1334
  if (path === "api-calls")
package/src/store.ts CHANGED
@@ -43,6 +43,8 @@ export interface AddUserInput {
43
43
  name: string;
44
44
  real_name?: string;
45
45
  email?: string;
46
+ title?: string;
47
+ status?: string;
46
48
  is_admin?: boolean;
47
49
  is_bot?: boolean;
48
50
  tz?: string;
@@ -244,6 +246,8 @@ export class Store {
244
246
  real_name_normalized: realName,
245
247
  display_name_normalized: input.name,
246
248
  email: input.email,
249
+ title: input.title,
250
+ status_text: input.status,
247
251
  team: this.team.id,
248
252
  },
249
253
  };
package/src/types.ts CHANGED
@@ -19,6 +19,8 @@ export interface SlackUser {
19
19
  email?: string;
20
20
  image_72?: string;
21
21
  team: string;
22
+ title?: string;
23
+ status_text?: string;
22
24
  };
23
25
  }
24
26
 
@@ -1,52 +0,0 @@
1
- // @bun
2
- // src/screenshot.ts
3
- import { existsSync } from "fs";
4
- var CHROME_CANDIDATES = [
5
- process.env.SLACK_MOCK_CHROME,
6
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
7
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
8
- "/usr/bin/google-chrome",
9
- "/usr/bin/google-chrome-stable",
10
- "/usr/bin/chromium",
11
- "/usr/bin/chromium-browser"
12
- ];
13
- function findChrome2() {
14
- for (const c of CHROME_CANDIDATES)
15
- if (c && existsSync(c))
16
- return c;
17
- const fromPath = Bun.which("google-chrome") ?? Bun.which("chromium") ?? Bun.which("chrome");
18
- return fromPath ?? undefined;
19
- }
20
- function requireChrome2() {
21
- const chrome = findChrome2();
22
- if (!chrome)
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();
28
- const target = new URL(url);
29
- if (!target.searchParams.has("screenshot"))
30
- target.searchParams.set("screenshot", "1");
31
- const proc = Bun.spawn([
32
- chrome,
33
- "--headless=new",
34
- "--disable-gpu",
35
- "--hide-scrollbars",
36
- "--no-first-run",
37
- "--no-default-browser-check",
38
- `--window-size=${opts.width ?? 800},${opts.height ?? 1000}`,
39
- `--screenshot=${opts.out}`,
40
- target.toString()
41
- ], { stdout: "ignore", stderr: "pipe" });
42
- const timer = setTimeout(() => proc.kill(), opts.timeoutMs ?? 30000);
43
- const code = await proc.exited;
44
- clearTimeout(timer);
45
- if (code !== 0 || !existsSync(opts.out)) {
46
- const err = await new Response(proc.stderr).text();
47
- throw new Error(`chrome exited with ${code}: ${err.slice(-500)}`);
48
- }
49
- return opts.out;
50
- }
51
-
52
- export { findChrome2, requireChrome2, screenshot2 };