@theholocron/holocron-plugin-discord 5.0.0-alpha.356 → 5.0.0-alpha.358

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -114,6 +114,16 @@ export declare class DiscordNotifications implements Notifications {
114
114
  /** What the bot's roles give it server-wide (the owner holds every permission), before any channel overwrite. */
115
115
  private serverPermissions;
116
116
  holdsPermission(permission: string): Promise<boolean>;
117
+ /**
118
+ * What a member holding `bits` through the roles in `held` has in a channel, in the order Discord applies the
119
+ * channel's overwrites: @everyone, then the roles, then the member itself.
120
+ */
121
+ private static afterOverwrites;
122
+ /**
123
+ * What the bot can do with the threads of a forum: start posts and reply (`post`) and tag and close them (`manage`).
124
+ * The owner and an Administrator hold every permission, whatever the forum's overwrites say.
125
+ */
126
+ private botThreadsIn;
117
127
  /**
118
128
  * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
119
129
  * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
@@ -150,6 +160,14 @@ export declare class DiscordNotifications implements Notifications {
150
160
  readDiscussion(channel: string, key: string, url?: string): Promise<DiscussionPost | undefined>;
151
161
  /** Changes a document's post: its title, its tag, the state last synced, the pull request line. */
152
162
  updateDiscussion(channel: string, key: string, patch: DiscussionPatch): Promise<void>;
163
+ /** Appends a message to a document's post, reopening and closing it again if it was closed. */
164
+ postDiscussionMessage(channel: string, key: string, content: string, opts?: {
165
+ quiet?: boolean;
166
+ }): Promise<void>;
167
+ /** The text of a post's recent messages, newest first. */
168
+ readDiscussionMessages(channel: string, key: string, limit?: number): Promise<string[]>;
169
+ /** Keeps the oldest post for `key` and deletes the others; returns how many it deleted. */
170
+ dedupeDiscussion(channel: string, key: string): Promise<number>;
153
171
  /**
154
172
  * Posts `content` (up to 2000 characters) in a text channel as the bot, without letting it mention anyone. A `#name`
155
173
  * that is one of the server's channels is linked.
package/dist/index.mjs CHANGED
@@ -48,9 +48,9 @@ const MAX_MESSAGE = 2e3;
48
48
  /**
49
49
  * The line that ends a post's first message and makes it findable and comparable: `-# sync: <key> | <state>`, where
50
50
  * `-#` is Discord's small print. `key` is the document's path; `state` is the state the post and the document last
51
- * agreed on, empty when none.
51
+ * agreed on, empty when none. A state is a tag's name, which may hold spaces (`changes requested`).
52
52
  */
53
- const FOOTER = /^-# sync: (.+) \| (\S*)$/m;
53
+ const FOOTER = /^-# sync: (.+) \| (.*)$/m;
54
54
  /** The paragraph of a first message that names the pull request, as `discussionBody` writes it. */
55
55
  const PR_LINE = /^PR: \[#\d+\]\(<[^>]*>\)$/m;
56
56
  /**
@@ -100,12 +100,21 @@ var DiscordDiscussions = class DiscordDiscussions {
100
100
  for (const thread of await bot.threads.inChannel(this.deps.guild(), forum.id)) {
101
101
  const first = await bot.channels.message(thread.id, thread.id).catch(() => void 0);
102
102
  const footer = first ? FOOTER.exec(first.content) : null;
103
- if (first && footer) entries.set(footer[1], {
104
- key: footer[1],
105
- thread,
106
- content: first.content,
107
- synced: footer[2] || void 0
108
- });
103
+ if (first && footer) {
104
+ const entry = {
105
+ key: footer[1],
106
+ thread,
107
+ content: first.content,
108
+ synced: footer[2] || void 0,
109
+ duplicates: []
110
+ };
111
+ const held = entries.get(entry.key);
112
+ if (!held) entries.set(entry.key, entry);
113
+ else if (BigInt(thread.id) < BigInt(held.thread.id)) {
114
+ entry.duplicates = [held.thread, ...held.duplicates];
115
+ entries.set(entry.key, entry);
116
+ } else held.duplicates.push(thread);
117
+ }
109
118
  }
110
119
  return entries;
111
120
  }
@@ -200,7 +209,8 @@ var DiscordDiscussions = class DiscordDiscussions {
200
209
  key: input.key,
201
210
  thread,
202
211
  content,
203
- synced: input.state
212
+ synced: input.state,
213
+ duplicates: []
204
214
  };
205
215
  posts.set(input.key, entry);
206
216
  return {
@@ -242,7 +252,8 @@ var DiscordDiscussions = class DiscordDiscussions {
242
252
  if (patch.state !== void 0) change.applied_tags = [this.tagId(forum, patch.state)];
243
253
  const nextKey = patch.key ?? key;
244
254
  const footerEdited = nextKey !== key || patch.synced !== void 0 && patch.synced !== entry.synced;
245
- const withPr = patch.prLine === void 0 ? entry.content : DiscordDiscussions.withPrLine(entry.content, patch.prLine);
255
+ const base = patch.body === void 0 ? entry.content : DiscordDiscussions.message(patch.body, key, entry.synced ?? "");
256
+ const withPr = patch.prLine === void 0 ? base : DiscordDiscussions.withPrLine(base, patch.prLine);
246
257
  const withId = patch.idLine === void 0 ? withPr : DiscordDiscussions.withIdLine(withPr, patch.idLine);
247
258
  const edited = footerEdited || withId !== entry.content;
248
259
  if ((Object.keys(change).length > 0 || edited || reopening) && thread.thread_metadata.archived) change.archived = false;
@@ -271,6 +282,58 @@ var DiscordDiscussions = class DiscordDiscussions {
271
282
  })
272
283
  };
273
284
  }
285
+ /**
286
+ * Append a message to the post for `key`, mentioning no one. A post that is archived or locked is unarchived and
287
+ * unlocked for the write and put back as it was, also when the write fails.
288
+ */
289
+ async post(channel, key, content, opts = {}) {
290
+ const entry = (await this.posts(await this.forum(channel))).get(key);
291
+ if (!entry) throw new Error(`no discussion post for \`${key}\` in \`${channel}\``);
292
+ const bot = this.deps.bot();
293
+ const { archived, locked } = entry.thread.thread_metadata;
294
+ const reopen = archived || locked;
295
+ if (reopen) entry.thread = {
296
+ ...entry.thread,
297
+ ...await bot.threads.modify(entry.thread.id, {
298
+ archived: false,
299
+ locked: false
300
+ })
301
+ };
302
+ try {
303
+ const text = content.length > MAX_MESSAGE ? `${content.slice(0, 1999)}…` : content;
304
+ await bot.channels.createMessage(entry.thread.id, {
305
+ content: text,
306
+ ...opts.quiet ? { flags: MessageFlag.SuppressNotifications } : {}
307
+ });
308
+ } finally {
309
+ if (reopen) entry.thread = {
310
+ ...entry.thread,
311
+ ...await bot.threads.modify(entry.thread.id, {
312
+ archived,
313
+ locked
314
+ })
315
+ };
316
+ }
317
+ }
318
+ /** The text of the recent messages of the post for `key`, newest first; empty when there is no post. */
319
+ async messages(channel, key, limit = 50) {
320
+ const entry = (await this.posts(await this.forum(channel))).get(key);
321
+ if (!entry) return [];
322
+ return (await this.deps.bot().channels.messages(entry.thread.id, Math.min(Math.max(limit, 1), 100))).map((m) => m.content);
323
+ }
324
+ /** Keep the oldest post that carries `key` and delete the others. Returns how many were deleted. */
325
+ async dedupe(channel, key) {
326
+ const entry = (await this.posts(await this.forum(channel))).get(key);
327
+ if (!entry) return 0;
328
+ const bot = this.deps.bot();
329
+ let deleted = 0;
330
+ while (entry.duplicates.length > 0) {
331
+ await bot.threads.delete(entry.duplicates[0].id);
332
+ entry.duplicates.shift();
333
+ deleted++;
334
+ }
335
+ return deleted;
336
+ }
274
337
  };
275
338
  // src/capabilities/notifications.ts
276
339
  /** Discord's numeric settings, by the names the layout uses. */
@@ -533,6 +596,7 @@ var DiscordNotifications = class DiscordNotifications {
533
596
  const channels = await this.channelList();
534
597
  const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
535
598
  const wantsWebhook = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.webhook || ch.feeds?.monitoring || ch.feeds?.errors).map((ch) => ch.name.toLowerCase())));
