@desplega.ai/slack-mock 0.4.0 → 0.5.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.
@@ -4,1491 +4,665 @@ import {
4
4
  screenshot2
5
5
  } from "./index-xs37gskt.js";
6
6
 
7
- // src/store.ts
8
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
9
- import { dirname } from "path";
7
+ // src/frames.ts
8
+ import { copyFileSync, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync } from "fs";
9
+ import { tmpdir } from "os";
10
+ import { join, resolve } from "path";
10
11
 
11
- // src/ids.ts
12
- var ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
13
- function slackId(prefix, length = 8) {
14
- let out = prefix;
15
- for (let i = 0;i < length; i++)
16
- out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
17
- return out;
12
+ // src/render/mrkdwn.ts
13
+ function escapeHtml(s) {
14
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
18
15
  }
19
- var lastMicros = 0;
20
- function nextTs() {
21
- let micros = Date.now() * 1000;
22
- if (micros <= lastMicros)
23
- micros = lastMicros + 1;
24
- lastMicros = micros;
25
- const seconds = Math.floor(micros / 1e6);
26
- const fraction = (micros % 1e6).toString().padStart(6, "0");
27
- return `${seconds}.${fraction}`;
16
+ function unescapeSlack(s) {
17
+ return s.replace(/&(amp|lt|gt|quot);/g, (_m, name) => name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : '"');
28
18
  }
29
- function nowUnix() {
30
- return Math.floor(Date.now() / 1000);
19
+ function reEscape(s) {
20
+ return escapeHtml(unescapeSlack(s));
31
21
  }
32
-
33
- // src/store.ts
34
- class SlackApiError2 extends Error {
35
- code;
36
- extra;
37
- constructor(code, extra = {}) {
38
- super(code);
39
- this.code = code;
40
- this.extra = extra;
41
- }
22
+ var EMOJI = {
23
+ eyes: "\uD83D\uDC40",
24
+ white_check_mark: "\u2705",
25
+ x: "\u274C",
26
+ heavy_plus_sign: "\u2795",
27
+ heavy_minus_sign: "\u2796",
28
+ heavy_multiplication_x: "\u2716\uFE0F",
29
+ zap: "\u26A1",
30
+ speech_balloon: "\uD83D\uDCAC",
31
+ robot_face: "\uD83E\uDD16",
32
+ gear: "\u2699\uFE0F",
33
+ rocket: "\uD83D\uDE80",
34
+ star: "\u2B50",
35
+ crystal_ball: "\uD83D\uDD2E",
36
+ bulb: "\uD83D\uDCA1",
37
+ wrench: "\uD83D\uDD27",
38
+ hammer: "\uD83D\uDD28",
39
+ crown: "\uD83D\uDC51",
40
+ tada: "\uD83C\uDF89",
41
+ warning: "\u26A0\uFE0F",
42
+ hourglass: "\u231B",
43
+ hourglass_flowing_sand: "\u23F3",
44
+ thumbsup: "\uD83D\uDC4D",
45
+ thumbsdown: "\uD83D\uDC4E",
46
+ "+1": "\uD83D\uDC4D",
47
+ "-1": "\uD83D\uDC4E",
48
+ heavy_check_mark: "\u2714\uFE0F",
49
+ question: "\u2753",
50
+ grey_question: "\u2754",
51
+ exclamation: "\u2757",
52
+ white_circle: "\u26AA",
53
+ large_blue_circle: "\uD83D\uDD35",
54
+ black_circle: "\u26AB",
55
+ red_circle: "\uD83D\uDD34",
56
+ large_green_circle: "\uD83D\uDFE2",
57
+ large_yellow_circle: "\uD83D\uDFE1",
58
+ fire: "\uD83D\uDD25",
59
+ sparkles: "\u2728",
60
+ memo: "\uD83D\uDCDD",
61
+ clipboard: "\uD83D\uDCCB",
62
+ mag: "\uD83D\uDD0D",
63
+ mag_right: "\uD83D\uDD0E",
64
+ link: "\uD83D\uDD17",
65
+ lock: "\uD83D\uDD12",
66
+ unlock: "\uD83D\uDD13",
67
+ bell: "\uD83D\uDD14",
68
+ package: "\uD83D\uDCE6",
69
+ construction: "\uD83D\uDEA7",
70
+ bug: "\uD83D\uDC1B",
71
+ boom: "\uD83D\uDCA5",
72
+ pencil2: "\u270F\uFE0F",
73
+ scroll: "\uD83D\uDCDC",
74
+ page_facing_up: "\uD83D\uDCC4",
75
+ file_folder: "\uD83D\uDCC1",
76
+ card_index_dividers: "\uD83D\uDDC2\uFE0F",
77
+ paperclip: "\uD83D\uDCCE",
78
+ bar_chart: "\uD83D\uDCCA",
79
+ chart_with_upwards_trend: "\uD83D\uDCC8",
80
+ calendar: "\uD83D\uDCC5",
81
+ clock1: "\uD83D\uDD50",
82
+ arrow_right: "\u27A1\uFE0F",
83
+ arrow_left: "\u2B05\uFE0F",
84
+ arrow_up: "\u2B06\uFE0F",
85
+ arrow_down: "\u2B07\uFE0F",
86
+ arrow_right_hook: "\u21AA\uFE0F",
87
+ repeat: "\uD83D\uDD01",
88
+ arrows_counterclockwise: "\uD83D\uDD04",
89
+ recycle: "\u267B\uFE0F",
90
+ no_entry: "\u26D4",
91
+ no_entry_sign: "\uD83D\uDEAB",
92
+ stop_sign: "\uD83D\uDED1",
93
+ pause_button: "\u23F8\uFE0F",
94
+ information_source: "\u2139\uFE0F",
95
+ wave: "\uD83D\uDC4B",
96
+ pray: "\uD83D\uDE4F",
97
+ muscle: "\uD83D\uDCAA",
98
+ brain: "\uD83E\uDDE0",
99
+ dart: "\uD83C\uDFAF",
100
+ trophy: "\uD83C\uDFC6",
101
+ medal: "\uD83C\uDFC5",
102
+ checkered_flag: "\uD83C\uDFC1",
103
+ ok_hand: "\uD83D\uDC4C",
104
+ point_right: "\uD83D\uDC49",
105
+ clap: "\uD83D\uDC4F",
106
+ raised_hands: "\uD83D\uDE4C",
107
+ thinking_face: "\uD83E\uDD14",
108
+ "100": "\uD83D\uDCAF",
109
+ green_heart: "\uD83D\uDC9A",
110
+ thread: "\uD83E\uDDF5",
111
+ satellite_antenna: "\uD83D\uDCE1",
112
+ inbox_tray: "\uD83D\uDCE5",
113
+ outbox_tray: "\uD83D\uDCE4",
114
+ incoming_envelope: "\uD83D\uDCE8",
115
+ mailbox_with_no_mail: "\uD83D\uDCED",
116
+ envelope: "\u2709\uFE0F",
117
+ test_tube: "\uD83E\uDDEA",
118
+ ship: "\uD83D\uDEA2",
119
+ sos: "\uD83C\uDD98",
120
+ small_blue_diamond: "\uD83D\uDD39",
121
+ small_orange_diamond: "\uD83D\uDD38",
122
+ black_small_square: "\u25AA\uFE0F",
123
+ white_small_square: "\u25AB\uFE0F"
124
+ };
125
+ function emojiChar(name) {
126
+ return EMOJI[name.replace(/^:|:$/g, "").replace(/::skin-tone-\d$/, "")];
42
127
  }
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
- }
128
+ function emojiFromUnicode(code) {
129
+ const points = code.split("-").map((p) => Number.parseInt(p, 16));
130
+ if (points.some((p) => !Number.isFinite(p)))
131
+ return;
132
+ try {
133
+ return String.fromCodePoint(...points);
134
+ } catch {
135
+ return;
56
136
  }
57
- return entries;
58
137
  }
59
-
60
- class Store2 {
61
- team;
62
- app;
63
- bot;
64
- users = new Map;
65
- channels = new Map;
66
- messages = new Map;
67
- files = new Map;
68
- views = new Map;
69
- ephemerals = [];
70
- apiCalls = [];
71
- assistantThreads = new Map;
72
- listeners = new Set;
73
- dataFile;
74
- replaying = false;
75
- constructor(opts = {}) {
76
- this.team = {
77
- id: opts.teamId ?? "T0MOCK0000",
78
- name: opts.teamName ?? "Mock Workspace",
79
- domain: opts.teamDomain ?? "mock"
80
- };
81
- this.app = { id: opts.appId ?? "A0MOCK0000", name: opts.appName ?? "mock-bot" };
82
- this.bot = {
83
- userId: opts.botUserId ?? "U0BOT00000",
84
- botId: opts.botId ?? "B0BOT00000",
85
- token: opts.botToken ?? "xoxb-mock-bot-token",
86
- appToken: opts.appToken ?? "xapp-mock-app-token",
87
- userToken: opts.userToken
88
- };
89
- this.dataFile = opts.dataFile;
90
- if (this.dataFile && existsSync(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);
94
- if (!this.users.has(this.bot.userId)) {
95
- this.addUser({
96
- id: this.bot.userId,
97
- name: this.app.name,
98
- real_name: this.app.name,
99
- is_bot: true
100
- });
101
- }
102
- }
103
- onChange(listener) {
104
- this.listeners.add(listener);
105
- return () => this.listeners.delete(listener);
138
+ function renderEmoji(html) {
139
+ return html.replace(/:([a-z][a-z0-9_+'-]*|\+1|-1|100):/g, (m, name) => {
140
+ const char = emojiChar(name);
141
+ return char ?? `<span class="sm-emoji-name">${m}</span>`;
142
+ });
143
+ }
144
+ function displayName(user) {
145
+ return user.profile.display_name || user.real_name || user.name;
146
+ }
147
+ function pill(text) {
148
+ return `<span class="sm-pill">${escapeHtml(text)}</span>`;
149
+ }
150
+ function isSafeUrl(url) {
151
+ return /^(https?:\/\/|mailto:|tel:)/i.test(url);
152
+ }
153
+ function renderControl(inner, ctx) {
154
+ const bar = inner.indexOf("|");
155
+ const head = bar >= 0 ? inner.slice(0, bar) : inner;
156
+ const label = bar >= 0 ? inner.slice(bar + 1) : "";
157
+ if (head.startsWith("@")) {
158
+ const id = head.slice(1);
159
+ const user = ctx.users.get(id);
160
+ return pill(`@${user ? displayName(user) : label || id}`);
106
161
  }
107
- onChangeEmit(change) {
108
- this.emit(change);
162
+ if (head.startsWith("#")) {
163
+ const id = head.slice(1);
164
+ const channel = ctx.channels.get(id);
165
+ return pill(`#${channel ? channel.name : label.replace(/^#/, "") || id}`);
109
166
  }
110
- emit(change) {
111
- if (this.dataFile && !this.replaying && change.kind !== "api.call") {
112
- appendFileSync(this.dataFile, `${JSON.stringify({ at: new Date().toISOString(), ...stripBytes(change) })}
113
- `);
167
+ if (head.startsWith("!")) {
168
+ const cmd = head.slice(1);
169
+ if (cmd === "here" || cmd === "channel" || cmd === "everyone")
170
+ return pill(`@${cmd}`);
171
+ if (cmd.startsWith("subteam^")) {
172
+ const handle = label || cmd.slice("subteam^".length);
173
+ return pill(handle.startsWith("@") ? handle : `@${handle}`);
114
174
  }
115
- for (const l of this.listeners)
116
- l(change);
117
- }
118
- replay(changes) {
119
- this.replaying = true;
120
- try {
121
- for (const change of changes)
122
- this.applyReplayed(change);
123
- } finally {
124
- this.replaying = false;
125
- }
126
- }
127
- applyReplayed(change) {
128
- switch (change.kind) {
129
- case "user.add":
130
- this.users.set(change.user.id, change.user);
131
- break;
132
- case "channel.add":
133
- case "channel.update":
134
- this.channels.set(change.channel.id, change.channel);
135
- break;
136
- case "member.join": {
137
- const c = this.channels.get(change.channel.id);
138
- if (c && !c.members.includes(change.user))
139
- c.members.push(change.user);
140
- break;
141
- }
142
- case "message.add":
143
- this.insertMessage(change.message);
144
- break;
145
- case "message.update":
146
- case "reaction.add":
147
- case "reaction.remove": {
148
- const list = this.messages.get(change.message.channel);
149
- const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
150
- if (list && i >= 0)
151
- list[i] = change.message;
152
- break;
153
- }
154
- case "message.delete": {
155
- const list = this.messages.get(change.message.channel);
156
- const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
157
- if (list && i >= 0)
158
- list.splice(i, 1);
159
- break;
160
- }
161
- case "file.add":
162
- this.files.set(change.file.id, change.file);
163
- break;
164
- default:
165
- break;
166
- }
167
- }
168
- addUser(input) {
169
- const id = input.id ?? slackId("U");
170
- const realName = input.real_name ?? input.name;
171
- const user = {
172
- id,
173
- team_id: this.team.id,
174
- name: input.name,
175
- real_name: realName,
176
- deleted: false,
177
- is_bot: input.is_bot ?? false,
178
- is_admin: input.is_admin ?? false,
179
- is_app_user: false,
180
- tz: input.tz ?? "UTC",
181
- profile: {
182
- real_name: realName,
183
- display_name: input.name,
184
- real_name_normalized: realName,
185
- display_name_normalized: input.name,
186
- email: input.email,
187
- title: input.title,
188
- status_text: input.status,
189
- team: this.team.id
190
- }
191
- };
192
- this.users.set(id, user);
193
- this.emit({ kind: "user.add", user });
194
- return user;
195
- }
196
- user(id) {
197
- const u = this.users.get(id);
198
- if (!u)
199
- throw new SlackApiError2("user_not_found");
200
- return u;
201
- }
202
- userByEmail(email) {
203
- for (const u of this.users.values())
204
- if (u.profile.email === email)
205
- return u;
206
- return;
207
- }
208
- isBotUser(userId) {
209
- return userId === this.bot.userId;
210
- }
211
- addChannel(input) {
212
- const name = input.name.replace(/^#/, "");
213
- for (const c of this.channels.values()) {
214
- if (c.name === name && !c.is_im)
215
- throw new SlackApiError2("name_taken");
175
+ if (cmd.startsWith("date^")) {
176
+ if (label)
177
+ return renderEmoji(reEscape(label));
178
+ const secs = Number(cmd.split("^")[1]);
179
+ return Number.isFinite(secs) ? escapeHtml(new Date(secs * 1000).toISOString()) : "";
216
180
  }
217
- const id = input.id ?? slackId(input.is_private ? "G" : "C");
218
- const creator = input.creator ?? this.bot.userId;
219
- const members = [...new Set([creator, ...input.members ?? []])];
220
- const channel = {
221
- id,
222
- name,
223
- is_channel: !input.is_private,
224
- is_group: !!input.is_private,
225
- is_im: false,
226
- is_mpim: false,
227
- is_private: !!input.is_private,
228
- is_archived: false,
229
- is_general: name === "general",
230
- created: nowUnix(),
231
- creator,
232
- topic: { value: input.topic ?? "", creator, last_set: 0 },
233
- purpose: { value: input.purpose ?? "", creator, last_set: 0 },
234
- members
235
- };
236
- this.channels.set(id, channel);
237
- this.messages.set(id, []);
238
- this.emit({ kind: "channel.add", channel });
239
- return channel;
240
- }
241
- openDm(userId) {
242
- this.user(userId);
243
- for (const c of this.channels.values())
244
- if (c.is_im && c.user === userId)
245
- return c;
246
- const id = slackId("D");
247
- const channel = {
248
- id,
249
- name: id,
250
- is_channel: false,
251
- is_group: false,
252
- is_im: true,
253
- is_mpim: false,
254
- is_private: true,
255
- is_archived: false,
256
- is_general: false,
257
- created: nowUnix(),
258
- creator: userId,
259
- user: userId,
260
- topic: { value: "", creator: "", last_set: 0 },
261
- purpose: { value: "", creator: "", last_set: 0 },
262
- members: [userId, this.bot.userId]
263
- };
264
- this.channels.set(id, channel);
265
- this.messages.set(id, []);
266
- this.emit({ kind: "channel.add", channel });
267
- return channel;
268
- }
269
- channel(id) {
270
- const c = this.channels.get(id);
271
- if (!c)
272
- throw new SlackApiError2("channel_not_found");
273
- return c;
274
- }
275
- channelByName(name) {
276
- const n = name.replace(/^#/, "");
277
- for (const c of this.channels.values())
278
- if (c.name === n)
279
- return c;
280
- return;
281
- }
282
- channelType(c) {
283
- if (c.is_im)
284
- return "im";
285
- if (c.is_mpim)
286
- return "mpim";
287
- if (c.is_private)
288
- return "group";
289
- return "channel";
181
+ return pill(`@${cmd}`);
290
182
  }
291
- join(channelId, userId, inviter) {
292
- const channel = this.channel(channelId);
293
- if (channel.is_archived)
294
- throw new SlackApiError2("is_archived");
295
- if (channel.members.includes(userId))
296
- return { alreadyMember: true };
297
- channel.members.push(userId);
298
- this.emit({ kind: "member.join", channel, user: userId, inviter });
299
- return { alreadyMember: false };
183
+ if (isSafeUrl(head)) {
184
+ const shown = label || head.replace(/^mailto:/i, "");
185
+ const attrs = /^mailto:/i.test(head) ? "" : ' target="_blank" rel="noopener"';
186
+ return `<a class="sm-link" href="${escapeHtml(head)}"${attrs}>${renderEmoji(reEscape(shown))}</a>`;
300
187
  }
301
- archive(channelId) {
302
- const channel = this.channel(channelId);
303
- if (channel.is_archived)
304
- throw new SlackApiError2("already_archived");
305
- if (channel.is_general)
306
- throw new SlackApiError2("cant_archive_general");
307
- channel.is_archived = true;
308
- this.emit({ kind: "channel.update", channel });
188
+ return escapeHtml(`<${unescapeSlack(inner)}>`);
189
+ }
190
+ function preHtml(body) {
191
+ let code = body.replace(/^\n/, "").replace(/\n$/, "");
192
+ if (code.includes(`
193
+ `))
194
+ code = code.replace(/^[a-z][a-z0-9+#-]{0,11}\n/, "");
195
+ return `<pre class="sm-pre">${reEscape(code)}</pre>`;
196
+ }
197
+ var BOUND_L = `(^|[\\s(\\[{'"\\uE000\\uE001])`;
198
+ var BOUND_R = `(?=$|[\\s.,;:!?)\\]}'"\\uE000\\uE001])`;
199
+ function styleRule(marker) {
200
+ const m = marker.replace(/[*]/g, "\\*");
201
+ return new RegExp(`${BOUND_L}${m}(?![\\s${m}])([^${m}\\n]*[^\\s${m}])${m}${BOUND_R}`, "g");
202
+ }
203
+ var RULES = [
204
+ [styleRule("*"), "strong"],
205
+ [styleRule("~"), "s"],
206
+ [styleRule("_"), "em"]
207
+ ];
208
+ function inlineStyles(s) {
209
+ let out = s;
210
+ for (const [re, tag] of RULES)
211
+ out = out.replace(re, `$1<${tag}>$2</${tag}>`);
212
+ return out;
213
+ }
214
+ var QUOTE = /^\s*(?:&gt;|>)\s?/;
215
+ var BULLET = /^(\s*)(?:\u2022|-|\*)\s+(.*)$/;
216
+ var NUMBER = /^(\s*)\d+[.)]\s+(.*)$/;
217
+ function blockify(text) {
218
+ const groups = [];
219
+ const push = (kind, html, indent = 0) => {
220
+ const last = groups[groups.length - 1];
221
+ if (last?.kind === kind)
222
+ last.items.push({ html, indent });
223
+ else
224
+ groups.push({ kind, items: [{ html, indent }] });
225
+ };
226
+ for (const line of text.split(`
227
+ `)) {
228
+ const bullet = BULLET.exec(line);
229
+ const numbered = bullet ? null : NUMBER.exec(line);
230
+ if (QUOTE.test(line))
231
+ push("quote", line.replace(QUOTE, ""));
232
+ else if (bullet)
233
+ push("ul", bullet[2] ?? "", Math.min(4, Math.floor((bullet[1]?.length ?? 0) / 2)));
234
+ else if (numbered)
235
+ push("ol", numbered[2] ?? "", Math.min(4, Math.floor((numbered[1]?.length ?? 0) / 2)));
236
+ else
237
+ push("p", line);
309
238
  }
310
- insertMessage(message) {
311
- const list = this.messages.get(message.channel) ?? [];
312
- this.messages.set(message.channel, list);
313
- let i = list.length;
314
- while (i > 0 && Number(list[i - 1].ts) > Number(message.ts))
315
- i--;
316
- list.splice(i, 0, message);
317
- if (message.thread_ts && message.thread_ts !== message.ts) {
318
- const parent = this.findMessage(message.channel, message.thread_ts);
319
- if (parent) {
320
- parent.reply_count = (parent.reply_count ?? 0) + 1;
321
- const users = new Set(parent.reply_users ?? []);
322
- if (message.user)
323
- users.add(message.user);
324
- parent.reply_users = [...users];
325
- parent.reply_users_count = users.size;
326
- parent.latest_reply = message.ts;
327
- if (parent.user)
328
- message.parent_user_id = parent.user;
329
- }
330
- }
331
- }
332
- findMessage(channelId, ts) {
333
- return this.messages.get(channelId)?.find((m) => m.ts === ts);
334
- }
335
- findAnyMessage(channelId, ts) {
336
- return this.findMessage(channelId, ts) ?? this.ephemerals.find((m) => m.channel === channelId && m.ts === ts);
337
- }
338
- updateEphemeral(channelId, ts, patch) {
339
- const m = this.ephemerals.find((x) => x.channel === channelId && x.ts === ts);
340
- if (!m)
341
- throw new SlackApiError2("message_not_found");
342
- Object.assign(m, patch);
343
- return m;
344
- }
345
- deleteEphemeral(channelId, ts) {
346
- const i = this.ephemerals.findIndex((x) => x.channel === channelId && x.ts === ts);
347
- if (i < 0)
348
- throw new SlackApiError2("message_not_found");
349
- this.ephemerals.splice(i, 1);
350
- }
351
- message(channelId, ts) {
352
- const m = this.findMessage(channelId, ts);
353
- if (!m)
354
- throw new SlackApiError2("message_not_found");
355
- return m;
239
+ return groups.map((g) => {
240
+ if (g.kind === "p")
241
+ return g.items.map((i) => i.html).join("<br>");
242
+ const inner = g.items.map((i) => `<li${i.indent ? ` style="margin-left:${i.indent * 18}px"` : ""}>${i.html}</li>`).join("");
243
+ if (g.kind === "quote")
244
+ return `<blockquote class="sm-quote">${g.items.map((i) => i.html).join("<br>")}</blockquote>`;
245
+ return `<${g.kind} class="sm-list">${inner}</${g.kind}>`;
246
+ }).join("");
247
+ }
248
+ var BLOCK_TAGS = "pre|blockquote|ul|ol";
249
+ function tidy(html) {
250
+ return html.replace(new RegExp(`<br>\\s*(<(?:${BLOCK_TAGS})\\b)`, "g"), "$1").replace(new RegExp(`(</(?:${BLOCK_TAGS})>)\\s*<br>`, "g"), "$1");
251
+ }
252
+ function mrkdwnToHtml(text, ctx) {
253
+ if (!text)
254
+ return "";
255
+ const tokens = [];
256
+ const hold = (html) => {
257
+ tokens.push(html);
258
+ return `\uE000${tokens.length - 1}\uE001`;
259
+ };
260
+ let s = text.replace(/\r\n/g, `
261
+ `);
262
+ s = s.replace(/```([\s\S]*?)```/g, (_m, body) => hold(preHtml(body)));
263
+ s = s.replace(/`([^`\n]+)`/g, (_m, body) => hold(`<code class="sm-code">${reEscape(body)}</code>`));
264
+ s = s.replace(/<([^<>\n]*)>/g, (_m, inner) => hold(renderControl(inner, ctx)));
265
+ s = renderEmoji(reEscape(s));
266
+ s = inlineStyles(s);
267
+ s = blockify(s);
268
+ const expand = (html) => html.replace(/\uE000(\d+)\uE001/g, (_m, i) => expand(tokens[Number(i)] ?? ""));
269
+ return tidy(expand(s));
270
+ }
271
+ function plainTextToHtml(text) {
272
+ if (!text)
273
+ return "";
274
+ return renderEmoji(reEscape(text.replace(/\r\n/g, `
275
+ `))).replace(/\n/g, "<br>");
276
+ }
277
+ var BOLD = "\uE002";
278
+ var CODE = /\uE003(\d+)\uE004/g;
279
+ function markdownProse(s) {
280
+ return s.replace(/^(\s*)[-*+]\s+/gm, "$1\u2022 ").replace(/^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/gm, "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500").replace(/\*\*(.+?)\*\*/g, `${BOLD}$1${BOLD}`).replace(/__(.+?)__/g, `${BOLD}$1${BOLD}`).replace(/(^|[^*\w])\*(?![\s*])([^*\n]*[^\s*])\*(?![*\w])/g, "$1_$2_").replace(/~~(.+?)~~/g, "~$1~").replace(/\[([^\]]+)\]\(((?:https?:\/\/|mailto:)[^)\s]+)\)/g, "<$2|$1>").replace(/^ {0,3}#{1,6}\s+(.+?)\s*#*\s*$/gm, (_m, title) => `${BOLD}${title.replaceAll(BOLD, "")}${BOLD}`).replaceAll(BOLD, "*");
281
+ }
282
+ function markdownToMrkdwn(text) {
283
+ const code = [];
284
+ const held = text.replace(/\r\n/g, `
285
+ `).replace(/```[\s\S]*?```|`[^`\n]+`/g, (m) => `\uE003${code.push(m) - 1}\uE004`);
286
+ return markdownProse(held).replace(CODE, (_m, i) => code[Number(i)] ?? "");
287
+ }
288
+ function markdownToHtml(text, ctx) {
289
+ return mrkdwnToHtml(markdownToMrkdwn(text), ctx);
290
+ }
291
+
292
+ // src/render/blocks.ts
293
+ function rec(v) {
294
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
295
+ }
296
+ function str(v) {
297
+ return typeof v === "string" ? v : "";
298
+ }
299
+ function arr(v) {
300
+ return Array.isArray(v) ? v : [];
301
+ }
302
+ function safeUrl(url) {
303
+ return /^(https?:\/\/|\/)/i.test(url) ? escapeHtml(url) : undefined;
304
+ }
305
+ function unsupported(what) {
306
+ return `<div class="sm-unsupported">unsupported: ${escapeHtml(what || "unknown")}</div>`;
307
+ }
308
+ function textObject(v, ctx) {
309
+ if (typeof v === "string")
310
+ return plainTextToHtml(v);
311
+ const o = rec(v);
312
+ if (!o)
313
+ return "";
314
+ const text = str(o.text);
315
+ return o.type === "mrkdwn" ? mrkdwnToHtml(text, ctx) : plainTextToHtml(text);
316
+ }
317
+ function plainOf(v) {
318
+ const o = rec(v);
319
+ return plainTextToHtml(o ? str(o.text) : str(v));
320
+ }
321
+ function image(url, alt, cls) {
322
+ const src = safeUrl(url);
323
+ if (!src)
324
+ return unsupported("image url");
325
+ return `<img class="${cls}" src="${src}" alt="${escapeHtml(alt)}">`;
326
+ }
327
+ function imageSrcOf(block) {
328
+ const direct = str(block.image_url);
329
+ if (direct)
330
+ return direct;
331
+ const file = rec(block.slack_file);
332
+ return file ? str(file.url) || str(file.url_private) : "";
333
+ }
334
+ function button(el, ctx) {
335
+ const style = str(el.style);
336
+ const cls = `sm-btn${style === "primary" ? " sm-btn-primary" : style === "danger" ? " sm-btn-danger" : ""}`;
337
+ const label = textObject(el.text, ctx) || "Button";
338
+ const url = safeUrl(str(el.url));
339
+ const confirm = rec(el.confirm) ? '<span class="sm-btn-confirm" title="confirmation dialog">\u26A0</span>' : "";
340
+ return url ? `<a class="${cls}" href="${url}" target="_blank" rel="noopener">${label}${confirm}</a>` : `<span class="${cls}">${label}${confirm}</span>`;
341
+ }
342
+ function selectPill(el, ctx, glyph = "\u25BE") {
343
+ const initial = rec(el.initial_option);
344
+ const label = initial && textObject(initial.text, ctx) || textObject(el.placeholder, ctx) || plainTextToHtml(str(el.type).replace(/_/g, " "));
345
+ return `<span class="sm-select">${label}<span class="sm-select-caret">${glyph}</span></span>`;
346
+ }
347
+ function inputBox(el, ctx) {
348
+ const multiline = el.multiline === true;
349
+ const value = str(el.initial_value);
350
+ const inner = value ? plainTextToHtml(value) : `<span class="sm-input-ph">${textObject(el.placeholder, ctx)}</span>`;
351
+ return `<div class="sm-input${multiline ? " sm-input-multi" : ""}">${inner}</div>`;
352
+ }
353
+ function renderElement(v, ctx) {
354
+ const el = rec(v);
355
+ if (!el)
356
+ return "";
357
+ const type = str(el.type);
358
+ switch (type) {
359
+ case "button":
360
+ return button(el, ctx);
361
+ case "image":
362
+ return image(imageSrcOf(el), str(el.alt_text), "sm-acc-img");
363
+ case "overflow":
364
+ return `<span class="sm-select sm-overflow">\u22EF</span>`;
365
+ case "datepicker":
366
+ return selectPill({ ...el, placeholder: el.placeholder ?? "Select a date" }, ctx, "\uD83D\uDCC5");
367
+ case "timepicker":
368
+ return selectPill({ ...el, placeholder: el.placeholder ?? "Select a time" }, ctx, "\uD83D\uDD50");
369
+ case "plain_text_input":
370
+ return inputBox(el, ctx);
371
+ case "checkboxes":
372
+ case "radio_buttons":
373
+ return `<div class="sm-options">${arr(el.options).map((o) => {
374
+ const opt = rec(o);
375
+ const mark = type === "checkboxes" ? "\u2610" : "\u25EF";
376
+ return `<div class="sm-option">${mark} ${opt ? textObject(opt.text, ctx) : ""}</div>`;
377
+ }).join("")}</div>`;
378
+ default:
379
+ if (type.endsWith("_select") || type.startsWith("multi_"))
380
+ return selectPill(el, ctx);
381
+ return unsupported(type);
356
382
  }
357
- addMessage(input) {
358
- const channel = this.channel(input.channel);
359
- if (channel.is_archived)
360
- throw new SlackApiError2("is_archived");
361
- if (input.thread_ts && !this.findMessage(input.channel, input.thread_ts)) {
362
- throw new SlackApiError2("thread_not_found");
383
+ }
384
+ function richStyle(html, style) {
385
+ if (!html || !style)
386
+ return html;
387
+ let out = html;
388
+ if (style.code === true)
389
+ out = `<code class="sm-code">${out}</code>`;
390
+ if (style.bold === true)
391
+ out = `<strong>${out}</strong>`;
392
+ if (style.italic === true)
393
+ out = `<em>${out}</em>`;
394
+ if (style.strike === true)
395
+ out = `<s>${out}</s>`;
396
+ return out;
397
+ }
398
+ function richElement(v, ctx) {
399
+ const el = rec(v);
400
+ if (!el)
401
+ return "";
402
+ const style = rec(el.style);
403
+ switch (str(el.type)) {
404
+ case "text":
405
+ return richStyle(plainTextToHtml(str(el.text)).replace(/\n/g, "<br>"), style);
406
+ case "link": {
407
+ const url = safeUrl(str(el.url));
408
+ const label = plainTextToHtml(str(el.text) || str(el.url));
409
+ if (!url)
410
+ return label;
411
+ return richStyle(`<a class="sm-link" href="${url}" target="_blank" rel="noopener">${label}</a>`, style);
363
412
  }
364
- const message = {
365
- type: "message",
366
- team: this.team.id,
367
- ts: input.ts ?? nextTs(),
368
- ...input
369
- };
370
- if (message.ephemeral_user)
371
- this.ephemerals.push(message);
372
- else
373
- this.insertMessage(message);
374
- this.emit({ kind: "message.add", message });
375
- return message;
376
- }
377
- updateMessage(channelId, ts, patch, editor, opts = {}) {
378
- const message = this.message(channelId, ts);
379
- const previous = structuredClone(message);
380
- Object.assign(message, patch, opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } });
381
- this.emit({ kind: "message.update", message, previous });
382
- return message;
383
- }
384
- deleteMessage(channelId, ts) {
385
- const list = this.messages.get(channelId);
386
- const i = list?.findIndex((m) => m.ts === ts) ?? -1;
387
- if (!list || i < 0)
388
- throw new SlackApiError2("message_not_found");
389
- const [message] = list.splice(i, 1);
390
- if (message.thread_ts && message.thread_ts !== ts) {
391
- const parent = this.findMessage(channelId, message.thread_ts);
392
- if (parent?.reply_count)
393
- parent.reply_count -= 1;
413
+ case "user": {
414
+ const user = ctx.users.get(str(el.user_id));
415
+ return `<span class="sm-pill">@${escapeHtml(user ? displayName(user) : str(el.user_id))}</span>`;
394
416
  }
395
- this.emit({ kind: "message.delete", message });
396
- return message;
397
- }
398
- addReaction(channelId, ts, name, userId) {
399
- const message = this.message(channelId, ts);
400
- message.reactions ??= [];
401
- let reaction = message.reactions.find((r) => r.name === name);
402
- if (reaction?.users.includes(userId))
403
- throw new SlackApiError2("already_reacted");
404
- if (!reaction) {
405
- reaction = { name, users: [], count: 0 };
406
- message.reactions.push(reaction);
417
+ case "usergroup":
418
+ return `<span class="sm-pill">@${escapeHtml(str(el.usergroup_id))}</span>`;
419
+ case "channel": {
420
+ const channel = ctx.channels.get(str(el.channel_id));
421
+ return `<span class="sm-pill">#${escapeHtml(channel ? channel.name : str(el.channel_id))}</span>`;
407
422
  }
408
- reaction.users.push(userId);
409
- reaction.count = reaction.users.length;
410
- this.emit({ kind: "reaction.add", message, name, user: userId });
411
- return message;
423
+ case "broadcast":
424
+ return `<span class="sm-pill">@${escapeHtml(str(el.range) || "channel")}</span>`;
425
+ case "emoji": {
426
+ const char = emojiChar(str(el.name)) ?? (el.unicode ? emojiFromUnicode(str(el.unicode)) : undefined);
427
+ return char ?? `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
428
+ }
429
+ case "date":
430
+ return plainTextToHtml(str(el.fallback) || str(el.timestamp));
431
+ case "color":
432
+ return plainTextToHtml(str(el.value));
433
+ default:
434
+ return "";
412
435
  }
413
- removeReaction(channelId, ts, name, userId) {
414
- const message = this.message(channelId, ts);
415
- const reaction = message.reactions?.find((r) => r.name === name);
416
- if (!reaction?.users.includes(userId))
417
- throw new SlackApiError2("no_reaction");
418
- reaction.users = reaction.users.filter((u) => u !== userId);
419
- reaction.count = reaction.users.length;
420
- message.reactions = message.reactions.filter((r) => r.count > 0);
421
- if (message.reactions.length === 0)
422
- message.reactions = undefined;
423
- this.emit({ kind: "reaction.remove", message, name, user: userId });
424
- return message;
425
- }
426
- history(channelId, q = {}) {
427
- this.channel(channelId);
428
- const all = (this.messages.get(channelId) ?? []).filter((m) => !m.thread_ts || m.thread_ts === m.ts || m.subtype === "thread_broadcast");
429
- return paginate(all, q);
430
- }
431
- replies(channelId, threadTs, q = {}) {
432
- const parent = this.message(channelId, threadTs);
433
- const all = [
434
- parent,
435
- ...(this.messages.get(channelId) ?? []).filter((m) => m.thread_ts === threadTs && m.ts !== threadTs)
436
- ];
437
- return paginate(all, q);
438
- }
439
- addFile(input) {
440
- const id = input.id ?? slackId("F");
441
- const ext = input.name.includes(".") ? input.name.split(".").pop().toLowerCase() : "";
442
- const mimetype = input.mimetype ?? guessMime(ext);
443
- const now = nowUnix();
444
- const file = {
445
- id,
446
- created: now,
447
- timestamp: now,
448
- name: input.name,
449
- title: input.title ?? input.name,
450
- mimetype,
451
- filetype: ext || "binary",
452
- pretty_type: ext ? ext.toUpperCase() : "Binary",
453
- user: input.user,
454
- size: input.bytes.byteLength,
455
- mode: "hosted",
456
- is_external: false,
457
- is_public: false,
458
- url_private: `${input.baseUrl}/files-pri/${this.team.id}-${id}/${encodeURIComponent(input.name)}`,
459
- url_private_download: `${input.baseUrl}/files-pri/${this.team.id}-${id}/download/${encodeURIComponent(input.name)}`,
460
- permalink: `${input.baseUrl}/files/${input.user}/${id}/${encodeURIComponent(input.name)}`,
461
- channels: [],
462
- bytes: input.bytes
463
- };
464
- if (mimetype.startsWith("image/")) {
465
- const thumbs = file;
466
- for (const size of [64, 80, 160, 360, 480])
467
- thumbs[`thumb_${size}`] = file.url_private;
436
+ }
437
+ function richSection(v, ctx) {
438
+ const block = rec(v);
439
+ if (!block)
440
+ return "";
441
+ const inner = arr(block.elements).map((e) => richElement(e, ctx)).join("");
442
+ switch (str(block.type)) {
443
+ case "rich_text_section":
444
+ return `<div class="sm-rt-section">${inner}</div>`;
445
+ case "rich_text_quote":
446
+ return `<blockquote class="sm-quote">${inner}</blockquote>`;
447
+ case "rich_text_preformatted":
448
+ return `<pre class="sm-pre">${inner}</pre>`;
449
+ case "rich_text_list": {
450
+ const tag = str(block.style) === "ordered" ? "ol" : "ul";
451
+ const indent = Number(block.indent) || 0;
452
+ const items = arr(block.elements).map((item) => `<li>${richSection(item, ctx)}</li>`).join("");
453
+ const margin = indent ? ` style="margin-left:${indent * 18}px"` : "";
454
+ return `<${tag} class="sm-list"${margin}>${items}</${tag}>`;
468
455
  }
469
- this.files.set(id, file);
470
- this.emit({ kind: "file.add", file });
471
- return file;
472
- }
473
- file(id) {
474
- const f = this.files.get(id);
475
- if (!f)
476
- throw new SlackApiError2("file_not_found");
477
- return f;
478
- }
479
- openView(view) {
480
- const id = view.id ?? slackId("V");
481
- const full = {
482
- ...view,
483
- id,
484
- team_id: this.team.id,
485
- app_id: this.app.id,
486
- bot_id: this.bot.botId,
487
- hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`,
488
- root_view_id: id
489
- };
490
- this.views.set(id, full);
491
- this.emit({ kind: "view.open", view: full });
492
- return full;
493
- }
494
- recordApiCall(call) {
495
- this.apiCalls.push(call);
496
- this.emit({ kind: "api.call", call });
456
+ default:
457
+ return inner;
497
458
  }
498
- assistantThread(channel, threadTs) {
499
- const key = `${channel}:${threadTs}`;
500
- let t = this.assistantThreads.get(key);
501
- if (!t) {
502
- t = {};
503
- this.assistantThreads.set(key, t);
504
- }
505
- return t;
459
+ }
460
+ function sectionBlock(block, ctx) {
461
+ const parts = [];
462
+ if (block.text)
463
+ parts.push(`<div class="sm-section-text">${textObject(block.text, ctx)}</div>`);
464
+ const fields = arr(block.fields);
465
+ if (fields.length) {
466
+ parts.push(`<div class="sm-fields">${fields.map((f) => `<div class="sm-field">${textObject(f, ctx)}</div>`).join("")}</div>`);
506
467
  }
468
+ const accessory = block.accessory ? renderElement(block.accessory, ctx) : "";
469
+ const body = parts.join("");
470
+ if (!accessory)
471
+ return `<div class="sm-block sm-section">${body}</div>`;
472
+ return `<div class="sm-block sm-section sm-section-split"><div class="sm-section-main">${body}</div><div class="sm-section-acc">${accessory}</div></div>`;
507
473
  }
508
- function paginate(all, q) {
509
- let items = all;
510
- if (q.oldest)
511
- items = items.filter((m) => q.inclusive ? Number(m.ts) >= Number(q.oldest) : Number(m.ts) > Number(q.oldest));
512
- if (q.latest)
513
- items = items.filter((m) => q.inclusive ? Number(m.ts) <= Number(q.latest) : Number(m.ts) < Number(q.latest));
514
- const start = q.cursor ? Number.parseInt(Buffer.from(q.cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0 : 0;
515
- const limit = Math.max(1, Math.min(q.limit ?? 100, 1000));
516
- const page = items.slice(start, start + limit);
517
- const has_more = start + limit < items.length;
518
- return {
519
- items: page,
520
- has_more,
521
- next_cursor: has_more ? Buffer.from(`offset:${start + limit}`).toString("base64") : ""
522
- };
474
+ function contextBlock(block, ctx) {
475
+ const inner = arr(block.elements).map((e) => {
476
+ const el = rec(e);
477
+ if (!el)
478
+ return "";
479
+ if (str(el.type) === "image")
480
+ return image(imageSrcOf(el), str(el.alt_text), "sm-context-img");
481
+ return `<span class="sm-context-text">${textObject(el, ctx)}</span>`;
482
+ }).join("");
483
+ return `<div class="sm-block sm-context">${inner}</div>`;
523
484
  }
524
- function guessMime(ext) {
525
- const map = {
526
- png: "image/png",
527
- jpg: "image/jpeg",
528
- jpeg: "image/jpeg",
529
- gif: "image/gif",
530
- webp: "image/webp",
531
- svg: "image/svg+xml",
532
- txt: "text/plain",
533
- md: "text/markdown",
534
- log: "text/plain",
535
- json: "application/json",
536
- csv: "text/csv",
537
- pdf: "application/pdf",
538
- html: "text/html",
539
- zip: "application/zip"
540
- };
541
- return map[ext] ?? "application/octet-stream";
485
+ function imageBlock(block, ctx) {
486
+ const title = block.title ? `<div class="sm-img-title">${textObject(block.title, ctx)}</div>` : "";
487
+ const src = imageSrcOf(block);
488
+ const alt = str(block.alt_text);
489
+ if (!src) {
490
+ const file = rec(block.slack_file);
491
+ return `<div class="sm-block">${title}${unsupported(`image (file ${str(file?.id) || "?"})`)}</div>`;
492
+ }
493
+ return `<div class="sm-block sm-image">${title}${image(src, alt, "sm-img")}</div>`;
542
494
  }
543
- function wireMessage(m) {
544
- const { ephemeral_user: _e, ...rest } = m;
545
- if (rest.files)
546
- rest.files = rest.files.map(wireFile);
547
- return rest;
495
+ function inputBlock(block, ctx) {
496
+ const label = block.label ? `<div class="sm-label">${plainOf(block.label)}</div>` : "";
497
+ const element = block.element ? renderElement(block.element, ctx) : "";
498
+ const hint = block.hint ? `<div class="sm-hint">${plainOf(block.hint)}</div>` : "";
499
+ return `<div class="sm-block sm-input-block">${label}${element}${hint}</div>`;
548
500
  }
549
- function wireFile(f) {
550
- const { bytes: _b, ...rest } = f;
551
- return rest;
501
+ function videoBlock(block, ctx) {
502
+ const thumb = safeUrl(str(block.thumbnail_url));
503
+ const url = safeUrl(str(block.title_url) || str(block.video_url));
504
+ const title = textObject(block.title, ctx) || plainTextToHtml(str(block.alt_text));
505
+ const inner = `${thumb ? `<img class="sm-video-thumb" src="${thumb}" alt="${escapeHtml(str(block.alt_text))}">` : ""}<div class="sm-video-title">\u25B6 ${title}</div>`;
506
+ return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
552
507
  }
553
- function stripBytes(change) {
554
- if (change.kind === "file.add")
555
- return { ...change, file: wireFile(change.file) };
556
- if ("message" in change && change.message.files) {
557
- return {
558
- ...change,
559
- message: { ...change.message, files: change.message.files.map(wireFile) }
560
- };
508
+ function renderBlock(v, ctx) {
509
+ const block = rec(v);
510
+ if (!block)
511
+ return unsupported("block");
512
+ switch (str(block.type)) {
513
+ case "header":
514
+ return `<div class="sm-block sm-header-block">${textObject(block.text, ctx)}</div>`;
515
+ case "section":
516
+ return sectionBlock(block, ctx);
517
+ case "divider":
518
+ return `<div class="sm-block"><hr class="sm-hr"></div>`;
519
+ case "context":
520
+ return contextBlock(block, ctx);
521
+ case "actions":
522
+ return `<div class="sm-block sm-actions">${arr(block.elements).map((e) => renderElement(e, ctx)).join("")}</div>`;
523
+ case "image":
524
+ return imageBlock(block, ctx);
525
+ case "rich_text":
526
+ return `<div class="sm-block sm-rich-text">${arr(block.elements).map((e) => richSection(e, ctx)).join("")}</div>`;
527
+ case "input":
528
+ return inputBlock(block, ctx);
529
+ case "file":
530
+ return `<div class="sm-block sm-file-block">\uD83D\uDCCE ${escapeHtml(str(block.external_id) || str(block.file_id) || "file")}</div>`;
531
+ case "video":
532
+ return videoBlock(block, ctx);
533
+ case "markdown":
534
+ return `<div class="sm-block sm-markdown">${markdownToHtml(str(block.text), ctx)}</div>`;
535
+ default:
536
+ return `<div class="sm-block">${unsupported(str(block.type))}</div>`;
561
537
  }
562
- return change;
563
538
  }
564
- function ensureDir(file) {
565
- mkdirSync(dirname(file), { recursive: true });
566
- }
567
-
568
- // src/server.ts
569
- import { readFileSync as readFileSync2 } from "fs";
570
-
571
- // src/body.ts
572
- var JSON_FIELDS = new Set([
573
- "blocks",
574
- "attachments",
575
- "metadata",
576
- "files",
577
- "view",
578
- "prompts",
579
- "icons",
580
- "user_ids",
581
- "types",
582
- "chunks",
583
- "loading_messages"
584
- ]);
585
- function coerce(key, value) {
586
- if (JSON_FIELDS.has(key)) {
587
- try {
588
- return JSON.parse(value);
589
- } catch {
590
- return value;
591
- }
592
- }
593
- if (value === "true")
594
- return true;
595
- if (value === "false")
596
- return false;
597
- return value;
539
+ function renderBlocks(blocks, ctx) {
540
+ const list = arr(blocks);
541
+ if (!list.length)
542
+ return "";
543
+ return `<div class="sm-blocks">${list.map((b) => renderBlock(b, ctx)).join("")}</div>`;
598
544
  }
599
- async function parseArgs(req) {
600
- const url = new URL(req.url);
601
- const args = {};
602
- for (const [k, v] of url.searchParams)
603
- args[k] = coerce(k, v);
604
- if (req.method !== "POST")
605
- return args;
606
- const contentType = req.headers.get("content-type") ?? "";
607
- if (contentType.includes("application/json")) {
608
- const text = await req.text();
609
- if (text.trim())
610
- Object.assign(args, JSON.parse(text));
611
- return args;
612
- }
613
- if (contentType.includes("multipart/form-data")) {
614
- const form = await req.formData();
615
- form.forEach((v, k) => {
616
- args[k] = typeof v === "string" ? coerce(k, v) : v;
617
- });
618
- return args;
619
- }
620
- const text = await req.text();
621
- if (!text)
622
- return args;
623
- for (const [k, v] of new URLSearchParams(text))
624
- args[k] = coerce(k, v);
625
- return args;
626
- }
627
- function bearerToken(req, args) {
628
- const header = req.headers.get("authorization");
629
- if (header?.toLowerCase().startsWith("bearer "))
630
- return header.slice(7).trim();
631
- if (typeof args.token === "string")
632
- return args.token;
633
- return;
634
- }
635
- function str(args, key) {
636
- const v = args[key];
637
- return typeof v === "string" ? v : v == null ? undefined : String(v);
638
- }
639
- function num(args, key, fallback) {
640
- const v = args[key];
641
- const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : Number.NaN;
642
- return Number.isFinite(n) ? n : fallback;
643
- }
644
- function bool(args, key) {
645
- const v = args[key];
646
- if (typeof v === "boolean")
647
- return v;
648
- if (v === "true" || v === "1" || v === 1)
649
- return true;
650
- if (v === "false" || v === "0" || v === 0)
651
- return false;
652
- return;
545
+ var NAMED_COLORS = {
546
+ good: "#2eb67d",
547
+ warning: "#ecb22e",
548
+ danger: "#e01e5a"
549
+ };
550
+ function barColor(v) {
551
+ const raw = str(v).trim();
552
+ if (!raw)
553
+ return "#dddddd";
554
+ const named = NAMED_COLORS[raw.toLowerCase()];
555
+ if (named)
556
+ return named;
557
+ const hex = raw.startsWith("#") ? raw : `#${raw}`;
558
+ return /^#[0-9a-fA-F]{3,8}$/.test(hex) ? hex : "#dddddd";
653
559
  }
654
-
655
- // src/events.ts
656
- var VERIFICATION_TOKEN = "mock-verification-token";
657
- function eventCallback(store, event) {
658
- return {
659
- token: VERIFICATION_TOKEN,
660
- team_id: store.team.id,
661
- context_team_id: store.team.id,
662
- context_enterprise_id: null,
663
- api_app_id: store.app.id,
664
- event,
665
- type: "event_callback",
666
- event_id: slackId("Ev", 9),
667
- event_time: nowUnix(),
668
- authorizations: [
669
- {
670
- enterprise_id: null,
671
- team_id: store.team.id,
672
- user_id: store.bot.userId,
673
- is_bot: true,
674
- is_enterprise_install: false
675
- }
676
- ],
677
- is_ext_shared_channel: false,
678
- event_context: Buffer.from(`${store.team.id}:${store.app.id}:${event.channel ?? ""}`).toString("base64")
679
- };
560
+ function attachmentFields(fields, ctx) {
561
+ if (!fields.length)
562
+ return "";
563
+ return `<div class="sm-fields">${fields.map((f) => {
564
+ const field = rec(f);
565
+ if (!field)
566
+ return "";
567
+ const wide = field.short === true ? "" : " sm-field-wide";
568
+ return `<div class="sm-field${wide}"><div class="sm-field-title">${plainTextToHtml(str(field.title))}</div><div>${mrkdwnToHtml(str(field.value), ctx)}</div></div>`;
569
+ }).join("")}</div>`;
680
570
  }
681
- function messageEvent(store, m, channel) {
682
- const {
683
- channel: _c,
684
- team,
685
- ...rest
686
- } = wireMessage(m);
687
- const event = {
688
- ...rest,
689
- type: "message",
690
- channel: m.channel,
691
- event_ts: m.ts,
692
- channel_type: store.channelType(channel),
693
- team
694
- };
695
- if (m.files?.length && !m.subtype)
696
- event.subtype = "file_share";
697
- if (m.files?.length) {
698
- event.upload = false;
699
- event.display_as_bot = false;
571
+ function attachment(v, ctx) {
572
+ const att = rec(v);
573
+ if (!att)
574
+ return "";
575
+ const parts = [];
576
+ const author = str(att.author_name);
577
+ if (author) {
578
+ const icon = safeUrl(str(att.author_icon));
579
+ parts.push(`<div class="sm-att-author">${icon ? `<img class="sm-att-author-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(author)}</div>`);
700
580
  }
701
- return event;
702
- }
703
- function appMentionEvent(store, m) {
704
- const { channel_type: _ct, ...event } = messageEvent(store, m, store.channel(m.channel));
705
- return { ...event, type: "app_mention" };
706
- }
707
- function messageChangedEvent(store, m, previous) {
708
- const channel = store.channel(m.channel);
709
- const ts = nextTs();
710
- return {
711
- type: "message",
712
- subtype: "message_changed",
713
- channel: m.channel,
714
- channel_type: store.channelType(channel),
715
- hidden: true,
716
- ts,
717
- event_ts: ts,
718
- message: {
719
- ...wireMessage(m),
720
- channel: undefined,
721
- source_team: store.team.id,
722
- user_team: store.team.id
723
- },
724
- previous_message: { ...wireMessage(previous), channel: undefined }
725
- };
726
- }
727
- function messageDeletedEvent(store, m) {
728
- const channel = store.channel(m.channel);
729
- const ts = nextTs();
730
- return {
731
- type: "message",
732
- subtype: "message_deleted",
733
- channel: m.channel,
734
- channel_type: store.channelType(channel),
735
- hidden: true,
736
- deleted_ts: m.ts,
737
- ts,
738
- event_ts: ts,
739
- previous_message: { ...wireMessage(m), channel: undefined }
740
- };
741
- }
742
- function reactionEvent(kind, m, name, user) {
743
- return {
744
- type: kind,
745
- user,
746
- reaction: name,
747
- item_user: m.user,
748
- item: { type: "message", channel: m.channel, ts: m.ts },
749
- event_ts: nextTs()
750
- };
751
- }
752
- function memberJoinedEvent(store, channel, user, inviter) {
753
- return {
754
- type: "member_joined_channel",
755
- user,
756
- channel: channel.id,
757
- channel_type: store.channelType(channel) === "channel" ? "C" : "G",
758
- team: store.team.id,
759
- inviter,
760
- event_ts: nextTs()
761
- };
762
- }
763
- function assistantThreadStartedEvent(store, dm, user, threadTs, context = {}) {
764
- return {
765
- type: "assistant_thread_started",
766
- assistant_thread: {
767
- user_id: user,
768
- context: { team_id: store.team.id, enterprise_id: null, ...context },
769
- channel_id: dm.id,
770
- thread_ts: threadTs
771
- },
772
- event_ts: nextTs()
773
- };
581
+ const title = str(att.title);
582
+ if (title) {
583
+ const link = safeUrl(str(att.title_link));
584
+ const inner = plainTextToHtml(title);
585
+ parts.push(`<div class="sm-att-title">${link ? `<a class="sm-link" href="${link}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`);
586
+ }
587
+ const text = str(att.text) || (parts.length ? "" : str(att.fallback));
588
+ if (text)
589
+ parts.push(`<div class="sm-att-text">${mrkdwnToHtml(text, ctx)}</div>`);
590
+ parts.push(attachmentFields(arr(att.fields), ctx));
591
+ const img = safeUrl(str(att.image_url));
592
+ if (img)
593
+ parts.push(`<img class="sm-att-img" src="${img}" alt="">`);
594
+ const thumb = !img ? safeUrl(str(att.thumb_url)) : undefined;
595
+ if (thumb)
596
+ parts.push(`<img class="sm-att-thumb" src="${thumb}" alt="">`);
597
+ const blocks = arr(att.blocks);
598
+ if (blocks.length)
599
+ parts.push(renderBlocks(blocks, ctx));
600
+ const footer = str(att.footer);
601
+ const ts = att.ts ? formatAttachmentTs(att.ts) : "";
602
+ if (footer || ts) {
603
+ const icon = safeUrl(str(att.footer_icon));
604
+ parts.push(`<div class="sm-att-footer">${icon ? `<img class="sm-att-footer-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(footer)}${footer && ts ? " | " : ""}${escapeHtml(ts)}</div>`);
605
+ }
606
+ const pretext = str(att.pretext);
607
+ const box = `<div class="sm-att" style="border-left-color:${barColor(att.color)}">${parts.join("")}</div>`;
608
+ return pretext ? `<div class="sm-att-pretext">${mrkdwnToHtml(pretext, ctx)}</div>${box}` : box;
774
609
  }
775
- function assistantThreadContextChangedEvent(store, dm, user, threadTs, context) {
776
- return {
777
- type: "assistant_thread_context_changed",
778
- assistant_thread: {
779
- user_id: user,
780
- context: { team_id: store.team.id, enterprise_id: null, ...context },
781
- channel_id: dm.id,
782
- thread_ts: threadTs
783
- },
784
- event_ts: nextTs()
785
- };
610
+ function formatAttachmentTs(v) {
611
+ const secs = Number(v);
612
+ if (!Number.isFinite(secs) || secs <= 0)
613
+ return str(v);
614
+ const d = new Date(secs * 1000);
615
+ const pad = (n) => String(n).padStart(2, "0");
616
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
786
617
  }
787
- function slashCommandPayload(store, input) {
788
- return {
789
- token: VERIFICATION_TOKEN,
790
- team_id: store.team.id,
791
- team_domain: store.team.domain,
792
- channel_id: input.channel.id,
793
- channel_name: input.channel.is_im ? "directmessage" : input.channel.name,
794
- user_id: input.user.id,
795
- user_name: input.user.name,
796
- command: input.command,
797
- text: input.text,
798
- api_app_id: store.app.id,
799
- is_enterprise_install: "false",
800
- response_url: input.responseUrl,
801
- trigger_id: input.triggerId
802
- };
803
- }
804
- function blockActionsPayload(store, input) {
805
- return {
806
- type: "block_actions",
807
- user: {
808
- id: input.user.id,
809
- username: input.user.name,
810
- name: input.user.name,
811
- team_id: store.team.id
812
- },
813
- api_app_id: store.app.id,
814
- token: VERIFICATION_TOKEN,
815
- container: {
816
- type: "message",
817
- message_ts: input.message.ts,
818
- channel_id: input.channel.id,
819
- is_ephemeral: !!input.message.ephemeral_user,
820
- ...input.message.thread_ts ? { thread_ts: input.message.thread_ts } : {}
821
- },
822
- trigger_id: input.triggerId,
823
- team: { id: store.team.id, domain: store.team.domain },
824
- enterprise: null,
825
- is_enterprise_install: false,
826
- channel: { id: input.channel.id, name: input.channel.name },
827
- message: wireMessage(input.message),
828
- state: { values: {} },
829
- response_url: input.responseUrl,
830
- actions: input.actions.map((a) => ({ action_ts: nextTs(), ...a }))
831
- };
832
- }
833
- function viewSubmissionPayload(store, input) {
834
- const { opened_by: _o, trigger_id: _t, ...view } = input.view;
835
- return {
836
- type: "view_submission",
837
- team: { id: store.team.id, domain: store.team.domain },
838
- user: {
839
- id: input.user.id,
840
- username: input.user.name,
841
- name: input.user.name,
842
- team_id: store.team.id
843
- },
844
- api_app_id: store.app.id,
845
- token: VERIFICATION_TOKEN,
846
- trigger_id: input.triggerId,
847
- view: { ...view, state: { values: input.values } },
848
- response_urls: [],
849
- is_enterprise_install: false,
850
- enterprise: null
851
- };
618
+ function renderAttachments(attachments, ctx) {
619
+ const list = arr(attachments);
620
+ if (!list.length)
621
+ return "";
622
+ return `<div class="sm-atts">${list.map((a) => attachment(a, ctx)).join("")}</div>`;
852
623
  }
853
624
 
854
- // src/render/mrkdwn.ts
855
- function escapeHtml(s) {
856
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
857
- }
858
- function unescapeSlack(s) {
859
- return s.replace(/&(amp|lt|gt|quot);/g, (_m, name) => name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : '"');
860
- }
861
- function reEscape(s) {
862
- return escapeHtml(unescapeSlack(s));
863
- }
864
- var EMOJI = {
865
- eyes: "\uD83D\uDC40",
866
- white_check_mark: "\u2705",
867
- x: "\u274C",
868
- heavy_plus_sign: "\u2795",
869
- heavy_minus_sign: "\u2796",
870
- heavy_multiplication_x: "\u2716\uFE0F",
871
- zap: "\u26A1",
872
- speech_balloon: "\uD83D\uDCAC",
873
- robot_face: "\uD83E\uDD16",
874
- gear: "\u2699\uFE0F",
875
- rocket: "\uD83D\uDE80",
876
- star: "\u2B50",
877
- crystal_ball: "\uD83D\uDD2E",
878
- bulb: "\uD83D\uDCA1",
879
- wrench: "\uD83D\uDD27",
880
- hammer: "\uD83D\uDD28",
881
- crown: "\uD83D\uDC51",
882
- tada: "\uD83C\uDF89",
883
- warning: "\u26A0\uFE0F",
884
- hourglass: "\u231B",
885
- hourglass_flowing_sand: "\u23F3",
886
- thumbsup: "\uD83D\uDC4D",
887
- thumbsdown: "\uD83D\uDC4E",
888
- "+1": "\uD83D\uDC4D",
889
- "-1": "\uD83D\uDC4E",
890
- heavy_check_mark: "\u2714\uFE0F",
891
- question: "\u2753",
892
- grey_question: "\u2754",
893
- exclamation: "\u2757",
894
- white_circle: "\u26AA",
895
- large_blue_circle: "\uD83D\uDD35",
896
- black_circle: "\u26AB",
897
- red_circle: "\uD83D\uDD34",
898
- large_green_circle: "\uD83D\uDFE2",
899
- large_yellow_circle: "\uD83D\uDFE1",
900
- fire: "\uD83D\uDD25",
901
- sparkles: "\u2728",
902
- memo: "\uD83D\uDCDD",
903
- clipboard: "\uD83D\uDCCB",
904
- mag: "\uD83D\uDD0D",
905
- mag_right: "\uD83D\uDD0E",
906
- link: "\uD83D\uDD17",
907
- lock: "\uD83D\uDD12",
908
- unlock: "\uD83D\uDD13",
909
- bell: "\uD83D\uDD14",
910
- package: "\uD83D\uDCE6",
911
- construction: "\uD83D\uDEA7",
912
- bug: "\uD83D\uDC1B",
913
- boom: "\uD83D\uDCA5",
914
- pencil2: "\u270F\uFE0F",
915
- scroll: "\uD83D\uDCDC",
916
- page_facing_up: "\uD83D\uDCC4",
917
- file_folder: "\uD83D\uDCC1",
918
- card_index_dividers: "\uD83D\uDDC2\uFE0F",
919
- paperclip: "\uD83D\uDCCE",
920
- bar_chart: "\uD83D\uDCCA",
921
- chart_with_upwards_trend: "\uD83D\uDCC8",
922
- calendar: "\uD83D\uDCC5",
923
- clock1: "\uD83D\uDD50",
924
- arrow_right: "\u27A1\uFE0F",
925
- arrow_left: "\u2B05\uFE0F",
926
- arrow_up: "\u2B06\uFE0F",
927
- arrow_down: "\u2B07\uFE0F",
928
- arrow_right_hook: "\u21AA\uFE0F",
929
- repeat: "\uD83D\uDD01",
930
- arrows_counterclockwise: "\uD83D\uDD04",
931
- recycle: "\u267B\uFE0F",
932
- no_entry: "\u26D4",
933
- no_entry_sign: "\uD83D\uDEAB",
934
- stop_sign: "\uD83D\uDED1",
935
- pause_button: "\u23F8\uFE0F",
936
- information_source: "\u2139\uFE0F",
937
- wave: "\uD83D\uDC4B",
938
- pray: "\uD83D\uDE4F",
939
- muscle: "\uD83D\uDCAA",
940
- brain: "\uD83E\uDDE0",
941
- dart: "\uD83C\uDFAF",
942
- trophy: "\uD83C\uDFC6",
943
- medal: "\uD83C\uDFC5",
944
- checkered_flag: "\uD83C\uDFC1",
945
- ok_hand: "\uD83D\uDC4C",
946
- point_right: "\uD83D\uDC49",
947
- clap: "\uD83D\uDC4F",
948
- raised_hands: "\uD83D\uDE4C",
949
- thinking_face: "\uD83E\uDD14",
950
- "100": "\uD83D\uDCAF",
951
- green_heart: "\uD83D\uDC9A",
952
- thread: "\uD83E\uDDF5",
953
- satellite_antenna: "\uD83D\uDCE1",
954
- inbox_tray: "\uD83D\uDCE5",
955
- outbox_tray: "\uD83D\uDCE4",
956
- incoming_envelope: "\uD83D\uDCE8",
957
- mailbox_with_no_mail: "\uD83D\uDCED",
958
- envelope: "\u2709\uFE0F",
959
- test_tube: "\uD83E\uDDEA",
960
- ship: "\uD83D\uDEA2",
961
- sos: "\uD83C\uDD98",
962
- small_blue_diamond: "\uD83D\uDD39",
963
- small_orange_diamond: "\uD83D\uDD38",
964
- black_small_square: "\u25AA\uFE0F",
965
- white_small_square: "\u25AB\uFE0F"
966
- };
967
- function emojiChar(name) {
968
- return EMOJI[name.replace(/^:|:$/g, "").replace(/::skin-tone-\d$/, "")];
969
- }
970
- function emojiFromUnicode(code) {
971
- const points = code.split("-").map((p) => Number.parseInt(p, 16));
972
- if (points.some((p) => !Number.isFinite(p)))
973
- return;
974
- try {
975
- return String.fromCodePoint(...points);
976
- } catch {
977
- return;
978
- }
979
- }
980
- function renderEmoji(html) {
981
- return html.replace(/:([a-z][a-z0-9_+'-]*|\+1|-1|100):/g, (m, name) => {
982
- const char = emojiChar(name);
983
- return char ?? `<span class="sm-emoji-name">${m}</span>`;
984
- });
985
- }
986
- function displayName(user) {
987
- return user.profile.display_name || user.real_name || user.name;
988
- }
989
- function pill(text) {
990
- return `<span class="sm-pill">${escapeHtml(text)}</span>`;
991
- }
992
- function isSafeUrl(url) {
993
- return /^(https?:\/\/|mailto:|tel:)/i.test(url);
994
- }
995
- function renderControl(inner, ctx) {
996
- const bar = inner.indexOf("|");
997
- const head = bar >= 0 ? inner.slice(0, bar) : inner;
998
- const label = bar >= 0 ? inner.slice(bar + 1) : "";
999
- if (head.startsWith("@")) {
1000
- const id = head.slice(1);
1001
- const user = ctx.users.get(id);
1002
- return pill(`@${user ? displayName(user) : label || id}`);
1003
- }
1004
- if (head.startsWith("#")) {
1005
- const id = head.slice(1);
1006
- const channel = ctx.channels.get(id);
1007
- return pill(`#${channel ? channel.name : label.replace(/^#/, "") || id}`);
1008
- }
1009
- if (head.startsWith("!")) {
1010
- const cmd = head.slice(1);
1011
- if (cmd === "here" || cmd === "channel" || cmd === "everyone")
1012
- return pill(`@${cmd}`);
1013
- if (cmd.startsWith("subteam^")) {
1014
- const handle = label || cmd.slice("subteam^".length);
1015
- return pill(handle.startsWith("@") ? handle : `@${handle}`);
1016
- }
1017
- if (cmd.startsWith("date^")) {
1018
- if (label)
1019
- return renderEmoji(reEscape(label));
1020
- const secs = Number(cmd.split("^")[1]);
1021
- return Number.isFinite(secs) ? escapeHtml(new Date(secs * 1000).toISOString()) : "";
1022
- }
1023
- return pill(`@${cmd}`);
1024
- }
1025
- if (isSafeUrl(head)) {
1026
- const shown = label || head.replace(/^mailto:/i, "");
1027
- const attrs = /^mailto:/i.test(head) ? "" : ' target="_blank" rel="noopener"';
1028
- return `<a class="sm-link" href="${escapeHtml(head)}"${attrs}>${renderEmoji(reEscape(shown))}</a>`;
1029
- }
1030
- return escapeHtml(`<${unescapeSlack(inner)}>`);
1031
- }
1032
- function preHtml(body) {
1033
- let code = body.replace(/^\n/, "").replace(/\n$/, "");
1034
- if (code.includes(`
1035
- `))
1036
- code = code.replace(/^[a-z][a-z0-9+#-]{0,11}\n/, "");
1037
- return `<pre class="sm-pre">${reEscape(code)}</pre>`;
1038
- }
1039
- var BOUND_L = `(^|[\\s(\\[{'"\\uE000\\uE001])`;
1040
- var BOUND_R = `(?=$|[\\s.,;:!?)\\]}'"\\uE000\\uE001])`;
1041
- function styleRule(marker) {
1042
- const m = marker.replace(/[*]/g, "\\*");
1043
- return new RegExp(`${BOUND_L}${m}(?![\\s${m}])([^${m}\\n]*[^\\s${m}])${m}${BOUND_R}`, "g");
1044
- }
1045
- var RULES = [
1046
- [styleRule("*"), "strong"],
1047
- [styleRule("~"), "s"],
1048
- [styleRule("_"), "em"]
625
+ // src/render/index.ts
626
+ var DEFAULT_PANEL_WIDTH = "50%";
627
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
628
+ var AVATAR_COLORS = [
629
+ "#4a154b",
630
+ "#1264a3",
631
+ "#2eb67d",
632
+ "#e01e5a",
633
+ "#e8912d",
634
+ "#007a5a",
635
+ "#7c3aed",
636
+ "#00a2ac",
637
+ "#df10a5",
638
+ "#3d5afe"
1049
639
  ];
1050
- function inlineStyles(s) {
1051
- let out = s;
1052
- for (const [re, tag] of RULES)
1053
- out = out.replace(re, `$1<${tag}>$2</${tag}>`);
1054
- return out;
1055
- }
1056
- var QUOTE = /^\s*(?:&gt;|>)\s?/;
1057
- var BULLET = /^(\s*)(?:\u2022|-|\*)\s+(.*)$/;
1058
- var NUMBER = /^(\s*)\d+[.)]\s+(.*)$/;
1059
- function blockify(text) {
1060
- const groups = [];
1061
- const push = (kind, html, indent = 0) => {
1062
- const last = groups[groups.length - 1];
1063
- if (last?.kind === kind)
1064
- last.items.push({ html, indent });
1065
- else
1066
- groups.push({ kind, items: [{ html, indent }] });
1067
- };
1068
- for (const line of text.split(`
1069
- `)) {
1070
- const bullet = BULLET.exec(line);
1071
- const numbered = bullet ? null : NUMBER.exec(line);
1072
- if (QUOTE.test(line))
1073
- push("quote", line.replace(QUOTE, ""));
1074
- else if (bullet)
1075
- push("ul", bullet[2] ?? "", Math.min(4, Math.floor((bullet[1]?.length ?? 0) / 2)));
1076
- else if (numbered)
1077
- push("ol", numbered[2] ?? "", Math.min(4, Math.floor((numbered[1]?.length ?? 0) / 2)));
1078
- else
1079
- push("p", line);
1080
- }
1081
- return groups.map((g) => {
1082
- if (g.kind === "p")
1083
- return g.items.map((i) => i.html).join("<br>");
1084
- const inner = g.items.map((i) => `<li${i.indent ? ` style="margin-left:${i.indent * 18}px"` : ""}>${i.html}</li>`).join("");
1085
- if (g.kind === "quote")
1086
- return `<blockquote class="sm-quote">${g.items.map((i) => i.html).join("<br>")}</blockquote>`;
1087
- return `<${g.kind} class="sm-list">${inner}</${g.kind}>`;
1088
- }).join("");
1089
- }
1090
- var BLOCK_TAGS = "pre|blockquote|ul|ol";
1091
- function tidy(html) {
1092
- return html.replace(new RegExp(`<br>\\s*(<(?:${BLOCK_TAGS})\\b)`, "g"), "$1").replace(new RegExp(`(</(?:${BLOCK_TAGS})>)\\s*<br>`, "g"), "$1");
1093
- }
1094
- function mrkdwnToHtml(text, ctx) {
1095
- if (!text)
1096
- return "";
1097
- const tokens = [];
1098
- const hold = (html) => {
1099
- tokens.push(html);
1100
- return `\uE000${tokens.length - 1}\uE001`;
1101
- };
1102
- let s = text.replace(/\r\n/g, `
1103
- `);
1104
- s = s.replace(/```([\s\S]*?)```/g, (_m, body) => hold(preHtml(body)));
1105
- s = s.replace(/`([^`\n]+)`/g, (_m, body) => hold(`<code class="sm-code">${reEscape(body)}</code>`));
1106
- s = s.replace(/<([^<>\n]*)>/g, (_m, inner) => hold(renderControl(inner, ctx)));
1107
- s = renderEmoji(reEscape(s));
1108
- s = inlineStyles(s);
1109
- s = blockify(s);
1110
- const expand = (html) => html.replace(/\uE000(\d+)\uE001/g, (_m, i) => expand(tokens[Number(i)] ?? ""));
1111
- return tidy(expand(s));
1112
- }
1113
- function plainTextToHtml(text) {
1114
- if (!text)
1115
- return "";
1116
- return renderEmoji(reEscape(text.replace(/\r\n/g, `
1117
- `))).replace(/\n/g, "<br>");
1118
- }
1119
-
1120
- // src/render/blocks.ts
1121
- function rec(v) {
1122
- return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
1123
- }
1124
- function str2(v) {
1125
- return typeof v === "string" ? v : "";
1126
- }
1127
- function arr(v) {
1128
- return Array.isArray(v) ? v : [];
1129
- }
1130
- function safeUrl(url) {
1131
- return /^(https?:\/\/|\/)/i.test(url) ? escapeHtml(url) : undefined;
1132
- }
1133
- function unsupported(what) {
1134
- return `<div class="sm-unsupported">unsupported: ${escapeHtml(what || "unknown")}</div>`;
1135
- }
1136
- function textObject(v, ctx) {
1137
- if (typeof v === "string")
1138
- return plainTextToHtml(v);
1139
- const o = rec(v);
1140
- if (!o)
1141
- return "";
1142
- const text = str2(o.text);
1143
- return o.type === "mrkdwn" ? mrkdwnToHtml(text, ctx) : plainTextToHtml(text);
1144
- }
1145
- function plainOf(v) {
1146
- const o = rec(v);
1147
- return plainTextToHtml(o ? str2(o.text) : str2(v));
1148
- }
1149
- function image(url, alt, cls) {
1150
- const src = safeUrl(url);
1151
- if (!src)
1152
- return unsupported("image url");
1153
- return `<img class="${cls}" src="${src}" alt="${escapeHtml(alt)}">`;
1154
- }
1155
- function imageSrcOf(block) {
1156
- const direct = str2(block.image_url);
1157
- if (direct)
1158
- return direct;
1159
- const file = rec(block.slack_file);
1160
- return file ? str2(file.url) || str2(file.url_private) : "";
1161
- }
1162
- function button(el, ctx) {
1163
- const style = str2(el.style);
1164
- const cls = `sm-btn${style === "primary" ? " sm-btn-primary" : style === "danger" ? " sm-btn-danger" : ""}`;
1165
- const label = textObject(el.text, ctx) || "Button";
1166
- const url = safeUrl(str2(el.url));
1167
- const confirm = rec(el.confirm) ? '<span class="sm-btn-confirm" title="confirmation dialog">\u26A0</span>' : "";
1168
- return url ? `<a class="${cls}" href="${url}" target="_blank" rel="noopener">${label}${confirm}</a>` : `<span class="${cls}">${label}${confirm}</span>`;
1169
- }
1170
- function selectPill(el, ctx, glyph = "\u25BE") {
1171
- const initial = rec(el.initial_option);
1172
- const label = initial && textObject(initial.text, ctx) || textObject(el.placeholder, ctx) || plainTextToHtml(str2(el.type).replace(/_/g, " "));
1173
- return `<span class="sm-select">${label}<span class="sm-select-caret">${glyph}</span></span>`;
1174
- }
1175
- function inputBox(el, ctx) {
1176
- const multiline = el.multiline === true;
1177
- const value = str2(el.initial_value);
1178
- const inner = value ? plainTextToHtml(value) : `<span class="sm-input-ph">${textObject(el.placeholder, ctx)}</span>`;
1179
- return `<div class="sm-input${multiline ? " sm-input-multi" : ""}">${inner}</div>`;
1180
- }
1181
- function renderElement(v, ctx) {
1182
- const el = rec(v);
1183
- if (!el)
1184
- return "";
1185
- const type = str2(el.type);
1186
- switch (type) {
1187
- case "button":
1188
- return button(el, ctx);
1189
- case "image":
1190
- return image(imageSrcOf(el), str2(el.alt_text), "sm-acc-img");
1191
- case "overflow":
1192
- return `<span class="sm-select sm-overflow">\u22EF</span>`;
1193
- case "datepicker":
1194
- return selectPill({ ...el, placeholder: el.placeholder ?? "Select a date" }, ctx, "\uD83D\uDCC5");
1195
- case "timepicker":
1196
- return selectPill({ ...el, placeholder: el.placeholder ?? "Select a time" }, ctx, "\uD83D\uDD50");
1197
- case "plain_text_input":
1198
- return inputBox(el, ctx);
1199
- case "checkboxes":
1200
- case "radio_buttons":
1201
- return `<div class="sm-options">${arr(el.options).map((o) => {
1202
- const opt = rec(o);
1203
- const mark = type === "checkboxes" ? "\u2610" : "\u25EF";
1204
- return `<div class="sm-option">${mark} ${opt ? textObject(opt.text, ctx) : ""}</div>`;
1205
- }).join("")}</div>`;
1206
- default:
1207
- if (type.endsWith("_select") || type.startsWith("multi_"))
1208
- return selectPill(el, ctx);
1209
- return unsupported(type);
1210
- }
1211
- }
1212
- function richStyle(html, style) {
1213
- if (!html || !style)
1214
- return html;
1215
- let out = html;
1216
- if (style.code === true)
1217
- out = `<code class="sm-code">${out}</code>`;
1218
- if (style.bold === true)
1219
- out = `<strong>${out}</strong>`;
1220
- if (style.italic === true)
1221
- out = `<em>${out}</em>`;
1222
- if (style.strike === true)
1223
- out = `<s>${out}</s>`;
1224
- return out;
1225
- }
1226
- function richElement(v, ctx) {
1227
- const el = rec(v);
1228
- if (!el)
1229
- return "";
1230
- const style = rec(el.style);
1231
- switch (str2(el.type)) {
1232
- case "text":
1233
- return richStyle(plainTextToHtml(str2(el.text)).replace(/\n/g, "<br>"), style);
1234
- case "link": {
1235
- const url = safeUrl(str2(el.url));
1236
- const label = plainTextToHtml(str2(el.text) || str2(el.url));
1237
- if (!url)
1238
- return label;
1239
- return richStyle(`<a class="sm-link" href="${url}" target="_blank" rel="noopener">${label}</a>`, style);
1240
- }
1241
- case "user": {
1242
- const user = ctx.users.get(str2(el.user_id));
1243
- return `<span class="sm-pill">@${escapeHtml(user ? displayName(user) : str2(el.user_id))}</span>`;
1244
- }
1245
- case "usergroup":
1246
- return `<span class="sm-pill">@${escapeHtml(str2(el.usergroup_id))}</span>`;
1247
- case "channel": {
1248
- const channel = ctx.channels.get(str2(el.channel_id));
1249
- return `<span class="sm-pill">#${escapeHtml(channel ? channel.name : str2(el.channel_id))}</span>`;
1250
- }
1251
- case "broadcast":
1252
- return `<span class="sm-pill">@${escapeHtml(str2(el.range) || "channel")}</span>`;
1253
- case "emoji": {
1254
- const char = emojiChar(str2(el.name)) ?? (el.unicode ? emojiFromUnicode(str2(el.unicode)) : undefined);
1255
- return char ?? `<span class="sm-emoji-name">:${escapeHtml(str2(el.name))}:</span>`;
1256
- }
1257
- case "date":
1258
- return plainTextToHtml(str2(el.fallback) || str2(el.timestamp));
1259
- case "color":
1260
- return plainTextToHtml(str2(el.value));
1261
- default:
1262
- return "";
1263
- }
1264
- }
1265
- function richSection(v, ctx) {
1266
- const block = rec(v);
1267
- if (!block)
1268
- return "";
1269
- const inner = arr(block.elements).map((e) => richElement(e, ctx)).join("");
1270
- switch (str2(block.type)) {
1271
- case "rich_text_section":
1272
- return `<div class="sm-rt-section">${inner}</div>`;
1273
- case "rich_text_quote":
1274
- return `<blockquote class="sm-quote">${inner}</blockquote>`;
1275
- case "rich_text_preformatted":
1276
- return `<pre class="sm-pre">${inner}</pre>`;
1277
- case "rich_text_list": {
1278
- const tag = str2(block.style) === "ordered" ? "ol" : "ul";
1279
- const indent = Number(block.indent) || 0;
1280
- const items = arr(block.elements).map((item) => `<li>${richSection(item, ctx)}</li>`).join("");
1281
- const margin = indent ? ` style="margin-left:${indent * 18}px"` : "";
1282
- return `<${tag} class="sm-list"${margin}>${items}</${tag}>`;
1283
- }
1284
- default:
1285
- return inner;
1286
- }
1287
- }
1288
- function sectionBlock(block, ctx) {
1289
- const parts = [];
1290
- if (block.text)
1291
- parts.push(`<div class="sm-section-text">${textObject(block.text, ctx)}</div>`);
1292
- const fields = arr(block.fields);
1293
- if (fields.length) {
1294
- parts.push(`<div class="sm-fields">${fields.map((f) => `<div class="sm-field">${textObject(f, ctx)}</div>`).join("")}</div>`);
1295
- }
1296
- const accessory = block.accessory ? renderElement(block.accessory, ctx) : "";
1297
- const body = parts.join("");
1298
- if (!accessory)
1299
- return `<div class="sm-block sm-section">${body}</div>`;
1300
- return `<div class="sm-block sm-section sm-section-split"><div class="sm-section-main">${body}</div><div class="sm-section-acc">${accessory}</div></div>`;
1301
- }
1302
- function contextBlock(block, ctx) {
1303
- const inner = arr(block.elements).map((e) => {
1304
- const el = rec(e);
1305
- if (!el)
1306
- return "";
1307
- if (str2(el.type) === "image")
1308
- return image(imageSrcOf(el), str2(el.alt_text), "sm-context-img");
1309
- return `<span class="sm-context-text">${textObject(el, ctx)}</span>`;
1310
- }).join("");
1311
- return `<div class="sm-block sm-context">${inner}</div>`;
1312
- }
1313
- function imageBlock(block, ctx) {
1314
- const title = block.title ? `<div class="sm-img-title">${textObject(block.title, ctx)}</div>` : "";
1315
- const src = imageSrcOf(block);
1316
- const alt = str2(block.alt_text);
1317
- if (!src) {
1318
- const file = rec(block.slack_file);
1319
- return `<div class="sm-block">${title}${unsupported(`image (file ${str2(file?.id) || "?"})`)}</div>`;
1320
- }
1321
- return `<div class="sm-block sm-image">${title}${image(src, alt, "sm-img")}</div>`;
1322
- }
1323
- function inputBlock(block, ctx) {
1324
- const label = block.label ? `<div class="sm-label">${plainOf(block.label)}</div>` : "";
1325
- const element = block.element ? renderElement(block.element, ctx) : "";
1326
- const hint = block.hint ? `<div class="sm-hint">${plainOf(block.hint)}</div>` : "";
1327
- return `<div class="sm-block sm-input-block">${label}${element}${hint}</div>`;
1328
- }
1329
- function videoBlock(block, ctx) {
1330
- const thumb = safeUrl(str2(block.thumbnail_url));
1331
- const url = safeUrl(str2(block.title_url) || str2(block.video_url));
1332
- const title = textObject(block.title, ctx) || plainTextToHtml(str2(block.alt_text));
1333
- const inner = `${thumb ? `<img class="sm-video-thumb" src="${thumb}" alt="${escapeHtml(str2(block.alt_text))}">` : ""}<div class="sm-video-title">\u25B6 ${title}</div>`;
1334
- return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
1335
- }
1336
- function renderBlock(v, ctx) {
1337
- const block = rec(v);
1338
- if (!block)
1339
- return unsupported("block");
1340
- switch (str2(block.type)) {
1341
- case "header":
1342
- return `<div class="sm-block sm-header-block">${textObject(block.text, ctx)}</div>`;
1343
- case "section":
1344
- return sectionBlock(block, ctx);
1345
- case "divider":
1346
- return `<div class="sm-block"><hr class="sm-hr"></div>`;
1347
- case "context":
1348
- return contextBlock(block, ctx);
1349
- case "actions":
1350
- return `<div class="sm-block sm-actions">${arr(block.elements).map((e) => renderElement(e, ctx)).join("")}</div>`;
1351
- case "image":
1352
- return imageBlock(block, ctx);
1353
- case "rich_text":
1354
- return `<div class="sm-block sm-rich-text">${arr(block.elements).map((e) => richSection(e, ctx)).join("")}</div>`;
1355
- case "input":
1356
- return inputBlock(block, ctx);
1357
- case "file":
1358
- return `<div class="sm-block sm-file-block">\uD83D\uDCCE ${escapeHtml(str2(block.external_id) || str2(block.file_id) || "file")}</div>`;
1359
- case "video":
1360
- return videoBlock(block, ctx);
1361
- default:
1362
- return `<div class="sm-block">${unsupported(str2(block.type))}</div>`;
1363
- }
1364
- }
1365
- function renderBlocks(blocks, ctx) {
1366
- const list = arr(blocks);
1367
- if (!list.length)
1368
- return "";
1369
- return `<div class="sm-blocks">${list.map((b) => renderBlock(b, ctx)).join("")}</div>`;
1370
- }
1371
- var NAMED_COLORS = {
1372
- good: "#2eb67d",
1373
- warning: "#ecb22e",
1374
- danger: "#e01e5a"
1375
- };
1376
- function barColor(v) {
1377
- const raw = str2(v).trim();
1378
- if (!raw)
1379
- return "#dddddd";
1380
- const named = NAMED_COLORS[raw.toLowerCase()];
1381
- if (named)
1382
- return named;
1383
- const hex = raw.startsWith("#") ? raw : `#${raw}`;
1384
- return /^#[0-9a-fA-F]{3,8}$/.test(hex) ? hex : "#dddddd";
1385
- }
1386
- function attachmentFields(fields, ctx) {
1387
- if (!fields.length)
1388
- return "";
1389
- return `<div class="sm-fields">${fields.map((f) => {
1390
- const field = rec(f);
1391
- if (!field)
1392
- return "";
1393
- const wide = field.short === true ? "" : " sm-field-wide";
1394
- return `<div class="sm-field${wide}"><div class="sm-field-title">${plainTextToHtml(str2(field.title))}</div><div>${mrkdwnToHtml(str2(field.value), ctx)}</div></div>`;
1395
- }).join("")}</div>`;
1396
- }
1397
- function attachment(v, ctx) {
1398
- const att = rec(v);
1399
- if (!att)
1400
- return "";
1401
- const parts = [];
1402
- const author = str2(att.author_name);
1403
- if (author) {
1404
- const icon = safeUrl(str2(att.author_icon));
1405
- parts.push(`<div class="sm-att-author">${icon ? `<img class="sm-att-author-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(author)}</div>`);
1406
- }
1407
- const title = str2(att.title);
1408
- if (title) {
1409
- const link = safeUrl(str2(att.title_link));
1410
- const inner = plainTextToHtml(title);
1411
- parts.push(`<div class="sm-att-title">${link ? `<a class="sm-link" href="${link}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`);
1412
- }
1413
- const text = str2(att.text) || (parts.length ? "" : str2(att.fallback));
1414
- if (text)
1415
- parts.push(`<div class="sm-att-text">${mrkdwnToHtml(text, ctx)}</div>`);
1416
- parts.push(attachmentFields(arr(att.fields), ctx));
1417
- const img = safeUrl(str2(att.image_url));
1418
- if (img)
1419
- parts.push(`<img class="sm-att-img" src="${img}" alt="">`);
1420
- const thumb = !img ? safeUrl(str2(att.thumb_url)) : undefined;
1421
- if (thumb)
1422
- parts.push(`<img class="sm-att-thumb" src="${thumb}" alt="">`);
1423
- const blocks = arr(att.blocks);
1424
- if (blocks.length)
1425
- parts.push(renderBlocks(blocks, ctx));
1426
- const footer = str2(att.footer);
1427
- const ts = att.ts ? formatAttachmentTs(att.ts) : "";
1428
- if (footer || ts) {
1429
- const icon = safeUrl(str2(att.footer_icon));
1430
- parts.push(`<div class="sm-att-footer">${icon ? `<img class="sm-att-footer-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(footer)}${footer && ts ? " | " : ""}${escapeHtml(ts)}</div>`);
1431
- }
1432
- const pretext = str2(att.pretext);
1433
- const box = `<div class="sm-att" style="border-left-color:${barColor(att.color)}">${parts.join("")}</div>`;
1434
- return pretext ? `<div class="sm-att-pretext">${mrkdwnToHtml(pretext, ctx)}</div>${box}` : box;
1435
- }
1436
- function formatAttachmentTs(v) {
1437
- const secs = Number(v);
1438
- if (!Number.isFinite(secs) || secs <= 0)
1439
- return str2(v);
1440
- const d = new Date(secs * 1000);
1441
- const pad = (n) => String(n).padStart(2, "0");
1442
- return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
1443
- }
1444
- function renderAttachments(attachments, ctx) {
1445
- const list = arr(attachments);
1446
- if (!list.length)
1447
- return "";
1448
- return `<div class="sm-atts">${list.map((a) => attachment(a, ctx)).join("")}</div>`;
1449
- }
1450
-
1451
- // src/render/index.ts
1452
- var DEFAULT_PANEL_WIDTH = "50%";
1453
- var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1454
- var AVATAR_COLORS = [
1455
- "#4a154b",
1456
- "#1264a3",
1457
- "#2eb67d",
1458
- "#e01e5a",
1459
- "#e8912d",
1460
- "#007a5a",
1461
- "#7c3aed",
1462
- "#00a2ac",
1463
- "#df10a5",
1464
- "#3d5afe"
1465
- ];
1466
- var CSS = `
1467
- *{box-sizing:border-box}
1468
- html,body{margin:0;padding:0;height:100%}
1469
- body{font-family:Lato,-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,Helvetica,Arial,sans-serif;font-size:15px;line-height:1.46668;color:#1d1c1d;background:#fff;-webkit-font-smoothing:antialiased}
1470
- a{color:#1264a3;text-decoration:none}
1471
- a:hover{text-decoration:underline}
1472
- .sm-app{display:flex;height:100vh;overflow:hidden}
1473
- .sm-side{width:230px;flex:none;background:#3f0e40;color:#d9d0d9;padding:16px 0;overflow-y:auto}
1474
- .sm-side-title{color:#fff;font-weight:900;font-size:17px;padding:0 16px 12px;border-bottom:1px solid #522653;margin-bottom:10px}
1475
- .sm-side-team{display:block;font-weight:400;font-size:12px;color:#bda9bd}
1476
- .sm-side-h{font-size:13px;color:#bda9bd;padding:10px 16px 4px}
1477
- .sm-side a{display:block;color:#d9d0d9;padding:3px 16px;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1478
- .sm-side a:hover{background:#522653;color:#fff;text-decoration:none}
1479
- .sm-side a.sm-active,.sm-side a.sm-active:hover{background:#1164a3;color:#fff}
1480
- .sm-side-title a:hover{background:none;text-decoration:underline}
1481
- .sm-main{flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden}
1482
- .sm-shot{width:760px;padding:16px;background:#fff}
1483
- .sm-top{border-bottom:1px solid #e8e8e8;padding:12px 20px;display:flex;align-items:baseline;gap:12px;flex:none}
1484
- .sm-top h1{font-size:18px;font-weight:900;margin:0}
1485
- .sm-top .sm-sub{font-size:13px;color:#616061;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1486
- .sm-back{font-size:13px;font-weight:700;color:#616061;flex:none}
1487
- .sm-back:hover{color:#1264a3}
1488
- .sm-page{padding:12px 20px 32px}
1489
- .sm-main .sm-page{flex:1;overflow-y:auto}
1490
- .sm-shot .sm-page{padding:0}
1491
- .sm-shot .sm-top{padding:0 0 10px;margin-bottom:8px}
640
+ var CSS = `
641
+ *{box-sizing:border-box}
642
+ html,body{margin:0;padding:0;height:100%}
643
+ body{font-family:Lato,-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,Helvetica,Arial,sans-serif;font-size:15px;line-height:1.46668;color:#1d1c1d;background:#fff;-webkit-font-smoothing:antialiased}
644
+ a{color:#1264a3;text-decoration:none}
645
+ a:hover{text-decoration:underline}
646
+ .sm-app{display:flex;height:100vh;overflow:hidden}
647
+ .sm-side{width:230px;flex:none;background:#3f0e40;color:#d9d0d9;padding:16px 0;overflow-y:auto}
648
+ .sm-side-title{color:#fff;font-weight:900;font-size:17px;padding:0 16px 12px;border-bottom:1px solid #522653;margin-bottom:10px}
649
+ .sm-side-team{display:block;font-weight:400;font-size:12px;color:#bda9bd}
650
+ .sm-side-h{font-size:13px;color:#bda9bd;padding:10px 16px 4px}
651
+ .sm-side a{display:block;color:#d9d0d9;padding:3px 16px;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
652
+ .sm-side a:hover{background:#522653;color:#fff;text-decoration:none}
653
+ .sm-side a.sm-active,.sm-side a.sm-active:hover{background:#1164a3;color:#fff}
654
+ .sm-side-title a:hover{background:none;text-decoration:underline}
655
+ .sm-main{flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden}
656
+ .sm-shot{width:760px;padding:16px;background:#fff}
657
+ .sm-top{border-bottom:1px solid #e8e8e8;padding:12px 20px;display:flex;align-items:baseline;gap:12px;flex:none}
658
+ .sm-top h1{font-size:18px;font-weight:900;margin:0}
659
+ .sm-top .sm-sub{font-size:13px;color:#616061;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
660
+ .sm-back{font-size:13px;font-weight:700;color:#616061;flex:none}
661
+ .sm-back:hover{color:#1264a3}
662
+ .sm-page{padding:12px 20px 32px}
663
+ .sm-main .sm-page{flex:1;overflow-y:auto}
664
+ .sm-shot .sm-page{padding:0}
665
+ .sm-shot .sm-top{padding:0 0 10px;margin-bottom:8px}
1492
666
 
1493
667
  .sm-panel{width:var(--sm-panel-w,50%);min-width:360px;flex:0 1 auto;display:flex;flex-direction:column;border-left:1px solid #e8e8e8;background:#fff;overflow:hidden}
1494
668
  .sm-panel-top{display:flex;align-items:flex-start;gap:10px;padding:12px 16px;border-bottom:1px solid #e8e8e8;flex:none}
@@ -1874,474 +1048,1328 @@ function avatarHtml(m, name) {
1874
1048
  const char = emojiChar(emojiName) ?? emojiName.replace(/:/g, "");
1875
1049
  return `<div class="sm-avatar sm-avatar-emoji">${escapeHtml(char)}</div>`;
1876
1050
  }
1877
- const imageUrl = m.icons?.image_72 ?? m.icons?.image_48 ?? m.icons?.image_64;
1878
- if (imageUrl && /^(https?:\/\/|\/)/.test(imageUrl)) {
1879
- return `<div class="sm-avatar"><img src="${escapeHtml(imageUrl)}" alt=""></div>`;
1051
+ const imageUrl = m.icons?.image_72 ?? m.icons?.image_48 ?? m.icons?.image_64;
1052
+ if (imageUrl && /^(https?:\/\/|\/)/.test(imageUrl)) {
1053
+ return `<div class="sm-avatar"><img src="${escapeHtml(imageUrl)}" alt=""></div>`;
1054
+ }
1055
+ const seed = m.user ?? m.bot_id ?? name;
1056
+ const color = AVATAR_COLORS[hashIndex(seed, AVATAR_COLORS.length)];
1057
+ return `<div class="sm-avatar" style="background:${color}">${escapeHtml(initials(name))}</div>`;
1058
+ }
1059
+ function reactionsHtml(store, m, interactive, locked) {
1060
+ if (!m.reactions?.length)
1061
+ return "";
1062
+ const chips = m.reactions.map((r) => {
1063
+ const who = r.users.map((id) => {
1064
+ const user = store.users.get(id);
1065
+ return user ? displayName(user) : id;
1066
+ }).join(", ");
1067
+ const char = emojiChar(r.name) ?? `:${r.name}:`;
1068
+ const content = `${escapeHtml(char)}<span class="sm-reaction-count">${r.count}</span>`;
1069
+ return interactive ? `<button type="button" class="sm-reaction" title="${escapeHtml(who)}" data-reaction="${escapeHtml(r.name)}" data-users="${escapeHtml(JSON.stringify(r.users))}" aria-label="Add :${escapeHtml(r.name)}: reaction, ${r.count} ${r.count === 1 ? "person" : "people"} reacted" aria-pressed="false"${locked ? " disabled" : ""}>${content}</button>` : `<span class="sm-reaction" title="${escapeHtml(who)}">${content}</span>`;
1070
+ });
1071
+ return `<div class="sm-reactions">${chips.join("")}</div>`;
1072
+ }
1073
+ function messageActions(m, opts) {
1074
+ const thread = m.thread_ts ?? m.ts;
1075
+ const reactIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><circle cx="11" cy="12" r="8"/><path d="M7 14c2 3 6 3 8 0M8 9h.01M14 9h.01M20 2v6M17 5h6" stroke-linecap="round"/></svg>`;
1076
+ const replyIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6 4V6a2 2 0 0 1 2-2Z" stroke-linejoin="round"/><path d="M7 9h10M7 13h6" stroke-linecap="round"/></svg>`;
1077
+ return `<div class="sm-message-actions"><button type="button" class="sm-add-reaction" aria-label="Add reaction" aria-haspopup="dialog" aria-controls="sm-reaction-picker" title="Add reaction"${opts.writeGated ? " disabled" : ""}>${reactIcon}</button><a class="sm-reply-action" href="${threadHref(m.channel, thread, opts)}" data-thread="${escapeHtml(thread)}" aria-label="Open thread" title="Open thread">${replyIcon}</a></div><div class="sm-action-error" role="alert" hidden></div>`;
1078
+ }
1079
+ function reactionPicker() {
1080
+ const names = [
1081
+ "thumbsup",
1082
+ "green_heart",
1083
+ "eyes",
1084
+ "white_check_mark",
1085
+ "tada",
1086
+ "rocket",
1087
+ "star",
1088
+ "thinking_face",
1089
+ "sparkles",
1090
+ "fire",
1091
+ "raised_hands",
1092
+ "clap"
1093
+ ];
1094
+ const buttons = names.map((name) => `<button type="button" data-reaction="${name}" aria-label="React with ${name.replaceAll("_", " ")}" title=":${name}:">${escapeHtml(emojiChar(name) ?? `:${name}:`)}</button>`).join("");
1095
+ return `<dialog class="sm-reaction-picker" id="sm-reaction-picker" aria-labelledby="sm-reaction-title"><div class="sm-reaction-picker-head"><h2 id="sm-reaction-title">Add a reaction</h2><button type="button" class="sm-reaction-close" aria-label="Close reactions">\u2715</button></div><div class="sm-reaction-choices">${buttons}</div><div class="sm-action-error" role="alert" hidden></div></dialog>`;
1096
+ }
1097
+ function fileUrl(f, token) {
1098
+ if (!f.url_private)
1099
+ return "";
1100
+ return escapeHtml(`${f.url_private}${f.url_private.includes("?") ? "&" : "?"}t=${token}`);
1101
+ }
1102
+ function filesHtml(files, token) {
1103
+ if (!files?.length)
1104
+ return "";
1105
+ const cards = files.map((f) => {
1106
+ if (f.mimetype?.startsWith("image/") && f.url_private) {
1107
+ return `<img class="sm-file-img" src="${fileUrl(f, token)}" alt="${escapeHtml(f.title || f.name)}">`;
1108
+ }
1109
+ const href = fileUrl(f, token);
1110
+ const name = escapeHtml(f.title || f.name);
1111
+ const meta = `${escapeHtml(f.pretty_type || f.filetype || "File")} \xB7 ${fileSize(f.size ?? 0)}`;
1112
+ const label = href ? `<a href="${href}">${name}</a>` : name;
1113
+ return `<div class="sm-file-card"><div class="sm-file-icon">\uD83D\uDCC4</div><div><div class="sm-file-name">${label}</div><div class="sm-file-meta">${meta}</div></div></div>`;
1114
+ });
1115
+ return `<div class="sm-files">${cards.join("")}</div>`;
1116
+ }
1117
+ function renderMessage(store, ctx, m, opts, flags = {}) {
1118
+ const name = authorName(store, m);
1119
+ const isApp = Boolean(m.bot_id);
1120
+ const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
1121
+ const interactive = !opts.screenshot && !flags.ephemeral && humanUsers(store).length > 0;
1122
+ const body = [];
1123
+ if (m.streaming_state !== undefined && !m.stream_replaced) {
1124
+ if (m.text)
1125
+ body.push(`<div class="sm-text">${markdownToHtml(m.text, ctx)}</div>`);
1126
+ if (blocks)
1127
+ body.push(renderBlocks(blocks, ctx));
1128
+ } else if (blocks)
1129
+ body.push(renderBlocks(blocks, ctx));
1130
+ else if (m.text)
1131
+ body.push(`<div class="sm-text">${m.text_format === "markdown" ? markdownToHtml(m.text, ctx) : mrkdwnToHtml(m.text, ctx)}</div>`);
1132
+ if (m.edited)
1133
+ body.push(`<div class="sm-edited">(edited)</div>`);
1134
+ if (m.attachments?.length)
1135
+ body.push(renderAttachments(m.attachments, ctx));
1136
+ body.push(filesHtml(m.files, store.bot.token));
1137
+ body.push(reactionsHtml(store, m, interactive, Boolean(opts.writeGated)));
1138
+ if (flags.ephemeral)
1139
+ body.push(`<div class="sm-eph-note">Only visible to you</div>`);
1140
+ if (flags.threadLink && m.reply_count) {
1141
+ const count = `${m.reply_count} ${m.reply_count === 1 ? "reply" : "replies"}`;
1142
+ const last = m.latest_reply ? `<span class="sm-replies-time">Last reply ${timeOf(m.latest_reply)}</span>` : "";
1143
+ body.push(`<a class="sm-replies" href="${threadHref(m.channel, m.thread_ts ?? m.ts, opts)}">${count}${last}</a>`);
1144
+ }
1145
+ if (interactive)
1146
+ body.push(messageActions(m, opts));
1147
+ const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
1148
+ const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
1149
+ 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>`;
1150
+ }
1151
+ function renderMessageList(store, ctx, messages, opts, flags = {}) {
1152
+ const out = [];
1153
+ let day = "";
1154
+ for (const m of messages) {
1155
+ const label = flags.dividers === false ? "" : dayLabel(m.ts);
1156
+ if (label && label !== day) {
1157
+ day = label;
1158
+ out.push(`<div class="sm-daydiv"><span>${escapeHtml(label)}</span></div>`);
1159
+ }
1160
+ out.push(renderMessage(store, ctx, m, opts, { ...flags, ephemeral: m._ephemeral === true }));
1161
+ }
1162
+ return out.join("");
1163
+ }
1164
+ function sidebar(store, opts, active) {
1165
+ const channels = [...store.channels.values()].sort((a, b) => channelLabel(store, a).localeCompare(channelLabel(store, b)));
1166
+ const links = channels.map((c) => `<a class="${c.id === active ? "sm-active" : ""}" href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a>`).join("");
1167
+ const options = channels.map((c) => `<option value="${escapeHtml(channelHref(c.id, opts))}"${c.id === active ? " selected" : ""}>${escapeHtml(channelLabel(store, c))}</option>`).join("");
1168
+ const mobile = `<div class="sm-mobile-bar"><div class="sm-mobile-heading"><a class="sm-mobile-workspace" href="${homeHref(opts)}">${escapeHtml(store.team.name)}</a>${identityChip(store, opts)}</div><select class="sm-channel-switch" aria-label="Channel"><option value="${homeHref(opts)}"${active ? "" : " selected"}>Workspace</option>${options}</select></div>`;
1169
+ return `${mobile}<nav class="sm-side"><div class="sm-side-title"><a href="${homeHref(opts)}" style="color:#fff">${escapeHtml(store.team.name)}</a><span class="sm-side-team">${escapeHtml(store.team.id)} \xB7 slack-mock</span></div><div class="sm-side-h">Channels</div>${links}</nav>`;
1170
+ }
1171
+ function shell(store, opts, parts) {
1172
+ const refresh = opts.refreshSec && !opts.screenshot ? `<meta http-equiv="refresh" content="${Math.max(1, Math.floor(opts.refreshSec))}">` : "";
1173
+ const style = opts.screenshot ? "" : ` style="--sm-panel-w:${panelWidth(opts)}"`;
1174
+ const head = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>${escapeHtml(parts.title)}</title>${refresh}<style>${CSS}</style></head>`;
1175
+ if (opts.screenshot) {
1176
+ return `${head}<body><div class="sm-shot">${parts.header}<div class="sm-page">${parts.main}</div></div></body></html>`;
1177
+ }
1178
+ const app = `sm-app${parts.panel ? " sm-app-thread" : ""}`;
1179
+ const handle = parts.panel ? `<div class="sm-resize" title="Drag to resize, double-click to reset"></div>` : "";
1180
+ return `${head}<body${style}><div class="${app}">${sidebar(store, opts, parts.active)}<div class="sm-main">${parts.header}<div class="sm-page sm-scroll">${parts.main}</div>${parts.footer ?? ""}</div>${handle}${parts.panel ?? ""}</div>${parts.script ?? ""}</body></html>`;
1181
+ }
1182
+ function topbar(title, sub, back, actions) {
1183
+ const backLink = back ? `<a class="sm-back" href="${back.href}">${escapeHtml(back.label)}</a>` : "";
1184
+ const right = actions ? `<div class="sm-top-actions">${actions}</div>` : "";
1185
+ return `<div class="sm-top">${backLink}<h1>${title}</h1>${sub ? `<div class="sm-sub">${sub}</div>` : ""}${right}</div>`;
1186
+ }
1187
+ function indexView(store, opts) {
1188
+ const cards = [
1189
+ ["Workspace", escapeHtml(store.team.name)],
1190
+ ["Team id", escapeHtml(store.team.id)],
1191
+ ["Bot user", escapeHtml(`${store.app.name} (${store.bot.userId})`)],
1192
+ ["Connections", String(opts.connections ?? 0)]
1193
+ ].map(([k, v]) => `<div class="sm-card"><div class="sm-card-k">${k}</div><div class="sm-card-v">${v}</div></div>`).join("");
1194
+ const channels = [...store.channels.values()];
1195
+ const channelRows = channels.map((c) => {
1196
+ const count = store.messages.get(c.id)?.length ?? 0;
1197
+ return `<tr><td data-label="Name"><a href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a></td><td data-label="Type"><span class="sm-tag">${channelKind(c)}</span></td><td class="sm-muted" data-label="Id">${c.id}</td><td data-label="Messages">${count}</td></tr>`;
1198
+ }).join("");
1199
+ const userRows = [...store.users.values()].map((u) => `<tr><td data-label="Name">${escapeHtml(u.name)}${userStatus(u)}</td><td data-label="Real name">${escapeHtml(u.real_name)}</td><td class="sm-muted" data-label="Title">${escapeHtml(u.profile.title ?? "")}</td><td class="sm-muted" data-label="Email">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted" data-label="Id">${u.id}</td><td data-label="Type">${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`).join("");
1200
+ const main = `<div class="sm-cards">${cards}</div>
1201
+ <div class="sm-h2">Channels</div>
1202
+ ${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>`}
1203
+ <div class="sm-h2">Users</div>
1204
+ <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>`;
1205
+ return shell(store, opts, {
1206
+ title: `${store.team.name} \xB7 slack-mock`,
1207
+ header: topbar(escapeHtml(store.team.name), "slack-mock workspace", undefined, identityChip(store, opts)),
1208
+ main,
1209
+ script: opts.screenshot ? "" : uiScript(store, opts, undefined, false)
1210
+ });
1211
+ }
1212
+ function channelMessages(store, channel) {
1213
+ const history = store.history(channel.id, { limit: 1000 }).items;
1214
+ const ephemerals = store.ephemerals.filter((e) => e.channel === channel.id).map((e) => ({ ...e, _ephemeral: true }));
1215
+ return [...history, ...ephemerals].sort((a, b) => Number(a.ts) - Number(b.ts));
1216
+ }
1217
+ function channelColumn(store, ctx, opts, channel, openTs) {
1218
+ const messages = channelMessages(store, channel);
1219
+ if (!messages.length)
1220
+ return `<div class="sm-empty">No messages yet</div>`;
1221
+ return renderMessageList(store, ctx, messages, opts, {
1222
+ threadLink: true,
1223
+ dividers: true,
1224
+ openTs
1225
+ });
1226
+ }
1227
+ function channelHeader(store, opts, channel) {
1228
+ const sub = [channel.topic.value, channel.purpose.value].filter(Boolean).join(" \xB7 ");
1229
+ const back = opts.screenshot ? undefined : { href: homeHref(opts), label: "\u2190 Workspace" };
1230
+ return topbar(escapeHtml(channelLabel(store, channel)), escapeHtml(sub), back, identityChip(store, opts));
1231
+ }
1232
+ function humanUsers(store) {
1233
+ return [...store.users.values()].filter((u) => !u.is_bot && !u.deleted);
1234
+ }
1235
+ function userStatus(user) {
1236
+ return user.profile.status_text ? `<span class="sm-user-status">${escapeHtml(user.profile.status_text)}</span>` : "";
1237
+ }
1238
+ function identityChip(store, opts) {
1239
+ if (opts.screenshot)
1240
+ return "";
1241
+ const users = humanUsers(store);
1242
+ const selected = users[0];
1243
+ if (!selected)
1244
+ return "";
1245
+ const name = selected.real_name || selected.name;
1246
+ const avatar = `<span class="sm-identity-avatar" style="background:${AVATAR_COLORS[hashIndex(selected.id, AVATAR_COLORS.length)]}">${escapeHtml(initials(name))}</span>`;
1247
+ const items = users.map((u) => {
1248
+ const real = u.real_name || u.name;
1249
+ const color = AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)];
1250
+ return `<li><button type="button" data-user="${escapeHtml(u.id)}"><span class="sm-identity-avatar" style="background:${color}">${escapeHtml(initials(real))}</span><span>${escapeHtml(real)}${userStatus(u)}</span><span class="sm-identity-user">@${escapeHtml(u.name)}</span></button></li>`;
1251
+ }).join("");
1252
+ const hidden = opts.writeGated ? " hidden" : "";
1253
+ return `<details class="sm-identity"${hidden}><summary title="Change posting identity" aria-label="Posting as ${escapeHtml(name)}">${avatar}<span class="sm-identity-name">${escapeHtml(name)}</span></summary><ul class="sm-identity-list">${items}</ul></details>`;
1254
+ }
1255
+ function composer(store, opts, channel, threadTs) {
1256
+ if (opts.screenshot)
1257
+ return "";
1258
+ const users = humanUsers(store);
1259
+ if (!users.length)
1260
+ return "";
1261
+ const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
1262
+ const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
1263
+ const gated = opts.writeGated ? ' data-gated="1"' : "";
1264
+ const lock = opts.writeGated ? `<div class="sm-composer-lock" hidden><span>Reading is open. Sign in to post.</span><input class="sm-lock-user" placeholder="user" autocomplete="username"><input class="sm-lock-pass" type="password" placeholder="password" autocomplete="current-password"><button type="button" class="sm-lock-go">Sign in</button><span class="sm-err"></span></div>` : "";
1265
+ return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}${gated}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}" data-placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><button type="button" class="sm-composer-send">Send</button></div></div>${lock}<div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention<span class="sm-lock-state"></span></div></div>`;
1266
+ }
1267
+ function mentionData(store) {
1268
+ const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
1269
+ id: u.id,
1270
+ name: u.name,
1271
+ real: u.real_name || u.name,
1272
+ initials: initials(u.real_name || u.name),
1273
+ color: AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)],
1274
+ bot: u.is_bot
1275
+ }));
1276
+ const json = JSON.stringify(users).replace(/</g, "\\u003c");
1277
+ return `<script type="application/json" id="sm-users">${json}</script>`;
1278
+ }
1279
+ function uiScript(store, opts, closeUrl, autoScroll = true) {
1280
+ const esc = closeUrl ? `document.addEventListener("keydown",function(e){if(e.key==="Escape"&&!/^(TEXTAREA|INPUT|SELECT)$/.test(document.activeElement&&document.activeElement.tagName||""))location.href=${JSON.stringify(closeUrl)}});` : "";
1281
+ const body = `(function(){
1282
+ var viewport=window.visualViewport;
1283
+ function fitViewport(){if(viewport&&viewport.scale!==1)return;var style=document.documentElement.style;style.setProperty("--sm-viewport-height",(viewport?viewport.height:innerHeight)+"px");style.setProperty("--sm-viewport-top",(viewport?viewport.offsetTop:0)+"px")}
1284
+ fitViewport();addEventListener("resize",fitViewport);
1285
+ if(viewport){viewport.addEventListener("resize",fitViewport);viewport.addEventListener("scroll",fitViewport)}
1286
+ document.addEventListener("change",function(e){if(e.target.classList.contains("sm-channel-switch"))location.href=e.target.value});
1287
+ var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
1288
+ ${autoScroll ? `function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}
1289
+ scroll();addEventListener("load",scroll);` : ""}
1290
+ var handle=document.querySelector(".sm-resize");
1291
+ if(handle){
1292
+ var saved=null;try{saved=localStorage.getItem(W)}catch(e){}
1293
+ if(!FIXED&&saved)document.body.style.setProperty("--sm-panel-w",saved);
1294
+ var dragging=false;
1295
+ handle.addEventListener("mousedown",function(e){dragging=true;handle.classList.add("sm-dragging");e.preventDefault()});
1296
+ document.addEventListener("mousemove",function(e){if(!dragging)return;var w=Math.round(Math.min(Math.max(innerWidth-e.clientX,360),Math.max(innerWidth-320,360)));document.body.style.setProperty("--sm-panel-w",w+"px")});
1297
+ document.addEventListener("mouseup",function(){if(!dragging)return;dragging=false;handle.classList.remove("sm-dragging");try{localStorage.setItem(W,document.body.style.getPropertyValue("--sm-panel-w"))}catch(e){}});
1298
+ handle.addEventListener("dblclick",function(){try{localStorage.removeItem(W)}catch(e){}document.body.style.setProperty("--sm-panel-w",DEF)});
1299
+ }
1300
+ var raw=document.getElementById("sm-users");
1301
+ var USERS=raw?JSON.parse(raw.textContent||"[]"):[],HUMANS=USERS.filter(function(u){return !u.bot});
1302
+ var PEOPLE=USERS.concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
1303
+ function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&amp;":c==="<"?"&lt;":c===">"?"&gt;":"&quot;"})}
1304
+ var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter",IK="sm-identity",currentIdentity="",identityStorage=true;
1305
+ function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
1306
+ function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
1307
+ function setIdentity(v){currentIdentity=v;try{if(v)localStorage.setItem(IK,v);else localStorage.removeItem(IK)}catch(e){identityStorage=false}}
1308
+ function findIdentity(value,key){for(var i=0;i<HUMANS.length;i++)if(HUMANS[i][key]===value)return HUMANS[i];return null}
1309
+ function identity(){var id=currentIdentity;if(identityStorage)try{id=localStorage.getItem(IK)||currentIdentity}catch(e){identityStorage=false}currentIdentity=id;var u=findIdentity(id,"id");if(!u&&HUMANS.length){u=HUMANS[0];setIdentity(u.id)}return u}
1310
+ (function(){var url=null,name=null;try{url=new URL(location.href);name=url.searchParams.get("as")}catch(e){}if(url&&name!==null){var u=findIdentity(name,"name");if(u)setIdentity(u.id);url.searchParams.delete("as");var search=url.searchParams.toString();history.replaceState(null,"",url.pathname+(search?"?"+search:"")+url.hash)}})();
1311
+ (function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
1312
+ function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
1313
+ var reactionDialog=document.querySelector(".sm-reaction-picker"),reactionTarget=null,reactionScope=null,reactionBusy=false;
1314
+ function closeReactions(restoreFocus){var button=reactionTarget&&reactionTarget.querySelector(".sm-add-reaction");if(reactionDialog&&reactionDialog.open)reactionDialog.close();reactionTarget=null;reactionScope=null;if(restoreFocus&&button&&button.isConnected&&!button.disabled)button.focus({preventScroll:true})}
1315
+ function findMessageElement(scope,ts){var found=null;if(scope)scope.querySelectorAll(".sm-msg[data-ts]").forEach(function(message){if(message.dataset.ts===ts)found=message});return found}
1316
+ function positionReactions(){
1317
+ if(!reactionDialog||!reactionDialog.open||!reactionTarget)return;
1318
+ if(!reactionTarget.isConnected){reactionTarget=findMessageElement(reactionScope,reactionTarget.dataset.ts);if(!reactionTarget){closeReactions();return}}
1319
+ var button=reactionTarget.querySelector(".sm-add-reaction"),anchor=button.getBoundingClientRect(),v=window.visualViewport,left=v?v.offsetLeft:0,top=v?v.offsetTop:0,width=v?v.width:innerWidth,height=v?v.height:innerHeight,scope=reactionScope.getBoundingClientRect(),pad=12,gap=8;
1320
+ if(anchor.bottom<=Math.max(top,scope.top)||anchor.top>=Math.min(top+height,scope.bottom)){closeReactions();return}
1321
+ reactionDialog.style.maxWidth=Math.max(0,width-pad*2)+"px";reactionDialog.style.maxHeight=Math.max(0,height-pad*2)+"px";
1322
+ var rect=reactionDialog.getBoundingClientRect(),x=Math.max(left+pad,Math.min(anchor.right-rect.width,left+width-rect.width-pad)),y=anchor.bottom+gap;
1323
+ if(y+rect.height>top+height-pad)y=anchor.top-rect.height-gap;
1324
+ reactionDialog.style.left=x+"px";reactionDialog.style.top=Math.max(top+pad,Math.min(y,top+height-rect.height-pad))+"px";
1325
+ }
1326
+ document.addEventListener("scroll",function(e){if(!reactionDialog.contains(e.target))positionReactions()},true);
1327
+ addEventListener("resize",positionReactions);
1328
+ if(window.visualViewport){window.visualViewport.addEventListener("resize",positionReactions);window.visualViewport.addEventListener("scroll",positionReactions)}
1329
+ document.addEventListener("pointerdown",function(e){if(reactionDialog.open&&!reactionDialog.contains(e.target)&&!e.target.closest(".sm-add-reaction"))closeReactions()});
1330
+ document.addEventListener("focusin",function(e){if(reactionDialog.open&&!reactionDialog.contains(e.target)&&(!reactionTarget||e.target!==reactionTarget.querySelector(".sm-add-reaction")))closeReactions()});
1331
+ function hasReaction(button,user){return JSON.parse(button.dataset.users||"[]").indexOf(user)!==-1}
1332
+ function reactionUi(root){var u=identity(),locked=(GATED&&!cred())||!u;(root||document).querySelectorAll(".sm-add-reaction,.sm-reaction[data-reaction],.sm-reaction-choices button").forEach(function(button){button.disabled=locked||reactionBusy;if(button.classList.contains("sm-reaction")){var mine=Boolean(u&&hasReaction(button,u.id)),count=button.querySelector(".sm-reaction-count").textContent;button.setAttribute("aria-pressed",String(mine));button.setAttribute("aria-label",(mine?"Remove":"Add")+" :"+button.dataset.reaction+": reaction, "+count+" "+(count==="1"?"person":"people")+" reacted")}});if(locked)closeReactions()}
1333
+ function identityUi(){var u=identity();document.querySelectorAll(".sm-identity").forEach(function(chip){chip.hidden=GATED&&!cred();if(!u)return;var av=chip.querySelector("summary .sm-identity-avatar"),name=chip.querySelector(".sm-identity-name"),summary=chip.querySelector("summary");if(av){av.textContent=u.initials;av.style.backgroundColor=u.color}if(name)name.textContent=u.real;if(summary)summary.setAttribute("aria-label","Posting as "+u.real);chip.querySelectorAll("[data-user]").forEach(function(button){if(button.dataset.user===u.id)button.setAttribute("aria-current","true");else button.removeAttribute("aria-current")})});reactionUi()}
1334
+ function lockUi(){document.querySelectorAll(".sm-composer").forEach(function(box){var locked=GATED&&!cred(),lock=box.querySelector(".sm-composer-lock"),ta=box.querySelector(".sm-composer-text"),btn=box.querySelector(".sm-composer-send"),state=box.querySelector(".sm-lock-state");if(lock)lock.hidden=!locked;ta.disabled=locked;btn.disabled=locked;ta.placeholder=locked?"Sign in to post":(ta.dataset.placeholder||"");if(state)state.innerHTML=GATED&&!locked?' \xB7 signed in \xB7 <a href="#" class="sm-lock-out">Sign out</a>':""});identityUi()}
1335
+ function signIn(box){if(!box)return;var u=box.querySelector(".sm-lock-user").value.trim(),p=box.querySelector(".sm-lock-pass").value,err=box.querySelector(".sm-err");if(!u){err.textContent="Enter the presenter user";return}var c=btoa(u+":"+p);err.textContent="";fetch("/mock/presenter",{headers:{authorization:"Basic "+c}}).then(function(r){if(!r.ok)throw new Error(r.status===401||r.status===403?"Wrong user or password":"Sign-in failed ("+r.status+")");setCred(c);lockUi();box.querySelector(".sm-composer-text").focus()}).catch(function(e){err.textContent=e.message})}
1336
+ document.addEventListener("click",function(e){var pick=e.target.closest(".sm-identity-list button");if(pick){setIdentity(pick.dataset.user);identityUi();pick.closest(".sm-identity").open=false;return}if(!e.target.closest(".sm-identity"))document.querySelectorAll(".sm-identity[open]").forEach(function(chip){chip.open=false});var out=e.target.closest(".sm-lock-out");if(out){e.preventDefault();setCred("");lockUi();return}var go=e.target.closest(".sm-lock-go");if(go)signIn(go.closest(".sm-composer"))});
1337
+ document.addEventListener("keydown",function(e){if(e.key!=="Escape")return;var chip=document.querySelector(".sm-identity[open]");if(!chip)return;e.preventDefault();e.stopImmediatePropagation();chip.open=false;chip.querySelector("summary").focus()});
1338
+ document.addEventListener("keydown",function(e){if(e.key==="Escape"&&reactionDialog&&reactionDialog.open){e.preventDefault();e.stopImmediatePropagation();closeReactions(true)}});
1339
+ document.addEventListener("keydown",function(e){var c=e.target.classList;if(e.key==="Enter"&&c&&(c.contains("sm-lock-pass")||c.contains("sm-lock-user"))){e.preventDefault();signIn(e.target.closest(".sm-composer"))}});
1340
+ addEventListener("storage",function(e){if(e.key===IK){currentIdentity=e.newValue||"";identityUi()}});
1341
+ lockUi();
1342
+ var pending=null;
1343
+ function refresh(){if(pending)return;pending=setTimeout(function(){pending=null;fetch(location.href,{headers:{accept:"text/html"},credentials:"same-origin"}).then(function(r){return r.ok?r.text():Promise.reject(r.status)}).then(apply).catch(function(){reactionUi()})},120)}
1344
+ function apply(html){
1345
+ var doc=new DOMParser().parseFromString(html,"text/html"),opener=document.activeElement,focusedMessage=opener&&opener.classList.contains("sm-add-reaction")?opener.closest(".sm-msg"):null,focusedScope=focusedMessage&&focusedMessage.closest(".sm-page,.sm-panel-body");
1346
+ reactionUi();reactionUi(doc);[".sm-side",".sm-channel-switch",".sm-page",".sm-panel-body"].forEach(function(sel){var cur=document.querySelector(sel),nxt=doc.querySelector(sel);if(!cur||!nxt)return;var seen={};cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){el.classList.remove("sm-msg-new","sm-msg-changed");seen[el.dataset.ts]=el.outerHTML});var atBottom=cur.scrollHeight-cur.scrollTop-cur.clientHeight<80;cur.innerHTML=nxt.innerHTML;cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){var prev=seen[el.dataset.ts];if(prev===undefined)el.classList.add("sm-msg-new");else if(prev!==el.outerHTML)el.classList.add("sm-msg-changed")});if(atBottom)cur.scrollTop=cur.scrollHeight});identityUi();positionReactions();if(doc.title)document.title=doc.title;
1347
+ if(focusedMessage&&!opener.isConnected){var message=findMessageElement(focusedScope,focusedMessage.dataset.ts);if(message)message.querySelector(".sm-add-reaction").focus({preventScroll:true})}
1348
+ }
1349
+ if(LIVE&&window.EventSource){
1350
+ var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
1351
+ if(chan){
1352
+ var h1=document.querySelector(".sm-top h1"),dot=null;
1353
+ if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="\u25CF live";h1.appendChild(dot)}
1354
+ var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
1355
+ es.addEventListener("change",refresh);
1356
+ es.onopen=function(){if(dot){dot.textContent="\u25CF live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
1357
+ es.onerror=function(){down=true;if(dot){dot.textContent="\u25CF reconnecting";dot.classList.add("sm-live-off")}};
1358
+ }
1359
+ }
1360
+ function react(message,name){
1361
+ var u=identity();if(!message||!u||reactionBusy||(GATED&&!cred()))return;
1362
+ var action="add";message.querySelectorAll(".sm-reaction[data-reaction]").forEach(function(button){if(button.dataset.reaction===name&&hasReaction(button,u.id))action="remove"});
1363
+ var err=(reactionDialog&&reactionDialog.open?reactionDialog:message).querySelector(".sm-action-error");if(err){err.hidden=true;err.textContent=""}
1364
+ reactionBusy=true;reactionUi();
1365
+ fetch("/mock/reactions",{method:"POST",headers:authHeaders({"content-type":"application/json"}),body:JSON.stringify({channel:message.dataset.channel,ts:message.dataset.ts,name:name,user:u.id,action:action})}).then(function(r){
1366
+ if(r.status===401||r.status===403){setCred("");lockUi();throw new Error("Sign in to react.")}
1367
+ return r.json().then(function(data){if(!r.ok&&data.error!=="already_reacted"&&data.error!=="no_reaction")throw new Error("Could not save the reaction. Try again.")})
1368
+ }).then(function(){reactionBusy=false;reactionUi();closeReactions(true);refresh()}).catch(function(e){reactionBusy=false;reactionUi();if(err){if(err.closest("dialog")&&!reactionDialog.open)err=message.querySelector(".sm-action-error");err.textContent=e.message==="Sign in to react."?e.message:"Could not save the reaction. Try again.";err.hidden=false;positionReactions()}})
1369
+ }
1370
+ document.addEventListener("click",function(e){
1371
+ var add=e.target.closest(".sm-add-reaction");if(add&&!add.disabled){var message=add.closest(".sm-msg");if(reactionDialog.open&&reactionTarget===message){closeReactions(true);return}reactionTarget=message;reactionScope=message.closest(".sm-page,.sm-panel-body");var err=reactionDialog.querySelector(".sm-action-error");err.hidden=true;err.textContent="";if(!reactionDialog.open)reactionDialog.show();positionReactions();return}
1372
+ var choice=e.target.closest("button[data-reaction]");if(choice&&!choice.disabled){react(choice.closest(".sm-reaction-picker")?reactionTarget:choice.closest(".sm-msg"),choice.dataset.reaction);return}
1373
+ if(e.target.closest(".sm-reaction-close")){closeReactions(true);return}
1374
+ var reply=e.target.closest(".sm-reply-action"),box=document.querySelector(".sm-composer[data-thread]");if(reply&&box&&box.dataset.thread===reply.dataset.thread&&box.dataset.channel===reply.closest(".sm-msg").dataset.channel)e.preventDefault()
1375
+ });
1376
+ function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim(),user=identity();if(!text||t.disabled||!user)return;var body={channel:box.dataset.channel,user:user.id,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:authHeaders({"content-type":"application/json"}),body:JSON.stringify(body)}).then(function(r){t.disabled=false;if(r.status===401||r.status===403){setCred("");lockUi();var err=box.querySelector(".sm-err");if(err)err.textContent="Not signed in, or the credential changed. Sign in to post.";return}if(!r.ok)throw new Error("send failed "+r.status);t.value="";if(LIVE)refresh();else location.reload()}).catch(function(){t.disabled=false})}
1377
+ document.querySelectorAll(".sm-composer").forEach(function(box){
1378
+ var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
1379
+ function close(){items=[];menu.style.display="none"}
1380
+ function prefix(){var m=/(?:^|\\s)@(\\w*)$/.exec(ta.value.slice(0,ta.selectionStart));return m?m[1]:null}
1381
+ function paint(){menu.querySelectorAll(".sm-mention").forEach(function(el,i){el.className="sm-mention"+(i===active?" sm-mention-on":"")})}
1382
+ function show(){
1383
+ var q=prefix();if(q===null)return close();
1384
+ var low=q.toLowerCase();
1385
+ var list=PEOPLE.filter(function(u){return !low||u.name.toLowerCase().indexOf(low)===0||u.real.toLowerCase().indexOf(low)===0}).slice(0,8);
1386
+ if(!list.length)return close();
1387
+ items=list;active=0;
1388
+ menu.innerHTML=list.map(function(u,i){return '<div class="sm-mention'+(i?"":" sm-mention-on")+'" data-i="'+i+'"><span class="sm-mention-av" style="background:'+esc(u.color)+'">'+esc(u.initials)+'</span><span class="sm-mention-name">@'+esc(u.name)+'</span><span class="sm-mention-real">'+esc(u.real)+'</span></div>'}).join("");
1389
+ menu.style.display="block";
1390
+ }
1391
+ function pick(i){var u=items[i];if(!u)return;var pos=ta.selectionStart,before=ta.value.slice(0,pos).replace(/@\\w*$/,"@"+u.name+" "),after=ta.value.slice(pos);ta.value=before+after;ta.selectionStart=ta.selectionEnd=before.length;close();ta.focus()}
1392
+ ta.addEventListener("input",show);
1393
+ ta.addEventListener("blur",function(){setTimeout(close,150)});
1394
+ menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
1395
+ ta.addEventListener("keydown",function(e){
1396
+ if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
1397
+ var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
1398
+ for(var k=0;k<PEOPLE.length;k++){var tok="@"+PEOPLE[k].name;var cand=before.endsWith(tok)?tok:"";if(cand&&cand.length>hit.length){var at=before.length-cand.length;if(at===0||/s/.test(before.charAt(at-1)))hit=cand}}
1399
+ if(hit){e.preventDefault();ta.value=before.slice(0,before.length-hit.length)+ta.value.slice(pos);ta.selectionStart=ta.selectionEnd=pos-hit.length;close();return}
1400
+ }
1401
+ if(items.length){
1402
+ if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
1403
+ if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
1404
+ if(e.key==="Enter"||e.key==="Tab"){e.preventDefault();pick(active);return}
1405
+ if(e.key==="Escape"){e.preventDefault();e.stopPropagation();close();return}
1406
+ }
1407
+ if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send(box)}
1408
+ });
1409
+ box.querySelector(".sm-composer-send").addEventListener("click",function(){send(box)});
1410
+ });
1411
+ })();`;
1412
+ return `${mentionData(store)}${reactionPicker()}<script>${body}${esc}</script>`;
1413
+ }
1414
+ function channelView(store, opts, channelId) {
1415
+ const channel = store.channels.get(channelId);
1416
+ const ctx = ctxOf(store);
1417
+ if (!channel)
1418
+ return notFound(store, opts, "Channel not found");
1419
+ const label = channelLabel(store, channel);
1420
+ return shell(store, opts, {
1421
+ title: `${label} \xB7 slack-mock`,
1422
+ header: channelHeader(store, opts, channel),
1423
+ main: channelColumn(store, ctx, opts, channel),
1424
+ active: channel.id,
1425
+ footer: composer(store, opts, channel),
1426
+ script: opts.screenshot ? "" : uiScript(store, opts)
1427
+ });
1428
+ }
1429
+ function assistantPanel(store, channelId, ts) {
1430
+ const thread = store.assistantThreads.get(`${channelId}:${ts}`);
1431
+ if (!thread)
1432
+ return "";
1433
+ const parts = [];
1434
+ if (thread.title)
1435
+ parts.push(`<div class="sm-assist-title">${plainTextToHtml(thread.title)}</div>`);
1436
+ if (thread.status)
1437
+ parts.push(`<div class="sm-assist-status">${plainTextToHtml(thread.status)}<span class="sm-stream">\u2022\u2022\u2022</span></div>`);
1438
+ const prompts = Array.isArray(thread.prompts) ? thread.prompts : [];
1439
+ if (prompts.length) {
1440
+ const chips = prompts.map((p) => {
1441
+ const prompt = typeof p === "object" && p !== null ? p : {};
1442
+ const title = typeof prompt.title === "string" ? prompt.title : "";
1443
+ const message = typeof prompt.message === "string" ? prompt.message : "";
1444
+ return `<span class="sm-prompt" title="${escapeHtml(message)}">${plainTextToHtml(title || message)}</span>`;
1445
+ }).join("");
1446
+ const heading = thread.promptsTitle ? `<div class="sm-assist-status">${plainTextToHtml(thread.promptsTitle)}</div>` : "";
1447
+ parts.push(`${heading}<div class="sm-prompts">${chips}</div>`);
1448
+ }
1449
+ if (!parts.length)
1450
+ return "";
1451
+ return `<div class="sm-assist">${parts.join("")}</div>`;
1452
+ }
1453
+ function threadView(store, opts, channelId, ts) {
1454
+ const channel = store.channels.get(channelId);
1455
+ const ctx = ctxOf(store);
1456
+ if (!channel)
1457
+ return notFound(store, opts, "Channel not found");
1458
+ const parent = store.findMessage(channel.id, ts);
1459
+ if (!parent)
1460
+ return notFound(store, opts, "Message not found");
1461
+ const items = store.replies(channel.id, ts, { limit: 1000 }).items;
1462
+ const replies = items.slice(1);
1463
+ const label = channelLabel(store, channel);
1464
+ const repliesBar = replies.length ? `<div class="sm-daydiv"><span>${replies.length} ${replies.length === 1 ? "reply" : "replies"}</span></div>` : `<div class="sm-empty">No replies yet</div>`;
1465
+ const body = `${assistantPanel(store, channel.id, ts)}${renderMessage(store, ctx, parent, opts)}${repliesBar}${renderMessageList(store, ctx, replies, opts, { dividers: false })}`;
1466
+ if (opts.screenshot) {
1467
+ const header = topbar(`Thread <span class="sm-muted">\xB7</span> <a href="${channelHref(channel.id, opts)}">${escapeHtml(label)}</a>`, "");
1468
+ return shell(store, opts, {
1469
+ title: `Thread \xB7 ${label}`,
1470
+ header,
1471
+ main: body,
1472
+ active: channel.id
1473
+ });
1474
+ }
1475
+ const close = channelHref(channel.id, opts);
1476
+ const title = `Thread \xB7 ${label}`;
1477
+ if (opts.threadView === "full") {
1478
+ const header = topbar(`Thread <span class="sm-muted">\xB7</span> ${escapeHtml(label)}`, "", { href: close, label: `\u2190 ${label}` }, `<a class="sm-icon-btn" href="${threadHref(channel.id, ts, opts, { full: false })}" title="Collapse to panel" aria-label="Collapse to panel">\u2921</a>${identityChip(store, opts)}`);
1479
+ return shell(store, opts, {
1480
+ title,
1481
+ header,
1482
+ main: body,
1483
+ active: channel.id,
1484
+ footer: composer(store, opts, channel, ts),
1485
+ script: uiScript(store, opts, close)
1486
+ });
1487
+ }
1488
+ const expand = threadHref(channel.id, ts, opts, { full: true });
1489
+ const panel = `<aside class="sm-panel"><div class="sm-panel-top"><a class="sm-panel-back" href="${close}" aria-label="Back to ${escapeHtml(label)}">\u2190</a><div class="sm-panel-heading"><h2 class="sm-panel-title">Thread</h2><div class="sm-panel-sub">${escapeHtml(label)}</div></div><a class="sm-panel-expand" href="${expand}" title="Expand thread">\u2922</a><a class="sm-panel-close" href="${close}" title="Close thread">\xD7</a></div><div class="sm-panel-body sm-scroll">${body}</div>${composer(store, opts, channel, ts)}</aside>`;
1490
+ return shell(store, opts, {
1491
+ title,
1492
+ header: channelHeader(store, opts, channel),
1493
+ main: channelColumn(store, ctx, opts, channel, ts),
1494
+ active: channel.id,
1495
+ panel,
1496
+ footer: composer(store, opts, channel),
1497
+ script: uiScript(store, opts, close)
1498
+ });
1499
+ }
1500
+ function notFound(store, opts, message) {
1501
+ return shell(store, opts, {
1502
+ title: message,
1503
+ header: topbar(escapeHtml(message), ""),
1504
+ main: `<div class="sm-empty">${escapeHtml(message)}</div>`
1505
+ });
1506
+ }
1507
+ function renderPage(store, view, opts = {}) {
1508
+ switch (view.kind) {
1509
+ case "channel":
1510
+ return channelView(store, opts, view.channel);
1511
+ case "thread":
1512
+ return threadView(store, opts, view.channel, view.ts);
1513
+ default:
1514
+ return indexView(store, opts);
1515
+ }
1516
+ }
1517
+
1518
+ // src/server.ts
1519
+ import { readFileSync as readFileSync2 } from "fs";
1520
+
1521
+ // src/body.ts
1522
+ var JSON_FIELDS = new Set([
1523
+ "blocks",
1524
+ "attachments",
1525
+ "metadata",
1526
+ "files",
1527
+ "view",
1528
+ "prompts",
1529
+ "icons",
1530
+ "user_ids",
1531
+ "types",
1532
+ "chunks",
1533
+ "loading_messages"
1534
+ ]);
1535
+ function coerce(key, value) {
1536
+ if (JSON_FIELDS.has(key)) {
1537
+ try {
1538
+ return JSON.parse(value);
1539
+ } catch {
1540
+ return value;
1541
+ }
1542
+ }
1543
+ if (value === "true")
1544
+ return true;
1545
+ if (value === "false")
1546
+ return false;
1547
+ return value;
1548
+ }
1549
+ async function parseArgs(req) {
1550
+ const url = new URL(req.url);
1551
+ const args = {};
1552
+ for (const [k, v] of url.searchParams)
1553
+ args[k] = coerce(k, v);
1554
+ if (req.method !== "POST")
1555
+ return args;
1556
+ const contentType = req.headers.get("content-type") ?? "";
1557
+ if (contentType.includes("application/json")) {
1558
+ const text = await req.text();
1559
+ if (text.trim())
1560
+ Object.assign(args, JSON.parse(text));
1561
+ return args;
1562
+ }
1563
+ if (contentType.includes("multipart/form-data")) {
1564
+ const form = await req.formData();
1565
+ form.forEach((v, k) => {
1566
+ args[k] = typeof v === "string" ? coerce(k, v) : v;
1567
+ });
1568
+ return args;
1569
+ }
1570
+ const text = await req.text();
1571
+ if (!text)
1572
+ return args;
1573
+ for (const [k, v] of new URLSearchParams(text))
1574
+ args[k] = coerce(k, v);
1575
+ return args;
1576
+ }
1577
+ function bearerToken(req, args) {
1578
+ const header = req.headers.get("authorization");
1579
+ if (header?.toLowerCase().startsWith("bearer "))
1580
+ return header.slice(7).trim();
1581
+ if (typeof args.token === "string")
1582
+ return args.token;
1583
+ return;
1584
+ }
1585
+ function str2(args, key) {
1586
+ const v = args[key];
1587
+ return typeof v === "string" ? v : v == null ? undefined : String(v);
1588
+ }
1589
+ function num(args, key, fallback) {
1590
+ const v = args[key];
1591
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : Number.NaN;
1592
+ return Number.isFinite(n) ? n : fallback;
1593
+ }
1594
+ function bool(args, key) {
1595
+ const v = args[key];
1596
+ if (typeof v === "boolean")
1597
+ return v;
1598
+ if (v === "true" || v === "1" || v === 1)
1599
+ return true;
1600
+ if (v === "false" || v === "0" || v === 0)
1601
+ return false;
1602
+ return;
1603
+ }
1604
+
1605
+ // src/ids.ts
1606
+ var ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
1607
+ function slackId(prefix, length = 8) {
1608
+ let out = prefix;
1609
+ for (let i = 0;i < length; i++)
1610
+ out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
1611
+ return out;
1612
+ }
1613
+ var lastMicros = 0;
1614
+ function nextTs() {
1615
+ let micros = Date.now() * 1000;
1616
+ if (micros <= lastMicros)
1617
+ micros = lastMicros + 1;
1618
+ lastMicros = micros;
1619
+ const seconds = Math.floor(micros / 1e6);
1620
+ const fraction = (micros % 1e6).toString().padStart(6, "0");
1621
+ return `${seconds}.${fraction}`;
1622
+ }
1623
+ function nowUnix() {
1624
+ return Math.floor(Date.now() / 1000);
1625
+ }
1626
+
1627
+ // src/store.ts
1628
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
1629
+ import { dirname } from "path";
1630
+ class SlackApiError2 extends Error {
1631
+ code;
1632
+ extra;
1633
+ constructor(code, extra = {}) {
1634
+ super(code);
1635
+ this.code = code;
1636
+ this.extra = extra;
1637
+ }
1638
+ }
1639
+ function parseJournal(text, source = "journal") {
1640
+ const entries = [];
1641
+ let line = 0;
1642
+ for (const raw of text.split(`
1643
+ `)) {
1644
+ line += 1;
1645
+ if (!raw.trim())
1646
+ continue;
1647
+ try {
1648
+ entries.push({ line, change: JSON.parse(raw) });
1649
+ } catch (e) {
1650
+ console.warn(`[slack-mock] skipping corrupt journal line ${line} in ${source}: ${e instanceof Error ? e.message : e}`);
1651
+ }
1652
+ }
1653
+ return entries;
1654
+ }
1655
+
1656
+ class Store2 {
1657
+ team;
1658
+ app;
1659
+ bot;
1660
+ users = new Map;
1661
+ channels = new Map;
1662
+ messages = new Map;
1663
+ files = new Map;
1664
+ views = new Map;
1665
+ ephemerals = [];
1666
+ apiCalls = [];
1667
+ assistantThreads = new Map;
1668
+ listeners = new Set;
1669
+ dataFile;
1670
+ replaying = false;
1671
+ constructor(opts = {}) {
1672
+ this.team = {
1673
+ id: opts.teamId ?? "T0MOCK0000",
1674
+ name: opts.teamName ?? "Mock Workspace",
1675
+ domain: opts.teamDomain ?? "mock"
1676
+ };
1677
+ this.app = { id: opts.appId ?? "A0MOCK0000", name: opts.appName ?? "mock-bot" };
1678
+ this.bot = {
1679
+ userId: opts.botUserId ?? "U0BOT00000",
1680
+ botId: opts.botId ?? "B0BOT00000",
1681
+ token: opts.botToken ?? "xoxb-mock-bot-token",
1682
+ appToken: opts.appToken ?? "xapp-mock-app-token",
1683
+ userToken: opts.userToken
1684
+ };
1685
+ this.dataFile = opts.dataFile;
1686
+ if (this.dataFile && existsSync(this.dataFile))
1687
+ this.replay(parseJournal(readFileSync(this.dataFile, "utf8"), this.dataFile).map((e) => e.change));
1688
+ if (opts.replay)
1689
+ this.replay(opts.replay);
1690
+ if (!this.users.has(this.bot.userId)) {
1691
+ this.addUser({
1692
+ id: this.bot.userId,
1693
+ name: this.app.name,
1694
+ real_name: this.app.name,
1695
+ is_bot: true
1696
+ });
1697
+ }
1698
+ }
1699
+ onChange(listener) {
1700
+ this.listeners.add(listener);
1701
+ return () => this.listeners.delete(listener);
1702
+ }
1703
+ onChangeEmit(change) {
1704
+ this.emit(change);
1705
+ }
1706
+ emit(change) {
1707
+ if (this.dataFile && !this.replaying && change.kind !== "api.call") {
1708
+ appendFileSync(this.dataFile, `${JSON.stringify({ at: new Date().toISOString(), ...stripBytes(change) })}
1709
+ `);
1710
+ }
1711
+ for (const l of this.listeners)
1712
+ l(change);
1713
+ }
1714
+ replay(changes) {
1715
+ this.replaying = true;
1716
+ try {
1717
+ for (const change of changes)
1718
+ this.applyReplayed(change);
1719
+ } finally {
1720
+ this.replaying = false;
1721
+ }
1722
+ }
1723
+ applyReplayed(change) {
1724
+ switch (change.kind) {
1725
+ case "user.add":
1726
+ this.users.set(change.user.id, change.user);
1727
+ break;
1728
+ case "channel.add":
1729
+ case "channel.update":
1730
+ this.channels.set(change.channel.id, change.channel);
1731
+ break;
1732
+ case "member.join": {
1733
+ const c = this.channels.get(change.channel.id);
1734
+ if (c && !c.members.includes(change.user))
1735
+ c.members.push(change.user);
1736
+ break;
1737
+ }
1738
+ case "message.add":
1739
+ this.insertMessage(change.message);
1740
+ break;
1741
+ case "message.update":
1742
+ case "reaction.add":
1743
+ case "reaction.remove": {
1744
+ const list = this.messages.get(change.message.channel);
1745
+ const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
1746
+ if (list && i >= 0)
1747
+ list[i] = change.message;
1748
+ break;
1749
+ }
1750
+ case "message.delete": {
1751
+ const list = this.messages.get(change.message.channel);
1752
+ const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
1753
+ if (list && i >= 0)
1754
+ list.splice(i, 1);
1755
+ break;
1756
+ }
1757
+ case "file.add":
1758
+ this.files.set(change.file.id, change.file);
1759
+ break;
1760
+ default:
1761
+ break;
1762
+ }
1763
+ }
1764
+ addUser(input) {
1765
+ const id = input.id ?? slackId("U");
1766
+ const realName = input.real_name ?? input.name;
1767
+ const user = {
1768
+ id,
1769
+ team_id: this.team.id,
1770
+ name: input.name,
1771
+ real_name: realName,
1772
+ deleted: false,
1773
+ is_bot: input.is_bot ?? false,
1774
+ is_admin: input.is_admin ?? false,
1775
+ is_app_user: false,
1776
+ tz: input.tz ?? "UTC",
1777
+ profile: {
1778
+ real_name: realName,
1779
+ display_name: input.name,
1780
+ real_name_normalized: realName,
1781
+ display_name_normalized: input.name,
1782
+ email: input.email,
1783
+ title: input.title,
1784
+ status_text: input.status,
1785
+ team: this.team.id
1786
+ }
1787
+ };
1788
+ this.users.set(id, user);
1789
+ this.emit({ kind: "user.add", user });
1790
+ return user;
1791
+ }
1792
+ user(id) {
1793
+ const u = this.users.get(id);
1794
+ if (!u)
1795
+ throw new SlackApiError2("user_not_found");
1796
+ return u;
1797
+ }
1798
+ userByEmail(email) {
1799
+ for (const u of this.users.values())
1800
+ if (u.profile.email === email)
1801
+ return u;
1802
+ return;
1803
+ }
1804
+ isBotUser(userId) {
1805
+ return userId === this.bot.userId;
1806
+ }
1807
+ addChannel(input) {
1808
+ const name = input.name.replace(/^#/, "");
1809
+ for (const c of this.channels.values()) {
1810
+ if (c.name === name && !c.is_im)
1811
+ throw new SlackApiError2("name_taken");
1812
+ }
1813
+ const id = input.id ?? slackId(input.is_private ? "G" : "C");
1814
+ const creator = input.creator ?? this.bot.userId;
1815
+ const members = [...new Set([creator, ...input.members ?? []])];
1816
+ const channel = {
1817
+ id,
1818
+ name,
1819
+ is_channel: !input.is_private,
1820
+ is_group: !!input.is_private,
1821
+ is_im: false,
1822
+ is_mpim: false,
1823
+ is_private: !!input.is_private,
1824
+ is_archived: false,
1825
+ is_general: name === "general",
1826
+ created: nowUnix(),
1827
+ creator,
1828
+ topic: { value: input.topic ?? "", creator, last_set: 0 },
1829
+ purpose: { value: input.purpose ?? "", creator, last_set: 0 },
1830
+ members
1831
+ };
1832
+ this.channels.set(id, channel);
1833
+ this.messages.set(id, []);
1834
+ this.emit({ kind: "channel.add", channel });
1835
+ return channel;
1836
+ }
1837
+ openDm(userId) {
1838
+ this.user(userId);
1839
+ for (const c of this.channels.values())
1840
+ if (c.is_im && c.user === userId)
1841
+ return c;
1842
+ const id = slackId("D");
1843
+ const channel = {
1844
+ id,
1845
+ name: id,
1846
+ is_channel: false,
1847
+ is_group: false,
1848
+ is_im: true,
1849
+ is_mpim: false,
1850
+ is_private: true,
1851
+ is_archived: false,
1852
+ is_general: false,
1853
+ created: nowUnix(),
1854
+ creator: userId,
1855
+ user: userId,
1856
+ topic: { value: "", creator: "", last_set: 0 },
1857
+ purpose: { value: "", creator: "", last_set: 0 },
1858
+ members: [userId, this.bot.userId]
1859
+ };
1860
+ this.channels.set(id, channel);
1861
+ this.messages.set(id, []);
1862
+ this.emit({ kind: "channel.add", channel });
1863
+ return channel;
1864
+ }
1865
+ channel(id) {
1866
+ const c = this.channels.get(id);
1867
+ if (!c)
1868
+ throw new SlackApiError2("channel_not_found");
1869
+ return c;
1870
+ }
1871
+ channelByName(name) {
1872
+ const n = name.replace(/^#/, "");
1873
+ for (const c of this.channels.values())
1874
+ if (c.name === n)
1875
+ return c;
1876
+ return;
1877
+ }
1878
+ channelType(c) {
1879
+ if (c.is_im)
1880
+ return "im";
1881
+ if (c.is_mpim)
1882
+ return "mpim";
1883
+ if (c.is_private)
1884
+ return "group";
1885
+ return "channel";
1886
+ }
1887
+ join(channelId, userId, inviter) {
1888
+ const channel = this.channel(channelId);
1889
+ if (channel.is_archived)
1890
+ throw new SlackApiError2("is_archived");
1891
+ if (channel.members.includes(userId))
1892
+ return { alreadyMember: true };
1893
+ channel.members.push(userId);
1894
+ this.emit({ kind: "member.join", channel, user: userId, inviter });
1895
+ return { alreadyMember: false };
1896
+ }
1897
+ leave(channelId, userId) {
1898
+ const channel = this.channel(channelId);
1899
+ if (channel.is_archived)
1900
+ throw new SlackApiError2("is_archived");
1901
+ if (channel.is_general)
1902
+ throw new SlackApiError2("cant_leave_general");
1903
+ if (!channel.members.includes(userId))
1904
+ return { notInChannel: true };
1905
+ channel.members = channel.members.filter((m) => m !== userId);
1906
+ this.emit({ kind: "channel.update", channel });
1907
+ return { notInChannel: false };
1908
+ }
1909
+ archive(channelId) {
1910
+ const channel = this.channel(channelId);
1911
+ if (channel.is_archived)
1912
+ throw new SlackApiError2("already_archived");
1913
+ if (channel.is_general)
1914
+ throw new SlackApiError2("cant_archive_general");
1915
+ channel.is_archived = true;
1916
+ this.emit({ kind: "channel.update", channel });
1917
+ }
1918
+ insertMessage(message) {
1919
+ const list = this.messages.get(message.channel) ?? [];
1920
+ this.messages.set(message.channel, list);
1921
+ let i = list.length;
1922
+ while (i > 0 && Number(list[i - 1].ts) > Number(message.ts))
1923
+ i--;
1924
+ list.splice(i, 0, message);
1925
+ if (message.thread_ts && message.thread_ts !== message.ts) {
1926
+ const parent = this.findMessage(message.channel, message.thread_ts);
1927
+ if (parent) {
1928
+ parent.reply_count = (parent.reply_count ?? 0) + 1;
1929
+ const users = new Set(parent.reply_users ?? []);
1930
+ if (message.user)
1931
+ users.add(message.user);
1932
+ parent.reply_users = [...users];
1933
+ parent.reply_users_count = users.size;
1934
+ parent.latest_reply = message.ts;
1935
+ if (parent.user)
1936
+ message.parent_user_id = parent.user;
1937
+ }
1938
+ }
1939
+ }
1940
+ findMessage(channelId, ts) {
1941
+ return this.messages.get(channelId)?.find((m) => m.ts === ts);
1942
+ }
1943
+ findAnyMessage(channelId, ts) {
1944
+ return this.findMessage(channelId, ts) ?? this.ephemerals.find((m) => m.channel === channelId && m.ts === ts);
1945
+ }
1946
+ updateEphemeral(channelId, ts, patch) {
1947
+ const m = this.ephemerals.find((x) => x.channel === channelId && x.ts === ts);
1948
+ if (!m)
1949
+ throw new SlackApiError2("message_not_found");
1950
+ Object.assign(m, patch);
1951
+ return m;
1952
+ }
1953
+ deleteEphemeral(channelId, ts) {
1954
+ const i = this.ephemerals.findIndex((x) => x.channel === channelId && x.ts === ts);
1955
+ if (i < 0)
1956
+ throw new SlackApiError2("message_not_found");
1957
+ this.ephemerals.splice(i, 1);
1958
+ }
1959
+ message(channelId, ts) {
1960
+ const m = this.findMessage(channelId, ts);
1961
+ if (!m)
1962
+ throw new SlackApiError2("message_not_found");
1963
+ return m;
1964
+ }
1965
+ addMessage(input) {
1966
+ const channel = this.channel(input.channel);
1967
+ if (channel.is_archived)
1968
+ throw new SlackApiError2("is_archived");
1969
+ if (input.thread_ts && !this.findMessage(input.channel, input.thread_ts)) {
1970
+ throw new SlackApiError2("thread_not_found");
1971
+ }
1972
+ const message = {
1973
+ type: "message",
1974
+ team: this.team.id,
1975
+ ts: input.ts ?? nextTs(),
1976
+ ...input
1977
+ };
1978
+ if (message.ephemeral_user)
1979
+ this.ephemerals.push(message);
1980
+ else
1981
+ this.insertMessage(message);
1982
+ this.emit({ kind: "message.add", message });
1983
+ return message;
1984
+ }
1985
+ updateMessage(channelId, ts, patch, editor, opts = {}) {
1986
+ const message = this.message(channelId, ts);
1987
+ const previous = structuredClone(message);
1988
+ Object.assign(message, patch, opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } });
1989
+ this.emit({ kind: "message.update", message, previous });
1990
+ return message;
1991
+ }
1992
+ deleteMessage(channelId, ts) {
1993
+ const list = this.messages.get(channelId);
1994
+ const i = list?.findIndex((m) => m.ts === ts) ?? -1;
1995
+ if (!list || i < 0)
1996
+ throw new SlackApiError2("message_not_found");
1997
+ const [message] = list.splice(i, 1);
1998
+ if (message.thread_ts && message.thread_ts !== ts) {
1999
+ const parent = this.findMessage(channelId, message.thread_ts);
2000
+ if (parent?.reply_count)
2001
+ parent.reply_count -= 1;
2002
+ }
2003
+ this.emit({ kind: "message.delete", message });
2004
+ return message;
2005
+ }
2006
+ addReaction(channelId, ts, name, userId) {
2007
+ const message = this.message(channelId, ts);
2008
+ message.reactions ??= [];
2009
+ let reaction = message.reactions.find((r) => r.name === name);
2010
+ if (reaction?.users.includes(userId))
2011
+ throw new SlackApiError2("already_reacted");
2012
+ if (!reaction) {
2013
+ reaction = { name, users: [], count: 0 };
2014
+ message.reactions.push(reaction);
2015
+ }
2016
+ reaction.users.push(userId);
2017
+ reaction.count = reaction.users.length;
2018
+ this.emit({ kind: "reaction.add", message, name, user: userId });
2019
+ return message;
2020
+ }
2021
+ removeReaction(channelId, ts, name, userId) {
2022
+ const message = this.message(channelId, ts);
2023
+ const reaction = message.reactions?.find((r) => r.name === name);
2024
+ if (!reaction?.users.includes(userId))
2025
+ throw new SlackApiError2("no_reaction");
2026
+ reaction.users = reaction.users.filter((u) => u !== userId);
2027
+ reaction.count = reaction.users.length;
2028
+ message.reactions = message.reactions.filter((r) => r.count > 0);
2029
+ if (message.reactions.length === 0)
2030
+ message.reactions = undefined;
2031
+ this.emit({ kind: "reaction.remove", message, name, user: userId });
2032
+ return message;
2033
+ }
2034
+ history(channelId, q = {}) {
2035
+ this.channel(channelId);
2036
+ const all = (this.messages.get(channelId) ?? []).filter((m) => !m.thread_ts || m.thread_ts === m.ts || m.subtype === "thread_broadcast");
2037
+ return paginate(all, q);
2038
+ }
2039
+ replies(channelId, threadTs, q = {}) {
2040
+ const parent = this.message(channelId, threadTs);
2041
+ const all = [
2042
+ parent,
2043
+ ...(this.messages.get(channelId) ?? []).filter((m) => m.thread_ts === threadTs && m.ts !== threadTs)
2044
+ ];
2045
+ return paginate(all, q);
1880
2046
  }
1881
- const seed = m.user ?? m.bot_id ?? name;
1882
- const color = AVATAR_COLORS[hashIndex(seed, AVATAR_COLORS.length)];
1883
- return `<div class="sm-avatar" style="background:${color}">${escapeHtml(initials(name))}</div>`;
1884
- }
1885
- function reactionsHtml(store, m, interactive, locked) {
1886
- if (!m.reactions?.length)
1887
- return "";
1888
- const chips = m.reactions.map((r) => {
1889
- const who = r.users.map((id) => {
1890
- const user = store.users.get(id);
1891
- return user ? displayName(user) : id;
1892
- }).join(", ");
1893
- const char = emojiChar(r.name) ?? `:${r.name}:`;
1894
- const content = `${escapeHtml(char)}<span class="sm-reaction-count">${r.count}</span>`;
1895
- return interactive ? `<button type="button" class="sm-reaction" title="${escapeHtml(who)}" data-reaction="${escapeHtml(r.name)}" data-users="${escapeHtml(JSON.stringify(r.users))}" aria-label="Add :${escapeHtml(r.name)}: reaction, ${r.count} ${r.count === 1 ? "person" : "people"} reacted" aria-pressed="false"${locked ? " disabled" : ""}>${content}</button>` : `<span class="sm-reaction" title="${escapeHtml(who)}">${content}</span>`;
1896
- });
1897
- return `<div class="sm-reactions">${chips.join("")}</div>`;
1898
- }
1899
- function messageActions(m, opts) {
1900
- const thread = m.thread_ts ?? m.ts;
1901
- const reactIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><circle cx="11" cy="12" r="8"/><path d="M7 14c2 3 6 3 8 0M8 9h.01M14 9h.01M20 2v6M17 5h6" stroke-linecap="round"/></svg>`;
1902
- const replyIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6 4V6a2 2 0 0 1 2-2Z" stroke-linejoin="round"/><path d="M7 9h10M7 13h6" stroke-linecap="round"/></svg>`;
1903
- return `<div class="sm-message-actions"><button type="button" class="sm-add-reaction" aria-label="Add reaction" aria-haspopup="dialog" aria-controls="sm-reaction-picker" title="Add reaction"${opts.writeGated ? " disabled" : ""}>${reactIcon}</button><a class="sm-reply-action" href="${threadHref(m.channel, thread, opts)}" data-thread="${escapeHtml(thread)}" aria-label="Open thread" title="Open thread">${replyIcon}</a></div><div class="sm-action-error" role="alert" hidden></div>`;
1904
- }
1905
- function reactionPicker() {
1906
- const names = [
1907
- "thumbsup",
1908
- "green_heart",
1909
- "eyes",
1910
- "white_check_mark",
1911
- "tada",
1912
- "rocket",
1913
- "star",
1914
- "thinking_face",
1915
- "sparkles",
1916
- "fire",
1917
- "raised_hands",
1918
- "clap"
1919
- ];
1920
- const buttons = names.map((name) => `<button type="button" data-reaction="${name}" aria-label="React with ${name.replaceAll("_", " ")}" title=":${name}:">${escapeHtml(emojiChar(name) ?? `:${name}:`)}</button>`).join("");
1921
- return `<dialog class="sm-reaction-picker" id="sm-reaction-picker" aria-labelledby="sm-reaction-title"><div class="sm-reaction-picker-head"><h2 id="sm-reaction-title">Add a reaction</h2><button type="button" class="sm-reaction-close" aria-label="Close reactions">\u2715</button></div><div class="sm-reaction-choices">${buttons}</div><div class="sm-action-error" role="alert" hidden></div></dialog>`;
1922
- }
1923
- function fileUrl(f, token) {
1924
- if (!f.url_private)
1925
- return "";
1926
- return escapeHtml(`${f.url_private}${f.url_private.includes("?") ? "&" : "?"}t=${token}`);
1927
- }
1928
- function filesHtml(files, token) {
1929
- if (!files?.length)
1930
- return "";
1931
- const cards = files.map((f) => {
1932
- if (f.mimetype?.startsWith("image/") && f.url_private) {
1933
- return `<img class="sm-file-img" src="${fileUrl(f, token)}" alt="${escapeHtml(f.title || f.name)}">`;
2047
+ addFile(input) {
2048
+ const id = input.id ?? slackId("F");
2049
+ const ext = input.name.includes(".") ? input.name.split(".").pop().toLowerCase() : "";
2050
+ const mimetype = input.mimetype ?? guessMime(ext);
2051
+ const now = nowUnix();
2052
+ const file = {
2053
+ id,
2054
+ created: now,
2055
+ timestamp: now,
2056
+ name: input.name,
2057
+ title: input.title ?? input.name,
2058
+ mimetype,
2059
+ filetype: ext || "binary",
2060
+ pretty_type: ext ? ext.toUpperCase() : "Binary",
2061
+ user: input.user,
2062
+ size: input.bytes.byteLength,
2063
+ mode: "hosted",
2064
+ is_external: false,
2065
+ is_public: false,
2066
+ url_private: `${input.baseUrl}/files-pri/${this.team.id}-${id}/${encodeURIComponent(input.name)}`,
2067
+ url_private_download: `${input.baseUrl}/files-pri/${this.team.id}-${id}/download/${encodeURIComponent(input.name)}`,
2068
+ permalink: `${input.baseUrl}/files/${input.user}/${id}/${encodeURIComponent(input.name)}`,
2069
+ channels: [],
2070
+ bytes: input.bytes
2071
+ };
2072
+ if (mimetype.startsWith("image/")) {
2073
+ const thumbs = file;
2074
+ for (const size of [64, 80, 160, 360, 480])
2075
+ thumbs[`thumb_${size}`] = file.url_private;
1934
2076
  }
1935
- const href = fileUrl(f, token);
1936
- const name = escapeHtml(f.title || f.name);
1937
- const meta = `${escapeHtml(f.pretty_type || f.filetype || "File")} \xB7 ${fileSize(f.size ?? 0)}`;
1938
- const label = href ? `<a href="${href}">${name}</a>` : name;
1939
- return `<div class="sm-file-card"><div class="sm-file-icon">\uD83D\uDCC4</div><div><div class="sm-file-name">${label}</div><div class="sm-file-meta">${meta}</div></div></div>`;
1940
- });
1941
- return `<div class="sm-files">${cards.join("")}</div>`;
1942
- }
1943
- function renderMessage(store, ctx, m, opts, flags = {}) {
1944
- const name = authorName(store, m);
1945
- const isApp = Boolean(m.bot_id);
1946
- const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
1947
- const interactive = !opts.screenshot && !flags.ephemeral && humanUsers(store).length > 0;
1948
- const body = [];
1949
- if (m.streaming_state !== undefined) {
1950
- if (m.text)
1951
- body.push(`<div class="sm-text">${mrkdwnToHtml(markdownToMrkdwn(m.text), ctx)}</div>`);
1952
- if (blocks)
1953
- body.push(renderBlocks(blocks, ctx));
1954
- } else if (blocks)
1955
- body.push(renderBlocks(blocks, ctx));
1956
- else if (m.text)
1957
- body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
1958
- if (m.edited)
1959
- body.push(`<div class="sm-edited">(edited)</div>`);
1960
- if (m.attachments?.length)
1961
- body.push(renderAttachments(m.attachments, ctx));
1962
- body.push(filesHtml(m.files, store.bot.token));
1963
- body.push(reactionsHtml(store, m, interactive, Boolean(opts.writeGated)));
1964
- if (flags.ephemeral)
1965
- body.push(`<div class="sm-eph-note">Only visible to you</div>`);
1966
- if (flags.threadLink && m.reply_count) {
1967
- const count = `${m.reply_count} ${m.reply_count === 1 ? "reply" : "replies"}`;
1968
- const last = m.latest_reply ? `<span class="sm-replies-time">Last reply ${timeOf(m.latest_reply)}</span>` : "";
1969
- body.push(`<a class="sm-replies" href="${threadHref(m.channel, m.thread_ts ?? m.ts, opts)}">${count}${last}</a>`);
2077
+ this.files.set(id, file);
2078
+ this.emit({ kind: "file.add", file });
2079
+ return file;
1970
2080
  }
1971
- if (interactive)
1972
- body.push(messageActions(m, opts));
1973
- const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
1974
- const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
1975
- 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>`;
1976
- }
1977
- function markdownToMrkdwn(text) {
1978
- return text.split(/(```[\s\S]*?```)/).map((part, i) => i % 2 === 1 ? part : part.replace(/\*\*(.+?)\*\*/g, "*$1*").replace(/__(.+?)__/g, "*$1*").replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, "<$2|$1>").replace(/^#{1,6}\s+(.+)$/gm, "*$1*").replace(/^(\s*)[-*]\s+/gm, "$1\u2022 ")).join("");
1979
- }
1980
- function renderMessageList(store, ctx, messages, opts, flags = {}) {
1981
- const out = [];
1982
- let day = "";
1983
- for (const m of messages) {
1984
- const label = flags.dividers === false ? "" : dayLabel(m.ts);
1985
- if (label && label !== day) {
1986
- day = label;
1987
- out.push(`<div class="sm-daydiv"><span>${escapeHtml(label)}</span></div>`);
1988
- }
1989
- out.push(renderMessage(store, ctx, m, opts, { ...flags, ephemeral: m._ephemeral === true }));
2081
+ file(id) {
2082
+ const f = this.files.get(id);
2083
+ if (!f)
2084
+ throw new SlackApiError2("file_not_found");
2085
+ return f;
1990
2086
  }
1991
- return out.join("");
1992
- }
1993
- function sidebar(store, opts, active) {
1994
- const channels = [...store.channels.values()].sort((a, b) => channelLabel(store, a).localeCompare(channelLabel(store, b)));
1995
- const links = channels.map((c) => `<a class="${c.id === active ? "sm-active" : ""}" href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a>`).join("");
1996
- const options = channels.map((c) => `<option value="${escapeHtml(channelHref(c.id, opts))}"${c.id === active ? " selected" : ""}>${escapeHtml(channelLabel(store, c))}</option>`).join("");
1997
- const mobile = `<div class="sm-mobile-bar"><div class="sm-mobile-heading"><a class="sm-mobile-workspace" href="${homeHref(opts)}">${escapeHtml(store.team.name)}</a>${identityChip(store, opts)}</div><select class="sm-channel-switch" aria-label="Channel"><option value="${homeHref(opts)}"${active ? "" : " selected"}>Workspace</option>${options}</select></div>`;
1998
- return `${mobile}<nav class="sm-side"><div class="sm-side-title"><a href="${homeHref(opts)}" style="color:#fff">${escapeHtml(store.team.name)}</a><span class="sm-side-team">${escapeHtml(store.team.id)} \xB7 slack-mock</span></div><div class="sm-side-h">Channels</div>${links}</nav>`;
1999
- }
2000
- function shell(store, opts, parts) {
2001
- const refresh = opts.refreshSec && !opts.screenshot ? `<meta http-equiv="refresh" content="${Math.max(1, Math.floor(opts.refreshSec))}">` : "";
2002
- const style = opts.screenshot ? "" : ` style="--sm-panel-w:${panelWidth(opts)}"`;
2003
- const head = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><title>${escapeHtml(parts.title)}</title>${refresh}<style>${CSS}</style></head>`;
2004
- if (opts.screenshot) {
2005
- return `${head}<body><div class="sm-shot">${parts.header}<div class="sm-page">${parts.main}</div></div></body></html>`;
2087
+ openView(view) {
2088
+ const id = view.id ?? slackId("V");
2089
+ const full = {
2090
+ ...view,
2091
+ id,
2092
+ team_id: this.team.id,
2093
+ app_id: this.app.id,
2094
+ bot_id: this.bot.botId,
2095
+ hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`,
2096
+ root_view_id: id
2097
+ };
2098
+ this.views.set(id, full);
2099
+ this.emit({ kind: "view.open", view: full });
2100
+ return full;
2101
+ }
2102
+ recordApiCall(call) {
2103
+ this.apiCalls.push(call);
2104
+ this.emit({ kind: "api.call", call });
2105
+ }
2106
+ assistantThread(channel, threadTs) {
2107
+ const key = `${channel}:${threadTs}`;
2108
+ let t = this.assistantThreads.get(key);
2109
+ if (!t) {
2110
+ t = {};
2111
+ this.assistantThreads.set(key, t);
2112
+ }
2113
+ return t;
2006
2114
  }
2007
- const app = `sm-app${parts.panel ? " sm-app-thread" : ""}`;
2008
- const handle = parts.panel ? `<div class="sm-resize" title="Drag to resize, double-click to reset"></div>` : "";
2009
- return `${head}<body${style}><div class="${app}">${sidebar(store, opts, parts.active)}<div class="sm-main">${parts.header}<div class="sm-page sm-scroll">${parts.main}</div>${parts.footer ?? ""}</div>${handle}${parts.panel ?? ""}</div>${parts.script ?? ""}</body></html>`;
2010
- }
2011
- function topbar(title, sub, back, actions) {
2012
- const backLink = back ? `<a class="sm-back" href="${back.href}">${escapeHtml(back.label)}</a>` : "";
2013
- const right = actions ? `<div class="sm-top-actions">${actions}</div>` : "";
2014
- return `<div class="sm-top">${backLink}<h1>${title}</h1>${sub ? `<div class="sm-sub">${sub}</div>` : ""}${right}</div>`;
2015
- }
2016
- function indexView(store, opts) {
2017
- const cards = [
2018
- ["Workspace", escapeHtml(store.team.name)],
2019
- ["Team id", escapeHtml(store.team.id)],
2020
- ["Bot user", escapeHtml(`${store.app.name} (${store.bot.userId})`)],
2021
- ["Connections", String(opts.connections ?? 0)]
2022
- ].map(([k, v]) => `<div class="sm-card"><div class="sm-card-k">${k}</div><div class="sm-card-v">${v}</div></div>`).join("");
2023
- const channels = [...store.channels.values()];
2024
- const channelRows = channels.map((c) => {
2025
- const count = store.messages.get(c.id)?.length ?? 0;
2026
- return `<tr><td data-label="Name"><a href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a></td><td data-label="Type"><span class="sm-tag">${channelKind(c)}</span></td><td class="sm-muted" data-label="Id">${c.id}</td><td data-label="Messages">${count}</td></tr>`;
2027
- }).join("");
2028
- const userRows = [...store.users.values()].map((u) => `<tr><td data-label="Name">${escapeHtml(u.name)}${userStatus(u)}</td><td data-label="Real name">${escapeHtml(u.real_name)}</td><td class="sm-muted" data-label="Title">${escapeHtml(u.profile.title ?? "")}</td><td class="sm-muted" data-label="Email">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted" data-label="Id">${u.id}</td><td data-label="Type">${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`).join("");
2029
- const main = `<div class="sm-cards">${cards}</div>
2030
- <div class="sm-h2">Channels</div>
2031
- ${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>`}
2032
- <div class="sm-h2">Users</div>
2033
- <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>`;
2034
- return shell(store, opts, {
2035
- title: `${store.team.name} \xB7 slack-mock`,
2036
- header: topbar(escapeHtml(store.team.name), "slack-mock workspace", undefined, identityChip(store, opts)),
2037
- main,
2038
- script: opts.screenshot ? "" : uiScript(store, opts, undefined, false)
2039
- });
2040
- }
2041
- function channelMessages(store, channel) {
2042
- const history = store.history(channel.id, { limit: 1000 }).items;
2043
- const ephemerals = store.ephemerals.filter((e) => e.channel === channel.id).map((e) => ({ ...e, _ephemeral: true }));
2044
- return [...history, ...ephemerals].sort((a, b) => Number(a.ts) - Number(b.ts));
2045
2115
  }
2046
- function channelColumn(store, ctx, opts, channel, openTs) {
2047
- const messages = channelMessages(store, channel);
2048
- if (!messages.length)
2049
- return `<div class="sm-empty">No messages yet</div>`;
2050
- return renderMessageList(store, ctx, messages, opts, {
2051
- threadLink: true,
2052
- dividers: true,
2053
- openTs
2054
- });
2116
+ function paginate(all, q) {
2117
+ let items = all;
2118
+ if (q.oldest)
2119
+ items = items.filter((m) => q.inclusive ? Number(m.ts) >= Number(q.oldest) : Number(m.ts) > Number(q.oldest));
2120
+ if (q.latest)
2121
+ items = items.filter((m) => q.inclusive ? Number(m.ts) <= Number(q.latest) : Number(m.ts) < Number(q.latest));
2122
+ const start = q.cursor ? Number.parseInt(Buffer.from(q.cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0 : 0;
2123
+ const limit = Math.max(1, Math.min(q.limit ?? 100, 1000));
2124
+ const page = items.slice(start, start + limit);
2125
+ const has_more = start + limit < items.length;
2126
+ return {
2127
+ items: page,
2128
+ has_more,
2129
+ next_cursor: has_more ? Buffer.from(`offset:${start + limit}`).toString("base64") : ""
2130
+ };
2055
2131
  }
2056
- function channelHeader(store, opts, channel) {
2057
- const sub = [channel.topic.value, channel.purpose.value].filter(Boolean).join(" \xB7 ");
2058
- const back = opts.screenshot ? undefined : { href: homeHref(opts), label: "\u2190 Workspace" };
2059
- return topbar(escapeHtml(channelLabel(store, channel)), escapeHtml(sub), back, identityChip(store, opts));
2132
+ function guessMime(ext) {
2133
+ const map = {
2134
+ png: "image/png",
2135
+ jpg: "image/jpeg",
2136
+ jpeg: "image/jpeg",
2137
+ gif: "image/gif",
2138
+ webp: "image/webp",
2139
+ svg: "image/svg+xml",
2140
+ txt: "text/plain",
2141
+ md: "text/markdown",
2142
+ log: "text/plain",
2143
+ json: "application/json",
2144
+ csv: "text/csv",
2145
+ pdf: "application/pdf",
2146
+ html: "text/html",
2147
+ zip: "application/zip"
2148
+ };
2149
+ return map[ext] ?? "application/octet-stream";
2060
2150
  }
2061
- function humanUsers(store) {
2062
- return [...store.users.values()].filter((u) => !u.is_bot && !u.deleted);
2151
+ function wireMessage(m) {
2152
+ const { ephemeral_user: _e, text_format: _f, stream_replaced: _r, ...rest } = m;
2153
+ if (rest.files)
2154
+ rest.files = rest.files.map(wireFile);
2155
+ return rest;
2063
2156
  }
2064
- function userStatus(user) {
2065
- return user.profile.status_text ? `<span class="sm-user-status">${escapeHtml(user.profile.status_text)}</span>` : "";
2157
+ function wireFile(f) {
2158
+ const { bytes: _b, ...rest } = f;
2159
+ return rest;
2066
2160
  }
2067
- function identityChip(store, opts) {
2068
- if (opts.screenshot)
2069
- return "";
2070
- const users = humanUsers(store);
2071
- const selected = users[0];
2072
- if (!selected)
2073
- return "";
2074
- const name = selected.real_name || selected.name;
2075
- const avatar = `<span class="sm-identity-avatar" style="background:${AVATAR_COLORS[hashIndex(selected.id, AVATAR_COLORS.length)]}">${escapeHtml(initials(name))}</span>`;
2076
- const items = users.map((u) => {
2077
- const real = u.real_name || u.name;
2078
- const color = AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)];
2079
- return `<li><button type="button" data-user="${escapeHtml(u.id)}"><span class="sm-identity-avatar" style="background:${color}">${escapeHtml(initials(real))}</span><span>${escapeHtml(real)}${userStatus(u)}</span><span class="sm-identity-user">@${escapeHtml(u.name)}</span></button></li>`;
2080
- }).join("");
2081
- const hidden = opts.writeGated ? " hidden" : "";
2082
- return `<details class="sm-identity"${hidden}><summary title="Change posting identity" aria-label="Posting as ${escapeHtml(name)}">${avatar}<span class="sm-identity-name">${escapeHtml(name)}</span></summary><ul class="sm-identity-list">${items}</ul></details>`;
2161
+ function stripBytes(change) {
2162
+ if (change.kind === "file.add")
2163
+ return { ...change, file: wireFile(change.file) };
2164
+ if ("message" in change && change.message.files) {
2165
+ return {
2166
+ ...change,
2167
+ message: { ...change.message, files: change.message.files.map(wireFile) }
2168
+ };
2169
+ }
2170
+ return change;
2083
2171
  }
2084
- function composer(store, opts, channel, threadTs) {
2085
- if (opts.screenshot)
2086
- return "";
2087
- const users = humanUsers(store);
2088
- if (!users.length)
2089
- return "";
2090
- const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
2091
- const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
2092
- const gated = opts.writeGated ? ' data-gated="1"' : "";
2093
- const lock = opts.writeGated ? `<div class="sm-composer-lock" hidden><span>Reading is open. Sign in to post.</span><input class="sm-lock-user" placeholder="user" autocomplete="username"><input class="sm-lock-pass" type="password" placeholder="password" autocomplete="current-password"><button type="button" class="sm-lock-go">Sign in</button><span class="sm-err"></span></div>` : "";
2094
- return `<div class="sm-composer" data-channel="${escapeHtml(channel.id)}"${thread}${gated}><div class="sm-mentions"></div><div class="sm-composer-box"><textarea class="sm-composer-text" rows="2" placeholder="${escapeHtml(placeholder)}" data-placeholder="${escapeHtml(placeholder)}"></textarea><div class="sm-composer-row"><button type="button" class="sm-composer-send">Send</button></div></div>${lock}<div class="sm-composer-hint">Enter to send, Shift+Enter for a new line, @name to mention<span class="sm-lock-state"></span></div></div>`;
2172
+ function ensureDir(file) {
2173
+ mkdirSync(dirname(file), { recursive: true });
2095
2174
  }
2096
- function mentionData(store) {
2097
- const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
2098
- id: u.id,
2099
- name: u.name,
2100
- real: u.real_name || u.name,
2101
- initials: initials(u.real_name || u.name),
2102
- color: AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)],
2103
- bot: u.is_bot
2104
- }));
2105
- const json = JSON.stringify(users).replace(/</g, "\\u003c");
2106
- return `<script type="application/json" id="sm-users">${json}</script>`;
2175
+
2176
+ // src/events.ts
2177
+ var VERIFICATION_TOKEN = "mock-verification-token";
2178
+ function eventCallback(store, event) {
2179
+ return {
2180
+ token: VERIFICATION_TOKEN,
2181
+ team_id: store.team.id,
2182
+ context_team_id: store.team.id,
2183
+ context_enterprise_id: null,
2184
+ api_app_id: store.app.id,
2185
+ event,
2186
+ type: "event_callback",
2187
+ event_id: slackId("Ev", 9),
2188
+ event_time: nowUnix(),
2189
+ authorizations: [
2190
+ {
2191
+ enterprise_id: null,
2192
+ team_id: store.team.id,
2193
+ user_id: store.bot.userId,
2194
+ is_bot: true,
2195
+ is_enterprise_install: false
2196
+ }
2197
+ ],
2198
+ is_ext_shared_channel: false,
2199
+ event_context: Buffer.from(`${store.team.id}:${store.app.id}:${event.channel ?? ""}`).toString("base64")
2200
+ };
2107
2201
  }
2108
- function uiScript(store, opts, closeUrl, autoScroll = true) {
2109
- const esc = closeUrl ? `document.addEventListener("keydown",function(e){if(e.key==="Escape"&&!/^(TEXTAREA|INPUT|SELECT)$/.test(document.activeElement&&document.activeElement.tagName||""))location.href=${JSON.stringify(closeUrl)}});` : "";
2110
- const body = `(function(){
2111
- var viewport=window.visualViewport;
2112
- function fitViewport(){if(viewport&&viewport.scale!==1)return;var style=document.documentElement.style;style.setProperty("--sm-viewport-height",(viewport?viewport.height:innerHeight)+"px");style.setProperty("--sm-viewport-top",(viewport?viewport.offsetTop:0)+"px")}
2113
- fitViewport();addEventListener("resize",fitViewport);
2114
- if(viewport){viewport.addEventListener("resize",fitViewport);viewport.addEventListener("scroll",fitViewport)}
2115
- document.addEventListener("change",function(e){if(e.target.classList.contains("sm-channel-switch"))location.href=e.target.value});
2116
- var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
2117
- ${autoScroll ? `function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}
2118
- scroll();addEventListener("load",scroll);` : ""}
2119
- var handle=document.querySelector(".sm-resize");
2120
- if(handle){
2121
- var saved=null;try{saved=localStorage.getItem(W)}catch(e){}
2122
- if(!FIXED&&saved)document.body.style.setProperty("--sm-panel-w",saved);
2123
- var dragging=false;
2124
- handle.addEventListener("mousedown",function(e){dragging=true;handle.classList.add("sm-dragging");e.preventDefault()});
2125
- document.addEventListener("mousemove",function(e){if(!dragging)return;var w=Math.round(Math.min(Math.max(innerWidth-e.clientX,360),Math.max(innerWidth-320,360)));document.body.style.setProperty("--sm-panel-w",w+"px")});
2126
- document.addEventListener("mouseup",function(){if(!dragging)return;dragging=false;handle.classList.remove("sm-dragging");try{localStorage.setItem(W,document.body.style.getPropertyValue("--sm-panel-w"))}catch(e){}});
2127
- handle.addEventListener("dblclick",function(){try{localStorage.removeItem(W)}catch(e){}document.body.style.setProperty("--sm-panel-w",DEF)});
2202
+ function messageEvent(store, m, channel) {
2203
+ const {
2204
+ channel: _c,
2205
+ team,
2206
+ ...rest
2207
+ } = wireMessage(m);
2208
+ const event = {
2209
+ ...rest,
2210
+ type: "message",
2211
+ channel: m.channel,
2212
+ event_ts: m.ts,
2213
+ channel_type: store.channelType(channel),
2214
+ team
2215
+ };
2216
+ if (m.files?.length && !m.subtype)
2217
+ event.subtype = "file_share";
2218
+ if (m.files?.length) {
2219
+ event.upload = false;
2220
+ event.display_as_bot = false;
2221
+ }
2222
+ return event;
2128
2223
  }
2129
- var raw=document.getElementById("sm-users");
2130
- var USERS=raw?JSON.parse(raw.textContent||"[]"):[],HUMANS=USERS.filter(function(u){return !u.bot});
2131
- var PEOPLE=USERS.concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
2132
- function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&amp;":c==="<"?"&lt;":c===">"?"&gt;":"&quot;"})}
2133
- var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter",IK="sm-identity",currentIdentity="",identityStorage=true;
2134
- function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
2135
- function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
2136
- function setIdentity(v){currentIdentity=v;try{if(v)localStorage.setItem(IK,v);else localStorage.removeItem(IK)}catch(e){identityStorage=false}}
2137
- function findIdentity(value,key){for(var i=0;i<HUMANS.length;i++)if(HUMANS[i][key]===value)return HUMANS[i];return null}
2138
- function identity(){var id=currentIdentity;if(identityStorage)try{id=localStorage.getItem(IK)||currentIdentity}catch(e){identityStorage=false}currentIdentity=id;var u=findIdentity(id,"id");if(!u&&HUMANS.length){u=HUMANS[0];setIdentity(u.id)}return u}
2139
- (function(){var url=null,name=null;try{url=new URL(location.href);name=url.searchParams.get("as")}catch(e){}if(url&&name!==null){var u=findIdentity(name,"name");if(u)setIdentity(u.id);url.searchParams.delete("as");var search=url.searchParams.toString();history.replaceState(null,"",url.pathname+(search?"?"+search:"")+url.hash)}})();
2140
- (function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
2141
- function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
2142
- var reactionDialog=document.querySelector(".sm-reaction-picker"),reactionTarget=null,reactionScope=null,reactionBusy=false;
2143
- function closeReactions(restoreFocus){var button=reactionTarget&&reactionTarget.querySelector(".sm-add-reaction");if(reactionDialog&&reactionDialog.open)reactionDialog.close();reactionTarget=null;reactionScope=null;if(restoreFocus&&button&&button.isConnected&&!button.disabled)button.focus({preventScroll:true})}
2144
- function findMessageElement(scope,ts){var found=null;if(scope)scope.querySelectorAll(".sm-msg[data-ts]").forEach(function(message){if(message.dataset.ts===ts)found=message});return found}
2145
- function positionReactions(){
2146
- if(!reactionDialog||!reactionDialog.open||!reactionTarget)return;
2147
- if(!reactionTarget.isConnected){reactionTarget=findMessageElement(reactionScope,reactionTarget.dataset.ts);if(!reactionTarget){closeReactions();return}}
2148
- var button=reactionTarget.querySelector(".sm-add-reaction"),anchor=button.getBoundingClientRect(),v=window.visualViewport,left=v?v.offsetLeft:0,top=v?v.offsetTop:0,width=v?v.width:innerWidth,height=v?v.height:innerHeight,scope=reactionScope.getBoundingClientRect(),pad=12,gap=8;
2149
- if(anchor.bottom<=Math.max(top,scope.top)||anchor.top>=Math.min(top+height,scope.bottom)){closeReactions();return}
2150
- reactionDialog.style.maxWidth=Math.max(0,width-pad*2)+"px";reactionDialog.style.maxHeight=Math.max(0,height-pad*2)+"px";
2151
- var rect=reactionDialog.getBoundingClientRect(),x=Math.max(left+pad,Math.min(anchor.right-rect.width,left+width-rect.width-pad)),y=anchor.bottom+gap;
2152
- if(y+rect.height>top+height-pad)y=anchor.top-rect.height-gap;
2153
- reactionDialog.style.left=x+"px";reactionDialog.style.top=Math.max(top+pad,Math.min(y,top+height-rect.height-pad))+"px";
2224
+ function appMentionEvent(store, m) {
2225
+ const { channel_type: _ct, ...event } = messageEvent(store, m, store.channel(m.channel));
2226
+ return { ...event, type: "app_mention" };
2154
2227
  }
2155
- document.addEventListener("scroll",function(e){if(!reactionDialog.contains(e.target))positionReactions()},true);
2156
- addEventListener("resize",positionReactions);
2157
- if(window.visualViewport){window.visualViewport.addEventListener("resize",positionReactions);window.visualViewport.addEventListener("scroll",positionReactions)}
2158
- document.addEventListener("pointerdown",function(e){if(reactionDialog.open&&!reactionDialog.contains(e.target)&&!e.target.closest(".sm-add-reaction"))closeReactions()});
2159
- document.addEventListener("focusin",function(e){if(reactionDialog.open&&!reactionDialog.contains(e.target)&&(!reactionTarget||e.target!==reactionTarget.querySelector(".sm-add-reaction")))closeReactions()});
2160
- function hasReaction(button,user){return JSON.parse(button.dataset.users||"[]").indexOf(user)!==-1}
2161
- function reactionUi(root){var u=identity(),locked=(GATED&&!cred())||!u;(root||document).querySelectorAll(".sm-add-reaction,.sm-reaction[data-reaction],.sm-reaction-choices button").forEach(function(button){button.disabled=locked||reactionBusy;if(button.classList.contains("sm-reaction")){var mine=Boolean(u&&hasReaction(button,u.id)),count=button.querySelector(".sm-reaction-count").textContent;button.setAttribute("aria-pressed",String(mine));button.setAttribute("aria-label",(mine?"Remove":"Add")+" :"+button.dataset.reaction+": reaction, "+count+" "+(count==="1"?"person":"people")+" reacted")}});if(locked)closeReactions()}
2162
- function identityUi(){var u=identity();document.querySelectorAll(".sm-identity").forEach(function(chip){chip.hidden=GATED&&!cred();if(!u)return;var av=chip.querySelector("summary .sm-identity-avatar"),name=chip.querySelector(".sm-identity-name"),summary=chip.querySelector("summary");if(av){av.textContent=u.initials;av.style.backgroundColor=u.color}if(name)name.textContent=u.real;if(summary)summary.setAttribute("aria-label","Posting as "+u.real);chip.querySelectorAll("[data-user]").forEach(function(button){if(button.dataset.user===u.id)button.setAttribute("aria-current","true");else button.removeAttribute("aria-current")})});reactionUi()}
2163
- function lockUi(){document.querySelectorAll(".sm-composer").forEach(function(box){var locked=GATED&&!cred(),lock=box.querySelector(".sm-composer-lock"),ta=box.querySelector(".sm-composer-text"),btn=box.querySelector(".sm-composer-send"),state=box.querySelector(".sm-lock-state");if(lock)lock.hidden=!locked;ta.disabled=locked;btn.disabled=locked;ta.placeholder=locked?"Sign in to post":(ta.dataset.placeholder||"");if(state)state.innerHTML=GATED&&!locked?' \xB7 signed in \xB7 <a href="#" class="sm-lock-out">Sign out</a>':""});identityUi()}
2164
- function signIn(box){if(!box)return;var u=box.querySelector(".sm-lock-user").value.trim(),p=box.querySelector(".sm-lock-pass").value,err=box.querySelector(".sm-err");if(!u){err.textContent="Enter the presenter user";return}var c=btoa(u+":"+p);err.textContent="";fetch("/mock/presenter",{headers:{authorization:"Basic "+c}}).then(function(r){if(!r.ok)throw new Error(r.status===401||r.status===403?"Wrong user or password":"Sign-in failed ("+r.status+")");setCred(c);lockUi();box.querySelector(".sm-composer-text").focus()}).catch(function(e){err.textContent=e.message})}
2165
- document.addEventListener("click",function(e){var pick=e.target.closest(".sm-identity-list button");if(pick){setIdentity(pick.dataset.user);identityUi();pick.closest(".sm-identity").open=false;return}if(!e.target.closest(".sm-identity"))document.querySelectorAll(".sm-identity[open]").forEach(function(chip){chip.open=false});var out=e.target.closest(".sm-lock-out");if(out){e.preventDefault();setCred("");lockUi();return}var go=e.target.closest(".sm-lock-go");if(go)signIn(go.closest(".sm-composer"))});
2166
- document.addEventListener("keydown",function(e){if(e.key!=="Escape")return;var chip=document.querySelector(".sm-identity[open]");if(!chip)return;e.preventDefault();e.stopImmediatePropagation();chip.open=false;chip.querySelector("summary").focus()});
2167
- document.addEventListener("keydown",function(e){if(e.key==="Escape"&&reactionDialog&&reactionDialog.open){e.preventDefault();e.stopImmediatePropagation();closeReactions(true)}});
2168
- document.addEventListener("keydown",function(e){var c=e.target.classList;if(e.key==="Enter"&&c&&(c.contains("sm-lock-pass")||c.contains("sm-lock-user"))){e.preventDefault();signIn(e.target.closest(".sm-composer"))}});
2169
- addEventListener("storage",function(e){if(e.key===IK){currentIdentity=e.newValue||"";identityUi()}});
2170
- lockUi();
2171
- var pending=null;
2172
- function refresh(){if(pending)return;pending=setTimeout(function(){pending=null;fetch(location.href,{headers:{accept:"text/html"},credentials:"same-origin"}).then(function(r){return r.ok?r.text():Promise.reject(r.status)}).then(apply).catch(function(){reactionUi()})},120)}
2173
- function apply(html){
2174
- var doc=new DOMParser().parseFromString(html,"text/html"),opener=document.activeElement,focusedMessage=opener&&opener.classList.contains("sm-add-reaction")?opener.closest(".sm-msg"):null,focusedScope=focusedMessage&&focusedMessage.closest(".sm-page,.sm-panel-body");
2175
- reactionUi();reactionUi(doc);[".sm-side",".sm-channel-switch",".sm-page",".sm-panel-body"].forEach(function(sel){var cur=document.querySelector(sel),nxt=doc.querySelector(sel);if(!cur||!nxt)return;var seen={};cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){el.classList.remove("sm-msg-new","sm-msg-changed");seen[el.dataset.ts]=el.outerHTML});var atBottom=cur.scrollHeight-cur.scrollTop-cur.clientHeight<80;cur.innerHTML=nxt.innerHTML;cur.querySelectorAll(".sm-msg[data-ts]").forEach(function(el){var prev=seen[el.dataset.ts];if(prev===undefined)el.classList.add("sm-msg-new");else if(prev!==el.outerHTML)el.classList.add("sm-msg-changed")});if(atBottom)cur.scrollTop=cur.scrollHeight});identityUi();positionReactions();if(doc.title)document.title=doc.title;
2176
- if(focusedMessage&&!opener.isConnected){var message=findMessageElement(focusedScope,focusedMessage.dataset.ts);if(message)message.querySelector(".sm-add-reaction").focus({preventScroll:true})}
2228
+ function messageChangedEvent(store, m, previous) {
2229
+ const channel = store.channel(m.channel);
2230
+ const ts = nextTs();
2231
+ return {
2232
+ type: "message",
2233
+ subtype: "message_changed",
2234
+ channel: m.channel,
2235
+ channel_type: store.channelType(channel),
2236
+ hidden: true,
2237
+ ts,
2238
+ event_ts: ts,
2239
+ message: {
2240
+ ...wireMessage(m),
2241
+ channel: undefined,
2242
+ source_team: store.team.id,
2243
+ user_team: store.team.id
2244
+ },
2245
+ previous_message: { ...wireMessage(previous), channel: undefined }
2246
+ };
2177
2247
  }
2178
- if(LIVE&&window.EventSource){
2179
- var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
2180
- if(chan){
2181
- var h1=document.querySelector(".sm-top h1"),dot=null;
2182
- if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="\u25CF live";h1.appendChild(dot)}
2183
- var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
2184
- es.addEventListener("change",refresh);
2185
- es.onopen=function(){if(dot){dot.textContent="\u25CF live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
2186
- es.onerror=function(){down=true;if(dot){dot.textContent="\u25CF reconnecting";dot.classList.add("sm-live-off")}};
2187
- }
2248
+ function messageDeletedEvent(store, m) {
2249
+ const channel = store.channel(m.channel);
2250
+ const ts = nextTs();
2251
+ return {
2252
+ type: "message",
2253
+ subtype: "message_deleted",
2254
+ channel: m.channel,
2255
+ channel_type: store.channelType(channel),
2256
+ hidden: true,
2257
+ deleted_ts: m.ts,
2258
+ ts,
2259
+ event_ts: ts,
2260
+ previous_message: { ...wireMessage(m), channel: undefined }
2261
+ };
2188
2262
  }
2189
- function react(message,name){
2190
- var u=identity();if(!message||!u||reactionBusy||(GATED&&!cred()))return;
2191
- var action="add";message.querySelectorAll(".sm-reaction[data-reaction]").forEach(function(button){if(button.dataset.reaction===name&&hasReaction(button,u.id))action="remove"});
2192
- var err=(reactionDialog&&reactionDialog.open?reactionDialog:message).querySelector(".sm-action-error");if(err){err.hidden=true;err.textContent=""}
2193
- reactionBusy=true;reactionUi();
2194
- fetch("/mock/reactions",{method:"POST",headers:authHeaders({"content-type":"application/json"}),body:JSON.stringify({channel:message.dataset.channel,ts:message.dataset.ts,name:name,user:u.id,action:action})}).then(function(r){
2195
- if(r.status===401||r.status===403){setCred("");lockUi();throw new Error("Sign in to react.")}
2196
- return r.json().then(function(data){if(!r.ok&&data.error!=="already_reacted"&&data.error!=="no_reaction")throw new Error("Could not save the reaction. Try again.")})
2197
- }).then(function(){reactionBusy=false;reactionUi();closeReactions(true);refresh()}).catch(function(e){reactionBusy=false;reactionUi();if(err){if(err.closest("dialog")&&!reactionDialog.open)err=message.querySelector(".sm-action-error");err.textContent=e.message==="Sign in to react."?e.message:"Could not save the reaction. Try again.";err.hidden=false;positionReactions()}})
2263
+ function reactionEvent(kind, m, name, user) {
2264
+ return {
2265
+ type: kind,
2266
+ user,
2267
+ reaction: name,
2268
+ item_user: m.user,
2269
+ item: { type: "message", channel: m.channel, ts: m.ts },
2270
+ event_ts: nextTs()
2271
+ };
2198
2272
  }
2199
- document.addEventListener("click",function(e){
2200
- var add=e.target.closest(".sm-add-reaction");if(add&&!add.disabled){var message=add.closest(".sm-msg");if(reactionDialog.open&&reactionTarget===message){closeReactions(true);return}reactionTarget=message;reactionScope=message.closest(".sm-page,.sm-panel-body");var err=reactionDialog.querySelector(".sm-action-error");err.hidden=true;err.textContent="";if(!reactionDialog.open)reactionDialog.show();positionReactions();return}
2201
- var choice=e.target.closest("button[data-reaction]");if(choice&&!choice.disabled){react(choice.closest(".sm-reaction-picker")?reactionTarget:choice.closest(".sm-msg"),choice.dataset.reaction);return}
2202
- if(e.target.closest(".sm-reaction-close")){closeReactions(true);return}
2203
- var reply=e.target.closest(".sm-reply-action"),box=document.querySelector(".sm-composer[data-thread]");if(reply&&box&&box.dataset.thread===reply.dataset.thread&&box.dataset.channel===reply.closest(".sm-msg").dataset.channel)e.preventDefault()
2204
- });
2205
- function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim(),user=identity();if(!text||t.disabled||!user)return;var body={channel:box.dataset.channel,user:user.id,text:text};if(box.dataset.thread)body.thread_ts=box.dataset.thread;t.disabled=true;fetch("/mock/messages",{method:"POST",headers:authHeaders({"content-type":"application/json"}),body:JSON.stringify(body)}).then(function(r){t.disabled=false;if(r.status===401||r.status===403){setCred("");lockUi();var err=box.querySelector(".sm-err");if(err)err.textContent="Not signed in, or the credential changed. Sign in to post.";return}if(!r.ok)throw new Error("send failed "+r.status);t.value="";if(LIVE)refresh();else location.reload()}).catch(function(){t.disabled=false})}
2206
- document.querySelectorAll(".sm-composer").forEach(function(box){
2207
- var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
2208
- function close(){items=[];menu.style.display="none"}
2209
- function prefix(){var m=/(?:^|\\s)@(\\w*)$/.exec(ta.value.slice(0,ta.selectionStart));return m?m[1]:null}
2210
- function paint(){menu.querySelectorAll(".sm-mention").forEach(function(el,i){el.className="sm-mention"+(i===active?" sm-mention-on":"")})}
2211
- function show(){
2212
- var q=prefix();if(q===null)return close();
2213
- var low=q.toLowerCase();
2214
- var list=PEOPLE.filter(function(u){return !low||u.name.toLowerCase().indexOf(low)===0||u.real.toLowerCase().indexOf(low)===0}).slice(0,8);
2215
- if(!list.length)return close();
2216
- items=list;active=0;
2217
- menu.innerHTML=list.map(function(u,i){return '<div class="sm-mention'+(i?"":" sm-mention-on")+'" data-i="'+i+'"><span class="sm-mention-av" style="background:'+esc(u.color)+'">'+esc(u.initials)+'</span><span class="sm-mention-name">@'+esc(u.name)+'</span><span class="sm-mention-real">'+esc(u.real)+'</span></div>'}).join("");
2218
- menu.style.display="block";
2219
- }
2220
- function pick(i){var u=items[i];if(!u)return;var pos=ta.selectionStart,before=ta.value.slice(0,pos).replace(/@\\w*$/,"@"+u.name+" "),after=ta.value.slice(pos);ta.value=before+after;ta.selectionStart=ta.selectionEnd=before.length;close();ta.focus()}
2221
- ta.addEventListener("input",show);
2222
- ta.addEventListener("blur",function(){setTimeout(close,150)});
2223
- menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
2224
- ta.addEventListener("keydown",function(e){
2225
- if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
2226
- var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
2227
- for(var k=0;k<PEOPLE.length;k++){var tok="@"+PEOPLE[k].name;var cand=before.endsWith(tok)?tok:"";if(cand&&cand.length>hit.length){var at=before.length-cand.length;if(at===0||/s/.test(before.charAt(at-1)))hit=cand}}
2228
- if(hit){e.preventDefault();ta.value=before.slice(0,before.length-hit.length)+ta.value.slice(pos);ta.selectionStart=ta.selectionEnd=pos-hit.length;close();return}
2229
- }
2230
- if(items.length){
2231
- if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
2232
- if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
2233
- if(e.key==="Enter"||e.key==="Tab"){e.preventDefault();pick(active);return}
2234
- if(e.key==="Escape"){e.preventDefault();e.stopPropagation();close();return}
2235
- }
2236
- if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send(box)}
2237
- });
2238
- box.querySelector(".sm-composer-send").addEventListener("click",function(){send(box)});
2239
- });
2240
- })();`;
2241
- return `${mentionData(store)}${reactionPicker()}<script>${body}${esc}</script>`;
2273
+ function memberJoinedEvent(store, channel, user, inviter) {
2274
+ return {
2275
+ type: "member_joined_channel",
2276
+ user,
2277
+ channel: channel.id,
2278
+ channel_type: store.channelType(channel) === "channel" ? "C" : "G",
2279
+ team: store.team.id,
2280
+ inviter,
2281
+ event_ts: nextTs()
2282
+ };
2242
2283
  }
2243
- function channelView(store, opts, channelId) {
2244
- const channel = store.channels.get(channelId);
2245
- const ctx = ctxOf(store);
2246
- if (!channel)
2247
- return notFound(store, opts, "Channel not found");
2248
- const label = channelLabel(store, channel);
2249
- return shell(store, opts, {
2250
- title: `${label} \xB7 slack-mock`,
2251
- header: channelHeader(store, opts, channel),
2252
- main: channelColumn(store, ctx, opts, channel),
2253
- active: channel.id,
2254
- footer: composer(store, opts, channel),
2255
- script: opts.screenshot ? "" : uiScript(store, opts)
2256
- });
2284
+ function assistantThreadStartedEvent(store, dm, user, threadTs, context = {}) {
2285
+ return {
2286
+ type: "assistant_thread_started",
2287
+ assistant_thread: {
2288
+ user_id: user,
2289
+ context: { team_id: store.team.id, enterprise_id: null, ...context },
2290
+ channel_id: dm.id,
2291
+ thread_ts: threadTs
2292
+ },
2293
+ event_ts: nextTs()
2294
+ };
2257
2295
  }
2258
- function assistantPanel(store, channelId, ts) {
2259
- const thread = store.assistantThreads.get(`${channelId}:${ts}`);
2260
- if (!thread)
2261
- return "";
2262
- const parts = [];
2263
- if (thread.title)
2264
- parts.push(`<div class="sm-assist-title">${plainTextToHtml(thread.title)}</div>`);
2265
- if (thread.status)
2266
- parts.push(`<div class="sm-assist-status">${plainTextToHtml(thread.status)}<span class="sm-stream">\u2022\u2022\u2022</span></div>`);
2267
- const prompts = Array.isArray(thread.prompts) ? thread.prompts : [];
2268
- if (prompts.length) {
2269
- const chips = prompts.map((p) => {
2270
- const prompt = typeof p === "object" && p !== null ? p : {};
2271
- const title = typeof prompt.title === "string" ? prompt.title : "";
2272
- const message = typeof prompt.message === "string" ? prompt.message : "";
2273
- return `<span class="sm-prompt" title="${escapeHtml(message)}">${plainTextToHtml(title || message)}</span>`;
2274
- }).join("");
2275
- const heading = thread.promptsTitle ? `<div class="sm-assist-status">${plainTextToHtml(thread.promptsTitle)}</div>` : "";
2276
- parts.push(`${heading}<div class="sm-prompts">${chips}</div>`);
2277
- }
2278
- if (!parts.length)
2279
- return "";
2280
- return `<div class="sm-assist">${parts.join("")}</div>`;
2296
+ function assistantThreadContextChangedEvent(store, dm, user, threadTs, context) {
2297
+ return {
2298
+ type: "assistant_thread_context_changed",
2299
+ assistant_thread: {
2300
+ user_id: user,
2301
+ context: { team_id: store.team.id, enterprise_id: null, ...context },
2302
+ channel_id: dm.id,
2303
+ thread_ts: threadTs
2304
+ },
2305
+ event_ts: nextTs()
2306
+ };
2281
2307
  }
2282
- function threadView(store, opts, channelId, ts) {
2283
- const channel = store.channels.get(channelId);
2284
- const ctx = ctxOf(store);
2285
- if (!channel)
2286
- return notFound(store, opts, "Channel not found");
2287
- const parent = store.findMessage(channel.id, ts);
2288
- if (!parent)
2289
- return notFound(store, opts, "Message not found");
2290
- const items = store.replies(channel.id, ts, { limit: 1000 }).items;
2291
- const replies = items.slice(1);
2292
- const label = channelLabel(store, channel);
2293
- const repliesBar = replies.length ? `<div class="sm-daydiv"><span>${replies.length} ${replies.length === 1 ? "reply" : "replies"}</span></div>` : `<div class="sm-empty">No replies yet</div>`;
2294
- const body = `${assistantPanel(store, channel.id, ts)}${renderMessage(store, ctx, parent, opts)}${repliesBar}${renderMessageList(store, ctx, replies, opts, { dividers: false })}`;
2295
- if (opts.screenshot) {
2296
- const header = topbar(`Thread <span class="sm-muted">\xB7</span> <a href="${channelHref(channel.id, opts)}">${escapeHtml(label)}</a>`, "");
2297
- return shell(store, opts, {
2298
- title: `Thread \xB7 ${label}`,
2299
- header,
2300
- main: body,
2301
- active: channel.id
2302
- });
2303
- }
2304
- const close = channelHref(channel.id, opts);
2305
- const title = `Thread \xB7 ${label}`;
2306
- if (opts.threadView === "full") {
2307
- const header = topbar(`Thread <span class="sm-muted">\xB7</span> ${escapeHtml(label)}`, "", { href: close, label: `\u2190 ${label}` }, `<a class="sm-icon-btn" href="${threadHref(channel.id, ts, opts, { full: false })}" title="Collapse to panel" aria-label="Collapse to panel">\u2921</a>${identityChip(store, opts)}`);
2308
- return shell(store, opts, {
2309
- title,
2310
- header,
2311
- main: body,
2312
- active: channel.id,
2313
- footer: composer(store, opts, channel, ts),
2314
- script: uiScript(store, opts, close)
2315
- });
2316
- }
2317
- const expand = threadHref(channel.id, ts, opts, { full: true });
2318
- const panel = `<aside class="sm-panel"><div class="sm-panel-top"><a class="sm-panel-back" href="${close}" aria-label="Back to ${escapeHtml(label)}">\u2190</a><div class="sm-panel-heading"><h2 class="sm-panel-title">Thread</h2><div class="sm-panel-sub">${escapeHtml(label)}</div></div><a class="sm-panel-expand" href="${expand}" title="Expand thread">\u2922</a><a class="sm-panel-close" href="${close}" title="Close thread">\xD7</a></div><div class="sm-panel-body sm-scroll">${body}</div>${composer(store, opts, channel, ts)}</aside>`;
2319
- return shell(store, opts, {
2320
- title,
2321
- header: channelHeader(store, opts, channel),
2322
- main: channelColumn(store, ctx, opts, channel, ts),
2323
- active: channel.id,
2324
- panel,
2325
- footer: composer(store, opts, channel),
2326
- script: uiScript(store, opts, close)
2327
- });
2308
+ function slashCommandPayload(store, input) {
2309
+ return {
2310
+ token: VERIFICATION_TOKEN,
2311
+ team_id: store.team.id,
2312
+ team_domain: store.team.domain,
2313
+ channel_id: input.channel.id,
2314
+ channel_name: input.channel.is_im ? "directmessage" : input.channel.name,
2315
+ user_id: input.user.id,
2316
+ user_name: input.user.name,
2317
+ command: input.command,
2318
+ text: input.text,
2319
+ api_app_id: store.app.id,
2320
+ is_enterprise_install: "false",
2321
+ response_url: input.responseUrl,
2322
+ trigger_id: input.triggerId
2323
+ };
2328
2324
  }
2329
- function notFound(store, opts, message) {
2330
- return shell(store, opts, {
2331
- title: message,
2332
- header: topbar(escapeHtml(message), ""),
2333
- main: `<div class="sm-empty">${escapeHtml(message)}</div>`
2334
- });
2325
+ function blockActionsPayload(store, input) {
2326
+ return {
2327
+ type: "block_actions",
2328
+ user: {
2329
+ id: input.user.id,
2330
+ username: input.user.name,
2331
+ name: input.user.name,
2332
+ team_id: store.team.id
2333
+ },
2334
+ api_app_id: store.app.id,
2335
+ token: VERIFICATION_TOKEN,
2336
+ container: {
2337
+ type: "message",
2338
+ message_ts: input.message.ts,
2339
+ channel_id: input.channel.id,
2340
+ is_ephemeral: !!input.message.ephemeral_user,
2341
+ ...input.message.thread_ts ? { thread_ts: input.message.thread_ts } : {}
2342
+ },
2343
+ trigger_id: input.triggerId,
2344
+ team: { id: store.team.id, domain: store.team.domain },
2345
+ enterprise: null,
2346
+ is_enterprise_install: false,
2347
+ channel: { id: input.channel.id, name: input.channel.name },
2348
+ message: wireMessage(input.message),
2349
+ state: { values: {} },
2350
+ response_url: input.responseUrl,
2351
+ actions: input.actions.map((a) => ({ action_ts: nextTs(), ...a }))
2352
+ };
2335
2353
  }
2336
- function renderPage(store, view, opts = {}) {
2337
- switch (view.kind) {
2338
- case "channel":
2339
- return channelView(store, opts, view.channel);
2340
- case "thread":
2341
- return threadView(store, opts, view.channel, view.ts);
2342
- default:
2343
- return indexView(store, opts);
2344
- }
2354
+ function viewSubmissionPayload(store, input) {
2355
+ const { opened_by: _o, trigger_id: _t, ...view } = input.view;
2356
+ return {
2357
+ type: "view_submission",
2358
+ team: { id: store.team.id, domain: store.team.domain },
2359
+ user: {
2360
+ id: input.user.id,
2361
+ username: input.user.name,
2362
+ name: input.user.name,
2363
+ team_id: store.team.id
2364
+ },
2365
+ api_app_id: store.app.id,
2366
+ token: VERIFICATION_TOKEN,
2367
+ trigger_id: input.triggerId,
2368
+ view: { ...view, state: { values: input.values } },
2369
+ response_urls: [],
2370
+ is_enterprise_install: false,
2371
+ enterprise: null
2372
+ };
2345
2373
  }
2346
2374
 
2347
2375
  // src/socket-mode.ts
@@ -2520,7 +2548,7 @@ class SocketModeHub {
2520
2548
 
2521
2549
  // src/web-api.ts
2522
2550
  function required(args, key) {
2523
- const v = str(args, key);
2551
+ const v = str2(args, key);
2524
2552
  if (!v)
2525
2553
  throw new SlackApiError2("invalid_arguments", {
2526
2554
  response_metadata: { messages: [`[ERROR] missing required field: ${key}`] }
@@ -2557,8 +2585,17 @@ function botFields(ctx) {
2557
2585
  }
2558
2586
  };
2559
2587
  }
2588
+ function markdownText(args) {
2589
+ const markdown = str2(args, "markdown_text");
2590
+ if (markdown === undefined)
2591
+ return;
2592
+ if (str2(args, "text") || Array.isArray(args.blocks) && args.blocks.length)
2593
+ throw new SlackApiError2("markdown_text_conflict");
2594
+ return markdown;
2595
+ }
2560
2596
  function messageContent(args) {
2561
- const text = str(args, "text") ?? "";
2597
+ const markdown = markdownText(args);
2598
+ const text = markdown ?? str2(args, "text") ?? "";
2562
2599
  const blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
2563
2600
  const attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
2564
2601
  if (!text && !blocks?.length && !attachments?.length)
@@ -2568,7 +2605,13 @@ function messageContent(args) {
2568
2605
  response_metadata: { messages: ["[ERROR] must have at most 50 blocks"] }
2569
2606
  });
2570
2607
  const metadata = args.metadata && typeof args.metadata === "object" ? args.metadata : undefined;
2571
- return { text, blocks, attachments, metadata };
2608
+ return {
2609
+ text,
2610
+ blocks,
2611
+ attachments,
2612
+ metadata,
2613
+ ...markdown !== undefined ? { text_format: "markdown" } : {}
2614
+ };
2572
2615
  }
2573
2616
  function channelInfo(store, c, actor) {
2574
2617
  const { members, ...rest } = c;
@@ -2627,18 +2670,18 @@ var handlers = {
2627
2670
  "chat.postMessage": (ctx, args) => {
2628
2671
  const channel = resolveChannel(ctx.store, required(args, "channel"));
2629
2672
  requireMember(channel, ctx.actor);
2630
- const threadTs = str(args, "thread_ts");
2673
+ const threadTs = str2(args, "thread_ts");
2631
2674
  const message = ctx.store.addMessage({
2632
2675
  channel: channel.id,
2633
2676
  user: ctx.actor.userId,
2634
2677
  ...messageContent(args),
2635
2678
  ...threadTs ? { thread_ts: threadTs } : {},
2636
2679
  ...bool(args, "reply_broadcast") && threadTs ? { subtype: "thread_broadcast" } : {},
2637
- ...str(args, "username") ? { username: str(args, "username") } : {},
2638
- ...str(args, "icon_emoji") || str(args, "icon_url") ? {
2680
+ ...str2(args, "username") ? { username: str2(args, "username") } : {},
2681
+ ...str2(args, "icon_emoji") || str2(args, "icon_url") ? {
2639
2682
  icons: {
2640
- ...str(args, "icon_emoji") ? { emoji: str(args, "icon_emoji") } : {},
2641
- ...str(args, "icon_url") ? { image_64: str(args, "icon_url") } : {}
2683
+ ...str2(args, "icon_emoji") ? { emoji: str2(args, "icon_emoji") } : {},
2684
+ ...str2(args, "icon_url") ? { image_64: str2(args, "icon_url") } : {}
2642
2685
  }
2643
2686
  } : {},
2644
2687
  ...botFields(ctx)
@@ -2649,7 +2692,7 @@ var handlers = {
2649
2692
  const channel = resolveChannel(ctx.store, required(args, "channel"));
2650
2693
  const user = required(args, "user");
2651
2694
  ctx.store.user(user);
2652
- const threadTs = str(args, "thread_ts");
2695
+ const threadTs = str2(args, "thread_ts");
2653
2696
  const message = ctx.store.addMessage({
2654
2697
  channel: channel.id,
2655
2698
  user: ctx.actor.userId,
@@ -2667,10 +2710,19 @@ var handlers = {
2667
2710
  if (existing.user !== ctx.actor.userId && !ctx.actor.isBot)
2668
2711
  throw new SlackApiError2("cant_update_message");
2669
2712
  const patch = {};
2670
- if (args.text !== undefined)
2671
- patch.text = str(args, "text") ?? "";
2672
- if (args.blocks !== undefined)
2713
+ const markdown = markdownText(args);
2714
+ if (markdown !== undefined) {
2715
+ patch.text = markdown;
2716
+ patch.text_format = "markdown";
2717
+ } else if (args.text !== undefined) {
2718
+ patch.text = str2(args, "text") ?? "";
2719
+ patch.text_format = undefined;
2720
+ }
2721
+ if (args.blocks !== undefined) {
2673
2722
  patch.blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
2723
+ if (existing.streaming_state !== undefined)
2724
+ patch.stream_replaced = true;
2725
+ }
2674
2726
  if (args.attachments !== undefined)
2675
2727
  patch.attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
2676
2728
  if (args.metadata !== undefined)
@@ -2689,15 +2741,15 @@ var handlers = {
2689
2741
  "chat.startStream": (ctx, args) => {
2690
2742
  const channel = resolveChannel(ctx.store, required(args, "channel"));
2691
2743
  requireMember(channel, ctx.actor);
2692
- const threadTs = str(args, "thread_ts");
2744
+ const threadTs = str2(args, "thread_ts");
2693
2745
  const message = ctx.store.addMessage({
2694
2746
  channel: channel.id,
2695
2747
  user: ctx.actor.userId,
2696
2748
  text: streamText(args),
2697
2749
  streaming_state: "in_progress",
2698
2750
  ...threadTs ? { thread_ts: threadTs } : {},
2699
- ...str(args, "username") ? { username: str(args, "username") } : {},
2700
- ...str(args, "icon_emoji") ? { icons: { emoji: str(args, "icon_emoji") } } : {},
2751
+ ...str2(args, "username") ? { username: str2(args, "username") } : {},
2752
+ ...str2(args, "icon_emoji") ? { icons: { emoji: str2(args, "icon_emoji") } } : {},
2701
2753
  ...botFields(ctx)
2702
2754
  });
2703
2755
  return { channel: channel.id, ts: message.ts };
@@ -2721,8 +2773,10 @@ var handlers = {
2721
2773
  streaming_state: "completed",
2722
2774
  text: existing.text + streamText(args)
2723
2775
  };
2724
- if (Array.isArray(args.blocks))
2776
+ if (Array.isArray(args.blocks)) {
2725
2777
  patch.blocks = args.blocks;
2778
+ patch.stream_replaced = undefined;
2779
+ }
2726
2780
  const message = ctx.store.updateMessage(channel.id, ts, patch, ctx.actor.userId, {
2727
2781
  markEdited: false
2728
2782
  });
@@ -2738,7 +2792,7 @@ var handlers = {
2738
2792
  };
2739
2793
  },
2740
2794
  "conversations.list": (ctx, args) => {
2741
- const types = new Set((str(args, "types") ?? "public_channel").split(",").map((t) => t.trim()));
2795
+ const types = new Set((str2(args, "types") ?? "public_channel").split(",").map((t) => t.trim()));
2742
2796
  const excludeArchived = bool(args, "exclude_archived") ?? false;
2743
2797
  const all = [...ctx.store.channels.values()].filter((c) => {
2744
2798
  if (excludeArchived && c.is_archived)
@@ -2752,7 +2806,7 @@ var handlers = {
2752
2806
  return types.has("public_channel");
2753
2807
  });
2754
2808
  const limit = num(args, "limit", 100);
2755
- const start = cursorOffset(str(args, "cursor"));
2809
+ const start = cursorOffset(str2(args, "cursor"));
2756
2810
  const slice = all.slice(start, start + limit);
2757
2811
  const hasMore = start + limit < all.length;
2758
2812
  return {
@@ -2805,6 +2859,10 @@ var handlers = {
2805
2859
  ...errors.length ? { errors } : {}
2806
2860
  };
2807
2861
  },
2862
+ "conversations.leave": (ctx, args) => {
2863
+ const { notInChannel } = ctx.store.leave(required(args, "channel"), ctx.actor.userId);
2864
+ return notInChannel ? { ok: false, not_in_channel: true } : {};
2865
+ },
2808
2866
  "conversations.archive": (ctx, args) => {
2809
2867
  ctx.store.archive(required(args, "channel"));
2810
2868
  return {};
@@ -2814,7 +2872,7 @@ var handlers = {
2814
2872
  return { members: channel.members, response_metadata: { next_cursor: "" } };
2815
2873
  },
2816
2874
  "conversations.open": (ctx, args) => {
2817
- const users = (str(args, "users") ?? "").split(",").map((u) => u.trim()).filter(Boolean);
2875
+ const users = (str2(args, "users") ?? "").split(",").map((u) => u.trim()).filter(Boolean);
2818
2876
  if (users.length !== 1)
2819
2877
  throw new SlackApiError2("users_list_not_supplied");
2820
2878
  const dm = ctx.store.openDm(users[0]);
@@ -2824,11 +2882,11 @@ var handlers = {
2824
2882
  const channel = ctx.store.channel(required(args, "channel"));
2825
2883
  requireMember(channel, ctx.actor);
2826
2884
  const p = ctx.store.history(channel.id, {
2827
- oldest: str(args, "oldest"),
2828
- latest: str(args, "latest"),
2885
+ oldest: str2(args, "oldest"),
2886
+ latest: str2(args, "latest"),
2829
2887
  inclusive: bool(args, "inclusive"),
2830
2888
  limit: num(args, "limit", 100),
2831
- cursor: str(args, "cursor")
2889
+ cursor: str2(args, "cursor")
2832
2890
  });
2833
2891
  return {
2834
2892
  messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
@@ -2844,11 +2902,11 @@ var handlers = {
2844
2902
  if (!ctx.store.findMessage(channel.id, ts))
2845
2903
  throw new SlackApiError2("thread_not_found");
2846
2904
  const p = ctx.store.replies(channel.id, ts, {
2847
- oldest: str(args, "oldest"),
2848
- latest: str(args, "latest"),
2905
+ oldest: str2(args, "oldest"),
2906
+ latest: str2(args, "latest"),
2849
2907
  inclusive: bool(args, "inclusive"),
2850
2908
  limit: num(args, "limit", 1000),
2851
- cursor: str(args, "cursor")
2909
+ cursor: str2(args, "cursor")
2852
2910
  });
2853
2911
  return {
2854
2912
  messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
@@ -2868,7 +2926,7 @@ var handlers = {
2868
2926
  return { user };
2869
2927
  },
2870
2928
  "users.conversations": (ctx, args) => {
2871
- const user = str(args, "user") ?? ctx.actor.userId;
2929
+ const user = str2(args, "user") ?? ctx.actor.userId;
2872
2930
  const channels = [...ctx.store.channels.values()].filter((c) => c.members.includes(user) && !c.is_im);
2873
2931
  return {
2874
2932
  channels: channels.map((c) => channelInfo(ctx.store, c, ctx.actor)),
@@ -2905,7 +2963,7 @@ var handlers = {
2905
2963
  ctx.pendingUploads.set(id, {
2906
2964
  name: filename,
2907
2965
  length,
2908
- alt_text: str(args, "alt_text"),
2966
+ alt_text: str2(args, "alt_text"),
2909
2967
  user: ctx.actor.userId
2910
2968
  });
2911
2969
  return { upload_url: `${ctx.baseUrl}/upload/v1/${id}`, file_id: id };
@@ -2922,19 +2980,19 @@ var handlers = {
2922
2980
  f.title = title;
2923
2981
  return f;
2924
2982
  });
2925
- const channelId = str(args, "channel_id");
2983
+ const channelId = str2(args, "channel_id");
2926
2984
  if (channelId) {
2927
2985
  const channel = ctx.store.channel(channelId);
2928
2986
  requireMember(channel, ctx.actor);
2929
2987
  for (const f of files)
2930
2988
  if (!f.channels.includes(channel.id))
2931
2989
  f.channels.push(channel.id);
2932
- const threadTs = str(args, "thread_ts");
2990
+ const threadTs = str2(args, "thread_ts");
2933
2991
  ctx.store.addMessage({
2934
2992
  channel: channel.id,
2935
2993
  user: ctx.actor.userId,
2936
2994
  subtype: "file_share",
2937
- text: str(args, "initial_comment") ?? "",
2995
+ text: str2(args, "initial_comment") ?? "",
2938
2996
  files,
2939
2997
  ...threadTs ? { thread_ts: threadTs } : {},
2940
2998
  ...botFields(ctx)
@@ -2962,13 +3020,13 @@ var handlers = {
2962
3020
  });
2963
3021
  const stored = ctx.store.openView({
2964
3022
  type: "modal",
2965
- callback_id: str(view, "callback_id"),
2966
- private_metadata: str(view, "private_metadata") ?? "",
3023
+ callback_id: str2(view, "callback_id"),
3024
+ private_metadata: str2(view, "private_metadata") ?? "",
2967
3025
  title: view.title,
2968
3026
  submit: view.submit,
2969
3027
  close: view.close,
2970
3028
  blocks: Array.isArray(view.blocks) ? view.blocks : [],
2971
- external_id: str(view, "external_id"),
3029
+ external_id: str2(view, "external_id"),
2972
3030
  opened_by: "",
2973
3031
  trigger_id: triggerId,
2974
3032
  state: { values: {} },
@@ -2984,8 +3042,8 @@ var handlers = {
2984
3042
  throw new SlackApiError2("not_found");
2985
3043
  const view = viewArg(args);
2986
3044
  Object.assign(existing, {
2987
- callback_id: str(view, "callback_id") ?? existing.callback_id,
2988
- private_metadata: str(view, "private_metadata") ?? existing.private_metadata,
3045
+ callback_id: str2(view, "callback_id") ?? existing.callback_id,
3046
+ private_metadata: str2(view, "private_metadata") ?? existing.private_metadata,
2989
3047
  title: view.title ?? existing.title,
2990
3048
  submit: view.submit ?? existing.submit,
2991
3049
  close: view.close ?? existing.close,
@@ -3000,7 +3058,7 @@ var handlers = {
3000
3058
  const channel = ctx.store.channel(required(args, "channel_id"));
3001
3059
  const threadTs = required(args, "thread_ts");
3002
3060
  const t = ctx.store.assistantThread(channel.id, threadTs);
3003
- t.status = str(args, "status") ?? "";
3061
+ t.status = str2(args, "status") ?? "";
3004
3062
  ctx.store.onChangeEmit({
3005
3063
  kind: "assistant.status",
3006
3064
  channel: channel.id,
@@ -3009,6 +3067,17 @@ var handlers = {
3009
3067
  });
3010
3068
  return {};
3011
3069
  },
3070
+ "agents.sessions.setStatus": (ctx, args) => {
3071
+ const channel = ctx.store.channel(required(args, "channel_id"));
3072
+ const status = required(args, "status");
3073
+ if (!["active", "processing", "suspended", "closed"].includes(status))
3074
+ throw new SlackApiError2("invalid_status");
3075
+ const threadTs = str2(args, "thread_ts");
3076
+ if (!threadTs)
3077
+ throw new SlackApiError2("thread_ts_required");
3078
+ ctx.store.assistantThread(channel.id, threadTs).sessionStatus = status;
3079
+ return { status, agent_status: status };
3080
+ },
3012
3081
  "assistant.threads.setTitle": (ctx, args) => {
3013
3082
  const channel = ctx.store.channel(required(args, "channel_id"));
3014
3083
  const threadTs = required(args, "thread_ts");
@@ -3027,7 +3096,7 @@ var handlers = {
3027
3096
  const threadTs = required(args, "thread_ts");
3028
3097
  const t = ctx.store.assistantThread(channel.id, threadTs);
3029
3098
  t.prompts = Array.isArray(args.prompts) ? args.prompts : [];
3030
- t.promptsTitle = str(args, "title");
3099
+ t.promptsTitle = str2(args, "title");
3031
3100
  ctx.store.onChangeEmit({
3032
3101
  kind: "assistant.prompts",
3033
3102
  channel: channel.id,
@@ -3044,7 +3113,7 @@ var handlers = {
3044
3113
  }
3045
3114
  };
3046
3115
  function streamText(args) {
3047
- const md = str(args, "markdown_text");
3116
+ const md = str2(args, "markdown_text");
3048
3117
  if (md)
3049
3118
  return md;
3050
3119
  const chunks = Array.isArray(args.chunks) ? args.chunks : [];
@@ -3367,7 +3436,7 @@ class SlackMock2 {
3367
3436
  };
3368
3437
  try {
3369
3438
  const body = handler(ctx, args);
3370
- record(true);
3439
+ record(body.ok !== false);
3371
3440
  return Response.json({ ok: true, ...body });
3372
3441
  } catch (e) {
3373
3442
  if (e instanceof SlackApiError2) {
@@ -4106,9 +4175,6 @@ function denied(req, path) {
4106
4175
  }
4107
4176
 
4108
4177
  // src/frames.ts
4109
- import { copyFileSync, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync } from "fs";
4110
- import { tmpdir } from "os";
4111
- import { join, resolve } from "path";
4112
4178
  var FRAME_KINDS = new Set([
4113
4179
  "message.add",
4114
4180
  "message.update",