@theholocron/holocron-plugin-discord 5.0.0-alpha.19 → 5.0.0-alpha.190

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/README.md CHANGED
@@ -61,3 +61,25 @@ server membership is required — generate one in Discord under
61
61
  The webhook id and token are embedded in the URL path — no `Authorization`
62
62
  header is sent. `parseWebhookUrl` is exported as a utility for callers
63
63
  that need to split the URL into its parts.
64
+
65
+ ## Provisioning
66
+
67
+ `holocron notifications setup` and `holocron notifications channel add` create
68
+ channels, roles and webhooks through the `notifications` capability's `ensure*`
69
+ methods. They use the **Holonet bot**, not a webhook URL:
70
+
71
+ - `HOLOCRON_DISCORD_BOT_TOKEN` (or `DISCORD_BOT_TOKEN`), or the keyring entry
72
+ `discord.holonet` (`holocron auth set discord.holonet <token>`) — the bot token
73
+ from the Developer Portal. Only read when a provisioning command runs, or when
74
+ `holocron doctor` checks a provider that has a `guildId`; posting never needs it.
75
+ - `guildId` — the server id (not a secret), set in the provider options.
76
+ - `layout` — categories, channels (each optionally with a `webhook`) and roles.
77
+
78
+ The bot needs Manage Channels, Manage Roles, Manage Webhooks and View Channels.
79
+ Everything is idempotent (looked up by name). Discord returns a webhook's URL
80
+ only to the application that created it, so a webhook the bot did not create
81
+ cannot have its URL read back.
82
+
83
+ `baseUrl` only redirects posting. The bot token is always sent to the real
84
+ Discord API unless `unsafeBotBaseUrl: true` is also set (meant for tests that
85
+ stub the API), so a changed config cannot redirect the token to another host.
package/dist/index.d.mts CHANGED
@@ -1,30 +1,8 @@
1
- import { AuthError, Notifications, ResolveTokenInput } from "@theholocron/cli";
1
+ import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
+ import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
2
3
  //#region src/auth.d.ts
3
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
4
- //#endregion
5
- //#region src/rest.d.ts
6
- interface DiscordClientOptions {
7
- /** Override base URL for tests. Default: https://discord.com/api/v10 */
8
- baseUrl?: string;
9
- fetch?: typeof fetch;
10
- }
11
- interface DiscordWebhookInfo {
12
- id: string;
13
- name: string;
14
- guild_id?: string;
15
- }
16
- interface DiscordClient {
17
- webhooks: {
18
- get(id: string, token: string): Promise<DiscordWebhookInfo>;
19
- execute(id: string, token: string, content: string): Promise<void>;
20
- };
21
- }
22
- declare function createDiscordClient({ baseUrl, fetch: fetchImpl }?: DiscordClientOptions): DiscordClient;
23
- /** Parse a Discord webhook URL into its id and token parts. */
24
- declare function parseWebhookUrl(url: string): {
25
- id: string;
26
- token: string;
27
- };
5
+ declare const resolveBotToken: (input?: ResolveTokenInput) => string;
28
6
  //#endregion
29
7
  //#region src/capabilities/notifications.d.ts