599
+ const wantsPrs = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.feeds?.prs).map((ch) => ch.name.toLowerCase())));
536
600
  const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement || c.type === ChannelType.Forum);
537
601
  const found = [];
538
602
  for (const c of text) {
@@ -548,6 +612,13 @@ var DiscordNotifications = class DiscordNotifications {
548
612
  } catch (err) {
549
613
  webhooksError = reason(err);
550
614
  }
615
+ let botThreads;
616
+ let botThreadsError;
617
+ if (c.type === ChannelType.Forum && wantsPrs.has(c.name.toLowerCase())) try {
618
+ botThreads = await this.botThreadsIn(c.permission_overwrites ?? []);
619
+ } catch (err) {
620
+ botThreadsError = reason(err);
621
+ }
551
622
  const category = c.parent_id ? categoryName.get(c.parent_id) : void 0;
552
623
  found.push({
553
624
  name: c.name,
@@ -561,7 +632,9 @@ var DiscordNotifications = class DiscordNotifications {
561
632
  webhooks,
562
633
  webhookAvatars,
563
634
  webhookIds,
564
- ...webhooksError ? { webhooksError } : {}
635
+ ...webhooksError ? { webhooksError } : {},
636
+ ...botThreads ? { botThreads } : {},
637
+ ...botThreadsError ? { botThreadsError } : {}
565
638
  });
566
639
  }
567
640
  let roles = [];
@@ -912,6 +985,44 @@ var DiscordNotifications = class DiscordNotifications {
912
985
  return has("Administrator") || has(permission);
913
986
  }
914
987
  /**
988
+ * What a member holding `bits` through the roles in `held` has in a channel, in the order Discord applies the
989
+ * channel's overwrites: @everyone, then the roles, then the member itself.
990
+ */
991
+ static afterOverwrites(bits, held, me, guild, list) {
992
+ const apply = (now, found) => {
993
+ const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
994
+ const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
995
+ return now & ~deny | allow;
996
+ };
997
+ let now = apply(bits, list.filter((o) => o.id === guild));
998
+ now = apply(now, list.filter((o) => o.type === 0 && o.id !== guild && held.has(o.id)));
999
+ return apply(now, list.filter((o) => o.type === 1 && o.id === me));
1000
+ }
1001
+ /**
1002
+ * What the bot can do with the threads of a forum: start posts and reply (`post`) and tag and close them (`manage`).
1003
+ * The owner and an Administrator hold every permission, whatever the forum's overwrites say.
1004
+ */
1005
+ async botThreadsIn(overwrites) {
1006
+ const { owner, bits, held, me } = await this.serverPermissions();
1007
+ if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n) return {
1008
+ post: true,
1009
+ manage: true
1010
+ };
1011
+ const now = DiscordNotifications.afterOverwrites(bits, held, me, this.guild(), overwrites);
1012
+ const has = (names) => {
1013
+ const bit = BigInt(permissions(names));
1014
+ return (now & bit) === bit;
1015
+ };
1016
+ return {
1017
+ post: has([
1018
+ "ViewChannel",
1019
+ "CreatePublicThreads",
1020
+ "SendMessagesInThreads"
1021
+ ]),
1022
+ manage: has(["ManageThreads"])
1023
+ };
1024
+ }
1025
+ /**
915
1026
  * Whether a channel's own overwrites take a permission away from a bot whose roles grant it, in the order Discord
916
1027
  * applies them: @everyone, then the bot's roles, then the bot itself. Read fresh, since a person may have just edited them.
917
1028
  */
