@desplega.ai/slack-mock 0.3.0 → 0.4.1

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.
@@ -2,2146 +2,2349 @@
2
2
  import {
3
3
  requireChrome2,
4
4
  screenshot2
5
- } from "./index-v2hesj4s.js";
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
- team: this.team.id
189
- }
190
- };
191
- this.users.set(id, user);
192
- this.emit({ kind: "user.add", user });
193
- return user;
194
- }
195
- user(id) {
196
- const u = this.users.get(id);
197
- if (!u)
198
- throw new SlackApiError2("user_not_found");
199
- return u;
200
- }
201
- userByEmail(email) {
202
- for (const u of this.users.values())
203
- if (u.profile.email === email)
204
- return u;
205
- return;
206
- }
207
- isBotUser(userId) {
208
- return userId === this.bot.userId;
209
- }
210
- addChannel(input) {
211
- const name = input.name.replace(/^#/, "");
212
- for (const c of this.channels.values()) {
213
- if (c.name === name && !c.is_im)
214
- 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()) : "";
215
180
  }
216
- const id = input.id ?? slackId(input.is_private ? "G" : "C");
217
- const creator = input.creator ?? this.bot.userId;
218
- const members = [...new Set([creator, ...input.members ?? []])];
219
- const channel = {
220
- id,
221
- name,
222
- is_channel: !input.is_private,
223
- is_group: !!input.is_private,
224
- is_im: false,
225
- is_mpim: false,
226
- is_private: !!input.is_private,
227
- is_archived: false,
228
- is_general: name === "general",
229
- created: nowUnix(),
230
- creator,
231
- topic: { value: input.topic ?? "", creator, last_set: 0 },
232
- purpose: { value: input.purpose ?? "", creator, last_set: 0 },
233
- members
234
- };
235
- this.channels.set(id, channel);
236
- this.messages.set(id, []);
237
- this.emit({ kind: "channel.add", channel });
238
- return channel;
239
- }
240
- openDm(userId) {
241
- this.user(userId);
242
- for (const c of this.channels.values())
243
- if (c.is_im && c.user === userId)
244
- return c;
245
- const id = slackId("D");
246
- const channel = {
247
- id,
248
- name: id,
249
- is_channel: false,
250
- is_group: false,
251
- is_im: true,
252
- is_mpim: false,
253
- is_private: true,
254
- is_archived: false,
255
- is_general: false,
256
- created: nowUnix(),
257
- creator: userId,
258
- user: userId,
259
- topic: { value: "", creator: "", last_set: 0 },
260
- purpose: { value: "", creator: "", last_set: 0 },
261
- members: [userId, this.bot.userId]
262
- };
263
- this.channels.set(id, channel);
264
- this.messages.set(id, []);
265
- this.emit({ kind: "channel.add", channel });
266
- return channel;
267
- }
268
- channel(id) {
269
- const c = this.channels.get(id);
270
- if (!c)
271
- throw new SlackApiError2("channel_not_found");
272
- return c;
273
- }
274
- channelByName(name) {
275
- const n = name.replace(/^#/, "");
276
- for (const c of this.channels.values())
277
- if (c.name === n)
278
- return c;
279
- return;
280
- }
281
- channelType(c) {
282
- if (c.is_im)
283
- return "im";
284
- if (c.is_mpim)
285
- return "mpim";
286
- if (c.is_private)
287
- return "group";
288
- return "channel";
181
+ return pill(`@${cmd}`);
289
182
  }
290
- join(channelId, userId, inviter) {
291
- const channel = this.channel(channelId);
292
- if (channel.is_archived)
293
- throw new SlackApiError2("is_archived");
294
- if (channel.members.includes(userId))
295
- return { alreadyMember: true };
296
- channel.members.push(userId);
297
- this.emit({ kind: "member.join", channel, user: userId, inviter });
298
- 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>`;
299
187
  }
300
- archive(channelId) {
301
- const channel = this.channel(channelId);
302
- if (channel.is_archived)
303
- throw new SlackApiError2("already_archived");
304
- if (channel.is_general)
305
- throw new SlackApiError2("cant_archive_general");
306
- channel.is_archived = true;
307
- 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);
308
238
  }
309
- insertMessage(message) {
310
- const list = this.messages.get(message.channel) ?? [];
311
- this.messages.set(message.channel, list);
312
- let i = list.length;
313
- while (i > 0 && Number(list[i - 1].ts) > Number(message.ts))
314
- i--;
315
- list.splice(i, 0, message);
316
- if (message.thread_ts && message.thread_ts !== message.ts) {
317
- const parent = this.findMessage(message.channel, message.thread_ts);
318
- if (parent) {
319
- parent.reply_count = (parent.reply_count ?? 0) + 1;
320
- const users = new Set(parent.reply_users ?? []);
321
- if (message.user)
322
- users.add(message.user);
323
- parent.reply_users = [...users];
324
- parent.reply_users_count = users.size;
325
- parent.latest_reply = message.ts;
326
- if (parent.user)
327
- message.parent_user_id = parent.user;
328
- }
329
- }
330
- }
331
- findMessage(channelId, ts) {
332
- return this.messages.get(channelId)?.find((m) => m.ts === ts);
333
- }
334
- findAnyMessage(channelId, ts) {
335
- return this.findMessage(channelId, ts) ?? this.ephemerals.find((m) => m.channel === channelId && m.ts === ts);
336
- }
337
- updateEphemeral(channelId, ts, patch) {
338
- const m = this.ephemerals.find((x) => x.channel === channelId && x.ts === ts);
339
- if (!m)
340
- throw new SlackApiError2("message_not_found");
341
- Object.assign(m, patch);
342
- return m;
343
- }
344
- deleteEphemeral(channelId, ts) {
345
- const i = this.ephemerals.findIndex((x) => x.channel === channelId && x.ts === ts);
346
- if (i < 0)
347
- throw new SlackApiError2("message_not_found");
348
- this.ephemerals.splice(i, 1);
349
- }
350
- message(channelId, ts) {
351
- const m = this.findMessage(channelId, ts);
352
- if (!m)
353
- throw new SlackApiError2("message_not_found");
354
- 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
+
278
+ // src/render/blocks.ts
279
+ function rec(v) {
280
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
281
+ }
282
+ function str(v) {
283
+ return typeof v === "string" ? v : "";
284
+ }
285
+ function arr(v) {
286
+ return Array.isArray(v) ? v : [];
287
+ }
288
+ function safeUrl(url) {
289
+ return /^(https?:\/\/|\/)/i.test(url) ? escapeHtml(url) : undefined;
290
+ }
291
+ function unsupported(what) {
292
+ return `<div class="sm-unsupported">unsupported: ${escapeHtml(what || "unknown")}</div>`;
293
+ }
294
+ function textObject(v, ctx) {
295
+ if (typeof v === "string")
296
+ return plainTextToHtml(v);
297
+ const o = rec(v);
298
+ if (!o)
299
+ return "";
300
+ const text = str(o.text);
301
+ return o.type === "mrkdwn" ? mrkdwnToHtml(text, ctx) : plainTextToHtml(text);
302
+ }
303
+ function plainOf(v) {
304
+ const o = rec(v);
305
+ return plainTextToHtml(o ? str(o.text) : str(v));
306
+ }
307
+ function image(url, alt, cls) {
308
+ const src = safeUrl(url);
309
+ if (!src)
310
+ return unsupported("image url");
311
+ return `<img class="${cls}" src="${src}" alt="${escapeHtml(alt)}">`;
312
+ }
313
+ function imageSrcOf(block) {
314
+ const direct = str(block.image_url);
315
+ if (direct)
316
+ return direct;
317
+ const file = rec(block.slack_file);
318
+ return file ? str(file.url) || str(file.url_private) : "";
319
+ }
320
+ function button(el, ctx) {
321
+ const style = str(el.style);
322
+ const cls = `sm-btn${style === "primary" ? " sm-btn-primary" : style === "danger" ? " sm-btn-danger" : ""}`;
323
+ const label = textObject(el.text, ctx) || "Button";
324
+ const url = safeUrl(str(el.url));
325
+ const confirm = rec(el.confirm) ? '<span class="sm-btn-confirm" title="confirmation dialog">\u26A0</span>' : "";
326
+ return url ? `<a class="${cls}" href="${url}" target="_blank" rel="noopener">${label}${confirm}</a>` : `<span class="${cls}">${label}${confirm}</span>`;
327
+ }
328
+ function selectPill(el, ctx, glyph = "\u25BE") {
329
+ const initial = rec(el.initial_option);
330
+ const label = initial && textObject(initial.text, ctx) || textObject(el.placeholder, ctx) || plainTextToHtml(str(el.type).replace(/_/g, " "));
331
+ return `<span class="sm-select">${label}<span class="sm-select-caret">${glyph}</span></span>`;
332
+ }
333
+ function inputBox(el, ctx) {
334
+ const multiline = el.multiline === true;
335
+ const value = str(el.initial_value);
336
+ const inner = value ? plainTextToHtml(value) : `<span class="sm-input-ph">${textObject(el.placeholder, ctx)}</span>`;
337
+ return `<div class="sm-input${multiline ? " sm-input-multi" : ""}">${inner}</div>`;
338
+ }
339
+ function renderElement(v, ctx) {
340
+ const el = rec(v);
341
+ if (!el)
342
+ return "";
343
+ const type = str(el.type);
344
+ switch (type) {
345
+ case "button":
346
+ return button(el, ctx);
347
+ case "image":
348
+ return image(imageSrcOf(el), str(el.alt_text), "sm-acc-img");
349
+ case "overflow":
350
+ return `<span class="sm-select sm-overflow">\u22EF</span>`;
351
+ case "datepicker":
352
+ return selectPill({ ...el, placeholder: el.placeholder ?? "Select a date" }, ctx, "\uD83D\uDCC5");
353
+ case "timepicker":
354
+ return selectPill({ ...el, placeholder: el.placeholder ?? "Select a time" }, ctx, "\uD83D\uDD50");
355
+ case "plain_text_input":
356
+ return inputBox(el, ctx);
357
+ case "checkboxes":
358
+ case "radio_buttons":
359
+ return `<div class="sm-options">${arr(el.options).map((o) => {
360
+ const opt = rec(o);
361
+ const mark = type === "checkboxes" ? "\u2610" : "\u25EF";
362
+ return `<div class="sm-option">${mark} ${opt ? textObject(opt.text, ctx) : ""}</div>`;
363
+ }).join("")}</div>`;
364
+ default:
365
+ if (type.endsWith("_select") || type.startsWith("multi_"))
366
+ return selectPill(el, ctx);
367
+ return unsupported(type);
355
368
  }
356
- addMessage(input) {
357
- const channel = this.channel(input.channel);
358
- if (channel.is_archived)
359
- throw new SlackApiError2("is_archived");
360
- if (input.thread_ts && !this.findMessage(input.channel, input.thread_ts)) {
361
- throw new SlackApiError2("thread_not_found");
369
+ }
370
+ function richStyle(html, style) {
371
+ if (!html || !style)
372
+ return html;
373
+ let out = html;
374
+ if (style.code === true)
375
+ out = `<code class="sm-code">${out}</code>`;
376
+ if (style.bold === true)
377
+ out = `<strong>${out}</strong>`;
378
+ if (style.italic === true)
379
+ out = `<em>${out}</em>`;
380
+ if (style.strike === true)
381
+ out = `<s>${out}</s>`;
382
+ return out;
383
+ }
384
+ function richElement(v, ctx) {
385
+ const el = rec(v);
386
+ if (!el)
387
+ return "";
388
+ const style = rec(el.style);
389
+ switch (str(el.type)) {
390
+ case "text":
391
+ return richStyle(plainTextToHtml(str(el.text)).replace(/\n/g, "<br>"), style);
392
+ case "link": {
393
+ const url = safeUrl(str(el.url));
394
+ const label = plainTextToHtml(str(el.text) || str(el.url));
395
+ if (!url)
396
+ return label;
397
+ return richStyle(`<a class="sm-link" href="${url}" target="_blank" rel="noopener">${label}</a>`, style);
362
398
  }
363
- const message = {
364
- type: "message",
365
- team: this.team.id,
366
- ts: input.ts ?? nextTs(),
367
- ...input
368
- };
369
- if (message.ephemeral_user)
370
- this.ephemerals.push(message);
371
- else
372
- this.insertMessage(message);
373
- this.emit({ kind: "message.add", message });
374
- return message;
375
- }
376
- updateMessage(channelId, ts, patch, editor, opts = {}) {
377
- const message = this.message(channelId, ts);
378
- const previous = structuredClone(message);
379
- Object.assign(message, patch, opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } });
380
- this.emit({ kind: "message.update", message, previous });
381
- return message;
382
- }
383
- deleteMessage(channelId, ts) {
384
- const list = this.messages.get(channelId);
385
- const i = list?.findIndex((m) => m.ts === ts) ?? -1;
386
- if (!list || i < 0)
387
- throw new SlackApiError2("message_not_found");
388
- const [message] = list.splice(i, 1);
389
- if (message.thread_ts && message.thread_ts !== ts) {
390
- const parent = this.findMessage(channelId, message.thread_ts);
391
- if (parent?.reply_count)
392
- parent.reply_count -= 1;
399
+ case "user": {
400
+ const user = ctx.users.get(str(el.user_id));
401
+ return `<span class="sm-pill">@${escapeHtml(user ? displayName(user) : str(el.user_id))}</span>`;
393
402
  }
394
- this.emit({ kind: "message.delete", message });
395
- return message;
396
- }
397
- addReaction(channelId, ts, name, userId) {
398
- const message = this.message(channelId, ts);
399
- message.reactions ??= [];
400
- let reaction = message.reactions.find((r) => r.name === name);
401
- if (reaction?.users.includes(userId))
402
- throw new SlackApiError2("already_reacted");
403
- if (!reaction) {
404
- reaction = { name, users: [], count: 0 };
405
- message.reactions.push(reaction);
403
+ case "usergroup":
404
+ return `<span class="sm-pill">@${escapeHtml(str(el.usergroup_id))}</span>`;
405
+ case "channel": {
406
+ const channel = ctx.channels.get(str(el.channel_id));
407
+ return `<span class="sm-pill">#${escapeHtml(channel ? channel.name : str(el.channel_id))}</span>`;
406
408
  }
407
- reaction.users.push(userId);
408
- reaction.count = reaction.users.length;
409
- this.emit({ kind: "reaction.add", message, name, user: userId });
410
- return message;
409
+ case "broadcast":
410
+ return `<span class="sm-pill">@${escapeHtml(str(el.range) || "channel")}</span>`;
411
+ case "emoji": {
412
+ const char = emojiChar(str(el.name)) ?? (el.unicode ? emojiFromUnicode(str(el.unicode)) : undefined);
413
+ return char ?? `<span class="sm-emoji-name">:${escapeHtml(str(el.name))}:</span>`;
414
+ }
415
+ case "date":
416
+ return plainTextToHtml(str(el.fallback) || str(el.timestamp));
417
+ case "color":
418
+ return plainTextToHtml(str(el.value));
419
+ default:
420
+ return "";
411
421
  }
