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

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, NotificationsServerLayout, 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,146 @@ 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
+ /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
56
+ private inviteUrl;
57
+ /** Changing server settings needs Manage Server; an empty edit proves the bot has it without changing anything. */
58
+ preflight(layout: NotificationsLayout): Promise<void>;
59
+ /** A 403 on a server edit becomes the explanation and the invite link; anything else is passed on as it is. */
60
+ private manageServerHint;
61
+ ensureServer(settings: NotificationsServerLayout): Promise<{
62
+ updated: string[];
63
+ }>;
64
+ validateLayout(layout: NotificationsLayout): string | undefined;
65
+ private botUser?;
66
+ private botId;
67
+ /**
68
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
69
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
70
+ */
71
+ private overwritesFor;
72
+ /**
73
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
74
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
75
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
76
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
77
+ * rather than guessed at.
78
+ */
79
+ private accessOf;
80
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
81
+ private roleLoad?;
82
+ private roleList;
83
+ private guild;
84
+ /**
85
+ * The server's channel list, fetched once per instance. Every ensure* call used
86
+ * to refetch it -- about 40 identical GETs in one setup run -- and Discord
87
+ * rate-limited the route. Our own creates and edits update the copy, so it
88
+ * stays accurate for the run; a new run builds a new instance.
89
+ *
90
+ * It is the in-flight promise that is shared, not the array: callers that start
91
+ * while the first fetch is pending all get the same snapshot, so a later
92
+ * response can never overwrite what an earlier caller added.
93
+ */
94
+ private channelLoad?;
95
+ private channelList;
96
+ /**
97
+ * Create a channel and add it to the shared list. If the create fails, Discord
98
+ * may still have applied it (a timeout looks the same as a refusal), so forget the
99
+ * list: the next ensure refetches the server's real state instead of creating a
100
+ * duplicate.
101
+ */
102
+ private createChannel;
103
+ private static same;
104
+ ensureCategory(name: string, opts?: {
105
+ access?: NotificationsAccess;
106
+ }): Promise<EnsuredResource>;
107
+ /**
108
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
109
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
110
+ * sent, something else changed it at the same time, so say so instead of reporting success.
111
+ */
112
+ private modifyChannel;
113
+ /**
114
+ * Find a channel by name. A name can exist in several categories, so with a
115
+ * parent: prefer the one already there, then an uncategorised one (moved in);
116
+ * never grab a channel that lives under a different category. Announcement
117
+ * channels count: reusing one beats creating a same-named text channel.
118
+ */
119
+ private static findChannel;
120
+ ensureChannel(input: {
121
+ name: string;
122
+ category?: string;
123
+ topic?: string;
124
+ access?: NotificationsAccess;
125
+ }): Promise<EnsuredResource>;
126
+ ensureWebhook(input: {
127
+ channel: string;
128
+ name: string;
129
+ category?: string;
130
+ }): Promise<EnsureWebhookResult>;
131
+ ensureRole(input: {
132
+ name: string;
133
+ mentionable?: boolean;
134
+ color?: string;
135
+ hoist?: boolean;
136
+ permissions?: string[];
137
+ }): Promise<EnsuredResource>;
53
138
  private resolve;
54
139
  }
55
140
  //#endregion
56
141
  //#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
142
  interface VerifyTokenOptions {
67
143
  baseUrl?: string;
68
144
  fetch?: typeof fetch;
69
145
  }
