@theholocron/holocron-plugin-discord 5.0.0-alpha.188 → 5.0.0-alpha.189

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
@@ -1,4 +1,4 @@
1
- import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
1
+ import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
2
  import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
3
3
  //#region src/auth.d.ts
4
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
@@ -53,6 +53,24 @@ declare class DiscordNotifications implements Notifications {
53
53
  */
54
54
  inspect(layout: NotificationsLayout): Promise<ServerInspection>;
55
55
  validateLayout(layout: NotificationsLayout): string | undefined;
56
+ private botUser?;
57
+ private botId;
58
+ /**
59
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
60
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
61
+ */
62
+ private overwritesFor;
63
+ /**
64
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
65
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
66
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
67
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
68
+ * rather than guessed at.
69
+ */
70
+ private accessOf;
71
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
72
+ private roleLoad?;
73
+ private roleList;
56
74
  private guild;
57
75
  /**
58
76
  * The server's channel list, fetched once per instance. Every ensure* call used
@@ -74,7 +92,15 @@ declare class DiscordNotifications implements Notifications {
74
92
  */
75
93
  private createChannel;
76
94
  private static same;
77
- ensureCategory(name: string): Promise<EnsuredResource>;
95
+ ensureCategory(name: string, opts?: {
96
+ access?: NotificationsAccess;
97
+ }): Promise<EnsuredResource>;
98
+ /**
99
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
100
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
101
+ * sent, something else changed it at the same time, so say so instead of reporting success.
102
+ */
103
+ private modifyChannel;
78
104
  /**
79
105
  * Find a channel by name. A name can exist in several categories, so with a
80
106
  * parent: prefer the one already there, then an uncategorised one (moved in);
@@ -86,6 +112,7 @@ declare class DiscordNotifications implements Notifications {
86
112
  name: string;
87
113
  category?: string;
88
114
  topic?: string;
115
+ access?: NotificationsAccess;
89
116
  }): Promise<EnsuredResource>;
90
117
  ensureWebhook(input: {
91
118
  channel: string;
package/dist/index.mjs CHANGED
@@ -29,6 +29,25 @@ function colorToHex(color) {
29
29
  function reason(err) {
30
30
  return err instanceof ProviderApiError && err.details ? `${errorMessage(err)}: ${String(err.details).slice(0, 200)}` : errorMessage(err);
31
31
  }
32
+ /** What @everyone loses when a channel is read-only: sending, and starting or posting in threads. */
33
+ const POST = [
34
+ "SendMessages",
35
+ "SendMessagesInThreads",
36
+ "CreatePublicThreads",
37
+ "CreatePrivateThreads"
38
+ ];
39
+ /** What the bot keeps in a channel it has locked down, so it can still manage it and post. */
40
+ const BOT_KEEPS = [
41
+ "ViewChannel",
42
+ "SendMessages",
43
+ "ReadMessageHistory",
44
+ "ManageChannels",
45
+ "ManageWebhooks"
46
+ ];
47
+ /** Overwrites as a comparable set: order and the shape of the array do not matter. */
48
+ function overwriteKey(list) {
49
+ return (list ?? []).map((o) => `${o.id}:${o.type}:${o.allow}:${o.deny}`).sort().join("|");
50
+ }
32
51
  var DiscordNotifications = class DiscordNotifications {
33
52
  client;
34
53
  opts;
@@ -112,8 +131,15 @@ var DiscordNotifications = class DiscordNotifications {
112
131
  } catch (err) {
113
132
  rolesError = reason(err);
114
133
  }
134
+ const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
135
+ found.forEach((entry, i) => {
136
+ entry.access = this.accessOf(text[i].permission_overwrites, roleName);
137
+ });
138
+ const categoryAccess = {};
139
+ for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
115
140
  return {
116
141
  categories: [...categoryName.values()],
142
+ categoryAccess,
117
143
  channels: found,
118
144
  roles,
119
145
  ...rolesError ? { rolesError } : {}
@@ -127,6 +153,96 @@ var DiscordNotifications = class DiscordNotifications {
127
153
  return `role \`${role.name}\`: ${errorMessage(err)}`;
128
154
  }
129
155
  }
156
+ botUser;
157
+ botId() {
158
+ return this.botUser ??= this.bot().users.me().then((u) => u.id).catch((err) => {
159
+ this.botUser = void 0;
160
+ throw err;
161
+ });
162
+ }
163
+ /**
164
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
165
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
166
+ */
167
+ async overwritesFor(access) {
168
+ const view = access.view ?? "everyone";
169
+ const post = access.post ?? "everyone";
170
+ const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
171
+ if (everyoneDeny.length === 0) return [];
172
+ const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
173
+ const idOf = (name) => {
174
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
175
+ if (found.length === 0) throw new Error(`access names the role \`${name}\`, which does not exist on the server yet`);
176
+ if (found.length > 1) throw new Error(`access names the role \`${name}\`, but ${found.length} roles have that name (ids ${found.map((r) => r.id).join(", ")}) -- delete or rename the extras`);
177
+ return found[0].id;
178
+ };
179
+ const allow = /* @__PURE__ */ new Map();
180
+ const grant = (roleName, names) => {
181
+ const id = idOf(roleName);
182
+ allow.set(id, [.../* @__PURE__ */ new Set([...allow.get(id) ?? [], ...names])]);
183
+ };
184
+ if (view !== "everyone") for (const r of view) grant(r, ["ViewChannel"]);
185
+ if (post !== "everyone") for (const r of post) grant(r, POST);
186
+ return [
187
+ {
188
+ id: this.guild(),
189
+ type: 0,
190
+ allow: "0",
191
+ deny: permissions(everyoneDeny)
192
+ },
193
+ ...[...allow].map(([id, names]) => ({
194
+ id,
195
+ type: 0,
196
+ allow: permissions(names),
197
+ deny: "0"
198
+ })),
199
+ {
200
+ id: await this.botId(),
201
+ type: 1,
202
+ allow: permissions(BOT_KEEPS),
203
+ deny: "0"
204
+ }
205
+ ];
206
+ }
207
+ /**
208
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
209
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
210
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
211
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
212
+ * rather than guessed at.
213
+ */
214
+ accessOf(overwrites, roleName) {
215
+ const list = overwrites ?? [];
216
+ const managed = permissions(["ViewChannel", ...POST]);
217
+ const within = (bits) => (BigInt(bits) & ~BigInt(managed)) === 0n;
218
+ const postOf = (bits) => {
219
+ const have = POST.filter((b) => permissionNames(bits).includes(b)).length;
220
+ return have === 0 ? "none" : have === POST.length ? "all" : "some";
221
+ };
222
+ const botSignature = permissions(BOT_KEEPS);
223
+ let everyone;
224
+ const roles = [];
225
+ for (const o of list) if (o.type === 1) {
226
+ if (o.allow !== botSignature || o.deny !== "0") return "custom";
227
+ } else if (o.id === this.guild()) everyone = o;
228
+ else roles.push(o);
229
+ if (everyone && (everyone.allow !== "0" || !within(everyone.deny) || postOf(everyone.deny) === "some")) return "custom";
230
+ for (const o of roles) if (o.deny !== "0" || !within(o.allow) || postOf(o.allow) === "some") return "custom";
231
+ const denied = (bit) => everyone !== void 0 && permissionNames(everyone.deny).includes(bit);
232
+ const names = (bit) => roles.filter((o) => permissionNames(o.allow).includes(bit)).map((o) => roleName(o.id));
233
+ return {
234
+ view: denied("ViewChannel") ? names("ViewChannel") : "everyone",
235
+ post: denied("SendMessages") ? names("SendMessages") : "everyone"
236
+ };
237
+ }
238
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
239
+ roleLoad;
240
+ roleList() {
241
+ return this.roleLoad ??= this.bot().guilds.roles(this.guild()).catch((err) => {
242
+ this.roleLoad = void 0;
243
+ throw err;
244
+ });
245
+ }
130
246
  guild() {
131
247
  if (!this.opts.guildId) throw new Error("no Discord server id — set `guildId` in the discord provider options in holocron.config.ts");
132
248
  return this.opts.guildId;
@@ -167,21 +283,52 @@ var DiscordNotifications = class DiscordNotifications {
167
283
  static same(a, b) {
168
284
  return a.toLowerCase() === b.toLowerCase();
169
285
  }
170
- async ensureCategory(name) {
286
+ async ensureCategory(name, opts = {}) {
171
287
  const existing = (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, name));
172
- if (existing) return {
173
- id: existing.id,
174
- created: false
175
- };
288
+ const overwrites = opts.access ? await this.overwritesFor(opts.access) : void 0;
289
+ if (existing) {
290
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
291
+ await this.modifyChannel(existing, { permission_overwrites: overwrites });
292
+ return {
293
+ id: existing.id,
294
+ created: false,
295
+ updated: ["access"]
296
+ };
297
+ }
298
+ return {
299
+ id: existing.id,
300
+ created: false
301
+ };
302
+ }
176
303
  return {
177
304
  id: (await this.createChannel({
178
305
  name,
179
- type: ChannelType.Category
306
+ type: ChannelType.Category,
307
+ ...overwrites ? { permission_overwrites: overwrites } : {}
180
308
  })).id,
181
309
  created: true
182
310
  };
183
311
  }
184
312
  /**
313
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
314
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
315
+ * sent, something else changed it at the same time, so say so instead of reporting success.
316
+ */
317
+ async modifyChannel(channel, patch) {
318
+ let after;
319
+ try {
320
+ after = await this.bot().channels.modify(channel.id, patch);
321
+ } catch (err) {
322
+ this.channelLoad = void 0;
323
+ throw err;
324
+ }
325
+ if (patch.permission_overwrites && overwriteKey(after.permission_overwrites) !== overwriteKey(patch.permission_overwrites)) {
326
+ this.channelLoad = void 0;
327
+ throw new Error(`\`${channel.name}\`: sent its access but the channel came back different -- another setup run may be changing it at the same time; re-run once it has finished`);
328
+ }
329
+ Object.assign(channel, patch);
330
+ }
331
+ /**
185
332
  * Find a channel by name. A name can exist in several categories, so with a
186
333
  * parent: prefer the one already there, then an uncategorised one (moved in);
187
334
  * never grab a channel that lives under a different category. Announcement
@@ -193,26 +340,29 @@ var DiscordNotifications = class DiscordNotifications {
193
340
  return named.find((c) => c.parent_id === parentId) ?? named.find((c) => !c.parent_id);
194
341
  }
195
342
  async ensureChannel(input) {
196
- const bot = this.bot();
197
343
  const parent = input.category ? (await this.ensureCategory(input.category)).id : void 0;
198
344
  const existing = DiscordNotifications.findChannel(await this.channelList(), input.name, parent);
345
+ const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
199
346
  if (existing) {
200
- const patch = {
201
- ...parent && existing.parent_id !== parent ? { parent_id: parent } : {},
202
- ...input.topic !== void 0 && (existing.topic ?? "") !== input.topic ? { topic: input.topic } : {}
203
- };
204
- if (Object.keys(patch).length > 0) {
205
- try {
206
- await bot.channels.modify(existing.id, patch);
207
- } catch (err) {
208
- this.channelLoad = void 0;
209
- throw err;
210
- }
211
- Object.assign(existing, patch);
347
+ const updated = [];
348
+ const patch = {};
349
+ if (parent && existing.parent_id !== parent) {
350
+ patch.parent_id = parent;
351
+ updated.push("category");
352
+ }
353
+ if (input.topic !== void 0 && (existing.topic ?? "") !== input.topic) {
354
+ patch.topic = input.topic;
355
+ updated.push("topic");
356
+ }
357
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
358
+ patch.permission_overwrites = overwrites;
359
+ updated.push("access");
212
360
  }
361
+ if (updated.length > 0) await this.modifyChannel(existing, patch);
213
362
  return {
214
363
  id: existing.id,
215
- created: false
364
+ created: false,
365
+ ...updated.length > 0 ? { updated } : {}
216
366
  };
217
367
  }
218
368
  return {
@@ -220,7 +370,8 @@ var DiscordNotifications = class DiscordNotifications {
220
370
  name: input.name,
221
371
  type: ChannelType.Text,
222
372
  ...input.topic ? { topic: input.topic } : {},
223
- ...parent ? { parent_id: parent } : {}
373
+ ...parent ? { parent_id: parent } : {},
374
+ ...overwrites ? { permission_overwrites: overwrites } : {}
224
375
  })).id,
225
376
  created: true
226
377
  };
@@ -268,6 +419,7 @@ var DiscordNotifications = class DiscordNotifications {
268
419
  updated.push("permissions");
269
420
  }
270
421
  if (updated.length > 0) {
422
+ this.roleLoad = void 0;
271
423
  const after = await bot.guilds.modifyRole(this.guild(), existing.id, patch);
272
424
  const stuck = [
273
425
  [
@@ -299,6 +451,7 @@ var DiscordNotifications = class DiscordNotifications {
299
451
  ...updated.length > 0 ? { updated } : {}
300
452
  };
301
453
  }
454
+ this.roleLoad = void 0;
302
455
  const made = await bot.guilds.createRole(this.guild(), {
303
456
  name: input.name,
304
457
  ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.188",
3
+ "version": "5.0.0-alpha.189",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -48,12 +48,12 @@
48
48
  "tsx": "4.23.15",
49
49
  "typescript": "^5.9.3",
50
50
  "vitest": "^4.1.11",
51
- "@theholocron/cli": "5.0.0-alpha.188"
51
+ "@theholocron/cli": "5.0.0-alpha.189"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@theholocron/discord-client": "^1.44.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.188"
56
+ "@theholocron/cli": "5.0.0-alpha.189"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"