30
8
  interface DiscordNotificationsOptions {
@@ -38,42 +16,137 @@ interface DiscordNotificationsOptions {
38
16
  * without an explicit channel, or with an empty string.
39
17
  */
40
18
  defaultChannel?: string;
19
+ /** Discord server (guild) id that `notifications setup` provisions. Not a secret. */
20
+ guildId?: string;
21
+ /** The server layout `notifications setup` applies. */
22
+ layout?: NotificationsLayout;
41
23
  }
42
24
  declare class DiscordNotifications implements Notifications {
43
25
  private readonly client;
44
26
  private readonly opts;
45
27
  /** Memoized thunk — resolves the default webhook URL on the first `send()`. */
46
28
  private readonly defaultWebhookUrl;
29
+ /** Memoized thunk — resolves the bot token on first provisioning call, never on `send()`. */
30
+ private readonly bot;
47
31
  readonly key: "notifications";
48
32
  readonly providerName = "discord";
49
33
  constructor(client: DiscordClient, opts: DiscordNotificationsOptions,
50
34
  /** Memoized thunk — resolves the default webhook URL on the first `send()`. */
51
- defaultWebhookUrl: () => string);
35
+ defaultWebhookUrl: () => string,
36
+ /** Memoized thunk — resolves the bot token on first provisioning call, never on `send()`. */
37
+ bot?: () => DiscordBotClient);
38
+ get layout(): NotificationsLayout | undefined;
52
39
  send(channel: string, message: string): Promise<void>;
40
+ /**
41
+ * `holocron doctor`: the bot token is valid and can see the configured server.
42
+ * Null when no `guildId` is set -- a post-only config has no bot to check. A
43
+ * `layout` without a `guildId` is a half-written provisioning config, so that
44
+ * fails instead of passing as post-only.
45
+ */
46
+ whoami(): Promise<{
47
+ target: string;
48
+ } | null>;
49
+ /**
50
+ * Read-only: what is on the server, for the parts of `layout` we will compare. Webhooks are
51
+ * listed only for channels the layout gives one (one request each), so the cost scales with
52
+ * the layout, not with the server.
53
+ */
54
+ inspect(layout: NotificationsLayout): Promise<ServerInspection>;
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;
74
+ private guild;
75
+ /**
76
+ * The server's channel list, fetched once per instance. Every ensure* call used
77
+ * to refetch it -- about 40 identical GETs in one setup run -- and Discord
78
+ * rate-limited the route. Our own creates and edits update the copy, so it
79
+ * stays accurate for the run; a new run builds a new instance.
80
+ *
81
+ * It is the in-flight promise that is shared, not the array: callers that start
82
+ * while the first fetch is pending all get the same snapshot, so a later
83
+ * response can never overwrite what an earlier caller added.
84
+ */
85
+ private channelLoad?;
86
+ private channelList;
87
+ /**
88
+ * Create a channel and add it to the shared list. If the create fails, Discord
89
+ * may still have applied it (a timeout looks the same as a refusal), so forget the
90
+ * list: the next ensure refetches the server's real state instead of creating a
91
+ * duplicate.
92
+ */
93
+ private createChannel;
94
+ private static same;
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;
104
+ /**
105
+ * Find a channel by name. A name can exist in several categories, so with a
106
+ * parent: prefer the one already there, then an uncategorised one (moved in);
107
+ * never grab a channel that lives under a different category. Announcement
108
+ * channels count: reusing one beats creating a same-named text channel.
109
+ */
110
+ private static findChannel;
111
+ ensureChannel(input: {
112
+ name: string;
113
+ category?: string;
114
+ topic?: string;
115
+ access?: NotificationsAccess;
116
+ }): Promise<EnsuredResource>;
117
+ ensureWebhook(input: {
118
+ channel: string;
119
+ name: string;
120
+ category?: string;
121
+ }): Promise<EnsureWebhookResult>;
122
+ ensureRole(input: {
123
+ name: string;
124
+ mentionable?: boolean;
125
+ color?: string;
126
+ hoist?: boolean;
127
+ permissions?: string[];
128
+ }): Promise<EnsuredResource>;
53
129
  private resolve;
54
130
  }
55
131
  //#endregion
56
132
  //#region src/verify-token.d.ts
57
- interface VerifyTokenSuccess {
58
- ok: true;
59
- subject: string;
60
- }
61
- interface VerifyTokenFailure {
62
- ok: false;
63
- message: string;
64
- }
65
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
66
133
  interface VerifyTokenOptions {
67
134
  baseUrl?: string;
68
135
  fetch?: typeof fetch;
69
136
  }