70
- declare function verifyToken(webhookUrl: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
146
+ declare function verifyToken(webhookUrl: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
71
147
  //#endregion
72
148
  //#region src/index.d.ts
73
149
  interface DiscordPluginOptions extends ResolveTokenInput, DiscordNotificationsOptions {
74
150
  /** Override base URL for tests. Default: https://discord.com/api/v10 */
75
151
  baseUrl?: string;
76
152
  fetch?: typeof fetch;
153
+ /**
154
+ * Also send the BOT token to `baseUrl`. Off by default: `baseUrl` comes from a
155
+ * repo's config, and a changed config must not be able to redirect the bot
156
+ * token to another host. Tests that stub the API set it.
157
+ */
158
+ unsafeBotBaseUrl?: boolean;
77
159
  }
78
160
  interface PluginContext {
79
161
  options: DiscordPluginOptions;
@@ -83,6 +165,8 @@ interface PluginContext {
83
165
  * resolved on first `send()`, not at plugin load. `describe()` never calls it.
84
166
  */
85
167
  defaultWebhookUrl: () => string;
168
+ /** 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. */
169
+ bot: () => DiscordBotClient;
86
170
  }
87
171
  declare function createContext(options?: DiscordPluginOptions): PluginContext;
88
172
  declare function notifications(ctx: PluginContext): Notifications;
@@ -94,4 +178,4 @@ declare function createPlugin(options?: DiscordPluginOptions): {
94
178
  };
95
179
  declare const AUTH_HINT: string;
96
180
  //#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 };
181
+ 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,685 @@ 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
+ /** Discord's numeric settings, by the names the layout uses. */
20
+ const VERIFICATION = {
21
+ none: 0,
22
+ low: 1,
23
+ medium: 2,
24
+ high: 3,
25
+ highest: 4
26
+ };
27
+ const NOTIFICATIONS = {
28
+ all: 0,
29
+ mentions: 1
30
+ };
31
+ const FILTER = {
32
+ off: 0,
33
+ noRoles: 1,
34
+ all: 2
35
+ };
36
+ const nameOf = (map, value) => Object.keys(map).find((k) => map[k] === value);
37
+ /** What the bot needs in the server to do everything `setup` does. The invite link asks for exactly these. */
38
+ const BOT_NEEDS = [
39
+ "ViewChannel",
40
+ "SendMessages",
41
+ "ReadMessageHistory",
42
+ "ManageChannels",
43
+ "ManageRoles",
44
+ "ManageWebhooks",
45
+ "ManageGuild",
46
+ "CreatePublicThreads",
47
+ "CreatePrivateThreads",
48
+ "SendMessagesInThreads"
49
+ ];
50
+ /** The locales Discord accepts for a server's preferred language. */
51
+ const LOCALES = /* @__PURE__ */ new Set([
52
+ "id",
53
+ "da",
54
+ "de",
55
+ "en-GB",
56
+ "en-US",
57
+ "es-ES",
58
+ "es-419",
59
+ "fr",
60
+ "hr",
61
+ "it",
62
+ "lt",
63
+ "hu",
64
+ "nl",
65
+ "no",
66
+ "pl",
67
+ "pt-BR",
68
+ "ro",
69
+ "fi",
70
+ "sv-SE",
71
+ "vi",
72
+ "tr",
73
+ "cs",
74
+ "el",
75
+ "bg",
76
+ "ru",
77
+ "uk",
78
+ "hi",
79
+ "th",
80
+ "zh-CN",
81
+ "ja",
82
+ "zh-TW",
83
+ "ko"
84
+ ]);
85
+ /** A layout name to Discord's number, undefined when the layout leaves it out; an unknown name is an error, not an omission. */
86
+ function s_(name, map) {
87
+ if (name === void 0) return void 0;
88
+ if (!Object.hasOwn(map, name)) throw new Error(`unknown value ${JSON.stringify(name)}; use one of ${Object.keys(map).join(", ")}`);
89
+ return map[name];
29
90
  }
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
- };
91
+ /** `#rrggbb` to Discord's integer colour. */
92
+ function colorToInt(hex) {
93
+ if (!/^#[0-9a-fA-F]{6}$/.test(hex)) throw new Error(`invalid colour ${JSON.stringify(hex)}: use #rrggbb`);
94
+ return Number.parseInt(hex.slice(1), 16);
38
95
  }
39
- //#endregion
40
- //#region src/capabilities/notifications.ts
41
- var DiscordNotifications = class {
96
+ /** Discord's integer colour to `#rrggbb`. 0 is Discord's "no colour", and is what `#000000` means too. */
97
+ function colorToHex(color) {
98
+ return `#${color.toString(16).padStart(6, "0")}`;
99
+ }
100
+ /** An error as one line: the message, plus Discord's own response body when there is one. */
101
+ function reason(err) {
102
+ return err instanceof ProviderApiError && err.details ? `${errorMessage(err)}: ${String(err.details).slice(0, 200)}` : errorMessage(err);
103
+ }
104
+ /**
105
+ * What @everyone loses when a channel is read-only. Only sending: Discord refuses (403) any change to the
106
+ * thread permissions on an existing text channel from a bot whose own role lacks them, and Holonet's
107
+ * does. Members can therefore still start threads in a read-only channel until the bot is given those
108
+ * permissions; see {@link THREAD_BITS} for how channels that already carry them are read.
109
+ */
110
+ const POST = ["SendMessages"];
111
+ const THREAD_MASK = ~BigInt(permissions([
112
+ "SendMessagesInThreads",
113
+ "CreatePublicThreads",
114
+ "CreatePrivateThreads"
115
+ ]));
116
+ /** What the bot keeps in a channel it has locked down, so it can still manage it and post. */
117
+ const BOT_KEEPS = [
118
+ "ViewChannel",
119
+ "SendMessages",
120
+ "ReadMessageHistory",
121
+ "ManageChannels",
122
+ "ManageWebhooks"
123
+ ];
124
+ /**
125
+ * Overwrites as a comparable set: order and the shape of the array do not matter, and the thread
126
+ * permissions are left out (setup does not manage them, so their presence is not a difference).
127
+ */
128
+ function overwriteKey(list) {
129
+ return (list ?? []).map((o) => ({
130
+ ...o,
131
+ allow: BigInt(o.allow) & THREAD_MASK,
132
+ deny: BigInt(o.deny) & THREAD_MASK
133
+ })).filter((o) => o.allow !== 0n || o.deny !== 0n).map((o) => `${o.id}:${o.type}:${o.allow}:${o.deny}`).sort().join("|");
134
+ }
135
+ /**
136
+ * Desired overwrites with the thread permissions of the existing ones laid back in. Discord refuses
137
+ * any change to those from this bot, so a replacement list must carry them over untouched or the
138
+ * whole edit is rejected, even when it changes nothing but what we do manage.
139
+ */
140
+ function keepThreadBits(desired, existing) {
141
+ const threads = ~THREAD_MASK;
142
+ const merged = desired.map((o) => ({ ...o }));
143
+ for (const old of existing ?? []) {
144
+ const allow = BigInt(old.allow) & threads;
145
+ const deny = BigInt(old.deny) & threads;
146
+ if (allow === 0n && deny === 0n) continue;
147
+ const same = merged.find((o) => o.id === old.id && o.type === old.type);
148
+ if (same) {
149
+ same.allow = (BigInt(same.allow) | allow).toString();
150
+ same.deny = (BigInt(same.deny) | deny).toString();
151
+ } else merged.push({
152
+ id: old.id,
153
+ type: old.type,
154
+ allow: allow.toString(),
155
+ deny: deny.toString()
156
+ });
157
+ }
158
+ return merged;
159
+ }
160
+ var DiscordNotifications = class DiscordNotifications {
42
161
  client;
43
162
  opts;
44
163
  defaultWebhookUrl;
164
+ bot;
45
165
  key = "notifications";
46
166
  providerName = "discord";
47
- constructor(client, opts, defaultWebhookUrl) {
167
+ constructor(client, opts, defaultWebhookUrl, bot = () => {
168
+ throw new Error("no Discord bot client configured");
169
+ }) {
48
170
  this.client = client;
49
171
  this.opts = opts;
50
172
  this.defaultWebhookUrl = defaultWebhookUrl;
173
+ this.bot = bot;
174
+ }
175
+ get layout() {
176
+ return this.opts.layout;
51
177
  }
52
178
  async send(channel, message) {
53
- const { id, token } = parseWebhookUrl(this.resolve(channel || this.opts.defaultChannel || ""));
179
+ const webhookUrl = this.resolve(channel || this.opts.defaultChannel || "");
180
+ const { id, token } = parseWebhookUrl(webhookUrl);
54
181
  await this.client.webhooks.execute(id, token, message);
55
182
  }
183
+ /**
184
+ * `holocron doctor`: the bot token is valid and can see the configured server.
185
+ * Null when no `guildId` is set -- a post-only config has no bot to check. A
186
+ * `layout` without a `guildId` is a half-written provisioning config, so that
187
+ * fails instead of passing as post-only.
188
+ */
189
+ async whoami() {
190
+ if (!this.opts.guildId) {
191
+ if (this.opts.layout) throw new Error("`layout` is set but `guildId` is not — add the server id to the discord provider options");
192
+ return null;
193
+ }
194
+ const bot = this.bot();
195
+ const me = await bot.users.me();
196
+ return { target: `${(await bot.guilds.get(this.opts.guildId)).name} (as ${me.username})` };
197
+ }
198
+ /**
199
+ * Read-only: what is on the server, for the parts of `layout` we will compare. Webhooks are
200
+ * listed only for channels the layout gives one (one request each), so the cost scales with
201
+ * the layout, not with the server.
202
+ */
203
+ async inspect(layout) {
204
+ const bot = this.bot();
205
+ const channels = await this.channelList();
206
+ const categoryName = new Map(channels.filter((c) => c.type === ChannelType.Category).map((c) => [c.id, c.name]));
207
+ const wantsWebhook = new Set((layout.categories ?? []).flatMap((c) => (c.channels ?? []).filter((ch) => ch.webhook).map((ch) => ch.name.toLowerCase())));
208
+ const text = channels.filter((c) => c.type === ChannelType.Text || c.type === ChannelType.Announcement);
209
+ const found = [];
210
+ for (const c of text) {
211
+ let webhooks = [];
212
+ let webhooksError;
213
+ if (wantsWebhook.has(c.name.toLowerCase())) try {
214
+ webhooks = (await bot.channels.webhooks(c.id)).map((w) => w.name ?? "");
215
+ } catch (err) {
216
+ webhooksError = reason(err);
217
+ }
218
+ const category = c.parent_id ? categoryName.get(c.parent_id) : void 0;
219
+ found.push({
220
+ name: c.name,
221
+ ...category ? { category } : {},
222
+ ...c.topic ? { topic: c.topic } : {},
223
+ webhooks,
224
+ ...webhooksError ? { webhooksError } : {}
225
+ });
226
+ }
227
+ let roles = [];
228
+ let rolesError;
229
+ if ((layout.roles ?? []).length > 0) try {
230
+ roles = (await bot.guilds.roles(this.guild())).map((r) => {
231
+ return {
232
+ name: r.name,
233
+ id: r.id,
234
+ mentionable: r.mentionable,
235
+ color: colorToHex(r.color),
236
+ ...r.hoist !== void 0 ? { hoist: r.hoist } : {},
237
+ ...r.permissions !== void 0 ? { permissions: permissionNames(r.permissions) } : {}
238
+ };
239
+ });
240
+ } catch (err) {
241
+ rolesError = reason(err);
242
+ }
243
+ let server;
244
+ let serverError;
245
+ if (layout.server) try {
246
+ const guild = await bot.guilds.get(this.guild());
247
+ const channelName = (id) => id ? channels.find((c) => c.id === id)?.name ?? id : void 0;
248
+ const verification = nameOf(VERIFICATION, guild.verification_level);
249
+ const defaultNotifications = nameOf(NOTIFICATIONS, guild.default_message_notifications);
250
+ const contentFilter = nameOf(FILTER, guild.explicit_content_filter);
251
+ const systemChannel = channelName(guild.system_channel_id);
252
+ const rulesChannel = channelName(guild.rules_channel_id);
253
+ const updatesChannel = channelName(guild.public_updates_channel_id);
254
+ server = {
255
+ ...verification ? { verification } : {},
256
+ ...defaultNotifications ? { defaultNotifications } : {},
257
+ ...contentFilter ? { contentFilter } : {},
258
+ ...systemChannel ? { systemChannel } : {},
259
+ ...rulesChannel ? { rulesChannel } : {},
260
+ ...updatesChannel ? { updatesChannel } : {},
261
+ community: (guild.features ?? []).includes("COMMUNITY"),
262
+ ...guild.description !== void 0 && guild.description !== null ? { description: guild.description } : {},
263
+ ...guild.preferred_locale ? { locale: guild.preferred_locale } : {}
264
+ };
265
+ } catch (err) {
266
+ serverError = reason(err);
267
+ }
268
+ const roleName = (id) => roles.find((r) => r.id === id)?.name ?? id;
269
+ found.forEach((entry, i) => {
270
+ entry.access = this.accessOf(text[i].permission_overwrites, roleName);
271
+ });
272
+ const categoryAccess = {};
273
+ for (const c of channels.filter((c) => c.type === ChannelType.Category)) categoryAccess[c.name] = this.accessOf(c.permission_overwrites, roleName);
274
+ return {
275
+ categories: [...categoryName.values()],
276
+ categoryAccess,
277
+ ...server ? { server } : {},
278
+ ...serverError ? { serverError } : {},
279
+ channels: found,
280
+ roles,
281
+ ...rolesError ? { rolesError } : {}
282
+ };
283
+ }
284
+ /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
285
+ async inviteUrl() {
286
+ const url = new URL("https://discord.com/oauth2/authorize");
287
+ url.searchParams.set("client_id", await this.botId());
288
+ url.searchParams.set("scope", "bot");
289
+ url.searchParams.set("permissions", permissions(BOT_NEEDS));
290
+ url.searchParams.set("guild_id", this.guild());
291
+ return url.toString();
292
+ }
293
+ /** Changing server settings needs Manage Server; an empty edit proves the bot has it without changing anything. */
294
+ async preflight(layout) {
295
+ if (!layout.server) return;
296
+ try {
297
+ await this.bot().guilds.modify(this.guild(), {});
298
+ } catch (err) {
299
+ throw await this.manageServerHint(err);
300
+ }
301
+ }
302
+ /** A 403 on a server edit becomes the explanation and the invite link; anything else is passed on as it is. */
303
+ async manageServerHint(err) {
304
+ if (err instanceof ProviderApiError && err.status === 403) return new Error(`the bot is not allowed to change server settings: its role lacks Manage Server. Re-invite it with the permissions setup needs (this updates its role in place): ${await this.inviteUrl()}`, { cause: err });
305
+ return err;
306
+ }
307
+ async ensureServer(settings) {
308
+ const bot = this.bot();
309
+ const guild = await bot.guilds.get(this.guild());
310
+ const channels = await this.channelList();
311
+ const idOf = (name) => {
312
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
313
+ if (named.length === 0) throw new Error(`server settings name the channel \`${name}\`, which does not exist on the server yet`);
314
+ if (named.length > 1) throw new Error(`server settings name the channel \`${name}\`, but ${named.length} channels have that name (ids ${named.map((c) => c.id).join(", ")}) -- rename one`);
315
+ return named[0].id;
316
+ };
317
+ const patch = {};
318
+ const updated = [];
319
+ const set = (label, key, want, have) => {
320
+ if (want !== void 0 && want !== have) {
321
+ patch[key] = want;
322
+ updated.push(label);
323
+ }
324
+ };
325
+ set("verification", "verification_level", s_(settings.verification, VERIFICATION), guild.verification_level);
326
+ set("defaultNotifications", "default_message_notifications", s_(settings.defaultNotifications, NOTIFICATIONS), guild.default_message_notifications);
327
+ set("contentFilter", "explicit_content_filter", s_(settings.contentFilter, FILTER), guild.explicit_content_filter);
328
+ set("systemChannel", "system_channel_id", settings.systemChannel && idOf(settings.systemChannel), guild.system_channel_id);
329
+ set("rulesChannel", "rules_channel_id", settings.rulesChannel && idOf(settings.rulesChannel), guild.rules_channel_id);
330
+ set("updatesChannel", "public_updates_channel_id", settings.updatesChannel && idOf(settings.updatesChannel), guild.public_updates_channel_id);
331
+ set("description", "description", settings.description, guild.description ?? "");
332
+ set("locale", "preferred_locale", settings.locale, guild.preferred_locale);
333
+ const features = guild.features ?? [];
334
+ const community = features.includes("COMMUNITY");
335
+ if (settings.community !== void 0 && settings.community !== community) {
336
+ patch.features = settings.community ? [...features, "COMMUNITY"] : features.filter((f) => f !== "COMMUNITY");
337
+ updated.push("community");
338
+ }
339
+ if (updated.length === 0) return { updated };
340
+ let after;
341
+ try {
342
+ after = await bot.guilds.modify(this.guild(), patch);
343
+ } catch (err) {
344
+ throw await this.manageServerHint(err);
345
+ }
346
+ const stuck = Object.keys(patch).filter((k) => k !== "features").filter((k) => {
347
+ const got = after[k];
348
+ return patch[k] !== (k === "description" ? got ?? "" : got);
349
+ });
350
+ const nowFeatures = after.features ?? [];
351
+ if (patch.features && patch.features.includes("COMMUNITY") !== nowFeatures.includes("COMMUNITY")) stuck.push("features");
352
+ if (stuck.length > 0) throw new Error(`sent ${stuck.join(", ")} but the server came back different -- Discord may have refused a part of it (community features need a rules channel, an updates channel, verification of at least low and the content filter on all members)`);
353
+ if (patch.features?.includes("COMMUNITY")) {
354
+ const lost = features.filter((f) => f !== "COMMUNITY" && !nowFeatures.includes(f));
355
+ if (lost.length > 0) throw new Error(`turned community on, but the server no longer has ${lost.join(", ")} -- another admin may have changed its features at the same time; check Server Settings and re-run`);
356
+ }
357
+ return { updated };
358
+ }
359
+ validateLayout(layout) {
360
+ const server = layout.server;
361
+ for (const [field, map] of [
362
+ ["verification", VERIFICATION],
363
+ ["defaultNotifications", NOTIFICATIONS],
364
+ ["contentFilter", FILTER]
365
+ ]) {
366
+ const value = server?.[field];
367
+ if (value !== void 0 && !Object.hasOwn(map, value)) return `server: \`${field}\` is ${JSON.stringify(value)}; use one of ${Object.keys(map).join(", ")}`;
368
+ }
369
+ if (server?.locale !== void 0 && !LOCALES.has(server.locale)) return `server: \`locale\` ${JSON.stringify(server.locale)} is not a locale Discord accepts (for example en-US, en-GB, de, fr)`;
370
+ if (server?.community === true && (server.verification === void 0 || server.verification === "none")) return "server: community features need `verification` of at least `low`";
371
+ if (server?.community === true && server.contentFilter !== "all") return "server: community features need `contentFilter: \"all\"`";
372
+ for (const role of layout.roles ?? []) try {
373
+ if (role.color !== void 0) colorToInt(role.color);
374
+ if (role.permissions !== void 0) permissions(role.permissions);
375
+ } catch (err) {
376
+ return `role \`${role.name}\`: ${errorMessage(err)}`;
377
+ }
378
+ }
379
+ botUser;
380
+ botId() {
381
+ return this.botUser ??= this.bot().users.me().then((u) => u.id).catch((err) => {
382
+ this.botUser = void 0;
383
+ throw err;
384
+ });
385
+ }
386
+ /**
387
+ * The overwrites that make a channel look like `access`. The list is exact: it replaces
388
+ * whatever was set by hand. `[]` (public) when nothing is restricted.
389
+ */
390
+ async overwritesFor(access) {
391
+ const view = access.view ?? "everyone";
392
+ const post = access.post ?? "everyone";
393
+ const everyoneDeny = [...view === "everyone" ? [] : ["ViewChannel"], ...post === "everyone" ? [] : POST];
394
+ if (everyoneDeny.length === 0) return [];
395
+ const roles = [...view === "everyone" ? [] : view, ...post === "everyone" ? [] : post].length > 0 ? await this.roleList() : [];
396
+ const idOf = (name) => {
397
+ const found = roles.filter((r) => DiscordNotifications.same(r.name, name));
398
+ if (found.length === 0) throw new Error(`access names the role \`${name}\`, which does not exist on the server yet`);
399
+ 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`);
400
+ return found[0].id;
401
+ };
402
+ const allow = /* @__PURE__ */ new Map();
403
+ const grant = (roleName, names) => {
404
+ const id = idOf(roleName);
405
+ allow.set(id, [.../* @__PURE__ */ new Set([...allow.get(id) ?? [], ...names])]);
406
+ };
407
+ if (view !== "everyone") for (const r of view) grant(r, ["ViewChannel"]);
408
+ if (post !== "everyone") for (const r of post) grant(r, POST);
409
+ return [
410
+ {
411
+ id: this.guild(),
412
+ type: 0,
413
+ allow: "0",
414
+ deny: permissions(everyoneDeny)
415
+ },
416
+ ...[...allow].map(([id, names]) => ({
417
+ id,
418
+ type: 0,
419
+ allow: permissions(names),
420
+ deny: "0"
421
+ })),
422
+ {
423
+ id: await this.botId(),
424
+ type: 1,
425
+ allow: permissions(BOT_KEEPS),
426
+ deny: "0"
427
+ }
428
+ ];
429
+ }
430
+ /**
431
+ * Read an access back out of a channel's overwrites, naming roles as the layout does. Only
432
+ * overwrites of the shape {@link overwritesFor} writes can be read back; anything else
433
+ * (a role-specific deny, a member overwrite, only some of the posting bits) means the
434
+ * channel's real access is not something the layout can state, and is reported as `"custom"`
435
+ * rather than guessed at.
436
+ */
437
+ accessOf(overwrites, roleName) {
438
+ const list = overwrites ?? [];
439
+ const managed = permissions(["ViewChannel", ...POST]);
440
+ const unthreaded = (bits) => BigInt(bits) & THREAD_MASK;
441
+ const within = (bits) => (unthreaded(bits) & ~BigInt(managed)) === 0n;
442
+ const botSignature = permissions(BOT_KEEPS);
443
+ let everyone;
444
+ const roles = [];
445
+ for (const o of list) if (o.type === 1) {
446
+ if (o.allow !== botSignature || o.deny !== "0") return "custom";
447
+ } else if (o.id === this.guild()) everyone = o;
448
+ else roles.push(o);
449
+ if (everyone && (unthreaded(everyone.allow) !== 0n || !within(everyone.deny))) return "custom";
450
+ for (const o of roles) if (unthreaded(o.deny) !== 0n || !within(o.allow)) return "custom";
451
+ const denied = (bit) => everyone !== void 0 && permissionNames(everyone.deny).includes(bit);
452
+ const names = (bit) => roles.filter((o) => permissionNames(o.allow).includes(bit)).map((o) => roleName(o.id));
453
+ return {
454
+ view: denied("ViewChannel") ? names("ViewChannel") : "everyone",
455
+ post: denied("SendMessages") ? names("SendMessages") : "everyone"
456
+ };
457
+ }
458
+ /** The server's roles, fetched once and forgotten whenever setup changes a role. */
459
+ roleLoad;
460
+ roleList() {
461
+ return this.roleLoad ??= this.bot().guilds.roles(this.guild()).catch((err) => {
462
+ this.roleLoad = void 0;
463
+ throw err;
464
+ });
465
+ }
466
+ guild() {
467
+ if (!this.opts.guildId) throw new Error("no Discord server id — set `guildId` in the discord provider options in holocron.config.ts");
468
+ if (!/^\d{1,20}$/.test(this.opts.guildId)) throw new Error(`\`guildId\` ${JSON.stringify(this.opts.guildId)} is not a Discord server id (digits only)`);
469
+ return this.opts.guildId;
470
+ }
471
+ /**
472
+ * The server's channel list, fetched once per instance. Every ensure* call used
473
+ * to refetch it -- about 40 identical GETs in one setup run -- and Discord
474
+ * rate-limited the route. Our own creates and edits update the copy, so it
475
+ * stays accurate for the run; a new run builds a new instance.
476
+ *
477
+ * It is the in-flight promise that is shared, not the array: callers that start
478
+ * while the first fetch is pending all get the same snapshot, so a later
479
+ * response can never overwrite what an earlier caller added.
480
+ */
481
+ channelLoad;
482
+ channelList() {
483
+ return this.channelLoad ??= this.bot().guilds.channels(this.guild()).catch((err) => {
484
+ this.channelLoad = void 0;
485
+ throw err;
486
+ });
487
+ }
488
+ /**
489
+ * Create a channel and add it to the shared list. If the create fails, Discord
490
+ * may still have applied it (a timeout looks the same as a refusal), so forget the
491
+ * list: the next ensure refetches the server's real state instead of creating a
492
+ * duplicate.
493
+ */
494
+ async createChannel(body) {
495
+ try {
496
+ const made = await this.bot().guilds.createChannel(this.guild(), body);
497
+ (await this.channelList()).push(made);
498
+ return made;
499
+ } catch (err) {
500
+ this.channelLoad = void 0;
501
+ throw err;
502
+ }
503
+ }
504
+ static same(a, b) {
505
+ return a.toLowerCase() === b.toLowerCase();
506
+ }
507
+ async ensureCategory(name, opts = {}) {
508
+ const existing = (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, name));
509
+ const overwrites = opts.access ? await this.overwritesFor(opts.access) : void 0;
510
+ if (existing) {
511
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
512
+ await this.modifyChannel(existing, { permission_overwrites: keepThreadBits(overwrites, existing.permission_overwrites) });
513
+ return {
514
+ id: existing.id,
515
+ created: false,
516
+ updated: ["access"]
517
+ };
518
+ }
519
+ return {
520
+ id: existing.id,
521
+ created: false
522
+ };
523
+ }
524
+ return {
525
+ id: (await this.createChannel({
526
+ name,
527
+ type: ChannelType.Category,
528
+ ...overwrites ? { permission_overwrites: overwrites } : {}
529
+ })).id,
530
+ created: true
531
+ };
532
+ }
533
+ /**
534
+ * Edit a channel and keep the shared list in step; forget the list if the edit may have half-applied.
535
+ * Discord answers with the channel as it now is: if the overwrites that come back are not the ones we
536
+ * sent, something else changed it at the same time, so say so instead of reporting success.
537
+ */
538
+ async modifyChannel(channel, patch) {
539
+ let after;
540
+ try {
541
+ after = await this.bot().channels.modify(channel.id, patch);
542
+ } catch (err) {
543
+ this.channelLoad = void 0;
544
+ throw err;
545
+ }
546
+ if (patch.permission_overwrites && overwriteKey(after.permission_overwrites) !== overwriteKey(patch.permission_overwrites)) {
547
+ this.channelLoad = void 0;
548
+ 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`);
549
+ }
550
+ Object.assign(channel, patch);
551
+ }
552
+ /**
553
+ * Find a channel by name. A name can exist in several categories, so with a
554
+ * parent: prefer the one already there, then an uncategorised one (moved in);
555
+ * never grab a channel that lives under a different category. Announcement
556
+ * channels count: reusing one beats creating a same-named text channel.
557
+ */
558
+ static findChannel(channels, name, parentId) {
559
+ const named = channels.filter((c) => (c.type === ChannelType.Text || c.type === ChannelType.Announcement) && DiscordNotifications.same(c.name, name));
560
+ if (!parentId) return named[0];
561
+ return named.find((c) => c.parent_id === parentId) ?? named.find((c) => !c.parent_id);
562
+ }
563
+ async ensureChannel(input) {
564
+ const parent = input.category ? (await this.ensureCategory(input.category)).id : void 0;
565
+ const existing = DiscordNotifications.findChannel(await this.channelList(), input.name, parent);
566
+ const overwrites = input.access ? await this.overwritesFor(input.access) : void 0;
567
+ if (existing) {
568
+ const updated = [];
569
+ const patch = {};
570
+ if (parent && existing.parent_id !== parent) {
571
+ patch.parent_id = parent;
572
+ updated.push("category");
573
+ }
574
+ if (input.topic !== void 0 && (existing.topic ?? "") !== input.topic) {
575
+ patch.topic = input.topic;
576
+ updated.push("topic");
577
+ }
578
+ if (overwrites && overwriteKey(existing.permission_overwrites) !== overwriteKey(overwrites)) {
579
+ patch.permission_overwrites = keepThreadBits(overwrites, existing.permission_overwrites);
580
+ updated.push("access");
581
+ }
582
+ if (updated.length > 0) await this.modifyChannel(existing, patch);
583
+ return {
584
+ id: existing.id,
585
+ created: false,
586
+ ...updated.length > 0 ? { updated } : {}
587
+ };
588
+ }
589
+ return {
590
+ id: (await this.createChannel({
591
+ name: input.name,
592
+ type: ChannelType.Text,
593
+ ...input.topic ? { topic: input.topic } : {},
594
+ ...parent ? { parent_id: parent } : {},
595
+ ...overwrites ? { permission_overwrites: overwrites } : {}
596
+ })).id,
597
+ created: true
598
+ };
599
+ }
600
+ async ensureWebhook(input) {
601
+ const bot = this.bot();
602
+ const parent = input.category ? (await this.channelList()).find((c) => c.type === ChannelType.Category && DiscordNotifications.same(c.name, input.category))?.id : void 0;
603
+ const channel = DiscordNotifications.findChannel(await this.channelList(), input.channel, parent);
604
+ if (!channel) throw new Error(`no channel named \`${input.channel}\` — create it first`);
605
+ const existing = (await bot.channels.webhooks(channel.id)).find((w) => DiscordNotifications.same(w.name ?? "", input.name));
606
+ if (existing) return {
607
+ created: false,
608
+ ...existing.url ? { url: existing.url } : {}
609
+ };
610
+ const made = await bot.channels.createWebhook(channel.id, { name: input.name });
611
+ return {
612
+ created: true,
613
+ ...made.url ? { url: made.url } : {}
614
+ };
615
+ }
616
+ async ensureRole(input) {
617
+ const bot = this.bot();
618
+ const color = input.color !== void 0 ? colorToInt(input.color) : void 0;
619
+ const wanted = input.permissions !== void 0 ? permissions(input.permissions) : void 0;
620
+ const matches = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
621
+ 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`);
622
+ const existing = matches[0];
623
+ if (existing) {
624
+ const patch = {};
625
+ const updated = [];
626
+ if (input.mentionable !== void 0 && existing.mentionable !== input.mentionable) {
627
+ patch.mentionable = input.mentionable;
628
+ updated.push("mentionable");
629
+ }
630
+ if (color !== void 0 && existing.color !== color) {
631
+ patch.color = color;
632
+ updated.push("colour");
633
+ }
634
+ if (input.hoist !== void 0 && (existing.hoist ?? false) !== input.hoist) {
635
+ patch.hoist = input.hoist;
636
+ updated.push("hoist");
637
+ }
638
+ if (wanted !== void 0 && existing.permissions !== wanted) {
639
+ patch.permissions = wanted;
640
+ updated.push("permissions");
641
+ }
642
+ if (updated.length > 0) {
643
+ this.roleLoad = void 0;
644
+ const after = await bot.guilds.modifyRole(this.guild(), existing.id, patch);
645
+ const stuck = [
646
+ [
647
+ "mentionable",
648
+ patch.mentionable,
649
+ after.mentionable
650
+ ],
651
+ [
652
+ "colour",
653
+ patch.color,
654
+ after.color
655
+ ],
656
+ [
657
+ "hoist",
658
+ patch.hoist,
659
+ after.hoist
660
+ ],
661
+ [
662
+ "permissions",
663
+ patch.permissions,
664
+ after.permissions
665
+ ]
666
+ ].filter(([, sent, now]) => sent !== void 0 && sent !== now).map(([name]) => name);
667
+ 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`);
668
+ }
669
+ return {
670
+ id: existing.id,
671
+ created: false,
672
+ ...updated.length > 0 ? { updated } : {}
673
+ };
674
+ }
675
+ this.roleLoad = void 0;
676
+ const made = await bot.guilds.createRole(this.guild(), {
677
+ name: input.name,
678
+ ...input.mentionable !== void 0 ? { mentionable: input.mentionable } : {},
679
+ ...color !== void 0 ? { color } : {},
680
+ ...input.hoist !== void 0 ? { hoist: input.hoist } : {},
681
+ ...wanted !== void 0 ? { permissions: wanted } : {}
682
+ });
683
+ const twins = (await bot.guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, input.name));
684
+ 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`);
685
+ return {
686
+ id: made.id,
687
+ created: true
688
+ };
689
+ }
56
690
  resolve(channel) {
57
691
  const alias = this.opts.webhooks?.[channel];
58
692
  if (alias) return alias;
@@ -78,7 +712,7 @@ async function verifyToken(webhookUrl, opts = {}) {
78
712
  } catch (err) {
79
713
  return {
80
714
  ok: false,
81
- message: err instanceof Error ? err.message : String(err)
715
+ message: errorMessage(err)
82
716
  };
83
717
  }
84
718
  }
@@ -86,17 +720,27 @@ async function verifyToken(webhookUrl, opts = {}) {
86
720
  //#region src/index.ts
87
721
  function createContext(options = {}) {
88
722
  let url;
723
+ let bot;
89
724
  return {
90
725
  options,
91
726
  client: createDiscordClient({
92
727
  baseUrl: options.baseUrl,
93
728
  fetch: options.fetch
94
729
  }),
95
- defaultWebhookUrl: () => url ??= resolveToken(options)
730
+ defaultWebhookUrl: () => url ??= resolveToken(options),
731
+ bot: () => bot ??= createDiscordBotClient({
732
+ botToken: resolveBotToken({
733
+ env: options.env,
734
+ keyring: options.keyring,
735
+ org: options.org
736
+ }),
737
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
738
+ ...options.fetch ? { fetch: options.fetch } : {}
739
+ })
96
740
  };
97
741
  }
98
742
  function notifications(ctx) {
99
- return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl);
743
+ return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot);
100
744
  }
101
745
  function createPlugin(options = {}) {
102
746
  const ctx = createContext(options);
@@ -107,4 +751,4 @@ function createPlugin(options = {}) {
107
751
  }
108
752
  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
753
  //#endregion
110
- export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveToken, verifyToken };
754
+ 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.191",
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.191"
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.191"
53
57
  },
54
58
  "engines": {
55
59
  "node": ">=22"