@@ -919,16 +1030,8 @@ var DiscordNotifications = class DiscordNotifications {
919
1030
  const { owner, bits, held, me } = await this.serverPermissions();
920
1031
  const bit = BigInt(permissions([permission]));
921
1032
  if (owner || (bits & BigInt(permissions(["Administrator"]))) !== 0n || (bits & bit) !== bit) return false;
922
- const list = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId)?.permission_overwrites ?? [];
923
- const apply = (now, found) => {
924
- const deny = found.reduce((all, o) => all | BigInt(o.deny), 0n);
925
- const allow = found.reduce((all, o) => all | BigInt(o.allow), 0n);
926
- return now & ~deny | allow;
927
- };
928
- let now = apply(bits, list.filter((o) => o.id === this.guild()));
929
- now = apply(now, list.filter((o) => o.type === 0 && o.id !== this.guild() && held.has(o.id)));
930
- now = apply(now, list.filter((o) => o.type === 1 && o.id === me));
931
- return (now & bit) !== bit;
1033
+ const channel = (await this.bot().guilds.channels(this.guild())).find((c) => c.id === channelId);
1034
+ return (DiscordNotifications.afterOverwrites(bits, held, me, this.guild(), channel?.permission_overwrites ?? []) & bit) !== bit;
932
1035
  }