70
- declare function verifyToken(webhookUrl: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
137
+ declare function verifyToken(webhookUrl: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
71
138
  //#endregion
72
139
  //#region src/index.d.ts
73
140
  interface DiscordPluginOptions extends ResolveTokenInput, DiscordNotificationsOptions {
74
141
  /** Override base URL for tests. Default: https://discord.com/api/v10 */
75
142
  baseUrl?: string;
76
143
  fetch?: typeof fetch;
144
+ /**
145
+ * Also send the BOT token to `baseUrl`. Off by default: `baseUrl` comes from a
146
+ * repo's config, and a changed config must not be able to redirect the bot
147
+ * token to another host. Tests that stub the API set it.
148
+ */
149
+ unsafeBotBaseUrl?: boolean;
77
150
  }
78
151
  interface PluginContext {
79
152
  options: DiscordPluginOptions;
@@ -83,6 +156,8 @@ interface PluginContext {
83
156
  * resolved on first `send()`, not at plugin load. `describe()` never calls it.
84
157
  */
85
158
  defaultWebhookUrl: () => string;
159
+ /** Memoized — resolves the bot token on the first provisioning call, or when `holocron doctor` checks a provider that has a `guildId`; `send()` and `describe()` never touch it. */
160
+ bot: () => DiscordBotClient;
86
161
  }
87
162
  declare function createContext(options?: DiscordPluginOptions): PluginContext;
88
163
  declare function notifications(ctx: PluginContext): Notifications;
@@ -94,4 +169,4 @@ declare function createPlugin(options?: DiscordPluginOptions): {
94
169
  };
95
170
  declare const AUTH_HINT: string;
96
171
  //#endregion
97
- export { AUTH_HINT, AuthError, type DiscordClient, type DiscordClientOptions, DiscordNotifications, type DiscordNotificationsOptions, DiscordPluginOptions, type DiscordWebhookInfo, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveToken, verifyToken };
172
+ export { AUTH_HINT, AuthError, type DiscordClient, type DiscordClientOptions, DiscordNotifications, type DiscordNotificationsOptions, DiscordPluginOptions, type DiscordWebhookInfo, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveToken, verifyToken };
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
2
+ import { errorMessage } from "@theholocron/misc-utils";
3
+ import { ChannelType, createDiscordBotClient, createDiscordClient, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
2
4
  //#region src/auth.ts
3
5
  const resolveToken = createResolveToken({
4
6
  envName: "HOLOCRON_DISCORD_WEBHOOK",
@@ -6,53 +8,498 @@ const resolveToken = createResolveToken({
6
8
  keyringService: "discord",
7
9
  errorMessage: "no Discord webhook URL found. Pass --token <WEBHOOK_URL>, set HOLOCRON_DISCORD_WEBHOOK / DISCORD_WEBHOOK_URL, or run: holocron auth set discord <https://discord.com/api/webhooks/...>"
8
10
  });
11
+ const resolveBotToken = createResolveToken({
12
+ envName: "HOLOCRON_DISCORD_BOT_TOKEN",
13
+ vendorEnvName: "DISCORD_BOT_TOKEN",
14
+ keyringService: "discord.holonet",
15
+ errorMessage: "no Discord bot token found. Set HOLOCRON_DISCORD_BOT_TOKEN (or DISCORD_BOT_TOKEN), or run: holocron auth set discord.holonet <token> — it is the bot token from the Discord developer portal (Bot → Reset Token), not a webhook URL."
16
+ });
9
17
  //#endregion
10
- //#region src/rest.ts
11
- function createDiscordClient({ baseUrl, fetch: fetchImpl } = {}) {
12
- const base = baseUrl ?? "https://discord.com/api/v10";
13
- const f = fetchImpl ?? globalThis.fetch;
14
- return { webhooks: {
15
- get: async (id, token) => {
16
- const res = await f(`${base}/webhooks/${id}/${token}`, { method: "GET" });
17
- if (!res.ok) throw new ProviderApiError(`Discord webhook not found or invalid (${res.status})`, res.status, void 0);
18
- return res.json();
19
- },
20
- execute: async (id, token, content) => {
21
- const res = await f(`${base}/webhooks/${id}/${token}`, {
22
- method: "POST",
23
- headers: { "content-type": "application/json" },
24
- body: JSON.stringify({ content })
25
- });
26
- if (!res.ok) throw new ProviderApiError(`Discord webhook POST failed (${res.status})`, res.status, void 0);
27
- }
28
- } };
18
+ //#region src/capabilities/notifications.ts
19
+ /** `#rrggbb` to Discord's integer colour. */
20
+ function colorToInt(hex) {
21
+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`invalid colour ${JSON.stringify(hex)}: use #rrggbb`);
22
+ return Number.parseInt(hex.slice(1), 16);
29
23
  }
30
- /** Parse a Discord webhook URL into its id and token parts. */
31
- function parseWebhookUrl(url) {
32
- const match = url.match(/webhooks\/(\d+)\/([^/?#]+)/);
33
- if (!match) throw new Error(`Invalid Discord webhook URL: ${url}`);
34
- return {
35
- id: match[1],
36
- token: match[2]
37
- };
24
+ /** Discord's integer colour to `#rrggbb`. 0 is Discord's "no colour", and is what `#000000` means too. */
25
+ function colorToHex(color) {
26
+ return `#${color.toString(16).padStart(6, "0")}`;
38
27
  }
39
- //#endregion
40
- //#region src/capabilities/notifications.ts
41
- var DiscordNotifications = class {
28
+ /** An error as one line: the message, plus Discord's own response body when there is one. */
29
+ function reason(err) {
30
+ return err instanceof ProviderApiError && err.details ? `${errorMessage(err)}: ${String(err.details).slice(0, 200)}` : errorMessage(err);
31
+ }
32
+ /**
33
+ * What @everyone loses when a channel is read-only. Only sending: Discord refuses (403) any change to the
34
+ * thread permissions on an existing text channel from a bot whose own role lacks them, and Holonet's
35
+ * does. Members can therefore still start threads in a read-only channel until the bot is given those
36
+ * permissions; see {@link THREAD_BITS} for how channels that already carry them are read.
37
+ */
38
+ const POST = ["SendMessages"];
39
+ const THREAD_MASK = ~BigInt(permissions([
40
+ "SendMessagesInThreads",
41
+ "CreatePublicThreads",
42
+ "CreatePrivateThreads"
43
+ ]));
44
+ /** What the bot keeps in a channel it has locked down, so it can still manage it and post. */
45
+ const BOT_KEEPS = [
46
+ "ViewChannel",
47
+ "SendMessages",
48
+ "ReadMessageHistory",
49
+ "ManageChannels",
50
+ "ManageWebhooks"
51
+ ];
52
+ /**
53
+ * Overwrites as a comparable set: order and the shape of the array do not matter, and the thread
54
+ * permissions are left out (setup does not manage them, so their presence is not a difference).
55
+ */
56
+ function overwriteKey(list) {
57
+ return (list ?? []).map((o) => ({
58
+ ...o,
59
+ allow: BigInt(o.allow) & THREAD_MASK,
60
+ deny: BigInt(o.deny) & THREAD_MASK
61
+ })).filter((o) => o.allow !== 0n || o.deny !== 0n).map((o) => `${o.id}:${o.type}:${o.allow}:${o.deny}`).sort().join("|");
62
+ }
63
+ /**
64
+ * Desired overwrites with the thread permissions of the existing ones laid back in. Discord refuses
65
+ * any change to those from this bot, so a replacement list must carry them over untouched or the
66
+ * whole edit is rejected, even when it changes nothing but what we do manage.
67
+ */
68
+ function keepThreadBits(desired, existing) {
69
+ const threads = ~THREAD_MASK;
70
+ const merged = desired.map((o) => ({ ...o }));
71
+ for (const old of existing ?? []) {
72
+ const allow = BigInt(old.allow) & threads;
73
+ const deny = BigInt(old.deny) & threads;
74
+ if (allow === 0n && deny === 0n) continue;
75
+ const same = merged.find((o) => o.id === old.id && o.type === old.type);
76
+ if (same) {
77
+ same.allow = (BigInt(same.allow) | allow).toString();
78
+ same.deny = (BigInt(same.deny) | deny).toString();
79
+ } else merged.push({
80
+ id: old.id,
81
+ type: old.type,
82
+ allow: allow.toString(),
83
+ deny: deny.toString()
84
+ });
85
+ }
86
+ return merged;
87
+ }
88
+ var DiscordNotifications = class DiscordNotifications {
42
89
  client;
43
90
  opts;
44
91
  defaultWebhookUrl;
92
+ bot;
45
93
  key = "notifications";
46
94
  providerName = "discord";
47
- constructor(client, opts, defaultWebhookUrl) {
95
+ constructor(client, opts, defaultWebhookUrl, bot = () => {
96
+ throw new Error("no Discord bot client configured");
97
+ }) {
48
98
  this.client = client;
49
99
  this.opts = opts;
50
100
  this.defaultWebhookUrl = defaultWebhookUrl;
101
+ this.bot = bot;
102
+ }
103
+ get layout() {
104
+ return this.opts.layout;
51
105
  }
52
106
  async send(channel, message) {
53
- const { id, token } = parseWebhookUrl(this.resolve(channel || this.opts.defaultChannel || ""));
107
+ const webhookUrl = this.resolve(channel || this.opts.defaultChannel || "");
108
+ const { id, token } = parseWebhookUrl(webhookUrl);
54
109
  await this.client.webhooks.execute(id, token, message);
55
110
  }
111
+ /**
112
+ * `holocron doctor`: the bot token is valid and can see the configured server.
113
+ * Null when no `guildId` is set -- a post-only config has no bot to check. A
114
+ * `layout` without a `guildId` is a half-written provisioning config, so that
115
+ * fails instead of passing as post-only.
116
+ */
117
+ async whoami() {
118
+ if (!this.opts.guildId) {
119
+ if (this.opts.layout) throw new Error("`layout` is set but `guildId` is not — add the server id to the discord provider options");
120
+ return null;
121
+ }
122
+ const bot = this.bot();
123
+ const me = await bot.users.me();
124
+ return { target: `${(await bot.guilds.get(this.opts.guildId)).name} (as ${me.username})` };
125
+ }
126
+ /**
127
+ * Read-only: what is on the server, for the parts of `layout` we will compare. Webhooks are
128
+ * listed only for channels the layout gives one (one request each), so the cost scales with
129
+ * the layout, not with the server.
130
+ */
131
+ async inspect(layout) {
132
+ const bot = this.bot();
133
+ const channels = await this.channelList();
134
+ const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
135
+ const wantsWebhook = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.webhook).map((ch) => ch.name.toLowerCase())));
136
+ const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement);
137
+ const found = [];
138
+ for (const c of text) {
139
+ let webhooks = [];
140
+ let webhooksError;
141
+ if (wantsWebhook.has(c.name.toLowerCase())) try {
142
+ webhooks = (await bot.channels.webhooks(c.id)).map((w) => w.name ?? "");
143
+ } catch (err) {
144
+ webhooksError = reason(err);
145
+ }
146
+ const category = c.parent_id ? categoryName.get(c.parent_id) : void 0;
147
+ found.push({
148
+ name: c.name,
149
+ ...category ? { category } : {},
150
+ ...c.topic ? { topic: c.topic } : {},
151
+ webhooks,
152
+ ...webhooksError ? { webhooksError } : {}
153
+ });
154
+ }
155
+ let roles = [];
156
+ let rolesError;
157
+ if ((layout.roles ?? []).length > 0) try {
158
+ roles = (await bot.guilds.roles(this.guild())).map((r) => {
159
+ return {
160
+ name: r.name,
161
+ id: r.id,
162
+ mentionable: r.mentionable,
163
+ color: colorToHex(r.color),
164
+ ...r.hoist !== void 0 ? { hoist: r.hoist } : {},
165
+ ...r.permissions !== void 0 ? { permissions: permissionNames(r.permissions) } : {}
166
+ };
167
+ });
168
+ } catch (err) {
169
+ rolesError = reason(err);
170
+ }
171
+ const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
172
+ found.forEach((entry, i) => {
173
+ entry.access = this.accessOf(text[i].permission_overwrites, roleName);
174
+ });
175
+ const categoryAccess = {};
176
+ for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
177
+ return {
178
+ categories: [...categoryName.values()],
179
+ categoryAccess,
180
+ channels: found,
181
+ roles,
182
+ ...rolesError ? { rolesError } : {}
183
+ };
184
+ }
185
+ validateLayout(layout) {
186
+ for (const role of layout.roles ?? []) try {
187
+ if (role.color !== void 0) colorToInt(role.color);
188
+ if (role.permissions !== void 0) permissions(role.permissions);
189
+ } catch (err) {
190
+ return `role \`${role.name}\`: ${errorMessage(err)}`;
191
+ }
192
+ }
193
+ botUser;
194
+ botId() {
195
+ return this.botUser ??= this.bot().users.me().then((u) => u.id).catch((err) => {
196
+ this.botUser = void 0;
197
+ throw err;
198
+ });
199
+ }
200
+ /**
201
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
202
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
203
+ */
204
+ async overwritesFor(access) {
205
+ const view = access.view ?? "everyone";
206
+ const post = access.post ?? "everyone";
207
+ const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
208
+ if (everyoneDeny.length === 0) return [];
209
+ const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
210
+ const idOf = (name) => {
211
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
212
+ if (found.length === 0) throw new Error(`access names the role \`${name}\`, which does not exist on the server yet`);
213
+ 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`);
214
+ return found[0].id;
215
+ };
216
+ const allow = /* @__PURE__ */ new Map();
217
+ const grant = (roleName, names) => {
218
+ const id = idOf(roleName);
219
+ allow.set(id, [.../* @__PURE__ */ new Set([...allow.get(id) ?? [], ...names])]);
220
+ };
221
+ if (view !== "everyone") for (const r of view) grant(r, ["ViewChannel"]);
222
+ if (post !== "everyone") for (const r of post) grant(r, POST);
223
+ return [
224
+ {
225
+ id: this.guild(),
226
+ type: 0,
227
+ allow: "0",
228
+ deny: permissions(everyoneDeny)
229
+ },
230
+ ...[...allow].map(([id, names]) => ({
231
+ id,
232
+ type: 0,
233
+ allow: permissions(names),
234
+ deny: "0"
235
+ })),
236
+ {
237
+ id: await this.botId(),
238
+ type: 1,
239
+ allow: permissions(BOT_KEEPS),
240
+ deny: "0"
241
+ }
242
+ ];
243
+ }
244
+ /**
245
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
246
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
247
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
248
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
249
+ * rather than guessed at.
250
+ */
251
+ accessOf(overwrites, roleName) {
252
+ const list = overwrites ?? [];
253
+ const managed = permissions(["ViewChannel", ...POST]);
254
+ const unthreaded = (bits) => BigInt(bits) & THREAD_MASK;
255
+ const within = (bits) => (unthreaded(bits) & ~BigInt(managed)) === 0n;
256
+ const botSignature = permissions(BOT_KEEPS);
257
+ let everyone;
258
+ const roles = [];
259
+ for (const o of list) if (o.type === 1) {
260
+ if (o.allow !== botSignature || o.deny !== "0") return "custom";
261
+ } else if (o.id === this.guild()) everyone = o;
262
+ else roles.push(o);
263
+ if (everyone && (unthreaded(everyone.allow) !== 0n || !within(everyone.deny))) return "custom";
264
+ for (const o of roles) if (unthreaded(o.deny) !== 0n || !within(o.allow)) return "custom";
265
+ const denied = (bit) => everyone !== void 0 && permissionNames(everyone.deny).includes(bit);
266
+ const names = (bit) => roles.filter((o) => permissionNames(o.allow).includes(bit)).map((o) => roleName(o.id));
267
+ return {
268
+ view: denied("ViewChannel") ? names("ViewChannel") : "everyone",
269
+ post: denied("SendMessages") ? names("SendMessages") : "everyone"
270
+ };
271
+ }
272
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
273
+ roleLoad;
274
+ roleList() {
275
+ return this.roleLoad ??= this.bot().guilds.roles(this.guild()).catch((err) => {
276
+ this.roleLoad = void 0;
277
+ throw err;
278
+ });
279
+ }
280
+ guild() {
281
+ if (!this.opts.guildId) throw new Error("no Discord server id — set `guildId` in the discord provider options in holocron.config.ts");
282
+ return this.opts.guildId;
283
+ }
284
+ /**
285
+ * The server's channel list, fetched once per instance. Every ensure* call used
286
+ * to refetch it -- about 40 identical GETs in one setup run -- and Discord
287
+ * rate-limited the route. Our own creates and edits update the copy, so it
288
+ * stays accurate for the run; a new run builds a new instance.
289
+ *
290
+ * It is the in-flight promise that is shared, not the array: callers that start
291
+ * while the first fetch is pending all get the same snapshot, so a later
292
+ * response can never overwrite what an earlier caller added.
293
+ */
294
+ channelLoad;
295
+ channelList() {
296
+ return this.channelLoad ??= this.bot().guilds.channels(this.guild()).catch((err) => {
297
+ this.channelLoad = void 0;
298
+ throw err;
299
+ });
300
+ }
301
+ /**
302
+ * Create a channel and add it to the shared list. If the create fails, Discord
303
+ * may still have applied it (a timeout looks the same as a refusal), so forget the
304
+ * list: the next ensure refetches the server's real state instead of creating a
305
+ * duplicate.
306
+ */
307
+ async createChannel(body) {
308
+ try {
309
+ const made = await this.bot().guilds.createChannel(this.guild(), body);
310
+ (await this.channelList()).push(made);
311
+ return made;
312
+ } catch (err) {
313
+ this.channelLoad = void 0;
314
+ throw err;
315
+ }
316
+ }
317
+ static same(a, b) {
318
+ return a.toLowerCase() === b.toLowerCase();
319
+ }
320
+ async ensureCategory(name, opts = {}) {
321
+ const existing = (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, name));
322
+ const overwrites = opts.access ? await this.overwritesFor(opts.access) : void 0;
323
+ if (existing) {
324
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
325
+ await this.modifyChannel(existing, { permission_overwrites: keepThreadBits(overwrites, existing.permission_overwrites) });
326
+ return {
327
+ id: existing.id,
328
+ created: false,
329
+ updated: ["access"]
330
+ };
331
+ }
332
+ return {
333
+ id: existing.id,
334
+ created: false
335
+ };
336
+ }
337
+ return {
338
+ id: (await this.createChannel({
339
+ name,
340
+ type: ChannelType.Category,
341
+ ...overwrites ? { permission_overwrites: overwrites } : {}
342
+ })).id,
343
+ created: true
344
+ };
345
+ }
346
+ /**
347
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
348
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
349
+ * sent, something else changed it at the same time, so say so instead of reporting success.
350
+ */
351
+ async modifyChannel(channel, patch) {
352
+ let after;
353
+ try {
354
+ after = await this.bot().channels.modify(channel.id, patch);
355
+ } catch (err) {
356
+ this.channelLoad = void 0;
357
+ throw err;
358
+ }
359
+ if (patch.permission_overwrites && overwriteKey(after.permission_overwrites) !== overwriteKey(patch.permission_overwrites)) {
360
+ this.channelLoad = void 0;
361
+ 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`);
362
+ }
363
+ Object.assign(channel, patch);
364
+ }
365
+ /**
366
+ * Find a channel by name. A name can exist in several categories, so with a
367
+ * parent: prefer the one already there, then an uncategorised one (moved in);
368
+ * never grab a channel that lives under a different category. Announcement
369
+ * channels count: reusing one beats creating a same-named text channel.
370
+ */
371
+ static findChannel(channels, name, parentId) {
372
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
373
+ if (!parentId) return named[0];
374
+ return named.find((c) => c.parent_id === parentId) ?? named.find((c) => !c.parent_id);
375
+ }
376
+ async ensureChannel(input) {
377
+ const parent = input.category ? (await this.ensureCategory(input.category)).id : void 0;
378
+ const existing = DiscordNotifications.findChannel(await this.channelList(), input.name, parent);
379
+ const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
380
+ if (existing) {
381
+ const updated = [];
382
+ const patch = {};
383
+ if (parent && existing.parent_id !== parent) {
384
+ patch.parent_id = parent;
385
+ updated.push("category");
386
+ }
387
+ if (input.topic !== void 0 && (existing.topic ?? "") !== input.topic) {
388
+ patch.topic = input.topic;
389
+ updated.push("topic");
390
+ }
391
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
392
+ patch.permission_overwrites = keepThreadBits(overwrites, existing.permission_overwrites);
393
+ updated.push("access");
394
+ }
395
+ if (updated.length > 0) await this.modifyChannel(existing, patch);
396
+ return {
397
+ id: existing.id,
398
+ created: false,
399
+ ...updated.length > 0 ? { updated } : {}
400
+ };
401
+ }
402
+ return {
403
+ id: (await this.createChannel({
404
+ name: input.name,
405
+ type: ChannelType.Text,
406
+ ...input.topic ? { topic: input.topic } : {},
407
+ ...parent ? { parent_id: parent } : {},
408
+ ...overwrites ? { permission_overwrites: overwrites } : {}
409
+ })).id,
410
+ created: true
411
+ };
412
+ }
413
+ async ensureWebhook(input) {
414
+ const bot = this.bot();
415
+ const parent = input.category ? (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, input.category))?.id : void 0;
416
+ const channel = DiscordNotifications.findChannel(await this.channelList(), input.channel, parent);
417
+ if (!channel) throw new Error(`no channel named \`${input.channel}\` — create it first`);
418
+ const existing = (await bot.channels.webhooks(channel.id)).find((w) => DiscordNotifications.same(w.name ?? "", input.name));
419
+ if (existing) return {
420
+ created: false,
421
+ ...existing.url ? { url: existing.url } : {}
422
+ };
423
+ const made = await bot.channels.createWebhook(channel.id, { name: input.name });
424
+ return {
425
+ created: true,
426
+ ...made.url ? { url: made.url } : {}
427
+ };
428
+ }
429
+ async ensureRole(input) {
430
+ const bot = this.bot();
431
+ const color = input.color !== void 0 ? colorToInt(input.color) : void 0;
432
+ const wanted = input.permissions !== void 0 ? permissions(input.permissions) : void 0;
433
+ const matches = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
434
+ if (matches.length > 1) throw new Error(`${matches.length} roles are named \`${input.name}\` (ids ${matches.map((r) => r.id).join(", ")}) — delete or rename the extras so setup knows which one to manage`);
435
+ const existing = matches[0];
436
+ if (existing) {
437
+ const patch = {};
438
+ const updated = [];
439
+ if (input.mentionable !== void 0 && existing.mentionable !== input.mentionable) {
440
+ patch.mentionable = input.mentionable;
441
+ updated.push("mentionable");
442
+ }
443
+ if (color !== void 0 && existing.color !== color) {
444
+ patch.color = color;
445
+ updated.push("colour");
446
+ }
447
+ if (input.hoist !== void 0 && (existing.hoist ?? false) !== input.hoist) {
448
+ patch.hoist = input.hoist;
449
+ updated.push("hoist");
450
+ }
451
+ if (wanted !== void 0 && existing.permissions !== wanted) {
452
+ patch.permissions = wanted;
453
+ updated.push("permissions");
454
+ }
455
+ if (updated.length > 0) {
456
+ this.roleLoad = void 0;
457
+ const after = await bot.guilds.modifyRole(this.guild(), existing.id, patch);
458
+ const stuck = [
459
+ [
460
+ "mentionable",
461
+ patch.mentionable,
462
+ after.mentionable
463
+ ],
464
+ [
465
+ "colour",
466
+ patch.color,
467
+ after.color
468
+ ],
469
+ [
470
+ "hoist",
471
+ patch.hoist,
472
+ after.hoist
473
+ ],
474
+ [
475
+ "permissions",
476
+ patch.permissions,
477
+ after.permissions
478
+ ]
479
+ ].filter(([, sent, now]) => sent !== void 0 && sent !== now).map(([name]) => name);
480
+ if (stuck.length > 0) throw new Error(`role \`${input.name}\`: sent ${stuck.join(", ")} but the role came back different -- another setup run may be changing it at the same time; re-run once it has finished`);
481
+ }
482
+ return {
483
+ id: existing.id,
484
+ created: false,
485
+ ...updated.length > 0 ? { updated } : {}
486
+ };
487
+ }
488
+ this.roleLoad = void 0;
489
+ const made = await bot.guilds.createRole(this.guild(), {
490
+ name: input.name,
491
+ ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {},
492
+ ...color !== void 0 ? { color } : {},
493
+ ...input.hoist !== void 0 ? { hoist: input.hoist } : {},
494
+ ...wanted !== void 0 ? { permissions: wanted } : {}
495
+ });
496
+ const twins = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
497
+ if (twins.length > 1) throw new Error(`created role \`${input.name}\` (id ${made.id}) but ${twins.length} roles now have that name (ids ${twins.map((r) => r.id).join(", ")}) -- another setup run probably created it at the same time; delete the extra one in Discord and re-run`);
498
+ return {
499
+ id: made.id,
500
+ created: true
501
+ };
502
+ }
56
503
  resolve(channel) {
57
504
  const alias = this.opts.webhooks?.[channel];
58
505
  if (alias) return alias;
@@ -78,7 +525,7 @@ async function verifyToken(webhookUrl, opts = {}) {
78
525
  } catch (err) {
79
526
  return {
80
527
  ok: false,
81
- message: err instanceof Error ? err.message : String(err)
528
+ message: errorMessage(err)
82
529
  };
83
530
  }
84
531
  }
@@ -86,17 +533,27 @@ async function verifyToken(webhookUrl, opts = {}) {
86
533
  //#region src/index.ts
87
534
  function createContext(options = {}) {
88
535
  let url;
536
+ let bot;
89
537
  return {
90
538
  options,
91
539
  client: createDiscordClient({
92
540
  baseUrl: options.baseUrl,
93
541
  fetch: options.fetch
94
542
  }),
95
- defaultWebhookUrl: () => url ??= resolveToken(options)
543
+ defaultWebhookUrl: () => url ??= resolveToken(options),
544
+ bot: () => bot ??= createDiscordBotClient({
545
+ botToken: resolveBotToken({
546
+ env: options.env,
547
+ keyring: options.keyring,
548
+ org: options.org
549
+ }),
550
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
551
+ ...options.fetch ? { fetch: options.fetch } : {}
552
+ })
96
553
  };
97
554
  }
98
555
  function notifications(ctx) {
99
- return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl);
556
+ return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot);
100
557
  }
101
558
  function createPlugin(options = {}) {
102
559
  const ctx = createContext(options);
@@ -107,4 +564,4 @@ function createPlugin(options = {}) {
107
564
  }
108
565
  const AUTH_HINT = "create a webhook in Discord: open your server → channel settings → Integrations → Webhooks → New Webhook, copy the webhook URL, then run: holocron auth set discord <https://discord.com/api/webhooks/...>";
109
566
  //#endregion
110
- export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveToken, verifyToken };
567
+ export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveToken, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.19",
3
+ "version": "5.0.0-alpha.190",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -8,12 +8,12 @@
8
8
  "notifications",
9
9
  "plugin"
10
10
  ],
11
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-discord#readme",
11
+ "homepage": "https://github.com/theholocron/holocron/tree/main/plugins/holocron-plugin-discord#readme",
12
12
  "bugs": "https://github.com/theholocron/holocron/issues",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "git+https://github.com/theholocron/holocron.git",
16
- "directory": "packages/holocron-plugin-discord"
16
+ "directory": "plugins/holocron-plugin-discord"
17
17
  },
18
18
  "license": "MIT",
19
19
  "author": "Newton Koumantzelis",
@@ -30,11 +30,13 @@
30
30
  "dist"
31
31
  ],
32
32
  "devDependencies": {
33
- "@theholocron/eslint-config": "^8.0.0",
34
- "@theholocron/http-client": "^1.19.0",
35
- "@theholocron/tsconfig": "^8.0.0",
36
- "@theholocron/tsdown-config": "^8.0.0",
37
- "@theholocron/vitest-config": "^8.0.0",
33
+ "@theholocron/discord-client": "^1.44.0",
34
+ "@theholocron/eslint-config": "^8.8.2",
35
+ "@theholocron/http-client": "^1.43.1",
36
+ "@theholocron/misc-utils": "^1.16.0",
37
+ "@theholocron/tsconfig": "^8.8.2",
38
+ "@theholocron/tsdown-config": "^8.8.2",
39
+ "@theholocron/vitest-config": "^8.8.2",
38
40
  "@types/node": "^26",
39
41
  "@vitest/coverage-v8": "^4.1.11",
40
42
  "@vitest/eslint-plugin": "^1.6.27",
@@ -43,13 +45,15 @@
43
45
  "eslint-plugin-n": "^18.3.0",
44
46
  "globals": "^17.11.0",
45
47
  "tsdown": "^0.22.14",
46
- "tsx": "4.23.12",
48
+ "tsx": "4.23.15",
47
49
  "typescript": "^5.9.3",
48
50
  "vitest": "^4.1.11",
49
- "@theholocron/cli": "5.0.0-alpha.19"
51
+ "@theholocron/cli": "5.0.0-alpha.190"
50
52
  },
51
53
  "peerDependencies": {
52
- "@theholocron/cli": "5.0.0-alpha.19"
54
+ "@theholocron/discord-client": "^1.44.0",
55
+ "@theholocron/misc-utils": "^1.16.0",
56
+ "@theholocron/cli": "5.0.0-alpha.190"
53
57
  },
54
58
  "engines": {
55
59
  "node": ">=22"