412
- removeReaction(channelId, ts, name, userId) {
413
- const message = this.message(channelId, ts);
414
- const reaction = message.reactions?.find((r) => r.name === name);
415
- if (!reaction?.users.includes(userId))
416
- throw new SlackApiError2("no_reaction");
417
- reaction.users = reaction.users.filter((u) => u !== userId);
418
- reaction.count = reaction.users.length;
419
- message.reactions = message.reactions.filter((r) => r.count > 0);
420
- if (message.reactions.length === 0)
421
- message.reactions = undefined;
422
- this.emit({ kind: "reaction.remove", message, name, user: userId });
423
- return message;
424
- }
425
- history(channelId, q = {}) {
426
- this.channel(channelId);
427
- const all = (this.messages.get(channelId) ?? []).filter((m) => !m.thread_ts || m.thread_ts === m.ts || m.subtype === "thread_broadcast");
428
- return paginate(all, q);
429
- }
430
- replies(channelId, threadTs, q = {}) {
431
- const parent = this.message(channelId, threadTs);
432
- const all = [
433
- parent,
434
- ...(this.messages.get(channelId) ?? []).filter((m) => m.thread_ts === threadTs && m.ts !== threadTs)
435
- ];
436
- return paginate(all, q);
437
- }
438
- addFile(input) {
439
- const id = input.id ?? slackId("F");
440
- const ext = input.name.includes(".") ? input.name.split(".").pop().toLowerCase() : "";
441
- const mimetype = input.mimetype ?? guessMime(ext);
442
- const now = nowUnix();
443
- const file = {
444
- id,
445
- created: now,
446
- timestamp: now,
447
- name: input.name,
448
- title: input.title ?? input.name,
449
- mimetype,
450
- filetype: ext || "binary",
451
- pretty_type: ext ? ext.toUpperCase() : "Binary",
452
- user: input.user,
453
- size: input.bytes.byteLength,
454
- mode: "hosted",
455
- is_external: false,
456
- is_public: false,
457
- url_private: `${input.baseUrl}/files-pri/${this.team.id}-${id}/${encodeURIComponent(input.name)}`,
458
- url_private_download: `${input.baseUrl}/files-pri/${this.team.id}-${id}/download/${encodeURIComponent(input.name)}`,
459
- permalink: `${input.baseUrl}/files/${input.user}/${id}/${encodeURIComponent(input.name)}`,
460
- channels: [],
461
- bytes: input.bytes
462
- };
463
- if (mimetype.startsWith("image/")) {
464
- const thumbs = file;
465
- for (const size of [64, 80, 160, 360, 480])
466
- thumbs[`thumb_${size}`] = file.url_private;
422
+ }
423
+ function richSection(v, ctx) {
424
+ const block = rec(v);
425
+ if (!block)
426
+ return "";
427
+ const inner = arr(block.elements).map((e) => richElement(e, ctx)).join("");
428
+ switch (str(block.type)) {
429
+ case "rich_text_section":
430
+ return `<div class="sm-rt-section">${inner}</div>`;
431
+ case "rich_text_quote":
432
+ return `<blockquote class="sm-quote">${inner}</blockquote>`;
433
+ case "rich_text_preformatted":
434
+ return `<pre class="sm-pre">${inner}</pre>`;
435
+ case "rich_text_list": {
436
+ const tag = str(block.style) === "ordered" ? "ol" : "ul";
437
+ const indent = Number(block.indent) || 0;
438
+ const items = arr(block.elements).map((item) => `<li>${richSection(item, ctx)}</li>`).join("");
439
+ const margin = indent ? ` style="margin-left:${indent * 18}px"` : "";
440
+ return `<${tag} class="sm-list"${margin}>${items}</${tag}>`;
467
441
  }
468
- this.files.set(id, file);
469
- this.emit({ kind: "file.add", file });
470
- return file;
471
- }
472
- file(id) {
473
- const f = this.files.get(id);
474
- if (!f)
475
- throw new SlackApiError2("file_not_found");
476
- return f;
477
- }
478
- openView(view) {
479
- const id = view.id ?? slackId("V");
480
- const full = {
481
- ...view,
482
- id,
483
- team_id: this.team.id,
484
- app_id: this.app.id,
485
- bot_id: this.bot.botId,
486
- hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`,
487
- root_view_id: id
488
- };
489
- this.views.set(id, full);
490
- this.emit({ kind: "view.open", view: full });
491
- return full;
492
- }
493
- recordApiCall(call) {
494
- this.apiCalls.push(call);
495
- this.emit({ kind: "api.call", call });
442
+ default:
443
+ return inner;
496
444
  }
497
- assistantThread(channel, threadTs) {
498
- const key = `${channel}:${threadTs}`;
499
- let t = this.assistantThreads.get(key);
500
- if (!t) {
501
- t = {};
502
- this.assistantThreads.set(key, t);
503
- }
504
- return t;
445
+ }
446
+ function sectionBlock(block, ctx) {
447
+ const parts = [];
448
+ if (block.text)
449
+ parts.push(`<div class="sm-section-text">${textObject(block.text, ctx)}</div>`);
450
+ const fields = arr(block.fields);
451
+ if (fields.length) {
452
+ parts.push(`<div class="sm-fields">${fields.map((f) => `<div class="sm-field">${textObject(f, ctx)}</div>`).join("")}</div>`);
505
453
  }
454
+ const accessory = block.accessory ? renderElement(block.accessory, ctx) : "";
455
+ const body = parts.join("");
456
+ if (!accessory)
457
+ return `<div class="sm-block sm-section">${body}</div>`;
458
+ 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>`;
506
459
  }
507
- function paginate(all, q) {
508
- let items = all;
509
- if (q.oldest)
510
- items = items.filter((m) => q.inclusive ? Number(m.ts) >= Number(q.oldest) : Number(m.ts) > Number(q.oldest));
511
- if (q.latest)
512
- items = items.filter((m) => q.inclusive ? Number(m.ts) <= Number(q.latest) : Number(m.ts) < Number(q.latest));
513
- const start = q.cursor ? Number.parseInt(Buffer.from(q.cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0 : 0;
514
- const limit = Math.max(1, Math.min(q.limit ?? 100, 1000));
515
- const page = items.slice(start, start + limit);
516
- const has_more = start + limit < items.length;
517
- return {
518
- items: page,
519
- has_more,
520
- next_cursor: has_more ? Buffer.from(`offset:${start + limit}`).toString("base64") : ""
521
- };
460
+ function contextBlock(block, ctx) {
461
+ const inner = arr(block.elements).map((e) => {
462
+ const el = rec(e);
463
+ if (!el)
464
+ return "";
465
+ if (str(el.type) === "image")
466
+ return image(imageSrcOf(el), str(el.alt_text), "sm-context-img");
467
+ return `<span class="sm-context-text">${textObject(el, ctx)}</span>`;
468
+ }).join("");
469
+ return `<div class="sm-block sm-context">${inner}</div>`;
522
470
  }
523
- function guessMime(ext) {
524
- const map = {
525
- png: "image/png",
526
- jpg: "image/jpeg",
527
- jpeg: "image/jpeg",
528
- gif: "image/gif",
529
- webp: "image/webp",
530
- svg: "image/svg+xml",
531
- txt: "text/plain",
532
- md: "text/markdown",
533
- log: "text/plain",
534
- json: "application/json",
535
- csv: "text/csv",
536
- pdf: "application/pdf",
537
- html: "text/html",
538
- zip: "application/zip"
539
- };
540
- return map[ext] ?? "application/octet-stream";
471
+ function imageBlock(block, ctx) {
472
+ const title = block.title ? `<div class="sm-img-title">${textObject(block.title, ctx)}</div>` : "";
473
+ const src = imageSrcOf(block);
474
+ const alt = str(block.alt_text);
475
+ if (!src) {
476
+ const file = rec(block.slack_file);
477
+ return `<div class="sm-block">${title}${unsupported(`image (file ${str(file?.id) || "?"})`)}</div>`;
478
+ }
479
+ return `<div class="sm-block sm-image">${title}${image(src, alt, "sm-img")}</div>`;
541
480
  }
542
- function wireMessage(m) {
543
- const { ephemeral_user: _e, ...rest } = m;
544
- if (rest.files)
545
- rest.files = rest.files.map(wireFile);
546
- return rest;
481
+ function inputBlock(block, ctx) {
482
+ const label = block.label ? `<div class="sm-label">${plainOf(block.label)}</div>` : "";
483
+ const element = block.element ? renderElement(block.element, ctx) : "";
484
+ const hint = block.hint ? `<div class="sm-hint">${plainOf(block.hint)}</div>` : "";
485
+ return `<div class="sm-block sm-input-block">${label}${element}${hint}</div>`;
547
486
  }
548
- function wireFile(f) {
549
- const { bytes: _b, ...rest } = f;
550
- return rest;
487
+ function videoBlock(block, ctx) {
488
+ const thumb = safeUrl(str(block.thumbnail_url));
489
+ const url = safeUrl(str(block.title_url) || str(block.video_url));
490
+ const title = textObject(block.title, ctx) || plainTextToHtml(str(block.alt_text));
491
+ const inner = `${thumb ? `<img class="sm-video-thumb" src="${thumb}" alt="${escapeHtml(str(block.alt_text))}">` : ""}<div class="sm-video-title">\u25B6 ${title}</div>`;
492
+ return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
551
493
  }
552
- function stripBytes(change) {
553
- if (change.kind === "file.add")
554
- return { ...change, file: wireFile(change.file) };
555
- if ("message" in change && change.message.files) {
556
- return {
557
- ...change,
558
- message: { ...change.message, files: change.message.files.map(wireFile) }
559
- };
494
+ function renderBlock(v, ctx) {
495
+ const block = rec(v);
496
+ if (!block)
497
+ return unsupported("block");
498
+ switch (str(block.type)) {
499
+ case "header":
500
+ return `<div class="sm-block sm-header-block">${textObject(block.text, ctx)}</div>`;
501
+ case "section":
502
+ return sectionBlock(block, ctx);
503
+ case "divider":
504
+ return `<div class="sm-block"><hr class="sm-hr"></div>`;
505
+ case "context":
506
+ return contextBlock(block, ctx);
507
+ case "actions":
508
+ return `<div class="sm-block sm-actions">${arr(block.elements).map((e) => renderElement(e, ctx)).join("")}</div>`;
509
+ case "image":
510
+ return imageBlock(block, ctx);
511
+ case "rich_text":
512
+ return `<div class="sm-block sm-rich-text">${arr(block.elements).map((e) => richSection(e, ctx)).join("")}</div>`;
513
+ case "input":
514
+ return inputBlock(block, ctx);
515
+ case "file":
516
+ return `<div class="sm-block sm-file-block">\uD83D\uDCCE ${escapeHtml(str(block.external_id) || str(block.file_id) || "file")}</div>`;
517
+ case "video":
518
+ return videoBlock(block, ctx);
519
+ default:
520
+ return `<div class="sm-block">${unsupported(str(block.type))}</div>`;
560
521
  }
561
- return change;
562
522
  }
563
- function ensureDir(file) {
564
- mkdirSync(dirname(file), { recursive: true });
565
- }
566
-
567
- // src/server.ts
568
- import { readFileSync as readFileSync2 } from "fs";
569
-
570
- // src/body.ts
571
- var JSON_FIELDS = new Set([
572
- "blocks",
573
- "attachments",
574
- "metadata",
575
- "files",
576
- "view",
577
- "prompts",
578
- "icons",
579
- "user_ids",
580
- "types",
581
- "chunks",
582
- "loading_messages"
583
- ]);
584
- function coerce(key, value) {
585
- if (JSON_FIELDS.has(key)) {
586
- try {
587
- return JSON.parse(value);
588
- } catch {
589
- return value;
590
- }
591
- }
592
- if (value === "true")
593
- return true;
594
- if (value === "false")
595
- return false;
596
- return value;
523
+ function renderBlocks(blocks, ctx) {
524
+ const list = arr(blocks);
525
+ if (!list.length)
526
+ return "";
527
+ return `<div class="sm-blocks">${list.map((b) => renderBlock(b, ctx)).join("")}</div>`;
597
528
  }
598
- async function parseArgs(req) {
599
- const url = new URL(req.url);
600
- const args = {};
601
- for (const [k, v] of url.searchParams)
602
- args[k] = coerce(k, v);
603
- if (req.method !== "POST")
604
- return args;
605
- const contentType = req.headers.get("content-type") ?? "";
606
- if (contentType.includes("application/json")) {
607
- const text = await req.text();
608
- if (text.trim())
609
- Object.assign(args, JSON.parse(text));
610
- return args;
611
- }
612
- if (contentType.includes("multipart/form-data")) {
613
- const form = await req.formData();
614
- form.forEach((v, k) => {
615
- args[k] = typeof v === "string" ? coerce(k, v) : v;
616
- });
617
- return args;
618
- }
619
- const text = await req.text();
620
- if (!text)
621
- return args;
622
- for (const [k, v] of new URLSearchParams(text))
623
- args[k] = coerce(k, v);
624
- return args;
625
- }
626
- function bearerToken(req, args) {
627
- const header = req.headers.get("authorization");
628
- if (header?.toLowerCase().startsWith("bearer "))
629
- return header.slice(7).trim();
630
- if (typeof args.token === "string")
631
- return args.token;
632
- return;
633
- }
634
- function str(args, key) {
635
- const v = args[key];
636
- return typeof v === "string" ? v : v == null ? undefined : String(v);
637
- }
638
- function num(args, key, fallback) {
639
- const v = args[key];
640
- const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : Number.NaN;
641
- return Number.isFinite(n) ? n : fallback;
642
- }
643
- function bool(args, key) {
644
- const v = args[key];
645
- if (typeof v === "boolean")
646
- return v;
647
- if (v === "true" || v === "1" || v === 1)
648
- return true;
649
- if (v === "false" || v === "0" || v === 0)
650
- return false;
651
- return;
529
+ var NAMED_COLORS = {
530
+ good: "#2eb67d",
531
+ warning: "#ecb22e",
532
+ danger: "#e01e5a"
533
+ };
534
+ function barColor(v) {
535
+ const raw = str(v).trim();
536
+ if (!raw)
537
+ return "#dddddd";
538
+ const named = NAMED_COLORS[raw.toLowerCase()];
539
+ if (named)
540
+ return named;
541
+ const hex = raw.startsWith("#") ? raw : `#${raw}`;
542
+ return /^#[0-9a-fA-F]{3,8}$/.test(hex) ? hex : "#dddddd";
652
543
  }
653
-
654
- // src/events.ts
655
- var VERIFICATION_TOKEN = "mock-verification-token";
656
- function eventCallback(store, event) {
657
- return {
658
- token: VERIFICATION_TOKEN,
659
- team_id: store.team.id,
660
- context_team_id: store.team.id,
661
- context_enterprise_id: null,
662
- api_app_id: store.app.id,
663
- event,
664
- type: "event_callback",
665
- event_id: slackId("Ev", 9),
666
- event_time: nowUnix(),
667
- authorizations: [
668
- {
669
- enterprise_id: null,
670
- team_id: store.team.id,
671
- user_id: store.bot.userId,
672
- is_bot: true,
673
- is_enterprise_install: false
674
- }
675
- ],
676
- is_ext_shared_channel: false,
677
- event_context: Buffer.from(`${store.team.id}:${store.app.id}:${event.channel ?? ""}`).toString("base64")
678
- };
544
+ function attachmentFields(fields, ctx) {
545
+ if (!fields.length)
546
+ return "";
547
+ return `<div class="sm-fields">${fields.map((f) => {
548
+ const field = rec(f);
549
+ if (!field)
550
+ return "";
551
+ const wide = field.short === true ? "" : " sm-field-wide";
552
+ return `<div class="sm-field${wide}"><div class="sm-field-title">${plainTextToHtml(str(field.title))}</div><div>${mrkdwnToHtml(str(field.value), ctx)}</div></div>`;
553
+ }).join("")}</div>`;
679
554
  }
680
- function messageEvent(store, m, channel) {
681
- const {
682
- channel: _c,
683
- team,
684
- ...rest
685
- } = wireMessage(m);
686
- const event = {
687
- ...rest,
688
- type: "message",
689
- channel: m.channel,
690
- event_ts: m.ts,
691
- channel_type: store.channelType(channel),
692
- team
693
- };
694
- if (m.files?.length && !m.subtype)
695
- event.subtype = "file_share";
696
- if (m.files?.length) {
697
- event.upload = false;
698
- event.display_as_bot = false;
555
+ function attachment(v, ctx) {
556
+ const att = rec(v);
557
+ if (!att)
558
+ return "";
559
+ const parts = [];
560
+ const author = str(att.author_name);
561
+ if (author) {
562
+ const icon = safeUrl(str(att.author_icon));
563
+ parts.push(`<div class="sm-att-author">${icon ? `<img class="sm-att-author-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(author)}</div>`);
699
564
  }
700
- return event;
701
- }
702
- function appMentionEvent(store, m) {
703
- const { channel_type: _ct, ...event } = messageEvent(store, m, store.channel(m.channel));
704
- return { ...event, type: "app_mention" };
705
- }
706
- function messageChangedEvent(store, m, previous) {
707
- const channel = store.channel(m.channel);
708
- const ts = nextTs();
709
- return {
710
- type: "message",
711
- subtype: "message_changed",
712
- channel: m.channel,
713
- channel_type: store.channelType(channel),
714
- hidden: true,
715
- ts,
716
- event_ts: ts,
717
- message: {
718
- ...wireMessage(m),
719
- channel: undefined,
720
- source_team: store.team.id,
721
- user_team: store.team.id
722
- },
723
- previous_message: { ...wireMessage(previous), channel: undefined }
724
- };
725
- }
726
- function messageDeletedEvent(store, m) {
727
- const channel = store.channel(m.channel);
728
- const ts = nextTs();
729
- return {
730
- type: "message",
731
- subtype: "message_deleted",
732
- channel: m.channel,
733
- channel_type: store.channelType(channel),
734
- hidden: true,
735
- deleted_ts: m.ts,
736
- ts,
737
- event_ts: ts,
738
- previous_message: { ...wireMessage(m), channel: undefined }
739
- };
740
- }
741
- function reactionEvent(kind, m, name, user) {
742
- return {
743
- type: kind,
744
- user,
745
- reaction: name,
746
- item_user: m.user,
747
- item: { type: "message", channel: m.channel, ts: m.ts },
748
- event_ts: nextTs()
749
- };
750
- }
751
- function memberJoinedEvent(store, channel, user, inviter) {
752
- return {
753
- type: "member_joined_channel",
754
- user,
755
- channel: channel.id,
756
- channel_type: store.channelType(channel) === "channel" ? "C" : "G",
757
- team: store.team.id,
758
- inviter,
759
- event_ts: nextTs()
760
- };
761
- }
762
- function assistantThreadStartedEvent(store, dm, user, threadTs, context = {}) {
763
- return {
764
- type: "assistant_thread_started",
765
- assistant_thread: {
766
- user_id: user,
767
- context: { team_id: store.team.id, enterprise_id: null, ...context },
768
- channel_id: dm.id,
769
- thread_ts: threadTs
770
- },
771
- event_ts: nextTs()
772
- };
565
+ const title = str(att.title);
566
+ if (title) {
567
+ const link = safeUrl(str(att.title_link));
568
+ const inner = plainTextToHtml(title);
569
+ parts.push(`<div class="sm-att-title">${link ? `<a class="sm-link" href="${link}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`);
570
+ }
571
+ const text = str(att.text) || (parts.length ? "" : str(att.fallback));
572
+ if (text)
573
+ parts.push(`<div class="sm-att-text">${mrkdwnToHtml(text, ctx)}</div>`);
574
+ parts.push(attachmentFields(arr(att.fields), ctx));
575
+ const img = safeUrl(str(att.image_url));
576
+ if (img)
577
+ parts.push(`<img class="sm-att-img" src="${img}" alt="">`);
578
+ const thumb = !img ? safeUrl(str(att.thumb_url)) : undefined;
579
+ if (thumb)
580
+ parts.push(`<img class="sm-att-thumb" src="${thumb}" alt="">`);
581
+ const blocks = arr(att.blocks);
582
+ if (blocks.length)
583
+ parts.push(renderBlocks(blocks, ctx));
584
+ const footer = str(att.footer);
585
+ const ts = att.ts ? formatAttachmentTs(att.ts) : "";
586
+ if (footer || ts) {
587
+ const icon = safeUrl(str(att.footer_icon));
588
+ parts.push(`<div class="sm-att-footer">${icon ? `<img class="sm-att-footer-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(footer)}${footer && ts ? " | " : ""}${escapeHtml(ts)}</div>`);
589
+ }
590
+ const pretext = str(att.pretext);
591
+ const box = `<div class="sm-att" style="border-left-color:${barColor(att.color)}">${parts.join("")}</div>`;
592
+ return pretext ? `<div class="sm-att-pretext">${mrkdwnToHtml(pretext, ctx)}</div>${box}` : box;
773
593
  }
774
- function assistantThreadContextChangedEvent(store, dm, user, threadTs, context) {
775
- return {
776
- type: "assistant_thread_context_changed",
777
- assistant_thread: {
778
- user_id: user,
779
- context: { team_id: store.team.id, enterprise_id: null, ...context },
780
- channel_id: dm.id,
781
- thread_ts: threadTs
782
- },
783
- event_ts: nextTs()
784
- };
594
+ function formatAttachmentTs(v) {
595
+ const secs = Number(v);
596
+ if (!Number.isFinite(secs) || secs <= 0)
597
+ return str(v);
598
+ const d = new Date(secs * 1000);
599
+ const pad = (n) => String(n).padStart(2, "0");
600
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
785
601
  }
786
- function slashCommandPayload(store, input) {
787
- return {
788
- token: VERIFICATION_TOKEN,
789
- team_id: store.team.id,
790
- team_domain: store.team.domain,
791
- channel_id: input.channel.id,
792
- channel_name: input.channel.is_im ? "directmessage" : input.channel.name,
793
- user_id: input.user.id,
794
- user_name: input.user.name,
795
- command: input.command,
796
- text: input.text,
797
- api_app_id: store.app.id,
798
- is_enterprise_install: "false",
799
- response_url: input.responseUrl,
800
- trigger_id: input.triggerId
801
- };
802
- }
803
- function blockActionsPayload(store, input) {
804
- return {
805
- type: "block_actions",
806
- user: {
807
- id: input.user.id,
808
- username: input.user.name,
809
- name: input.user.name,
810
- team_id: store.team.id
811
- },
812
- api_app_id: store.app.id,
813
- token: VERIFICATION_TOKEN,
814
- container: {
815
- type: "message",
816
- message_ts: input.message.ts,
817
- channel_id: input.channel.id,
818
- is_ephemeral: !!input.message.ephemeral_user,
819
- ...input.message.thread_ts ? { thread_ts: input.message.thread_ts } : {}
820
- },
821
- trigger_id: input.triggerId,
822
- team: { id: store.team.id, domain: store.team.domain },
823
- enterprise: null,
824
- is_enterprise_install: false,
825
- channel: { id: input.channel.id, name: input.channel.name },
826
- message: wireMessage(input.message),
827
- state: { values: {} },
828
- response_url: input.responseUrl,
829
- actions: input.actions.map((a) => ({ action_ts: nextTs(), ...a }))
830
- };
831
- }
832
- function viewSubmissionPayload(store, input) {
833
- const { opened_by: _o, trigger_id: _t, ...view } = input.view;
834
- return {
835
- type: "view_submission",
836
- team: { id: store.team.id, domain: store.team.domain },
837
- user: {
838
- id: input.user.id,
839
- username: input.user.name,
840
- name: input.user.name,
841
- team_id: store.team.id
842
- },
843
- api_app_id: store.app.id,
844
- token: VERIFICATION_TOKEN,
845
- trigger_id: input.triggerId,
846
- view: { ...view, state: { values: input.values } },
847
- response_urls: [],
848
- is_enterprise_install: false,
849
- enterprise: null
850
- };
602
+ function renderAttachments(attachments, ctx) {
603
+ const list = arr(attachments);
604
+ if (!list.length)
605
+ return "";
606
+ return `<div class="sm-atts">${list.map((a) => attachment(a, ctx)).join("")}</div>`;
851
607
  }
852
608
 
853
- // src/render/mrkdwn.ts
854
- function escapeHtml(s) {
855
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
856
- }
857
- function unescapeSlack(s) {
858
- return s.replace(/&(amp|lt|gt|quot);/g, (_m, name) => name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : '"');
859
- }
860
- function reEscape(s) {
861
- return escapeHtml(unescapeSlack(s));
862
- }
863
- var EMOJI = {
864
- eyes: "\uD83D\uDC40",
865
- white_check_mark: "\u2705",
866
- x: "\u274C",
867
- heavy_plus_sign: "\u2795",
868
- heavy_minus_sign: "\u2796",
869
- heavy_multiplication_x: "\u2716\uFE0F",
870
- zap: "\u26A1",
871
- speech_balloon: "\uD83D\uDCAC",
872
- robot_face: "\uD83E\uDD16",
873
- gear: "\u2699\uFE0F",
874
- rocket: "\uD83D\uDE80",
875
- star: "\u2B50",
876
- crystal_ball: "\uD83D\uDD2E",
877
- bulb: "\uD83D\uDCA1",
878
- wrench: "\uD83D\uDD27",
879
- hammer: "\uD83D\uDD28",
880
- crown: "\uD83D\uDC51",
881
- tada: "\uD83C\uDF89",
882
- warning: "\u26A0\uFE0F",
883
- hourglass: "\u231B",
884
- hourglass_flowing_sand: "\u23F3",
885
- thumbsup: "\uD83D\uDC4D",
886
- thumbsdown: "\uD83D\uDC4E",
887
- "+1": "\uD83D\uDC4D",
888
- "-1": "\uD83D\uDC4E",
889
- heavy_check_mark: "\u2714\uFE0F",
890
- question: "\u2753",
891
- grey_question: "\u2754",
892
- exclamation: "\u2757",
893
- white_circle: "\u26AA",
894
- large_blue_circle: "\uD83D\uDD35",
895
- black_circle: "\u26AB",
896
- red_circle: "\uD83D\uDD34",
897
- large_green_circle: "\uD83D\uDFE2",
898
- large_yellow_circle: "\uD83D\uDFE1",
899
- fire: "\uD83D\uDD25",
900
- sparkles: "\u2728",
901
- memo: "\uD83D\uDCDD",
902
- clipboard: "\uD83D\uDCCB",
903
- mag: "\uD83D\uDD0D",
904
- mag_right: "\uD83D\uDD0E",
905
- link: "\uD83D\uDD17",
906
- lock: "\uD83D\uDD12",
907
- unlock: "\uD83D\uDD13",
908
- bell: "\uD83D\uDD14",
909
- package: "\uD83D\uDCE6",
910
- construction: "\uD83D\uDEA7",
911
- bug: "\uD83D\uDC1B",
912
- boom: "\uD83D\uDCA5",
913
- pencil2: "\u270F\uFE0F",
914
- scroll: "\uD83D\uDCDC",
915
- page_facing_up: "\uD83D\uDCC4",
916
- file_folder: "\uD83D\uDCC1",
917
- card_index_dividers: "\uD83D\uDDC2\uFE0F",
918
- paperclip: "\uD83D\uDCCE",
919
- bar_chart: "\uD83D\uDCCA",
920
- chart_with_upwards_trend: "\uD83D\uDCC8",
921
- calendar: "\uD83D\uDCC5",
922
- clock1: "\uD83D\uDD50",
923
- arrow_right: "\u27A1\uFE0F",
924
- arrow_left: "\u2B05\uFE0F",
925
- arrow_up: "\u2B06\uFE0F",
926
- arrow_down: "\u2B07\uFE0F",
927
- arrow_right_hook: "\u21AA\uFE0F",
928
- repeat: "\uD83D\uDD01",
929
- arrows_counterclockwise: "\uD83D\uDD04",
930
- recycle: "\u267B\uFE0F",
931
- no_entry: "\u26D4",
932
- no_entry_sign: "\uD83D\uDEAB",
933
- stop_sign: "\uD83D\uDED1",
934
- pause_button: "\u23F8\uFE0F",
935
- information_source: "\u2139\uFE0F",
936
- wave: "\uD83D\uDC4B",
937
- pray: "\uD83D\uDE4F",
938
- muscle: "\uD83D\uDCAA",
939
- brain: "\uD83E\uDDE0",
940
- dart: "\uD83C\uDFAF",
941
- trophy: "\uD83C\uDFC6",
942
- medal: "\uD83C\uDFC5",
943
- checkered_flag: "\uD83C\uDFC1",
944
- ok_hand: "\uD83D\uDC4C",
945
- point_right: "\uD83D\uDC49",
946
- clap: "\uD83D\uDC4F",
947
- raised_hands: "\uD83D\uDE4C",
948
- thinking_face: "\uD83E\uDD14",
949
- "100": "\uD83D\uDCAF",
950
- green_heart: "\uD83D\uDC9A",
951
- thread: "\uD83E\uDDF5",
952
- satellite_antenna: "\uD83D\uDCE1",
953
- inbox_tray: "\uD83D\uDCE5",
954
- outbox_tray: "\uD83D\uDCE4",
955
- incoming_envelope: "\uD83D\uDCE8",
956
- mailbox_with_no_mail: "\uD83D\uDCED",
957
- envelope: "\u2709\uFE0F",
958
- test_tube: "\uD83E\uDDEA",
959
- ship: "\uD83D\uDEA2",
960
- sos: "\uD83C\uDD98",
961
- small_blue_diamond: "\uD83D\uDD39",
962
- small_orange_diamond: "\uD83D\uDD38",
963
- black_small_square: "\u25AA\uFE0F",
964
- white_small_square: "\u25AB\uFE0F"
965
- };
966
- function emojiChar(name) {
967
- return EMOJI[name.replace(/^:|:$/g, "").replace(/::skin-tone-\d$/, "")];
968
- }
969
- function emojiFromUnicode(code) {
970
- const points = code.split("-").map((p) => Number.parseInt(p, 16));
971
- if (points.some((p) => !Number.isFinite(p)))
972
- return;
973
- try {
974
- return String.fromCodePoint(...points);
975
- } catch {
976
- return;
977
- }
978
- }
979
- function renderEmoji(html) {
980
- return html.replace(/:([a-z][a-z0-9_+'-]*|\+1|-1|100):/g, (m, name) => {
981
- const char = emojiChar(name);
982
- return char ?? `<span class="sm-emoji-name">${m}</span>`;
983
- });
984
- }
985
- function displayName(user) {
986
- return user.profile.display_name || user.real_name || user.name;
987
- }
988
- function pill(text) {
989
- return `<span class="sm-pill">${escapeHtml(text)}</span>`;
990
- }
991
- function isSafeUrl(url) {
992
- return /^(https?:\/\/|mailto:|tel:)/i.test(url);
993
- }
994
- function renderControl(inner, ctx) {
995
- const bar = inner.indexOf("|");
996
- const head = bar >= 0 ? inner.slice(0, bar) : inner;
997
- const label = bar >= 0 ? inner.slice(bar + 1) : "";
998
- if (head.startsWith("@")) {
999
- const id = head.slice(1);
1000
- const user = ctx.users.get(id);
1001
- return pill(`@${user ? displayName(user) : label || id}`);
1002
- }
1003
- if (head.startsWith("#")) {
1004
- const id = head.slice(1);
1005
- const channel = ctx.channels.get(id);
1006
- return pill(`#${channel ? channel.name : label.replace(/^#/, "") || id}`);
1007
- }
1008
- if (head.startsWith("!")) {
1009
- const cmd = head.slice(1);
1010
- if (cmd === "here" || cmd === "channel" || cmd === "everyone")
1011
- return pill(`@${cmd}`);
1012
- if (cmd.startsWith("subteam^")) {
1013
- const handle = label || cmd.slice("subteam^".length);
1014
- return pill(handle.startsWith("@") ? handle : `@${handle}`);
1015
- }
1016
- if (cmd.startsWith("date^")) {
1017
- if (label)
1018
- return renderEmoji(reEscape(label));
1019
- const secs = Number(cmd.split("^")[1]);
1020
- return Number.isFinite(secs) ? escapeHtml(new Date(secs * 1000).toISOString()) : "";
1021
- }
1022
- return pill(`@${cmd}`);
1023
- }
1024
- if (isSafeUrl(head)) {
1025
- const shown = label || head.replace(/^mailto:/i, "");
1026
- const attrs = /^mailto:/i.test(head) ? "" : ' target="_blank" rel="noopener"';
1027
- return `<a class="sm-link" href="${escapeHtml(head)}"${attrs}>${renderEmoji(reEscape(shown))}</a>`;
1028
- }
1029
- return escapeHtml(`<${unescapeSlack(inner)}>`);
1030
- }
1031
- function preHtml(body) {
1032
- let code = body.replace(/^\n/, "").replace(/\n$/, "");
1033
- if (code.includes(`
1034
- `))
1035
- code = code.replace(/^[a-z][a-z0-9+#-]{0,11}\n/, "");
1036
- return `<pre class="sm-pre">${reEscape(code)}</pre>`;
1037
- }
1038
- var BOUND_L = `(^|[\\s(\\[{'"\\uE000\\uE001])`;
1039
- var BOUND_R = `(?=$|[\\s.,;:!?)\\]}'"\\uE000\\uE001])`;
1040
- function styleRule(marker) {
1041
- const m = marker.replace(/[*]/g, "\\*");
1042
- return new RegExp(`${BOUND_L}${m}(?![\\s${m}])([^${m}\\n]*[^\\s${m}])${m}${BOUND_R}`, "g");
1043
- }
1044
- var RULES = [
1045
- [styleRule("*"), "strong"],
1046
- [styleRule("~"), "s"],
1047
- [styleRule("_"), "em"]
609
+ // src/render/index.ts
610
+ var DEFAULT_PANEL_WIDTH = "50%";
611
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
612
+ var AVATAR_COLORS = [
613
+ "#4a154b",
614
+ "#1264a3",
615
+ "#2eb67d",
616
+ "#e01e5a",
617
+ "#e8912d",
618
+ "#007a5a",
619
+ "#7c3aed",
620
+ "#00a2ac",
621
+ "#df10a5",
622
+ "#3d5afe"
1048
623
  ];
1049
- function inlineStyles(s) {
1050
- let out = s;
1051
- for (const [re, tag] of RULES)
1052
- out = out.replace(re, `$1<${tag}>$2</${tag}>`);
1053
- return out;
624
+ var CSS = `
625
+ *{box-sizing:border-box}
626
+ html,body{margin:0;padding:0;height:100%}
627
+ 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}
628
+ a{color:#1264a3;text-decoration:none}
629
+ a:hover{text-decoration:underline}
630
+ .sm-app{display:flex;height:100vh;overflow:hidden}
631
+ .sm-side{width:230px;flex:none;background:#3f0e40;color:#d9d0d9;padding:16px 0;overflow-y:auto}
632
+ .sm-side-title{color:#fff;font-weight:900;font-size:17px;padding:0 16px 12px;border-bottom:1px solid #522653;margin-bottom:10px}
633
+ .sm-side-team{display:block;font-weight:400;font-size:12px;color:#bda9bd}
634
+ .sm-side-h{font-size:13px;color:#bda9bd;padding:10px 16px 4px}
635
+ .sm-side a{display:block;color:#d9d0d9;padding:3px 16px;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
636
+ .sm-side a:hover{background:#522653;color:#fff;text-decoration:none}
637
+ .sm-side a.sm-active,.sm-side a.sm-active:hover{background:#1164a3;color:#fff}
638
+ .sm-side-title a:hover{background:none;text-decoration:underline}
639
+ .sm-main{flex:1;min-width:0;display:flex;flex-direction:column;overflow:hidden}
640
+ .sm-shot{width:760px;padding:16px;background:#fff}
641
+ .sm-top{border-bottom:1px solid #e8e8e8;padding:12px 20px;display:flex;align-items:baseline;gap:12px;flex:none}
642
+ .sm-top h1{font-size:18px;font-weight:900;margin:0}
643
+ .sm-top .sm-sub{font-size:13px;color:#616061;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
644
+ .sm-back{font-size:13px;font-weight:700;color:#616061;flex:none}
645
+ .sm-back:hover{color:#1264a3}
646
+ .sm-page{padding:12px 20px 32px}
647
+ .sm-main .sm-page{flex:1;overflow-y:auto}
648
+ .sm-shot .sm-page{padding:0}
649
+ .sm-shot .sm-top{padding:0 0 10px;margin-bottom:8px}
650
+
651
+ .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}
652
+ .sm-panel-top{display:flex;align-items:flex-start;gap:10px;padding:12px 16px;border-bottom:1px solid #e8e8e8;flex:none}
653
+ .sm-panel-heading{flex:1;min-width:0}
654
+ .sm-panel-title{font-size:18px;font-weight:900;margin:0;line-height:22px}
655
+ .sm-panel-sub{font-size:13px;color:#616061}
656
+ .sm-panel-close,.sm-panel-expand{font-size:16px;line-height:22px;color:#616061;padding:0 6px;border-radius:4px;flex:none}
657
+ .sm-panel-close{font-size:20px}
658
+ .sm-panel-close:hover,.sm-panel-expand:hover{background:#f0f0f0;color:#1d1c1d;text-decoration:none}
659
+ .sm-panel-back{display:none;padding:8px 16px;font-size:13px;font-weight:700;border-bottom:1px solid #e8e8e8;flex:none}
660
+ .sm-panel-body{flex:1;overflow-y:auto;padding:12px 16px 32px}
661
+ .sm-resize{width:6px;flex:none;cursor:col-resize;background:#f2f2f2;border-left:1px solid #e8e8e8}
662
+ .sm-resize:hover,.sm-resize.sm-dragging{background:#1264a3;border-left-color:#1264a3}
663
+ .sm-icon-btn{display:inline-block;font-size:16px;line-height:22px;color:#616061;padding:0 6px;border-radius:4px;cursor:pointer}
664
+ .sm-icon-btn:hover{background:#f0f0f0;color:#1d1c1d;text-decoration:none}
665
+ .sm-composer{position:relative;flex:none;border-top:1px solid #e8e8e8;padding:10px 20px 12px;background:#fff}
666
+ .sm-panel .sm-composer{padding:10px 16px 12px}
667
+ .sm-composer-box{border:1px solid #bbb;border-radius:8px;padding:8px 10px;background:#fff}
668
+ .sm-composer-box:focus-within{border-color:#1264a3;box-shadow:0 0 0 1px #1264a3}
669
+ .sm-composer-row{display:flex;align-items:center;gap:8px;margin-top:6px}
670
+ .sm-composer-text{display:block;width:100%;border:0;outline:none;resize:vertical;font-family:inherit;font-size:15px;line-height:20px;color:#1d1c1d;padding:0;background:none}
671
+ .sm-composer-send{flex:none;margin-left:auto;border:0;border-radius:4px;background:#007a5a;color:#fff;font-family:inherit;font-weight:700;font-size:13px;padding:6px 14px;cursor:pointer}
672
+ .sm-composer-send:hover{background:#148567;color:#fff}
673
+ .sm-composer-hint{font-size:11px;color:#616061;margin-top:4px}
674
+ .sm-mentions{display:none;position:absolute;left:20px;right:20px;bottom:100%;margin-bottom:6px;max-height:260px;overflow-y:auto;background:#fff;border:1px solid #ddd;border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.16);z-index:5}
675
+ .sm-panel .sm-mentions{left:16px;right:16px}
676
+ .sm-mention{display:flex;align-items:center;gap:8px;padding:6px 10px;font-size:14px;cursor:pointer;color:#1d1c1d}
677
+ .sm-mention-on{background:#1264a3;color:#fff}
678
+ .sm-mention-on .sm-mention-real{color:#dbe9f5}
679
+ .sm-mention-av{width:20px;height:20px;border-radius:3px;flex:none;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700}
680
+ .sm-mention-name{font-weight:700}
681
+ .sm-mention-real{color:#616061;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
682
+
683
+ .sm-side a,.sm-btn,.sm-select,.sm-reaction,.sm-file-card,.sm-prompt,.sm-replies,.sm-back,.sm-panel-close,.sm-panel-expand,.sm-composer-send,.sm-top-actions a{cursor:pointer}
684
+ .sm-composer-text{cursor:text}
685
+ .sm-badge,.sm-time,.sm-daydiv,.sm-pill,.sm-emoji-name,.sm-avatar,.sm-name,.sm-composer-hint,.sm-unsupported,.sm-tag,.sm-card{cursor:default}
686
+ .sm-top-actions{margin-left:auto;display:flex;gap:12px;align-items:center;flex:none}
687
+ .sm-top-actions a{font-size:13px;font-weight:700;color:#616061}
688
+ .sm-top-actions a:hover{color:#1264a3}
689
+ .sm-identity{position:relative}
690
+ .sm-identity[hidden]{display:none}
691
+ .sm-identity summary{display:flex;align-items:center;gap:6px;list-style:none;border:1px solid #ddd;border-radius:16px;padding:2px 8px 2px 3px;font-size:13px;font-weight:700;cursor:pointer}
692
+ .sm-identity summary::-webkit-details-marker{display:none}
693
+ .sm-identity summary:hover{background:#f8f8f8}
694
+ .sm-identity-avatar{width:24px;height:24px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700;flex:none}
695
+ .sm-identity-list{position:absolute;right:0;top:100%;z-index:10;width:max-content;min-width:190px;max-width:280px;margin:6px 0 0;padding:4px;list-style:none;background:#fff;border:1px solid #ddd;border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.16)}
696
+ .sm-identity-list button{display:flex;align-items:center;gap:8px;width:100%;border:0;border-radius:4px;padding:6px;background:#fff;color:#1d1c1d;font:inherit;text-align:left;cursor:pointer}
697
+ .sm-identity-list button:hover,.sm-identity-list button:focus{background:#f0f0f0;outline:none}
698
+ .sm-identity-user{font-size:12px;color:#616061;margin-left:auto}
699
+ .sm-user-status{margin-left:6px;font-size:12px;font-weight:400;color:#616061}
700
+ .sm-mobile-bar{display:none}
701
+
702
+ .sm-daydiv{display:flex;align-items:center;gap:10px;margin:14px 0 8px}
703
+ .sm-daydiv:before,.sm-daydiv:after{content:"";flex:1;height:1px;background:#e8e8e8}
704
+ .sm-daydiv span{border:1px solid #e8e8e8;border-radius:12px;padding:2px 12px;font-size:13px;font-weight:700;color:#454245;background:#fff}
705
+
706
+ .sm-msg{position:relative;display:flex;gap:12px;padding:8px 8px;border-radius:6px}
707
+ .sm-msg:hover{background:#f8f8f8}
708
+ .sm-msg-eph{background:#fffbe6}
709
+ .sm-msg-eph:hover{background:#fff7d1}
710
+ .sm-msg-open,.sm-msg-open:hover{background:#fff8e2;box-shadow:inset 3px 0 0 #ecb22e}
711
+ .sm-avatar{width:36px;height:36px;flex:none;border-radius:4px;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:14px;overflow:hidden}
712
+ .sm-avatar img{width:36px;height:36px;object-fit:cover}
713
+ .sm-avatar-emoji{font-size:20px;background:#f0f0f0}
714
+ .sm-msg-body{min-width:0;flex:1}
715
+ .sm-msg-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin-bottom:1px}
716
+ .sm-name{font-weight:700;font-size:15px;color:#1d1c1d}
717
+ .sm-badge{background:#e8e8e8;color:#616061;font-size:10px;font-weight:700;border-radius:2px;padding:1px 4px;letter-spacing:.4px;text-transform:uppercase}
718
+ .sm-time{font-size:12px;color:#616061}
719
+ .sm-text{font-size:15px;line-height:22px;word-wrap:break-word;overflow-wrap:anywhere}
720
+ .sm-edited{font-size:12px;color:#616061}
721
+ .sm-eph-note{font-size:12px;color:#8a6d1a;margin-top:4px}
722
+ .sm-stream{display:inline-block;margin-left:4px;color:#616061;font-weight:700;animation:sm-pulse 1s ease-in-out infinite}
723
+ @keyframes sm-pulse{0%,100%{opacity:.25}50%{opacity:1}}
724
+ @keyframes sm-flash{0%{background:#fff3bf}100%{background:transparent}}
725
+ @keyframes sm-flash-soft{0%{background:#eaf3ff}100%{background:transparent}}
726
+ .sm-msg-new{animation:sm-flash 2.4s ease-out}
727
+ .sm-msg-changed{animation:sm-flash-soft .9s ease-out}
728
+ @media (prefers-reduced-motion:reduce){.sm-msg-new,.sm-msg-changed{animation:none}}
729
+ .sm-live{font-size:11px;font-weight:600;color:#2eb67d;margin-left:10px;vertical-align:middle;white-space:nowrap}
730
+ .sm-live-off{color:#e8912d}
731
+ .sm-composer-lock{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 0 2px;font-size:13px;color:#616061}
732
+ .sm-composer-lock[hidden]{display:none}
733
+ .sm-composer-lock input{font:inherit;font-size:13px;padding:5px 8px;border:1px solid #bbb;border-radius:4px;width:130px}
734
+ .sm-composer-lock .sm-lock-go{font:inherit;font-size:13px;padding:5px 10px;border:1px solid #1264a3;border-radius:4px;background:#1264a3;color:#fff;cursor:pointer}
735
+ .sm-composer-lock .sm-err{color:#e01e5a}
736
+ .sm-composer-text:disabled{background:#f8f8f8;color:#888}
737
+
738
+ .sm-pill{background:#e8f5fa;color:#1264a3;border-radius:3px;padding:0 2px}
739
+ .sm-link{color:#1264a3}
740
+ .sm-emoji-name{color:#616061}
741
+ .sm-code{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;background:#f8f8f8;border:1px solid #ddd;border-radius:3px;padding:1px 3px;color:#e01e5a}
742
+ .sm-pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;line-height:18px;background:#f8f8f8;border:1px solid #ddd;border-radius:4px;padding:8px;margin:4px 0;white-space:pre-wrap;word-break:break-word;color:#1d1c1d}
743
+ .sm-quote{border-left:4px solid #ddd;margin:4px 0;padding:0 0 0 12px;color:#1d1c1d}
744
+ .sm-list{margin:2px 0;padding-left:22px}
745
+ .sm-list li{margin:1px 0}
746
+
747
+ .sm-blocks{margin:2px 0}
748
+ .sm-block{margin:6px 0}
749
+ .sm-header-block{font-size:18px;font-weight:900;line-height:24px}
750
+ .sm-section-split{display:flex;gap:12px;align-items:flex-start}
751
+ .sm-section-main{flex:1;min-width:0}
752
+ .sm-section-acc{flex:none}
753
+ .sm-fields{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:6px}
754
+ .sm-field{flex:1 1 40%;min-width:0;font-size:14px;line-height:20px}
755
+ .sm-field-wide{flex-basis:100%}
756
+ .sm-field-title{font-weight:700}
757
+ .sm-context{display:flex;flex-wrap:wrap;align-items:center;gap:8px;font-size:13px;line-height:18px;color:#616061}
758
+ .sm-context .sm-pre,.sm-context .sm-code{font-size:11px}
759
+ .sm-context-img{width:16px;height:16px;border-radius:2px;object-fit:cover}
760
+ .sm-hr{border:0;border-top:1px solid #ddd;margin:10px 0}
761
+ .sm-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
762
+ .sm-btn{display:inline-block;border:1px solid #bbb;border-radius:4px;padding:6px 12px;font-size:14px;font-weight:700;color:#1d1c1d;background:#fff;line-height:16px}
763
+ .sm-btn:hover{text-decoration:none;background:#f8f8f8;color:#1d1c1d}
764
+ .sm-btn-primary{background:#007a5a;border-color:#007a5a;color:#fff}
765
+ .sm-btn-primary:hover{background:#148567;border-color:#148567;color:#fff}
766
+ .sm-btn-danger{background:#e01e5a;border-color:#e01e5a;color:#fff}
767
+ .sm-btn-danger:hover{background:#c31f4c;border-color:#c31f4c;color:#fff}
768
+ .sm-btn-confirm{margin-left:6px;opacity:.7;font-weight:400}
769
+ .sm-select{display:inline-flex;align-items:center;gap:6px;border:1px solid #bbb;border-radius:4px;padding:6px 10px;font-size:14px;color:#1d1c1d;background:#fff;line-height:16px}
770
+ .sm-select-caret{color:#616061;font-size:12px}
771
+ .sm-options{display:flex;flex-direction:column;gap:4px;font-size:14px}
772
+ .sm-acc-img{max-width:88px;max-height:88px;border-radius:4px;display:block}
773
+ .sm-img{max-width:100%;border-radius:6px;display:block;margin-top:4px}
774
+ .sm-img-title{font-size:13px;font-weight:700;color:#454245}
775
+ .sm-label{font-weight:700;font-size:14px;margin-bottom:4px}
776
+ .sm-hint{font-size:12px;color:#616061;margin-top:4px}
777
+ .sm-input{border:1px solid #bbb;border-radius:4px;padding:8px 10px;font-size:14px;min-height:36px;background:#fff}
778
+ .sm-input-multi{min-height:76px}
779
+ .sm-input-ph{color:#8d8d8e}
780
+ .sm-file-block{font-size:14px;color:#454245}
781
+ .sm-video-thumb{max-width:320px;border-radius:6px;display:block}
782
+ .sm-video-title{font-size:14px;font-weight:700;margin-top:4px}
783
+ .sm-unsupported{display:inline-block;background:#f4f4f4;border:1px solid #ddd;border-radius:4px;padding:4px 8px;font-size:12px;color:#616061;font-family:Monaco,Menlo,monospace}
784
+ .sm-rt-section{margin:2px 0}
785
+
786
+ .sm-atts{margin-top:4px}
787
+ .sm-att{border-left:4px solid #ddd;border-radius:2px;padding:2px 0 2px 12px;margin:6px 0;max-width:600px}
788
+ .sm-att-pretext{font-size:15px;line-height:22px;margin-top:4px}
789
+ .sm-att-author{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:700;color:#454245}
790
+ .sm-att-author-icon{width:16px;height:16px;border-radius:2px}
791
+ .sm-att-title{font-size:15px;font-weight:700;margin:2px 0}
792
+ .sm-att-text{font-size:15px;line-height:21px}
793
+ .sm-att-img{max-width:360px;border-radius:6px;display:block;margin-top:6px}
794
+ .sm-att-thumb{max-width:80px;border-radius:4px;display:block;margin-top:6px}
795
+ .sm-att-footer{display:flex;align-items:center;gap:6px;font-size:12px;color:#616061;margin-top:6px}
796
+ .sm-att-footer-icon{width:14px;height:14px;border-radius:2px}
797
+
798
+ .sm-files{margin-top:6px;display:flex;flex-direction:column;gap:6px;align-items:flex-start}
799
+ .sm-file-img{max-width:480px;max-height:420px;border-radius:8px;border:1px solid #e8e8e8;display:block}
800
+ .sm-file-card{display:flex;gap:10px;align-items:center;border:1px solid #ddd;border-radius:8px;padding:8px 12px;max-width:420px}
801
+ .sm-file-icon{font-size:20px}
802
+ .sm-file-name{font-weight:700;font-size:14px}
803
+ .sm-file-meta{font-size:12px;color:#616061}
804
+
805
+ .sm-reactions{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
806
+ .sm-reaction{display:inline-flex;align-items:center;gap:5px;background:#f0f0f0;border:1px solid #f0f0f0;border-radius:12px;padding:1px 8px;font-size:12px;line-height:18px;color:#454245}
807
+ .sm-reaction:hover{background:#e8f5fa;border-color:#1264a3;color:#1d1c1d}
808
+ .sm-reaction[aria-pressed="true"]{background:#e8f5fa;border-color:#1264a3;color:#1264a3}
809
+ .sm-reaction:disabled{cursor:default}
810
+ .sm-reaction-count{font-weight:700;font-size:12px}
811
+ .sm-message-actions{position:absolute;right:8px;top:-8px;display:flex;gap:2px;padding:3px;background:#fff;border:1px solid #ddd;border-radius:6px;box-shadow:0 1px 4px #0001;opacity:0;z-index:2}
812
+ .sm-msg:hover .sm-message-actions,.sm-msg:focus-within .sm-message-actions{opacity:1}
813
+ .sm-message-actions button,.sm-message-actions a{display:inline-flex;align-items:center;justify-content:center;width:32px;min-height:32px;padding:4px;border:0;border-radius:4px;background:#fff;color:#616061;font:inherit;font-size:12px;cursor:pointer;text-decoration:none}
814
+ .sm-message-actions button:hover,.sm-message-actions a:hover{background:#f0f0f0;color:#1d1c1d}
815
+ .sm-message-actions button:disabled{opacity:.5;cursor:default}
816
+ .sm-message-actions svg{width:18px;height:18px;flex:none}
817
+ .sm-action-error{font-size:13px;color:#a12622;margin-top:6px}
818
+ .sm-reaction-picker{position:fixed;inset:auto;top:0;left:0;margin:0;z-index:100;width:300px;max-width:calc(100vw - 24px);max-height:calc(var(--sm-viewport-height,100dvh) - 24px);padding:16px;border:1px solid #ddd;border-radius:12px;color:#1d1c1d;box-shadow:0 8px 32px #0003}
819
+ .sm-reaction-picker-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px}
820
+ .sm-reaction-picker h2{font-size:16px;margin:0}
821
+ .sm-reaction-picker button{min-width:40px;min-height:40px;border:0;border-radius:6px;background:#fff;font:inherit;cursor:pointer}
822
+ .sm-reaction-picker button:hover,.sm-reaction-picker button:focus-visible{background:#f0f0f0}
823
+ .sm-reaction-picker button:disabled{opacity:.5;cursor:default}
824
+ .sm-reaction-choices{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}
825
+ .sm-reaction-choices button{font-size:24px}
826
+ .sm-file-card:hover{background:#f8f8f8}
827
+
828
+ .sm-replies{display:inline-flex;align-items:center;gap:8px;margin-top:4px;font-size:13px;font-weight:700;color:#1264a3}
829
+ .sm-replies:hover{color:#0b4c81}
830
+ .sm-replies-time{font-weight:400;color:#616061}
831
+ .sm-empty{color:#616061;font-size:14px;padding:16px 0}
832
+
833
+ .sm-assist{border:1px solid #e8e8e8;border-radius:8px;padding:10px 12px;margin-bottom:10px;background:#fafafa}
834
+ .sm-assist-title{font-weight:700;font-size:14px}
835
+ .sm-assist-status{font-size:13px;color:#616061;margin-top:2px}
836
+ .sm-assist-status .sm-stream{margin-left:2px}
837
+ .sm-prompts{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
838
+ .sm-prompt{border:1px solid #ddd;border-radius:16px;padding:5px 12px;font-size:13px;background:#fff}
839
+
840
+ .sm-cards{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:16px}
841
+ .sm-card{border:1px solid #e8e8e8;border-radius:8px;padding:10px 14px;min-width:150px}
842
+ .sm-card-k{font-size:12px;color:#616061;text-transform:uppercase;letter-spacing:.4px}
843
+ .sm-card-v{font-size:16px;font-weight:700;margin-top:2px}
844
+ .sm-h2{font-size:15px;font-weight:900;margin:18px 0 6px}
845
+ .sm-table{border-collapse:collapse;width:100%;max-width:900px;font-size:14px}
846
+ .sm-table th{text-align:left;font-size:12px;color:#616061;font-weight:700;text-transform:uppercase;letter-spacing:.4px;padding:4px 10px 4px 0;border-bottom:1px solid #e8e8e8}
847
+ .sm-table td{padding:6px 10px 6px 0;border-bottom:1px solid #f2f2f2;vertical-align:top}
848
+ .sm-tag{display:inline-block;background:#f0f0f0;color:#454245;border-radius:10px;padding:0 8px;font-size:11px;font-weight:700}
849
+ .sm-muted{color:#616061}
850
+
851
+ @media (min-width:700px) and (max-width:1000px){
852
+ .sm-side{width:180px}
853
+ .sm-panel{min-width:300px;max-width:calc(100% - 360px)}
854
+ .sm-top{padding:8px 12px;gap:6px;align-items:center;flex-wrap:wrap}
855
+ .sm-top h1{min-width:0;overflow-wrap:anywhere}
856
+ .sm-top .sm-sub{display:none}
857
+ .sm-top-actions{min-width:0;max-width:100%;flex-shrink:1}
858
+ .sm-identity{min-width:0;max-width:100%}
859
+ .sm-identity-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
860
+ .sm-replies{flex-wrap:wrap}
861
+ .sm-att-img,.sm-file-img,.sm-video-thumb,.sm-file-card{max-width:100%}
862
+ }
863
+ @media (max-width:699px),(hover:none),(pointer:coarse){
864
+ .sm-message-actions{position:static;opacity:1;justify-content:flex-start;gap:6px;margin-top:6px;padding:0;border:0;box-shadow:none;background:none}
865
+ .sm-message-actions button,.sm-message-actions a{width:40px;min-height:40px;background:none}
866
+ }
867
+ @media (max-width:699px){
868
+ html,body{overflow:hidden;overscroll-behavior:none}
869
+ body{overflow-wrap:anywhere}
870
+ .sm-app{position:fixed;top:var(--sm-viewport-top,0px);left:0;width:100%;height:100dvh;height:var(--sm-viewport-height,100dvh);flex-direction:column}
871
+ .sm-side,.sm-resize{display:none}
872
+ .sm-mobile-bar{display:block;flex:none;background:#3f0e40;color:#fff;padding:calc(8px + env(safe-area-inset-top)) 12px 8px;z-index:10}
873
+ .sm-mobile-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;min-width:0}
874
+ .sm-mobile-workspace{display:flex;align-items:center;min-height:40px;min-width:0;color:#fff;font-size:17px;font-weight:900}
875
+ .sm-mobile-bar .sm-identity{flex:none;max-width:55%;color:#1d1c1d}
876
+ .sm-identity summary{min-height:40px;background:#fff;border-radius:20px}
877
+ .sm-identity-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
878
+ .sm-identity-list{width:280px;max-width:calc(100vw - 24px);max-height:calc(var(--sm-viewport-height,100dvh) - 120px);overflow-y:auto}
879
+ .sm-identity-list button{min-height:40px}
880
+ .sm-identity-list button>span{min-width:0;overflow-wrap:anywhere}
881
+ .sm-identity-user{white-space:normal}
882
+ .sm-channel-switch{display:block;width:100%;min-height:40px;margin-top:6px;padding:6px 10px;border:1px solid #79547a;border-radius:5px;background:#522653;color:#fff;font:inherit;font-size:16px}
883
+ .sm-main{min-height:0}
884
+ .sm-app-thread .sm-main{display:none}
885
+ .sm-panel{width:100%;min-width:0;min-height:0;flex:1;border-left:0}
886
+ .sm-top{padding:6px 12px;align-items:center;gap:10px;flex-wrap:wrap}
887
+ .sm-top h1{font-size:16px;min-width:0}
888
+ .sm-top .sm-sub,.sm-top .sm-identity,.sm-live{display:none}
889
+ .sm-panel-top{padding:6px 12px;align-items:center}
890
+ .sm-panel-back{display:inline-flex;align-items:center;justify-content:center;width:40px;min-height:40px;padding:0;border:0;font-size:22px}
891
+ .sm-panel-close,.sm-panel-expand{display:none}
892
+ .sm-main .sm-page,.sm-panel-body{min-height:0;padding:8px 12px 20px;overscroll-behavior:contain}
893
+ .sm-msg{padding:8px 0;gap:10px}
894
+ .sm-msg-body,.sm-card-v,.sm-field,.sm-att,.sm-context,.sm-file-card{overflow-wrap:anywhere}
895
+ .sm-text,.sm-blocks,.sm-field,.sm-att-text,.sm-att-pretext{font-size:16px;line-height:24px}
896
+ .sm-name{font-size:14px}
897
+ .sm-time{font-size:12px}
898
+ .sm-composer,.sm-panel .sm-composer{padding:8px 12px calc(10px + env(safe-area-inset-bottom))}
899
+ .sm-composer-text{font-size:16px;line-height:22px;resize:none;max-height:30vh}
900
+ .sm-composer-lock input{font-size:16px;min-height:40px;flex:1;min-width:0}
901
+ .sm-composer-lock>span:first-child{width:100%}
902
+ .sm-mentions,.sm-panel .sm-mentions{left:12px;right:12px;max-height:min(260px,40vh)}
903
+ .sm-mention{min-height:40px}
904
+ .sm-btn,.sm-select,.sm-reaction,.sm-prompt,.sm-replies,.sm-back,.sm-icon-btn,.sm-composer-send,.sm-composer-lock .sm-lock-go,.sm-lock-out{min-height:40px;display:inline-flex;align-items:center}
905
+ .sm-btn,.sm-select{max-width:100%;white-space:normal}
906
+ .sm-replies{flex-wrap:wrap;gap:4px 8px}
907
+ .sm-section-split{flex-wrap:wrap}
908
+ .sm-section-main{flex-basis:100%}
909
+ .sm-section-acc,.sm-context>*{min-width:0;max-width:100%}
910
+ .sm-att-img,.sm-file-img,.sm-video-thumb{max-width:100%;height:auto}
911
+ .sm-file-card,.sm-unsupported{max-width:100%}
912
+ .sm-file-card>div:last-child{min-width:0}
913
+ .sm-cards{gap:10px}
914
+ .sm-card{flex:1 1 calc(50% - 5px);min-width:0}
915
+ .sm-table,.sm-table tbody{display:block;width:100%}
916
+ .sm-table tr{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 14px;padding:12px 0;border-bottom:1px solid #e8e8e8}
917
+ .sm-table tr:first-child{display:none}
918
+ .sm-table td{display:block;padding:0;border:0;overflow-wrap:anywhere}
919
+ .sm-table td:before{content:attr(data-label);display:block;font-size:11px;color:#616061;text-transform:uppercase;letter-spacing:.4px}
920
+ .sm-table td a{display:inline-flex;align-items:center;min-height:40px}
921
+ .sm-shot{width:100%;padding:12px}
1054
922
  }
1055
- var QUOTE = /^\s*(?:&gt;|>)\s?/;
1056
- var BULLET = /^(\s*)(?:\u2022|-|\*)\s+(.*)$/;
1057
- var NUMBER = /^(\s*)\d+[.)]\s+(.*)$/;
1058
- function blockify(text) {
1059
- const groups = [];
1060
- const push = (kind, html, indent = 0) => {
1061
- const last = groups[groups.length - 1];
1062
- if (last?.kind === kind)
1063
- last.items.push({ html, indent });
1064
- else
1065
- groups.push({ kind, items: [{ html, indent }] });
1066
- };
1067
- for (const line of text.split(`
1068
- `)) {
1069
- const bullet = BULLET.exec(line);
1070
- const numbered = bullet ? null : NUMBER.exec(line);
1071
- if (QUOTE.test(line))
1072
- push("quote", line.replace(QUOTE, ""));
1073
- else if (bullet)
1074
- push("ul", bullet[2] ?? "", Math.min(4, Math.floor((bullet[1]?.length ?? 0) / 2)));
1075
- else if (numbered)
1076
- push("ol", numbered[2] ?? "", Math.min(4, Math.floor((numbered[1]?.length ?? 0) / 2)));
1077
- else
1078
- push("p", line);
1079
- }
1080
- return groups.map((g) => {
1081
- if (g.kind === "p")
1082
- return g.items.map((i) => i.html).join("<br>");
1083
- const inner = g.items.map((i) => `<li${i.indent ? ` style="margin-left:${i.indent * 18}px"` : ""}>${i.html}</li>`).join("");
1084
- if (g.kind === "quote")
1085
- return `<blockquote class="sm-quote">${g.items.map((i) => i.html).join("<br>")}</blockquote>`;
1086
- return `<${g.kind} class="sm-list">${inner}</${g.kind}>`;
1087
- }).join("");
923
+ `;
924
+ function ctxOf(store) {
925
+ return { users: store.users, channels: store.channels, botUserId: store.bot.userId };
1088
926
  }
1089
- var BLOCK_TAGS = "pre|blockquote|ul|ol";
1090
- function tidy(html) {
1091
- return html.replace(new RegExp(`<br>\\s*(<(?:${BLOCK_TAGS})\\b)`, "g"), "$1").replace(new RegExp(`(</(?:${BLOCK_TAGS})>)\\s*<br>`, "g"), "$1");
927
+ function panelWidth(opts) {
928
+ const raw = (opts.panelWidth ?? "").trim();
929
+ return /^\d{1,4}(%|px|vw|rem)$/.test(raw) ? raw : DEFAULT_PANEL_WIDTH;
1092
930
  }
1093
- function mrkdwnToHtml(text, ctx) {
1094
- if (!text)
931
+ function panelParam(opts) {
932
+ const width = (opts.panelWidth ?? "").trim();
933
+ if (!/^\d{1,4}(%|px|vw|rem)$/.test(width) || width === DEFAULT_PANEL_WIDTH)
1095
934
  return "";
1096
- const tokens = [];
1097
- const hold = (html) => {
1098
- tokens.push(html);
1099
- return `\uE000${tokens.length - 1}\uE001`;
1100
- };
1101
- let s = text.replace(/\r\n/g, `
1102
- `);
1103
- s = s.replace(/```([\s\S]*?)```/g, (_m, body) => hold(preHtml(body)));
1104
- s = s.replace(/`([^`\n]+)`/g, (_m, body) => hold(`<code class="sm-code">${reEscape(body)}</code>`));
1105
- s = s.replace(/<([^<>\n]*)>/g, (_m, inner) => hold(renderControl(inner, ctx)));
1106
- s = renderEmoji(reEscape(s));
1107
- s = inlineStyles(s);
1108
- s = blockify(s);
1109
- const expand = (html) => html.replace(/\uE000(\d+)\uE001/g, (_m, i) => expand(tokens[Number(i)] ?? ""));
1110
- return tidy(expand(s));
935
+ return width.endsWith("%") ? width.slice(0, -1) : width;
1111
936
  }
1112
- function plainTextToHtml(text) {
1113
- if (!text)
1114
- return "";
1115
- return renderEmoji(reEscape(text.replace(/\r\n/g, `
1116
- `))).replace(/\n/g, "<br>");
937
+ function query(opts, over = {}) {
938
+ if (opts.screenshot)
939
+ return "?screenshot";
940
+ const parts = [];
941
+ if (opts.refreshSec)
942
+ parts.push(`refresh=${opts.refreshSec}`);
943
+ const panel = panelParam(opts);
944
+ if (panel)
945
+ parts.push(`panel=${panel}`);
946
+ if (over.full ?? opts.threadView === "full")
947
+ parts.push("full");
948
+ return parts.length ? `?${parts.join("&")}` : "";
1117
949
  }
1118
-
1119
- // src/render/blocks.ts
1120
- function rec(v) {
1121
- return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
950
+ function channelHref(channelId, opts) {
951
+ return `/c/${encodeURIComponent(channelId)}${query(opts, { full: false })}`;
1122
952
  }
1123
- function str2(v) {
1124
- return typeof v === "string" ? v : "";
953
+ function homeHref(opts) {
954
+ return `/${query(opts, { full: false })}`;
1125
955
  }
1126
- function arr(v) {
1127
- return Array.isArray(v) ? v : [];
956
+ function threadHref(channelId, ts, opts, over = {}) {
957
+ return `/c/${encodeURIComponent(channelId)}/t/${encodeURIComponent(ts)}${query(opts, over)}`;
1128
958
  }
1129
- function safeUrl(url) {
1130
- return /^(https?:\/\/|\/)/i.test(url) ? escapeHtml(url) : undefined;
959
+ function pad(n) {
960
+ return String(n).padStart(2, "0");
1131
961
  }
1132
- function unsupported(what) {
1133
- return `<div class="sm-unsupported">unsupported: ${escapeHtml(what || "unknown")}</div>`;
962
+ function timeOf(ts) {
963
+ const d = new Date(Number(ts) * 1000);
964
+ if (Number.isNaN(d.getTime()))
965
+ return "";
966
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
1134
967
  }
1135
- function textObject(v, ctx) {
1136
- if (typeof v === "string")
1137
- return plainTextToHtml(v);
1138
- const o = rec(v);
1139
- if (!o)
968
+ function dayKey(d) {
969
+ return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
970
+ }
971
+ function dayLabel(ts) {
972
+ const d = new Date(Number(ts) * 1000);
973
+ if (Number.isNaN(d.getTime()))
1140
974
  return "";
1141
- const text = str2(o.text);
1142
- return o.type === "mrkdwn" ? mrkdwnToHtml(text, ctx) : plainTextToHtml(text);
975
+ const now = new Date;
976
+ if (dayKey(d) === dayKey(now))
977
+ return "Today";
978
+ const yesterday = new Date(now.getTime() - 86400000);
979
+ if (dayKey(d) === dayKey(yesterday))
980
+ return "Yesterday";
981
+ return `${MONTHS[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
1143
982
  }
1144
- function plainOf(v) {
1145
- const o = rec(v);
1146
- return plainTextToHtml(o ? str2(o.text) : str2(v));
983
+ function fileSize(bytes) {
984
+ if (bytes < 1024)
985
+ return `${bytes} B`;
986
+ if (bytes < 1024 * 1024)
987
+ return `${(bytes / 1024).toFixed(1)} KB`;
988
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1147
989
  }
1148
- function image(url, alt, cls) {
1149
- const src = safeUrl(url);
1150
- if (!src)
1151
- return unsupported("image url");
1152
- return `<img class="${cls}" src="${src}" alt="${escapeHtml(alt)}">`;
990
+ function hashIndex(s, buckets) {
991
+ let h = 0;
992
+ for (let i = 0;i < s.length; i++)
993
+ h = h * 31 + s.charCodeAt(i) >>> 0;
994
+ return h % buckets;
1153
995
  }
1154
- function imageSrcOf(block) {
1155
- const direct = str2(block.image_url);
1156
- if (direct)
1157
- return direct;
1158
- const file = rec(block.slack_file);
1159
- return file ? str2(file.url) || str2(file.url_private) : "";
996
+ function initials(name) {
997
+ const words = name.replace(/[^\p{L}\p{N} ]/gu, " ").trim().split(/\s+/);
998
+ const letters = words.slice(0, 2).map((w) => w[0] ?? "").join("");
999
+ return (letters || name.slice(0, 2) || "?").toUpperCase();
1160
1000
  }
1161
- function button(el, ctx) {
1162
- const style = str2(el.style);
1163
- const cls = `sm-btn${style === "primary" ? " sm-btn-primary" : style === "danger" ? " sm-btn-danger" : ""}`;
1164
- const label = textObject(el.text, ctx) || "Button";
1165
- const url = safeUrl(str2(el.url));
1166
- const confirm = rec(el.confirm) ? '<span class="sm-btn-confirm" title="confirmation dialog">\u26A0</span>' : "";
1167
- return url ? `<a class="${cls}" href="${url}" target="_blank" rel="noopener">${label}${confirm}</a>` : `<span class="${cls}">${label}${confirm}</span>`;
1001
+ function channelLabel(store, c) {
1002
+ if (!c.is_im)
1003
+ return `#${c.name}`;
1004
+ const peer = c.user ? store.users.get(c.user) : undefined;
1005
+ return peer ? displayName(peer) : c.name;
1168
1006
  }
1169
- function selectPill(el, ctx, glyph = "\u25BE") {
1170
- const initial = rec(el.initial_option);
1171
- const label = initial && textObject(initial.text, ctx) || textObject(el.placeholder, ctx) || plainTextToHtml(str2(el.type).replace(/_/g, " "));
1172
- return `<span class="sm-select">${label}<span class="sm-select-caret">${glyph}</span></span>`;
1007
+ function channelIcon(c) {
1008
+ if (c.is_im)
1009
+ return "@";
1010
+ if (c.is_private)
1011
+ return "\uD83D\uDD12";
1012
+ return "#";
1173
1013
  }
1174
- function inputBox(el, ctx) {
1175
- const multiline = el.multiline === true;
1176
- const value = str2(el.initial_value);
1177
- const inner = value ? plainTextToHtml(value) : `<span class="sm-input-ph">${textObject(el.placeholder, ctx)}</span>`;
1178
- return `<div class="sm-input${multiline ? " sm-input-multi" : ""}">${inner}</div>`;
1014
+ function channelKind(c) {
1015
+ if (c.is_im)
1016
+ return "DM";
1017
+ if (c.is_private)
1018
+ return "private";
1019
+ return "public";
1179
1020
  }
1180
- function renderElement(v, ctx) {
1181
- const el = rec(v);
1182
- if (!el)
1183
- return "";
1184
- const type = str2(el.type);
1185
- switch (type) {
1186
- case "button":
1187
- return button(el, ctx);
1188
- case "image":
1189
- return image(imageSrcOf(el), str2(el.alt_text), "sm-acc-img");
1190
- case "overflow":
1191
- return `<span class="sm-select sm-overflow">\u22EF</span>`;
1192
- case "datepicker":
1193
- return selectPill({ ...el, placeholder: el.placeholder ?? "Select a date" }, ctx, "\uD83D\uDCC5");
1194
- case "timepicker":
1195
- return selectPill({ ...el, placeholder: el.placeholder ?? "Select a time" }, ctx, "\uD83D\uDD50");
1196
- case "plain_text_input":
1197
- return inputBox(el, ctx);
1198
- case "checkboxes":
1199
- case "radio_buttons":
1200
- return `<div class="sm-options">${arr(el.options).map((o) => {
1201
- const opt = rec(o);
1202
- const mark = type === "checkboxes" ? "\u2610" : "\u25EF";
1203
- return `<div class="sm-option">${mark} ${opt ? textObject(opt.text, ctx) : ""}</div>`;
1204
- }).join("")}</div>`;
1205
- default:
1206
- if (type.endsWith("_select") || type.startsWith("multi_"))
1207
- return selectPill(el, ctx);
1208
- return unsupported(type);
1021
+ function authorName(store, m) {
1022
+ if (m.username)
1023
+ return m.username;
1024
+ const user = m.user ? store.users.get(m.user) : undefined;
1025
+ if (user)
1026
+ return user.real_name || user.name;
1027
+ return m.bot_profile?.name ?? m.user ?? "unknown";
1028
+ }
1029
+ function avatarHtml(m, name) {
1030
+ const emojiName = m.icons?.emoji;
1031
+ if (emojiName) {
1032
+ const char = emojiChar(emojiName) ?? emojiName.replace(/:/g, "");
1033
+ return `<div class="sm-avatar sm-avatar-emoji">${escapeHtml(char)}</div>`;
1034
+ }
1035
+ const imageUrl = m.icons?.image_72 ?? m.icons?.image_48 ?? m.icons?.image_64;
1036
+ if (imageUrl && /^(https?:\/\/|\/)/.test(imageUrl)) {
1037
+ return `<div class="sm-avatar"><img src="${escapeHtml(imageUrl)}" alt=""></div>`;
1209
1038
  }
1039
+ const seed = m.user ?? m.bot_id ?? name;
1040
+ const color = AVATAR_COLORS[hashIndex(seed, AVATAR_COLORS.length)];
1041
+ return `<div class="sm-avatar" style="background:${color}">${escapeHtml(initials(name))}</div>`;
1210
1042
  }
1211
- function richStyle(html, style) {
1212
- if (!html || !style)
1213
- return html;
1214
- let out = html;
1215
- if (style.code === true)
1216
- out = `<code class="sm-code">${out}</code>`;
1217
- if (style.bold === true)
1218
- out = `<strong>${out}</strong>`;
1219
- if (style.italic === true)
1220
- out = `<em>${out}</em>`;
1221
- if (style.strike === true)
1222
- out = `<s>${out}</s>`;
1223
- return out;
1043
+ function reactionsHtml(store, m, interactive, locked) {
1044
+ if (!m.reactions?.length)
1045
+ return "";
1046
+ const chips = m.reactions.map((r) => {
1047
+ const who = r.users.map((id) => {
1048
+ const user = store.users.get(id);
1049
+ return user ? displayName(user) : id;
1050
+ }).join(", ");
1051
+ const char = emojiChar(r.name) ?? `:${r.name}:`;
1052
+ const content = `${escapeHtml(char)}<span class="sm-reaction-count">${r.count}</span>`;
1053
+ 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>`;
1054
+ });
1055
+ return `<div class="sm-reactions">${chips.join("")}</div>`;
1224
1056
  }
1225
- function richElement(v, ctx) {
1226
- const el = rec(v);
1227
- if (!el)
1057
+ function messageActions(m, opts) {
1058
+ const thread = m.thread_ts ?? m.ts;
1059
+ 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>`;
1060
+ 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>`;
1061
+ 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>`;
1062
+ }
1063
+ function reactionPicker() {
1064
+ const names = [
1065
+ "thumbsup",
1066
+ "green_heart",
1067
+ "eyes",
1068
+ "white_check_mark",
1069
+ "tada",
1070
+ "rocket",
1071
+ "star",
1072
+ "thinking_face",
1073
+ "sparkles",
1074
+ "fire",
1075
+ "raised_hands",
1076
+ "clap"
1077
+ ];
1078
+ 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("");
1079
+ 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>`;
1080
+ }
1081
+ function fileUrl(f, token) {
1082
+ if (!f.url_private)
1228
1083
  return "";
1229
- const style = rec(el.style);
1230
- switch (str2(el.type)) {
1231
- case "text":
1232
- return richStyle(plainTextToHtml(str2(el.text)).replace(/\n/g, "<br>"), style);
1233
- case "link": {
1234
- const url = safeUrl(str2(el.url));
1235
- const label = plainTextToHtml(str2(el.text) || str2(el.url));
1236
- if (!url)
1237
- return label;
1238
- return richStyle(`<a class="sm-link" href="${url}" target="_blank" rel="noopener">${label}</a>`, style);
1239
- }
1240
- case "user": {
1241
- const user = ctx.users.get(str2(el.user_id));
1242
- return `<span class="sm-pill">@${escapeHtml(user ? displayName(user) : str2(el.user_id))}</span>`;
1243
- }
1244
- case "usergroup":
1245
- return `<span class="sm-pill">@${escapeHtml(str2(el.usergroup_id))}</span>`;
1246
- case "channel": {
1247
- const channel = ctx.channels.get(str2(el.channel_id));
1248
- return `<span class="sm-pill">#${escapeHtml(channel ? channel.name : str2(el.channel_id))}</span>`;
1249
- }
1250
- case "broadcast":
1251
- return `<span class="sm-pill">@${escapeHtml(str2(el.range) || "channel")}</span>`;
1252
- case "emoji": {
1253
- const char = emojiChar(str2(el.name)) ?? (el.unicode ? emojiFromUnicode(str2(el.unicode)) : undefined);
1254
- return char ?? `<span class="sm-emoji-name">:${escapeHtml(str2(el.name))}:</span>`;
1255
- }
1256
- case "date":
1257
- return plainTextToHtml(str2(el.fallback) || str2(el.timestamp));
1258
- case "color":
1259
- return plainTextToHtml(str2(el.value));
1260
- default:
1261
- return "";
1262
- }
1084
+ return escapeHtml(`${f.url_private}${f.url_private.includes("?") ? "&" : "?"}t=${token}`);
1263
1085
  }
1264
- function richSection(v, ctx) {
1265
- const block = rec(v);
1266
- if (!block)
1086
+ function filesHtml(files, token) {
1087
+ if (!files?.length)
1267
1088
  return "";
1268
- const inner = arr(block.elements).map((e) => richElement(e, ctx)).join("");
1269
- switch (str2(block.type)) {
1270
- case "rich_text_section":
1271
- return `<div class="sm-rt-section">${inner}</div>`;
1272
- case "rich_text_quote":
1273
- return `<blockquote class="sm-quote">${inner}</blockquote>`;
1274
- case "rich_text_preformatted":
1275
- return `<pre class="sm-pre">${inner}</pre>`;
1276
- case "rich_text_list": {
1277
- const tag = str2(block.style) === "ordered" ? "ol" : "ul";
1278
- const indent = Number(block.indent) || 0;
1279
- const items = arr(block.elements).map((item) => `<li>${richSection(item, ctx)}</li>`).join("");
1280
- const margin = indent ? ` style="margin-left:${indent * 18}px"` : "";
1281
- return `<${tag} class="sm-list"${margin}>${items}</${tag}>`;
1089
+ const cards = files.map((f) => {
1090
+ if (f.mimetype?.startsWith("image/") && f.url_private) {
1091
+ return `<img class="sm-file-img" src="${fileUrl(f, token)}" alt="${escapeHtml(f.title || f.name)}">`;
1282
1092
  }
1283
- default:
1284
- return inner;
1285
- }
1093
+ const href = fileUrl(f, token);
1094
+ const name = escapeHtml(f.title || f.name);
1095
+ const meta = `${escapeHtml(f.pretty_type || f.filetype || "File")} \xB7 ${fileSize(f.size ?? 0)}`;
1096
+ const label = href ? `<a href="${href}">${name}</a>` : name;
1097
+ 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>`;
1098
+ });
1099
+ return `<div class="sm-files">${cards.join("")}</div>`;
1286
1100
  }
1287
- function sectionBlock(block, ctx) {
1288
- const parts = [];
1289
- if (block.text)
1290
- parts.push(`<div class="sm-section-text">${textObject(block.text, ctx)}</div>`);
1291
- const fields = arr(block.fields);
1292
- if (fields.length) {
1293
- parts.push(`<div class="sm-fields">${fields.map((f) => `<div class="sm-field">${textObject(f, ctx)}</div>`).join("")}</div>`);
1294
- }
1295
- const accessory = block.accessory ? renderElement(block.accessory, ctx) : "";
1296
- const body = parts.join("");
1297
- if (!accessory)
1298
- return `<div class="sm-block sm-section">${body}</div>`;
1299
- 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>`;
1101
+ function renderMessage(store, ctx, m, opts, flags = {}) {
1102
+ const name = authorName(store, m);
1103
+ const isApp = Boolean(m.bot_id);
1104
+ const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
1105
+ const interactive = !opts.screenshot && !flags.ephemeral && humanUsers(store).length > 0;
1106
+ const body = [];
1107
+ if (m.streaming_state !== undefined) {
1108
+ if (m.text)
1109
+ body.push(`<div class="sm-text">${mrkdwnToHtml(markdownToMrkdwn(m.text), ctx)}</div>`);
1110
+ if (blocks)
1111
+ body.push(renderBlocks(blocks, ctx));
1112
+ } else if (blocks)
1113
+ body.push(renderBlocks(blocks, ctx));
1114
+ else if (m.text)
1115
+ body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
1116
+ if (m.edited)
1117
+ body.push(`<div class="sm-edited">(edited)</div>`);
1118
+ if (m.attachments?.length)
1119
+ body.push(renderAttachments(m.attachments, ctx));
1120
+ body.push(filesHtml(m.files, store.bot.token));
1121
+ body.push(reactionsHtml(store, m, interactive, Boolean(opts.writeGated)));
1122
+ if (flags.ephemeral)
1123
+ body.push(`<div class="sm-eph-note">Only visible to you</div>`);
1124
+ if (flags.threadLink && m.reply_count) {
1125
+ const count = `${m.reply_count} ${m.reply_count === 1 ? "reply" : "replies"}`;
1126
+ const last = m.latest_reply ? `<span class="sm-replies-time">Last reply ${timeOf(m.latest_reply)}</span>` : "";
1127
+ body.push(`<a class="sm-replies" href="${threadHref(m.channel, m.thread_ts ?? m.ts, opts)}">${count}${last}</a>`);
1128
+ }
1129
+ if (interactive)
1130
+ body.push(messageActions(m, opts));
1131
+ const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
1132
+ const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
1133
+ 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>`;
1300
1134
  }
1301
- function contextBlock(block, ctx) {
1302
- const inner = arr(block.elements).map((e) => {
1303
- const el = rec(e);
1304
- if (!el)
1305
- return "";
1306
- if (str2(el.type) === "image")
1307
- return image(imageSrcOf(el), str2(el.alt_text), "sm-context-img");
1308
- return `<span class="sm-context-text">${textObject(el, ctx)}</span>`;
1309
- }).join("");
1310
- return `<div class="sm-block sm-context">${inner}</div>`;
1135
+ function markdownToMrkdwn(text) {
1136
+ 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("");
1311
1137
  }
1312
- function imageBlock(block, ctx) {
1313
- const title = block.title ? `<div class="sm-img-title">${textObject(block.title, ctx)}</div>` : "";
1314
- const src = imageSrcOf(block);
1315
- const alt = str2(block.alt_text);
1316
- if (!src) {
1317
- const file = rec(block.slack_file);
1318
- return `<div class="sm-block">${title}${unsupported(`image (file ${str2(file?.id) || "?"})`)}</div>`;
1138
+ function renderMessageList(store, ctx, messages, opts, flags = {}) {
1139
+ const out = [];
1140
+ let day = "";
1141
+ for (const m of messages) {
1142
+ const label = flags.dividers === false ? "" : dayLabel(m.ts);
1143
+ if (label && label !== day) {
1144
+ day = label;
1145
+ out.push(`<div class="sm-daydiv"><span>${escapeHtml(label)}</span></div>`);
1146
+ }
1147
+ out.push(renderMessage(store, ctx, m, opts, { ...flags, ephemeral: m._ephemeral === true }));
1319
1148
  }
1320
- return `<div class="sm-block sm-image">${title}${image(src, alt, "sm-img")}</div>`;
1321
- }
1322
- function inputBlock(block, ctx) {
1323
- const label = block.label ? `<div class="sm-label">${plainOf(block.label)}</div>` : "";
1324
- const element = block.element ? renderElement(block.element, ctx) : "";
1325
- const hint = block.hint ? `<div class="sm-hint">${plainOf(block.hint)}</div>` : "";
1326
- return `<div class="sm-block sm-input-block">${label}${element}${hint}</div>`;
1149
+ return out.join("");
1327
1150
  }
1328
- function videoBlock(block, ctx) {
1329
- const thumb = safeUrl(str2(block.thumbnail_url));
1330
- const url = safeUrl(str2(block.title_url) || str2(block.video_url));
1331
- const title = textObject(block.title, ctx) || plainTextToHtml(str2(block.alt_text));
1332
- const inner = `${thumb ? `<img class="sm-video-thumb" src="${thumb}" alt="${escapeHtml(str2(block.alt_text))}">` : ""}<div class="sm-video-title">\u25B6 ${title}</div>`;
1333
- return `<div class="sm-block sm-video">${url ? `<a class="sm-video-link" href="${url}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`;
1151
+ function sidebar(store, opts, active) {
1152
+ const channels = [...store.channels.values()].sort((a, b) => channelLabel(store, a).localeCompare(channelLabel(store, b)));
1153
+ 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("");
1154
+ const options = channels.map((c) => `<option value="${escapeHtml(channelHref(c.id, opts))}"${c.id === active ? " selected" : ""}>${escapeHtml(channelLabel(store, c))}</option>`).join("");
1155
+ 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>`;
1156
+ 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>`;
1334
1157
  }
1335
- function renderBlock(v, ctx) {
1336
- const block = rec(v);
1337
- if (!block)
1338
- return unsupported("block");
1339
- switch (str2(block.type)) {
1340
- case "header":
1341
- return `<div class="sm-block sm-header-block">${textObject(block.text, ctx)}</div>`;
1342
- case "section":
1343
- return sectionBlock(block, ctx);
1344
- case "divider":
1345
- return `<div class="sm-block"><hr class="sm-hr"></div>`;
1346
- case "context":
1347
- return contextBlock(block, ctx);
1348
- case "actions":
1349
- return `<div class="sm-block sm-actions">${arr(block.elements).map((e) => renderElement(e, ctx)).join("")}</div>`;
1350
- case "image":
1351
- return imageBlock(block, ctx);
1352
- case "rich_text":
1353
- return `<div class="sm-block sm-rich-text">${arr(block.elements).map((e) => richSection(e, ctx)).join("")}</div>`;
1354
- case "input":
1355
- return inputBlock(block, ctx);
1356
- case "file":
1357
- return `<div class="sm-block sm-file-block">\uD83D\uDCCE ${escapeHtml(str2(block.external_id) || str2(block.file_id) || "file")}</div>`;
1358
- case "video":
1359
- return videoBlock(block, ctx);
1360
- default:
1361
- return `<div class="sm-block">${unsupported(str2(block.type))}</div>`;
1158
+ function shell(store, opts, parts) {
1159
+ const refresh = opts.refreshSec && !opts.screenshot ? `<meta http-equiv="refresh" content="${Math.max(1, Math.floor(opts.refreshSec))}">` : "";
1160
+ const style = opts.screenshot ? "" : ` style="--sm-panel-w:${panelWidth(opts)}"`;
1161
+ 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>`;
1162
+ if (opts.screenshot) {
1163
+ return `${head}<body><div class="sm-shot">${parts.header}<div class="sm-page">${parts.main}</div></div></body></html>`;
1362
1164
  }
1165
+ const app = `sm-app${parts.panel ? " sm-app-thread" : ""}`;
1166
+ const handle = parts.panel ? `<div class="sm-resize" title="Drag to resize, double-click to reset"></div>` : "";
1167
+ 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>`;
1363
1168
  }
1364
- function renderBlocks(blocks, ctx) {
1365
- const list = arr(blocks);
1366
- if (!list.length)
1367
- return "";
1368
- return `<div class="sm-blocks">${list.map((b) => renderBlock(b, ctx)).join("")}</div>`;
1169
+ function topbar(title, sub, back, actions) {
1170
+ const backLink = back ? `<a class="sm-back" href="${back.href}">${escapeHtml(back.label)}</a>` : "";
1171
+ const right = actions ? `<div class="sm-top-actions">${actions}</div>` : "";
1172
+ return `<div class="sm-top">${backLink}<h1>${title}</h1>${sub ? `<div class="sm-sub">${sub}</div>` : ""}${right}</div>`;
1369
1173
  }
1370
- var NAMED_COLORS = {
1371
- good: "#2eb67d",
1372
- warning: "#ecb22e",
1373
- danger: "#e01e5a"
1374
- };
1375
- function barColor(v) {
1376
- const raw = str2(v).trim();
1377
- if (!raw)
1378
- return "#dddddd";
1379
- const named = NAMED_COLORS[raw.toLowerCase()];
1380
- if (named)
1381
- return named;
1382
- const hex = raw.startsWith("#") ? raw : `#${raw}`;
1383
- return /^#[0-9a-fA-F]{3,8}$/.test(hex) ? hex : "#dddddd";
1174
+ function indexView(store, opts) {
1175
+ const cards = [
1176
+ ["Workspace", escapeHtml(store.team.name)],
1177
+ ["Team id", escapeHtml(store.team.id)],
1178
+ ["Bot user", escapeHtml(`${store.app.name} (${store.bot.userId})`)],
1179
+ ["Connections", String(opts.connections ?? 0)]
1180
+ ].map(([k, v]) => `<div class="sm-card"><div class="sm-card-k">${k}</div><div class="sm-card-v">${v}</div></div>`).join("");
1181
+ const channels = [...store.channels.values()];
1182
+ const channelRows = channels.map((c) => {
1183
+ const count = store.messages.get(c.id)?.length ?? 0;
1184
+ 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>`;
1185
+ }).join("");
1186
+ 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("");
1187
+ const main = `<div class="sm-cards">${cards}</div>
1188
+ <div class="sm-h2">Channels</div>
1189
+ ${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>`}
1190
+ <div class="sm-h2">Users</div>
1191
+ <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>`;
1192
+ return shell(store, opts, {
1193
+ title: `${store.team.name} \xB7 slack-mock`,
1194
+ header: topbar(escapeHtml(store.team.name), "slack-mock workspace", undefined, identityChip(store, opts)),
1195
+ main,
1196
+ script: opts.screenshot ? "" : uiScript(store, opts, undefined, false)
1197
+ });
1384
1198
  }
1385
- function attachmentFields(fields, ctx) {
1386
- if (!fields.length)
1199
+ function channelMessages(store, channel) {
1200
+ const history = store.history(channel.id, { limit: 1000 }).items;
1201
+ const ephemerals = store.ephemerals.filter((e) => e.channel === channel.id).map((e) => ({ ...e, _ephemeral: true }));
1202
+ return [...history, ...ephemerals].sort((a, b) => Number(a.ts) - Number(b.ts));
1203
+ }
1204
+ function channelColumn(store, ctx, opts, channel, openTs) {
1205
+ const messages = channelMessages(store, channel);
1206
+ if (!messages.length)
1207
+ return `<div class="sm-empty">No messages yet</div>`;
1208
+ return renderMessageList(store, ctx, messages, opts, {
1209
+ threadLink: true,
1210
+ dividers: true,
1211
+ openTs
1212
+ });
1213
+ }
1214
+ function channelHeader(store, opts, channel) {
1215
+ const sub = [channel.topic.value, channel.purpose.value].filter(Boolean).join(" \xB7 ");
1216
+ const back = opts.screenshot ? undefined : { href: homeHref(opts), label: "\u2190 Workspace" };
1217
+ return topbar(escapeHtml(channelLabel(store, channel)), escapeHtml(sub), back, identityChip(store, opts));
1218
+ }
1219
+ function humanUsers(store) {
1220
+ return [...store.users.values()].filter((u) => !u.is_bot && !u.deleted);
1221
+ }
1222
+ function userStatus(user) {
1223
+ return user.profile.status_text ? `<span class="sm-user-status">${escapeHtml(user.profile.status_text)}</span>` : "";
1224
+ }
1225
+ function identityChip(store, opts) {
1226
+ if (opts.screenshot)
1387
1227
  return "";
1388
- return `<div class="sm-fields">${fields.map((f) => {
1389
- const field = rec(f);
1390
- if (!field)
1391
- return "";
1392
- const wide = field.short === true ? "" : " sm-field-wide";
1393
- return `<div class="sm-field${wide}"><div class="sm-field-title">${plainTextToHtml(str2(field.title))}</div><div>${mrkdwnToHtml(str2(field.value), ctx)}</div></div>`;
1394
- }).join("")}</div>`;
1228
+ const users = humanUsers(store);
1229
+ const selected = users[0];
1230
+ if (!selected)
1231
+ return "";
1232
+ const name = selected.real_name || selected.name;
1233
+ const avatar = `<span class="sm-identity-avatar" style="background:${AVATAR_COLORS[hashIndex(selected.id, AVATAR_COLORS.length)]}">${escapeHtml(initials(name))}</span>`;
1234
+ const items = users.map((u) => {
1235
+ const real = u.real_name || u.name;
1236
+ const color = AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)];
1237
+ 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>`;
1238
+ }).join("");
1239
+ const hidden = opts.writeGated ? " hidden" : "";
1240
+ 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>`;
1395
1241
  }
1396
- function attachment(v, ctx) {
1397
- const att = rec(v);
1398
- if (!att)
1242
+ function composer(store, opts, channel, threadTs) {
1243
+ if (opts.screenshot)
1399
1244
  return "";
1400
- const parts = [];
1401
- const author = str2(att.author_name);
1402
- if (author) {
1403
- const icon = safeUrl(str2(att.author_icon));
1404
- parts.push(`<div class="sm-att-author">${icon ? `<img class="sm-att-author-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(author)}</div>`);
1405
- }
1406
- const title = str2(att.title);
1407
- if (title) {
1408
- const link = safeUrl(str2(att.title_link));
1409
- const inner = plainTextToHtml(title);
1410
- parts.push(`<div class="sm-att-title">${link ? `<a class="sm-link" href="${link}" target="_blank" rel="noopener">${inner}</a>` : inner}</div>`);
1411
- }
1412
- const text = str2(att.text) || (parts.length ? "" : str2(att.fallback));
1413
- if (text)
1414
- parts.push(`<div class="sm-att-text">${mrkdwnToHtml(text, ctx)}</div>`);
1415
- parts.push(attachmentFields(arr(att.fields), ctx));
1416
- const img = safeUrl(str2(att.image_url));
1417
- if (img)
1418
- parts.push(`<img class="sm-att-img" src="${img}" alt="">`);
1419
- const thumb = !img ? safeUrl(str2(att.thumb_url)) : undefined;
1420
- if (thumb)
1421
- parts.push(`<img class="sm-att-thumb" src="${thumb}" alt="">`);
1422
- const blocks = arr(att.blocks);
1423
- if (blocks.length)
1424
- parts.push(renderBlocks(blocks, ctx));
1425
- const footer = str2(att.footer);
1426
- const ts = att.ts ? formatAttachmentTs(att.ts) : "";
1427
- if (footer || ts) {
1428
- const icon = safeUrl(str2(att.footer_icon));
1429
- parts.push(`<div class="sm-att-footer">${icon ? `<img class="sm-att-footer-icon" src="${icon}" alt="">` : ""}${plainTextToHtml(footer)}${footer && ts ? " | " : ""}${escapeHtml(ts)}</div>`);
1430
- }
1431
- const pretext = str2(att.pretext);
1432
- const box = `<div class="sm-att" style="border-left-color:${barColor(att.color)}">${parts.join("")}</div>`;
1433
- return pretext ? `<div class="sm-att-pretext">${mrkdwnToHtml(pretext, ctx)}</div>${box}` : box;
1245
+ const users = humanUsers(store);
1246
+ if (!users.length)
1247
+ return "";
1248
+ const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
1249
+ const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
1250
+ const gated = opts.writeGated ? ' data-gated="1"' : "";
1251
+ 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>` : "";
1252
+ 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>`;
1434
1253
  }
1435
- function formatAttachmentTs(v) {
1436
- const secs = Number(v);
1437
- if (!Number.isFinite(secs) || secs <= 0)
1438
- return str2(v);
1439
- const d = new Date(secs * 1000);
1440
- const pad = (n) => String(n).padStart(2, "0");
1441
- return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
1254
+ function mentionData(store) {
1255
+ const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
1256
+ id: u.id,
1257
+ name: u.name,
1258
+ real: u.real_name || u.name,
1259
+ initials: initials(u.real_name || u.name),
1260
+ color: AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)],
1261
+ bot: u.is_bot
1262
+ }));
1263
+ const json = JSON.stringify(users).replace(/</g, "\\u003c");
1264
+ return `<script type="application/json" id="sm-users">${json}</script>`;
1442
1265
  }
1443
- function renderAttachments(attachments, ctx) {
1444
- const list = arr(attachments);
1445
- if (!list.length)
1446
- return "";
1447
- return `<div class="sm-atts">${list.map((a) => attachment(a, ctx)).join("")}</div>`;
1266
+ function uiScript(store, opts, closeUrl, autoScroll = true) {
1267
+ 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)}});` : "";
1268
+ const body = `(function(){
1269
+ var viewport=window.visualViewport;
1270
+ 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")}
1271
+ fitViewport();addEventListener("resize",fitViewport);
1272
+ if(viewport){viewport.addEventListener("resize",fitViewport);viewport.addEventListener("scroll",fitViewport)}
1273
+ document.addEventListener("change",function(e){if(e.target.classList.contains("sm-channel-switch"))location.href=e.target.value});
1274
+ var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
1275
+ ${autoScroll ? `function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}
1276
+ scroll();addEventListener("load",scroll);` : ""}
1277
+ var handle=document.querySelector(".sm-resize");
1278
+ if(handle){
1279
+ var saved=null;try{saved=localStorage.getItem(W)}catch(e){}
1280
+ if(!FIXED&&saved)document.body.style.setProperty("--sm-panel-w",saved);
1281
+ var dragging=false;
1282
+ handle.addEventListener("mousedown",function(e){dragging=true;handle.classList.add("sm-dragging");e.preventDefault()});
1283
+ 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")});
1284
+ 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){}});
1285
+ handle.addEventListener("dblclick",function(){try{localStorage.removeItem(W)}catch(e){}document.body.style.setProperty("--sm-panel-w",DEF)});
1448
1286
  }
1449
-
1450
- // src/render/index.ts
1451
- var DEFAULT_PANEL_WIDTH = "50%";
1452
- var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1453
- var AVATAR_COLORS = [
1454
- "#4a154b",
1455
- "#1264a3",
1456
- "#2eb67d",
1457
- "#e01e5a",
1458
- "#e8912d",
1459
- "#007a5a",
1460
- "#7c3aed",
1461
- "#00a2ac",
1462
- "#df10a5",
1463
- "#3d5afe"
1464
- ];
1465
- var CSS = `
1466
- *{box-sizing:border-box}
1467
- html,body{margin:0;padding:0;height:100%}
1468
- 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}
1469
- a{color:#1264a3;text-decoration:none}
1470
- a:hover{text-decoration:underline}
1471
- .sm-app{display:flex;height:100vh;overflow:hidden}
1472
- .sm-side{width:230px;flex:none;background:#3f0e40;color:#d9d0d9;padding:16px 0;overflow-y:auto}
1473
- .sm-side-title{color:#fff;font-weight:900;font-size:17px;padding:0 16px 12px;border-bottom:1px solid #522653;margin-bottom:10px}
1474
- .sm-side-team{display:block;font-weight:400;font-size:12px;color:#bda9bd}
1475
- .sm-side-h{font-size:13px;color:#bda9bd;padding:10px 16px 4px}
1476
- .sm-side a{display:block;color:#d9d0d9;padding:3px 16px;font-size:15px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1477
- .sm-side a:hover{background:#522653;color:#fff;text-decoration:none}
1478
- .sm-side a.sm-active,.sm-side a.sm-active:hover{background:#1164a3;color:#fff}
1479
- .sm-side-title a:hover{background:none;text-decoration:underline}
1480
- .sm-main{flex:1;min-width:280px;display:flex;flex-direction:column;overflow:hidden}
1481
- .sm-shot{width:760px;padding:16px;background:#fff}
1482
- .sm-top{border-bottom:1px solid #e8e8e8;padding:12px 20px;display:flex;align-items:baseline;gap:12px;flex:none}
1483
- .sm-top h1{font-size:18px;font-weight:900;margin:0}
1484
- .sm-top .sm-sub{font-size:13px;color:#616061;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1485
- .sm-back{font-size:13px;font-weight:700;color:#616061;flex:none}
1486
- .sm-back:hover{color:#1264a3}
1487
- .sm-page{padding:12px 20px 32px}
1488
- .sm-main .sm-page{flex:1;overflow-y:auto}
1489
- .sm-shot .sm-page{padding:0}
1490
- .sm-shot .sm-top{padding:0 0 10px;margin-bottom:8px}
1491
-
1492
- .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}
1493
- .sm-panel-top{display:flex;align-items:flex-start;gap:10px;padding:12px 16px;border-bottom:1px solid #e8e8e8;flex:none}
1494
- .sm-panel-heading{flex:1;min-width:0}
1495
- .sm-panel-title{font-size:18px;font-weight:900;margin:0;line-height:22px}
1496
- .sm-panel-sub{font-size:13px;color:#616061}
1497
- .sm-panel-close,.sm-panel-expand{font-size:16px;line-height:22px;color:#616061;padding:0 6px;border-radius:4px;flex:none}
1498
- .sm-panel-close{font-size:20px}
1499
- .sm-panel-close:hover,.sm-panel-expand:hover{background:#f0f0f0;color:#1d1c1d;text-decoration:none}
1500
- .sm-panel-back{display:none;padding:8px 16px;font-size:13px;font-weight:700;border-bottom:1px solid #e8e8e8;flex:none}
1501
- .sm-panel-body{flex:1;overflow-y:auto;padding:12px 16px 32px}
1502
- .sm-resize{width:6px;flex:none;cursor:col-resize;background:#f2f2f2;border-left:1px solid #e8e8e8}
1503
- .sm-resize:hover,.sm-resize.sm-dragging{background:#1264a3;border-left-color:#1264a3}
1504
- .sm-icon-btn{display:inline-block;font-size:16px;line-height:22px;color:#616061;padding:0 6px;border-radius:4px;cursor:pointer}
1505
- .sm-icon-btn:hover{background:#f0f0f0;color:#1d1c1d;text-decoration:none}
1506
- .sm-composer{position:relative;flex:none;border-top:1px solid #e8e8e8;padding:10px 20px 12px;background:#fff}
1507
- .sm-panel .sm-composer{padding:10px 16px 12px}
1508
- .sm-composer-box{border:1px solid #bbb;border-radius:8px;padding:8px 10px;background:#fff}
1509
- .sm-composer-box:focus-within{border-color:#1264a3;box-shadow:0 0 0 1px #1264a3}
1510
- .sm-composer-row{display:flex;align-items:center;gap:8px;margin-top:6px}
1511
- .sm-composer-user{flex:0 1 auto;min-width:0;max-width:170px;border:0;border-radius:4px;background:#f0f0f0;color:#1d1c1d;font-family:inherit;font-size:12px;padding:4px 6px}
1512
- .sm-composer-user:hover{background:#e8e8e8}
1513
- .sm-composer-text{display:block;width:100%;border:0;outline:none;resize:vertical;font-family:inherit;font-size:15px;line-height:20px;color:#1d1c1d;padding:0;background:none}
1514
- .sm-composer-send{flex:none;margin-left:auto;border:0;border-radius:4px;background:#007a5a;color:#fff;font-family:inherit;font-weight:700;font-size:13px;padding:6px 14px;cursor:pointer}
1515
- .sm-composer-send:hover{background:#148567;color:#fff}
1516
- .sm-composer-hint{font-size:11px;color:#616061;margin-top:4px}
1517
- .sm-mentions{display:none;position:absolute;left:20px;right:20px;bottom:100%;margin-bottom:6px;max-height:260px;overflow-y:auto;background:#fff;border:1px solid #ddd;border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.16);z-index:5}
1518
- .sm-panel .sm-mentions{left:16px;right:16px}
1519
- .sm-mention{display:flex;align-items:center;gap:8px;padding:6px 10px;font-size:14px;cursor:pointer;color:#1d1c1d}
1520
- .sm-mention-on{background:#1264a3;color:#fff}
1521
- .sm-mention-on .sm-mention-real{color:#dbe9f5}
1522
- .sm-mention-av{width:20px;height:20px;border-radius:3px;flex:none;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-size:10px;font-weight:700}
1523
- .sm-mention-name{font-weight:700}
1524
- .sm-mention-real{color:#616061;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1525
-
1526
- .sm-side a,.sm-btn,.sm-select,.sm-reaction,.sm-file-card,.sm-prompt,.sm-replies,.sm-back,.sm-panel-close,.sm-panel-expand,.sm-composer-send,.sm-composer-user,.sm-top-actions a{cursor:pointer}
1527
- .sm-composer-text{cursor:text}
1528
- .sm-badge,.sm-time,.sm-daydiv,.sm-pill,.sm-emoji-name,.sm-avatar,.sm-name,.sm-composer-hint,.sm-unsupported,.sm-tag,.sm-card{cursor:default}
1529
- .sm-top-actions{margin-left:auto;display:flex;gap:12px;align-items:baseline;flex:none}
1530
- .sm-top-actions a{font-size:13px;font-weight:700;color:#616061}
1531
- .sm-top-actions a:hover{color:#1264a3}
1532
- @media (max-width:900px){
1533
- .sm-side{display:none}
1534
- .sm-app-thread .sm-main{display:none}
1535
- .sm-panel{width:100%;min-width:0;border-left:0}
1536
- .sm-panel-back{display:block}
1537
- .sm-panel-expand,.sm-resize{display:none}
1287
+ var raw=document.getElementById("sm-users");
1288
+ var USERS=raw?JSON.parse(raw.textContent||"[]"):[],HUMANS=USERS.filter(function(u){return !u.bot});
1289
+ var PEOPLE=USERS.concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
1290
+ function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&amp;":c==="<"?"&lt;":c===">"?"&gt;":"&quot;"})}
1291
+ var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter",IK="sm-identity",currentIdentity="",identityStorage=true;
1292
+ function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
1293
+ function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
1294
+ function setIdentity(v){currentIdentity=v;try{if(v)localStorage.setItem(IK,v);else localStorage.removeItem(IK)}catch(e){identityStorage=false}}
1295
+ function findIdentity(value,key){for(var i=0;i<HUMANS.length;i++)if(HUMANS[i][key]===value)return HUMANS[i];return null}
1296
+ 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}
1297
+ (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)}})();
1298
+ (function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
1299
+ function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
1300
+ var reactionDialog=document.querySelector(".sm-reaction-picker"),reactionTarget=null,reactionScope=null,reactionBusy=false;
1301
+ 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})}
1302
+ 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}
1303
+ function positionReactions(){
1304
+ if(!reactionDialog||!reactionDialog.open||!reactionTarget)return;
1305
+ if(!reactionTarget.isConnected){reactionTarget=findMessageElement(reactionScope,reactionTarget.dataset.ts);if(!reactionTarget){closeReactions();return}}
1306
+ 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;
1307
+ if(anchor.bottom<=Math.max(top,scope.top)||anchor.top>=Math.min(top+height,scope.bottom)){closeReactions();return}
1308
+ reactionDialog.style.maxWidth=Math.max(0,width-pad*2)+"px";reactionDialog.style.maxHeight=Math.max(0,height-pad*2)+"px";
1309
+ var rect=reactionDialog.getBoundingClientRect(),x=Math.max(left+pad,Math.min(anchor.right-rect.width,left+width-rect.width-pad)),y=anchor.bottom+gap;
1310
+ if(y+rect.height>top+height-pad)y=anchor.top-rect.height-gap;
1311
+ reactionDialog.style.left=x+"px";reactionDialog.style.top=Math.max(top+pad,Math.min(y,top+height-rect.height-pad))+"px";
1312
+ }
1313
+ document.addEventListener("scroll",function(e){if(!reactionDialog.contains(e.target))positionReactions()},true);
1314
+ addEventListener("resize",positionReactions);
1315
+ if(window.visualViewport){window.visualViewport.addEventListener("resize",positionReactions);window.visualViewport.addEventListener("scroll",positionReactions)}
1316
+ document.addEventListener("pointerdown",function(e){if(reactionDialog.open&&!reactionDialog.contains(e.target)&&!e.target.closest(".sm-add-reaction"))closeReactions()});
1317
+ document.addEventListener("focusin",function(e){if(reactionDialog.open&&!reactionDialog.contains(e.target)&&(!reactionTarget||e.target!==reactionTarget.querySelector(".sm-add-reaction")))closeReactions()});
1318
+ function hasReaction(button,user){return JSON.parse(button.dataset.users||"[]").indexOf(user)!==-1}
1319
+ 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()}
1320
+ 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()}
1321
+ 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()}
1322
+ 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})}
1323
+ 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"))});
1324
+ 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()});
1325
+ document.addEventListener("keydown",function(e){if(e.key==="Escape"&&reactionDialog&&reactionDialog.open){e.preventDefault();e.stopImmediatePropagation();closeReactions(true)}});
1326
+ 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"))}});
1327
+ addEventListener("storage",function(e){if(e.key===IK){currentIdentity=e.newValue||"";identityUi()}});
1328
+ lockUi();
1329
+ var pending=null;
1330
+ 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)}
1331
+ function apply(html){
1332
+ 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");
1333
+ 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;
1334
+ if(focusedMessage&&!opener.isConnected){var message=findMessageElement(focusedScope,focusedMessage.dataset.ts);if(message)message.querySelector(".sm-add-reaction").focus({preventScroll:true})}
1538
1335
  }
1539
-
1540
- .sm-daydiv{display:flex;align-items:center;gap:10px;margin:14px 0 8px}
1541
- .sm-daydiv:before,.sm-daydiv:after{content:"";flex:1;height:1px;background:#e8e8e8}
1542
- .sm-daydiv span{border:1px solid #e8e8e8;border-radius:12px;padding:2px 12px;font-size:13px;font-weight:700;color:#454245;background:#fff}
1543
-
1544
- .sm-msg{display:flex;gap:12px;padding:8px 8px;border-radius:6px}
1545
- .sm-msg:hover{background:#f8f8f8}
1546
- .sm-msg-eph{background:#fffbe6}
1547
- .sm-msg-eph:hover{background:#fff7d1}
1548
- .sm-msg-open,.sm-msg-open:hover{background:#fff8e2;box-shadow:inset 3px 0 0 #ecb22e}
1549
- .sm-avatar{width:36px;height:36px;flex:none;border-radius:4px;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:14px;overflow:hidden}
1550
- .sm-avatar img{width:36px;height:36px;object-fit:cover}
1551
- .sm-avatar-emoji{font-size:20px;background:#f0f0f0}
1552
- .sm-msg-body{min-width:0;flex:1}
1553
- .sm-msg-head{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;margin-bottom:1px}
1554
- .sm-name{font-weight:700;font-size:15px;color:#1d1c1d}
1555
- .sm-badge{background:#e8e8e8;color:#616061;font-size:10px;font-weight:700;border-radius:2px;padding:1px 4px;letter-spacing:.4px;text-transform:uppercase}
1556
- .sm-time{font-size:12px;color:#616061}
1557
- .sm-text{font-size:15px;line-height:22px;word-wrap:break-word;overflow-wrap:anywhere}
1558
- .sm-edited{font-size:12px;color:#616061}
1559
- .sm-eph-note{font-size:12px;color:#8a6d1a;margin-top:4px}
1560
- .sm-stream{display:inline-block;margin-left:4px;color:#616061;font-weight:700;animation:sm-pulse 1s ease-in-out infinite}
1561
- @keyframes sm-pulse{0%,100%{opacity:.25}50%{opacity:1}}
1562
- @keyframes sm-flash{0%{background:#fff3bf}100%{background:transparent}}
1563
- @keyframes sm-flash-soft{0%{background:#eaf3ff}100%{background:transparent}}
1564
- .sm-msg-new{animation:sm-flash 2.4s ease-out}
1565
- .sm-msg-changed{animation:sm-flash-soft .9s ease-out}
1566
- @media (prefers-reduced-motion:reduce){.sm-msg-new,.sm-msg-changed{animation:none}}
1567
- .sm-live{font-size:11px;font-weight:600;color:#2eb67d;margin-left:10px;vertical-align:middle}
1568
- .sm-live-off{color:#e8912d}
1569
- .sm-composer-lock{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 0 2px;font-size:13px;color:#616061}
1570
- .sm-composer-lock[hidden]{display:none}
1571
- .sm-composer-lock input{font:inherit;font-size:13px;padding:5px 8px;border:1px solid #bbb;border-radius:4px;width:130px}
1572
- .sm-composer-lock .sm-lock-go{font:inherit;font-size:13px;padding:5px 10px;border:1px solid #1264a3;border-radius:4px;background:#1264a3;color:#fff;cursor:pointer}
1573
- .sm-composer-lock .sm-err{color:#e01e5a}
1574
- .sm-composer-text:disabled{background:#f8f8f8;color:#888}
1575
-
1576
- .sm-pill{background:#e8f5fa;color:#1264a3;border-radius:3px;padding:0 2px}
1577
- .sm-link{color:#1264a3}
1578
- .sm-emoji-name{color:#616061}
1579
- .sm-code{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;background:#f8f8f8;border:1px solid #ddd;border-radius:3px;padding:1px 3px;color:#e01e5a}
1580
- .sm-pre{font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;line-height:18px;background:#f8f8f8;border:1px solid #ddd;border-radius:4px;padding:8px;margin:4px 0;white-space:pre-wrap;word-break:break-word;color:#1d1c1d}
1581
- .sm-quote{border-left:4px solid #ddd;margin:4px 0;padding:0 0 0 12px;color:#1d1c1d}
1582
- .sm-list{margin:2px 0;padding-left:22px}
1583
- .sm-list li{margin:1px 0}
1584
-
1585
- .sm-blocks{margin:2px 0}
1586
- .sm-block{margin:6px 0}
1587
- .sm-header-block{font-size:18px;font-weight:900;line-height:24px}
1588
- .sm-section-split{display:flex;gap:12px;align-items:flex-start}
1589
- .sm-section-main{flex:1;min-width:0}
1590
- .sm-section-acc{flex:none}
1591
- .sm-fields{display:flex;flex-wrap:wrap;gap:8px 16px;margin-top:6px}
1592
- .sm-field{flex:1 1 40%;min-width:0;font-size:14px;line-height:20px}
1593
- .sm-field-wide{flex-basis:100%}
1594
- .sm-field-title{font-weight:700}
1595
- .sm-context{display:flex;flex-wrap:wrap;align-items:center;gap:8px;font-size:13px;line-height:18px;color:#616061}
1596
- .sm-context .sm-pre,.sm-context .sm-code{font-size:11px}
1597
- .sm-context-img{width:16px;height:16px;border-radius:2px;object-fit:cover}
1598
- .sm-hr{border:0;border-top:1px solid #ddd;margin:10px 0}
1599
- .sm-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
1600
- .sm-btn{display:inline-block;border:1px solid #bbb;border-radius:4px;padding:6px 12px;font-size:14px;font-weight:700;color:#1d1c1d;background:#fff;line-height:16px}
1601
- .sm-btn:hover{text-decoration:none;background:#f8f8f8;color:#1d1c1d}
1602
- .sm-btn-primary{background:#007a5a;border-color:#007a5a;color:#fff}
1603
- .sm-btn-primary:hover{background:#148567;border-color:#148567;color:#fff}
1604
- .sm-btn-danger{background:#e01e5a;border-color:#e01e5a;color:#fff}
1605
- .sm-btn-danger:hover{background:#c31f4c;border-color:#c31f4c;color:#fff}
1606
- .sm-btn-confirm{margin-left:6px;opacity:.7;font-weight:400}
1607
- .sm-select{display:inline-flex;align-items:center;gap:6px;border:1px solid #bbb;border-radius:4px;padding:6px 10px;font-size:14px;color:#1d1c1d;background:#fff;line-height:16px}
1608
- .sm-select-caret{color:#616061;font-size:12px}
1609
- .sm-options{display:flex;flex-direction:column;gap:4px;font-size:14px}
1610
- .sm-acc-img{max-width:88px;max-height:88px;border-radius:4px;display:block}
1611
- .sm-img{max-width:100%;border-radius:6px;display:block;margin-top:4px}
1612
- .sm-img-title{font-size:13px;font-weight:700;color:#454245}
1613
- .sm-label{font-weight:700;font-size:14px;margin-bottom:4px}
1614
- .sm-hint{font-size:12px;color:#616061;margin-top:4px}
1615
- .sm-input{border:1px solid #bbb;border-radius:4px;padding:8px 10px;font-size:14px;min-height:36px;background:#fff}
1616
- .sm-input-multi{min-height:76px}
1617
- .sm-input-ph{color:#8d8d8e}
1618
- .sm-file-block{font-size:14px;color:#454245}
1619
- .sm-video-thumb{max-width:320px;border-radius:6px;display:block}
1620
- .sm-video-title{font-size:14px;font-weight:700;margin-top:4px}
1621
- .sm-unsupported{display:inline-block;background:#f4f4f4;border:1px solid #ddd;border-radius:4px;padding:4px 8px;font-size:12px;color:#616061;font-family:Monaco,Menlo,monospace}
1622
- .sm-rt-section{margin:2px 0}
1623
-
1624
- .sm-atts{margin-top:4px}
1625
- .sm-att{border-left:4px solid #ddd;border-radius:2px;padding:2px 0 2px 12px;margin:6px 0;max-width:600px}
1626
- .sm-att-pretext{font-size:15px;line-height:22px;margin-top:4px}
1627
- .sm-att-author{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:700;color:#454245}
1628
- .sm-att-author-icon{width:16px;height:16px;border-radius:2px}
1629
- .sm-att-title{font-size:15px;font-weight:700;margin:2px 0}
1630
- .sm-att-text{font-size:15px;line-height:21px}
1631
- .sm-att-img{max-width:360px;border-radius:6px;display:block;margin-top:6px}
1632
- .sm-att-thumb{max-width:80px;border-radius:4px;display:block;margin-top:6px}
1633
- .sm-att-footer{display:flex;align-items:center;gap:6px;font-size:12px;color:#616061;margin-top:6px}
1634
- .sm-att-footer-icon{width:14px;height:14px;border-radius:2px}
1635
-
1636
- .sm-files{margin-top:6px;display:flex;flex-direction:column;gap:6px;align-items:flex-start}
1637
- .sm-file-img{max-width:480px;max-height:420px;border-radius:8px;border:1px solid #e8e8e8;display:block}
1638
- .sm-file-card{display:flex;gap:10px;align-items:center;border:1px solid #ddd;border-radius:8px;padding:8px 12px;max-width:420px}
1639
- .sm-file-icon{font-size:20px}
1640
- .sm-file-name{font-weight:700;font-size:14px}
1641
- .sm-file-meta{font-size:12px;color:#616061}
1642
-
1643
- .sm-reactions{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}
1644
- .sm-reaction{display:inline-flex;align-items:center;gap:5px;background:#f0f0f0;border:1px solid #f0f0f0;border-radius:12px;padding:1px 8px;font-size:12px;line-height:18px;color:#454245}
1645
- .sm-reaction:hover{background:#e8f5fa;border-color:#1264a3;color:#1d1c1d}
1646
- .sm-reaction-count{font-weight:700;font-size:12px}
1647
- .sm-file-card:hover{background:#f8f8f8}
1648
-
1649
- .sm-replies{display:inline-flex;align-items:center;gap:8px;margin-top:4px;font-size:13px;font-weight:700;color:#1264a3}
1650
- .sm-replies:hover{color:#0b4c81}
1651
- .sm-replies-time{font-weight:400;color:#616061}
1652
- .sm-empty{color:#616061;font-size:14px;padding:16px 0}
1653
-
1654
- .sm-assist{border:1px solid #e8e8e8;border-radius:8px;padding:10px 12px;margin-bottom:10px;background:#fafafa}
1655
- .sm-assist-title{font-weight:700;font-size:14px}
1656
- .sm-assist-status{font-size:13px;color:#616061;margin-top:2px}
1657
- .sm-assist-status .sm-stream{margin-left:2px}
1658
- .sm-prompts{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
1659
- .sm-prompt{border:1px solid #ddd;border-radius:16px;padding:5px 12px;font-size:13px;background:#fff}
1660
-
1661
- .sm-cards{display:flex;flex-wrap:wrap;gap:12px;margin-bottom:16px}
1662
- .sm-card{border:1px solid #e8e8e8;border-radius:8px;padding:10px 14px;min-width:150px}
1663
- .sm-card-k{font-size:12px;color:#616061;text-transform:uppercase;letter-spacing:.4px}
1664
- .sm-card-v{font-size:16px;font-weight:700;margin-top:2px}
1665
- .sm-h2{font-size:15px;font-weight:900;margin:18px 0 6px}
1666
- .sm-table{border-collapse:collapse;width:100%;max-width:900px;font-size:14px}
1667
- .sm-table th{text-align:left;font-size:12px;color:#616061;font-weight:700;text-transform:uppercase;letter-spacing:.4px;padding:4px 10px 4px 0;border-bottom:1px solid #e8e8e8}
1668
- .sm-table td{padding:6px 10px 6px 0;border-bottom:1px solid #f2f2f2;vertical-align:top}
1669
- .sm-tag{display:inline-block;background:#f0f0f0;color:#454245;border-radius:10px;padding:0 8px;font-size:11px;font-weight:700}
1670
- .sm-muted{color:#616061}
1671
- `;
1672
- function ctxOf(store) {
1673
- return { users: store.users, channels: store.channels, botUserId: store.bot.userId };
1336
+ if(LIVE&&window.EventSource){
1337
+ var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
1338
+ if(chan){
1339
+ var h1=document.querySelector(".sm-top h1"),dot=null;
1340
+ if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="\u25CF live";h1.appendChild(dot)}
1341
+ var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
1342
+ es.addEventListener("change",refresh);
1343
+ es.onopen=function(){if(dot){dot.textContent="\u25CF live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
1344
+ es.onerror=function(){down=true;if(dot){dot.textContent="\u25CF reconnecting";dot.classList.add("sm-live-off")}};
1345
+ }
1674
1346
  }
1675
- function panelWidth(opts) {
1676
- const raw = (opts.panelWidth ?? "").trim();
1677
- return /^\d{1,4}(%|px|vw|rem)$/.test(raw) ? raw : DEFAULT_PANEL_WIDTH;
1347
+ function react(message,name){
1348
+ var u=identity();if(!message||!u||reactionBusy||(GATED&&!cred()))return;
1349
+ var action="add";message.querySelectorAll(".sm-reaction[data-reaction]").forEach(function(button){if(button.dataset.reaction===name&&hasReaction(button,u.id))action="remove"});
1350
+ var err=(reactionDialog&&reactionDialog.open?reactionDialog:message).querySelector(".sm-action-error");if(err){err.hidden=true;err.textContent=""}
1351
+ reactionBusy=true;reactionUi();
1352
+ 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){
1353
+ if(r.status===401||r.status===403){setCred("");lockUi();throw new Error("Sign in to react.")}
1354
+ 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.")})
1355
+ }).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()}})
1356
+ }
1357
+ document.addEventListener("click",function(e){
1358
+ 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}
1359
+ 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}
1360
+ if(e.target.closest(".sm-reaction-close")){closeReactions(true);return}
1361
+ 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()
1362
+ });
1363
+ 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})}
1364
+ document.querySelectorAll(".sm-composer").forEach(function(box){
1365
+ var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
1366
+ function close(){items=[];menu.style.display="none"}
1367
+ function prefix(){var m=/(?:^|\\s)@(\\w*)$/.exec(ta.value.slice(0,ta.selectionStart));return m?m[1]:null}
1368
+ function paint(){menu.querySelectorAll(".sm-mention").forEach(function(el,i){el.className="sm-mention"+(i===active?" sm-mention-on":"")})}
1369
+ function show(){
1370
+ var q=prefix();if(q===null)return close();
1371
+ var low=q.toLowerCase();
1372
+ var list=PEOPLE.filter(function(u){return !low||u.name.toLowerCase().indexOf(low)===0||u.real.toLowerCase().indexOf(low)===0}).slice(0,8);
1373
+ if(!list.length)return close();
1374
+ items=list;active=0;
1375
+ 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("");
1376
+ menu.style.display="block";
1377
+ }
1378
+ 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()}
1379
+ ta.addEventListener("input",show);
1380
+ ta.addEventListener("blur",function(){setTimeout(close,150)});
1381
+ menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
1382
+ ta.addEventListener("keydown",function(e){
1383
+ if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
1384
+ var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
1385
+ 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}}
1386
+ 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}
1387
+ }
1388
+ if(items.length){
1389
+ if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
1390
+ if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
1391
+ if(e.key==="Enter"||e.key==="Tab"){e.preventDefault();pick(active);return}
1392
+ if(e.key==="Escape"){e.preventDefault();e.stopPropagation();close();return}
1393
+ }
1394
+ if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send(box)}
1395
+ });
1396
+ box.querySelector(".sm-composer-send").addEventListener("click",function(){send(box)});
1397
+ });
1398
+ })();`;
1399
+ return `${mentionData(store)}${reactionPicker()}<script>${body}${esc}</script>`;
1678
1400
  }
1679
- function panelParam(opts) {
1680
- const width = (opts.panelWidth ?? "").trim();
1681
- if (!/^\d{1,4}(%|px|vw|rem)$/.test(width) || width === DEFAULT_PANEL_WIDTH)
1682
- return "";
1683
- return width.endsWith("%") ? width.slice(0, -1) : width;
1401
+ function channelView(store, opts, channelId) {
1402
+ const channel = store.channels.get(channelId);
1403
+ const ctx = ctxOf(store);
1404
+ if (!channel)
1405
+ return notFound(store, opts, "Channel not found");
1406
+ const label = channelLabel(store, channel);
1407
+ return shell(store, opts, {
1408
+ title: `${label} \xB7 slack-mock`,
1409
+ header: channelHeader(store, opts, channel),
1410
+ main: channelColumn(store, ctx, opts, channel),
1411
+ active: channel.id,
1412
+ footer: composer(store, opts, channel),
1413
+ script: opts.screenshot ? "" : uiScript(store, opts)
1414
+ });
1684
1415
  }
1685
- function query(opts, over = {}) {
1686
- if (opts.screenshot)
1687
- return "?screenshot";
1416
+ function assistantPanel(store, channelId, ts) {
1417
+ const thread = store.assistantThreads.get(`${channelId}:${ts}`);
1418
+ if (!thread)
1419
+ return "";
1688
1420
  const parts = [];
1689
- if (opts.refreshSec)
1690
- parts.push(`refresh=${opts.refreshSec}`);
1691
- const panel = panelParam(opts);
1692
- if (panel)
1693
- parts.push(`panel=${panel}`);
1694
- if (over.full ?? opts.threadView === "full")
1695
- parts.push("full");
1696
- return parts.length ? `?${parts.join("&")}` : "";
1421
+ if (thread.title)
1422
+ parts.push(`<div class="sm-assist-title">${plainTextToHtml(thread.title)}</div>`);
1423
+ if (thread.status)
1424
+ parts.push(`<div class="sm-assist-status">${plainTextToHtml(thread.status)}<span class="sm-stream">\u2022\u2022\u2022</span></div>`);
1425
+ const prompts = Array.isArray(thread.prompts) ? thread.prompts : [];
1426
+ if (prompts.length) {
1427
+ const chips = prompts.map((p) => {
1428
+ const prompt = typeof p === "object" && p !== null ? p : {};
1429
+ const title = typeof prompt.title === "string" ? prompt.title : "";
1430
+ const message = typeof prompt.message === "string" ? prompt.message : "";
1431
+ return `<span class="sm-prompt" title="${escapeHtml(message)}">${plainTextToHtml(title || message)}</span>`;
1432
+ }).join("");
1433
+ const heading = thread.promptsTitle ? `<div class="sm-assist-status">${plainTextToHtml(thread.promptsTitle)}</div>` : "";
1434
+ parts.push(`${heading}<div class="sm-prompts">${chips}</div>`);
1435
+ }
1436
+ if (!parts.length)
1437
+ return "";
1438
+ return `<div class="sm-assist">${parts.join("")}</div>`;
1697
1439
  }
1698
- function channelHref(channelId, opts) {
1699
- return `/c/${encodeURIComponent(channelId)}${query(opts, { full: false })}`;
1440
+ function threadView(store, opts, channelId, ts) {
1441
+ const channel = store.channels.get(channelId);
1442
+ const ctx = ctxOf(store);
1443
+ if (!channel)
1444
+ return notFound(store, opts, "Channel not found");
1445
+ const parent = store.findMessage(channel.id, ts);
1446
+ if (!parent)
1447
+ return notFound(store, opts, "Message not found");
1448
+ const items = store.replies(channel.id, ts, { limit: 1000 }).items;
1449
+ const replies = items.slice(1);
1450
+ const label = channelLabel(store, channel);
1451
+ 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>`;
1452
+ const body = `${assistantPanel(store, channel.id, ts)}${renderMessage(store, ctx, parent, opts)}${repliesBar}${renderMessageList(store, ctx, replies, opts, { dividers: false })}`;
1453
+ if (opts.screenshot) {
1454
+ const header = topbar(`Thread <span class="sm-muted">\xB7</span> <a href="${channelHref(channel.id, opts)}">${escapeHtml(label)}</a>`, "");
1455
+ return shell(store, opts, {
1456
+ title: `Thread \xB7 ${label}`,
1457
+ header,
1458
+ main: body,
1459
+ active: channel.id
1460
+ });
1461
+ }
1462
+ const close = channelHref(channel.id, opts);
1463
+ const title = `Thread \xB7 ${label}`;
1464
+ if (opts.threadView === "full") {
1465
+ 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)}`);
1466
+ return shell(store, opts, {
1467
+ title,
1468
+ header,
1469
+ main: body,
1470
+ active: channel.id,
1471
+ footer: composer(store, opts, channel, ts),
1472
+ script: uiScript(store, opts, close)
1473
+ });
1474
+ }
1475
+ const expand = threadHref(channel.id, ts, opts, { full: true });
1476
+ 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>`;
1477
+ return shell(store, opts, {
1478
+ title,
1479
+ header: channelHeader(store, opts, channel),
1480
+ main: channelColumn(store, ctx, opts, channel, ts),
1481
+ active: channel.id,
1482
+ panel,
1483
+ footer: composer(store, opts, channel),
1484
+ script: uiScript(store, opts, close)
1485
+ });
1700
1486
  }
1701
- function homeHref(opts) {
1702
- return `/${query(opts, { full: false })}`;
1487
+ function notFound(store, opts, message) {
1488
+ return shell(store, opts, {
1489
+ title: message,
1490
+ header: topbar(escapeHtml(message), ""),
1491
+ main: `<div class="sm-empty">${escapeHtml(message)}</div>`
1492
+ });
1703
1493
  }
1704
- function threadHref(channelId, ts, opts, over = {}) {
1705
- return `/c/${encodeURIComponent(channelId)}/t/${encodeURIComponent(ts)}${query(opts, over)}`;
1494
+ function renderPage(store, view, opts = {}) {
1495
+ switch (view.kind) {
1496
+ case "channel":
1497
+ return channelView(store, opts, view.channel);
1498
+ case "thread":
1499
+ return threadView(store, opts, view.channel, view.ts);
1500
+ default:
1501
+ return indexView(store, opts);
1502
+ }
1706
1503
  }
1707
- function pad(n) {
1708
- return String(n).padStart(2, "0");
1504
+
1505
+ // src/server.ts
1506
+ import { readFileSync as readFileSync2 } from "fs";
1507
+
1508
+ // src/body.ts
1509
+ var JSON_FIELDS = new Set([
1510
+ "blocks",
1511
+ "attachments",
1512
+ "metadata",
1513
+ "files",
1514
+ "view",
1515
+ "prompts",
1516
+ "icons",
1517
+ "user_ids",
1518
+ "types",
1519
+ "chunks",
1520
+ "loading_messages"
1521
+ ]);
1522
+ function coerce(key, value) {
1523
+ if (JSON_FIELDS.has(key)) {
1524
+ try {
1525
+ return JSON.parse(value);
1526
+ } catch {
1527
+ return value;
1528
+ }
1529
+ }
1530
+ if (value === "true")
1531
+ return true;
1532
+ if (value === "false")
1533
+ return false;
1534
+ return value;
1709
1535
  }
1710
- function timeOf(ts) {
1711
- const d = new Date(Number(ts) * 1000);
1712
- if (Number.isNaN(d.getTime()))
1713
- return "";
1714
- return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
1536
+ async function parseArgs(req) {
1537
+ const url = new URL(req.url);
1538
+ const args = {};
1539
+ for (const [k, v] of url.searchParams)
1540
+ args[k] = coerce(k, v);
1541
+ if (req.method !== "POST")
1542
+ return args;
1543
+ const contentType = req.headers.get("content-type") ?? "";
1544
+ if (contentType.includes("application/json")) {
1545
+ const text = await req.text();
1546
+ if (text.trim())
1547
+ Object.assign(args, JSON.parse(text));
1548
+ return args;
1549
+ }
1550
+ if (contentType.includes("multipart/form-data")) {
1551
+ const form = await req.formData();
1552
+ form.forEach((v, k) => {
1553
+ args[k] = typeof v === "string" ? coerce(k, v) : v;
1554
+ });
1555
+ return args;
1556
+ }
1557
+ const text = await req.text();
1558
+ if (!text)
1559
+ return args;
1560
+ for (const [k, v] of new URLSearchParams(text))
1561
+ args[k] = coerce(k, v);
1562
+ return args;
1715
1563
  }
1716
- function dayKey(d) {
1717
- return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
1564
+ function bearerToken(req, args) {
1565
+ const header = req.headers.get("authorization");
1566
+ if (header?.toLowerCase().startsWith("bearer "))
1567
+ return header.slice(7).trim();
1568
+ if (typeof args.token === "string")
1569
+ return args.token;
1570
+ return;
1718
1571
  }
1719
- function dayLabel(ts) {
1720
- const d = new Date(Number(ts) * 1000);
1721
- if (Number.isNaN(d.getTime()))
1722
- return "";
1723
- const now = new Date;
1724
- if (dayKey(d) === dayKey(now))
1725
- return "Today";
1726
- const yesterday = new Date(now.getTime() - 86400000);
1727
- if (dayKey(d) === dayKey(yesterday))
1728
- return "Yesterday";
1729
- return `${MONTHS[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
1572
+ function str2(args, key) {
1573
+ const v = args[key];
1574
+ return typeof v === "string" ? v : v == null ? undefined : String(v);
1730
1575
  }
1731
- function fileSize(bytes) {
1732
- if (bytes < 1024)
1733
- return `${bytes} B`;
1734
- if (bytes < 1024 * 1024)
1735
- return `${(bytes / 1024).toFixed(1)} KB`;
1736
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1576
+ function num(args, key, fallback) {
1577
+ const v = args[key];
1578
+ const n = typeof v === "number" ? v : typeof v === "string" ? Number.parseInt(v, 10) : Number.NaN;
1579
+ return Number.isFinite(n) ? n : fallback;
1737
1580
  }
1738
- function hashIndex(s, buckets) {
1739
- let h = 0;
1740
- for (let i = 0;i < s.length; i++)
1741
- h = h * 31 + s.charCodeAt(i) >>> 0;
1742
- return h % buckets;
1581
+ function bool(args, key) {
1582
+ const v = args[key];
1583
+ if (typeof v === "boolean")
1584
+ return v;
1585
+ if (v === "true" || v === "1" || v === 1)
1586
+ return true;
1587
+ if (v === "false" || v === "0" || v === 0)
1588
+ return false;
1589
+ return;
1743
1590
  }
1744
- function initials(name) {
1745
- const words = name.replace(/[^\p{L}\p{N} ]/gu, " ").trim().split(/\s+/);
1746
- const letters = words.slice(0, 2).map((w) => w[0] ?? "").join("");
1747
- return (letters || name.slice(0, 2) || "?").toUpperCase();
1591
+
1592
+ // src/ids.ts
1593
+ var ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
1594
+ function slackId(prefix, length = 8) {
1595
+ let out = prefix;
1596
+ for (let i = 0;i < length; i++)
1597
+ out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];
1598
+ return out;
1748
1599
  }
1749
- function channelLabel(store, c) {
1750
- if (!c.is_im)
1751
- return `#${c.name}`;
1752
- const peer = c.user ? store.users.get(c.user) : undefined;
1753
- return peer ? displayName(peer) : c.name;
1600
+ var lastMicros = 0;
1601
+ function nextTs() {
1602
+ let micros = Date.now() * 1000;
1603
+ if (micros <= lastMicros)
1604
+ micros = lastMicros + 1;
1605
+ lastMicros = micros;
1606
+ const seconds = Math.floor(micros / 1e6);
1607
+ const fraction = (micros % 1e6).toString().padStart(6, "0");
1608
+ return `${seconds}.${fraction}`;
1754
1609
  }
1755
- function channelIcon(c) {
1756
- if (c.is_im)
1757
- return "@";
1758
- if (c.is_private)
1759
- return "\uD83D\uDD12";
1760
- return "#";
1610
+ function nowUnix() {
1611
+ return Math.floor(Date.now() / 1000);
1761
1612
  }
1762
- function channelKind(c) {
1763
- if (c.is_im)
1764
- return "DM";
1765
- if (c.is_private)
1766
- return "private";
1767
- return "public";
1613
+
1614
+ // src/store.ts
1615
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
1616
+ import { dirname } from "path";
1617
+ class SlackApiError2 extends Error {
1618
+ code;
1619
+ extra;
1620
+ constructor(code, extra = {}) {
1621
+ super(code);
1622
+ this.code = code;
1623
+ this.extra = extra;
1624
+ }
1768
1625
  }
1769
- function authorName(store, m) {
1770
- if (m.username)
1771
- return m.username;
1772
- const user = m.user ? store.users.get(m.user) : undefined;
1773
- if (user)
1774
- return user.real_name || user.name;
1775
- return m.bot_profile?.name ?? m.user ?? "unknown";
1626
+ function parseJournal(text, source = "journal") {
1627
+ const entries = [];
1628
+ let line = 0;
1629
+ for (const raw of text.split(`
1630
+ `)) {
1631
+ line += 1;
1632
+ if (!raw.trim())
1633
+ continue;
1634
+ try {
1635
+ entries.push({ line, change: JSON.parse(raw) });
1636
+ } catch (e) {
1637
+ console.warn(`[slack-mock] skipping corrupt journal line ${line} in ${source}: ${e instanceof Error ? e.message : e}`);
1638
+ }
1639
+ }
1640
+ return entries;
1776
1641
  }
1777
- function avatarHtml(m, name) {
1778
- const emojiName = m.icons?.emoji;
1779
- if (emojiName) {
1780
- const char = emojiChar(emojiName) ?? emojiName.replace(/:/g, "");
1781
- return `<div class="sm-avatar sm-avatar-emoji">${escapeHtml(char)}</div>`;
1642
+
1643
+ class Store2 {
1644
+ team;
1645
+ app;
1646
+ bot;
1647
+ users = new Map;
1648
+ channels = new Map;
1649
+ messages = new Map;
1650
+ files = new Map;
1651
+ views = new Map;
1652
+ ephemerals = [];
1653
+ apiCalls = [];
1654
+ assistantThreads = new Map;
1655
+ listeners = new Set;
1656
+ dataFile;
1657
+ replaying = false;
1658
+ constructor(opts = {}) {
1659
+ this.team = {
1660
+ id: opts.teamId ?? "T0MOCK0000",
1661
+ name: opts.teamName ?? "Mock Workspace",
1662
+ domain: opts.teamDomain ?? "mock"
1663
+ };
1664
+ this.app = { id: opts.appId ?? "A0MOCK0000", name: opts.appName ?? "mock-bot" };
1665
+ this.bot = {
1666
+ userId: opts.botUserId ?? "U0BOT00000",
1667
+ botId: opts.botId ?? "B0BOT00000",
1668
+ token: opts.botToken ?? "xoxb-mock-bot-token",
1669
+ appToken: opts.appToken ?? "xapp-mock-app-token",
1670
+ userToken: opts.userToken
1671
+ };
1672
+ this.dataFile = opts.dataFile;
1673
+ if (this.dataFile && existsSync(this.dataFile))
1674
+ this.replay(parseJournal(readFileSync(this.dataFile, "utf8"), this.dataFile).map((e) => e.change));
1675
+ if (opts.replay)
1676
+ this.replay(opts.replay);
1677
+ if (!this.users.has(this.bot.userId)) {
1678
+ this.addUser({
1679
+ id: this.bot.userId,
1680
+ name: this.app.name,
1681
+ real_name: this.app.name,
1682
+ is_bot: true
1683
+ });
1684
+ }
1685
+ }
1686
+ onChange(listener) {
1687
+ this.listeners.add(listener);
1688
+ return () => this.listeners.delete(listener);
1689
+ }
1690
+ onChangeEmit(change) {
1691
+ this.emit(change);
1692
+ }
1693
+ emit(change) {
1694
+ if (this.dataFile && !this.replaying && change.kind !== "api.call") {
1695
+ appendFileSync(this.dataFile, `${JSON.stringify({ at: new Date().toISOString(), ...stripBytes(change) })}
1696
+ `);
1697
+ }
1698
+ for (const l of this.listeners)
1699
+ l(change);
1700
+ }
1701
+ replay(changes) {
1702
+ this.replaying = true;
1703
+ try {
1704
+ for (const change of changes)
1705
+ this.applyReplayed(change);
1706
+ } finally {
1707
+ this.replaying = false;
1708
+ }
1709
+ }
1710
+ applyReplayed(change) {
1711
+ switch (change.kind) {
1712
+ case "user.add":
1713
+ this.users.set(change.user.id, change.user);
1714
+ break;
1715
+ case "channel.add":
1716
+ case "channel.update":
1717
+ this.channels.set(change.channel.id, change.channel);
1718
+ break;
1719
+ case "member.join": {
1720
+ const c = this.channels.get(change.channel.id);
1721
+ if (c && !c.members.includes(change.user))
1722
+ c.members.push(change.user);
1723
+ break;
1724
+ }
1725
+ case "message.add":
1726
+ this.insertMessage(change.message);
1727
+ break;
1728
+ case "message.update":
1729
+ case "reaction.add":
1730
+ case "reaction.remove": {
1731
+ const list = this.messages.get(change.message.channel);
1732
+ const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
1733
+ if (list && i >= 0)
1734
+ list[i] = change.message;
1735
+ break;
1736
+ }
1737
+ case "message.delete": {
1738
+ const list = this.messages.get(change.message.channel);
1739
+ const i = list?.findIndex((m) => m.ts === change.message.ts) ?? -1;
1740
+ if (list && i >= 0)
1741
+ list.splice(i, 1);
1742
+ break;
1743
+ }
1744
+ case "file.add":
1745
+ this.files.set(change.file.id, change.file);
1746
+ break;
1747
+ default:
1748
+ break;
1749
+ }
1750
+ }
1751
+ addUser(input) {
1752
+ const id = input.id ?? slackId("U");
1753
+ const realName = input.real_name ?? input.name;
1754
+ const user = {
1755
+ id,
1756
+ team_id: this.team.id,
1757
+ name: input.name,
1758
+ real_name: realName,
1759
+ deleted: false,
1760
+ is_bot: input.is_bot ?? false,
1761
+ is_admin: input.is_admin ?? false,
1762
+ is_app_user: false,
1763
+ tz: input.tz ?? "UTC",
1764
+ profile: {
1765
+ real_name: realName,
1766
+ display_name: input.name,
1767
+ real_name_normalized: realName,
1768
+ display_name_normalized: input.name,
1769
+ email: input.email,
1770
+ title: input.title,
1771
+ status_text: input.status,
1772
+ team: this.team.id
1773
+ }
1774
+ };
1775
+ this.users.set(id, user);
1776
+ this.emit({ kind: "user.add", user });
1777
+ return user;
1778
+ }
1779
+ user(id) {
1780
+ const u = this.users.get(id);
1781
+ if (!u)
1782
+ throw new SlackApiError2("user_not_found");
1783
+ return u;
1784
+ }
1785
+ userByEmail(email) {
1786
+ for (const u of this.users.values())
1787
+ if (u.profile.email === email)
1788
+ return u;
1789
+ return;
1790
+ }
1791
+ isBotUser(userId) {
1792
+ return userId === this.bot.userId;
1793
+ }
1794
+ addChannel(input) {
1795
+ const name = input.name.replace(/^#/, "");
1796
+ for (const c of this.channels.values()) {
1797
+ if (c.name === name && !c.is_im)
1798
+ throw new SlackApiError2("name_taken");
1799
+ }
1800
+ const id = input.id ?? slackId(input.is_private ? "G" : "C");
1801
+ const creator = input.creator ?? this.bot.userId;
1802
+ const members = [...new Set([creator, ...input.members ?? []])];
1803
+ const channel = {
1804
+ id,
1805
+ name,
1806
+ is_channel: !input.is_private,
1807
+ is_group: !!input.is_private,
1808
+ is_im: false,
1809
+ is_mpim: false,
1810
+ is_private: !!input.is_private,
1811
+ is_archived: false,
1812
+ is_general: name === "general",
1813
+ created: nowUnix(),
1814
+ creator,
1815
+ topic: { value: input.topic ?? "", creator, last_set: 0 },
1816
+ purpose: { value: input.purpose ?? "", creator, last_set: 0 },
1817
+ members
1818
+ };
1819
+ this.channels.set(id, channel);
1820
+ this.messages.set(id, []);
1821
+ this.emit({ kind: "channel.add", channel });
1822
+ return channel;
1823
+ }
1824
+ openDm(userId) {
1825
+ this.user(userId);
1826
+ for (const c of this.channels.values())
1827
+ if (c.is_im && c.user === userId)
1828
+ return c;
1829
+ const id = slackId("D");
1830
+ const channel = {
1831
+ id,
1832
+ name: id,
1833
+ is_channel: false,
1834
+ is_group: false,
1835
+ is_im: true,
1836
+ is_mpim: false,
1837
+ is_private: true,
1838
+ is_archived: false,
1839
+ is_general: false,
1840
+ created: nowUnix(),
1841
+ creator: userId,
1842
+ user: userId,
1843
+ topic: { value: "", creator: "", last_set: 0 },
1844
+ purpose: { value: "", creator: "", last_set: 0 },
1845
+ members: [userId, this.bot.userId]
1846
+ };
1847
+ this.channels.set(id, channel);
1848
+ this.messages.set(id, []);
1849
+ this.emit({ kind: "channel.add", channel });
1850
+ return channel;
1851
+ }
1852
+ channel(id) {
1853
+ const c = this.channels.get(id);
1854
+ if (!c)
1855
+ throw new SlackApiError2("channel_not_found");
1856
+ return c;
1857
+ }
1858
+ channelByName(name) {
1859
+ const n = name.replace(/^#/, "");
1860
+ for (const c of this.channels.values())
1861
+ if (c.name === n)
1862
+ return c;
1863
+ return;
1864
+ }
1865
+ channelType(c) {
1866
+ if (c.is_im)
1867
+ return "im";
1868
+ if (c.is_mpim)
1869
+ return "mpim";
1870
+ if (c.is_private)
1871
+ return "group";
1872
+ return "channel";
1873
+ }
1874
+ join(channelId, userId, inviter) {
1875
+ const channel = this.channel(channelId);
1876
+ if (channel.is_archived)
1877
+ throw new SlackApiError2("is_archived");
1878
+ if (channel.members.includes(userId))
1879
+ return { alreadyMember: true };
1880
+ channel.members.push(userId);
1881
+ this.emit({ kind: "member.join", channel, user: userId, inviter });
1882
+ return { alreadyMember: false };
1782
1883
  }
1783
- const imageUrl = m.icons?.image_72 ?? m.icons?.image_48 ?? m.icons?.image_64;
1784
- if (imageUrl && /^(https?:\/\/|\/)/.test(imageUrl)) {
1785
- return `<div class="sm-avatar"><img src="${escapeHtml(imageUrl)}" alt=""></div>`;
1884
+ archive(channelId) {
1885
+ const channel = this.channel(channelId);
1886
+ if (channel.is_archived)
1887
+ throw new SlackApiError2("already_archived");
1888
+ if (channel.is_general)
1889
+ throw new SlackApiError2("cant_archive_general");
1890
+ channel.is_archived = true;
1891
+ this.emit({ kind: "channel.update", channel });
1786
1892
  }
1787
- const seed = m.user ?? m.bot_id ?? name;
1788
- const color = AVATAR_COLORS[hashIndex(seed, AVATAR_COLORS.length)];
1789
- return `<div class="sm-avatar" style="background:${color}">${escapeHtml(initials(name))}</div>`;
1790
- }
1791
- function reactionsHtml(store, m) {
1792
- if (!m.reactions?.length)
1793
- return "";
1794
- const chips = m.reactions.map((r) => {
1795
- const who = r.users.map((id) => {
1796
- const user = store.users.get(id);
1797
- return user ? displayName(user) : id;
1798
- }).join(", ");
1799
- const char = emojiChar(r.name) ?? `:${r.name}:`;
1800
- return `<span class="sm-reaction" title="${escapeHtml(who)}">${escapeHtml(char)}<span class="sm-reaction-count">${r.count}</span></span>`;
1801
- });
1802
- return `<div class="sm-reactions">${chips.join("")}</div>`;
1803
- }
1804
- function fileUrl(f, token) {
1805
- if (!f.url_private)
1806
- return "";
1807
- return escapeHtml(`${f.url_private}${f.url_private.includes("?") ? "&" : "?"}t=${token}`);
1808
- }
1809
- function filesHtml(files, token) {
1810
- if (!files?.length)
1811
- return "";
1812
- const cards = files.map((f) => {
1813
- if (f.mimetype?.startsWith("image/") && f.url_private) {
1814
- return `<img class="sm-file-img" src="${fileUrl(f, token)}" alt="${escapeHtml(f.title || f.name)}">`;
1893
+ insertMessage(message) {
1894
+ const list = this.messages.get(message.channel) ?? [];
1895
+ this.messages.set(message.channel, list);
1896
+ let i = list.length;
1897
+ while (i > 0 && Number(list[i - 1].ts) > Number(message.ts))
1898
+ i--;
1899
+ list.splice(i, 0, message);
1900
+ if (message.thread_ts && message.thread_ts !== message.ts) {
1901
+ const parent = this.findMessage(message.channel, message.thread_ts);
1902
+ if (parent) {
1903
+ parent.reply_count = (parent.reply_count ?? 0) + 1;
1904
+ const users = new Set(parent.reply_users ?? []);
1905
+ if (message.user)
1906
+ users.add(message.user);
1907
+ parent.reply_users = [...users];
1908
+ parent.reply_users_count = users.size;
1909
+ parent.latest_reply = message.ts;
1910
+ if (parent.user)
1911
+ message.parent_user_id = parent.user;
1912
+ }
1815
1913
  }
1816
- const href = fileUrl(f, token);
1817
- const name = escapeHtml(f.title || f.name);
1818
- const meta = `${escapeHtml(f.pretty_type || f.filetype || "File")} \xB7 ${fileSize(f.size ?? 0)}`;
1819
- const label = href ? `<a href="${href}">${name}</a>` : name;
1820
- 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>`;
1821
- });
1822
- return `<div class="sm-files">${cards.join("")}</div>`;
1823
- }
1824
- function renderMessage(store, ctx, m, opts, flags = {}) {
1825
- const name = authorName(store, m);
1826
- const isApp = Boolean(m.bot_id);
1827
- const blocks = Array.isArray(m.blocks) && m.blocks.length ? m.blocks : undefined;
1828
- const body = [];
1829
- if (m.streaming_state !== undefined) {
1830
- if (m.text)
1831
- body.push(`<div class="sm-text">${mrkdwnToHtml(markdownToMrkdwn(m.text), ctx)}</div>`);
1832
- if (blocks)
1833
- body.push(renderBlocks(blocks, ctx));
1834
- } else if (blocks)
1835
- body.push(renderBlocks(blocks, ctx));
1836
- else if (m.text)
1837
- body.push(`<div class="sm-text">${mrkdwnToHtml(m.text, ctx)}</div>`);
1838
- if (m.edited)
1839
- body.push(`<div class="sm-edited">(edited)</div>`);
1840
- if (m.attachments?.length)
1841
- body.push(renderAttachments(m.attachments, ctx));
1842
- body.push(filesHtml(m.files, store.bot.token));
1843
- body.push(reactionsHtml(store, m));
1844
- if (flags.ephemeral)
1845
- body.push(`<div class="sm-eph-note">Only visible to you</div>`);
1846
- if (flags.threadLink && m.reply_count) {
1847
- const count = `${m.reply_count} ${m.reply_count === 1 ? "reply" : "replies"}`;
1848
- const last = m.latest_reply ? `<span class="sm-replies-time">Last reply ${timeOf(m.latest_reply)}</span>` : "";
1849
- body.push(`<a class="sm-replies" href="${threadHref(m.channel, m.thread_ts ?? m.ts, opts)}">${count}${last}</a>`);
1850
1914
  }
1851
- const streaming = m.streaming_state === "in_progress" ? `<span class="sm-stream" title="streaming">\u2022\u2022\u2022</span>` : "";
1852
- const open = flags.openTs && flags.openTs === m.ts ? " sm-msg-open" : "";
1853
- return `<div class="sm-msg${flags.ephemeral ? " sm-msg-eph" : ""}${open}" data-ts="${escapeHtml(m.ts)}">${avatarHtml(m, name)}<div class="sm-msg-body"><div class="sm-msg-head"><span class="sm-name">${escapeHtml(name)}</span>${isApp ? `<span class="sm-badge">APP</span>` : ""}<span class="sm-time">${timeOf(m.ts)}</span>${streaming}</div>${body.join("")}</div></div>`;
1854
- }
1855
- function markdownToMrkdwn(text) {
1856
- 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("");
1857
- }
1858
- function renderMessageList(store, ctx, messages, opts, flags = {}) {
1859
- const out = [];
1860
- let day = "";
1861
- for (const m of messages) {
1862
- const label = flags.dividers === false ? "" : dayLabel(m.ts);
1863
- if (label && label !== day) {
1864
- day = label;
1865
- out.push(`<div class="sm-daydiv"><span>${escapeHtml(label)}</span></div>`);
1915
+ findMessage(channelId, ts) {
1916
+ return this.messages.get(channelId)?.find((m) => m.ts === ts);
1917
+ }
1918
+ findAnyMessage(channelId, ts) {
1919
+ return this.findMessage(channelId, ts) ?? this.ephemerals.find((m) => m.channel === channelId && m.ts === ts);
1920
+ }
1921
+ updateEphemeral(channelId, ts, patch) {
1922
+ const m = this.ephemerals.find((x) => x.channel === channelId && x.ts === ts);
1923
+ if (!m)
1924
+ throw new SlackApiError2("message_not_found");
1925
+ Object.assign(m, patch);
1926
+ return m;
1927
+ }
1928
+ deleteEphemeral(channelId, ts) {
1929
+ const i = this.ephemerals.findIndex((x) => x.channel === channelId && x.ts === ts);
1930
+ if (i < 0)
1931
+ throw new SlackApiError2("message_not_found");
1932
+ this.ephemerals.splice(i, 1);
1933
+ }
1934
+ message(channelId, ts) {
1935
+ const m = this.findMessage(channelId, ts);
1936
+ if (!m)
1937
+ throw new SlackApiError2("message_not_found");
1938
+ return m;
1939
+ }
1940
+ addMessage(input) {
1941
+ const channel = this.channel(input.channel);
1942
+ if (channel.is_archived)
1943
+ throw new SlackApiError2("is_archived");
1944
+ if (input.thread_ts && !this.findMessage(input.channel, input.thread_ts)) {
1945
+ throw new SlackApiError2("thread_not_found");
1946
+ }
1947
+ const message = {
1948
+ type: "message",
1949
+ team: this.team.id,
1950
+ ts: input.ts ?? nextTs(),
1951
+ ...input
1952
+ };
1953
+ if (message.ephemeral_user)
1954
+ this.ephemerals.push(message);
1955
+ else
1956
+ this.insertMessage(message);
1957
+ this.emit({ kind: "message.add", message });
1958
+ return message;
1959
+ }
1960
+ updateMessage(channelId, ts, patch, editor, opts = {}) {
1961
+ const message = this.message(channelId, ts);
1962
+ const previous = structuredClone(message);
1963
+ Object.assign(message, patch, opts.markEdited === false ? {} : { edited: { user: editor, ts: nextTs() } });
1964
+ this.emit({ kind: "message.update", message, previous });
1965
+ return message;
1966
+ }
1967
+ deleteMessage(channelId, ts) {
1968
+ const list = this.messages.get(channelId);
1969
+ const i = list?.findIndex((m) => m.ts === ts) ?? -1;
1970
+ if (!list || i < 0)
1971
+ throw new SlackApiError2("message_not_found");
1972
+ const [message] = list.splice(i, 1);
1973
+ if (message.thread_ts && message.thread_ts !== ts) {
1974
+ const parent = this.findMessage(channelId, message.thread_ts);
1975
+ if (parent?.reply_count)
1976
+ parent.reply_count -= 1;
1977
+ }
1978
+ this.emit({ kind: "message.delete", message });
1979
+ return message;
1980
+ }
1981
+ addReaction(channelId, ts, name, userId) {
1982
+ const message = this.message(channelId, ts);
1983
+ message.reactions ??= [];
1984
+ let reaction = message.reactions.find((r) => r.name === name);
1985
+ if (reaction?.users.includes(userId))
1986
+ throw new SlackApiError2("already_reacted");
1987
+ if (!reaction) {
1988
+ reaction = { name, users: [], count: 0 };
1989
+ message.reactions.push(reaction);
1990
+ }
1991
+ reaction.users.push(userId);
1992
+ reaction.count = reaction.users.length;
1993
+ this.emit({ kind: "reaction.add", message, name, user: userId });
1994
+ return message;
1995
+ }
1996
+ removeReaction(channelId, ts, name, userId) {
1997
+ const message = this.message(channelId, ts);
1998
+ const reaction = message.reactions?.find((r) => r.name === name);
1999
+ if (!reaction?.users.includes(userId))
2000
+ throw new SlackApiError2("no_reaction");
2001
+ reaction.users = reaction.users.filter((u) => u !== userId);
2002
+ reaction.count = reaction.users.length;
2003
+ message.reactions = message.reactions.filter((r) => r.count > 0);
2004
+ if (message.reactions.length === 0)
2005
+ message.reactions = undefined;
2006
+ this.emit({ kind: "reaction.remove", message, name, user: userId });
2007
+ return message;
2008
+ }
2009
+ history(channelId, q = {}) {
2010
+ this.channel(channelId);
2011
+ const all = (this.messages.get(channelId) ?? []).filter((m) => !m.thread_ts || m.thread_ts === m.ts || m.subtype === "thread_broadcast");
2012
+ return paginate(all, q);
2013
+ }
2014
+ replies(channelId, threadTs, q = {}) {
2015
+ const parent = this.message(channelId, threadTs);
2016
+ const all = [
2017
+ parent,
2018
+ ...(this.messages.get(channelId) ?? []).filter((m) => m.thread_ts === threadTs && m.ts !== threadTs)
2019
+ ];
2020
+ return paginate(all, q);
2021
+ }
2022
+ addFile(input) {
2023
+ const id = input.id ?? slackId("F");
2024
+ const ext = input.name.includes(".") ? input.name.split(".").pop().toLowerCase() : "";
2025
+ const mimetype = input.mimetype ?? guessMime(ext);
2026
+ const now = nowUnix();
2027
+ const file = {
2028
+ id,
2029
+ created: now,
2030
+ timestamp: now,
2031
+ name: input.name,
2032
+ title: input.title ?? input.name,
2033
+ mimetype,
2034
+ filetype: ext || "binary",
2035
+ pretty_type: ext ? ext.toUpperCase() : "Binary",
2036
+ user: input.user,
2037
+ size: input.bytes.byteLength,
2038
+ mode: "hosted",
2039
+ is_external: false,
2040
+ is_public: false,
2041
+ url_private: `${input.baseUrl}/files-pri/${this.team.id}-${id}/${encodeURIComponent(input.name)}`,
2042
+ url_private_download: `${input.baseUrl}/files-pri/${this.team.id}-${id}/download/${encodeURIComponent(input.name)}`,
2043
+ permalink: `${input.baseUrl}/files/${input.user}/${id}/${encodeURIComponent(input.name)}`,
2044
+ channels: [],
2045
+ bytes: input.bytes
2046
+ };
2047
+ if (mimetype.startsWith("image/")) {
2048
+ const thumbs = file;
2049
+ for (const size of [64, 80, 160, 360, 480])
2050
+ thumbs[`thumb_${size}`] = file.url_private;
2051
+ }
2052
+ this.files.set(id, file);
2053
+ this.emit({ kind: "file.add", file });
2054
+ return file;
2055
+ }
2056
+ file(id) {
2057
+ const f = this.files.get(id);
2058
+ if (!f)
2059
+ throw new SlackApiError2("file_not_found");
2060
+ return f;
2061
+ }
2062
+ openView(view) {
2063
+ const id = view.id ?? slackId("V");
2064
+ const full = {
2065
+ ...view,
2066
+ id,
2067
+ team_id: this.team.id,
2068
+ app_id: this.app.id,
2069
+ bot_id: this.bot.botId,
2070
+ hash: `${nowUnix()}.${slackId("", 6).toLowerCase()}`,
2071
+ root_view_id: id
2072
+ };
2073
+ this.views.set(id, full);
2074
+ this.emit({ kind: "view.open", view: full });
2075
+ return full;
2076
+ }
2077
+ recordApiCall(call) {
2078
+ this.apiCalls.push(call);
2079
+ this.emit({ kind: "api.call", call });
2080
+ }
2081
+ assistantThread(channel, threadTs) {
2082
+ const key = `${channel}:${threadTs}`;
2083
+ let t = this.assistantThreads.get(key);
2084
+ if (!t) {
2085
+ t = {};
2086
+ this.assistantThreads.set(key, t);
1866
2087
  }
1867
- out.push(renderMessage(store, ctx, m, opts, { ...flags, ephemeral: m._ephemeral === true }));
2088
+ return t;
1868
2089
  }
1869
- return out.join("");
1870
- }
1871
- function sidebar(store, opts, active) {
1872
- const channels = [...store.channels.values()].sort((a, b) => channelLabel(store, a).localeCompare(channelLabel(store, b)));
1873
- 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("");
1874
- return `<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>`;
1875
2090
  }
1876
- function shell(store, opts, parts) {
1877
- const refresh = opts.refreshSec && !opts.screenshot ? `<meta http-equiv="refresh" content="${Math.max(1, Math.floor(opts.refreshSec))}">` : "";
1878
- const style = opts.screenshot ? "" : ` style="--sm-panel-w:${panelWidth(opts)}"`;
1879
- const head = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(parts.title)}</title>${refresh}<style>${CSS}</style></head>`;
1880
- if (opts.screenshot) {
1881
- return `${head}<body><div class="sm-shot">${parts.header}<div class="sm-page">${parts.main}</div></div></body></html>`;
1882
- }
1883
- const app = `sm-app${parts.panel ? " sm-app-thread" : ""}`;
1884
- const handle = parts.panel ? `<div class="sm-resize" title="Drag to resize, double-click to reset"></div>` : "";
1885
- 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>`;
2091
+ function paginate(all, q) {
2092
+ let items = all;
2093
+ if (q.oldest)
2094
+ items = items.filter((m) => q.inclusive ? Number(m.ts) >= Number(q.oldest) : Number(m.ts) > Number(q.oldest));
2095
+ if (q.latest)
2096
+ items = items.filter((m) => q.inclusive ? Number(m.ts) <= Number(q.latest) : Number(m.ts) < Number(q.latest));
2097
+ const start = q.cursor ? Number.parseInt(Buffer.from(q.cursor, "base64").toString("utf8").replace("offset:", ""), 10) || 0 : 0;
2098
+ const limit = Math.max(1, Math.min(q.limit ?? 100, 1000));
2099
+ const page = items.slice(start, start + limit);
2100
+ const has_more = start + limit < items.length;
2101
+ return {
2102
+ items: page,
2103
+ has_more,
2104
+ next_cursor: has_more ? Buffer.from(`offset:${start + limit}`).toString("base64") : ""
2105
+ };
1886
2106
  }
1887
- function topbar(title, sub, back, actions) {
1888
- const backLink = back ? `<a class="sm-back" href="${back.href}">${escapeHtml(back.label)}</a>` : "";
1889
- const right = actions ? `<div class="sm-top-actions">${actions}</div>` : "";
1890
- return `<div class="sm-top">${backLink}<h1>${title}</h1>${sub ? `<div class="sm-sub">${sub}</div>` : ""}${right}</div>`;
2107
+ function guessMime(ext) {
2108
+ const map = {
2109
+ png: "image/png",
2110
+ jpg: "image/jpeg",
2111
+ jpeg: "image/jpeg",
2112
+ gif: "image/gif",
2113
+ webp: "image/webp",
2114
+ svg: "image/svg+xml",
2115
+ txt: "text/plain",
2116
+ md: "text/markdown",
2117
+ log: "text/plain",
2118
+ json: "application/json",
2119
+ csv: "text/csv",
2120
+ pdf: "application/pdf",
2121
+ html: "text/html",
2122
+ zip: "application/zip"
2123
+ };
2124
+ return map[ext] ?? "application/octet-stream";
1891
2125
  }
1892
- function indexView(store, opts) {
1893
- const cards = [
1894
- ["Workspace", escapeHtml(store.team.name)],
1895
- ["Team id", escapeHtml(store.team.id)],
1896
- ["Bot user", escapeHtml(`${store.app.name} (${store.bot.userId})`)],
1897
- ["Connections", String(opts.connections ?? 0)]
1898
- ].map(([k, v]) => `<div class="sm-card"><div class="sm-card-k">${k}</div><div class="sm-card-v">${v}</div></div>`).join("");
1899
- const channels = [...store.channels.values()];
1900
- const channelRows = channels.map((c) => {
1901
- const count = store.messages.get(c.id)?.length ?? 0;
1902
- return `<tr><td><a href="${channelHref(c.id, opts)}">${escapeHtml(channelIcon(c))} ${escapeHtml(c.is_im ? channelLabel(store, c) : c.name)}</a></td><td><span class="sm-tag">${channelKind(c)}</span></td><td class="sm-muted">${c.id}</td><td>${count}</td></tr>`;
1903
- }).join("");
1904
- const userRows = [...store.users.values()].map((u) => `<tr><td>${escapeHtml(u.name)}</td><td>${escapeHtml(u.real_name)}</td><td class="sm-muted">${escapeHtml(u.profile.title ?? "")}</td><td class="sm-muted">${escapeHtml(u.profile.email ?? "")}</td><td class="sm-muted">${u.id}</td><td>${u.is_bot ? `<span class="sm-tag">bot</span>` : ""}</td></tr>`).join("");
1905
- const main = `<div class="sm-cards">${cards}</div>
1906
- <div class="sm-h2">Channels</div>
1907
- ${channels.length ? `<table class="sm-table"><tr><th>Name</th><th>Type</th><th>Id</th><th>Messages</th></tr>${channelRows}</table>` : `<div class="sm-empty">No channels yet</div>`}
1908
- <div class="sm-h2">Users</div>
1909
- <table class="sm-table"><tr><th>Name</th><th>Real name</th><th>Title</th><th>Email</th><th>Id</th><th></th></tr>${userRows}</table>`;
1910
- return shell(store, opts, {
1911
- title: `${store.team.name} \xB7 slack-mock`,
1912
- header: topbar(escapeHtml(store.team.name), "slack-mock workspace"),
1913
- main
1914
- });
2126
+ function wireMessage(m) {
2127
+ const { ephemeral_user: _e, ...rest } = m;
2128
+ if (rest.files)
2129
+ rest.files = rest.files.map(wireFile);
2130
+ return rest;
1915
2131
  }
1916
- function channelMessages(store, channel) {
1917
- const history = store.history(channel.id, { limit: 1000 }).items;
1918
- const ephemerals = store.ephemerals.filter((e) => e.channel === channel.id).map((e) => ({ ...e, _ephemeral: true }));
1919
- return [...history, ...ephemerals].sort((a, b) => Number(a.ts) - Number(b.ts));
2132
+ function wireFile(f) {
2133
+ const { bytes: _b, ...rest } = f;
2134
+ return rest;
1920
2135
  }
1921
- function channelColumn(store, ctx, opts, channel, openTs) {
1922
- const messages = channelMessages(store, channel);
1923
- if (!messages.length)
1924
- return `<div class="sm-empty">No messages yet</div>`;
1925
- return renderMessageList(store, ctx, messages, opts, {
1926
- threadLink: true,
1927
- dividers: true,
1928
- openTs
1929
- });
2136
+ function stripBytes(change) {
2137
+ if (change.kind === "file.add")
2138
+ return { ...change, file: wireFile(change.file) };
2139
+ if ("message" in change && change.message.files) {
2140
+ return {
2141
+ ...change,
2142
+ message: { ...change.message, files: change.message.files.map(wireFile) }
2143
+ };
2144
+ }
2145
+ return change;
1930
2146
  }
1931
- function channelHeader(store, opts, channel) {
1932
- const sub = [channel.topic.value, channel.purpose.value].filter(Boolean).join(" \xB7 ");
1933
- const back = opts.screenshot ? undefined : { href: homeHref(opts), label: "\u2190 Workspace" };
1934
- return topbar(escapeHtml(channelLabel(store, channel)), escapeHtml(sub), back);
2147
+ function ensureDir(file) {
2148
+ mkdirSync(dirname(file), { recursive: true });
1935
2149
  }
1936
- function humanUsers(store) {
1937
- return [...store.users.values()].filter((u) => !u.is_bot && !u.deleted);
2150
+
2151
+ // src/events.ts
2152
+ var VERIFICATION_TOKEN = "mock-verification-token";
2153
+ function eventCallback(store, event) {
2154
+ return {
2155
+ token: VERIFICATION_TOKEN,
2156
+ team_id: store.team.id,
2157
+ context_team_id: store.team.id,
2158
+ context_enterprise_id: null,
2159
+ api_app_id: store.app.id,
2160
+ event,
2161
+ type: "event_callback",
2162
+ event_id: slackId("Ev", 9),
2163
+ event_time: nowUnix(),
2164
+ authorizations: [
2165
+ {
2166
+ enterprise_id: null,
2167
+ team_id: store.team.id,
2168
+ user_id: store.bot.userId,
2169
+ is_bot: true,
2170
+ is_enterprise_install: false
2171
+ }
2172
+ ],
2173
+ is_ext_shared_channel: false,
2174
+ event_context: Buffer.from(`${store.team.id}:${store.app.id}:${event.channel ?? ""}`).toString("base64")
2175
+ };
1938
2176
  }
1939
- function composer(store, opts, channel, threadTs) {
1940
- if (opts.screenshot)
1941
- return "";
1942
- const users = humanUsers(store);
1943
- if (!users.length)
1944
- return "";
1945
- const options = users.map((u, i) => `<option value="${escapeHtml(u.id)}"${i === 0 ? " selected" : ""}>${escapeHtml(u.real_name || u.name)}</option>`).join("");
1946
- const placeholder = threadTs ? "Reply in thread" : `Message ${channelLabel(store, channel)}`;
1947
- const thread = threadTs ? ` data-thread="${escapeHtml(threadTs)}"` : "";
1948
- const gated = opts.writeGated ? ' data-gated="1"' : "";
1949
- 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>` : "";
1950
- 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"><select class="sm-composer-user" aria-label="Post as">${options}</select><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>`;
2177
+ function messageEvent(store, m, channel) {
2178
+ const {
2179
+ channel: _c,
2180
+ team,
2181
+ ...rest
2182
+ } = wireMessage(m);
2183
+ const event = {
2184
+ ...rest,
2185
+ type: "message",
2186
+ channel: m.channel,
2187
+ event_ts: m.ts,
2188
+ channel_type: store.channelType(channel),
2189
+ team
2190
+ };
2191
+ if (m.files?.length && !m.subtype)
2192
+ event.subtype = "file_share";
2193
+ if (m.files?.length) {
2194
+ event.upload = false;
2195
+ event.display_as_bot = false;
2196
+ }
2197
+ return event;
1951
2198
  }
1952
- function mentionData(store) {
1953
- const users = [...store.users.values()].filter((u) => !u.deleted).map((u) => ({
1954
- name: u.name,
1955
- real: u.real_name || u.name,
1956
- initials: initials(u.real_name || u.name),
1957
- color: AVATAR_COLORS[hashIndex(u.id, AVATAR_COLORS.length)]
1958
- }));
1959
- const json = JSON.stringify(users).replace(/</g, "\\u003c");
1960
- return `<script type="application/json" id="sm-users">${json}</script>`;
2199
+ function appMentionEvent(store, m) {
2200
+ const { channel_type: _ct, ...event } = messageEvent(store, m, store.channel(m.channel));
2201
+ return { ...event, type: "app_mention" };
1961
2202
  }
1962
- function uiScript(store, opts, closeUrl) {
1963
- 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)}});` : "";
1964
- const body = `(function(){
1965
- var W="sm-panel-w",DEF=${JSON.stringify(panelWidth(opts))},FIXED=${opts.panelWidth ? "true" : "false"};
1966
- function scroll(){document.querySelectorAll(".sm-scroll").forEach(function(el){el.scrollTop=el.scrollHeight})}
1967
- scroll();addEventListener("load",scroll);
1968
- var handle=document.querySelector(".sm-resize");
1969
- if(handle){
1970
- var saved=null;try{saved=localStorage.getItem(W)}catch(e){}
1971
- if(!FIXED&&saved)document.body.style.setProperty("--sm-panel-w",saved);
1972
- var dragging=false;
1973
- handle.addEventListener("mousedown",function(e){dragging=true;handle.classList.add("sm-dragging");e.preventDefault()});
1974
- 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")});
1975
- 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){}});
1976
- handle.addEventListener("dblclick",function(){try{localStorage.removeItem(W)}catch(e){}document.body.style.setProperty("--sm-panel-w",DEF)});
2203
+ function messageChangedEvent(store, m, previous) {
2204
+ const channel = store.channel(m.channel);
2205
+ const ts = nextTs();
2206
+ return {
2207
+ type: "message",
2208
+ subtype: "message_changed",
2209
+ channel: m.channel,
2210
+ channel_type: store.channelType(channel),
2211
+ hidden: true,
2212
+ ts,
2213
+ event_ts: ts,
2214
+ message: {
2215
+ ...wireMessage(m),
2216
+ channel: undefined,
2217
+ source_team: store.team.id,
2218
+ user_team: store.team.id
2219
+ },
2220
+ previous_message: { ...wireMessage(previous), channel: undefined }
2221
+ };
1977
2222
  }
1978
- var raw=document.getElementById("sm-users");
1979
- var PEOPLE=(raw?JSON.parse(raw.textContent||"[]"):[]).concat([{name:"here",real:"Notify everyone online",initials:"@",color:"#616061"},{name:"channel",real:"Notify everyone in the channel",initials:"@",color:"#616061"}]);
1980
- function esc(s){return String(s).replace(/[&<>"]/g,function(c){return c==="&"?"&amp;":c==="<"?"&lt;":c===">"?"&gt;":"&quot;"})}
1981
- var GATED=${opts.writeGated ? "true" : "false"},LIVE=${opts.live !== false && !opts.refreshSec ? "true" : "false"},CK="sm-presenter";
1982
- function cred(){try{return localStorage.getItem(CK)||""}catch(e){return ""}}
1983
- function setCred(v){try{if(v)localStorage.setItem(CK,v);else localStorage.removeItem(CK)}catch(e){}}
1984
- (function(){var m=/[#&]presenter=([^&]+)/.exec(location.hash||"");if(m){setCred(btoa(decodeURIComponent(m[1])));history.replaceState(null,"",location.pathname+location.search)}})();
1985
- function authHeaders(h){var c=cred();if(c)h.authorization="Basic "+c;return h}
1986
- 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>':""})}
1987
- 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})}
1988
- document.addEventListener("click",function(e){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"))});
1989
- 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"))}});
1990
- lockUi();
1991
- var pending=null;
1992
- 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(){})},120)}
1993
- function apply(html){var doc=new DOMParser().parseFromString(html,"text/html");[".sm-side",".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});if(doc.title)document.title=doc.title}
1994
- if(LIVE&&window.EventSource){
1995
- var box0=document.querySelector(".sm-composer"),pm=/^\\/c\\/([^/]+)/.exec(location.pathname),chan=box0?box0.dataset.channel:(pm?decodeURIComponent(pm[1]):null);
1996
- if(chan){
1997
- var h1=document.querySelector(".sm-top h1"),dot=null;
1998
- if(h1){dot=document.createElement("span");dot.className="sm-live";dot.textContent="\u25CF live";h1.appendChild(dot)}
1999
- var es=new EventSource("/c/"+encodeURIComponent(chan)+"/events"),down=false;
2000
- es.addEventListener("change",refresh);
2001
- es.onopen=function(){if(dot){dot.textContent="\u25CF live";dot.classList.remove("sm-live-off")}if(down){down=false;refresh()}};
2002
- es.onerror=function(){down=true;if(dot){dot.textContent="\u25CF reconnecting";dot.classList.add("sm-live-off")}};
2003
- }
2223
+ function messageDeletedEvent(store, m) {
2224
+ const channel = store.channel(m.channel);
2225
+ const ts = nextTs();
2226
+ return {
2227
+ type: "message",
2228
+ subtype: "message_deleted",
2229
+ channel: m.channel,
2230
+ channel_type: store.channelType(channel),
2231
+ hidden: true,
2232
+ deleted_ts: m.ts,
2233
+ ts,
2234
+ event_ts: ts,
2235
+ previous_message: { ...wireMessage(m), channel: undefined }
2236
+ };
2004
2237
  }
2005
- function send(box){var t=box.querySelector(".sm-composer-text"),text=t.value.trim();if(!text||t.disabled)return;var body={channel:box.dataset.channel,user:box.querySelector(".sm-composer-user").value,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})}
2006
- document.querySelectorAll(".sm-composer").forEach(function(box){
2007
- var ta=box.querySelector(".sm-composer-text"),menu=box.querySelector(".sm-mentions"),items=[],active=0;
2008
- function close(){items=[];menu.style.display="none"}
2009
- function prefix(){var m=/(?:^|\\s)@(\\w*)$/.exec(ta.value.slice(0,ta.selectionStart));return m?m[1]:null}
2010
- function paint(){menu.querySelectorAll(".sm-mention").forEach(function(el,i){el.className="sm-mention"+(i===active?" sm-mention-on":"")})}
2011
- function show(){
2012
- var q=prefix();if(q===null)return close();
2013
- var low=q.toLowerCase();
2014
- var list=PEOPLE.filter(function(u){return !low||u.name.toLowerCase().indexOf(low)===0||u.real.toLowerCase().indexOf(low)===0}).slice(0,8);
2015
- if(!list.length)return close();
2016
- items=list;active=0;
2017
- 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("");
2018
- menu.style.display="block";
2019
- }
2020
- 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()}
2021
- ta.addEventListener("input",show);
2022
- ta.addEventListener("blur",function(){setTimeout(close,150)});
2023
- menu.addEventListener("mousedown",function(e){var el=e.target.closest(".sm-mention");if(el){e.preventDefault();pick(Number(el.dataset.i))}});
2024
- ta.addEventListener("keydown",function(e){
2025
- if(e.key==="Backspace"&&ta.selectionStart===ta.selectionEnd&&ta.selectionStart>0){
2026
- var pos=ta.selectionStart,before=ta.value.slice(0,pos),hit="";
2027
- 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}}
2028
- 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}
2029
- }
2030
- if(items.length){
2031
- if(e.key==="ArrowDown"){e.preventDefault();active=(active+1)%items.length;paint();return}
2032
- if(e.key==="ArrowUp"){e.preventDefault();active=(active-1+items.length)%items.length;paint();return}
2033
- if(e.key==="Enter"||e.key==="Tab"){e.preventDefault();pick(active);return}
2034
- if(e.key==="Escape"){e.preventDefault();e.stopPropagation();close();return}
2035
- }
2036
- if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();send(box)}
2037
- });
2038
- box.querySelector(".sm-composer-send").addEventListener("click",function(){send(box)});
2039
- });
2040
- })();`;
2041
- return `${mentionData(store)}<script>${body}${esc}</script>`;
2238
+ function reactionEvent(kind, m, name, user) {
2239
+ return {
2240
+ type: kind,
2241
+ user,
2242
+ reaction: name,
2243
+ item_user: m.user,
2244
+ item: { type: "message", channel: m.channel, ts: m.ts },
2245
+ event_ts: nextTs()
2246
+ };
2042
2247
  }
2043
- function channelView(store, opts, channelId) {
2044
- const channel = store.channels.get(channelId);
2045
- const ctx = ctxOf(store);
2046
- if (!channel)
2047
- return notFound(store, opts, "Channel not found");
2048
- const label = channelLabel(store, channel);
2049
- return shell(store, opts, {
2050
- title: `${label} \xB7 slack-mock`,
2051
- header: channelHeader(store, opts, channel),
2052
- main: channelColumn(store, ctx, opts, channel),
2053
- active: channel.id,
2054
- footer: composer(store, opts, channel),
2055
- script: opts.screenshot ? "" : uiScript(store, opts)
2056
- });
2248
+ function memberJoinedEvent(store, channel, user, inviter) {
2249
+ return {
2250
+ type: "member_joined_channel",
2251
+ user,
2252
+ channel: channel.id,
2253
+ channel_type: store.channelType(channel) === "channel" ? "C" : "G",
2254
+ team: store.team.id,
2255
+ inviter,
2256
+ event_ts: nextTs()
2257
+ };
2057
2258
  }
2058
- function assistantPanel(store, channelId, ts) {
2059
- const thread = store.assistantThreads.get(`${channelId}:${ts}`);
2060
- if (!thread)
2061
- return "";
2062
- const parts = [];
2063
- if (thread.title)
2064
- parts.push(`<div class="sm-assist-title">${plainTextToHtml(thread.title)}</div>`);
2065
- if (thread.status)
2066
- parts.push(`<div class="sm-assist-status">${plainTextToHtml(thread.status)}<span class="sm-stream">\u2022\u2022\u2022</span></div>`);
2067
- const prompts = Array.isArray(thread.prompts) ? thread.prompts : [];
2068
- if (prompts.length) {
2069
- const chips = prompts.map((p) => {
2070
- const prompt = typeof p === "object" && p !== null ? p : {};
2071
- const title = typeof prompt.title === "string" ? prompt.title : "";
2072
- const message = typeof prompt.message === "string" ? prompt.message : "";
2073
- return `<span class="sm-prompt" title="${escapeHtml(message)}">${plainTextToHtml(title || message)}</span>`;
2074
- }).join("");
2075
- const heading = thread.promptsTitle ? `<div class="sm-assist-status">${plainTextToHtml(thread.promptsTitle)}</div>` : "";
2076
- parts.push(`${heading}<div class="sm-prompts">${chips}</div>`);
2077
- }
2078
- if (!parts.length)
2079
- return "";
2080
- return `<div class="sm-assist">${parts.join("")}</div>`;
2259
+ function assistantThreadStartedEvent(store, dm, user, threadTs, context = {}) {
2260
+ return {
2261
+ type: "assistant_thread_started",
2262
+ assistant_thread: {
2263
+ user_id: user,
2264
+ context: { team_id: store.team.id, enterprise_id: null, ...context },
2265
+ channel_id: dm.id,
2266
+ thread_ts: threadTs
2267
+ },
2268
+ event_ts: nextTs()
2269
+ };
2081
2270
  }
2082
- function threadView(store, opts, channelId, ts) {
2083
- const channel = store.channels.get(channelId);
2084
- const ctx = ctxOf(store);
2085
- if (!channel)
2086
- return notFound(store, opts, "Channel not found");
2087
- const parent = store.findMessage(channel.id, ts);
2088
- if (!parent)
2089
- return notFound(store, opts, "Message not found");
2090
- const items = store.replies(channel.id, ts, { limit: 1000 }).items;
2091
- const replies = items.slice(1);
2092
- const label = channelLabel(store, channel);
2093
- 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>`;
2094
- const body = `${assistantPanel(store, channel.id, ts)}${renderMessage(store, ctx, parent, opts)}${repliesBar}${renderMessageList(store, ctx, replies, opts, { dividers: false })}`;
2095
- if (opts.screenshot) {
2096
- const header = topbar(`Thread <span class="sm-muted">\xB7</span> <a href="${channelHref(channel.id, opts)}">${escapeHtml(label)}</a>`, "");
2097
- return shell(store, opts, {
2098
- title: `Thread \xB7 ${label}`,
2099
- header,
2100
- main: body,
2101
- active: channel.id
2102
- });
2103
- }
2104
- const close = channelHref(channel.id, opts);
2105
- const title = `Thread \xB7 ${label}`;
2106
- if (opts.threadView === "full") {
2107
- 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>`);
2108
- return shell(store, opts, {
2109
- title,
2110
- header,
2111
- main: body,
2112
- active: channel.id,
2113
- footer: composer(store, opts, channel, ts),
2114
- script: uiScript(store, opts, close)
2115
- });
2116
- }
2117
- const expand = threadHref(channel.id, ts, opts, { full: true });
2118
- const panel = `<aside class="sm-panel"><div class="sm-panel-top"><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><a class="sm-panel-back" href="${close}">\u2190 ${escapeHtml(label)}</a><div class="sm-panel-body sm-scroll">${body}</div>${composer(store, opts, channel, ts)}</aside>`;
2119
- return shell(store, opts, {
2120
- title,
2121
- header: channelHeader(store, opts, channel),
2122
- main: channelColumn(store, ctx, opts, channel, ts),
2123
- active: channel.id,
2124
- panel,
2125
- footer: composer(store, opts, channel),
2126
- script: uiScript(store, opts, close)
2127
- });
2271
+ function assistantThreadContextChangedEvent(store, dm, user, threadTs, context) {
2272
+ return {
2273
+ type: "assistant_thread_context_changed",
2274
+ assistant_thread: {
2275
+ user_id: user,
2276
+ context: { team_id: store.team.id, enterprise_id: null, ...context },
2277
+ channel_id: dm.id,
2278
+ thread_ts: threadTs
2279
+ },
2280
+ event_ts: nextTs()
2281
+ };
2128
2282
  }
2129
- function notFound(store, opts, message) {
2130
- return shell(store, opts, {
2131
- title: message,
2132
- header: topbar(escapeHtml(message), ""),
2133
- main: `<div class="sm-empty">${escapeHtml(message)}</div>`
2134
- });
2283
+ function slashCommandPayload(store, input) {
2284
+ return {
2285
+ token: VERIFICATION_TOKEN,
2286
+ team_id: store.team.id,
2287
+ team_domain: store.team.domain,
2288
+ channel_id: input.channel.id,
2289
+ channel_name: input.channel.is_im ? "directmessage" : input.channel.name,
2290
+ user_id: input.user.id,
2291
+ user_name: input.user.name,
2292
+ command: input.command,
2293
+ text: input.text,
2294
+ api_app_id: store.app.id,
2295
+ is_enterprise_install: "false",
2296
+ response_url: input.responseUrl,
2297
+ trigger_id: input.triggerId
2298
+ };
2135
2299
  }
2136
- function renderPage(store, view, opts = {}) {
2137
- switch (view.kind) {
2138
- case "channel":
2139
- return channelView(store, opts, view.channel);
2140
- case "thread":
2141
- return threadView(store, opts, view.channel, view.ts);
2142
- default:
2143
- return indexView(store, opts);
2144
- }
2300
+ function blockActionsPayload(store, input) {
2301
+ return {
2302
+ type: "block_actions",
2303
+ user: {
2304
+ id: input.user.id,
2305
+ username: input.user.name,
2306
+ name: input.user.name,
2307
+ team_id: store.team.id
2308
+ },
2309
+ api_app_id: store.app.id,
2310
+ token: VERIFICATION_TOKEN,
2311
+ container: {
2312
+ type: "message",
2313
+ message_ts: input.message.ts,
2314
+ channel_id: input.channel.id,
2315
+ is_ephemeral: !!input.message.ephemeral_user,
2316
+ ...input.message.thread_ts ? { thread_ts: input.message.thread_ts } : {}
2317
+ },
2318
+ trigger_id: input.triggerId,
2319
+ team: { id: store.team.id, domain: store.team.domain },
2320
+ enterprise: null,
2321
+ is_enterprise_install: false,
2322
+ channel: { id: input.channel.id, name: input.channel.name },
2323
+ message: wireMessage(input.message),
2324
+ state: { values: {} },
2325
+ response_url: input.responseUrl,
2326
+ actions: input.actions.map((a) => ({ action_ts: nextTs(), ...a }))
2327
+ };
2328
+ }
2329
+ function viewSubmissionPayload(store, input) {
2330
+ const { opened_by: _o, trigger_id: _t, ...view } = input.view;
2331
+ return {
2332
+ type: "view_submission",
2333
+ team: { id: store.team.id, domain: store.team.domain },
2334
+ user: {
2335
+ id: input.user.id,
2336
+ username: input.user.name,
2337
+ name: input.user.name,
2338
+ team_id: store.team.id
2339
+ },
2340
+ api_app_id: store.app.id,
2341
+ token: VERIFICATION_TOKEN,
2342
+ trigger_id: input.triggerId,
2343
+ view: { ...view, state: { values: input.values } },
2344
+ response_urls: [],
2345
+ is_enterprise_install: false,
2346
+ enterprise: null
2347
+ };
2145
2348
  }
2146
2349
 
2147
2350
  // src/socket-mode.ts
@@ -2320,7 +2523,7 @@ class SocketModeHub {
2320
2523
 
2321
2524
  // src/web-api.ts
2322
2525
  function required(args, key) {
2323
- const v = str(args, key);
2526
+ const v = str2(args, key);
2324
2527
  if (!v)
2325
2528
  throw new SlackApiError2("invalid_arguments", {
2326
2529
  response_metadata: { messages: [`[ERROR] missing required field: ${key}`] }
@@ -2357,8 +2560,16 @@ function botFields(ctx) {
2357
2560
  }
2358
2561
  };
2359
2562
  }
2563
+ function markdownText(args) {
2564
+ const markdown = str2(args, "markdown_text");
2565
+ if (markdown === undefined)
2566
+ return;
2567
+ if (str2(args, "text") || Array.isArray(args.blocks) && args.blocks.length)
2568
+ throw new SlackApiError2("markdown_text_conflict");
2569
+ return markdown;
2570
+ }
2360
2571
  function messageContent(args) {
2361
- const text = str(args, "text") ?? "";
2572
+ const text = markdownText(args) ?? str2(args, "text") ?? "";
2362
2573
  const blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
2363
2574
  const attachments = Array.isArray(args.attachments) ? args.attachments : undefined;
2364
2575
  if (!text && !blocks?.length && !attachments?.length)
@@ -2427,18 +2638,18 @@ var handlers = {
2427
2638
  "chat.postMessage": (ctx, args) => {
2428
2639
  const channel = resolveChannel(ctx.store, required(args, "channel"));
2429
2640
  requireMember(channel, ctx.actor);
2430
- const threadTs = str(args, "thread_ts");
2641
+ const threadTs = str2(args, "thread_ts");
2431
2642
  const message = ctx.store.addMessage({
2432
2643
  channel: channel.id,
2433
2644
  user: ctx.actor.userId,
2434
2645
  ...messageContent(args),
2435
2646
  ...threadTs ? { thread_ts: threadTs } : {},
2436
2647
  ...bool(args, "reply_broadcast") && threadTs ? { subtype: "thread_broadcast" } : {},
2437
- ...str(args, "username") ? { username: str(args, "username") } : {},
2438
- ...str(args, "icon_emoji") || str(args, "icon_url") ? {
2648
+ ...str2(args, "username") ? { username: str2(args, "username") } : {},
2649
+ ...str2(args, "icon_emoji") || str2(args, "icon_url") ? {
2439
2650
  icons: {
2440
- ...str(args, "icon_emoji") ? { emoji: str(args, "icon_emoji") } : {},
2441
- ...str(args, "icon_url") ? { image_64: str(args, "icon_url") } : {}
2651
+ ...str2(args, "icon_emoji") ? { emoji: str2(args, "icon_emoji") } : {},
2652
+ ...str2(args, "icon_url") ? { image_64: str2(args, "icon_url") } : {}
2442
2653
  }
2443
2654
  } : {},
2444
2655
  ...botFields(ctx)
@@ -2449,7 +2660,7 @@ var handlers = {
2449
2660
  const channel = resolveChannel(ctx.store, required(args, "channel"));
2450
2661
  const user = required(args, "user");
2451
2662
  ctx.store.user(user);
2452
- const threadTs = str(args, "thread_ts");
2663
+ const threadTs = str2(args, "thread_ts");
2453
2664
  const message = ctx.store.addMessage({
2454
2665
  channel: channel.id,
2455
2666
  user: ctx.actor.userId,
@@ -2467,8 +2678,11 @@ var handlers = {
2467
2678
  if (existing.user !== ctx.actor.userId && !ctx.actor.isBot)
2468
2679
  throw new SlackApiError2("cant_update_message");
2469
2680
  const patch = {};
2470
- if (args.text !== undefined)
2471
- patch.text = str(args, "text") ?? "";
2681
+ const markdown = markdownText(args);
2682
+ if (markdown !== undefined)
2683
+ patch.text = markdown;
2684
+ else if (args.text !== undefined)
2685
+ patch.text = str2(args, "text") ?? "";
2472
2686
  if (args.blocks !== undefined)
2473
2687
  patch.blocks = Array.isArray(args.blocks) ? args.blocks : undefined;
2474
2688
  if (args.attachments !== undefined)
@@ -2489,15 +2703,15 @@ var handlers = {
2489
2703
  "chat.startStream": (ctx, args) => {
2490
2704
  const channel = resolveChannel(ctx.store, required(args, "channel"));
2491
2705
  requireMember(channel, ctx.actor);
2492
- const threadTs = str(args, "thread_ts");
2706
+ const threadTs = str2(args, "thread_ts");
2493
2707
  const message = ctx.store.addMessage({
2494
2708
  channel: channel.id,
2495
2709
  user: ctx.actor.userId,
2496
2710
  text: streamText(args),
2497
2711
  streaming_state: "in_progress",
2498
2712
  ...threadTs ? { thread_ts: threadTs } : {},
2499
- ...str(args, "username") ? { username: str(args, "username") } : {},
2500
- ...str(args, "icon_emoji") ? { icons: { emoji: str(args, "icon_emoji") } } : {},
2713
+ ...str2(args, "username") ? { username: str2(args, "username") } : {},
2714
+ ...str2(args, "icon_emoji") ? { icons: { emoji: str2(args, "icon_emoji") } } : {},
2501
2715
  ...botFields(ctx)
2502
2716
  });
2503
2717
  return { channel: channel.id, ts: message.ts };
@@ -2538,7 +2752,7 @@ var handlers = {
2538
2752
  };
2539
2753
  },
2540
2754
  "conversations.list": (ctx, args) => {
2541
- const types = new Set((str(args, "types") ?? "public_channel").split(",").map((t) => t.trim()));
2755
+ const types = new Set((str2(args, "types") ?? "public_channel").split(",").map((t) => t.trim()));
2542
2756
  const excludeArchived = bool(args, "exclude_archived") ?? false;
2543
2757
  const all = [...ctx.store.channels.values()].filter((c) => {
2544
2758
  if (excludeArchived && c.is_archived)
@@ -2552,7 +2766,7 @@ var handlers = {
2552
2766
  return types.has("public_channel");
2553
2767
  });
2554
2768
  const limit = num(args, "limit", 100);
2555
- const start = cursorOffset(str(args, "cursor"));
2769
+ const start = cursorOffset(str2(args, "cursor"));
2556
2770
  const slice = all.slice(start, start + limit);
2557
2771
  const hasMore = start + limit < all.length;
2558
2772
  return {
@@ -2614,7 +2828,7 @@ var handlers = {
2614
2828
  return { members: channel.members, response_metadata: { next_cursor: "" } };
2615
2829
  },
2616
2830
  "conversations.open": (ctx, args) => {
2617
- const users = (str(args, "users") ?? "").split(",").map((u) => u.trim()).filter(Boolean);
2831
+ const users = (str2(args, "users") ?? "").split(",").map((u) => u.trim()).filter(Boolean);
2618
2832
  if (users.length !== 1)
2619
2833
  throw new SlackApiError2("users_list_not_supplied");
2620
2834
  const dm = ctx.store.openDm(users[0]);
@@ -2624,11 +2838,11 @@ var handlers = {
2624
2838
  const channel = ctx.store.channel(required(args, "channel"));
2625
2839
  requireMember(channel, ctx.actor);
2626
2840
  const p = ctx.store.history(channel.id, {
2627
- oldest: str(args, "oldest"),
2628
- latest: str(args, "latest"),
2841
+ oldest: str2(args, "oldest"),
2842
+ latest: str2(args, "latest"),
2629
2843
  inclusive: bool(args, "inclusive"),
2630
2844
  limit: num(args, "limit", 100),
2631
- cursor: str(args, "cursor")
2845
+ cursor: str2(args, "cursor")
2632
2846
  });
2633
2847
  return {
2634
2848
  messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
@@ -2644,11 +2858,11 @@ var handlers = {
2644
2858
  if (!ctx.store.findMessage(channel.id, ts))
2645
2859
  throw new SlackApiError2("thread_not_found");
2646
2860
  const p = ctx.store.replies(channel.id, ts, {
2647
- oldest: str(args, "oldest"),
2648
- latest: str(args, "latest"),
2861
+ oldest: str2(args, "oldest"),
2862
+ latest: str2(args, "latest"),
2649
2863
  inclusive: bool(args, "inclusive"),
2650
2864
  limit: num(args, "limit", 1000),
2651
- cursor: str(args, "cursor")
2865
+ cursor: str2(args, "cursor")
2652
2866
  });
2653
2867
  return {
2654
2868
  messages: p.items.map((m) => historyMessage(m, bool(args, "include_all_metadata"))),
@@ -2668,7 +2882,7 @@ var handlers = {
2668
2882
  return { user };
2669
2883
  },
2670
2884
  "users.conversations": (ctx, args) => {
2671
- const user = str(args, "user") ?? ctx.actor.userId;
2885
+ const user = str2(args, "user") ?? ctx.actor.userId;
2672
2886
  const channels = [...ctx.store.channels.values()].filter((c) => c.members.includes(user) && !c.is_im);
2673
2887
  return {
2674
2888
  channels: channels.map((c) => channelInfo(ctx.store, c, ctx.actor)),
@@ -2705,7 +2919,7 @@ var handlers = {
2705
2919
  ctx.pendingUploads.set(id, {
2706
2920
  name: filename,
2707
2921
  length,
2708
- alt_text: str(args, "alt_text"),
2922
+ alt_text: str2(args, "alt_text"),
2709
2923
  user: ctx.actor.userId
2710
2924
  });
2711
2925
  return { upload_url: `${ctx.baseUrl}/upload/v1/${id}`, file_id: id };
@@ -2722,19 +2936,19 @@ var handlers = {
2722
2936
  f.title = title;
2723
2937
  return f;
2724
2938
  });
2725
- const channelId = str(args, "channel_id");
2939
+ const channelId = str2(args, "channel_id");
2726
2940
  if (channelId) {
2727
2941
  const channel = ctx.store.channel(channelId);
2728
2942
  requireMember(channel, ctx.actor);
2729
2943
  for (const f of files)
2730
2944
  if (!f.channels.includes(channel.id))
2731
2945
  f.channels.push(channel.id);
2732
- const threadTs = str(args, "thread_ts");
2946
+ const threadTs = str2(args, "thread_ts");
2733
2947
  ctx.store.addMessage({
2734
2948
  channel: channel.id,
2735
2949
  user: ctx.actor.userId,
2736
2950
  subtype: "file_share",
2737
- text: str(args, "initial_comment") ?? "",
2951
+ text: str2(args, "initial_comment") ?? "",
2738
2952
  files,
2739
2953
  ...threadTs ? { thread_ts: threadTs } : {},
2740
2954
  ...botFields(ctx)
@@ -2762,13 +2976,13 @@ var handlers = {
2762
2976
  });
2763
2977
  const stored = ctx.store.openView({
2764
2978
  type: "modal",
2765
- callback_id: str(view, "callback_id"),
2766
- private_metadata: str(view, "private_metadata") ?? "",
2979
+ callback_id: str2(view, "callback_id"),
2980
+ private_metadata: str2(view, "private_metadata") ?? "",
2767
2981
  title: view.title,
2768
2982
  submit: view.submit,
2769
2983
  close: view.close,
2770
2984
  blocks: Array.isArray(view.blocks) ? view.blocks : [],
2771
- external_id: str(view, "external_id"),
2985
+ external_id: str2(view, "external_id"),
2772
2986
  opened_by: "",
2773
2987
  trigger_id: triggerId,
2774
2988
  state: { values: {} },
@@ -2784,8 +2998,8 @@ var handlers = {
2784
2998
  throw new SlackApiError2("not_found");
2785
2999
  const view = viewArg(args);
2786
3000
  Object.assign(existing, {
2787
- callback_id: str(view, "callback_id") ?? existing.callback_id,
2788
- private_metadata: str(view, "private_metadata") ?? existing.private_metadata,
3001
+ callback_id: str2(view, "callback_id") ?? existing.callback_id,
3002
+ private_metadata: str2(view, "private_metadata") ?? existing.private_metadata,
2789
3003
  title: view.title ?? existing.title,
2790
3004
  submit: view.submit ?? existing.submit,
2791
3005
  close: view.close ?? existing.close,
@@ -2800,7 +3014,7 @@ var handlers = {
2800
3014
  const channel = ctx.store.channel(required(args, "channel_id"));
2801
3015
  const threadTs = required(args, "thread_ts");
2802
3016
  const t = ctx.store.assistantThread(channel.id, threadTs);
2803
- t.status = str(args, "status") ?? "";
3017
+ t.status = str2(args, "status") ?? "";
2804
3018
  ctx.store.onChangeEmit({
2805
3019
  kind: "assistant.status",
2806
3020
  channel: channel.id,
@@ -2827,7 +3041,7 @@ var handlers = {
2827
3041
  const threadTs = required(args, "thread_ts");
2828
3042
  const t = ctx.store.assistantThread(channel.id, threadTs);
2829
3043
  t.prompts = Array.isArray(args.prompts) ? args.prompts : [];
2830
- t.promptsTitle = str(args, "title");
3044
+ t.promptsTitle = str2(args, "title");
2831
3045
  ctx.store.onChangeEmit({
2832
3046
  kind: "assistant.prompts",
2833
3047
  channel: channel.id,
@@ -2844,7 +3058,7 @@ var handlers = {
2844
3058
  }
2845
3059
  };
2846
3060
  function streamText(args) {
2847
- const md = str(args, "markdown_text");
3061
+ const md = str2(args, "markdown_text");
2848
3062
  if (md)
2849
3063
  return md;
2850
3064
  const chunks = Array.isArray(args.chunks) ? args.chunks : [];
@@ -3056,7 +3270,7 @@ class SlackMock2 {
3056
3270
  try {
3057
3271
  const isUiSurface = path === "/" || path === "" || path.startsWith("/c/");
3058
3272
  const isAdminSurface = path.startsWith("/mock/") || isUiSurface && !this.opts.publicUi;
3059
- const isPresenterRoute = path === "/mock/messages" && req.method === "POST" || path === "/mock/presenter";
3273
+ const isPresenterRoute = (path === "/mock/messages" || path === "/mock/reactions") && req.method === "POST" || path === "/mock/presenter";
3060
3274
  const allowed = isPresenterRoute ? this.authorizedPresenter(req) : this.authorizedAdmin(req);
3061
3275
  if (isAdminSurface && !allowed)
3062
3276
  return denied(req, path);
@@ -3550,6 +3764,11 @@ data: ${JSON.stringify(data)}
3550
3764
  this.store.addReaction(this.resolveChannel(input.channel).id, input.ts, input.name, user.id);
3551
3765
  await this.flush();
3552
3766
  }
3767
+ async removeReaction(input) {
3768
+ const user = input.user ? this.user(input.user) : this.defaultHuman();
3769
+ this.store.removeReaction(this.resolveChannel(input.channel).id, input.ts, input.name, user.id);
3770
+ await this.flush();
3771
+ }
3553
3772
  issueResponseUrl(target) {
3554
3773
  const id = `${this.store.team.id}/${slackId("", 10)}/${slackId("", 24).toLowerCase()}`;
3555
3774
  this.responseUrls.set(id, { ...target, expires: Date.now() + 30 * 60000 });
@@ -3828,7 +4047,13 @@ data: ${JSON.stringify(data)}
3828
4047
  if (path === "assistant/start" && req.method === "POST")
3829
4048
  return json(await this.startAssistantThread(body));
3830
4049
  if (path === "reactions" && req.method === "POST") {
3831
- await this.addReaction(body);
4050
+ const input = body;
4051
+ if (input.action !== undefined && input.action !== "add" && input.action !== "remove")
4052
+ throw new SlackApiError2("invalid_arguments");
4053
+ if (input.action === "remove")
4054
+ await this.removeReaction(input);
4055
+ else
4056
+ await this.addReaction(input);
3832
4057
  return json({ ok: true });
3833
4058
  }
3834
4059
  if (path === "api-calls")
@@ -3895,9 +4120,6 @@ function denied(req, path) {
3895
4120
  }
3896
4121
 
3897
4122
  // src/frames.ts
3898
- import { copyFileSync, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync } from "fs";
3899
- import { tmpdir } from "os";
3900
- import { join, resolve } from "path";
3901
4123
  var FRAME_KINDS = new Set([
3902
4124
  "message.add",
3903
4125
  "message.update",