933
1036
  /** The messages this bot posted in a channel, pinned or not, among the channel's last hundred. */
934
1037
  async ownMessages(channelId) {
@@ -1034,6 +1137,18 @@ var DiscordNotifications = class DiscordNotifications {
1034
1137
  updateDiscussion(channel, key, patch) {
1035
1138
  return this.discussions().update(channel, key, patch);
1036
1139
  }
1140
+ /** Appends a message to a document's post, reopening and closing it again if it was closed. */
1141
+ postDiscussionMessage(channel, key, content, opts) {
1142
+ return this.discussions().post(channel, key, content, opts);
1143
+ }
1144
+ /** The text of a post's recent messages, newest first. */
1145
+ readDiscussionMessages(channel, key, limit) {
1146
+ return this.discussions().messages(channel, key, limit);
1147
+ }
1148
+ /** Keeps the oldest post for `key` and deletes the others; returns how many it deleted. */
1149
+ dedupeDiscussion(channel, key) {
1150
+ return this.discussions().dedupe(channel, key);
1151
+ }
1037
1152
  /**
1038
1153
  * Posts `content` (up to 2000 characters) in a text channel as the bot, without letting it mention anyone. A `#name`
1039
1154
  * that is one of the server's channels is linked.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.356",
3
+ "version": "5.0.0-alpha.358",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -41,19 +41,19 @@
41
41
  "tsx": "4.23.15",
42
42
  "typescript": "^5.9.3",
43
43
  "vitest": "^5.0.5",
44
- "@theholocron/cli": "5.0.0-alpha.356",
45
- "@theholocron/eslint-config": "^8.9.0-alpha.9",
46
- "@theholocron/discord-client": "^1.58.0-alpha.12",
47
- "@theholocron/http-client": "^1.58.0-alpha.12",
44
+ "@theholocron/cli": "5.0.0-alpha.358",
45
+ "@theholocron/discord-client": "^1.58.0-alpha.13",
46
+ "@theholocron/misc-utils": "^1.17.0-alpha.1",
48
47
  "@theholocron/tsconfig": "^8.9.0-alpha.9",
49
- "@theholocron/tsdown-config": "^8.9.0-alpha.9",
48
+ "@theholocron/eslint-config": "^8.9.0-alpha.9",
50
49
  "@theholocron/vitest-config": "^8.9.0-alpha.9",
51
- "@theholocron/misc-utils": "^1.17.0-alpha.1"
50
+ "@theholocron/tsdown-config": "^8.9.0-alpha.9",
51
+ "@theholocron/http-client": "^1.58.0-alpha.13"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@theholocron/discord-client": "^1.50.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.356"
56
+ "@theholocron/cli": "5.0.0-alpha.358"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"