lunibee 0.2.3 → 0.3.0

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.
Files changed (86) hide show
  1. package/README.md +3 -3
  2. package/dist/builders/attachment.d.ts +8 -4
  3. package/dist/builders/commands.d.ts +122 -149
  4. package/dist/builders/components.d.ts +10 -150
  5. package/dist/builders/embed.d.ts +66 -37
  6. package/dist/builders/index.d.ts +0 -4
  7. package/dist/builders/index.js +112 -221
  8. package/dist/builders/index.js.map +10 -9
  9. package/dist/collection/cache.d.ts +15 -6
  10. package/dist/collection/index.d.ts +92 -17
  11. package/dist/collection/index.js +471 -279
  12. package/dist/collection/index.js.map +4 -4
  13. package/dist/core/api.d.ts +130 -0
  14. package/dist/core/channel-create.d.ts +72 -0
  15. package/dist/core/commands.d.ts +232 -0
  16. package/dist/core/events.d.ts +24 -7
  17. package/dist/core/handles.d.ts +157 -0
  18. package/dist/core/index.d.ts +68 -4
  19. package/dist/core/index.js +2639 -493
  20. package/dist/core/index.js.map +47 -37
  21. package/dist/core/permissions.d.ts +7 -7
  22. package/dist/formatters/index.js +9 -5
  23. package/dist/formatters/index.js.map +3 -3
  24. package/dist/handlers/index.js +5 -10
  25. package/dist/handlers/index.js.map +3 -3
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +9527 -7809
  28. package/dist/index.js.map +63 -53
  29. package/dist/managers/advanced.d.ts +29 -1
  30. package/dist/managers/base.d.ts +22 -14
  31. package/dist/managers/emoji.d.ts +0 -2
  32. package/dist/managers/guild-resources.d.ts +13 -5
  33. package/dist/managers/guild.d.ts +40 -4
  34. package/dist/managers/index.d.ts +21 -13
  35. package/dist/managers/index.js +969 -386
  36. package/dist/managers/index.js.map +30 -25
  37. package/dist/managers/member.d.ts +9 -2
  38. package/dist/managers/message.d.ts +10 -15
  39. package/dist/managers/role.d.ts +18 -10
  40. package/dist/managers/thread.d.ts +68 -0
  41. package/dist/managers/user.d.ts +18 -0
  42. package/dist/rest/errors.d.ts +14 -7
  43. package/dist/rest/index.d.ts +24 -12
  44. package/dist/rest/index.js +70 -20
  45. package/dist/rest/index.js.map +9 -9
  46. package/dist/rest/redis.d.ts +1 -1
  47. package/dist/rest/route.d.ts +8 -4
  48. package/dist/rest/routes.d.ts +122 -48
  49. package/dist/rest/transport.d.ts +10 -5
  50. package/dist/rest/webhook.d.ts +9 -5
  51. package/dist/sharding/bus.d.ts +47 -19
  52. package/dist/sharding/cluster.d.ts +11 -0
  53. package/dist/sharding/gateway-bot.d.ts +18 -0
  54. package/dist/sharding/index.d.ts +64 -25
  55. package/dist/sharding/index.js +439 -124
  56. package/dist/sharding/index.js.map +19 -14
  57. package/dist/sharding/supervisor.d.ts +32 -0
  58. package/dist/sharding/transport.d.ts +45 -0
  59. package/dist/structures/audit-log.d.ts +99 -2
  60. package/dist/structures/base.d.ts +40 -23
  61. package/dist/structures/channels.d.ts +45 -14
  62. package/dist/structures/index.d.ts +8 -12
  63. package/dist/structures/index.js +280 -132
  64. package/dist/structures/index.js.map +21 -15
  65. package/dist/structures/interactions.d.ts +91 -63
  66. package/dist/structures/resources.d.ts +99 -52
  67. package/dist/structures/sticker.d.ts +33 -0
  68. package/dist/types/channel-kind.d.ts +26 -0
  69. package/dist/types/gateway.d.ts +24 -12
  70. package/dist/types/index.d.ts +115 -113
  71. package/dist/types/index.js +53 -48
  72. package/dist/types/index.js.map +6 -5
  73. package/dist/voice/index.d.ts +12 -4
  74. package/dist/voice/index.js +14 -18
  75. package/dist/voice/index.js.map +3 -3
  76. package/dist/ws/decoder.d.ts +6 -2
  77. package/dist/ws/dispatcher.d.ts +19 -0
  78. package/dist/ws/index.d.ts +61 -15
  79. package/dist/ws/index.js +194 -77
  80. package/dist/ws/index.js.map +13 -11
  81. package/dist/ws/protocol.d.ts +10 -2
  82. package/dist/ws/reconnect.d.ts +10 -0
  83. package/dist/ws/send-budget.d.ts +6 -2
  84. package/dist/ws/session.d.ts +14 -4
  85. package/dist/ws/state.d.ts +22 -11
  86. package/package.json +20 -16
@@ -1,24 +1,30 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../packages/structures/src/base.ts", "../../packages/core/src/permissions.ts", "../../packages/types/src/gateway.ts", "../../packages/types/src/index.ts", "../../packages/rest/src/index.ts", "../../packages/managers/src/index.ts", "../../packages/ws/src/close-codes.ts", "../../packages/ws/src/reconnect.ts", "../../packages/structures/src/resources.ts", "../../packages/structures/src/channels.ts", "../../packages/structures/src/options.ts", "../../packages/structures/src/interactions.ts", "../../packages/structures/src/embed.ts", "../../packages/structures/src/audit-log.ts", "../../packages/structures/src/index.ts"],
3
+ "sources": ["../../packages/types/src/channel-kind.ts", "../../packages/types/src/gateway.ts", "../../packages/types/src/index.ts", "../../packages/structures/src/base.ts", "../../packages/core/src/permissions.ts", "../../packages/builders/src/components.ts", "../../packages/builders/src/commands.ts", "../../packages/utils/src/args.ts", "../../packages/collection/src/index.ts", "../../packages/rest/src/index.ts", "../../packages/managers/src/index.ts", "../../packages/ws/src/close-codes.ts", "../../packages/ws/src/reconnect.ts", "../../packages/structures/src/resources.ts", "../../packages/structures/src/channels.ts", "../../packages/structures/src/options.ts", "../../packages/structures/src/interactions.ts", "../../packages/structures/src/embed.ts", "../../packages/structures/src/audit-log.ts", "../../packages/structures/src/sticker.ts", "../../packages/structures/src/index.ts"],
4
4
  "sourcesContent": [
5
- "/** Common Discord snowflake-backed structure. */\nexport class BaseStructure {\n public readonly id: string;\n public constructor(id: string) {\n if (!/^\\d{1,20}$/.test(id))\n throw new TypeError(\n \"A Discord structure requires a valid snowflake ID.\",\n );\n this.id = id;\n }\n /** Returns the snowflake ID as a string. */\n public toString(): string {\n return this.id;\n }\n /** Returns the timestamp this snowflake was created at. */\n public get createdAt(): Date {\n return new Date(Number((BigInt(this.id) >> 22n) + 1420070400000n));\n }\n}\n\nexport interface ResourceContext {\n sendMessage(\n channelId: string,\n options: Record<string, unknown> & { content?: string },\n ): Promise<import(\"./index.js\").Message>;\n editMessage(\n channelId: string,\n messageId: string,\n options: Record<string, unknown> & { content?: string },\n ): Promise<import(\"./index.js\").Message>;\n deleteMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void>;\n crosspostMessage(\n channelId: string,\n messageId: string,\n ): Promise<import(\"./index.js\").Message>;\n editChannel?(\n channelId: string,\n options: Record<string, unknown>,\n ): Promise<import(\"./base.js\").Channel>;\n deleteChannel?(channelId: string, reason?: string): Promise<void>;\n addReaction?(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void>;\n removeOwnReaction?(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void>;\n removeReaction?(\n channelId: string,\n messageId: string,\n emoji: string,\n userId: string,\n ): Promise<void>;\n removeAllReactions?(channelId: string, messageId: string): Promise<void>;\n pinMessage?(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void>;\n unpinMessage?(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void>;\n /**\n * A member's permissions from cached state: guild-level, or channel-level\n * (with overwrites) when a channel ID is given. Null when the guild (or\n * channel) is not cached.\n */\n memberPermissions?(\n guildId: string,\n memberId: string,\n roleIds: readonly string[],\n channelId?: string,\n ): import(\"@lunibee/core\").PermissionSet | null;\n kickMember?(\n guildId: string,\n userId: string,\n reason?: string,\n ): Promise<void>;\n banMember?(\n guildId: string,\n userId: string,\n options?: { reason?: string; deleteMessageSeconds?: number },\n ): Promise<void>;\n editMember?(\n guildId: string,\n userId: string,\n options: Record<string, unknown>,\n reason?: string,\n ): Promise<import(\"./resources.js\").GuildMember>;\n addMemberRole?(\n guildId: string,\n userId: string,\n roleId: string,\n reason?: string,\n ): Promise<void>;\n removeMemberRole?(\n guildId: string,\n userId: string,\n roleId: string,\n reason?: string,\n ): Promise<void>;\n /** Collects the client's interactions (a `Collector` over `interactionCreate`). Used by message and interaction collectors. */\n collectInteractions?(\n options: import(\"@lunibee/core\").CollectorOptions<\n import(\"./interactions.js\").Interaction\n >,\n ): import(\"@lunibee/core\").Collector<\n string,\n import(\"./interactions.js\").Interaction\n >;\n editPermissionOverwrite?(\n channelId: string,\n targetId: string,\n changes: PermissionOverwriteChanges,\n options?: { type?: 0 | 1; reason?: string },\n ): Promise<void>;\n}\n\n/**\n * Permissions to change on one overwrite: `true` allows, `false` denies,\n * `null` goes back to inheriting. Permissions not named keep their state.\n */\nexport type PermissionOverwriteChanges = Partial<\n Record<import(\"@lunibee/core\").PermissionName, boolean | null>\n>;\n\n// ─── CDN helpers ──────────────────────────────────────────────────────────────\n\nexport const CDN_BASE = \"https://cdn.discordapp.com\";\n\n/** Options for CDN image URLs. */\nexport interface ImageURLOptions {\n extension?: \"png\" | \"jpg\" | \"webp\" | \"gif\" | \"jpeg\";\n size?: 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096;\n forceStatic?: boolean;\n}\n\n/** Builds a Discord CDN asset URL from a directory path and asset hash, applying\n * animated-hash (`a_`) gif detection, extension and size options. Shared by all\n * hash-backed asset accessors (user/member/role/webhook) to avoid duplicating the logic.\n * @param path CDN directory path, e.g. `/role-icons/{id}`. @param hash Asset hash. @param options Image URL options. */\nexport function cdnURL(\n path: string,\n hash: string,\n options: ImageURLOptions = {},\n): string {\n const isAnimated = hash.startsWith(\"a_\") && !options.forceStatic;\n const ext = options.extension ?? (isAnimated ? \"gif\" : \"png\");\n const size = options.size ? `?size=${options.size}` : \"\";\n return `${CDN_BASE}${path}/${hash}.${ext}${size}`;\n}\n\n// ─── User ─────────────────────────────────────────────────────────────────────\n\nexport class User extends BaseStructure {\n public username: string;\n public globalName: string | null;\n public avatar: string | null;\n public bot: boolean;\n public system: boolean;\n public flags: number;\n public discriminator: string | null;\n public constructor(data: import(\"@lunibee/types\").UserData) {\n super(data.id);\n if (!data.username)\n throw new TypeError(\"A Discord user requires a username.\");\n this.username = data.username;\n this.globalName = data.global_name ?? null;\n this.avatar = data.avatar ?? null;\n this.bot = data.bot ?? false;\n this.system = data.system ?? false;\n this.flags = data.public_flags ?? 0;\n this.discriminator =\n data.discriminator && data.discriminator !== \"0\"\n ? data.discriminator\n : null;\n }\n /** Effective display name — global name, falling back to username. */\n public get displayName(): string {\n return this.globalName ?? this.username;\n }\n /** Returns the user's avatar URL, or null if they have no avatar. */\n public avatarURL(options: ImageURLOptions = {}): string | null {\n if (!this.avatar) return null;\n return cdnURL(`/avatars/${this.id}`, this.avatar, options);\n }\n /** Returns the default avatar URL based on the user's discriminator/snowflake. */\n public defaultAvatarURL(): string {\n const index = this.discriminator\n ? Number(this.discriminator) % 5\n : Number((BigInt(this.id) >> 22n) % 6n);\n return `${CDN_BASE}/embed/avatars/${index}.png`;\n }\n /** Returns the avatar URL if available, falling back to the default avatar URL. */\n public displayAvatarURL(options: ImageURLOptions = {}): string {\n return this.avatarURL(options) ?? this.defaultAvatarURL();\n }\n /** Returns the Discord mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<@${this.id}>`;\n }\n}\n\n// ─── Channel ──────────────────────────────────────────────────────────────────\n\nexport class Channel extends BaseStructure {\n public type: number;\n public name?: string | null;\n public guildId?: string;\n public topic?: string | null;\n public parentId?: string | null;\n public nsfw?: boolean;\n public rateLimitPerUser?: number;\n public position?: number;\n /** Role and member permission overwrites (empty for DMs and when not provided). */\n public permissionOverwrites: import(\"@lunibee/types\").APIOverwrite[];\n readonly #context?: ResourceContext;\n\n /** Creates a channel structure from Discord channel data. */\n public constructor(\n data: import(\"@lunibee/types\").APIChannel,\n context?: ResourceContext,\n ) {\n super(data.id);\n if (!Number.isInteger(data.type) || data.type < 0)\n throw new RangeError(\n \"A Discord channel requires a valid channel type.\",\n );\n this.type = data.type;\n this.name = data.name;\n this.guildId = data.guild_id;\n this.topic = data.topic;\n this.parentId = data.parent_id;\n this.nsfw = data.nsfw;\n this.rateLimitPerUser = data.rate_limit_per_user;\n this.position = data.position;\n this.permissionOverwrites = (data.permission_overwrites ?? []).map(\n (overwrite) => ({ ...overwrite }),\n );\n this.#context = context;\n }\n\n /** Sends a message to this channel. @param options Message payload. @returns The created message. @throws {Error} If the channel is not attached to a client. */\n public send(\n options: Record<string, unknown> & { content?: string },\n ): Promise<import(\"./index.js\").Message> {\n if (!this.#context)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.sendMessage(this.id, options);\n }\n\n /** @deprecated Use {@link Channel.send}. Removed in 0.3.0. */\n public sendMessage(\n options: Record<string, unknown> & { content?: string },\n ): Promise<import(\"./index.js\").Message> {\n return this.send(options);\n }\n\n /** Edits this channel. @param options Channel fields to change. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n public edit(options: Record<string, unknown>): Promise<Channel> {\n if (!this.#context?.editChannel)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.editChannel(this.id, options);\n }\n\n /** Changes only this channel's name. @param name New channel name. @returns The updated channel. @throws {TypeError} If the name is empty. @throws {Error} If the channel is not attached to a client. */\n public editName(name: string): Promise<Channel> {\n if (!name.trim()) throw new TypeError(\"Channel name cannot be empty.\");\n return this.edit({ name });\n }\n\n /** Changes only this channel's topic. @param topic New topic, or null to clear it. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n public editTopic(topic: string | null): Promise<Channel> {\n return this.edit({ topic });\n }\n\n /** Moves this channel to another parent category. @param parentId Parent category ID, or null to remove the parent. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n /**\n * Changes some permissions of one overwrite and keeps the rest: `true`\n * allows, `false` denies, `null` resets to inherited.\n * @param targetId Role or member ID. @param changes Permissions to change.\n * @param options `type` (0 role, 1 member) when the overwrite does not exist yet; audit-log `reason`.\n * @example channel.editPermissionOverwrite(userId, { ViewChannel: true, SendMessages: false }, { type: 1 })\n */\n public editPermissionOverwrite(\n targetId: string,\n changes: PermissionOverwriteChanges,\n options?: { type?: 0 | 1; reason?: string },\n ): Promise<void> {\n if (!this.#context?.editPermissionOverwrite)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.editPermissionOverwrite(\n this.id,\n targetId,\n changes,\n options,\n );\n }\n\n public editParent(parentId: string | null): Promise<Channel> {\n return this.edit({ parent_id: parentId });\n }\n\n /** Deletes this channel. @param reason Audit-log reason. @returns A promise fulfilled when Discord confirms deletion. @throws {Error} If the channel is not attached to a client. */\n public delete(reason?: string): Promise<void> {\n if (!this.#context?.deleteChannel)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.deleteChannel(this.id, reason);\n }\n\n /** Updates this channel using the same resource operation as edit. @param options Channel fields to change. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n public update(options: Record<string, unknown>): Promise<Channel> {\n return this.edit(options);\n }\n\n /** Whether this is a thread (announcement, public or private). */\n public isThread(): boolean {\n return this.type === 10 || this.type === 11 || this.type === 12;\n }\n\n /** Whether messages can be sent in this channel (text, DM, announcement, voice, stage, threads). */\n public isTextBased(): boolean {\n return [0, 1, 2, 3, 5, 10, 11, 12, 13].includes(this.type);\n }\n\n /** Whether this is a voice or stage channel. */\n public isVoiceBased(): boolean {\n return this.type === 2 || this.type === 13;\n }\n\n /** Whether this is a direct-message channel (DM or group DM). */\n public isDMBased(): boolean {\n return this.type === 1 || this.type === 3;\n }\n\n /** Returns the Discord channel mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<#${this.id}>`;\n }\n}\n\n// ─── Guild ────────────────────────────────────────────────────────────────────\n\nexport class Guild extends BaseStructure {\n public name: string;\n public icon: string | null;\n public splash: string | null;\n public banner: string | null;\n public description: string | null;\n public preferredLocale: string;\n public ownerId?: string;\n public features: string[];\n public verificationLevel: number;\n public premiumTier: number;\n public premiumSubscriptionCount: number;\n public memberCount?: number;\n public approximateMemberCount?: number;\n public approximatePresenceCount?: number;\n public vanityUrlCode: string | null;\n public nsfwLevel: number;\n public discoverySplash: string | null;\n /** ID of the rules channel for Community guilds. */\n public rulesChannelId: string | null;\n /** ID of the system messages channel. */\n public systemChannelId: string | null;\n /** Bitfield of system channel flags. */\n public systemChannelFlags: number;\n /** Maximum number of members the guild can have. */\n public maxMembers: number;\n /** Required MFA level for administrators. */\n public mfaLevel: number;\n /** Explicit content filter level. */\n public explicitContentFilter: number;\n /** Default notification level for new members. */\n public defaultMessageNotifications: number;\n /** AFK voice channel, or null. */ public afkChannelId: string | null;\n /** Seconds before a silent member is moved to the AFK channel. */ public afkTimeout?: number;\n /** Whether the server widget is on. */ public widgetEnabled: boolean;\n /** Channel the widget invites to, or null. */ public widgetChannelId:\n string | null;\n /** Application that created the guild, if a bot did. */ public applicationId:\n string | null;\n /** Channel for Discord's community updates, or null. */ public publicUpdatesChannelId:\n string | null;\n /** Channel for safety alerts, or null. */ public safetyAlertsChannelId:\n string | null;\n /** Maximum presences (null for the default limit). */ public maxPresences:\n number | null;\n /** Maximum users in a video channel. */ public maxVideoChannelUsers?: number;\n\n public constructor(data: import(\"@lunibee/types\").APIGuild) {\n super(data.id);\n if (!data.name) throw new TypeError(\"A Discord guild requires a name.\");\n this.name = data.name;\n this.icon = data.icon ?? null;\n this.splash = data.splash ?? null;\n this.banner = data.banner ?? null;\n this.description = data.description ?? null;\n this.preferredLocale = data.preferred_locale ?? \"en-US\";\n this.ownerId = data.owner_id;\n this.features = data.features ?? [];\n this.verificationLevel = data.verification_level ?? 0;\n this.premiumTier = data.premium_tier ?? 0;\n this.premiumSubscriptionCount = data.premium_subscription_count ?? 0;\n this.memberCount = data.member_count ?? data.approximate_member_count;\n this.approximateMemberCount = data.approximate_member_count;\n this.approximatePresenceCount = data.approximate_presence_count;\n this.vanityUrlCode = data.vanity_url_code ?? null;\n this.nsfwLevel = data.nsfw_level ?? 0;\n this.discoverySplash = data.discovery_splash ?? null;\n this.rulesChannelId = data.rules_channel_id ?? null;\n this.systemChannelId = data.system_channel_id ?? null;\n this.systemChannelFlags = data.system_channel_flags ?? 0;\n this.maxMembers = data.max_members ?? 0;\n this.mfaLevel = data.mfa_level ?? 0;\n this.explicitContentFilter = data.explicit_content_filter ?? 0;\n this.defaultMessageNotifications =\n data.default_message_notifications ?? 0;\n this.afkChannelId = data.afk_channel_id ?? null;\n this.afkTimeout = data.afk_timeout;\n this.widgetEnabled = data.widget_enabled ?? false;\n this.widgetChannelId = data.widget_channel_id ?? null;\n this.applicationId = data.application_id ?? null;\n this.publicUpdatesChannelId = data.public_updates_channel_id ?? null;\n this.safetyAlertsChannelId = data.safety_alerts_channel_id ?? null;\n this.maxPresences = data.max_presences ?? null;\n this.maxVideoChannelUsers = data.max_video_channel_users;\n }\n\n /** Returns the guild icon URL, or null if no icon is set. */\n public iconURL(options: ImageURLOptions = {}): string | null {\n if (!this.icon) return null;\n return cdnURL(`/icons/${this.id}`, this.icon, options);\n }\n\n /** Returns the guild splash URL, or null if none. */\n public splashURL(options: ImageURLOptions = {}): string | null {\n if (!this.splash) return null;\n return cdnURL(`/splashes/${this.id}`, this.splash, options);\n }\n\n /** Returns the guild banner URL, or null if none. */\n public bannerURL(options: ImageURLOptions = {}): string | null {\n if (!this.banner) return null;\n return cdnURL(`/banners/${this.id}`, this.banner, options);\n }\n\n /** Returns the guild discovery splash URL, or null if none. */\n public discoverySplashURL(options: ImageURLOptions = {}): string | null {\n if (!this.discoverySplash) return null;\n return cdnURL(\n `/discovery-splashes/${this.id}`,\n this.discoverySplash,\n options,\n );\n }\n\n /** Returns a widget image URL for the guild.\n * @param style Widget style: shield (default), banner1, banner2, banner3, banner4.\n */\n public widgetImageURL(\n style:\n \"shield\" | \"banner1\" | \"banner2\" | \"banner3\" | \"banner4\" = \"shield\",\n ): string {\n return `https://discord.com/api/guilds/${this.id}/widget.png?style=${style}`;\n }\n\n /** Whether the guild has a given feature flag. @param feature Feature string, e.g. \"COMMUNITY\". */\n public hasFeature(feature: string): boolean {\n return this.features.includes(feature);\n }\n\n /** Whether the guild is a Community server. */\n public get isCommunity(): boolean {\n return this.hasFeature(\"COMMUNITY\");\n }\n\n /** Whether the guild is an official Discord Partner. */\n public get isPartnered(): boolean {\n return this.hasFeature(\"PARTNERED\");\n }\n\n /** Whether the guild is verified by Discord. */\n public get isVerified(): boolean {\n return this.hasFeature(\"VERIFIED\");\n }\n\n /** Whether the guild has any active boost subscriptions. */\n public get isBoosted(): boolean {\n return this.premiumSubscriptionCount > 0;\n }\n\n /** Alias for premiumTier — the guild's current Nitro boost level (0–3). */\n public get boostLevel(): number {\n return this.premiumTier;\n }\n\n /** Whether the guild has a vanity URL. */\n public get hasVanityUrl(): boolean {\n return this.vanityUrlCode !== null;\n }\n\n /** Returns the guild's vanity invite URL, or null if none. */\n public get vanityURL(): string | null {\n return this.vanityUrlCode\n ? `https://discord.gg/${this.vanityUrlCode}`\n : null;\n }\n\n /** Returns a human-readable string representation. */\n public override toString(): string {\n return this.name;\n }\n}\n",
6
- "/** Permission overwrite target types. */\nexport enum PermissionOverwriteEnum {\n Role = 0,\n Member = 1,\n}\n/** @deprecated Use {@link PermissionOverwriteEnum}. Removed in 0.3.0. */\nexport const PermissionOverwriteType = PermissionOverwriteEnum;\n/** @deprecated Use {@link PermissionOverwriteEnum}. Removed in 0.3.0. */\nexport type PermissionOverwriteType = PermissionOverwriteEnum;\n\n/** Lunibee idiomatic camelCase permission bitflags. */\nexport const Permission = {\n createInstantInvite: 1n << 0n,\n kickMembers: 1n << 1n,\n banMembers: 1n << 2n,\n administrator: 1n << 3n,\n manageChannels: 1n << 4n,\n manageGuild: 1n << 5n,\n addReactions: 1n << 6n,\n viewAuditLog: 1n << 7n,\n prioritySpeaker: 1n << 8n,\n stream: 1n << 9n,\n viewChannel: 1n << 10n,\n sendMessages: 1n << 11n,\n sendTTSMessages: 1n << 12n,\n manageMessages: 1n << 13n,\n embedLinks: 1n << 14n,\n attachFiles: 1n << 15n,\n readMessageHistory: 1n << 16n,\n mentionEveryone: 1n << 17n,\n useExternalEmojis: 1n << 18n,\n viewGuildInsights: 1n << 19n,\n connect: 1n << 20n,\n speak: 1n << 21n,\n muteMembers: 1n << 22n,\n deafenMembers: 1n << 23n,\n moveMembers: 1n << 24n,\n useVAD: 1n << 25n,\n changeNickname: 1n << 26n,\n manageNicknames: 1n << 27n,\n manageRoles: 1n << 28n,\n manageWebhooks: 1n << 29n,\n manageGuildExpressions: 1n << 30n,\n useApplicationCommands: 1n << 31n,\n requestToSpeak: 1n << 32n,\n manageEvents: 1n << 33n,\n manageThreads: 1n << 34n,\n createPublicThreads: 1n << 35n,\n createPrivateThreads: 1n << 36n,\n useExternalStickers: 1n << 37n,\n sendMessagesInThreads: 1n << 38n,\n useEmbeddedActivities: 1n << 39n,\n moderateMembers: 1n << 40n,\n viewCreatorMonetizationAnalytics: 1n << 41n,\n useSoundboard: 1n << 42n,\n createGuildExpressions: 1n << 43n,\n createEvents: 1n << 44n,\n useExternalSounds: 1n << 45n,\n sendVoiceMessages: 1n << 46n,\n setVoiceChannelStatus: 1n << 48n,\n sendPolls: 1n << 49n,\n useExternalApps: 1n << 50n,\n pinMessages: 1n << 51n,\n bypassSlowmode: 1n << 52n,\n} as const;\n\n/** Canonical PascalCase permission constants. */\nexport const Permissions = {\n CreateInstantInvite: 1n << 0n,\n KickMembers: 1n << 1n,\n BanMembers: 1n << 2n,\n Administrator: 1n << 3n,\n ManageChannels: 1n << 4n,\n ManageGuild: 1n << 5n,\n AddReactions: 1n << 6n,\n ViewAuditLog: 1n << 7n,\n PrioritySpeaker: 1n << 8n,\n Stream: 1n << 9n,\n ViewChannel: 1n << 10n,\n SendMessages: 1n << 11n,\n SendTTSMessages: 1n << 12n,\n ManageMessages: 1n << 13n,\n EmbedLinks: 1n << 14n,\n AttachFiles: 1n << 15n,\n ReadMessageHistory: 1n << 16n,\n MentionEveryone: 1n << 17n,\n UseExternalEmojis: 1n << 18n,\n ViewGuildInsights: 1n << 19n,\n Connect: 1n << 20n,\n Speak: 1n << 21n,\n MuteMembers: 1n << 22n,\n DeafenMembers: 1n << 23n,\n MoveMembers: 1n << 24n,\n UseVAD: 1n << 25n,\n ChangeNickname: 1n << 26n,\n ManageNicknames: 1n << 27n,\n ManageRoles: 1n << 28n,\n ManageWebhooks: 1n << 29n,\n ManageGuildExpressions: 1n << 30n,\n UseApplicationCommands: 1n << 31n,\n RequestToSpeak: 1n << 32n,\n ManageEvents: 1n << 33n,\n ManageThreads: 1n << 34n,\n CreatePublicThreads: 1n << 35n,\n CreatePrivateThreads: 1n << 36n,\n UseExternalStickers: 1n << 37n,\n SendMessagesInThreads: 1n << 38n,\n UseEmbeddedActivities: 1n << 39n,\n ModerateMembers: 1n << 40n,\n ViewCreatorMonetizationAnalytics: 1n << 41n,\n UseSoundboard: 1n << 42n,\n CreateGuildExpressions: 1n << 43n,\n CreateEvents: 1n << 44n,\n UseExternalSounds: 1n << 45n,\n SendVoiceMessages: 1n << 46n,\n SetVoiceChannelStatus: 1n << 48n,\n SendPolls: 1n << 49n,\n UseExternalApps: 1n << 50n,\n PinMessages: 1n << 51n,\n BypassSlowmode: 1n << 52n,\n} as const;\n\n/**\n * Permission flag bits with **bigint** values matching Discord's permission bit\n * positions. Mirrors discord.js's `PermissionFlagsBits`, so bitwise composition\n * (`Flags.A | Flags.B`) OR-s the bits instead of concatenating strings.\n *\n * Implemented as a `const` object rather than a TS `enum` because enums cannot\n * hold bigint members; the same-named union type below preserves usage as a type.\n */\nexport const PermissionFlagsBits = {\n CreateInstantInvite: 1n << 0n,\n KickMembers: 1n << 1n,\n BanMembers: 1n << 2n,\n Administrator: 1n << 3n,\n ManageChannels: 1n << 4n,\n ManageGuild: 1n << 5n,\n AddReactions: 1n << 6n,\n ViewAuditLog: 1n << 7n,\n PrioritySpeaker: 1n << 8n,\n Stream: 1n << 9n,\n ViewChannel: 1n << 10n,\n SendMessages: 1n << 11n,\n SendTTSMessages: 1n << 12n,\n ManageMessages: 1n << 13n,\n EmbedLinks: 1n << 14n,\n AttachFiles: 1n << 15n,\n ReadMessageHistory: 1n << 16n,\n MentionEveryone: 1n << 17n,\n UseExternalEmojis: 1n << 18n,\n ViewGuildInsights: 1n << 19n,\n Connect: 1n << 20n,\n Speak: 1n << 21n,\n MuteMembers: 1n << 22n,\n DeafenMembers: 1n << 23n,\n MoveMembers: 1n << 24n,\n UseVAD: 1n << 25n,\n ChangeNickname: 1n << 26n,\n ManageNicknames: 1n << 27n,\n ManageRoles: 1n << 28n,\n ManageWebhooks: 1n << 29n,\n ManageGuildExpressions: 1n << 30n,\n UseApplicationCommands: 1n << 31n,\n RequestToSpeak: 1n << 32n,\n ManageEvents: 1n << 33n,\n ManageThreads: 1n << 34n,\n CreatePublicThreads: 1n << 35n,\n CreatePrivateThreads: 1n << 36n,\n UseExternalStickers: 1n << 37n,\n SendMessagesInThreads: 1n << 38n,\n UseEmbeddedActivities: 1n << 39n,\n ModerateMembers: 1n << 40n,\n ViewCreatorMonetizationAnalytics: 1n << 41n,\n UseSoundboard: 1n << 42n,\n CreateGuildExpressions: 1n << 43n,\n CreateEvents: 1n << 44n,\n UseExternalSounds: 1n << 45n,\n SendVoiceMessages: 1n << 46n,\n SetVoiceChannelStatus: 1n << 48n,\n SendPolls: 1n << 49n,\n UseExternalApps: 1n << 50n,\n PinMessages: 1n << 51n,\n BypassSlowmode: 1n << 52n,\n} as const;\n\n/** Union of {@link PermissionFlagsBits} values (all bigint). */\nexport type PermissionFlagsBits =\n (typeof PermissionFlagsBits)[keyof typeof PermissionFlagsBits];\n\nexport type PermissionName =\n | keyof typeof Permission\n | keyof typeof Permissions\n | keyof typeof PermissionFlagsBits;\n\nexport type PermissionResolvable =\n | bigint\n | number\n | string\n | PermissionName\n | PermissionFlagsBits\n | PermissionSet\n | PermissionResolvable[];\n\n/** Immutable permission bitfield with direct boolean getters. */\nexport class PermissionSet {\n /** Permission bitfield. */\n public readonly bitfield: bigint;\n\n /** Creates a permission set. @param value Initial permission bitfield or array of permissions. @throws {RangeError} If the value is negative. @throws {TypeError} If the value is not a valid integer. */\n public constructor(value: PermissionResolvable = 0n) {\n try {\n if (Array.isArray(value)) {\n let bit = 0n;\n for (const item of value) {\n bit |= this.#resolve(item);\n }\n this.bitfield = bit;\n } else if (value instanceof PermissionSet) {\n this.bitfield = value.bitfield;\n } else {\n const bitfield = this.#resolve(value);\n if (bitfield < 0n)\n throw new RangeError(\n \"Permission bitfield cannot be negative.\",\n );\n this.bitfield = bitfield;\n }\n } catch (error) {\n if (error instanceof RangeError) throw error;\n throw new TypeError(\n \"Permission bitfield must be a valid non-negative integer.\",\n { cause: error },\n );\n }\n }\n\n // Direct camelCase boolean getters for instant checks (e.g. member.permissions.kickMembers)\n public get createInstantInvite(): boolean {\n return (\n (this.bitfield & Permission.createInstantInvite) ===\n Permission.createInstantInvite\n );\n }\n public get kickMembers(): boolean {\n return (\n (this.bitfield & Permission.kickMembers) === Permission.kickMembers\n );\n }\n public get banMembers(): boolean {\n return (\n (this.bitfield & Permission.banMembers) === Permission.banMembers\n );\n }\n public get administrator(): boolean {\n return (\n (this.bitfield & Permission.administrator) ===\n Permission.administrator\n );\n }\n public get manageChannels(): boolean {\n return (\n (this.bitfield & Permission.manageChannels) ===\n Permission.manageChannels\n );\n }\n public get manageGuild(): boolean {\n return (\n (this.bitfield & Permission.manageGuild) === Permission.manageGuild\n );\n }\n public get addReactions(): boolean {\n return (\n (this.bitfield & Permission.addReactions) ===\n Permission.addReactions\n );\n }\n public get viewAuditLog(): boolean {\n return (\n (this.bitfield & Permission.viewAuditLog) ===\n Permission.viewAuditLog\n );\n }\n public get prioritySpeaker(): boolean {\n return (\n (this.bitfield & Permission.prioritySpeaker) ===\n Permission.prioritySpeaker\n );\n }\n public get stream(): boolean {\n return (this.bitfield & Permission.stream) === Permission.stream;\n }\n public get viewChannel(): boolean {\n return (\n (this.bitfield & Permission.viewChannel) === Permission.viewChannel\n );\n }\n public get sendMessages(): boolean {\n return (\n (this.bitfield & Permission.sendMessages) ===\n Permission.sendMessages\n );\n }\n public get sendTTSMessages(): boolean {\n return (\n (this.bitfield & Permission.sendTTSMessages) ===\n Permission.sendTTSMessages\n );\n }\n public get manageMessages(): boolean {\n return (\n (this.bitfield & Permission.manageMessages) ===\n Permission.manageMessages\n );\n }\n public get embedLinks(): boolean {\n return (\n (this.bitfield & Permission.embedLinks) === Permission.embedLinks\n );\n }\n public get attachFiles(): boolean {\n return (\n (this.bitfield & Permission.attachFiles) === Permission.attachFiles\n );\n }\n public get readMessageHistory(): boolean {\n return (\n (this.bitfield & Permission.readMessageHistory) ===\n Permission.readMessageHistory\n );\n }\n public get mentionEveryone(): boolean {\n return (\n (this.bitfield & Permission.mentionEveryone) ===\n Permission.mentionEveryone\n );\n }\n public get useExternalEmojis(): boolean {\n return (\n (this.bitfield & Permission.useExternalEmojis) ===\n Permission.useExternalEmojis\n );\n }\n public get viewGuildInsights(): boolean {\n return (\n (this.bitfield & Permission.viewGuildInsights) ===\n Permission.viewGuildInsights\n );\n }\n public get connect(): boolean {\n return (this.bitfield & Permission.connect) === Permission.connect;\n }\n public get speak(): boolean {\n return (this.bitfield & Permission.speak) === Permission.speak;\n }\n public get muteMembers(): boolean {\n return (\n (this.bitfield & Permission.muteMembers) === Permission.muteMembers\n );\n }\n public get deafenMembers(): boolean {\n return (\n (this.bitfield & Permission.deafenMembers) ===\n Permission.deafenMembers\n );\n }\n public get moveMembers(): boolean {\n return (\n (this.bitfield & Permission.moveMembers) === Permission.moveMembers\n );\n }\n public get useVAD(): boolean {\n return (this.bitfield & Permission.useVAD) === Permission.useVAD;\n }\n public get changeNickname(): boolean {\n return (\n (this.bitfield & Permission.changeNickname) ===\n Permission.changeNickname\n );\n }\n public get manageNicknames(): boolean {\n return (\n (this.bitfield & Permission.manageNicknames) ===\n Permission.manageNicknames\n );\n }\n public get manageRoles(): boolean {\n return (\n (this.bitfield & Permission.manageRoles) === Permission.manageRoles\n );\n }\n public get manageWebhooks(): boolean {\n return (\n (this.bitfield & Permission.manageWebhooks) ===\n Permission.manageWebhooks\n );\n }\n public get manageGuildExpressions(): boolean {\n return (\n (this.bitfield & Permission.manageGuildExpressions) ===\n Permission.manageGuildExpressions\n );\n }\n public get useApplicationCommands(): boolean {\n return (\n (this.bitfield & Permission.useApplicationCommands) ===\n Permission.useApplicationCommands\n );\n }\n public get requestToSpeak(): boolean {\n return (\n (this.bitfield & Permission.requestToSpeak) ===\n Permission.requestToSpeak\n );\n }\n public get manageEvents(): boolean {\n return (\n (this.bitfield & Permission.manageEvents) ===\n Permission.manageEvents\n );\n }\n public get manageThreads(): boolean {\n return (\n (this.bitfield & Permission.manageThreads) ===\n Permission.manageThreads\n );\n }\n public get createPublicThreads(): boolean {\n return (\n (this.bitfield & Permission.createPublicThreads) ===\n Permission.createPublicThreads\n );\n }\n public get createPrivateThreads(): boolean {\n return (\n (this.bitfield & Permission.createPrivateThreads) ===\n Permission.createPrivateThreads\n );\n }\n public get useExternalStickers(): boolean {\n return (\n (this.bitfield & Permission.useExternalStickers) ===\n Permission.useExternalStickers\n );\n }\n public get sendMessagesInThreads(): boolean {\n return (\n (this.bitfield & Permission.sendMessagesInThreads) ===\n Permission.sendMessagesInThreads\n );\n }\n public get useEmbeddedActivities(): boolean {\n return (\n (this.bitfield & Permission.useEmbeddedActivities) ===\n Permission.useEmbeddedActivities\n );\n }\n public get moderateMembers(): boolean {\n return (\n (this.bitfield & Permission.moderateMembers) ===\n Permission.moderateMembers\n );\n }\n public get viewCreatorMonetizationAnalytics(): boolean {\n return (\n (this.bitfield & Permission.viewCreatorMonetizationAnalytics) ===\n Permission.viewCreatorMonetizationAnalytics\n );\n }\n public get useSoundboard(): boolean {\n return (\n (this.bitfield & Permission.useSoundboard) ===\n Permission.useSoundboard\n );\n }\n public get createGuildExpressions(): boolean {\n return (\n (this.bitfield & Permission.createGuildExpressions) ===\n Permission.createGuildExpressions\n );\n }\n public get createEvents(): boolean {\n return (\n (this.bitfield & Permission.createEvents) ===\n Permission.createEvents\n );\n }\n public get useExternalSounds(): boolean {\n return (\n (this.bitfield & Permission.useExternalSounds) ===\n Permission.useExternalSounds\n );\n }\n public get sendVoiceMessages(): boolean {\n return (\n (this.bitfield & Permission.sendVoiceMessages) ===\n Permission.sendVoiceMessages\n );\n }\n public get sendPolls(): boolean {\n return (this.bitfield & Permission.sendPolls) === Permission.sendPolls;\n }\n public get useExternalApps(): boolean {\n return (\n (this.bitfield & Permission.useExternalApps) ===\n Permission.useExternalApps\n );\n }\n\n /** Checks whether all supplied permissions are present (AND). @param permissions Permission names or raw bits. @returns True when every requested permission is present. */\n public has(...permissions: PermissionResolvable[]): boolean {\n if (permissions.length === 1) {\n const p = permissions[0]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n return (this.bitfield & bit) === bit;\n }\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n if ((this.bitfield & bit) !== bit) return false;\n }\n return true;\n }\n\n /** Checks whether any supplied permission is present (OR). @param permissions Permission names or raw bits. @returns True when at least one requested permission is present. */\n public any(...permissions: PermissionResolvable[]): boolean {\n if (permissions.length === 1) {\n const p = permissions[0]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n return (this.bitfield & bit) !== 0n;\n }\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n if ((this.bitfield & bit) !== 0n) return true;\n }\n return false;\n }\n\n /** Returns the known permission names from `permissions` that this set lacks. @param permissions Permission names or raw bits. */\n public missing(...permissions: PermissionResolvable[]): PermissionName[] {\n const wanted = new PermissionSet(permissions);\n return wanted.toArray().filter((name) => !this.has(name));\n }\n\n /** Returns a new set with permissions added. @param permissions Permission names or raw bits. @returns A new permission set. */\n public add(...permissions: PermissionResolvable[]): PermissionSet {\n let bitfield = this.bitfield;\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n bitfield |= typeof p === \"bigint\" ? p : this.#resolve(p);\n }\n return new PermissionSet(bitfield);\n }\n\n /** Returns a new set with permissions removed. @param permissions Permission names or raw bits. @returns A new permission set. */\n public remove(...permissions: PermissionResolvable[]): PermissionSet {\n let bitfield = this.bitfield;\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n bitfield &= ~(typeof p === \"bigint\" ? p : this.#resolve(p));\n }\n return new PermissionSet(bitfield);\n }\n\n /** Checks equality with another permission set or raw bitfield. @param other Permission set or raw bitfield. @returns True when both values are equal. */\n public equals(other: PermissionSet | bigint | number | string): boolean {\n return (\n this.bitfield ===\n (other instanceof PermissionSet\n ? other.bitfield\n : new PermissionSet(other).bitfield)\n );\n }\n\n /** Returns the decimal permission representation. @returns Decimal permission bitfield. */\n public toString(): string {\n return this.bitfield.toString();\n }\n\n /** Returns known permission names contained in this set. @returns Names of all enabled known permissions. */\n public toArray(): PermissionName[] {\n return (Object.keys(Permission) as PermissionName[]).filter(\n (permission) => this.has(permission),\n );\n }\n\n /** Resolves a named permission, enum value, or raw bit. @param permission Permission name, enum value, or raw bit. @returns Numeric permission bit. */\n /** Names Discord has since renamed, still accepted when resolving a permission by name. */\n static readonly #renamed: Readonly<Record<string, string>> = {\n ManageEmojisAndStickers: \"ManageGuildExpressions\",\n ManageEmojis: \"ManageGuildExpressions\",\n UseSlashCommands: \"UseApplicationCommands\",\n };\n\n #resolve(permission: PermissionResolvable): bigint {\n if (typeof permission === \"bigint\") return permission;\n if (typeof permission === \"number\") return BigInt(permission);\n if (permission instanceof PermissionSet) return permission.bitfield;\n if (Array.isArray(permission)) {\n let bit = 0n;\n for (let i = 0; i < permission.length; i++)\n bit |= this.#resolve(permission[i]!);\n return bit;\n }\n if (typeof permission === \"string\") {\n const renamed = PermissionSet.#renamed[permission];\n if (renamed) return this.#resolve(renamed);\n if (permission in Permission)\n return (Permission as Record<string, bigint>)[permission]!;\n if (permission in Permissions)\n return (Permissions as Record<string, bigint>)[permission]!;\n if (permission in PermissionFlagsBits)\n return (PermissionFlagsBits as Record<string, bigint>)[\n permission\n ]!;\n const lower =\n permission.charAt(0).toLowerCase() + permission.slice(1);\n if (lower in Permission)\n return (Permission as Record<string, bigint>)[lower]!;\n return BigInt(permission);\n }\n return 0n;\n }\n}\n\n/** Permissions bitfield alias. */\nexport class PermissionsBitField extends PermissionSet {\n /** Permission flags bits enum. */\n public static readonly Flags = PermissionFlagsBits;\n /** Permission flags constants. */\n public static readonly All = Permission;\n\n /** Creates a permissions bitfield. @param value Initial permission bitfield or array of permissions. */\n public constructor(value: PermissionResolvable = 0n) {\n super(value);\n }\n}\n\n/** Every known permission bit. */\nconst ALL_PERMISSIONS = Object.values(Permission).reduce(\n (bits, bit) => bits | bit,\n 0n,\n);\n\n/** A role as needed for permission resolution. */\nexport interface PermissionRole {\n id: string;\n permissions: PermissionResolvable;\n}\n\n/** A channel permission overwrite (Discord's `permission_overwrites` entry). */\nexport interface PermissionOverwrite {\n id: string;\n type: PermissionOverwriteEnum | number;\n allow: PermissionResolvable;\n deny: PermissionResolvable;\n}\n\n/** Everything needed to resolve a member's permissions. */\nexport interface PermissionContext {\n guildId: string;\n /** Guild owner ID; the owner has every permission. */\n ownerId?: string;\n memberId: string;\n memberRoleIds: readonly string[];\n /** Guild roles, including `@everyone` (whose ID is the guild ID). */\n roles: readonly PermissionRole[];\n /** Channel overwrites; omit for guild-level permissions. */\n overwrites?: readonly PermissionOverwrite[];\n}\n\nconst bits = (value: PermissionResolvable): bigint =>\n new PermissionSet(value).bitfield;\n\n/**\n * Resolves a member's effective permissions the way Discord does: base\n * permissions from `@everyone` and the member's roles (owner and\n * administrator get everything), then the channel's `@everyone` overwrite,\n * the combined role overwrites, and finally the member overwrite.\n */\nexport function computePermissions(context: PermissionContext): PermissionSet {\n if (context.ownerId !== undefined && context.ownerId === context.memberId)\n return new PermissionSet(ALL_PERMISSIONS);\n const roles = new Map(context.roles.map((role) => [role.id, role]));\n let base = bits(roles.get(context.guildId)?.permissions ?? 0n);\n for (const id of context.memberRoleIds)\n base |= bits(roles.get(id)?.permissions ?? 0n);\n if (base & Permission.administrator)\n return new PermissionSet(ALL_PERMISSIONS);\n const overwrites = context.overwrites ?? [];\n const everyone = overwrites.find((o) => o.id === context.guildId);\n if (everyone) base = (base & ~bits(everyone.deny)) | bits(everyone.allow);\n const memberRoles = new Set(context.memberRoleIds);\n let allow = 0n;\n let deny = 0n;\n for (const overwrite of overwrites)\n if (\n overwrite.type === PermissionOverwriteEnum.Role &&\n overwrite.id !== context.guildId &&\n memberRoles.has(overwrite.id)\n ) {\n allow |= bits(overwrite.allow);\n deny |= bits(overwrite.deny);\n }\n base = (base & ~deny) | allow;\n const member = overwrites.find(\n (o) =>\n o.type === PermissionOverwriteEnum.Member &&\n o.id === context.memberId,\n );\n if (member) base = (base & ~bits(member.deny)) | bits(member.allow);\n return new PermissionSet(base);\n}\n",
7
- "// ─── Gateway Intents ─────────────────────────────────────────────────────────\n\n/** Gateway intent bit flags supported by Discord (PascalCase). */\nexport const GatewayIntentBits = {\n Guilds: 1 << 0,\n GuildMembers: 1 << 1,\n GuildModeration: 1 << 2,\n GuildExpressions: 1 << 3,\n GuildIntegrations: 1 << 4,\n GuildWebhooks: 1 << 5,\n GuildInvites: 1 << 6,\n GuildVoiceStates: 1 << 7,\n GuildPresences: 1 << 8,\n GuildMessages: 1 << 9,\n GuildMessageReactions: 1 << 10,\n GuildMessageTyping: 1 << 11,\n DirectMessages: 1 << 12,\n DirectMessageReactions: 1 << 13,\n DirectMessageTyping: 1 << 14,\n MessageContent: 1 << 15,\n GuildScheduledEvents: 1 << 16,\n AutoModerationConfiguration: 1 << 20,\n AutoModerationExecution: 1 << 21,\n GuildMessagePolls: 1 << 24,\n DirectMessagePolls: 1 << 25,\n} as const;\n\n/** Idiomatic camelCase Gateway intent bit flags supported by Discord. */\nexport const IntentBits = {\n guild: 1 << 0,\n guilds: 1 << 0,\n guildMembers: 1 << 1,\n guildModeration: 1 << 2,\n guildBans: 1 << 2,\n guildExpressions: 1 << 3,\n guildEmojis: 1 << 3,\n guildEmojisAndStickers: 1 << 3,\n guildIntegrations: 1 << 4,\n guildWebhooks: 1 << 5,\n guildInvites: 1 << 6,\n guildVoiceStates: 1 << 7,\n guildPresences: 1 << 8,\n guildMessages: 1 << 9,\n guildMessage: 1 << 9,\n guildMessageReactions: 1 << 10,\n guildMessageTyping: 1 << 11,\n directMessages: 1 << 12,\n directMessageReactions: 1 << 13,\n directMessageTyping: 1 << 14,\n messageContent: 1 << 15,\n guildScheduledEvents: 1 << 16,\n autoModerationConfiguration: 1 << 20,\n autoModerationExecution: 1 << 21,\n guildMessagePolls: 1 << 24,\n directMessagePolls: 1 << 25,\n} as const;\n\n/** Alias for IntentBits. */\nexport const Intents = IntentBits;\n\n/** Gateway intent resolvable value (single bitfield, enum key, or array of bitfields/strings). */\nexport type GatewayIntentResolvable =\n | number\n | keyof typeof GatewayIntentBits\n | keyof typeof IntentBits\n | (\n | number\n | keyof typeof GatewayIntentBits\n | keyof typeof IntentBits\n | string\n )[]\n | { readonly bitfield: number };\n\n/** Resolves any GatewayIntentResolvable into a raw bitfield integer. */\nexport function resolveGatewayIntents(\n intents: GatewayIntentResolvable,\n): number {\n if (typeof intents === \"number\") return intents;\n if (intents && typeof intents === \"object\" && !Array.isArray(intents))\n return intents.bitfield;\n if (Array.isArray(intents)) {\n return intents.reduce<number>((acc, intent) => {\n return acc | resolveGatewayIntents(intent as any);\n }, 0);\n }\n if (typeof intents === \"string\") {\n if (intents in GatewayIntentBits)\n return (GatewayIntentBits as Record<string, number>)[intents]!;\n if (intents in IntentBits)\n return (IntentBits as Record<string, number>)[intents]!;\n const lower = intents.charAt(0).toLowerCase() + intents.slice(1);\n if (lower in IntentBits)\n return (IntentBits as Record<string, number>)[lower]!;\n const num = Number(intents);\n if (!Number.isNaN(num)) return num;\n }\n return 0;\n}\n\n/**\n * Discord.js-familiar intent bitfield.\n * @example new IntentsBitField([IntentsBitField.Flags.Guilds, \"GuildMessages\"])\n */\nexport class IntentsBitField {\n /** Intent flag values by name. */\n public static readonly Flags = GatewayIntentBits;\n /** Raw intent bitfield. */\n public bitfield: number;\n\n public constructor(bits: GatewayIntentResolvable = 0) {\n this.bitfield = resolveGatewayIntents(bits);\n }\n\n /** Whether every given intent is set. */\n public has(bits: GatewayIntentResolvable): boolean {\n const resolved = resolveGatewayIntents(bits);\n return (this.bitfield & resolved) === resolved;\n }\n\n /** Whether any given intent is set. */\n public any(bits: GatewayIntentResolvable): boolean {\n return (this.bitfield & resolveGatewayIntents(bits)) !== 0;\n }\n\n /** Adds intents in place. @returns This bitfield. */\n public add(...bits: GatewayIntentResolvable[]): this {\n for (const bit of bits) this.bitfield |= resolveGatewayIntents(bit);\n return this;\n }\n\n /** Removes intents in place. @returns This bitfield. */\n public remove(...bits: GatewayIntentResolvable[]): this {\n for (const bit of bits) this.bitfield &= ~resolveGatewayIntents(bit);\n return this;\n }\n\n /** Names of the set intents. */\n public toArray(): (keyof typeof GatewayIntentBits)[] {\n return (\n Object.keys(GatewayIntentBits) as (keyof typeof GatewayIntentBits)[]\n ).filter((name) => this.has(GatewayIntentBits[name]));\n }\n\n /** Whether this equals another bitfield. */\n public equals(bits: GatewayIntentResolvable): boolean {\n return this.bitfield === resolveGatewayIntents(bits);\n }\n\n public valueOf(): number {\n return this.bitfield;\n }\n\n public toJSON(): number {\n return this.bitfield;\n }\n}\n\n// ─── Gateway Config ───────────────────────────────────────────────────────────\n\n/** Gateway connection properties (OS, browser, device). */\nexport interface GatewayProperties {\n os?: string;\n browser?: string;\n device?: string;\n [key: string]: unknown;\n}\n/** Gateway presence activity. */\nexport interface GatewayPresenceActivity {\n name: string;\n type?: number;\n url?: string;\n state?: string;\n}\n/** Gateway presence data. */\nexport interface GatewayPresence {\n status?: \"online\" | \"dnd\" | \"idle\" | \"invisible\" | \"offline\";\n activities?: GatewayPresenceActivity[];\n afk?: boolean;\n since?: number | null;\n}\n/** Client configuration. */\nexport interface ClientOptions {\n token: string;\n intents: GatewayIntentResolvable;\n gateway?: GatewayOptions;\n rest?: RESTOptions;\n /** Opt-in bounded per-channel message cache. Messages are not cached by default. */\n messageCache?: { maxSize?: number; ttl?: number };\n /**\n * Which resources the client keeps from Gateway events. Everything is\n * cached by default; large bots can turn off what they do not read.\n * Events are still emitted either way.\n */\n cache?: {\n users?: boolean;\n members?: boolean;\n roles?: boolean;\n emojis?: boolean;\n };\n /**\n * Default `allowed_mentions` for every message the client sends (channel\n * send/edit, replies, interaction replies, edits and follow-ups), e.g.\n * `{ parse: [] }` so nothing pings unless a message says so. A message's\n * own `allowed_mentions` always wins.\n */\n allowedMentions?: AllowedMentions;\n}\n/** Discord's `allowed_mentions` object. */\nexport interface AllowedMentions {\n parse?: (\"users\" | \"roles\" | \"everyone\")[];\n users?: string[];\n roles?: string[];\n replied_user?: boolean;\n}\n/** Gateway connection configuration. */\nexport interface GatewayOptions {\n intents?: GatewayIntentResolvable;\n reconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectBaseDelay?: number;\n reconnectMaxDelay?: number;\n shardId?: number;\n shardCount?: number;\n properties?: GatewayProperties;\n presence?: GatewayPresence;\n}\n\n/** REST request configuration. */\nexport interface RESTOptions {\n timeout?: number;\n retries?: number;\n baseURL?: string;\n}\n",
8
- "/** Discord API snowflake identifier. */\nexport type Snowflake = string;\n\nexport * from \"./gateway.js\";\nexport * from \"./gateway-events.js\";\n\n// ─── Core Discord Objects ─────────────────────────────────────────────────────\n\n/** Discord user object. */\nexport interface UserData {\n id: Snowflake;\n username: string;\n discriminator?: string;\n global_name?: string | null;\n avatar?: string | null;\n bot?: boolean;\n system?: boolean;\n public_flags?: number;\n}\n/** Current authenticated bot user. */\nexport type ClientUser = UserData;\n/** Discord Gateway payload envelope. */\nexport interface GatewayPayload<T = unknown> {\n op: number;\n d: T | null;\n s: number | null;\n t: string | null;\n}\n/** Generic Discord API error payload. */\nexport interface APIError {\n code?: number;\n message?: string;\n errors?: Record<string, unknown>;\n}\n\n// ─── Discord Flags & Enums ────────────────────────────────────────────────────\n\n/** Discord message flags. */\nexport const MessageFlags = {\n Crossposted: 1,\n IsCrosspost: 2,\n SuppressEmbeds: 4,\n SourceMessageDeleted: 8,\n Urgent: 16,\n HasThread: 32,\n Ephemeral: 64,\n Loading: 128,\n IsComponentsV2: 32768,\n} as const;\n/** One {@link MessageFlags} value, usable as a type. */\nexport type MessageFlags = (typeof MessageFlags)[keyof typeof MessageFlags];\n\n/** Discord channel types. */\nexport const ChannelEnum = {\n GuildText: 0,\n DM: 1,\n GuildVoice: 2,\n GroupDM: 3,\n GuildCategory: 4,\n GuildAnnouncement: 5,\n AnnouncementThread: 10,\n PublicThread: 11,\n PrivateThread: 12,\n GuildStageVoice: 13,\n GuildDirectory: 14,\n GuildForum: 15,\n GuildMedia: 16,\n} as const;\n/** One {@link ChannelEnum} value, usable as a type. */\nexport type ChannelEnum = (typeof ChannelEnum)[keyof typeof ChannelEnum];\n\n/** Discord component types. */\nexport const ComponentEnum = {\n ActionRow: 1,\n Button: 2,\n StringSelect: 3,\n TextInput: 4,\n UserSelect: 5,\n RoleSelect: 6,\n MentionableSelect: 7,\n ChannelSelect: 8,\n Section: 9,\n TextDisplay: 10,\n Thumbnail: 11,\n MediaGallery: 12,\n File: 13,\n Separator: 14,\n ContentInventoryEntry: 16,\n Container: 17,\n} as const;\n/** One {@link ComponentEnum} value, usable as a type. */\nexport type ComponentEnum = (typeof ComponentEnum)[keyof typeof ComponentEnum];\n\n/** Discord button style types. */\nexport const ButtonType = {\n Primary: 1,\n Secondary: 2,\n Success: 3,\n Danger: 4,\n Link: 5,\n Premium: 6,\n} as const;\n/** One {@link ButtonType} value, usable as a type: `style: ButtonType`. */\nexport type ButtonType = (typeof ButtonType)[keyof typeof ButtonType];\n\n/** Discord text input style types. */\nexport const TextInputType = {\n Short: 1,\n Paragraph: 2,\n} as const;\n/** One {@link TextInputType} value, usable as a type. */\nexport type TextInputType = (typeof TextInputType)[keyof typeof TextInputType];\n\n/** Discord interaction response types. */\nexport const InteractionResponseEnum = {\n Pong: 1,\n ChannelMessage: 4,\n DeferredChannelMessage: 5,\n DeferredMessageUpdate: 6,\n MessageUpdate: 7,\n Autocomplete: 8,\n Modal: 9,\n} as const;\n/** One {@link InteractionResponseEnum} value, usable as a type. */\nexport type InteractionResponseEnum =\n (typeof InteractionResponseEnum)[keyof typeof InteractionResponseEnum];\n\n/** Discord sticker format types. */\nexport const StickerFormatEnum = {\n PNG: 1,\n APNG: 2,\n Lottie: 3,\n GIF: 4,\n} as const;\n/** One {@link StickerFormatEnum} value, usable as a type. */\nexport type StickerFormatEnum =\n (typeof StickerFormatEnum)[keyof typeof StickerFormatEnum];\n\n/** Discord sticker types. */\nexport const StickerEnum = {\n Standard: 1,\n Guild: 2,\n} as const;\n/** One {@link StickerEnum} value, usable as a type. */\nexport type StickerEnum = (typeof StickerEnum)[keyof typeof StickerEnum];\n\n/** Discord verification levels. */\nexport const VerificationLevel = {\n None: 0,\n Low: 1,\n Medium: 2,\n High: 3,\n VeryHigh: 4,\n} as const;\n\n/** Discord premium tiers. */\nexport const PremiumTier = {\n None: 0,\n Tier1: 1,\n Tier2: 2,\n Tier3: 3,\n} as const;\n\n// ─── Embeds ───────────────────────────────────────────────────────────────────\n\n/** Raw Discord embed footer object. */\nexport interface APIEmbedFooter {\n text: string;\n icon_url?: string;\n proxy_icon_url?: string;\n}\n/** Raw Discord embed image/thumbnail/video object. */\nexport interface APIEmbedMedia {\n url: string;\n proxy_url?: string;\n height?: number;\n width?: number;\n}\n/** Raw Discord embed provider object. */\nexport interface APIEmbedProvider {\n name?: string;\n url?: string;\n}\n/** Raw Discord embed author object. */\nexport interface APIEmbedAuthor {\n name: string;\n url?: string;\n icon_url?: string;\n proxy_icon_url?: string;\n}\n/** Raw Discord embed field object. */\nexport interface APIEmbedField {\n name: string;\n value: string;\n inline?: boolean;\n}\n/** Raw Discord embed object. */\nexport interface APIEmbed {\n title?: string;\n type?: string;\n description?: string;\n url?: string;\n timestamp?: string;\n color?: number;\n footer?: APIEmbedFooter;\n image?: APIEmbedMedia;\n thumbnail?: APIEmbedMedia;\n video?: APIEmbedMedia;\n provider?: APIEmbedProvider;\n author?: APIEmbedAuthor;\n fields?: APIEmbedField[];\n}\n\n// ─── Message Components ───────────────────────────────────────────────────────\n\n/** Raw Discord select menu option. */\nexport interface APISelectMenuOption {\n label: string;\n value: string;\n description?: string;\n emoji?: APIPartialEmoji;\n default?: boolean;\n}\n/** Raw Discord emoji (partial, as used in components). */\nexport interface APIPartialEmoji {\n id?: Snowflake | null;\n name?: string | null;\n animated?: boolean;\n}\n/** Raw Discord button component. */\nexport interface APIButtonComponent {\n type: 2;\n style: number;\n label?: string;\n emoji?: APIPartialEmoji;\n custom_id?: string;\n url?: string;\n sku_id?: string;\n disabled?: boolean;\n}\n/** Raw Discord select menu component. */\nexport interface APISelectMenuComponent {\n type: 3 | 5 | 6 | 7 | 8;\n custom_id: string;\n options?: APISelectMenuOption[];\n channel_types?: number[];\n placeholder?: string;\n min_values?: number;\n max_values?: number;\n disabled?: boolean;\n}\n/** Raw Discord text input component. */\nexport interface APITextInputComponent {\n type: 4;\n custom_id: string;\n style: number;\n label: string;\n min_length?: number;\n max_length?: number;\n required?: boolean;\n value?: string;\n placeholder?: string;\n}\n/** Union of all raw message component types. */\nexport type APIMessageActionRowComponent =\n APIButtonComponent | APISelectMenuComponent | APITextInputComponent;\n/** Raw Discord action row component. */\nexport interface APIActionRowComponent {\n type: 1;\n id?: number;\n components: APIMessageActionRowComponent[];\n}\n/** Union including action rows and V2 components. */\nexport type APIMessageComponent =\n APIActionRowComponent | { type: Exclude<number, 1>; [key: string]: any };\n\n// ─── Message payloads ────────────────────────────────────────────────────────\n\n/** A Discord payload, or a builder that serialises to one (its `toJSON()` runs when the request is sent). */\nexport type Buildable<T> = T | { toJSON(): T };\n\n/**\n * A message Lunibee sends: channel send and edit, message reply and edit,\n * interaction replies, follow-ups and updates. Embeds and components may be\n * builders or raw objects. Other Discord fields pass through unchanged.\n */\nexport interface MessagePayload {\n content?: string;\n embeds?: Buildable<APIEmbed>[];\n components?: Buildable<APIMessageComponent>[];\n allowed_mentions?: import(\"./gateway.js\").AllowedMentions;\n /** Discord message flags, e.g. `MessageFlags.SuppressEmbeds`. */\n flags?: number;\n tts?: boolean;\n [key: string]: unknown;\n}\n\n// ─── Attachments ─────────────────────────────────────────────────────────────\n\n/** Raw Discord attachment object. */\nexport interface APIAttachment {\n id: Snowflake;\n filename: string;\n description?: string | null;\n content_type?: string;\n size: number;\n url: string;\n proxy_url: string;\n height?: number | null;\n width?: number | null;\n ephemeral?: boolean;\n duration_secs?: number;\n waveform?: string;\n flags?: number;\n}\n\n// ─── Stickers ────────────────────────────────────────────────────────────────\n\n/** Compact sticker item as included in messages. */\nexport interface APIStickerItem {\n id: Snowflake;\n name: string;\n format_type: number;\n}\n/** Full Discord sticker object. */\nexport interface APISticker {\n id: Snowflake;\n pack_id?: Snowflake;\n name: string;\n description?: string | null;\n tags?: string;\n type: number;\n format_type: number;\n available?: boolean;\n guild_id?: Snowflake;\n user?: UserData;\n sort_value?: number;\n}\n\n// ─── Messages ────────────────────────────────────────────────────────────────\n\n/** Raw Discord message reference. */\nexport interface APIMessageReference {\n type?: number;\n message_id?: Snowflake;\n channel_id?: Snowflake;\n guild_id?: Snowflake;\n fail_if_not_exists?: boolean;\n}\n/** Raw Discord message reaction. */\nexport interface APIMessageReaction {\n count: number;\n count_details?: Record<string, number>;\n me?: boolean;\n me_burst?: boolean;\n emoji: APIPartialEmoji;\n burst_colors?: string[];\n}\n/** Raw Discord poll object. */\nexport interface APIPoll {\n question: { text?: string; emoji?: APIPartialEmoji };\n answers: Array<{\n answer_id: number;\n poll_media: { text?: string; emoji?: APIPartialEmoji };\n }>;\n expiry: string | null;\n allow_multiselect: boolean;\n layout_type: number;\n results?: {\n is_finalized: boolean;\n answer_counts: Array<{ id: number; count: number; me_voted: boolean }>;\n };\n}\n/** A forwarded message's snapshot of the original. */\nexport interface APIMessageSnapshot {\n message: Partial<\n Pick<\n APIMessage,\n | \"type\"\n | \"content\"\n | \"embeds\"\n | \"attachments\"\n | \"timestamp\"\n | \"edited_timestamp\"\n | \"flags\"\n | \"mentions\"\n | \"mention_roles\"\n | \"sticker_items\"\n | \"components\"\n >\n >;\n}\n/** Raw Discord message object. */\nexport interface APIMessage {\n id: Snowflake;\n channel_id: Snowflake;\n author: UserData;\n content: string;\n timestamp?: string;\n edited_timestamp?: string | null;\n tts?: boolean;\n mention_everyone?: boolean;\n mentions?: UserData[];\n mention_roles?: Snowflake[];\n mention_channels?: Array<Record<string, unknown>>;\n attachments?: APIAttachment[];\n embeds?: APIEmbed[];\n reactions?: APIMessageReaction[];\n nonce?: string | number | null;\n pinned?: boolean;\n webhook_id?: Snowflake;\n type?: number;\n activity?: Record<string, unknown>;\n application?: Record<string, unknown>;\n application_id?: Snowflake;\n message_reference?: APIMessageReference;\n flags?: number;\n referenced_message?: APIMessage | null;\n interaction_metadata?: Record<string, unknown>;\n thread?: Record<string, unknown>;\n components?: APIMessageComponent[];\n sticker_items?: APIStickerItem[];\n stickers?: APISticker[];\n position?: number;\n role_subscription_data?: Record<string, unknown>;\n purchase_notification?: Record<string, unknown>;\n poll?: APIPoll;\n /** Forwarded messages: a partial copy of the original (content, embeds, attachments, …). */\n message_snapshots?: APIMessageSnapshot[];\n guild_id?: Snowflake;\n /** The author's guild member, on guild messages from the Gateway (without `user`; the author is the user). */\n member?: Omit<APIGuildMember, \"user\"> & { user?: UserData };\n}\n\n// ─── Channels ────────────────────────────────────────────────────────────────\n\n/** Raw Discord channel object. */\nexport interface APIChannel {\n id: Snowflake;\n type: number;\n guild_id?: Snowflake;\n position?: number;\n permission_overwrites?: APIOverwrite[];\n name?: string | null;\n topic?: string | null;\n nsfw?: boolean;\n last_message_id?: Snowflake | null;\n bitrate?: number;\n user_limit?: number;\n rate_limit_per_user?: number;\n recipients?: UserData[];\n icon?: string | null;\n owner_id?: Snowflake;\n application_id?: Snowflake;\n parent_id?: Snowflake | null;\n last_pin_timestamp?: string | null;\n rtc_region?: string | null;\n video_quality_mode?: number;\n message_count?: number;\n member_count?: number;\n thread_metadata?: APIThreadMetadata;\n default_auto_archive_duration?: number;\n flags?: number;\n total_message_sent?: number;\n available_tags?: APIForumTag[];\n default_reaction_emoji?: APIPartialEmoji | null;\n default_thread_rate_limit_per_user?: number;\n default_sort_order?: number | null;\n default_forum_layout?: number;\n}\n\n/** Raw Discord thread metadata. */\nexport interface APIThreadMetadata {\n archived: boolean;\n auto_archive_duration: number;\n archive_timestamp: string;\n locked: boolean;\n invitable?: boolean;\n create_timestamp?: string | null;\n}\n\n/** Raw Discord forum tag. */\nexport interface APIForumTag {\n id: Snowflake;\n name: string;\n moderated: boolean;\n emoji_id?: Snowflake | null;\n emoji_name?: string | null;\n}\n\n/** Raw Discord thread member. */\nexport interface APIThreadMember {\n id?: Snowflake;\n user_id?: Snowflake;\n join_timestamp: string;\n flags: number;\n member?: APIGuildMember;\n}\n\n// ─── Roles ────────────────────────────────────────────────────────────────────\n\n/** Raw Discord role object. */\nexport interface APIRole {\n id: Snowflake;\n name: string;\n color: number;\n hoist: boolean;\n icon?: string | null;\n unicode_emoji?: string | null;\n position: number;\n permissions: string;\n managed: boolean;\n mentionable: boolean;\n tags?: Record<string, unknown>;\n flags?: number;\n}\n\n// ─── Emoji ────────────────────────────────────────────────────────────────────\n\n/** Raw Discord emoji object. */\nexport interface APIEmoji {\n id: Snowflake | null;\n name: string | null;\n roles?: Snowflake[];\n user?: UserData;\n require_colons?: boolean;\n managed?: boolean;\n animated?: boolean;\n available?: boolean;\n}\n\n// ─── Guilds ───────────────────────────────────────────────────────────────────\n\n/** Raw Discord guild object. */\nexport interface APIGuild {\n id: Snowflake;\n name: string;\n icon?: string | null;\n icon_hash?: string | null;\n splash?: string | null;\n discovery_splash?: string | null;\n owner?: boolean;\n owner_id?: Snowflake;\n permissions?: string;\n afk_channel_id?: Snowflake | null;\n afk_timeout?: number;\n widget_enabled?: boolean;\n widget_channel_id?: Snowflake | null;\n verification_level?: number;\n default_message_notifications?: number;\n explicit_content_filter?: number;\n roles?: APIRole[];\n emojis?: APIEmoji[];\n stickers?: APISticker[];\n features?: string[];\n mfa_level?: number;\n application_id?: Snowflake | null;\n system_channel_id?: Snowflake | null;\n system_channel_flags?: number;\n rules_channel_id?: Snowflake | null;\n max_presences?: number | null;\n max_members?: number;\n vanity_url_code?: string | null;\n description?: string | null;\n banner?: string | null;\n premium_tier?: number;\n premium_subscription_count?: number;\n preferred_locale?: string;\n public_updates_channel_id?: Snowflake | null;\n max_video_channel_users?: number;\n approximate_member_count?: number;\n approximate_presence_count?: number;\n nsfw_level?: number;\n safety_alerts_channel_id?: Snowflake | null;\n member_count?: number;\n}\n\n// ─── Welcome Screen ───────────────────────────────────────────────────────────\n\nexport interface APIWelcomeScreenChannel {\n channel_id: Snowflake;\n description: string;\n emoji_id: Snowflake | null;\n emoji_name: string | null;\n}\n\nexport interface APIGuildWelcomeScreen {\n description: string | null;\n welcome_channels: APIWelcomeScreenChannel[];\n}\n\n// ─── Guild Onboarding ─────────────────────────────────────────────────────────\n\nexport interface APIOnboardingPromptOption {\n id: Snowflake;\n channel_ids: Snowflake[];\n role_ids: Snowflake[];\n emoji?: APIPartialEmoji;\n title: string;\n description: string | null;\n}\n\nexport interface APIOnboardingPrompt {\n id: Snowflake;\n type: number;\n options: APIOnboardingPromptOption[];\n title: string;\n single_select: boolean;\n required: boolean;\n in_onboarding: boolean;\n}\n\nexport interface APIGuildOnboarding {\n guild_id: Snowflake;\n prompts: APIOnboardingPrompt[];\n default_channel_ids: Snowflake[];\n enabled: boolean;\n mode: number;\n}\n\n/** Raw Discord guild member object. */\nexport interface APIGuildMember {\n user: UserData;\n nick?: string | null;\n avatar?: string | null;\n roles: Snowflake[];\n joined_at: string;\n premium_since?: string | null;\n deaf?: boolean;\n mute?: boolean;\n flags?: number;\n pending?: boolean;\n permissions?: string;\n communication_disabled_until?: string | null;\n guild_id?: Snowflake;\n}\n\n// ─── Voice ────────────────────────────────────────────────────────────────────\n\n/** Raw Discord voice state object. */\nexport interface APIVoiceState {\n guild_id?: Snowflake;\n channel_id?: Snowflake | null;\n user_id: Snowflake;\n member?: APIGuildMember;\n session_id: string;\n deaf: boolean;\n mute: boolean;\n self_deaf: boolean;\n self_mute: boolean;\n self_stream?: boolean;\n self_video: boolean;\n suppress: boolean;\n request_to_speak_timestamp?: string | null;\n}\n\n/** Raw Discord voice server update event. */\nexport interface APIVoiceServerUpdate {\n token: string;\n guild_id: Snowflake;\n endpoint?: string | null;\n}\n\n// ─── Presence ────────────────────────────────────────────────────────────────\n\n/** Raw Discord activity object. */\n/** Discord activity types, for presences (`setPresence({ activities: [{ name, type: ActivityEnum.Watching }] })`). */\nexport const ActivityEnum = {\n Playing: 0,\n Streaming: 1,\n Listening: 2,\n Watching: 3,\n Custom: 4,\n Competing: 5,\n} as const;\n/** One {@link ActivityEnum} value, usable as a type. */\nexport type ActivityEnum = (typeof ActivityEnum)[keyof typeof ActivityEnum];\n\nexport interface APIActivity {\n name: string;\n type: number;\n url?: string | null;\n created_at: number;\n state?: string | null;\n details?: string | null;\n emoji?: APIPartialEmoji | null;\n}\n\n/** Raw Discord presence update event. */\nexport interface APIPresenceUpdate {\n user: { id: Snowflake } & Partial<UserData>;\n guild_id: Snowflake;\n status: string;\n activities: APIActivity[];\n client_status: { desktop?: string; mobile?: string; web?: string };\n}\n\n// ─── Typing ───────────────────────────────────────────────────────────────────\n\n/** Raw Discord typing start event. */\nexport interface APITypingStart {\n channel_id: Snowflake;\n guild_id?: Snowflake;\n user_id: Snowflake;\n timestamp: number;\n member?: APIGuildMember;\n}\n\n// ─── Guilds ──────────────────────────────────────────────────────────────────\n\n/** Raw Discord guild preview. */\nexport interface APIGuildPreview {\n id: Snowflake;\n name: string;\n icon: string | null;\n splash: string | null;\n discovery_splash: string | null;\n emojis: unknown[];\n features: string[];\n approximate_member_count: number;\n approximate_presence_count: number;\n description: string | null;\n stickers: unknown[];\n}\n\n// ─── Invites ─────────────────────────────────────────────────────────────────\n\n/** Raw Discord invite. */\nexport interface APIInvite {\n code: string;\n guild?: Partial<APIGuild>;\n channel: Partial<APIChannel>;\n inviter?: UserData;\n target_type?: number;\n target_user?: UserData;\n approximate_presence_count?: number;\n approximate_member_count?: number;\n}\n\n/** Raw Discord invite create event. */\nexport interface APIInviteCreate {\n channel_id: Snowflake;\n code: string;\n created_at: string;\n guild_id?: Snowflake;\n inviter?: UserData;\n max_age: number;\n max_uses: number;\n target_type?: number;\n target_user?: UserData;\n temporary: boolean;\n uses: number;\n}\n\n/** Raw Discord invite delete event. */\nexport interface APIInviteDelete {\n channel_id: Snowflake;\n guild_id?: Snowflake;\n code: string;\n}\n\n// ─── Webhooks ────────────────────────────────────────────────────────────────\n\n/** Raw Discord webhooks update event. */\nexport interface APIWebhooksUpdate {\n guild_id: Snowflake;\n channel_id: Snowflake;\n}\n\n/** Raw Discord webhook object. */\nexport interface APIWebhook {\n id: Snowflake;\n type: number;\n guild_id?: Snowflake | null;\n channel_id?: Snowflake | null;\n user?: UserData;\n name?: string | null;\n avatar?: string | null;\n token?: string;\n application_id?: Snowflake | null;\n url?: string;\n}\n\n// ─── AutoMod ─────────────────────────────────────────────────────────────────\n\n/** Raw Discord AutoMod action. */\nexport interface APIAutoModerationAction {\n type: number;\n metadata?: {\n channel_id?: Snowflake;\n duration_seconds?: number;\n custom_message?: string;\n };\n}\n\n// ─── Audit Logs ──────────────────────────────────────────────────────────────\n\n/** Raw Discord audit log change object. */\nexport interface APIAuditLogChange {\n new_value?: unknown;\n old_value?: unknown;\n key: string;\n}\n\n/** Raw Discord audit log entry options object. */\nexport interface APIAuditLogOptions {\n app_id?: Snowflake;\n auto_moderation_rule_name?: string;\n auto_moderation_rule_trigger_type?: string;\n channel_id?: Snowflake;\n count?: string;\n delete_member_days?: string;\n id?: Snowflake;\n members_removed?: string;\n message_id?: Snowflake;\n role_name?: string;\n type?: string;\n integration_type?: string;\n}\n\n/** Raw Discord audit log entry object. */\nexport interface APIAuditLogEntry {\n target_id: string | null;\n changes?: APIAuditLogChange[];\n user_id: Snowflake | null;\n id: Snowflake;\n action_type: number;\n options?: APIAuditLogOptions;\n reason?: string;\n}\n\n/** Raw Discord audit log object. */\nexport interface APIAuditLog {\n audit_log_entries: APIAuditLogEntry[];\n guild_scheduled_events: APIGuildScheduledEvent[];\n integrations: Array<Record<string, unknown>>;\n threads: APIChannel[];\n users: UserData[];\n webhooks: APIWebhook[];\n application_commands: APIApplicationCommand[];\n auto_moderation_rules: APIAutoModerationRule[];\n}\n\n/** Raw Discord AutoMod rule object. */\nexport interface APIAutoModerationRule {\n id: Snowflake;\n guild_id: Snowflake;\n name: string;\n creator_id: Snowflake;\n event_type: number;\n trigger_type: number;\n trigger_metadata: Record<string, unknown>;\n actions: APIAutoModerationAction[];\n enabled: boolean;\n exempt_roles: Snowflake[];\n exempt_channels: Snowflake[];\n}\n\n/** Raw Discord AutoMod action execution event. */\nexport interface APIAutoModerationActionExecution {\n guild_id: Snowflake;\n action: APIAutoModerationAction;\n rule_id: Snowflake;\n rule_trigger_type: number;\n user_id: Snowflake;\n channel_id?: Snowflake;\n message_id?: Snowflake;\n alert_system_message_id?: Snowflake;\n content: string;\n matched_keyword?: string | null;\n matched_content?: string | null;\n}\n\n// ─── Scheduled Events ─────────────────────────────────────────────────────────\n\n/** Raw Discord guild scheduled event entity metadata. */\nexport interface APIGuildScheduledEventEntityMetadata {\n location?: string;\n}\n\n/** Raw Discord guild scheduled event object. */\nexport interface APIGuildScheduledEvent {\n id: Snowflake;\n guild_id: Snowflake;\n channel_id?: Snowflake | null;\n creator_id?: Snowflake | null;\n name: string;\n description?: string | null;\n scheduled_start_time: string;\n scheduled_end_time?: string | null;\n privacy_level: number;\n status: number;\n entity_type: number;\n entity_id?: Snowflake | null;\n entity_metadata?: APIGuildScheduledEventEntityMetadata | null;\n creator?: UserData;\n user_count?: number;\n image?: string | null;\n}\n\n// ─── Stage Instances ─────────────────────────────────────────────────────────\n\n/** Raw Discord stage instance object. */\nexport interface APIStageInstance {\n id: Snowflake;\n guild_id: Snowflake;\n channel_id: Snowflake;\n topic: string;\n privacy_level: number;\n discoverable_disabled?: boolean;\n guild_scheduled_event_id?: Snowflake | null;\n}\n\n// ─── Application Commands ─────────────────────────────────────────────────────\n\n/** Discord application command option types. */\nexport const ApplicationCommandOptionEnum = {\n SubCommand: 1,\n SubCommandGroup: 2,\n String: 3,\n Integer: 4,\n Boolean: 5,\n User: 6,\n Channel: 7,\n Role: 8,\n Mentionable: 9,\n Number: 10,\n Attachment: 11,\n} as const;\n/** One {@link ApplicationCommandOptionEnum} value, usable as a type. */\nexport type ApplicationCommandOptionEnum =\n (typeof ApplicationCommandOptionEnum)[keyof typeof ApplicationCommandOptionEnum];\n\n/** Discord application command types. */\nexport const ApplicationCommandEnum = {\n ChatInput: 1,\n User: 2,\n Message: 3,\n} as const;\n/** One {@link ApplicationCommandEnum} value, usable as a type. */\nexport type ApplicationCommandEnum =\n (typeof ApplicationCommandEnum)[keyof typeof ApplicationCommandEnum];\n\n/** Raw Discord application command option. */\nexport interface APIApplicationCommandOption {\n type: number;\n name: string;\n description: string;\n required?: boolean;\n choices?: Array<{ name: string; value: string | number }>;\n options?: APIApplicationCommandOption[];\n min_value?: number;\n max_value?: number;\n min_length?: number;\n max_length?: number;\n autocomplete?: boolean;\n channel_types?: number[];\n}\n\n/** Raw Discord application command object (from API). */\nexport interface APIApplicationCommand {\n id: Snowflake;\n type?: number;\n application_id: Snowflake;\n guild_id?: Snowflake;\n name: string;\n description: string;\n options?: APIApplicationCommandOption[];\n default_member_permissions?: string | null;\n /** @deprecated Discord deprecated this field. Use `contexts`. Removed in 0.3.0. */\n dm_permission?: boolean;\n /** Where the command can be used: 0 guilds, 1 the bot's DMs, 2 other DMs. */\n contexts?: number[];\n nsfw?: boolean;\n version: Snowflake;\n}\n\n/** Data for creating/overwriting an application command. */\nexport interface ApplicationCommandData {\n name: string;\n description: string;\n type?: number;\n options?: APIApplicationCommandOption[];\n default_member_permissions?: string | null;\n /** @deprecated Discord deprecated this field. Use `contexts`. Removed in 0.3.0. */\n dm_permission?: boolean;\n /** Where the command can be used: 0 guilds, 1 the bot's DMs, 2 other DMs. */\n contexts?: number[];\n nsfw?: boolean;\n}\n\n/** A channel permission overwrite for a role (type 0) or member (type 1). */\nexport interface APIOverwrite {\n id: Snowflake;\n type: 0 | 1;\n /** Allowed permission bits as a decimal string. */\n allow: string;\n /** Denied permission bits as a decimal string. */\n deny: string;\n}\n\n// ─── Soundboard & Monetization ───────────────────────────────────────────────\n/** Raw Discord soundboard sound. */\nexport interface APISoundboardSound {\n sound_id: string;\n name: string;\n volume: number;\n emoji_id: string | null;\n emoji_name: string | null;\n guild_id?: string;\n available: boolean;\n user?: UserData;\n}\n\n/** Raw Discord SKU. */\nexport interface APISKU {\n id: string;\n type: number;\n application_id: string;\n name: string;\n slug: string;\n flags: number;\n}\n\n/** Raw Discord entitlement. */\nexport interface APIEntitlement {\n id: string;\n sku_id: string;\n application_id: string;\n user_id?: string;\n guild_id?: string;\n type: number;\n deleted: boolean;\n starts_at?: string | null;\n ends_at?: string | null;\n consumed?: boolean;\n}\n\n/** Raw Discord subscription. */\nexport interface APISubscription {\n id: string;\n user_id: string;\n sku_ids: string[];\n entitlement_ids: string[];\n current_period_start: string;\n current_period_end: string;\n status: number;\n canceled_at: string | null;\n country?: string;\n}\n\n// ─── Deprecated names (0.2.2) ────────────────────────────────────────────────\n// Kept so existing bots keep working; removed in 0.3.0. `…Style` became `…Type`\n// and `…Type` became `…Enum`.\n\n/** @deprecated Use {@link ButtonType}. Removed in 0.3.0. */\nexport const ButtonStyle = ButtonType;\n/** @deprecated Use {@link ButtonType}. Removed in 0.3.0. */\nexport type ButtonStyle = ButtonType;\n/** @deprecated Use {@link TextInputType}. Removed in 0.3.0. */\nexport const TextInputStyle = TextInputType;\n/** @deprecated Use {@link TextInputType}. Removed in 0.3.0. */\nexport type TextInputStyle = TextInputType;\n/** @deprecated Use {@link ChannelEnum}. Removed in 0.3.0. */\nexport const ChannelType = ChannelEnum;\n/** @deprecated Use {@link ChannelEnum}. Removed in 0.3.0. */\nexport type ChannelType = ChannelEnum;\n/** @deprecated Use {@link ComponentEnum}. Removed in 0.3.0. */\nexport const ComponentType = ComponentEnum;\n/** @deprecated Use {@link ComponentEnum}. Removed in 0.3.0. */\nexport type ComponentType = ComponentEnum;\n/** @deprecated Use {@link InteractionResponseEnum}. Removed in 0.3.0. */\nexport const InteractionResponseType = InteractionResponseEnum;\n/** @deprecated Use {@link InteractionResponseEnum}. Removed in 0.3.0. */\nexport type InteractionResponseType = InteractionResponseEnum;\n/** @deprecated Use {@link ApplicationCommandEnum}. Removed in 0.3.0. */\nexport const ApplicationCommandType = ApplicationCommandEnum;\n/** @deprecated Use {@link ApplicationCommandEnum}. Removed in 0.3.0. */\nexport type ApplicationCommandType = ApplicationCommandEnum;\n/** @deprecated Use {@link ApplicationCommandOptionEnum}. Removed in 0.3.0. */\nexport const ApplicationCommandOptionType = ApplicationCommandOptionEnum;\n/** @deprecated Use {@link ApplicationCommandOptionEnum}. Removed in 0.3.0. */\nexport type ApplicationCommandOptionType = ApplicationCommandOptionEnum;\n/** @deprecated Use {@link StickerEnum}. Removed in 0.3.0. */\nexport const StickerType = StickerEnum;\n/** @deprecated Use {@link StickerEnum}. Removed in 0.3.0. */\nexport type StickerType = StickerEnum;\n/** @deprecated Use {@link StickerFormatEnum}. Removed in 0.3.0. */\nexport const StickerFormatType = StickerFormatEnum;\n/** @deprecated Use {@link StickerFormatEnum}. Removed in 0.3.0. */\nexport type StickerFormatType = StickerFormatEnum;\n",
9
- "/** Library version and source URL used for the Discord-compliant User-Agent. */\nimport packageJson from \"../package.json\" with { type: \"json\" };\nconst LIBRARY_VERSION = packageJson.version;\nconst LIBRARY_URL = \"https://github.com/Ekretos/lunibee\";\nconst USER_AGENT = `DiscordBot (${LIBRARY_URL}, ${LIBRARY_VERSION})`;\n\nimport { MemoryRateLimitStore, type RateLimitStore } from \"./store.js\";\nimport { RESTError, abortError, redactPath, sleep } from \"./errors.js\";\nimport {\n createRouteKey,\n serializeQuery,\n type RESTQuery,\n type RouteKey,\n} from \"./route.js\";\nimport { RequestScheduler } from \"./scheduler.js\";\nimport { RateLimiter } from \"./limiter.js\";\nimport { HttpTransport, TransportError } from \"./transport.js\";\nimport { ResponseDecoder } from \"./decoder.js\";\n\n/** A file attachment sent as part of a multipart REST request. */\nexport interface RESTFileAttachment {\n name: string;\n data: Blob | Uint8Array | ArrayBuffer;\n contentType?: string;\n}\n\n/**\n * Options controlling an individual REST request.\n *\n * Lunibee's canonical call shape is positional (`post(path, body)`); these options\n * add the Discord.js-`@discordjs/rest`-familiar per-request knobs (`query`, `headers`,\n * `reason`, `auth`) additively without changing that positional default.\n */\nexport interface RESTRequestOptions {\n /** Abort signal used to cancel the request and any queued wait. */ signal?: AbortSignal;\n /** Query-string appended to the path (`URLSearchParams`, a record, or a raw string). */ query?: RESTQuery;\n /** Extra request headers merged in (library headers such as `Authorization` win). */ headers?: Record<\n string,\n string\n >;\n /** Audit-log reason, sent as the `X-Audit-Log-Reason` header. */ reason?: string;\n /** Set `false` to omit the `Authorization` header for this request. Defaults to `true`. */ auth?: boolean;\n}\n\n/**\n * Discord.js-familiar request payload. Superset of {@link RESTRequestOptions} that also\n * carries the `body` and `files`, matching `@discordjs/rest`'s `RequestData`. It powers the\n * additive `method(path, { body })` overloads without breaking the positional signature.\n */\nexport interface RequestData extends RESTRequestOptions {\n /** Request body. Encoded as JSON unless `files` are present (then multipart). */ body?: unknown;\n /** File attachments; presence upgrades the request to `multipart/form-data`. */ files?: RESTFileAttachment[];\n}\n\n/** Keys recognised on a {@link RequestData} wrapper, used to disambiguate it from a raw body. */\nconst REQUEST_DATA_KEYS = new Set([\n \"body\",\n \"files\",\n \"query\",\n \"headers\",\n \"reason\",\n \"auth\",\n \"signal\",\n]);\n\n/**\n * Detects a Discord.js-style `RequestData` wrapper so verb helpers can accept both\n * `post(path, rawBody)` (Lunibee-canonical) and `post(path, { body })` (Discord.js-familiar).\n * Conservative by design: only a plain object whose every own key is a known `RequestData`\n * key counts — a raw Discord payload (which always carries entity keys like `content`/`name`)\n * never matches, so existing positional callers are unaffected.\n */\nfunction isRequestData(value: unknown): value is RequestData {\n if (value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return false;\n if (typeof FormData !== \"undefined\" && value instanceof FormData)\n return false;\n if (\n value instanceof Blob ||\n value instanceof Uint8Array ||\n value instanceof ArrayBuffer\n )\n return false;\n const keys = Object.keys(value);\n if (keys.length === 0) return false;\n return keys.every((key) => REQUEST_DATA_KEYS.has(key));\n}\n\n// ─── REST Hooks ───────────────────────────────────────────────────────────────\n\n/** Context passed to `RESTHooks.onRequest`. */\nexport interface RESTRequestContext {\n method: string;\n path: string;\n attempt: number;\n}\n/** Context passed to `RESTHooks.onResponse`. */\nexport interface RESTResponseContext {\n method: string;\n path: string;\n status: number;\n durationMs: number;\n}\n/** Context passed to `RESTHooks.onRateLimit`. */\nexport interface RESTRateLimitContext {\n method: string;\n path: string;\n retryAfterMs: number;\n global: boolean;\n bucket?: string;\n}\n/** Context passed to `RESTHooks.onRetry`. */\nexport interface RESTRetryContext {\n method: string;\n path: string;\n attempt: number;\n status: number;\n delayMs: number;\n}\n\n/**\n * Lightweight callback hooks for REST request lifecycle events.\n *\n * All callbacks are optional. They are dispatched in isolation from the request\n * path (deferred to a microtask, and any thrown error is swallowed), so a hook\n * cannot break or reject a request. Even so, hooks **must** be fast and\n * non-blocking: heavy synchronous work in a hook still steals event-loop time\n * from in-flight requests. Offload anything expensive to your own queue.\n */\nexport interface RESTHooks {\n /** Called just before every HTTP attempt. */\n onRequest?(ctx: RESTRequestContext): void;\n /** Called after a successful or failed response is received. */\n onResponse?(ctx: RESTResponseContext): void;\n /** Called when a rate limit is encountered and the client is about to wait. */\n onRateLimit?(ctx: RESTRateLimitContext): void;\n /** Called when a failed request is about to be retried. */\n onRetry?(ctx: RESTRetryContext): void;\n}\n\n/** Configures which REST failures may be retried. */\nexport interface RetryPolicy {\n /** Maximum retry attempts. */ maxRetries: number;\n /** Determines whether a request may be retried. @param method HTTP method. @param status HTTP status, or zero for transport errors. @returns True when retrying is safe under the policy. */ shouldRetry(\n method: string,\n status: number,\n ): boolean;\n /** Calculates delay before the next attempt. @param attempt Zero-based retry number. @param retryAfter Server-provided delay, when available. @returns Delay in milliseconds. */ getDelay(\n attempt: number,\n retryAfter?: number,\n ): number;\n}\n/** Creates the default conservative REST retry policy. @param maxRetries Maximum retries. @returns Retry policy that retries rate limits and idempotent transient failures. @throws {TypeError} If maxRetries is negative or not finite. */\nexport function createRetryPolicy(maxRetries = 2): RetryPolicy {\n if (!Number.isFinite(maxRetries) || maxRetries < 0)\n throw new TypeError(\"maxRetries must be a non-negative finite number.\");\n return {\n maxRetries: Math.floor(maxRetries),\n shouldRetry(method, status) {\n const normalized = method.toUpperCase();\n const idempotent = [\"GET\", \"HEAD\", \"PUT\", \"DELETE\"].includes(\n normalized,\n );\n // Status 0 is a transport failure (DNS, reset connection, TLS):\n // no response reached Discord's handlers, so replaying an\n // idempotent request is as safe as replaying it after a 5xx.\n if (status === 0) return idempotent;\n return (\n status === 429 || (status >= 500 && status <= 599 && idempotent)\n );\n },\n getDelay(attempt, retryAfter) {\n if (retryAfter !== undefined) return Math.max(0, retryAfter * 1000);\n return Math.min(10_000, 500 * 2 ** attempt) + Math.random() * 250;\n },\n };\n}\n\n/** Bun-native REST transport with Discord bucket-aware rate limiting, retries, and cancellation. */\nexport class REST {\n readonly #retryPolicy: RetryPolicy;\n #token?: string;\n /** Rate-limit state: when a request may go out, what a response says. */\n readonly #limiter: RateLimiter;\n /** Per-bucket ordering. */\n readonly #scheduler = new RequestScheduler();\n /** One HTTP attempt, with timeout and cancellation. */\n readonly #transport: HttpTransport;\n /** Response payload and error metadata. */\n readonly #decoder = new ResponseDecoder();\n #hooks: RESTHooks = {};\n /** Whether requests on a known bucket may run concurrently. */\n readonly #concurrentBuckets: boolean;\n /** Creates a REST transport. @param options Transport configuration. @throws {TypeError} If retry configuration is invalid. */\n public constructor(\n options: {\n token?: string;\n timeout?: number;\n retries?: number;\n retryPolicy?: RetryPolicy;\n baseURL?: string;\n hooks?: RESTHooks;\n store?: RateLimitStore;\n /** Replaces the HTTP stage, e.g. with a recording transport in tests. */\n transport?: HttpTransport;\n /**\n * Lets requests on a bucket whose limit is known run concurrently, up\n * to its `remaining` allowance, instead of one at a time. Requires a\n * store with `reserve`. Requests on one bucket may then complete out\n * of order (e.g. messages to one channel). Defaults to `false`.\n */\n concurrentBuckets?: boolean;\n } = {},\n ) {\n this.#token = options.token;\n this.#retryPolicy =\n options.retryPolicy ?? createRetryPolicy(options.retries ?? 2);\n this.#transport =\n options.transport ??\n new HttpTransport({\n baseURL: options.baseURL,\n timeout: options.timeout,\n });\n const store = options.store ?? new MemoryRateLimitStore();\n this.#concurrentBuckets =\n (options.concurrentBuckets ?? false) &&\n typeof store.reserve === \"function\";\n this.#limiter = new RateLimiter(store, {\n concurrent: this.#concurrentBuckets,\n });\n if (options.hooks) this.#hooks = options.hooks;\n }\n /** The rate-limit store backing this transport. */\n public get store(): RateLimitStore {\n return this.#limiter.store;\n }\n /** Replaces the current hook set. Pass an empty object to clear all hooks. */\n public setHooks(hooks: RESTHooks): this {\n this.#hooks = hooks;\n return this;\n }\n /** Sets the authentication token. @param token Discord bot token. @returns Nothing. @throws {TypeError} If token is empty. */\n public setToken(token: string): void {\n if (!token.trim())\n throw new TypeError(\"A Discord bot token is required.\");\n this.#token = token;\n }\n /** Executes an HTTP request with Discord bucket/global rate limits, retry handling, and AbortSignal support.\n * Accepts a JSON body, a FormData body (for file uploads), or undefined.\n * @param method HTTP method.\n * @param path API path.\n * @param body Optional JSON body, FormData for file uploads, or undefined.\n * @param options Request options: cancellation `signal` plus the Discord.js-familiar\n * `query`, `headers`, `reason`, `auth`, and `files` (which upgrade to multipart).\n * @returns Decoded response body.\n * @throws {RESTError} If Discord or transport rejects the request.\n */\n public async request<T>(\n method: string,\n path: string,\n body?: unknown,\n options: RequestData = {},\n ): Promise<T> {\n if (!method.toUpperCase())\n throw new TypeError(\"REST method is required.\");\n if (!path.startsWith(\"/\"))\n throw new TypeError(\"REST paths must start with '/'.\");\n const route = createRouteKey(method, path);\n // Upgrade to multipart when file attachments are supplied via options.\n const files = options.files;\n if (files && files.length > 0 && !(body instanceof FormData))\n body = this.#fileForm(body, files);\n const query = serializeQuery(options.query);\n const requestPath = query ? `${path}${query}` : path;\n\n // Discord scopes a rate limit by (bucket hash, major parameter): two\n // channels sharing an endpoint have independent limits, while two\n // different routes can share one hash. The key is therefore resolved\n // again once the slot is acquired, so a request that queued under its\n // route-derived key joins the shared bucket's queue if one was\n // discovered while it waited.\n return this.#scheduler.runResolved(\n () => this.#limiter.resolveBucketKey(route.route, route.major),\n options.signal,\n path,\n (bucketKey, release) =>\n this.#attempts<T>(\n route,\n requestPath,\n body,\n options,\n bucketKey,\n release,\n ),\n );\n }\n /**\n * Runs the retry loop for one scheduled request: acquire limits, send,\n * record what the response says, decode, and decide whether to try again.\n */\n async #attempts<T>(\n route: RouteKey,\n requestPath: string,\n body: unknown,\n options: RequestData,\n initialBucketKey: string,\n release: () => void,\n ): Promise<T> {\n const { method, path } = route;\n let bucketKey = initialBucketKey;\n for (\n let attempt = 0;\n attempt <= this.#retryPolicy.maxRetries;\n attempt++\n ) {\n await this.#limiter.acquire(bucketKey, options.signal, path);\n // The reservation already claimed this request's unit, so once the\n // bucket's window is known the next request need not wait for our\n // response. An unknown bucket stays serial until a response\n // reveals its limit.\n if (this.#concurrentBuckets) {\n const bucket = await this.#limiter.store.getBucket(bucketKey);\n if (bucket && bucket.resetAt > Date.now()) release();\n }\n this.#emit(this.#hooks.onRequest, { method, path, attempt });\n const requestStart = Date.now();\n let response: Response;\n try {\n response = await this.#transport.send({\n method,\n path: requestPath,\n headers: this.#headers(body, options),\n body: this.#encodeBody(body),\n signal: options.signal,\n });\n } catch (error) {\n if (error instanceof RESTError) throw error;\n if (options.signal?.aborted)\n throw abortError(path, options.signal.reason);\n const failure =\n error instanceof TransportError\n ? error\n : new TransportError(\n \"Discord REST request failed\",\n false,\n error,\n );\n if (\n !failure.timedOut &&\n attempt < this.#retryPolicy.maxRetries &&\n this.#retryPolicy.shouldRetry(method, 0)\n ) {\n await sleep(\n this.#retryPolicy.getDelay(attempt),\n options.signal,\n path,\n );\n continue;\n }\n throw new RESTError(failure.message, 0, undefined, undefined, {\n method,\n path,\n cause: failure.cause ?? failure,\n kind: failure.timedOut ? \"timeout\" : \"network\",\n });\n }\n this.#emit(this.#hooks.onResponse, {\n method,\n path,\n status: response.status,\n durationMs: Date.now() - requestStart,\n });\n bucketKey = await this.#limiter.applyResponse(\n response,\n bucketKey,\n route.route,\n route.major,\n );\n const payload = await this.#decoder.read(response);\n if (response.ok)\n return (response.status === 204 ? undefined : payload) as T;\n\n const data = this.#decoder.errorData(payload);\n const retryAfter =\n response.status === 429\n ? this.#decoder.retryAfter(response, data)\n : undefined;\n if (data.global && retryAfter !== undefined)\n await this.#limiter.noteGlobalReset(\n Date.now() + retryAfter * 1000,\n );\n // Fire for ANY 429, including a global limit that arrives without a\n // Retry-After header; fall back to 1s in that case.\n if (response.status === 429)\n this.#emit(this.#hooks.onRateLimit, {\n method,\n path,\n retryAfterMs: (retryAfter ?? 1) * 1000,\n global: data.global ?? false,\n bucket: await this.#limiter.store.getBucketHash(\n route.route,\n ),\n });\n if (\n attempt < this.#retryPolicy.maxRetries &&\n this.#retryPolicy.shouldRetry(method, response.status)\n ) {\n const delay = this.#retryPolicy.getDelay(attempt, retryAfter);\n this.#emit(this.#hooks.onRetry, {\n method,\n path,\n attempt,\n status: response.status,\n delayMs: delay,\n });\n await sleep(delay, options.signal, path);\n continue;\n }\n throw new RESTError(\n data.message ??\n response.statusText ??\n `Discord REST request failed with status ${response.status}`,\n response.status,\n data.code,\n payload,\n { method, path },\n );\n }\n throw new RESTError(\n \"Discord REST request exhausted its retry attempts\",\n 0,\n undefined,\n undefined,\n { method, path },\n );\n }\n /** Builds the header set for one attempt; library headers win over caller headers. */\n #headers(body: unknown, options: RequestData): Record<string, string> {\n const isFormData =\n typeof FormData !== \"undefined\" && body instanceof FormData;\n const headers: Record<string, string> = { ...options.headers };\n if (options.auth !== false && this.#token)\n headers[\"Authorization\"] = `Bot ${this.#token}`;\n headers[\"User-Agent\"] = USER_AGENT;\n if (options.reason !== undefined)\n headers[\"X-Audit-Log-Reason\"] = encodeURIComponent(options.reason);\n if (!isFormData) headers[\"Content-Type\"] = \"application/json\";\n return headers;\n }\n /** Encodes a body as multipart (passed through) or JSON. */\n #encodeBody(body: unknown): BodyInit | undefined {\n if (typeof FormData !== \"undefined\" && body instanceof FormData)\n return body;\n return body === undefined ? undefined : JSON.stringify(body);\n }\n /**\n * Normalizes a verb helper's second argument into `(body, options)`.\n * Supports both `verb(path, rawBody, options?)` (Lunibee-canonical positional) and the\n * Discord.js-familiar `verb(path, { body, query, headers, reason, files })` wrapper.\n */\n #dispatch<T>(\n method: string,\n path: string,\n bodyOrOptions?: unknown,\n options?: RequestData,\n ): Promise<T> {\n if (options === undefined && isRequestData(bodyOrOptions))\n return this.request<T>(\n method,\n path,\n bodyOrOptions.body,\n bodyOrOptions,\n );\n return this.request<T>(method, path, bodyOrOptions, options);\n }\n /** Sends a GET request. @param path API path. @param options Request options (`query`, `headers`, `signal`, …). @returns Decoded response. @throws {RESTError} When the request fails. */ public get<\n T,\n >(path: string, options?: RequestData): Promise<T> {\n return this.request<T>(\"GET\", path, options?.body, options);\n }\n /** Sends a POST request. Accepts a raw body (`post(path, body)`) or a Discord.js-familiar `post(path, { body })`. @param path API path. @param body Optional JSON body, or a `RequestData` wrapper. @param options Request options. @returns Decoded response. @throws {RESTError} When the request fails. */\n public post<T>(path: string, options: RequestData): Promise<T>;\n public post<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T>;\n public post<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T> {\n return this.#dispatch<T>(\"POST\", path, body, options);\n }\n /** Sends a PATCH request. Accepts a raw body (`patch(path, body)`) or a Discord.js-familiar `patch(path, { body })`. @param path API path. @param body Optional JSON body, or a `RequestData` wrapper. @param options Request options. @returns Decoded response. @throws {RESTError} When the request fails. */\n public patch<T>(path: string, options: RequestData): Promise<T>;\n public patch<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T>;\n public patch<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T> {\n return this.#dispatch<T>(\"PATCH\", path, body, options);\n }\n /** Sends a PUT request. Accepts a raw body (`put(path, body)`) or a Discord.js-familiar `put(path, { body })`. @param path API path. @param body Optional JSON body, or a `RequestData` wrapper. @param options Request options. @returns Decoded response. @throws {RESTError} When the request fails. */\n public put<T>(path: string, options: RequestData): Promise<T>;\n public put<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T>;\n public put<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T> {\n return this.#dispatch<T>(\"PUT\", path, body, options);\n }\n /** Sends a DELETE request. @param path API path. @param options Request options (`reason`, `headers`, `signal`, …). @returns Decoded response. @throws {RESTError} When the request fails. */ public delete<\n T,\n >(path: string, options?: RequestData): Promise<T> {\n return this.request<T>(\"DELETE\", path, options?.body, options);\n }\n /**\n * Builds a multipart form with a JSON payload and file attachments.\n */\n #fileForm(payload: unknown, files: RESTFileAttachment[]): FormData {\n const form = new FormData();\n form.append(\"payload_json\", JSON.stringify(payload));\n for (let i = 0; i < files.length; i++) {\n const file = files[i]!;\n const blob =\n file.data instanceof Blob\n ? file.data\n : new Blob([file.data as ArrayBuffer], {\n type: file.contentType ?? \"application/octet-stream\",\n });\n form.append(`files[${i}]`, blob, file.name);\n }\n return form;\n }\n\n /**\n * Sends a multipart/form-data POST request for file uploads.\n * Attaches a JSON payload as `payload_json` and files as additional fields.\n * @param path API path.\n * @param payload JSON payload (e.g. message content, embeds).\n * @param files Array of file attachments.\n * @param options Cancellation options.\n * @returns Decoded response.\n * @throws {RESTError} When the request fails.\n */\n public postWithFiles<T>(\n path: string,\n payload: unknown,\n files: RESTFileAttachment[],\n options?: RESTRequestOptions,\n ): Promise<T> {\n return this.request<T>(\n \"POST\",\n path,\n this.#fileForm(payload, files),\n options,\n );\n }\n\n /**\n * Sends a multipart/form-data PATCH request for editing messages with files.\n * @param path API path.\n * @param payload JSON payload.\n * @param files Array of file attachments.\n * @param options Cancellation options.\n * @returns Decoded response.\n * @throws {RESTError} When the request fails.\n */\n public patchWithFiles<T>(\n path: string,\n payload: unknown,\n files: RESTFileAttachment[],\n options?: RESTRequestOptions,\n ): Promise<T> {\n return this.request<T>(\n \"PATCH\",\n path,\n this.#fileForm(payload, files),\n options,\n );\n }\n /** Dispatches a lifecycle hook in isolation: deferred to a microtask so it\n * cannot block the request path, with any thrown error swallowed so a faulty\n * hook cannot reject the request. @param hook Optional callback. @param ctx Event context. */\n #emit<C>(hook: ((ctx: C) => void) | undefined, ctx: C): void {\n if (!hook) return;\n const withPath = ctx as { path?: unknown };\n if (typeof withPath.path === \"string\")\n ctx = { ...ctx, path: redactPath(withPath.path) };\n Promise.resolve()\n .then(() => hook(ctx))\n .catch(() => {});\n }\n}\n\nexport { Routes } from \"./routes.js\";\nexport {\n RESTError,\n abortError,\n redactPath,\n type RESTErrorKind,\n} from \"./errors.js\";\nexport { RESTErrorCode } from \"./error-codes.js\";\nexport {\n createRouteKey,\n normalizeRoutePath,\n majorParameter,\n scopeBucket,\n serializeQuery,\n type RouteKey,\n type RESTQuery,\n} from \"./route.js\";\nexport { RequestScheduler } from \"./scheduler.js\";\nexport { RateLimiter } from \"./limiter.js\";\nexport {\n HttpTransport,\n TransportError,\n type TransportRequest,\n type FetchLike,\n} from \"./transport.js\";\nexport { ResponseDecoder, type DecodedError } from \"./decoder.js\";\nexport {\n type RateLimitStore,\n type BucketState,\n type Reservation,\n MemoryRateLimitStore,\n} from \"./store.js\";\nexport {\n RedisRateLimitStore,\n type RedisRateLimitStoreOptions,\n type MinimalRedisClient,\n} from \"./redis.js\";\n\nexport {\n WebhookClient,\n type WebhookClientOptions,\n type WebhookMessageOptions,\n} from \"./webhook.js\";\n\n/**\n * Discord.js-familiar alias for {@link RESTError}. `@discordjs/rest` throws `DiscordAPIError`\n * on a Discord-rejected request; Lunibee keeps `RESTError` as the canonical class and exports\n * this alias so Discord.js-shaped `catch (err) { if (err instanceof DiscordAPIError) … }` works.\n */\nexport { RESTError as DiscordAPIError };\n",
10
- "import { Manager, ResourceManager, splitReason } from \"./base.js\";\nexport { Manager, ResourceManager } from \"./base.js\";\n/** Discord.js-familiar alias for {@link ResourceManager}. */\nexport { ResourceManager as CachedManager } from \"./base.js\";\nimport { REST, Routes } from \"@lunibee/rest\";\nimport {\n Channel,\n createChannel,\n Message,\n User,\n type ResourceContext,\n} from \"@lunibee/structures\";\nimport {\n MessageManager,\n toRequest,\n type MessageCacheOptions,\n type MessageCreateOptions as ManagerMessageCreateOptions,\n} from \"./message.js\";\nimport { ThreadManager } from \"./thread.js\";\n\nexport { UserManager } from \"./user.js\";\nexport { GuildManager } from \"./guild.js\";\nexport type { AuditLogEntry, AuditLogResponse } from \"./guild.js\";\nexport { AuditLogEvent } from \"./guild.js\";\n\nexport type MessageCreateOptions = ManagerMessageCreateOptions;\nexport type MessageEditOptions = Record<string, unknown> & { content?: string };\n/** Discord only bulk-deletes messages younger than two weeks. */\nconst BULK_DELETE_MAX_AGE_MS = 14 * 24 * 60 * 60_000;\n/** Creation time (ms) encoded in a snowflake. */\nfunction snowflakeTime(id: string): number {\n return Number((BigInt(id) >> 22n) + 1_420_070_400_000n);\n}\nexport interface MessageFetchOptions {\n cache?: boolean;\n}\nexport interface MessageQueryOptions {\n before?: string;\n after?: string;\n around?: string;\n limit?: number;\n}\nexport interface MessageThreadOptions {\n name: string;\n autoArchiveDuration?: 60 | 1440 | 4320 | 10080;\n rateLimitPerUser?: number;\n}\nexport interface ReactionFetchOptions {\n limit?: number;\n after?: string;\n}\n\nexport interface ChannelCreateOptions extends Record<string, unknown> {\n /** Audit-log reason. */\n reason?: string;\n name: string;\n type: number;\n guild_id?: string;\n parent_id?: string | null;\n}\nexport type ChannelEditOptions = Record<string, unknown> & {\n /** Audit-log reason. */\n reason?: string;\n};\n\nimport { PermissionOverwriteManager } from \"./guild-resources.js\";\n\nexport class ChannelManager extends Manager<string, Channel> {\n readonly #rest: REST;\n readonly #context: ResourceContext;\n readonly #messageManagers = new Map<string, MessageManager>();\n readonly #messageCache?: MessageCacheOptions;\n readonly #allowedMentions?: unknown;\n /**\n * @param options.messageCache Enables a bounded per-channel message cache; messages are not cached by default.\n * @param options.allowedMentions Default `allowed_mentions` for sends and edits without their own.\n */\n public constructor(\n rest: REST,\n options: {\n messageCache?: MessageCacheOptions;\n allowedMentions?: unknown;\n } = {},\n ) {\n super();\n this.#rest = rest;\n this.#messageCache = options.messageCache;\n this.#allowedMentions = options.allowedMentions;\n this.#context = {\n sendMessage: (channelId, options) => this.send(channelId, options),\n editMessage: (channelId, messageId, options) =>\n this.editMessage(channelId, messageId, options),\n deleteMessage: (channelId, messageId, reason) =>\n this.deleteMessage(channelId, messageId, reason),\n crosspostMessage: (channelId, messageId) =>\n this.crosspostMessage(channelId, messageId),\n editChannel: (channelId, options) => this.edit(channelId, options),\n deleteChannel: (channelId, reason) =>\n this.remove(channelId, reason),\n addReaction: (channelId, messageId, emoji) =>\n this.addReaction(channelId, messageId, emoji),\n removeOwnReaction: (channelId, messageId, emoji) =>\n this.removeOwnReaction(channelId, messageId, emoji),\n removeReaction: (channelId, messageId, emoji, userId) =>\n this.removeReaction(channelId, messageId, emoji, userId),\n removeAllReactions: (channelId, messageId) =>\n this.removeAllReactions(channelId, messageId),\n pinMessage: (channelId, messageId, reason) =>\n this.pinMessage(channelId, messageId, reason),\n unpinMessage: (channelId, messageId, reason) =>\n this.unpinMessage(channelId, messageId, reason),\n };\n }\n public messages(channelId: string): MessageManager {\n let manager = this.#messageManagers.get(channelId);\n if (!manager) {\n manager = new MessageManager(\n this.#rest,\n this.#context,\n channelId,\n this.#messageCache,\n this.#allowedMentions,\n );\n this.#messageManagers.set(channelId, manager);\n }\n return manager;\n }\n /** Permission overwrite manager for a channel. */\n public permissionOverwrites(channelId: string): PermissionOverwriteManager {\n return new PermissionOverwriteManager(\n this.#rest,\n channelId,\n () => this.get(channelId)?.permissionOverwrites,\n );\n }\n public threads(channelId: string): ThreadManager {\n return new ThreadManager(this.#rest, this.#context, channelId);\n }\n /** Fetches a channel; concurrent fetches share a request and a stale result never overwrites newer state. */\n public fetch(channelId: string): Promise<Channel> {\n return this.fetchOnce(\n channelId,\n async () =>\n createChannel(\n await this.#rest.get<\n ConstructorParameters<typeof Channel>[0]\n >(Routes.channel(channelId)),\n this.#context,\n ),\n (channel) => this.#merge(channel),\n );\n }\n public async resolve(channelId: string): Promise<Channel> {\n return this.get(channelId) ?? this.fetch(channelId);\n }\n public upsert(data: ConstructorParameters<typeof Channel>[0]): Channel {\n return this.#merge(createChannel(data, this.#context));\n }\n /** Merges into the cached instance; a type change (e.g. text -> announcement) needs the new subclass. */\n #merge(channel: Channel): Channel {\n const existing = this.get(channel.id);\n if (existing && existing.type === channel.type) {\n Object.assign(existing, channel);\n return existing;\n }\n this.set(channel.id, channel);\n return channel;\n }\n public update(channel: Channel): this {\n return this.set(channel.id, channel);\n }\n /** Removes every cached channel that belongs to a guild. @returns Number removed. */\n public deleteGuildChannels(guildId: string): number {\n let removed = 0;\n for (const channel of this.values())\n if (channel.guildId === guildId && this.delete(channel.id))\n removed++;\n return removed;\n }\n /** Ends a poll now; returns the updated message. */\n public async endPoll(\n channelId: string,\n messageId: string,\n ): Promise<Message> {\n return this.messages(channelId).upsert(\n await this.#rest.post<ConstructorParameters<typeof Message>[0]>(\n Routes.pollExpire(channelId, messageId),\n ),\n );\n }\n /** Fetches users who voted for one poll answer. @param options.limit 1-100 (default 25). */\n public async fetchPollVoters(\n channelId: string,\n messageId: string,\n answerId: number,\n options: { after?: string; limit?: number } = {},\n ): Promise<User[]> {\n if (\n options.limit !== undefined &&\n (!Number.isInteger(options.limit) ||\n options.limit < 1 ||\n options.limit > 100)\n )\n throw new RangeError(\"Poll voter limit must be 1-100.\");\n const params = new URLSearchParams();\n if (options.after) params.set(\"after\", options.after);\n if (options.limit !== undefined)\n params.set(\"limit\", String(options.limit));\n const suffix = params.toString();\n const { users } = await this.#rest.get<{\n users: ConstructorParameters<typeof User>[0][];\n }>(\n `${Routes.pollAnswerVoters(channelId, messageId, answerId)}${suffix ? `?${suffix}` : \"\"}`,\n );\n return users.map((user) => new User(user));\n }\n /** Plays a soundboard sound in a voice channel the bot is connected to. */\n public async sendSoundboardSound(\n channelId: string,\n options: { soundId: string; sourceGuildId?: string },\n ): Promise<void> {\n await this.#rest.post(Routes.sendSoundboardSound(channelId), {\n sound_id: options.soundId,\n source_guild_id: options.sourceGuildId,\n });\n }\n /** Returns the message manager for a channel only if one already exists. */\n public cachedMessages(channelId: string): MessageManager | undefined {\n return this.#messageManagers.get(channelId);\n }\n public async create(\n guildId: string,\n options: ChannelCreateOptions,\n ): Promise<Channel> {\n const [payload, reason] = splitReason(options);\n return this.upsert(\n await this.#rest.post<ConstructorParameters<typeof Channel>[0]>(\n Routes.guildChannels(guildId),\n payload,\n { reason },\n ),\n );\n }\n public async edit(\n channelId: string,\n options: ChannelEditOptions,\n ): Promise<Channel> {\n const [payload, reason] = splitReason(options);\n return this.upsert(\n await this.#rest.patch<ConstructorParameters<typeof Channel>[0]>(\n Routes.channel(channelId),\n payload,\n { reason },\n ),\n );\n }\n\n /** Deletes a channel (or closes a DM). @param reason Audit-log reason. */\n public async remove(channelId: string, reason?: string): Promise<void> {\n await this.#rest.delete(Routes.channel(channelId), { reason });\n this.delete(channelId);\n }\n /** @deprecated Use {@link ChannelManager.remove}, which also takes an audit-log reason. Removed in 0.3.0. */\n public deleteChannel(channelId: string): Promise<void> {\n return this.remove(channelId);\n }\n /** Evicts a channel, dropping its per-channel message manager with it.\n * Overrides {@link Manager.delete} so cache eviction driven by a Gateway\n * `CHANNEL_DELETE`/`THREAD_DELETE` — which calls `delete` rather than\n * {@link remove} — releases the message manager and its cached\n * messages too, instead of retaining them for the client's lifetime. */\n public override delete(channelId: string): boolean {\n this.#messageManagers.delete(channelId);\n return super.delete(channelId);\n }\n public send(\n channelId: string,\n options: MessageCreateOptions,\n ): Promise<Message> {\n return this.messages(channelId).send(options);\n }\n /** @deprecated Use {@link ChannelManager.send}. Removed in 0.3.0. */\n public sendMessage(\n channelId: string,\n options: MessageCreateOptions,\n ): Promise<Message> {\n return this.send(channelId, options);\n }\n public async fetchMessage(\n channelId: string,\n messageId: string,\n options: MessageFetchOptions = {},\n ): Promise<Message> {\n void options;\n return this.messages(channelId).fetch(messageId);\n }\n public fetchMessages(\n channelId: string,\n query: MessageQueryOptions | Iterable<string>,\n ): Promise<Message[]> {\n if (isMessageQuery(query)) {\n const params = new URLSearchParams();\n if (query.before) params.set(\"before\", query.before);\n if (query.after) params.set(\"after\", query.after);\n if (query.around) params.set(\"around\", query.around);\n if (query.limit !== undefined)\n params.set(\"limit\", String(query.limit));\n const suffix = params.toString();\n return this.#rest\n .get<ConstructorParameters<typeof Message>[0][]>(\n `${Routes.channelMessages(channelId)}${suffix ? `?${suffix}` : \"\"}`,\n )\n .then((data) =>\n data.map((item) => this.messages(channelId).upsert(item)),\n );\n }\n return this.messages(channelId).fetchMany(query);\n }\n public upsertMessage(\n data: ConstructorParameters<typeof Message>[0],\n ): Message {\n return this.messages(data.channel_id).upsert(data);\n }\n public async editMessage(\n channelId: string,\n messageId: string,\n options: MessageEditOptions,\n ): Promise<Message> {\n return this.messages(channelId).upsert(\n await this.#rest.patch<ConstructorParameters<typeof Message>[0]>(\n Routes.message(channelId, messageId),\n toRequest(options, this.#allowedMentions),\n ),\n );\n }\n /** Deletes a message. @param reason Audit-log reason (shown when deleting someone else's message). */\n public async deleteMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void> {\n await this.#rest.delete(Routes.message(channelId, messageId), {\n reason,\n });\n this.messages(channelId).delete(messageId);\n }\n public deleteCachedMessage(channelId: string, messageId: string): boolean {\n return this.messages(channelId).delete(messageId);\n }\n public async crosspostMessage(\n channelId: string,\n messageId: string,\n ): Promise<Message> {\n return this.messages(channelId).upsert(\n await this.#rest.post<ConstructorParameters<typeof Message>[0]>(\n Routes.crosspostMessage(channelId, messageId),\n ),\n );\n }\n /** Bulk-deletes messages in a channel. Duplicate IDs are ignored and a\n * single ID falls back to a normal delete.\n * @throws {RangeError} If no IDs or more than 100 are provided, or any\n * message is older than 14 days (Discord refuses to bulk-delete those). */\n public async bulkDeleteMessages(\n channelId: string,\n messageIds: Iterable<string>,\n reason?: string,\n ): Promise<void> {\n const ids = [...new Set(messageIds)];\n if (ids.length < 1 || ids.length > 100)\n throw new RangeError(\n \"bulkDelete requires between 1 and 100 message IDs.\",\n );\n if (ids.length === 1)\n return this.deleteMessage(channelId, ids[0]!, reason);\n const cutoff = Date.now() - BULK_DELETE_MAX_AGE_MS;\n const tooOld = ids.filter((id) => snowflakeTime(id) < cutoff);\n if (tooOld.length)\n throw new RangeError(\n `bulkDelete cannot delete messages older than 14 days: ${tooOld.join(\", \")}`,\n );\n await this.#rest.post(\n Routes.channelBulkDelete(channelId),\n { messages: ids },\n { reason },\n );\n for (const id of ids) this.messages(channelId).delete(id);\n }\n /**\n * Iterates a channel's history newest-first, 100 messages per request,\n * starting before `before` (or the latest message) and stopping after\n * `limit` messages or at the start of the channel.\n */\n public async *iterateMessages(\n channelId: string,\n options: { before?: string; limit?: number } = {},\n ): AsyncGenerator<Message, void, undefined> {\n let before = options.before;\n let remaining = options.limit ?? Infinity;\n while (remaining > 0) {\n const page = await this.fetchMessages(channelId, {\n before,\n limit: Math.min(100, remaining),\n });\n for (const message of page) yield message;\n remaining -= page.length;\n if (page.length < 100) return;\n before = page.at(-1)!.id;\n }\n }\n public async addReaction(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void> {\n // Discord's create-reaction endpoint is\n // PUT .../reactions/{emoji}/@me — the bare .../reactions/{emoji} path\n // is not a valid target for PUT.\n await this.#rest.put(\n `${Routes.messageReactions(channelId, messageId, emoji)}/@me`,\n );\n }\n public async fetchReactions(\n channelId: string,\n messageId: string,\n emoji: string,\n options: ReactionFetchOptions = {},\n ): Promise<User[]> {\n const params = new URLSearchParams();\n if (options.limit !== undefined)\n params.set(\"limit\", String(options.limit));\n if (options.after) params.set(\"after\", options.after);\n const suffix = params.toString();\n const data = await this.#rest.get<\n ConstructorParameters<typeof User>[0][]\n >(\n `${Routes.messageReactions(channelId, messageId, emoji)}${suffix ? `?${suffix}` : \"\"}`,\n );\n return data.map((user) => new User(user));\n }\n public async removeOwnReaction(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void> {\n await this.#rest.delete(\n `${Routes.messageReactions(channelId, messageId, emoji)}/@me`,\n );\n }\n public async removeReaction(\n channelId: string,\n messageId: string,\n emoji: string,\n userId: string,\n ): Promise<void> {\n await this.#rest.delete(\n `${Routes.messageReactions(channelId, messageId, emoji)}/${userId}`,\n );\n }\n public async removeAllReactions(\n channelId: string,\n messageId: string,\n ): Promise<void> {\n await this.#rest.delete(\n Routes.messageReactionsAll(channelId, messageId),\n );\n }\n /** Fetches the newest pinned messages (one page, up to 50, like the endpoint it replaces). */\n public async fetchPinnedMessages(channelId: string): Promise<Message[]> {\n const data = await this.#rest.get<{\n items: { message: ConstructorParameters<typeof Message>[0] }[];\n }>(Routes.channelMessagesPins(channelId));\n return data.items.map((item) =>\n this.messages(channelId).upsert(item.message),\n );\n }\n /** Pins a message. @param reason Audit-log reason. */\n public async pinMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void> {\n await this.#rest.put(\n Routes.channelMessagesPin(channelId, messageId),\n undefined,\n { reason },\n );\n }\n /** Unpins a message. @param reason Audit-log reason. */\n public async unpinMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void> {\n await this.#rest.delete(\n Routes.channelMessagesPin(channelId, messageId),\n { reason },\n );\n }\n /** Creates a webhook in a channel. @param options Name, optional avatar data URI, and audit-log `reason`. */\n public async createWebhook(\n channelId: string,\n options: { name: string; avatar?: string | null; reason?: string },\n ): Promise<import(\"@lunibee/types\").APIWebhook> {\n const [payload, reason] = splitReason(options);\n return this.#rest.post(Routes.channelWebhooks(channelId), payload, {\n reason,\n });\n }\n public createThreadFromMessage(\n channelId: string,\n messageId: string,\n options: MessageThreadOptions,\n ): Promise<Channel> {\n return this.threads(channelId).createFromMessage(messageId, options);\n }\n /**\n * Fetches a page of messages with cursor metadata.\n * @param channelId Channel to fetch from.\n * @param options Page options — `before`, `after`, `around`, and `limit` (max 100).\n * @returns `{ messages, before, after, hasMore }` — use `before` or `after` as cursors for the next page.\n */\n public async fetchPage(\n channelId: string,\n options: MessageQueryOptions = {},\n ): Promise<{\n messages: Message[];\n before?: string;\n after?: string;\n hasMore: boolean;\n }> {\n const limit = Math.min(100, Math.max(1, options.limit ?? 50));\n const messages = await this.fetchMessages(channelId, {\n ...options,\n limit,\n });\n return {\n messages,\n before: messages[0]?.id,\n after: messages[messages.length - 1]?.id,\n hasMore: messages.length === limit,\n };\n }\n /** @deprecated Use {@link ChannelManager.bulkDeleteMessages}, which also takes an audit-log reason. Removed in 0.3.0. */\n public bulkDelete(channelId: string, messageIds: string[]): Promise<void> {\n return this.bulkDeleteMessages(channelId, messageIds);\n }\n public override clear(): void {\n this.#messageManagers.clear();\n super.clear();\n }\n}\n\nfunction isMessageQuery(\n value: MessageQueryOptions | Iterable<string>,\n): value is MessageQueryOptions {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !(Symbol.iterator in value)\n );\n}\nexport type CreateMessageOptions = MessageCreateOptions;\nexport {\n MessageManager,\n toRequest,\n type MessageCacheOptions,\n type MessageFile,\n} from \"./message.js\";\nexport { ThreadManager } from \"./thread.js\";\nexport {\n RoleManager,\n type RoleCreateOptions,\n type RoleEditOptions,\n} from \"./role.js\";\nexport {\n GuildMemberManager,\n type MemberEditOptions,\n type BanOptions,\n} from \"./member.js\";\nexport { ApplicationCommandManager } from \"./application.js\";\nexport {\n GuildBanManager,\n GuildScheduledEventManager,\n StageInstanceManager,\n PermissionOverwriteManager,\n type APIBan,\n type GuildBanCreateOptions,\n type GuildScheduledEventOptions,\n type StageInstanceCreateOptions,\n type PermissionOverwriteOptions,\n type PermissionOverwriteTargetType,\n type PermissionOverwriteUpdate,\n} from \"./guild-resources.js\";\nexport {\n EmojiManager,\n type EmojiCreateOptions,\n type EmojiEditOptions,\n} from \"./emoji.js\";\nexport {\n GuildStickerManager,\n GuildSoundboardManager,\n MonetizationManager,\n type APIEntitlement,\n type APISKU,\n type APISoundboardSound,\n type APISubscription,\n type EntitlementQuery,\n type GuildStickerCreateOptions,\n type SoundboardSoundCreateOptions,\n} from \"./advanced.js\";\n",
5
+ "/**\n * Channel kinds: a short name for what a channel is, in place of the numeric\n * `type` Discord sends. Threads share one kind; `type` still tells the three\n * apart.\n */\nexport const ChannelKinds = {\n text: [0],\n dm: [1],\n voice: [2],\n \"group-dm\": [3],\n category: [4],\n announcement: [5],\n thread: [10, 11, 12],\n stage: [13],\n directory: [14],\n forum: [15],\n media: [16],\n} as const;\n\n/** The name of a kind of channel, such as `\"text\"` or `\"voice\"`. */\nexport type ChannelKind = keyof typeof ChannelKinds;\n\n/** A channel type Discord has no kind for yet. */\nexport type UnknownChannelKind = \"unknown\";\n\nconst KIND_OF_TYPE = new Map<number, ChannelKind>(\n (Object.keys(ChannelKinds) as ChannelKind[]).flatMap((kind) =>\n ChannelKinds[kind].map((type): [number, ChannelKind] => [type, kind]),\n ),\n);\n\n/** The kind of a Discord channel `type`, or `\"unknown\"` for a type this version does not know. */\nexport function channelKindOf(type: number): ChannelKind | UnknownChannelKind {\n return KIND_OF_TYPE.get(type) ?? \"unknown\";\n}\n\n/** The Discord channel `type` numbers a kind covers (three for `\"thread\"`, one for the rest). */\nexport function channelTypesOf(kind: ChannelKind): readonly number[] {\n return ChannelKinds[kind];\n}\n",
6
+ "// ─── Gateway Intents ─────────────────────────────────────────────────────────\n\n/** Gateway intent bit flags supported by Discord (PascalCase). */\nexport const GatewayIntentBits = {\n Guilds: 1 << 0,\n GuildMembers: 1 << 1,\n GuildModeration: 1 << 2,\n GuildExpressions: 1 << 3,\n GuildIntegrations: 1 << 4,\n GuildWebhooks: 1 << 5,\n GuildInvites: 1 << 6,\n GuildVoiceStates: 1 << 7,\n GuildPresences: 1 << 8,\n GuildMessages: 1 << 9,\n GuildMessageReactions: 1 << 10,\n GuildMessageTyping: 1 << 11,\n DirectMessages: 1 << 12,\n DirectMessageReactions: 1 << 13,\n DirectMessageTyping: 1 << 14,\n MessageContent: 1 << 15,\n GuildScheduledEvents: 1 << 16,\n AutoModerationConfiguration: 1 << 20,\n AutoModerationExecution: 1 << 21,\n GuildMessagePolls: 1 << 24,\n DirectMessagePolls: 1 << 25,\n} as const;\n\n/** Idiomatic camelCase Gateway intent bit flags supported by Discord. */\nexport const IntentBits = {\n guild: 1 << 0,\n guilds: 1 << 0,\n guildMembers: 1 << 1,\n guildModeration: 1 << 2,\n guildBans: 1 << 2,\n guildExpressions: 1 << 3,\n guildEmojis: 1 << 3,\n guildEmojisAndStickers: 1 << 3,\n guildIntegrations: 1 << 4,\n guildWebhooks: 1 << 5,\n guildInvites: 1 << 6,\n guildVoiceStates: 1 << 7,\n guildPresences: 1 << 8,\n guildMessages: 1 << 9,\n guildMessage: 1 << 9,\n guildMessageReactions: 1 << 10,\n guildMessageTyping: 1 << 11,\n directMessages: 1 << 12,\n directMessageReactions: 1 << 13,\n directMessageTyping: 1 << 14,\n messageContent: 1 << 15,\n guildScheduledEvents: 1 << 16,\n autoModerationConfiguration: 1 << 20,\n autoModerationExecution: 1 << 21,\n guildMessagePolls: 1 << 24,\n directMessagePolls: 1 << 25,\n} as const;\n\n/** Alias for IntentBits. */\nexport const Intents = IntentBits;\n\n/** Gateway intents: an array of intent bits or names, e.g. `[GatewayIntentBits.Guilds, \"GuildMessages\"]`. A single number, name or OR-ed bitfield is not accepted. */\nexport type GatewayIntentResolvable = readonly (\n number | keyof typeof GatewayIntentBits | keyof typeof IntentBits | string\n)[];\n\n/**\n * Resolves an array of intents into a raw bitfield integer.\n * @throws {TypeError} If `intents` is not an array (an OR-ed number, a single name or a bitfield object).\n */\nexport function resolveGatewayIntents(\n intents: GatewayIntentResolvable,\n): number {\n if (!Array.isArray(intents))\n throw new TypeError(\n \"Gateway intents must be an array, e.g. [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages].\",\n );\n return intents.reduce<number>(\n (acc, intent) => acc | resolveIntent(intent),\n 0,\n );\n}\n\n/** Resolves one intent: a bitfield, an intent name in either casing, or a numeric string. */\nfunction resolveIntent(intent: number | string): number {\n if (typeof intent === \"number\") return intent;\n const bits: Record<string, number> = {\n ...IntentBits,\n ...GatewayIntentBits,\n };\n const lower = intent.charAt(0).toLowerCase() + intent.slice(1);\n if (Object.hasOwn(bits, intent)) return bits[intent]!;\n if (Object.hasOwn(bits, lower)) return bits[lower]!;\n const num = Number(intent);\n return Number.isNaN(num) ? 0 : num;\n}\n\n/** What `IntentsBitField` methods take: one intent or an array of them. Clients and gateways take only arrays. */\ntype IntentsInput = GatewayIntentResolvable[number] | GatewayIntentResolvable;\n\nfunction resolveInput(bits: IntentsInput): number {\n return resolveGatewayIntents(Array.isArray(bits) ? bits : [bits as number]);\n}\n\n/**\n * Discord.js-familiar intent bitfield.\n * @example new IntentsBitField([IntentsBitField.Flags.Guilds, \"GuildMessages\"])\n */\nexport class IntentsBitField {\n /** Intent flag values by name. */\n public static readonly Flags = GatewayIntentBits;\n /** Raw intent bitfield. */\n public bitfield: number;\n\n public constructor(bits: IntentsInput = []) {\n this.bitfield = resolveInput(bits);\n }\n\n /** Whether every given intent is set. */\n public has(bits: IntentsInput): boolean {\n const resolved = resolveInput(bits);\n return (this.bitfield & resolved) === resolved;\n }\n\n /** Whether any given intent is set. */\n public any(bits: IntentsInput): boolean {\n return (this.bitfield & resolveInput(bits)) !== 0;\n }\n\n /** Adds intents in place. @returns This bitfield. */\n public add(...bits: IntentsInput[]): this {\n for (const bit of bits) this.bitfield |= resolveInput(bit);\n return this;\n }\n\n /** Removes intents in place. @returns This bitfield. */\n public remove(...bits: IntentsInput[]): this {\n for (const bit of bits) this.bitfield &= ~resolveInput(bit);\n return this;\n }\n\n /** Names of the set intents. */\n public toArray(): (keyof typeof GatewayIntentBits)[] {\n return (\n Object.keys(GatewayIntentBits) as (keyof typeof GatewayIntentBits)[]\n ).filter((name) => this.has(GatewayIntentBits[name]));\n }\n\n /** Whether this equals another bitfield. */\n public equals(bits: IntentsInput): boolean {\n return this.bitfield === resolveInput(bits);\n }\n\n public valueOf(): number {\n return this.bitfield;\n }\n\n public toJSON(): number {\n return this.bitfield;\n }\n}\n\n// ─── Gateway Config ───────────────────────────────────────────────────────────\n\n/** Gateway connection properties (OS, browser, device). */\nexport interface GatewayProperties {\n os?: string;\n browser?: string;\n device?: string;\n [key: string]: string | undefined;\n}\n/** Gateway presence activity. */\nexport interface GatewayPresenceActivity {\n name: string;\n type?: number;\n url?: string;\n state?: string;\n}\n/** Gateway presence data. */\nexport interface GatewayPresence {\n status?: \"online\" | \"dnd\" | \"idle\" | \"invisible\" | \"offline\";\n activities?: GatewayPresenceActivity[];\n afk?: boolean;\n since?: number | null;\n}\n/** Client configuration. */\nexport interface ClientOptions {\n token: string;\n intents: GatewayIntentResolvable;\n gateway?: GatewayOptions;\n /**\n * zlib-stream transport compression for the Gateway connection, about a\n * tenth of the inbound bandwidth. Shorthand for `gateway: { compress }`,\n * which wins when both are set. Off by default.\n */\n compress?: boolean;\n rest?: RESTOptions;\n /** Opt-in bounded per-channel message cache. Messages are not cached by default. */\n messageCache?: { maxSize?: number; ttl?: number };\n /**\n * Which resources the client keeps from Gateway events. Everything is\n * cached by default; large bots can turn off what they do not read.\n * Events are still emitted either way.\n */\n cache?: {\n users?: boolean;\n members?: boolean;\n roles?: boolean;\n emojis?: boolean;\n /** Keep each member's latest presence (needs the `GuildPresences` intent). Off by default: it is a lot of data. */\n presences?: boolean;\n };\n /**\n * Default `allowed_mentions` for every message the client sends (channel\n * send/edit, replies, interaction replies, edits and follow-ups), e.g.\n * `{ parse: [] }` so nothing pings unless a message says so. A message's\n * own `allowed_mentions` always wins.\n */\n allowedMentions?: AllowedMentions;\n}\n/** Discord's `allowed_mentions` object. */\nexport interface AllowedMentions {\n parse?: (\"users\" | \"roles\" | \"everyone\")[];\n users?: string[];\n roles?: string[];\n replied_user?: boolean;\n}\n/** Gateway connection configuration. */\nexport interface GatewayOptions {\n intents?: GatewayIntentResolvable;\n reconnect?: boolean;\n maxReconnectAttempts?: number;\n reconnectBaseDelay?: number;\n reconnectMaxDelay?: number;\n shardId?: number;\n shardCount?: number;\n properties?: GatewayProperties;\n presence?: GatewayPresence;\n}\n\n/** REST request configuration. */\nexport interface RESTOptions {\n timeout?: number;\n retries?: number;\n baseURL?: string;\n}\n",
7
+ "/** Discord API snowflake identifier. */\nexport type Snowflake = string;\n\nexport * from \"./channel-kind.js\";\nexport * from \"./gateway.js\";\nexport * from \"./gateway-events.js\";\n\n// ─── Core Discord Objects ─────────────────────────────────────────────────────\n\n/** Discord user object. */\nexport interface UserData {\n id: Snowflake;\n username: string;\n discriminator?: string;\n global_name?: string | null;\n avatar?: string | null;\n bot?: boolean;\n system?: boolean;\n public_flags?: number;\n}\n/** Current authenticated bot user. */\nexport type ClientUser = UserData;\n/** Discord Gateway payload envelope. */\nexport interface GatewayPayload<T = unknown> {\n op: number;\n d: T | null;\n s: number | null;\n t: string | null;\n}\n/** Generic Discord API error payload. */\nexport interface APIError {\n code?: number;\n message?: string;\n errors?: Record<string, unknown>;\n}\n\n// ─── Discord Flags & Enums ────────────────────────────────────────────────────\n\n/** Discord message flags. */\nexport const MessageFlags = {\n Crossposted: 1,\n IsCrosspost: 2,\n SuppressEmbeds: 4,\n SourceMessageDeleted: 8,\n Urgent: 16,\n HasThread: 32,\n Ephemeral: 64,\n Loading: 128,\n IsComponentsV2: 32768,\n} as const;\n/** One {@link MessageFlags} value, usable as a type. */\nexport type MessageFlags = (typeof MessageFlags)[keyof typeof MessageFlags];\n\n/** Discord channel types. */\nexport const ChannelEnum = {\n GuildText: 0,\n DM: 1,\n GuildVoice: 2,\n GroupDM: 3,\n GuildCategory: 4,\n GuildAnnouncement: 5,\n AnnouncementThread: 10,\n PublicThread: 11,\n PrivateThread: 12,\n GuildStageVoice: 13,\n GuildDirectory: 14,\n GuildForum: 15,\n GuildMedia: 16,\n} as const;\n/** One {@link ChannelEnum} value, usable as a type. */\nexport type ChannelEnum = (typeof ChannelEnum)[keyof typeof ChannelEnum];\n\n/** Discord component types. */\nexport const ComponentEnum = {\n ActionRow: 1,\n Button: 2,\n StringSelect: 3,\n TextInput: 4,\n UserSelect: 5,\n RoleSelect: 6,\n MentionableSelect: 7,\n ChannelSelect: 8,\n Section: 9,\n TextDisplay: 10,\n Thumbnail: 11,\n MediaGallery: 12,\n File: 13,\n Separator: 14,\n ContentInventoryEntry: 16,\n Container: 17,\n} as const;\n/** One {@link ComponentEnum} value, usable as a type. */\nexport type ComponentEnum = (typeof ComponentEnum)[keyof typeof ComponentEnum];\n\n/** Discord button style types. */\nexport const ButtonType = {\n Primary: 1,\n Secondary: 2,\n Success: 3,\n Danger: 4,\n Link: 5,\n Premium: 6,\n} as const;\n/** One {@link ButtonType} value, usable as a type: `style: ButtonType`. */\nexport type ButtonType = (typeof ButtonType)[keyof typeof ButtonType];\n\n/** Discord text input style types. */\nexport const TextInputType = {\n Short: 1,\n Paragraph: 2,\n} as const;\n/** One {@link TextInputType} value, usable as a type. */\nexport type TextInputType = (typeof TextInputType)[keyof typeof TextInputType];\n\n/** Discord interaction response types. */\nexport const InteractionResponseEnum = {\n Pong: 1,\n ChannelMessage: 4,\n DeferredChannelMessage: 5,\n DeferredMessageUpdate: 6,\n MessageUpdate: 7,\n Autocomplete: 8,\n Modal: 9,\n} as const;\n/** One {@link InteractionResponseEnum} value, usable as a type. */\nexport type InteractionResponseEnum =\n (typeof InteractionResponseEnum)[keyof typeof InteractionResponseEnum];\n\n/** Discord sticker format types. */\nexport const StickerFormatEnum = {\n PNG: 1,\n APNG: 2,\n Lottie: 3,\n GIF: 4,\n} as const;\n/** One {@link StickerFormatEnum} value, usable as a type. */\nexport type StickerFormatEnum =\n (typeof StickerFormatEnum)[keyof typeof StickerFormatEnum];\n\n/** Discord sticker types. */\nexport const StickerEnum = {\n Standard: 1,\n Guild: 2,\n} as const;\n/** One {@link StickerEnum} value, usable as a type. */\nexport type StickerEnum = (typeof StickerEnum)[keyof typeof StickerEnum];\n\n/** Discord verification levels. */\nexport const VerificationLevel = {\n None: 0,\n Low: 1,\n Medium: 2,\n High: 3,\n VeryHigh: 4,\n} as const;\n\n/** Discord premium tiers. */\nexport const PremiumTier = {\n None: 0,\n Tier1: 1,\n Tier2: 2,\n Tier3: 3,\n} as const;\n\n// ─── Embeds ───────────────────────────────────────────────────────────────────\n\n/** Raw Discord embed footer object. */\nexport interface APIEmbedFooter {\n text: string;\n icon_url?: string;\n proxy_icon_url?: string;\n}\n/** Raw Discord embed image/thumbnail/video object. */\nexport interface APIEmbedMedia {\n url: string;\n proxy_url?: string;\n height?: number;\n width?: number;\n}\n/** Raw Discord embed provider object. */\nexport interface APIEmbedProvider {\n name?: string;\n url?: string;\n}\n/** Raw Discord embed author object. */\nexport interface APIEmbedAuthor {\n name: string;\n url?: string;\n icon_url?: string;\n proxy_icon_url?: string;\n}\n/** Raw Discord embed field object. */\nexport interface APIEmbedField {\n name: string;\n value: string;\n inline?: boolean;\n}\n/** Raw Discord embed object. */\nexport interface APIEmbed {\n title?: string;\n type?: string;\n description?: string;\n url?: string;\n timestamp?: string;\n color?: number;\n footer?: APIEmbedFooter;\n image?: APIEmbedMedia;\n thumbnail?: APIEmbedMedia;\n video?: APIEmbedMedia;\n provider?: APIEmbedProvider;\n author?: APIEmbedAuthor;\n fields?: APIEmbedField[];\n}\n\n// ─── Message Components ───────────────────────────────────────────────────────\n\n/** Raw Discord select menu option. */\nexport interface APISelectMenuOption {\n label: string;\n value: string;\n description?: string;\n emoji?: APIPartialEmoji;\n default?: boolean;\n}\n/** Raw Discord emoji (partial, as used in components). */\nexport interface APIPartialEmoji {\n id?: Snowflake | null;\n name?: string | null;\n animated?: boolean;\n}\n/** Raw Discord button component. */\nexport interface APIButtonComponent {\n type: 2;\n style: number;\n label?: string;\n emoji?: APIPartialEmoji;\n custom_id?: string;\n url?: string;\n sku_id?: string;\n disabled?: boolean;\n}\n/** Raw Discord select menu component. */\nexport interface APISelectMenuComponent {\n type: 3 | 5 | 6 | 7 | 8;\n custom_id: string;\n options?: APISelectMenuOption[];\n channel_types?: number[];\n placeholder?: string;\n min_values?: number;\n max_values?: number;\n disabled?: boolean;\n}\n/** Raw Discord text input component. */\nexport interface APITextInputComponent {\n type: 4;\n custom_id: string;\n style: number;\n label: string;\n min_length?: number;\n max_length?: number;\n required?: boolean;\n value?: string;\n placeholder?: string;\n}\n/** Union of all raw message component types. */\nexport type APIMessageActionRowComponent =\n APIButtonComponent | APISelectMenuComponent | APITextInputComponent;\n/** Raw Discord action row component. */\nexport interface APIActionRowComponent {\n type: 1;\n id?: number;\n components: APIMessageActionRowComponent[];\n}\n/** Union including action rows and V2 components. */\nexport type APIMessageComponent =\n APIActionRowComponent | { type: Exclude<number, 1>; [key: string]: any };\n\n// ─── Message payloads ────────────────────────────────────────────────────────\n\n/** A Discord payload, or a builder that serialises to one (its `toJSON()` runs when the request is sent). */\nexport type Buildable<T> = T | { toJSON(): T };\n\n/**\n * A message Lunibee sends: channel send and edit, message reply and edit,\n * interaction replies, follow-ups and updates. Embeds and components may be\n * builders or raw objects. Other Discord fields pass through unchanged.\n */\nexport interface MessagePayload {\n content?: string;\n embeds?: Buildable<APIEmbed>[];\n components?: Buildable<APIMessageComponent>[];\n allowed_mentions?: import(\"./gateway.js\").AllowedMentions;\n /** Discord message flags, e.g. `MessageFlags.SuppressEmbeds`. */\n flags?: number;\n tts?: boolean;\n /** Attachment metadata for files sent with the message. */\n attachments?: Array<{\n id: number | string;\n filename?: string;\n description?: string;\n }>;\n [key: string]: unknown;\n}\n\n/** A file to upload with a message. */\nexport interface MessageFile {\n name: string;\n data: Blob | Uint8Array | ArrayBuffer | string;\n contentType?: string;\n}\n\n/** A poll to send; Discord fills in `results` and `expiry` when it is read back. */\nexport interface MessagePoll {\n question: { text?: string; emoji?: APIPartialEmoji };\n answers: Array<{ poll_media: { text?: string; emoji?: APIPartialEmoji } }>;\n /** Hours the poll stays open (1-768). */\n duration?: number;\n allow_multiselect?: boolean;\n layout_type?: number;\n}\n\n/** What `send()` takes. */\nexport interface MessageCreateOptions extends MessagePayload {\n /** Files to upload; the message is sent as multipart. */\n files?: MessageFile[];\n /** Reply to or forward another message. */\n message_reference?: APIMessageReference;\n poll?: MessagePoll;\n sticker_ids?: Snowflake[];\n /** Returned on the Gateway event so the client can match its own message. */\n nonce?: string | number;\n enforce_nonce?: boolean;\n}\n\n/** What `edit()` takes: the fields Discord lets you change after sending. */\nexport interface MessageEditOptions extends MessagePayload {\n files?: MessageFile[];\n}\n\n/** What a reply, edit-reply, follow-up or update to an interaction takes. */\nexport interface InteractionReplyOptions extends MessagePayload {\n /** Only the person who ran the command sees it. */\n ephemeral?: boolean;\n files?: MessageFile[];\n poll?: MessagePoll;\n /** On `reply()` / `update()`: return the created message (one request, no `fetchReply()`). */\n withResponse?: boolean;\n}\n\n/** What `update()` on a component interaction takes. */\nexport type InteractionUpdateOptions = InteractionReplyOptions;\n\n/** What `followUp()` takes. */\nexport type FollowUpOptions = InteractionReplyOptions;\n\n// ─── Attachments ─────────────────────────────────────────────────────────────\n\n/** Raw Discord attachment object. */\nexport interface APIAttachment {\n id: Snowflake;\n filename: string;\n description?: string | null;\n content_type?: string;\n size: number;\n url: string;\n proxy_url: string;\n height?: number | null;\n width?: number | null;\n ephemeral?: boolean;\n duration_secs?: number;\n waveform?: string;\n flags?: number;\n}\n\n// ─── Stickers ────────────────────────────────────────────────────────────────\n\n/** Compact sticker item as included in messages. */\nexport interface APIStickerItem {\n id: Snowflake;\n name: string;\n format_type: number;\n}\n/** Full Discord sticker object. */\nexport interface APISticker {\n id: Snowflake;\n pack_id?: Snowflake;\n name: string;\n description?: string | null;\n tags?: string;\n type: number;\n format_type: number;\n available?: boolean;\n guild_id?: Snowflake;\n user?: UserData;\n sort_value?: number;\n}\n\n// ─── Messages ────────────────────────────────────────────────────────────────\n\n/** Raw Discord message reference. */\nexport interface APIMessageReference {\n type?: number;\n message_id?: Snowflake;\n channel_id?: Snowflake;\n guild_id?: Snowflake;\n fail_if_not_exists?: boolean;\n}\n/** Raw Discord message reaction. */\nexport interface APIMessageReaction {\n count: number;\n count_details?: Record<string, number>;\n me?: boolean;\n me_burst?: boolean;\n emoji: APIPartialEmoji;\n burst_colors?: string[];\n}\n/** Raw Discord poll object. */\nexport interface APIPoll {\n question: { text?: string; emoji?: APIPartialEmoji };\n answers: Array<{\n answer_id: number;\n poll_media: { text?: string; emoji?: APIPartialEmoji };\n }>;\n expiry: string | null;\n allow_multiselect: boolean;\n layout_type: number;\n results?: {\n is_finalized: boolean;\n answer_counts: Array<{ id: number; count: number; me_voted: boolean }>;\n };\n}\n/** A forwarded message's snapshot of the original. */\nexport interface APIMessageSnapshot {\n message: Partial<\n Pick<\n APIMessage,\n | \"type\"\n | \"content\"\n | \"embeds\"\n | \"attachments\"\n | \"timestamp\"\n | \"edited_timestamp\"\n | \"flags\"\n | \"mentions\"\n | \"mention_roles\"\n | \"sticker_items\"\n | \"components\"\n >\n >;\n}\n/** Raw Discord message object. */\nexport interface APIMessage {\n id: Snowflake;\n channel_id: Snowflake;\n author: UserData;\n content: string;\n timestamp?: string;\n edited_timestamp?: string | null;\n tts?: boolean;\n mention_everyone?: boolean;\n mentions?: UserData[];\n mention_roles?: Snowflake[];\n mention_channels?: Array<Record<string, unknown>>;\n attachments?: APIAttachment[];\n embeds?: APIEmbed[];\n reactions?: APIMessageReaction[];\n nonce?: string | number | null;\n pinned?: boolean;\n webhook_id?: Snowflake;\n type?: number;\n activity?: Record<string, unknown>;\n application?: Record<string, unknown>;\n application_id?: Snowflake;\n message_reference?: APIMessageReference;\n flags?: number;\n referenced_message?: APIMessage | null;\n interaction_metadata?: Record<string, unknown>;\n thread?: Record<string, unknown>;\n components?: APIMessageComponent[];\n sticker_items?: APIStickerItem[];\n stickers?: APISticker[];\n position?: number;\n role_subscription_data?: Record<string, unknown>;\n purchase_notification?: Record<string, unknown>;\n poll?: APIPoll;\n /** Forwarded messages: a partial copy of the original (content, embeds, attachments, …). */\n message_snapshots?: APIMessageSnapshot[];\n guild_id?: Snowflake;\n /** The author's guild member, on guild messages from the Gateway (without `user`; the author is the user). */\n member?: Omit<APIGuildMember, \"user\"> & { user?: UserData };\n}\n\n// ─── Channels ────────────────────────────────────────────────────────────────\n\n/** Raw Discord channel object. */\nexport interface APIChannel {\n id: Snowflake;\n type: number;\n guild_id?: Snowflake;\n position?: number;\n permission_overwrites?: APIOverwrite[];\n name?: string | null;\n topic?: string | null;\n nsfw?: boolean;\n last_message_id?: Snowflake | null;\n bitrate?: number;\n user_limit?: number;\n rate_limit_per_user?: number;\n recipients?: UserData[];\n icon?: string | null;\n owner_id?: Snowflake;\n application_id?: Snowflake;\n parent_id?: Snowflake | null;\n last_pin_timestamp?: string | null;\n rtc_region?: string | null;\n video_quality_mode?: number;\n message_count?: number;\n member_count?: number;\n thread_metadata?: APIThreadMetadata;\n default_auto_archive_duration?: number;\n flags?: number;\n total_message_sent?: number;\n available_tags?: APIForumTag[];\n default_reaction_emoji?: APIPartialEmoji | null;\n default_thread_rate_limit_per_user?: number;\n default_sort_order?: number | null;\n default_forum_layout?: number;\n}\n\n/** Raw Discord thread metadata. */\nexport interface APIThreadMetadata {\n archived: boolean;\n auto_archive_duration: number;\n archive_timestamp: string;\n locked: boolean;\n invitable?: boolean;\n create_timestamp?: string | null;\n}\n\n/** Fields for a forum or media channel tag. */\nexport interface ForumTagInput {\n name: string;\n /** Only moderators (Manage Threads) can apply it. */\n moderated?: boolean;\n emoji_id?: Snowflake | null;\n emoji_name?: string | null;\n}\n\n/** A role's colours: a solid colour, or a gradient or holographic style. */\nexport interface APIRoleColors {\n primary_color: number;\n secondary_color: number | null;\n tertiary_color: number | null;\n}\n\n/** Raw Discord forum tag. */\nexport interface APIForumTag {\n id: Snowflake;\n name: string;\n moderated: boolean;\n emoji_id?: Snowflake | null;\n emoji_name?: string | null;\n}\n\n/** Raw Discord thread member. */\nexport interface APIThreadMember {\n id?: Snowflake;\n user_id?: Snowflake;\n join_timestamp: string;\n flags: number;\n member?: APIGuildMember;\n}\n\n// ─── Guild welcome screen and onboarding ──────────────────────────────────────\n\n/** A channel shown on the welcome screen. */\nexport interface APIWelcomeScreenChannel {\n channel_id: Snowflake;\n description: string;\n emoji_id: Snowflake | null;\n emoji_name: string | null;\n}\n\n/** Raw Discord welcome screen. */\nexport interface APIWelcomeScreen {\n description: string | null;\n welcome_channels: APIWelcomeScreenChannel[];\n}\n\n/** One answer to an onboarding question. */\nexport interface APIOnboardingOption {\n id: Snowflake;\n channel_ids: Snowflake[];\n role_ids: Snowflake[];\n emoji?: APIPartialEmoji;\n title: string;\n description: string | null;\n}\n\n/** A question in a guild's onboarding. */\nexport interface APIOnboardingPrompt {\n id: Snowflake;\n type: number;\n options: APIOnboardingOption[];\n title: string;\n single_select: boolean;\n required: boolean;\n in_onboarding: boolean;\n}\n\n/** Raw Discord guild onboarding. */\nexport interface APIGuildOnboarding {\n guild_id: Snowflake;\n prompts: APIOnboardingPrompt[];\n default_channel_ids: Snowflake[];\n enabled: boolean;\n mode: number;\n}\n\n// ─── Roles ────────────────────────────────────────────────────────────────────\n\n/** Raw Discord role object. */\nexport interface APIRole {\n id: Snowflake;\n name: string;\n color: number;\n hoist: boolean;\n icon?: string | null;\n unicode_emoji?: string | null;\n /** Gradient and holographic colours; `color` stays the primary colour. */\n colors?: APIRoleColors;\n position: number;\n permissions: string;\n managed: boolean;\n mentionable: boolean;\n tags?: Record<string, unknown>;\n flags?: number;\n}\n\n// ─── Emoji ────────────────────────────────────────────────────────────────────\n\n/** Raw Discord emoji object. */\nexport interface APIEmoji {\n id: Snowflake | null;\n name: string | null;\n roles?: Snowflake[];\n user?: UserData;\n require_colons?: boolean;\n managed?: boolean;\n animated?: boolean;\n available?: boolean;\n}\n\n// ─── Guilds ───────────────────────────────────────────────────────────────────\n\n/** Raw Discord guild object. */\nexport interface APIGuild {\n id: Snowflake;\n name: string;\n icon?: string | null;\n icon_hash?: string | null;\n splash?: string | null;\n discovery_splash?: string | null;\n owner?: boolean;\n owner_id?: Snowflake;\n permissions?: string;\n afk_channel_id?: Snowflake | null;\n afk_timeout?: number;\n widget_enabled?: boolean;\n widget_channel_id?: Snowflake | null;\n verification_level?: number;\n default_message_notifications?: number;\n explicit_content_filter?: number;\n roles?: APIRole[];\n emojis?: APIEmoji[];\n stickers?: APISticker[];\n features?: string[];\n mfa_level?: number;\n application_id?: Snowflake | null;\n system_channel_id?: Snowflake | null;\n system_channel_flags?: number;\n rules_channel_id?: Snowflake | null;\n max_presences?: number | null;\n max_members?: number;\n vanity_url_code?: string | null;\n description?: string | null;\n banner?: string | null;\n premium_tier?: number;\n premium_subscription_count?: number;\n preferred_locale?: string;\n public_updates_channel_id?: Snowflake | null;\n max_video_channel_users?: number;\n premium_progress_bar_enabled?: boolean;\n approximate_member_count?: number;\n approximate_presence_count?: number;\n nsfw_level?: number;\n safety_alerts_channel_id?: Snowflake | null;\n member_count?: number;\n}\n\n// ─── Welcome Screen ───────────────────────────────────────────────────────────\n\nexport interface APIWelcomeScreenChannel {\n channel_id: Snowflake;\n description: string;\n emoji_id: Snowflake | null;\n emoji_name: string | null;\n}\n\nexport interface APIGuildWelcomeScreen {\n description: string | null;\n welcome_channels: APIWelcomeScreenChannel[];\n}\n\n// ─── Guild Onboarding ─────────────────────────────────────────────────────────\n\nexport interface APIOnboardingPromptOption {\n id: Snowflake;\n channel_ids: Snowflake[];\n role_ids: Snowflake[];\n emoji?: APIPartialEmoji;\n title: string;\n description: string | null;\n}\n\nexport interface APIOnboardingPrompt {\n id: Snowflake;\n type: number;\n options: APIOnboardingPromptOption[];\n title: string;\n single_select: boolean;\n required: boolean;\n in_onboarding: boolean;\n}\n\nexport interface APIGuildOnboarding {\n guild_id: Snowflake;\n prompts: APIOnboardingPrompt[];\n default_channel_ids: Snowflake[];\n enabled: boolean;\n mode: number;\n}\n\n/** Raw Discord guild member object. */\nexport interface APIGuildMember {\n user: UserData;\n nick?: string | null;\n avatar?: string | null;\n roles: Snowflake[];\n joined_at: string;\n premium_since?: string | null;\n deaf?: boolean;\n mute?: boolean;\n flags?: number;\n pending?: boolean;\n permissions?: string;\n communication_disabled_until?: string | null;\n guild_id?: Snowflake;\n}\n\n// ─── Voice ────────────────────────────────────────────────────────────────────\n\n/** Raw Discord voice state object. */\nexport interface APIVoiceState {\n guild_id?: Snowflake;\n channel_id?: Snowflake | null;\n user_id: Snowflake;\n member?: APIGuildMember;\n session_id: string;\n deaf: boolean;\n mute: boolean;\n self_deaf: boolean;\n self_mute: boolean;\n self_stream?: boolean;\n self_video: boolean;\n suppress: boolean;\n request_to_speak_timestamp?: string | null;\n}\n\n/** Raw Discord voice server update event. */\nexport interface APIVoiceServerUpdate {\n token: string;\n guild_id: Snowflake;\n endpoint?: string | null;\n}\n\n// ─── Presence ────────────────────────────────────────────────────────────────\n\n/** Raw Discord activity object. */\n/** Discord activity types, for presences (`setPresence({ activities: [{ name, type: ActivityEnum.Watching }] })`). */\nexport const ActivityEnum = {\n Playing: 0,\n Streaming: 1,\n Listening: 2,\n Watching: 3,\n Custom: 4,\n Competing: 5,\n} as const;\n/** One {@link ActivityEnum} value, usable as a type. */\nexport type ActivityEnum = (typeof ActivityEnum)[keyof typeof ActivityEnum];\n\nexport interface APIActivity {\n name: string;\n type: number;\n url?: string | null;\n created_at: number;\n state?: string | null;\n details?: string | null;\n emoji?: APIPartialEmoji | null;\n}\n\n/** Raw Discord presence update event. */\nexport interface APIPresenceUpdate {\n user: { id: Snowflake } & Partial<UserData>;\n guild_id: Snowflake;\n status: string;\n activities: APIActivity[];\n client_status: { desktop?: string; mobile?: string; web?: string };\n}\n\n// ─── Typing ───────────────────────────────────────────────────────────────────\n\n/** Raw Discord typing start event. */\nexport interface APITypingStart {\n channel_id: Snowflake;\n guild_id?: Snowflake;\n user_id: Snowflake;\n timestamp: number;\n member?: APIGuildMember;\n}\n\n// ─── Guilds ──────────────────────────────────────────────────────────────────\n\n/** Raw Discord guild preview. */\nexport interface APIGuildPreview {\n id: Snowflake;\n name: string;\n icon: string | null;\n splash: string | null;\n discovery_splash: string | null;\n emojis: unknown[];\n features: string[];\n approximate_member_count: number;\n approximate_presence_count: number;\n description: string | null;\n stickers: unknown[];\n}\n\n// ─── Invites ─────────────────────────────────────────────────────────────────\n\n/** Raw Discord invite. */\nexport interface APIInvite {\n code: string;\n guild?: Partial<APIGuild>;\n channel: Partial<APIChannel>;\n inviter?: UserData;\n target_type?: number;\n target_user?: UserData;\n approximate_presence_count?: number;\n approximate_member_count?: number;\n}\n\n/** Raw Discord invite create event. */\nexport interface APIInviteCreate {\n channel_id: Snowflake;\n code: string;\n created_at: string;\n guild_id?: Snowflake;\n inviter?: UserData;\n max_age: number;\n max_uses: number;\n target_type?: number;\n target_user?: UserData;\n temporary: boolean;\n uses: number;\n}\n\n/** Raw Discord invite delete event. */\nexport interface APIInviteDelete {\n channel_id: Snowflake;\n guild_id?: Snowflake;\n code: string;\n}\n\n// ─── Webhooks ────────────────────────────────────────────────────────────────\n\n/** Raw Discord webhooks update event. */\nexport interface APIWebhooksUpdate {\n guild_id: Snowflake;\n channel_id: Snowflake;\n}\n\n/** Raw Discord webhook object. */\nexport interface APIWebhook {\n id: Snowflake;\n type: number;\n guild_id?: Snowflake | null;\n channel_id?: Snowflake | null;\n user?: UserData;\n name?: string | null;\n avatar?: string | null;\n token?: string;\n application_id?: Snowflake | null;\n url?: string;\n}\n\n// ─── AutoMod ─────────────────────────────────────────────────────────────────\n\n/** Raw Discord AutoMod action. */\nexport interface APIAutoModerationAction {\n type: number;\n metadata?: {\n channel_id?: Snowflake;\n duration_seconds?: number;\n custom_message?: string;\n };\n}\n\n// ─── Audit Logs ──────────────────────────────────────────────────────────────\n\n/** Raw Discord audit log change object. */\nexport interface APIAuditLogChange {\n new_value?: unknown;\n old_value?: unknown;\n key: string;\n}\n\n/** Raw Discord audit log entry options object. */\nexport interface APIAuditLogOptions {\n app_id?: Snowflake;\n auto_moderation_rule_name?: string;\n auto_moderation_rule_trigger_type?: string;\n channel_id?: Snowflake;\n count?: string;\n delete_member_days?: string;\n id?: Snowflake;\n members_removed?: string;\n message_id?: Snowflake;\n role_name?: string;\n type?: string;\n integration_type?: string;\n}\n\n/** Raw Discord audit log entry object. */\nexport interface APIAuditLogEntry {\n target_id: string | null;\n changes?: APIAuditLogChange[];\n user_id: Snowflake | null;\n id: Snowflake;\n action_type: number;\n options?: APIAuditLogOptions;\n reason?: string;\n}\n\n/** Raw Discord audit log object. */\nexport interface APIAuditLog {\n audit_log_entries: APIAuditLogEntry[];\n guild_scheduled_events: APIGuildScheduledEvent[];\n integrations: Array<Record<string, unknown>>;\n threads: APIChannel[];\n users: UserData[];\n webhooks: APIWebhook[];\n application_commands: APIApplicationCommand[];\n auto_moderation_rules: APIAutoModerationRule[];\n}\n\n/** Raw Discord AutoMod rule object. */\nexport interface APIAutoModerationRule {\n id: Snowflake;\n guild_id: Snowflake;\n name: string;\n creator_id: Snowflake;\n event_type: number;\n trigger_type: number;\n trigger_metadata: Record<string, unknown>;\n actions: APIAutoModerationAction[];\n enabled: boolean;\n exempt_roles: Snowflake[];\n exempt_channels: Snowflake[];\n}\n\n/** Raw Discord AutoMod action execution event. */\nexport interface APIAutoModerationActionExecution {\n guild_id: Snowflake;\n action: APIAutoModerationAction;\n rule_id: Snowflake;\n rule_trigger_type: number;\n user_id: Snowflake;\n channel_id?: Snowflake;\n message_id?: Snowflake;\n alert_system_message_id?: Snowflake;\n content: string;\n matched_keyword?: string | null;\n matched_content?: string | null;\n}\n\n// ─── Scheduled Events ─────────────────────────────────────────────────────────\n\n/** Raw Discord guild scheduled event entity metadata. */\nexport interface APIGuildScheduledEventEntityMetadata {\n location?: string;\n}\n\n/** Raw Discord guild scheduled event object. */\nexport interface APIGuildScheduledEvent {\n id: Snowflake;\n guild_id: Snowflake;\n channel_id?: Snowflake | null;\n creator_id?: Snowflake | null;\n name: string;\n description?: string | null;\n scheduled_start_time: string;\n scheduled_end_time?: string | null;\n privacy_level: number;\n status: number;\n entity_type: number;\n entity_id?: Snowflake | null;\n entity_metadata?: APIGuildScheduledEventEntityMetadata | null;\n creator?: UserData;\n user_count?: number;\n image?: string | null;\n}\n\n// ─── Stage Instances ─────────────────────────────────────────────────────────\n\n/** Raw Discord stage instance object. */\nexport interface APIStageInstance {\n id: Snowflake;\n guild_id: Snowflake;\n channel_id: Snowflake;\n topic: string;\n privacy_level: number;\n discoverable_disabled?: boolean;\n guild_scheduled_event_id?: Snowflake | null;\n}\n\n// ─── Application Commands ─────────────────────────────────────────────────────\n\n/** Discord application command option types. */\nexport const ApplicationCommandOptionEnum = {\n SubCommand: 1,\n SubCommandGroup: 2,\n String: 3,\n Integer: 4,\n Boolean: 5,\n User: 6,\n Channel: 7,\n Role: 8,\n Mentionable: 9,\n Number: 10,\n Attachment: 11,\n} as const;\n/** One {@link ApplicationCommandOptionEnum} value, usable as a type. */\nexport type ApplicationCommandOptionEnum =\n (typeof ApplicationCommandOptionEnum)[keyof typeof ApplicationCommandOptionEnum];\n\n/** Discord application command types. */\nexport const ApplicationCommandEnum = {\n ChatInput: 1,\n User: 2,\n Message: 3,\n} as const;\n/** One {@link ApplicationCommandEnum} value, usable as a type. */\nexport type ApplicationCommandEnum =\n (typeof ApplicationCommandEnum)[keyof typeof ApplicationCommandEnum];\n\n/** Raw Discord application command option. */\nexport interface APIApplicationCommandOption {\n type: number;\n name: string;\n description: string;\n required?: boolean;\n choices?: Array<{ name: string; value: string | number }>;\n options?: APIApplicationCommandOption[];\n min_value?: number;\n max_value?: number;\n min_length?: number;\n max_length?: number;\n autocomplete?: boolean;\n channel_types?: number[];\n}\n\n/** Raw Discord application command object (from API). */\nexport interface APIApplicationCommand {\n id: Snowflake;\n type?: number;\n application_id: Snowflake;\n guild_id?: Snowflake;\n name: string;\n description: string;\n options?: APIApplicationCommandOption[];\n default_member_permissions?: string | null;\n /** Where the command can be used: 0 guilds, 1 the bot's DMs, 2 other DMs. */\n contexts?: number[];\n nsfw?: boolean;\n version: Snowflake;\n}\n\n/** Data for creating/overwriting an application command. */\nexport interface ApplicationCommandData {\n name: string;\n description: string;\n type?: number;\n options?: APIApplicationCommandOption[];\n default_member_permissions?: string | null;\n /** Where the command can be used: 0 guilds, 1 the bot's DMs, 2 other DMs. */\n contexts?: number[];\n nsfw?: boolean;\n}\n\n/** A channel permission overwrite for a role (type 0) or member (type 1). */\nexport interface APIOverwrite {\n id: Snowflake;\n type: 0 | 1;\n /** Allowed permission bits as a decimal string. */\n allow: string;\n /** Denied permission bits as a decimal string. */\n deny: string;\n}\n\n// ─── Soundboard & Monetization ───────────────────────────────────────────────\n/** Raw Discord soundboard sound. */\nexport interface APISoundboardSound {\n sound_id: string;\n name: string;\n volume: number;\n emoji_id: string | null;\n emoji_name: string | null;\n guild_id?: string;\n available: boolean;\n user?: UserData;\n}\n\n/** Raw Discord SKU. */\nexport interface APISKU {\n id: string;\n type: number;\n application_id: string;\n name: string;\n slug: string;\n flags: number;\n}\n\n/** Raw Discord entitlement. */\nexport interface APIEntitlement {\n id: string;\n sku_id: string;\n application_id: string;\n user_id?: string;\n guild_id?: string;\n type: number;\n deleted: boolean;\n starts_at?: string | null;\n ends_at?: string | null;\n consumed?: boolean;\n}\n\n/** Raw Discord subscription. */\nexport interface APISubscription {\n id: string;\n user_id: string;\n sku_ids: string[];\n entitlement_ids: string[];\n current_period_start: string;\n current_period_end: string;\n status: number;\n canceled_at: string | null;\n country?: string;\n}\n",
8
+ "import {\n channelKindOf,\n type ChannelKind,\n type MessageCreateOptions,\n type MessageEditOptions,\n type UnknownChannelKind,\n} from \"@lunibee/types\";\nimport type { ChannelOfKind } from \"./channels.js\";\n\n/** Common Discord snowflake-backed structure. */\nexport class BaseStructure {\n public readonly id: string;\n public constructor(id: string) {\n if (!/^\\d{1,20}$/.test(id))\n throw new TypeError(\n \"A Discord structure requires a valid snowflake ID.\",\n );\n this.id = id;\n }\n /** Returns the snowflake ID as a string. */\n public toString(): string {\n return this.id;\n }\n /** Milliseconds since the Unix epoch at which this snowflake was created. */\n public get createdTimestamp(): number {\n return Number((BigInt(this.id) >> 22n) + 1420070400000n);\n }\n /** Returns the timestamp this snowflake was created at. */\n public get createdAt(): Date {\n return new Date(this.createdTimestamp);\n }\n}\n\nexport interface ResourceContext {\n sendMessage(\n channelId: string,\n options: MessageCreateOptions,\n ): Promise<import(\"./index.js\").Message>;\n editMessage(\n channelId: string,\n messageId: string,\n options: MessageEditOptions,\n ): Promise<import(\"./index.js\").Message>;\n deleteMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void>;\n crosspostMessage(\n channelId: string,\n messageId: string,\n ): Promise<import(\"./index.js\").Message>;\n editChannel?(\n channelId: string,\n options: Record<string, unknown>,\n ): Promise<import(\"./base.js\").Channel>;\n deleteChannel?(channelId: string, reason?: string): Promise<void>;\n addReaction?(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void>;\n removeOwnReaction?(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void>;\n removeReaction?(\n channelId: string,\n messageId: string,\n emoji: string,\n userId: string,\n ): Promise<void>;\n removeAllReactions?(channelId: string, messageId: string): Promise<void>;\n pinMessage?(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void>;\n unpinMessage?(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void>;\n /**\n * A member's permissions from cached state: guild-level, or channel-level\n * (with overwrites) when a channel ID is given. Null when the guild (or\n * channel) is not cached.\n */\n memberPermissions?(\n guildId: string,\n memberId: string,\n roleIds: readonly string[],\n channelId?: string,\n timedOutUntil?: Date | null,\n ): import(\"@lunibee/core\").PermissionSet | null;\n kickMember?(\n guildId: string,\n userId: string,\n reason?: string,\n ): Promise<void>;\n banMember?(\n guildId: string,\n userId: string,\n options?: { reason?: string; deleteMessageSeconds?: number },\n ): Promise<void>;\n editMember?(\n guildId: string,\n userId: string,\n options: Record<string, unknown>,\n reason?: string,\n ): Promise<import(\"./resources.js\").GuildMember>;\n addMemberRole?(\n guildId: string,\n userId: string,\n roleId: string,\n reason?: string,\n ): Promise<void>;\n removeMemberRole?(\n guildId: string,\n userId: string,\n roleId: string,\n reason?: string,\n ): Promise<void>;\n /** Collects the client's interactions (a `Collector` over `interactionCreate`). Used by message and interaction collectors. */\n collectInteractions?(\n options: import(\"@lunibee/core\").CollectorOptions<\n import(\"./interactions.js\").Interaction\n >,\n ): import(\"@lunibee/core\").Collector<\n string,\n import(\"./interactions.js\").Interaction\n >;\n editPermissionOverwrite?(\n channelId: string,\n targetId: string,\n changes: PermissionOverwriteChanges,\n options?: { type?: 0 | 1; reason?: string },\n ): Promise<void>;\n}\n\n/**\n * Permissions to change on one overwrite: `true` allows, `false` denies,\n * `null` goes back to inheriting. Permissions not named keep their state.\n */\nexport type PermissionOverwriteChanges = Partial<\n Record<import(\"@lunibee/core\").PermissionName, boolean | null>\n>;\n\n// ─── CDN helpers ──────────────────────────────────────────────────────────────\n\nexport const CDN_BASE = \"https://cdn.discordapp.com\";\n\n/** Options for CDN image URLs. */\nexport interface ImageURLOptions {\n extension?: \"png\" | \"jpg\" | \"webp\" | \"gif\" | \"jpeg\";\n size?: 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096;\n forceStatic?: boolean;\n}\n\n/** Builds a Discord CDN asset URL from a directory path and asset hash, applying\n * animated-hash (`a_`) gif detection, extension and size options. Shared by all\n * hash-backed asset accessors (user/member/role/webhook) to avoid duplicating the logic.\n * @param path CDN directory path, e.g. `/role-icons/{id}`. @param hash Asset hash. @param options Image URL options. */\nexport function cdnURL(\n path: string,\n hash: string,\n options: ImageURLOptions = {},\n): string {\n const isAnimated = hash.startsWith(\"a_\") && !options.forceStatic;\n const ext = options.extension ?? (isAnimated ? \"gif\" : \"png\");\n const size = options.size ? `?size=${options.size}` : \"\";\n // Encoded, so a hash holding `/`, `?` or `#` cannot change the CDN path.\n return `${CDN_BASE}${path}/${encodeURIComponent(hash)}.${ext}${size}`;\n}\n\n// ─── User ─────────────────────────────────────────────────────────────────────\n\nexport class User extends BaseStructure {\n public username: string;\n public globalName: string | null;\n public avatar: string | null;\n public bot: boolean;\n public system: boolean;\n public flags: number;\n public discriminator: string | null;\n public constructor(data: import(\"@lunibee/types\").UserData) {\n super(data.id);\n if (!data.username)\n throw new TypeError(\"A Discord user requires a username.\");\n this.username = data.username;\n this.globalName = data.global_name ?? null;\n this.avatar = data.avatar ?? null;\n this.bot = data.bot ?? false;\n this.system = data.system ?? false;\n this.flags = data.public_flags ?? 0;\n this.discriminator =\n data.discriminator && data.discriminator !== \"0\"\n ? data.discriminator\n : null;\n }\n /** Effective display name — global name, falling back to username. */\n public get displayName(): string {\n return this.globalName ?? this.username;\n }\n /** Returns the user's avatar URL, or null if they have no avatar. */\n public avatarURL(options: ImageURLOptions = {}): string | null {\n if (!this.avatar) return null;\n return cdnURL(`/avatars/${this.id}`, this.avatar, options);\n }\n /** Returns the default avatar URL based on the user's discriminator/snowflake. */\n public defaultAvatarURL(): string {\n const index = this.discriminator\n ? Number(this.discriminator) % 5\n : Number((BigInt(this.id) >> 22n) % 6n);\n return `${CDN_BASE}/embed/avatars/${index}.png`;\n }\n /** Returns the avatar URL if available, falling back to the default avatar URL. */\n public displayAvatarURL(options: ImageURLOptions = {}): string {\n return this.avatarURL(options) ?? this.defaultAvatarURL();\n }\n /** Returns the Discord mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<@${this.id}>`;\n }\n}\n\n// ─── Channel ──────────────────────────────────────────────────────────────────\n\nexport class Channel extends BaseStructure {\n public type: number;\n public name?: string | null;\n public guildId?: string;\n public topic?: string | null;\n public parentId?: string | null;\n public nsfw?: boolean;\n public rateLimitPerUser?: number;\n public position?: number;\n /** Role and member permission overwrites (empty for DMs and when not provided). */\n public permissionOverwrites: import(\"@lunibee/types\").APIOverwrite[];\n readonly #context?: ResourceContext;\n\n /** Creates a channel structure from Discord channel data. */\n public constructor(\n data: import(\"@lunibee/types\").APIChannel,\n context?: ResourceContext,\n ) {\n super(data.id);\n if (!Number.isInteger(data.type) || data.type < 0)\n throw new RangeError(\n \"A Discord channel requires a valid channel type.\",\n );\n this.type = data.type;\n this.name = data.name;\n this.guildId = data.guild_id;\n this.topic = data.topic;\n this.parentId = data.parent_id;\n this.nsfw = data.nsfw;\n this.rateLimitPerUser = data.rate_limit_per_user;\n this.position = data.position;\n this.permissionOverwrites = (data.permission_overwrites ?? []).map(\n (overwrite) => ({ ...overwrite }),\n );\n this.#context = context;\n }\n\n /** Sends a message to this channel. @param options Message payload. @returns The created message. @throws {Error} If the channel is not attached to a client. */\n public send(\n options: MessageCreateOptions,\n ): Promise<import(\"./index.js\").Message> {\n if (!this.#context)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.sendMessage(this.id, options);\n }\n\n /** Edits this channel. @param options Channel fields to change. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n public edit(options: Record<string, unknown>): Promise<Channel> {\n if (!this.#context?.editChannel)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.editChannel(this.id, options);\n }\n\n /** Changes only this channel's name. @param name New channel name. @returns The updated channel. @throws {TypeError} If the name is empty. @throws {Error} If the channel is not attached to a client. */\n public editName(name: string): Promise<Channel> {\n if (!name.trim()) throw new TypeError(\"Channel name cannot be empty.\");\n return this.edit({ name });\n }\n\n /** Changes only this channel's topic. @param topic New topic, or null to clear it. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n public editTopic(topic: string | null): Promise<Channel> {\n return this.edit({ topic });\n }\n\n /** Moves this channel to another parent category. @param parentId Parent category ID, or null to remove the parent. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n /**\n * Changes some permissions of one overwrite and keeps the rest: `true`\n * allows, `false` denies, `null` resets to inherited.\n * @param targetId Role or member ID. @param changes Permissions to change.\n * @param options `type` (0 role, 1 member) when the overwrite does not exist yet; audit-log `reason`.\n * @example channel.editPermissionOverwrite(userId, { ViewChannel: true, SendMessages: false }, { type: 1 })\n */\n public editPermissionOverwrite(\n targetId: string,\n changes: PermissionOverwriteChanges,\n options?: { type?: 0 | 1; reason?: string },\n ): Promise<void> {\n if (!this.#context?.editPermissionOverwrite)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.editPermissionOverwrite(\n this.id,\n targetId,\n changes,\n options,\n );\n }\n\n public editParent(parentId: string | null): Promise<Channel> {\n return this.edit({ parent_id: parentId });\n }\n\n /** Deletes this channel. @param reason Audit-log reason. @returns A promise fulfilled when Discord confirms deletion. @throws {Error} If the channel is not attached to a client. */\n public delete(reason?: string): Promise<void> {\n if (!this.#context?.deleteChannel)\n throw new Error(\"This channel is not attached to a client.\");\n return this.#context.deleteChannel(this.id, reason);\n }\n\n /** Updates this channel using the same resource operation as edit. @param options Channel fields to change. @returns The updated channel. @throws {Error} If the channel is not attached to a client. */\n public update(options: Record<string, unknown>): Promise<Channel> {\n return this.edit(options);\n }\n\n /** What kind of channel this is: `\"text\"`, `\"voice\"`, `\"thread\"`, `\"forum\"`… (`\"unknown\"` for a type this version does not know). */\n public get kind(): ChannelKind | UnknownChannelKind {\n return channelKindOf(this.type);\n }\n\n /**\n * Whether this channel is one of `kinds`, narrowing its type to match.\n * @example if (channel.is(\"text\", \"announcement\")) await channel.send(\"hi\");\n */\n public is<K extends ChannelKind | UnknownChannelKind>(\n ...kinds: K[]\n ): this is ChannelOfKind<K> {\n return (kinds as string[]).includes(this.kind);\n }\n\n /**\n * Returns this channel typed as one of `kinds`.\n * @throws {TypeError} If it is a different kind.\n */\n public as<K extends ChannelKind | UnknownChannelKind>(\n ...kinds: K[]\n ): ChannelOfKind<K> {\n if (!this.is(...kinds))\n throw new TypeError(\n `Channel ${this.id} is a ${this.kind} channel, not ${kinds.join(\" or \")}.`,\n );\n return this;\n }\n\n /** Whether this is a thread (announcement, public or private). */\n public isThread(): boolean {\n return this.type === 10 || this.type === 11 || this.type === 12;\n }\n\n /** Whether messages can be sent in this channel (text, DM, announcement, voice, stage, threads). */\n public isTextBased(): boolean {\n return [0, 1, 2, 3, 5, 10, 11, 12, 13].includes(this.type);\n }\n\n /** Whether this is a voice or stage channel. */\n public isVoiceBased(): boolean {\n return this.type === 2 || this.type === 13;\n }\n\n /** Whether this is a direct-message channel (DM or group DM). */\n public isDMBased(): boolean {\n return this.type === 1 || this.type === 3;\n }\n\n /** Returns the Discord channel mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<#${this.id}>`;\n }\n}\n\n// ─── Guild ────────────────────────────────────────────────────────────────────\n\nexport class Guild extends BaseStructure {\n public name: string;\n public icon: string | null;\n public splash: string | null;\n public banner: string | null;\n public description: string | null;\n public preferredLocale: string;\n public ownerId?: string;\n public features: string[];\n public verificationLevel: number;\n public premiumTier: number;\n public premiumSubscriptionCount: number;\n public memberCount?: number;\n public approximateMemberCount?: number;\n public approximatePresenceCount?: number;\n public vanityUrlCode: string | null;\n public nsfwLevel: number;\n public discoverySplash: string | null;\n /** ID of the rules channel for Community guilds. */\n public rulesChannelId: string | null;\n /** ID of the system messages channel. */\n public systemChannelId: string | null;\n /** Bitfield of system channel flags. */\n public systemChannelFlags: number;\n /** Maximum number of members the guild can have. */\n public maxMembers: number;\n /** Required MFA level for administrators. */\n public mfaLevel: number;\n /** Explicit content filter level. */\n public explicitContentFilter: number;\n /** Default notification level for new members. */\n public defaultMessageNotifications: number;\n /** AFK voice channel, or null. */\n public afkChannelId: string | null;\n /** Seconds before a silent member is moved to the AFK channel. */\n public afkTimeout?: number;\n /** Whether the server widget is on. */\n public widgetEnabled: boolean;\n /** Channel the widget invites to, or null. */\n public widgetChannelId: string | null;\n /** Application that created the guild, if a bot did. */\n public applicationId: string | null;\n /** Channel for Discord's community updates, or null. */\n public publicUpdatesChannelId: string | null;\n /** Channel for safety alerts, or null. */\n public safetyAlertsChannelId: string | null;\n /** Maximum presences (null for the default limit). */\n public maxPresences: number | null;\n /** Maximum users in a video channel. */\n public maxVideoChannelUsers?: number;\n /** Whether the boost progress bar shows. */\n public premiumProgressBarEnabled: boolean;\n\n public constructor(data: import(\"@lunibee/types\").APIGuild) {\n super(data.id);\n if (!data.name) throw new TypeError(\"A Discord guild requires a name.\");\n this.name = data.name;\n this.icon = data.icon ?? null;\n this.splash = data.splash ?? null;\n this.banner = data.banner ?? null;\n this.description = data.description ?? null;\n this.preferredLocale = data.preferred_locale ?? \"en-US\";\n this.ownerId = data.owner_id;\n this.features = data.features ?? [];\n this.verificationLevel = data.verification_level ?? 0;\n this.premiumTier = data.premium_tier ?? 0;\n this.premiumSubscriptionCount = data.premium_subscription_count ?? 0;\n this.memberCount = data.member_count ?? data.approximate_member_count;\n this.approximateMemberCount = data.approximate_member_count;\n this.approximatePresenceCount = data.approximate_presence_count;\n this.vanityUrlCode = data.vanity_url_code ?? null;\n this.nsfwLevel = data.nsfw_level ?? 0;\n this.discoverySplash = data.discovery_splash ?? null;\n this.rulesChannelId = data.rules_channel_id ?? null;\n this.systemChannelId = data.system_channel_id ?? null;\n this.systemChannelFlags = data.system_channel_flags ?? 0;\n this.maxMembers = data.max_members ?? 0;\n this.mfaLevel = data.mfa_level ?? 0;\n this.explicitContentFilter = data.explicit_content_filter ?? 0;\n this.defaultMessageNotifications =\n data.default_message_notifications ?? 0;\n this.afkChannelId = data.afk_channel_id ?? null;\n this.afkTimeout = data.afk_timeout;\n this.widgetEnabled = data.widget_enabled ?? false;\n this.widgetChannelId = data.widget_channel_id ?? null;\n this.applicationId = data.application_id ?? null;\n this.publicUpdatesChannelId = data.public_updates_channel_id ?? null;\n this.safetyAlertsChannelId = data.safety_alerts_channel_id ?? null;\n this.maxPresences = data.max_presences ?? null;\n this.maxVideoChannelUsers = data.max_video_channel_users;\n this.premiumProgressBarEnabled =\n data.premium_progress_bar_enabled ?? false;\n }\n\n /** Returns the guild icon URL, or null if no icon is set. */\n public iconURL(options: ImageURLOptions = {}): string | null {\n if (!this.icon) return null;\n return cdnURL(`/icons/${this.id}`, this.icon, options);\n }\n\n /** Returns the guild splash URL, or null if none. */\n public splashURL(options: ImageURLOptions = {}): string | null {\n if (!this.splash) return null;\n return cdnURL(`/splashes/${this.id}`, this.splash, options);\n }\n\n /** Returns the guild banner URL, or null if none. */\n public bannerURL(options: ImageURLOptions = {}): string | null {\n if (!this.banner) return null;\n return cdnURL(`/banners/${this.id}`, this.banner, options);\n }\n\n /** Returns the guild discovery splash URL, or null if none. */\n public discoverySplashURL(options: ImageURLOptions = {}): string | null {\n if (!this.discoverySplash) return null;\n return cdnURL(\n `/discovery-splashes/${this.id}`,\n this.discoverySplash,\n options,\n );\n }\n\n /** Returns a widget image URL for the guild.\n * @param style Widget style: shield (default), banner1, banner2, banner3, banner4.\n */\n public widgetImageURL(\n style:\n \"shield\" | \"banner1\" | \"banner2\" | \"banner3\" | \"banner4\" = \"shield\",\n ): string {\n return `https://discord.com/api/guilds/${this.id}/widget.png?style=${style}`;\n }\n\n /** Whether the guild has a given feature flag. @param feature Feature string, e.g. \"COMMUNITY\". */\n public hasFeature(feature: string): boolean {\n return this.features.includes(feature);\n }\n\n /** Whether the guild is a Community server. */\n public get isCommunity(): boolean {\n return this.hasFeature(\"COMMUNITY\");\n }\n\n /** Whether the guild is an official Discord Partner. */\n public get isPartnered(): boolean {\n return this.hasFeature(\"PARTNERED\");\n }\n\n /** Whether the guild is verified by Discord. */\n public get isVerified(): boolean {\n return this.hasFeature(\"VERIFIED\");\n }\n\n /** Whether the guild has any active boost subscriptions. */\n public get isBoosted(): boolean {\n return this.premiumSubscriptionCount > 0;\n }\n\n /** Alias for premiumTier — the guild's current Nitro boost level (0–3). */\n public get boostLevel(): number {\n return this.premiumTier;\n }\n\n /** Whether the guild has a vanity URL. */\n public get hasVanityUrl(): boolean {\n return this.vanityUrlCode !== null;\n }\n\n /** Returns the guild's vanity invite URL, or null if none. */\n public get vanityURL(): string | null {\n return this.vanityUrlCode\n ? `https://discord.gg/${this.vanityUrlCode}`\n : null;\n }\n\n /** Returns a human-readable string representation. */\n public override toString(): string {\n return this.name;\n }\n}\n",
9
+ "/** Permission overwrite target types. */\nexport enum PermissionOverwriteEnum {\n Role = 0,\n Member = 1,\n}\n\n/** Lunibee idiomatic camelCase permission bitflags. */\nexport const Permission = {\n createInstantInvite: 1n << 0n,\n kickMembers: 1n << 1n,\n banMembers: 1n << 2n,\n administrator: 1n << 3n,\n manageChannels: 1n << 4n,\n manageGuild: 1n << 5n,\n addReactions: 1n << 6n,\n viewAuditLog: 1n << 7n,\n prioritySpeaker: 1n << 8n,\n stream: 1n << 9n,\n viewChannel: 1n << 10n,\n sendMessages: 1n << 11n,\n sendTTSMessages: 1n << 12n,\n manageMessages: 1n << 13n,\n embedLinks: 1n << 14n,\n attachFiles: 1n << 15n,\n readMessageHistory: 1n << 16n,\n mentionEveryone: 1n << 17n,\n useExternalEmojis: 1n << 18n,\n viewGuildInsights: 1n << 19n,\n connect: 1n << 20n,\n speak: 1n << 21n,\n muteMembers: 1n << 22n,\n deafenMembers: 1n << 23n,\n moveMembers: 1n << 24n,\n useVAD: 1n << 25n,\n changeNickname: 1n << 26n,\n manageNicknames: 1n << 27n,\n manageRoles: 1n << 28n,\n manageWebhooks: 1n << 29n,\n manageGuildExpressions: 1n << 30n,\n useApplicationCommands: 1n << 31n,\n requestToSpeak: 1n << 32n,\n manageEvents: 1n << 33n,\n manageThreads: 1n << 34n,\n createPublicThreads: 1n << 35n,\n createPrivateThreads: 1n << 36n,\n useExternalStickers: 1n << 37n,\n sendMessagesInThreads: 1n << 38n,\n useEmbeddedActivities: 1n << 39n,\n moderateMembers: 1n << 40n,\n viewCreatorMonetizationAnalytics: 1n << 41n,\n useSoundboard: 1n << 42n,\n createGuildExpressions: 1n << 43n,\n createEvents: 1n << 44n,\n useExternalSounds: 1n << 45n,\n sendVoiceMessages: 1n << 46n,\n setVoiceChannelStatus: 1n << 48n,\n sendPolls: 1n << 49n,\n useExternalApps: 1n << 50n,\n pinMessages: 1n << 51n,\n bypassSlowmode: 1n << 52n,\n} as const;\n\n/** Canonical PascalCase permission constants. */\nexport const Permissions = {\n CreateInstantInvite: 1n << 0n,\n KickMembers: 1n << 1n,\n BanMembers: 1n << 2n,\n Administrator: 1n << 3n,\n ManageChannels: 1n << 4n,\n ManageGuild: 1n << 5n,\n AddReactions: 1n << 6n,\n ViewAuditLog: 1n << 7n,\n PrioritySpeaker: 1n << 8n,\n Stream: 1n << 9n,\n ViewChannel: 1n << 10n,\n SendMessages: 1n << 11n,\n SendTTSMessages: 1n << 12n,\n ManageMessages: 1n << 13n,\n EmbedLinks: 1n << 14n,\n AttachFiles: 1n << 15n,\n ReadMessageHistory: 1n << 16n,\n MentionEveryone: 1n << 17n,\n UseExternalEmojis: 1n << 18n,\n ViewGuildInsights: 1n << 19n,\n Connect: 1n << 20n,\n Speak: 1n << 21n,\n MuteMembers: 1n << 22n,\n DeafenMembers: 1n << 23n,\n MoveMembers: 1n << 24n,\n UseVAD: 1n << 25n,\n ChangeNickname: 1n << 26n,\n ManageNicknames: 1n << 27n,\n ManageRoles: 1n << 28n,\n ManageWebhooks: 1n << 29n,\n ManageGuildExpressions: 1n << 30n,\n UseApplicationCommands: 1n << 31n,\n RequestToSpeak: 1n << 32n,\n ManageEvents: 1n << 33n,\n ManageThreads: 1n << 34n,\n CreatePublicThreads: 1n << 35n,\n CreatePrivateThreads: 1n << 36n,\n UseExternalStickers: 1n << 37n,\n SendMessagesInThreads: 1n << 38n,\n UseEmbeddedActivities: 1n << 39n,\n ModerateMembers: 1n << 40n,\n ViewCreatorMonetizationAnalytics: 1n << 41n,\n UseSoundboard: 1n << 42n,\n CreateGuildExpressions: 1n << 43n,\n CreateEvents: 1n << 44n,\n UseExternalSounds: 1n << 45n,\n SendVoiceMessages: 1n << 46n,\n SetVoiceChannelStatus: 1n << 48n,\n SendPolls: 1n << 49n,\n UseExternalApps: 1n << 50n,\n PinMessages: 1n << 51n,\n BypassSlowmode: 1n << 52n,\n} as const;\n\n/**\n * Permission flag bits with **bigint** values matching Discord's permission bit\n * positions. Mirrors discord.js's `PermissionFlagsBits`, so bitwise composition\n * (`Flags.A | Flags.B`) OR-s the bits instead of concatenating strings.\n *\n * The same object as {@link Permissions}, under the discord.js name. It is a\n * `const` object rather than a TS `enum` because enums cannot hold bigint\n * members; the same-named union type below preserves usage as a type.\n */\nexport const PermissionFlagsBits = Permissions;\n\n/** Union of {@link PermissionFlagsBits} values (all bigint). */\nexport type PermissionFlagsBits =\n (typeof PermissionFlagsBits)[keyof typeof PermissionFlagsBits];\n\nexport type PermissionName =\n | keyof typeof Permission\n | keyof typeof Permissions\n | keyof typeof PermissionFlagsBits;\n\nexport type PermissionResolvable =\n | bigint\n | number\n | string\n | PermissionName\n | PermissionFlagsBits\n | PermissionSet\n | PermissionResolvable[];\n\n/** Immutable permission bitfield with direct boolean getters. */\nexport class PermissionSet {\n /** Permission bitfield. */\n public readonly bitfield: bigint;\n\n /** Creates a permission set. @param value Initial permission bitfield or array of permissions. @throws {RangeError} If the value is negative. @throws {TypeError} If the value is not a valid integer. */\n public constructor(value: PermissionResolvable = 0n) {\n try {\n if (Array.isArray(value)) {\n let bit = 0n;\n for (const item of value) {\n bit |= this.#resolve(item);\n }\n this.bitfield = bit;\n } else if (value instanceof PermissionSet) {\n this.bitfield = value.bitfield;\n } else {\n const bitfield = this.#resolve(value);\n if (bitfield < 0n)\n throw new RangeError(\n \"Permission bitfield cannot be negative.\",\n );\n this.bitfield = bitfield;\n }\n } catch (error) {\n if (error instanceof RangeError) throw error;\n throw new TypeError(\n \"Permission bitfield must be a valid non-negative integer.\",\n { cause: error },\n );\n }\n }\n\n // Direct camelCase boolean getters for instant checks (e.g. member.permissions.kickMembers)\n public get createInstantInvite(): boolean {\n return (\n (this.bitfield & Permission.createInstantInvite) ===\n Permission.createInstantInvite\n );\n }\n public get kickMembers(): boolean {\n return (\n (this.bitfield & Permission.kickMembers) === Permission.kickMembers\n );\n }\n public get banMembers(): boolean {\n return (\n (this.bitfield & Permission.banMembers) === Permission.banMembers\n );\n }\n public get administrator(): boolean {\n return (\n (this.bitfield & Permission.administrator) ===\n Permission.administrator\n );\n }\n public get manageChannels(): boolean {\n return (\n (this.bitfield & Permission.manageChannels) ===\n Permission.manageChannels\n );\n }\n public get manageGuild(): boolean {\n return (\n (this.bitfield & Permission.manageGuild) === Permission.manageGuild\n );\n }\n public get addReactions(): boolean {\n return (\n (this.bitfield & Permission.addReactions) ===\n Permission.addReactions\n );\n }\n public get viewAuditLog(): boolean {\n return (\n (this.bitfield & Permission.viewAuditLog) ===\n Permission.viewAuditLog\n );\n }\n public get prioritySpeaker(): boolean {\n return (\n (this.bitfield & Permission.prioritySpeaker) ===\n Permission.prioritySpeaker\n );\n }\n public get stream(): boolean {\n return (this.bitfield & Permission.stream) === Permission.stream;\n }\n public get viewChannel(): boolean {\n return (\n (this.bitfield & Permission.viewChannel) === Permission.viewChannel\n );\n }\n public get sendMessages(): boolean {\n return (\n (this.bitfield & Permission.sendMessages) ===\n Permission.sendMessages\n );\n }\n public get sendTTSMessages(): boolean {\n return (\n (this.bitfield & Permission.sendTTSMessages) ===\n Permission.sendTTSMessages\n );\n }\n public get manageMessages(): boolean {\n return (\n (this.bitfield & Permission.manageMessages) ===\n Permission.manageMessages\n );\n }\n public get embedLinks(): boolean {\n return (\n (this.bitfield & Permission.embedLinks) === Permission.embedLinks\n );\n }\n public get attachFiles(): boolean {\n return (\n (this.bitfield & Permission.attachFiles) === Permission.attachFiles\n );\n }\n public get readMessageHistory(): boolean {\n return (\n (this.bitfield & Permission.readMessageHistory) ===\n Permission.readMessageHistory\n );\n }\n public get mentionEveryone(): boolean {\n return (\n (this.bitfield & Permission.mentionEveryone) ===\n Permission.mentionEveryone\n );\n }\n public get useExternalEmojis(): boolean {\n return (\n (this.bitfield & Permission.useExternalEmojis) ===\n Permission.useExternalEmojis\n );\n }\n public get viewGuildInsights(): boolean {\n return (\n (this.bitfield & Permission.viewGuildInsights) ===\n Permission.viewGuildInsights\n );\n }\n public get connect(): boolean {\n return (this.bitfield & Permission.connect) === Permission.connect;\n }\n public get speak(): boolean {\n return (this.bitfield & Permission.speak) === Permission.speak;\n }\n public get muteMembers(): boolean {\n return (\n (this.bitfield & Permission.muteMembers) === Permission.muteMembers\n );\n }\n public get deafenMembers(): boolean {\n return (\n (this.bitfield & Permission.deafenMembers) ===\n Permission.deafenMembers\n );\n }\n public get moveMembers(): boolean {\n return (\n (this.bitfield & Permission.moveMembers) === Permission.moveMembers\n );\n }\n public get useVAD(): boolean {\n return (this.bitfield & Permission.useVAD) === Permission.useVAD;\n }\n public get changeNickname(): boolean {\n return (\n (this.bitfield & Permission.changeNickname) ===\n Permission.changeNickname\n );\n }\n public get manageNicknames(): boolean {\n return (\n (this.bitfield & Permission.manageNicknames) ===\n Permission.manageNicknames\n );\n }\n public get manageRoles(): boolean {\n return (\n (this.bitfield & Permission.manageRoles) === Permission.manageRoles\n );\n }\n public get manageWebhooks(): boolean {\n return (\n (this.bitfield & Permission.manageWebhooks) ===\n Permission.manageWebhooks\n );\n }\n public get manageGuildExpressions(): boolean {\n return (\n (this.bitfield & Permission.manageGuildExpressions) ===\n Permission.manageGuildExpressions\n );\n }\n public get useApplicationCommands(): boolean {\n return (\n (this.bitfield & Permission.useApplicationCommands) ===\n Permission.useApplicationCommands\n );\n }\n public get requestToSpeak(): boolean {\n return (\n (this.bitfield & Permission.requestToSpeak) ===\n Permission.requestToSpeak\n );\n }\n public get manageEvents(): boolean {\n return (\n (this.bitfield & Permission.manageEvents) ===\n Permission.manageEvents\n );\n }\n public get manageThreads(): boolean {\n return (\n (this.bitfield & Permission.manageThreads) ===\n Permission.manageThreads\n );\n }\n public get createPublicThreads(): boolean {\n return (\n (this.bitfield & Permission.createPublicThreads) ===\n Permission.createPublicThreads\n );\n }\n public get createPrivateThreads(): boolean {\n return (\n (this.bitfield & Permission.createPrivateThreads) ===\n Permission.createPrivateThreads\n );\n }\n public get useExternalStickers(): boolean {\n return (\n (this.bitfield & Permission.useExternalStickers) ===\n Permission.useExternalStickers\n );\n }\n public get sendMessagesInThreads(): boolean {\n return (\n (this.bitfield & Permission.sendMessagesInThreads) ===\n Permission.sendMessagesInThreads\n );\n }\n public get useEmbeddedActivities(): boolean {\n return (\n (this.bitfield & Permission.useEmbeddedActivities) ===\n Permission.useEmbeddedActivities\n );\n }\n public get moderateMembers(): boolean {\n return (\n (this.bitfield & Permission.moderateMembers) ===\n Permission.moderateMembers\n );\n }\n public get viewCreatorMonetizationAnalytics(): boolean {\n return (\n (this.bitfield & Permission.viewCreatorMonetizationAnalytics) ===\n Permission.viewCreatorMonetizationAnalytics\n );\n }\n public get useSoundboard(): boolean {\n return (\n (this.bitfield & Permission.useSoundboard) ===\n Permission.useSoundboard\n );\n }\n public get createGuildExpressions(): boolean {\n return (\n (this.bitfield & Permission.createGuildExpressions) ===\n Permission.createGuildExpressions\n );\n }\n public get createEvents(): boolean {\n return (\n (this.bitfield & Permission.createEvents) ===\n Permission.createEvents\n );\n }\n public get useExternalSounds(): boolean {\n return (\n (this.bitfield & Permission.useExternalSounds) ===\n Permission.useExternalSounds\n );\n }\n public get sendVoiceMessages(): boolean {\n return (\n (this.bitfield & Permission.sendVoiceMessages) ===\n Permission.sendVoiceMessages\n );\n }\n public get sendPolls(): boolean {\n return (this.bitfield & Permission.sendPolls) === Permission.sendPolls;\n }\n public get useExternalApps(): boolean {\n return (\n (this.bitfield & Permission.useExternalApps) ===\n Permission.useExternalApps\n );\n }\n\n /** Checks whether all supplied permissions are present (AND). @param permissions Permission names or raw bits. @returns True when every requested permission is present. */\n public has(...permissions: PermissionResolvable[]): boolean {\n if (permissions.length === 1) {\n const p = permissions[0]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n return (this.bitfield & bit) === bit;\n }\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n if ((this.bitfield & bit) !== bit) return false;\n }\n return true;\n }\n\n /** Checks whether any supplied permission is present (OR). @param permissions Permission names or raw bits. @returns True when at least one requested permission is present. */\n public any(...permissions: PermissionResolvable[]): boolean {\n if (permissions.length === 1) {\n const p = permissions[0]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n return (this.bitfield & bit) !== 0n;\n }\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n const bit = typeof p === \"bigint\" ? p : this.#resolve(p);\n if ((this.bitfield & bit) !== 0n) return true;\n }\n return false;\n }\n\n /** Returns the known permission names from `permissions` that this set lacks. @param permissions Permission names or raw bits. */\n public missing(...permissions: PermissionResolvable[]): PermissionName[] {\n const wanted = new PermissionSet(permissions);\n return wanted.toArray().filter((name) => !this.has(name));\n }\n\n /** Returns a new set with permissions added. @param permissions Permission names or raw bits. @returns A new permission set. */\n public add(...permissions: PermissionResolvable[]): PermissionSet {\n let bitfield = this.bitfield;\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n bitfield |= typeof p === \"bigint\" ? p : this.#resolve(p);\n }\n return new PermissionSet(bitfield);\n }\n\n /** Returns a new set with permissions removed. @param permissions Permission names or raw bits. @returns A new permission set. */\n public remove(...permissions: PermissionResolvable[]): PermissionSet {\n let bitfield = this.bitfield;\n for (let i = 0; i < permissions.length; i++) {\n const p = permissions[i]!;\n bitfield &= ~(typeof p === \"bigint\" ? p : this.#resolve(p));\n }\n return new PermissionSet(bitfield);\n }\n\n /** Checks equality with another permission set or raw bitfield. @param other Permission set or raw bitfield. @returns True when both values are equal. */\n public equals(other: PermissionSet | bigint | number | string): boolean {\n return (\n this.bitfield ===\n (other instanceof PermissionSet\n ? other.bitfield\n : new PermissionSet(other).bitfield)\n );\n }\n\n /** Returns the decimal permission representation. @returns Decimal permission bitfield. */\n public toString(): string {\n return this.bitfield.toString();\n }\n\n /** Returns known permission names contained in this set. @returns Names of all enabled known permissions. */\n public toArray(): PermissionName[] {\n return (Object.keys(Permission) as PermissionName[]).filter(\n (permission) => this.has(permission),\n );\n }\n\n /** Resolves a named permission, enum value, or raw bit. @param permission Permission name, enum value, or raw bit. @returns Numeric permission bit. */\n /** Names Discord has since renamed, still accepted when resolving a permission by name. */\n static readonly #renamed: Readonly<Record<string, string>> = {\n ManageEmojisAndStickers: \"ManageGuildExpressions\",\n ManageEmojis: \"ManageGuildExpressions\",\n UseSlashCommands: \"UseApplicationCommands\",\n };\n\n #resolve(permission: PermissionResolvable): bigint {\n if (typeof permission === \"bigint\") return permission;\n if (typeof permission === \"number\") return BigInt(permission);\n if (permission instanceof PermissionSet) return permission.bitfield;\n if (Array.isArray(permission)) {\n let bit = 0n;\n for (let i = 0; i < permission.length; i++)\n bit |= this.#resolve(permission[i]!);\n return bit;\n }\n if (typeof permission === \"string\") {\n const renamed = PermissionSet.#renamed[permission];\n if (renamed) return this.#resolve(renamed);\n if (permission in Permission)\n return (Permission as Record<string, bigint>)[permission]!;\n if (permission in Permissions)\n return (Permissions as Record<string, bigint>)[permission]!;\n if (permission in PermissionFlagsBits)\n return (PermissionFlagsBits as Record<string, bigint>)[\n permission\n ]!;\n const lower =\n permission.charAt(0).toLowerCase() + permission.slice(1);\n if (lower in Permission)\n return (Permission as Record<string, bigint>)[lower]!;\n return BigInt(permission);\n }\n return 0n;\n }\n}\n\n/** Permissions bitfield alias. */\nexport class PermissionsBitField extends PermissionSet {\n /** Permission flags bits enum. */\n public static readonly Flags = PermissionFlagsBits;\n /** Permission flags constants. */\n public static readonly All = Permission;\n\n /** Creates a permissions bitfield. @param value Initial permission bitfield or array of permissions. */\n public constructor(value: PermissionResolvable = 0n) {\n super(value);\n }\n}\n\n/** Every known permission bit. */\nconst ALL_PERMISSIONS = Object.values(Permission).reduce(\n (bits, bit) => bits | bit,\n 0n,\n);\n\n/** A role as needed for permission resolution. */\nexport interface PermissionRole {\n id: string;\n permissions: PermissionResolvable;\n}\n\n/** A channel permission overwrite (Discord's `permission_overwrites` entry). */\nexport interface PermissionOverwrite {\n id: string;\n type: PermissionOverwriteEnum | number;\n allow: PermissionResolvable;\n deny: PermissionResolvable;\n}\n\n/** Everything needed to resolve a member's permissions. */\nexport interface PermissionContext {\n guildId: string;\n /** Guild owner ID; the owner has every permission. */\n ownerId?: string;\n memberId: string;\n memberRoleIds: readonly string[];\n /** Guild roles, including `@everyone` (whose ID is the guild ID). */\n roles: readonly PermissionRole[];\n /** Channel overwrites; omit for guild-level permissions. */\n overwrites?: readonly PermissionOverwrite[];\n /** When the member's timeout ends; while it is in the future the member keeps only View Channel and Read Message History. */\n timedOutUntil?: Date | number | null;\n}\n\nconst bits = (value: PermissionResolvable): bigint =>\n new PermissionSet(value).bitfield;\n\n/**\n * Resolves a member's effective permissions the way Discord does: base\n * permissions from `@everyone` and the member's roles (owner and\n * administrator get everything), then the channel's `@everyone` overwrite,\n * the combined role overwrites, and finally the member overwrite. A member\n * whose timeout has not ended keeps only View Channel and Read Message History.\n */\nexport function computePermissions(context: PermissionContext): PermissionSet {\n if (context.ownerId !== undefined && context.ownerId === context.memberId)\n return new PermissionSet(ALL_PERMISSIONS);\n const roles = new Map(context.roles.map((role) => [role.id, role]));\n let base = bits(roles.get(context.guildId)?.permissions ?? 0n);\n for (const id of context.memberRoleIds)\n base |= bits(roles.get(id)?.permissions ?? 0n);\n if (base & Permission.administrator)\n return new PermissionSet(ALL_PERMISSIONS);\n const overwrites = context.overwrites ?? [];\n const everyone = overwrites.find((o) => o.id === context.guildId);\n if (everyone) base = (base & ~bits(everyone.deny)) | bits(everyone.allow);\n const memberRoles = new Set(context.memberRoleIds);\n let allow = 0n;\n let deny = 0n;\n for (const overwrite of overwrites)\n if (\n overwrite.type === PermissionOverwriteEnum.Role &&\n overwrite.id !== context.guildId &&\n memberRoles.has(overwrite.id)\n ) {\n allow |= bits(overwrite.allow);\n deny |= bits(overwrite.deny);\n }\n base = (base & ~deny) | allow;\n const member = overwrites.find(\n (o) =>\n o.type === PermissionOverwriteEnum.Member &&\n o.id === context.memberId,\n );\n if (member) base = (base & ~bits(member.deny)) | bits(member.allow);\n // Discord: timed-out members lose every permission except View Channel and\n // Read Message History. Owners and administrators returned above.\n const until =\n context.timedOutUntil instanceof Date\n ? context.timedOutUntil.getTime()\n : (context.timedOutUntil ?? 0);\n if (until > Date.now())\n base &= Permission.viewChannel | Permission.readMessageHistory;\n return new PermissionSet(base);\n}\n",
10
+ "import { ButtonType, ComponentEnum } from \"@lunibee/types\";\nexport { ButtonType, ComponentEnum };\n\nexport const TextInputType = { Short: 1, Paragraph: 2 } as const;\n/** One {@link TextInputType} value, usable as a type. */\nexport type TextInputType = (typeof TextInputType)[keyof typeof TextInputType];\nexport interface APIComponentEmoji {\n id?: string | null;\n name?: string | null;\n animated?: boolean;\n}\nexport interface APIButtonComponent {\n type: typeof ComponentEnum.Button;\n style: 1 | 2 | 3 | 4 | 5 | 6;\n custom_id?: string;\n label?: string;\n emoji?: APIComponentEmoji;\n url?: string;\n /** SKU for premium (style 6) buttons. */\n sku_id?: string;\n disabled?: boolean;\n}\nexport interface APISelectOption {\n label: string;\n value: string;\n description?: string;\n emoji?: APIComponentEmoji;\n default?: boolean;\n}\nexport interface APIStringSelectComponent {\n type: typeof ComponentEnum.StringSelect;\n custom_id?: string;\n placeholder?: string;\n min_values?: number;\n max_values?: number;\n required?: boolean;\n disabled?: boolean;\n options?: APISelectOption[];\n}\nexport interface APIEntitySelectComponent {\n type:\n | typeof ComponentEnum.UserSelect\n | typeof ComponentEnum.RoleSelect\n | typeof ComponentEnum.MentionableSelect\n | typeof ComponentEnum.ChannelSelect;\n custom_id?: string;\n placeholder?: string;\n min_values?: number;\n max_values?: number;\n required?: boolean;\n disabled?: boolean;\n default_values?: APISelectDefaultValue[];\n}\nexport interface APITextInputComponent {\n type: typeof ComponentEnum.TextInput;\n style: typeof TextInputType.Short | typeof TextInputType.Paragraph;\n custom_id?: string;\n label?: string;\n placeholder?: string;\n min_length?: number;\n max_length?: number;\n required?: boolean;\n value?: string;\n}\nexport interface APIModalComponent {\n type: 9;\n custom_id: string;\n title: string;\n components: APIActionRowComponent[];\n}\nexport type APIActionRowChild =\n | APIButtonComponent\n | APIStringSelectComponent\n | APIEntitySelectComponent\n | APITextInputComponent;\nexport interface APIActionRowComponent {\n type: typeof ComponentEnum.ActionRow;\n components: APIActionRowChild[];\n}\nexport interface APISectionComponent {\n type: typeof ComponentEnum.Section;\n components?: APIComponent[]; // text displays\n accessory?: APIComponent; // buttons, thumbnails, etc.\n}\nexport interface APITextDisplayComponent {\n type: typeof ComponentEnum.TextDisplay;\n content: string;\n}\nexport interface APIMediaGalleryComponent {\n type: typeof ComponentEnum.MediaGallery;\n items: { media: { url: string; description?: string } }[];\n}\n/** Default values accepted by an auto-populated entity select. */\nexport interface APISelectDefaultValue {\n id: string;\n type: \"user\" | \"role\" | \"channel\";\n}\nexport interface APIFileComponent {\n type: typeof ComponentEnum.File;\n file: { url: string };\n spoiler?: boolean;\n}\nexport interface APISeparatorComponent {\n type: typeof ComponentEnum.Separator;\n spacing?: 1 | 2;\n divider?: boolean;\n}\nexport interface APIThumbnailComponent {\n type: typeof ComponentEnum.Thumbnail;\n url: string;\n proxy_url?: string;\n width?: number;\n height?: number;\n description?: string;\n spoiler?: boolean;\n}\nexport interface APIContentInventoryEntryComponent {\n type: typeof ComponentEnum.ContentInventoryEntry;\n id: string;\n}\nexport interface APIContainerComponent {\n type: typeof ComponentEnum.Container;\n components: APIComponent[];\n accent_color?: number;\n spoiler?: boolean;\n}\nexport type APIComponent =\n | APIActionRowComponent\n | APIButtonComponent\n | APIStringSelectComponent\n | APIEntitySelectComponent\n | APITextInputComponent\n | APISectionComponent\n | APITextDisplayComponent\n | APIThumbnailComponent\n | APIMediaGalleryComponent\n | APIFileComponent\n | APISeparatorComponent\n | APIContentInventoryEntryComponent\n | APIContainerComponent;\n\nexport class CreateActionRow<\n T extends { toJSON(): APIActionRowChild } = { toJSON(): APIActionRowChild },\n> {\n readonly #components: T[] = [];\n public addComponents(...components: T[]): this {\n if (!components.length)\n throw new TypeError(\"At least one component is required.\");\n if (this.#components.length + components.length > 5)\n throw new RangeError(\n \"An action row cannot contain more than 5 components.\",\n );\n this.#components.push(...components);\n return this;\n }\n public clearComponents(): this {\n this.#components.length = 0;\n return this;\n }\n public toJSON(): APIActionRowComponent {\n const components = this.#components.map((component) =>\n component.toJSON(),\n );\n if (components.length === 0)\n throw new RangeError(\"An action row needs at least one component.\");\n const types = components.map((component) => component.type);\n if (\n types.some((type) => type !== ComponentEnum.Button) &&\n components.length > 1\n )\n throw new RangeError(\n \"A select menu or text input must be alone in its action row.\",\n );\n return { type: ComponentEnum.ActionRow, components };\n }\n}\n/** Setters shared by string and entity select menus. */\nexport class CreateSelectMenu {\n readonly #select: APIStringSelectComponent | APIEntitySelectComponent;\n protected constructor(\n data: APIStringSelectComponent | APIEntitySelectComponent,\n ) {\n this.#select = data;\n }\n public setCustomId(value: string): this {\n validateText(value, 100, \"Component custom ID\");\n this.#select.custom_id = value;\n return this;\n }\n public setPlaceholder(value: string): this {\n validateText(value, 150, \"Component placeholder\");\n this.#select.placeholder = value;\n return this;\n }\n public setMinValues(value: number): this {\n validateCount(value, \"min_values\", 0);\n this.#select.min_values = value;\n return this;\n }\n public setMaxValues(value: number): this {\n validateCount(value, \"max_values\", 1);\n this.#select.max_values = value;\n return this;\n }\n public setRequired(value = true): this {\n this.#select.required = value;\n return this;\n }\n public setDisabled(value = true): this {\n this.#select.disabled = value;\n return this;\n }\n}\nexport class CreateStringSelect extends CreateSelectMenu {\n readonly #data: APIStringSelectComponent;\n public constructor() {\n const data: APIStringSelectComponent = {\n type: ComponentEnum.StringSelect,\n };\n super(data);\n this.#data = data;\n }\n public addOptions(...options: APISelectOption[]): this {\n if (!options.length)\n throw new TypeError(\"At least one select option is required.\");\n const current = this.#data.options ?? [];\n if (current.length + options.length > 25)\n throw new RangeError(\n \"A string select cannot contain more than 25 options.\",\n );\n for (const option of options) {\n validateText(option.label, 100, \"Select option label\");\n validateText(option.value, 100, \"Select option value\");\n if (option.description)\n validateText(\n option.description,\n 100,\n \"Select option description\",\n );\n }\n this.#data.options = [\n ...current,\n ...options.map((option) => ({ ...option })),\n ];\n return this;\n }\n public toJSON(): APIStringSelectComponent {\n assertSelect(this.#data);\n const count = this.#data.options?.length ?? 0;\n if (count === 0)\n throw new RangeError(\"A string select needs at least one option.\");\n if ((this.#data.max_values ?? 1) > count)\n throw new RangeError(\n \"max_values cannot exceed the number of options.\",\n );\n return structuredClone(this.#data);\n }\n}\nexport class CreateButton {\n readonly #data: APIButtonComponent = {\n type: ComponentEnum.Button,\n style: ButtonType.Secondary,\n };\n /** Sets the style and drops fields that style cannot carry. */\n public setStyle(style: APIButtonComponent[\"style\"]): this {\n const data = this.#data;\n data.style = style;\n if (style === ButtonType.Link) {\n delete data.custom_id;\n delete data.sku_id;\n } else if (style === ButtonType.Premium) {\n delete data.custom_id;\n delete data.url;\n delete data.label;\n delete data.emoji;\n } else {\n delete data.url;\n delete data.sku_id;\n }\n return this;\n }\n public setCustomId(value: string): this {\n validateText(value, 100, \"Button custom ID\");\n if (this.#data.style === ButtonType.Link)\n throw new TypeError(\"Link buttons cannot use custom IDs.\");\n this.#data.custom_id = value;\n return this;\n }\n public setLabel(value: string): this {\n validateText(value, 80, \"Button label\");\n this.#data.label = value;\n return this;\n }\n public setURL(value: string): this {\n validateText(value, 512, \"Button URL\");\n let url: URL;\n try {\n url = new URL(value);\n } catch (error) {\n throw new TypeError(\"Button URL must be a valid URL.\", {\n cause: error,\n });\n }\n this.setStyle(ButtonType.Link);\n this.#data.url = url.toString();\n return this;\n }\n /** Makes this a premium (purchase) button for a SKU. Premium buttons carry no label, emoji, custom ID or URL. */\n public setSKUId(skuId: string): this {\n validateText(skuId, 20, \"Button SKU ID\");\n this.setStyle(ButtonType.Premium);\n this.#data.sku_id = skuId;\n return this;\n }\n public setEmoji(emoji: APIComponentEmoji | string): this {\n this.#data.emoji =\n typeof emoji === \"string\" ? { name: emoji } : { ...emoji };\n return this;\n }\n public setDisabled(value = true): this {\n this.#data.disabled = value;\n return this;\n }\n public toJSON(): APIButtonComponent {\n const data = this.#data;\n if (data.style === ButtonType.Link) {\n if (!data.url) throw new TypeError(\"Link buttons require a URL.\");\n if (data.custom_id || data.sku_id)\n throw new TypeError(\n \"Link buttons cannot have a custom ID or SKU ID.\",\n );\n } else if (data.style === ButtonType.Premium) {\n if (!data.sku_id)\n throw new TypeError(\"Premium buttons require a SKU ID.\");\n if (data.custom_id || data.url || data.label || data.emoji)\n throw new TypeError(\n \"Premium buttons cannot have a custom ID, URL, label or emoji.\",\n );\n } else {\n if (!data.custom_id)\n throw new TypeError(\"Non-link buttons require a custom ID.\");\n if (data.url || data.sku_id)\n throw new TypeError(\n \"Only link buttons have a URL and only premium buttons have a SKU ID.\",\n );\n }\n if (data.style !== ButtonType.Premium && !data.label && !data.emoji)\n throw new TypeError(\"Buttons require a label or an emoji.\");\n return structuredClone(data);\n }\n}\nexport class CreateEntitySelect extends CreateSelectMenu {\n readonly #data: APIEntitySelectComponent;\n public constructor(\n type:\n | typeof ComponentEnum.UserSelect\n | typeof ComponentEnum.RoleSelect\n | typeof ComponentEnum.MentionableSelect\n | typeof ComponentEnum.ChannelSelect,\n ) {\n if (\n type !== ComponentEnum.UserSelect &&\n type !== ComponentEnum.RoleSelect &&\n type !== ComponentEnum.MentionableSelect &&\n type !== ComponentEnum.ChannelSelect\n )\n throw new TypeError(\"Invalid select component type.\");\n const data: APIEntitySelectComponent = { type };\n super(data);\n this.#data = data;\n }\n public setDefaultValues(...values: APISelectDefaultValue[]): this {\n this.#data.default_values = values.map((value) => ({ ...value }));\n return this;\n }\n public toJSON(): APIEntitySelectComponent {\n assertSelect(this.#data);\n return structuredClone(this.#data);\n }\n}\nexport class CreateModal {\n readonly #components: Array<{ toJSON(): APIActionRowComponent }> = [];\n #custom_id?: string;\n #title?: string;\n public setCustomId(value: string): this {\n validateText(value, 100, \"Modal custom ID\");\n this.#custom_id = value;\n return this;\n }\n public setTitle(value: string): this {\n validateText(value, 45, \"Modal title\");\n this.#title = value;\n return this;\n }\n public addComponents(\n ...components: Array<{ toJSON(): APIActionRowComponent }>\n ): this {\n if (!components.length)\n throw new TypeError(\"At least one modal component is required.\");\n if (this.#components.length + components.length > 5)\n throw new RangeError(\n \"A modal cannot contain more than 5 action rows.\",\n );\n this.#components.push(...components);\n return this;\n }\n /** Adds text inputs, each in its own action row (Discord's modal layout). @param inputs Text inputs, at most 5 per modal. */\n public addTextInputs(...inputs: CreateTextInput[]): this {\n return this.addComponents(\n ...inputs.map((input) =>\n new CreateActionRow<CreateTextInput>().addComponents(input),\n ),\n );\n }\n public toJSON(): APIModalComponent {\n if (!this.#custom_id || !this.#title)\n throw new TypeError(\"Modals require a custom ID and a title.\");\n if (this.#components.length === 0)\n throw new RangeError(\"Modals require at least one component.\");\n return {\n type: 9,\n custom_id: this.#custom_id,\n title: this.#title,\n components: this.#components.map((component) => component.toJSON()),\n };\n }\n}\nexport class CreateTextInput {\n readonly #data: APITextInputComponent = {\n type: ComponentEnum.TextInput,\n style: TextInputType.Short,\n };\n public setStyle(style: APITextInputComponent[\"style\"]): this {\n this.#data.style = style;\n return this;\n }\n public setCustomId(value: string): this {\n validateText(value, 100, \"Text input custom ID\");\n this.#data.custom_id = value;\n return this;\n }\n public setLabel(value: string): this {\n validateText(value, 45, \"Text input label\");\n this.#data.label = value;\n return this;\n }\n public setPlaceholder(value: string): this {\n validateText(value, 100, \"Text input placeholder\");\n this.#data.placeholder = value;\n return this;\n }\n public setMinLength(value: number): this {\n validateLength(value, \"min_length\", 4000);\n this.#data.min_length = value;\n return this;\n }\n public setMaxLength(value: number): this {\n validateLength(value, \"max_length\", 4000);\n this.#data.max_length = value;\n return this;\n }\n public setRequired(value = true): this {\n this.#data.required = value;\n return this;\n }\n public setValue(value: string): this {\n validateText(value, 4000, \"Text input value\");\n this.#data.value = value;\n return this;\n }\n public toJSON(): APITextInputComponent {\n const data = this.#data;\n if (!data.custom_id)\n throw new TypeError(\"Text inputs require a custom ID.\");\n if (\n data.min_length !== undefined &&\n data.max_length !== undefined &&\n data.min_length > data.max_length\n )\n throw new RangeError(\"min_length cannot exceed max_length.\");\n return structuredClone(data);\n }\n}\n\nexport class CreateContainer {\n readonly #components: { toJSON(): APIComponent }[] = [];\n #accentColor?: number;\n #spoiler?: boolean;\n public addComponents(...components: { toJSON(): APIComponent }[]): this {\n if (!components.length)\n throw new TypeError(\"At least one component is required.\");\n this.#components.push(...components);\n return this;\n }\n public setAccentColor(color: number): this {\n if (!Number.isInteger(color) || color < 0 || color > 0xffffff) {\n throw new RangeError(\n \"Accent color must be an integer between 0 and 16777215 (0xFFFFFF).\",\n );\n }\n this.#accentColor = color;\n return this;\n }\n /** Marks the whole container as a spoiler (blurred until clicked). */\n public setSpoiler(spoiler = true): this {\n this.#spoiler = spoiler;\n return this;\n }\n public toJSON(): APIContainerComponent {\n const data: APIContainerComponent = {\n type: ComponentEnum.Container,\n components: this.#components.map((c) => c.toJSON()),\n };\n if (this.#accentColor !== undefined)\n data.accent_color = this.#accentColor;\n if (this.#spoiler !== undefined) data.spoiler = this.#spoiler;\n return data;\n }\n}\n\nexport class CreateSection {\n readonly #components: { toJSON(): APIComponent }[] = [];\n #accessory?: { toJSON(): APIComponent };\n public addComponents(...components: { toJSON(): APIComponent }[]): this {\n if (!components.length)\n throw new TypeError(\"At least one component is required.\");\n this.#components.push(...components);\n return this;\n }\n public setAccessory(accessory: { toJSON(): APIComponent }): this {\n this.#accessory = accessory;\n return this;\n }\n public toJSON(): APISectionComponent {\n return {\n type: ComponentEnum.Section,\n components: this.#components.length\n ? this.#components.map((c) => c.toJSON())\n : undefined,\n accessory: this.#accessory?.toJSON(),\n };\n }\n}\n\nexport class CreateTextDisplay {\n #content = \"\";\n public setContent(content: string): this {\n validateText(content, 4000, \"Text display content\");\n this.#content = content;\n return this;\n }\n public toJSON(): APITextDisplayComponent {\n return {\n type: ComponentEnum.TextDisplay,\n content: this.#content,\n };\n }\n}\n\nexport class CreateMediaGallery {\n readonly #items: { media: { url: string; description?: string } }[] = [];\n public addItems(...items: { url: string; description?: string }[]): this {\n if (!items.length) {\n throw new TypeError(\"At least one media gallery item is required.\");\n }\n if (this.#items.length + items.length > 10) {\n throw new RangeError(\n \"MediaGallery can only contain up to 10 items.\",\n );\n }\n this.#items.push(...items.map((item) => ({ media: item })));\n return this;\n }\n public toJSON(): APIMediaGalleryComponent {\n return {\n type: ComponentEnum.MediaGallery,\n items: structuredClone(this.#items),\n };\n }\n}\n\nexport class CreateFileComponent {\n #url = \"\";\n #spoiler?: boolean;\n public setUrl(url: string): this {\n validateText(url, 2048, \"File component URL\");\n this.#url = url;\n return this;\n }\n public setSpoiler(spoiler = true): this {\n this.#spoiler = spoiler;\n return this;\n }\n public toJSON(): APIFileComponent {\n if (!this.#url) throw new Error(\"File component must have a URL.\");\n const data: APIFileComponent = {\n type: ComponentEnum.File,\n file: { url: this.#url },\n };\n if (this.#spoiler !== undefined) data.spoiler = this.#spoiler;\n return data;\n }\n}\n\nexport class CreateSeparator {\n #spacing?: 1 | 2;\n #divider?: boolean;\n public setSpacing(spacing: 1 | 2): this {\n this.#spacing = spacing;\n return this;\n }\n public setDivider(divider = true): this {\n this.#divider = divider;\n return this;\n }\n public toJSON(): APISeparatorComponent {\n const data: APISeparatorComponent = {\n type: ComponentEnum.Separator,\n };\n if (this.#spacing !== undefined) data.spacing = this.#spacing;\n if (this.#divider !== undefined) data.divider = this.#divider;\n return data;\n }\n}\n\nexport class CreateThumbnail {\n #url = \"\";\n #description?: string;\n #spoiler?: boolean;\n public setUrl(url: string): this {\n validateText(url, 2048, \"Thumbnail URL\");\n this.#url = url;\n return this;\n }\n /** Sets the thumbnail's alt-text description. */\n public setDescription(description: string): this {\n validateText(description, 1024, \"Thumbnail description\");\n this.#description = description;\n return this;\n }\n /** Marks the thumbnail as a spoiler (blurred until clicked). */\n public setSpoiler(spoiler = true): this {\n this.#spoiler = spoiler;\n return this;\n }\n public toJSON(): APIThumbnailComponent {\n const data: APIThumbnailComponent = {\n type: ComponentEnum.Thumbnail,\n url: this.#url,\n };\n if (this.#description !== undefined)\n data.description = this.#description;\n if (this.#spoiler !== undefined) data.spoiler = this.#spoiler;\n return data;\n }\n}\n\nexport class CreateContentInventoryEntry {\n #id = \"\";\n public setId(id: string): this {\n validateText(id, 100, \"Content inventory entry ID\");\n this.#id = id;\n return this;\n }\n public toJSON(): APIContentInventoryEntryComponent {\n return {\n type: ComponentEnum.ContentInventoryEntry,\n id: this.#id,\n };\n }\n}\n\nfunction validateText(value: string, max: number, field: string): void {\n if (typeof value !== \"string\")\n throw new TypeError(`${field} must be a string.`);\n if (!value.trim())\n throw new RangeError(`${field} must be a non-empty string.`);\n if (value.length > max)\n throw new RangeError(`${field} cannot exceed ${max} characters.`);\n}\nfunction validateCount(\n value: number,\n field: string,\n min: number,\n max = 25,\n): void {\n if (!Number.isInteger(value) || value < min || value > max)\n throw new RangeError(\n `${field} must be an integer between ${min} and ${max}.`,\n );\n}\nfunction validateLength(value: number, field: string, max = 4000): void {\n if (!Number.isInteger(value) || value < 0 || value > max)\n throw new RangeError(\n `${field} must be an integer between 0 and ${max}.`,\n );\n}\n\n/** Discord.js-familiar alias for {@link CreateStringSelect}. */\nexport { CreateStringSelect as CreateStringSelectMenu };\n/** User select menu builder (Discord.js-familiar). */\nexport class CreateUserSelectMenu extends CreateEntitySelect {\n public constructor() {\n super(ComponentEnum.UserSelect);\n }\n}\n/** Role select menu builder (Discord.js-familiar). */\nexport class CreateRoleSelectMenu extends CreateEntitySelect {\n public constructor() {\n super(ComponentEnum.RoleSelect);\n }\n}\n/** Mentionable select menu builder (Discord.js-familiar). */\nexport class CreateMentionableSelectMenu extends CreateEntitySelect {\n public constructor() {\n super(ComponentEnum.MentionableSelect);\n }\n}\n/** Channel select menu builder (Discord.js-familiar). */\nexport class CreateChannelSelectMenu extends CreateEntitySelect {\n public constructor() {\n super(ComponentEnum.ChannelSelect);\n }\n}\n\n/** Checks the fields every select menu needs. */\nfunction assertSelect(data: {\n custom_id?: string;\n min_values?: number;\n max_values?: number;\n}): void {\n if (!data.custom_id)\n throw new TypeError(\"Select menus require a custom ID.\");\n if ((data.min_values ?? 1) > (data.max_values ?? 1))\n throw new RangeError(\"min_values cannot exceed max_values.\");\n}\n\n/** Discord's flag for a message laid out with Components V2 (containers, text displays...). */\nconst IS_COMPONENTS_V2 = 1 << 15;\n\n/**\n * A message payload laid out with Components V2: the components, and the flag\n * Discord requires for them. A V2 message cannot also carry `content` or `embeds`.\n * @param components Top-level components (containers, sections, text displays, action rows...).\n * @param options Extra message fields, such as `allowed_mentions` or `ephemeral`; `flags` are combined.\n * @example channel.send(componentsV2Message(new CreateContainer().addComponents(new CreateTextDisplay().setContent(\"Hi\"))))\n */\nexport function componentsV2Message<\n T extends Record<string, unknown> = Record<string, never>,\n>(\n components: { toJSON(): APIComponent } | Array<{ toJSON(): APIComponent }>,\n options?: T & { flags?: number },\n): { components: APIComponent[]; flags: number } & T {\n const list = Array.isArray(components) ? components : [components];\n if (!list.length)\n throw new TypeError(\n \"A Components V2 message needs at least one component.\",\n );\n return {\n ...(options ?? ({} as T)),\n components: list.map((component) => component.toJSON()),\n flags: (options?.flags ?? 0) | IS_COMPONENTS_V2,\n };\n}\n",
11
+ "/** Discord application command option types. */\nexport const ApplicationCommandOptionEnum = {\n Subcommand: 1,\n SubcommandGroup: 2,\n String: 3,\n Integer: 4,\n Boolean: 5,\n User: 6,\n Channel: 7,\n Role: 8,\n Mentionable: 9,\n Number: 10,\n Attachment: 11,\n} as const;\n/** One {@link ApplicationCommandOptionEnum} value, usable as a type. */\nexport type ApplicationCommandOptionEnum =\n (typeof ApplicationCommandOptionEnum)[keyof typeof ApplicationCommandOptionEnum];\n\n/** Throws unless every context is 0 (guilds), 1 (the bot's DMs) or 2 (other DMs). */\nfunction validateContexts(contexts: number[]): void {\n if (\n contexts.some(\n (context) => context !== 0 && context !== 1 && context !== 2,\n )\n )\n throw new RangeError(\"Command contexts must be 0, 1 or 2.\");\n}\n\n/** Builds Discord application command payloads. */\nexport class CreateSlashCommand {\n readonly #data: Record<string, unknown> = { type: 1 };\n /** Sets the command name. */\n public setName(name: string): this {\n validateName(name, \"Command name\");\n this.#data.name = name;\n return this;\n }\n /** Sets the command description. */\n public setDescription(description: string): this {\n validateText(description, \"Command description\", 100);\n this.#data.description = description;\n return this;\n }\n /** Sets where the command can be used: 0 guilds, 1 the bot's DMs, 2 other DMs. @throws {RangeError} For any other value. */\n public setContexts(...contexts: number[]): this {\n validateContexts(contexts);\n this.#data.contexts = [...contexts];\n return this;\n }\n /** Sets whether the command is NSFW. */\n public setNSFW(nsfw = true): this {\n this.#data.nsfw = nsfw;\n return this;\n }\n /** Sets whether the command is NSFW. */\n public setNsfw(nsfw = true): this {\n return this.setNSFW(nsfw);\n }\n /** Sets command default member permissions. */\n public setDefaultMemberPermissions(\n permissions: bigint | number | string | null,\n ): this {\n this.#data.default_member_permissions =\n permissions === null ? null : BigInt(permissions).toString();\n return this;\n }\n /** Sets command integration types. */\n public setIntegrationTypes(...types: number[]): this {\n this.#data.integration_types = [...types];\n return this;\n }\n /** Adds a string option. */\n public addStringOption(\n configure: (option: CreateStringOption) => CreateStringOption,\n ): this {\n return this.addOption(configure(new CreateStringOption()));\n }\n /** Adds an integer option. */\n public addIntegerOption(\n configure: (option: CreateIntegerOption) => CreateIntegerOption,\n ): this {\n return this.addOption(configure(new CreateIntegerOption()));\n }\n /** Adds a number option. */\n public addNumberOption(\n configure: (option: CreateNumberOption) => CreateNumberOption,\n ): this {\n return this.addOption(configure(new CreateNumberOption()));\n }\n /** Adds a boolean option. */\n public addBooleanOption(\n configure: (option: CreateBooleanOption) => CreateBooleanOption,\n ): this {\n return this.addOption(configure(new CreateBooleanOption()));\n }\n /** Adds a user option. */\n public addUserOption(\n configure: (option: CreateUserOption) => CreateUserOption,\n ): this {\n return this.addOption(configure(new CreateUserOption()));\n }\n /** Adds a channel option. */\n public addChannelOption(\n configure: (option: CreateChannelOption) => CreateChannelOption,\n ): this {\n return this.addOption(configure(new CreateChannelOption()));\n }\n /** Adds a role option. */\n public addRoleOption(\n configure: (option: CreateRoleOption) => CreateRoleOption,\n ): this {\n return this.addOption(configure(new CreateRoleOption()));\n }\n /** Adds a mentionable option. */\n public addMentionableOption(\n configure: (option: CreateMentionableOption) => CreateMentionableOption,\n ): this {\n return this.addOption(configure(new CreateMentionableOption()));\n }\n /** Adds an attachment option. */\n public addAttachmentOption(\n configure: (option: CreateAttachmentOption) => CreateAttachmentOption,\n ): this {\n return this.addOption(configure(new CreateAttachmentOption()));\n }\n /** Adds a subcommand. */\n public addSubcommand(\n configure: (option: CreateSubcommand) => CreateSubcommand,\n ): this {\n return this.addOption(configure(new CreateSubcommand()));\n }\n /** Adds a subcommand group. */\n public addSubcommandGroup(\n configure: (option: CreateSubcommandGroup) => CreateSubcommandGroup,\n ): this {\n return this.addOption(configure(new CreateSubcommandGroup()));\n }\n /** Serializes the command payload. */\n public toJSON(): Record<string, unknown> {\n return structuredClone(this.#data);\n }\n /** Adds a validated top-level command option. */\n protected addOption(option: CreateCommandOption): this {\n this.#data.options = appendOption(\n this.#data.options,\n option.toJSON(),\n \"application command\",\n );\n return this;\n }\n}\n\n/** Base builder for command options. */\nexport class CreateCommandOption {\n protected readonly data: Record<string, unknown>;\n /** Creates an option builder. */\n public constructor(type: number) {\n this.data = { type };\n }\n /** Sets the option name. */\n public setName(name: string): this {\n validateName(name, \"Option name\");\n this.data.name = name;\n return this;\n }\n /** Sets the option description. */\n public setDescription(description: string): this {\n validateText(description, \"Option description\", 100);\n this.data.description = description;\n return this;\n }\n /** Makes the option required or optional. */\n public setRequired(required = true): this {\n this.data.required = required;\n return this;\n }\n /** Sets autocomplete. */\n public setAutocomplete(enabled = true): this {\n this.data.autocomplete = enabled;\n return this;\n }\n /** Serializes the option payload. */\n public toJSON(): Record<string, unknown> {\n return structuredClone(this.data);\n }\n}\n\n/** Builds a string command option. */\nexport class CreateStringOption extends CreateCommandOption {\n /** Creates a string option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.String);\n }\n /** Adds string choices. */\n public addChoices(\n ...choices: Array<{ name: string; value: string }>\n ): this {\n for (const choice of choices)\n validateText(choice.value, \"Choice value\", 100);\n appendChoices(this.data, choices);\n return this;\n }\n /** Sets the minimum string length. */\n public setMinLength(value: number): this {\n validateIntegerRange(value, 0, 6000, \"min_length\");\n this.data.min_length = value;\n return this;\n }\n /** Sets the maximum string length. */\n public setMaxLength(value: number): this {\n validateIntegerRange(value, 1, 6000, \"max_length\");\n if (\n (this.data.min_length as number | undefined) !== undefined &&\n (this.data.min_length as number) > value\n )\n throw new RangeError(\"min_length cannot exceed max_length.\");\n this.data.max_length = value;\n return this;\n }\n}\n/** Shared bounds, choices and autocomplete rules of integer and number options. */\nexport class CreateNumericOption extends CreateCommandOption {\n readonly #integer: boolean;\n /** Creates a numeric option; `integer` rejects fractional bounds. */\n public constructor(type: number, integer: boolean) {\n super(type);\n this.#integer = integer;\n }\n /** Sets the minimum value. */\n public setMinValue(value: number): this {\n validateNumberRange(\n value,\n -MAX_SAFE,\n MAX_SAFE,\n \"min_value\",\n this.#integer,\n );\n this.data.min_value = value;\n return this;\n }\n /** Sets the maximum value; it cannot be below the minimum. */\n public setMaxValue(value: number): this {\n validateNumberRange(\n value,\n -MAX_SAFE,\n MAX_SAFE,\n \"max_value\",\n this.#integer,\n );\n const min = this.data.min_value as number | undefined;\n if (min !== undefined && min > value)\n throw new RangeError(\"min_value cannot exceed max_value.\");\n this.data.max_value = value;\n return this;\n }\n /** Enables autocomplete; options with choices cannot use it. */\n public override setAutocomplete(enabled = true): this {\n if (\n enabled &&\n Array.isArray(this.data.choices) &&\n this.data.choices.length\n )\n throw new RangeError(\"Autocomplete options cannot define choices.\");\n this.data.autocomplete = enabled;\n return this;\n }\n /** Adds fixed choices. */\n public addChoices(...choices: { name: string; value: number }[]): this {\n appendChoices(this.data, choices);\n return this;\n }\n}\n/** Builds an integer command option. */\nexport class CreateIntegerOption extends CreateNumericOption {\n public constructor() {\n super(ApplicationCommandOptionEnum.Integer, true);\n }\n}\n/** Builds a number command option. */\nexport class CreateNumberOption extends CreateNumericOption {\n public constructor() {\n super(ApplicationCommandOptionEnum.Number, false);\n }\n}\n/** Builds a boolean command option. */\nexport class CreateBooleanOption extends CreateCommandOption {\n /** Creates a boolean option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.Boolean);\n }\n}\n/** Builds a user command option. */\nexport class CreateUserOption extends CreateCommandOption {\n /** Creates a user option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.User);\n }\n}\n/** Builds a role command option. */\nexport class CreateRoleOption extends CreateCommandOption {\n /** Creates a role option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.Role);\n }\n}\n/** Builds a mentionable command option. */\nexport class CreateMentionableOption extends CreateCommandOption {\n /** Creates a mentionable option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.Mentionable);\n }\n}\n/** Builds an attachment command option. */\nexport class CreateAttachmentOption extends CreateCommandOption {\n /** Creates an attachment option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.Attachment);\n }\n}\n/** Builds a channel command option. */\nexport class CreateChannelOption extends CreateCommandOption {\n /** Creates a channel option. */\n public constructor() {\n super(ApplicationCommandOptionEnum.Channel);\n }\n /** Restricts accepted channel types. */\n public addChannelTypes(...types: number[]): this {\n if (types.some((type) => !Number.isInteger(type) || type < 0))\n throw new RangeError(\n \"Channel types must be non-negative integers.\",\n );\n this.data.channel_types = [...new Set(types)];\n return this;\n }\n}\n/** Builds a nested subcommand. */\nexport class CreateSubcommand extends CreateCommandOption {\n /** Creates a subcommand. */\n public constructor() {\n super(ApplicationCommandOptionEnum.Subcommand);\n }\n /** Adds a string option to this subcommand. */\n public addStringOption(\n configure: (option: CreateStringOption) => CreateStringOption,\n ): this {\n return this.addChildOption(configure(new CreateStringOption()));\n }\n /** Adds an integer option to this subcommand. */\n public addIntegerOption(\n configure: (option: CreateIntegerOption) => CreateIntegerOption,\n ): this {\n return this.addChildOption(configure(new CreateIntegerOption()));\n }\n /** Adds a number option to this subcommand. */\n public addNumberOption(\n configure: (option: CreateNumberOption) => CreateNumberOption,\n ): this {\n return this.addChildOption(configure(new CreateNumberOption()));\n }\n /** Adds a boolean option to this subcommand. */\n public addBooleanOption(\n configure: (option: CreateBooleanOption) => CreateBooleanOption,\n ): this {\n return this.addChildOption(configure(new CreateBooleanOption()));\n }\n /** Adds a user option to this subcommand. */\n public addUserOption(\n configure: (option: CreateUserOption) => CreateUserOption,\n ): this {\n return this.addChildOption(configure(new CreateUserOption()));\n }\n /** Adds a channel option to this subcommand. */\n public addChannelOption(\n configure: (option: CreateChannelOption) => CreateChannelOption,\n ): this {\n return this.addChildOption(configure(new CreateChannelOption()));\n }\n /** Adds a role option to this subcommand. */\n public addRoleOption(\n configure: (option: CreateRoleOption) => CreateRoleOption,\n ): this {\n return this.addChildOption(configure(new CreateRoleOption()));\n }\n /** Adds a mentionable option to this subcommand. */\n public addMentionableOption(\n configure: (option: CreateMentionableOption) => CreateMentionableOption,\n ): this {\n return this.addChildOption(configure(new CreateMentionableOption()));\n }\n /** Adds an attachment option to this subcommand. */\n public addAttachmentOption(\n configure: (option: CreateAttachmentOption) => CreateAttachmentOption,\n ): this {\n return this.addChildOption(configure(new CreateAttachmentOption()));\n }\n protected addChildOption(option: CreateCommandOption): this {\n const options =\n (this.data.options as OptionPayload[] | undefined) ?? [];\n if (\n options.some(\n (existing) =>\n existing.type === ApplicationCommandOptionEnum.Subcommand,\n )\n )\n throw new RangeError(\n \"Subcommands cannot contain nested subcommands.\",\n );\n this.data.options = appendOption(\n options,\n option.toJSON(),\n \"subcommand\",\n );\n return this;\n }\n}\n/** Builds a nested subcommand group. */\nexport class CreateSubcommandGroup extends CreateCommandOption {\n /** Creates a subcommand group. */\n public constructor() {\n super(ApplicationCommandOptionEnum.SubcommandGroup);\n }\n /** Adds a subcommand to this group. */\n public addSubcommand(\n configure: (option: CreateSubcommand) => CreateSubcommand,\n ): this {\n const options = (this.data.options as unknown[] | undefined) ?? [];\n if (options.length >= 25)\n throw new RangeError(\n \"A subcommand group cannot contain more than 25 subcommands.\",\n );\n const payload = configure(new CreateSubcommand()).toJSON();\n if (\n options.some(\n (existing) =>\n (existing as Record<string, unknown>).name === payload.name,\n )\n )\n throw new RangeError(\n `Duplicate subcommand name: ${String(payload.name)}.`,\n );\n if (payload.type !== ApplicationCommandOptionEnum.Subcommand)\n throw new TypeError(\n \"Subcommand group children must be subcommands.\",\n );\n options.push(payload);\n this.data.options = options;\n return this;\n }\n}\nconst MAX_SAFE = Number.MAX_SAFE_INTEGER;\n\n/** A serialized option as stored on its parent. */\ntype OptionPayload = Record<string, unknown>;\n\n/**\n * Returns `options` with `payload` appended, enforcing Discord's limit of 25,\n * unique names, and required options before optional ones.\n */\nfunction appendOption(\n options: unknown,\n payload: OptionPayload,\n parent: \"application command\" | \"subcommand\",\n): OptionPayload[] {\n const list = (options as OptionPayload[] | undefined) ?? [];\n if (list.length >= 25)\n throw new RangeError(\n `${parent === \"subcommand\" ? \"A subcommand\" : \"An application command\"} cannot contain more than 25 options.`,\n );\n if (list.some((existing) => existing.name === payload.name))\n throw new RangeError(`Duplicate option name: ${String(payload.name)}.`);\n if (\n payload.required === true &&\n list.some((existing) => existing.required !== true)\n )\n throw new RangeError(\n `Required ${parent} options must be placed before optional options.`,\n );\n return [...list, payload];\n}\n\n/** Appends choices to an option, enforcing the shared choice rules. */\nfunction appendChoices(\n data: OptionPayload,\n choices: { name: string; value: string | number }[],\n): void {\n const current = (data.choices as unknown[] | undefined) ?? [];\n if (!choices.length)\n throw new TypeError(\"At least one choice is required.\");\n if (data.autocomplete === true)\n throw new RangeError(\"Autocomplete options cannot define choices.\");\n if (current.length + choices.length > 25)\n throw new RangeError(\"An option cannot contain more than 25 choices.\");\n for (const choice of choices) validateText(choice.name, \"Choice name\", 100);\n data.choices = [...current, ...choices.map((choice) => ({ ...choice }))];\n}\n\nfunction validateName(value: string, field: string): void {\n if (!/^[\\p{L}\\p{N}_-]{1,32}$/u.test(value) || value !== value.toLowerCase())\n throw new RangeError(\n `${field} must contain 1-32 lowercase letters, numbers, underscores, or hyphens.`,\n );\n}\nfunction validateText(value: string, field: string, max: number): void {\n if (typeof value !== \"string\" || !value.trim() || value.length > max)\n throw new RangeError(`${field} must contain 1-${max} characters.`);\n}\nfunction validateIntegerRange(\n value: number,\n minimum: number,\n maximum: number,\n field: string,\n): void {\n if (!Number.isInteger(value) || value < minimum || value > maximum)\n throw new RangeError(\n `${field} must be an integer between ${minimum} and ${maximum}.`,\n );\n}\nfunction validateNumberRange(\n value: number,\n minimum: number,\n maximum: number,\n field: string,\n integerOnly = true,\n): void {\n if (\n !Number.isFinite(value) ||\n (integerOnly && !Number.isInteger(value)) ||\n value < minimum ||\n value > maximum\n )\n throw new RangeError(\n `${field} must be ${integerOnly ? \"an integer\" : \"a number\"} between ${minimum} and ${maximum}.`,\n );\n}\n\n// ─── Context Menu Builders ────────────────────────────────────────────────────\n\n/** Builder for application commands that appear in right-click context menus.\n * Discord.js-familiar: `new CreateContextMenuCommand().setName(\"x\").setType(2)`. */\nexport class CreateContextMenuCommand {\n protected readonly data: Record<string, unknown>;\n public constructor(type: 2 | 3 = 2) {\n this.data = { type };\n }\n /** Sets the command type: 2 = USER, 3 = MESSAGE. @throws {RangeError} For any other type. */\n public setType(type: 2 | 3): this {\n if (type !== 2 && type !== 3)\n throw new RangeError(\"Context menu command type must be 2 or 3.\");\n this.data.type = type;\n return this;\n }\n /** Sets the command name (shown in the right-click menu).\n * Unlike CHAT_INPUT commands, USER (type 2) and MESSAGE (type 3) context-menu\n * command names may contain uppercase letters and spaces, so no lowercase/charset\n * validation is applied here — only Discord's 1-32 length limit and a non-empty\n * (non-whitespace) requirement are enforced.\n * @param name Display name; 1-32 characters, mixed case and spaces allowed.\n * @throws {RangeError} If the name is empty/whitespace-only or exceeds 32 characters.\n */\n public setName(name: string): this {\n if (\n typeof name !== \"string\" ||\n name.trim().length < 1 ||\n name.length > 32\n )\n throw new RangeError(\"Command name must contain 1-32 characters.\");\n this.data.name = name;\n return this;\n }\n /** Sets default member permissions required to see this command. */\n public setDefaultMemberPermissions(\n permissions: bigint | number | string | null,\n ): this {\n this.data.default_member_permissions =\n permissions === null ? null : BigInt(permissions).toString();\n return this;\n }\n /** Sets command integration types (0 guild install, 1 user install). */\n public setIntegrationTypes(...types: number[]): this {\n this.data.integration_types = [...types];\n return this;\n }\n /** Sets where the command can be used: 0 guilds, 1 the bot's DMs, 2 other DMs. @throws {RangeError} For any other value. */\n public setContexts(...contexts: number[]): this {\n validateContexts(contexts);\n this.data.contexts = [...contexts];\n return this;\n }\n /** Sets the name shown per locale, e.g. `{ \"es-ES\": \"Ver perfil\" }`; null clears it. */\n public setNameLocalizations(\n localizations: Record<string, string> | null,\n ): this {\n this.data.name_localizations =\n localizations === null ? null : { ...localizations };\n return this;\n }\n /** Serializes the command payload for the Discord API. */\n public toJSON(): Record<string, unknown> {\n return structuredClone(this.data);\n }\n}\n\n/** Builds a User context menu command (appears when right-clicking a user, type 2).\n * @example\n * new CreateUserCommand().setName(\"View Profile\").toJSON()\n */\nexport class CreateUserCommand extends CreateContextMenuCommand {\n public constructor() {\n super(2);\n }\n}\n\n/** Builds a Message context menu command (appears when right-clicking a message, type 3).\n * @example\n * new CreateMessageCommand().setName(\"Translate Message\").toJSON()\n */\nexport class CreateMessageCommand extends CreateContextMenuCommand {\n public constructor() {\n super(3);\n }\n}\n",
12
+ "/**\n * Prefix-command arguments: split a message into arguments and read them as\n * typed values, the way slash-command options are read.\n */\n\n/** What an argument is read as. `rest` takes everything left, as one string. */\nexport type PrefixArgType =\n | \"string\"\n | \"integer\"\n | \"number\"\n | \"boolean\"\n | \"user\"\n | \"role\"\n | \"channel\"\n | \"mentionable\"\n | \"rest\";\n\n/** One expected argument. */\nexport interface PrefixArgSpec {\n name: string;\n type: PrefixArgType;\n required?: boolean;\n /** For `string` and `rest`: the longest accepted value. */\n maxLength?: number;\n /** For `integer` and `number`: the accepted range. */\n min?: number;\n max?: number;\n /** Accepted values (compared case-insensitively for strings). */\n choices?: readonly (string | number)[];\n}\n\n/** A mentionable argument: which kind of mention it was. An unmarked ID reads as a user. */\nexport interface MentionableArg {\n id: string;\n type: \"user\" | \"role\";\n}\n\nexport type PrefixArgValue = string | number | boolean | MentionableArg;\n\nexport type PrefixArgsResult =\n | { ok: true; values: Record<string, PrefixArgValue | undefined> }\n | { ok: false; arg: string; error: string };\n\nconst SNOWFLAKE = /^\\d{16,22}$/;\nconst TRUE_WORDS = new Set([\n \"true\",\n \"yes\",\n \"y\",\n \"on\",\n \"1\",\n \"enable\",\n \"enabled\",\n]);\nconst FALSE_WORDS = new Set([\n \"false\",\n \"no\",\n \"n\",\n \"off\",\n \"0\",\n \"disable\",\n \"disabled\",\n]);\n\n/**\n * Splits text into arguments on whitespace. \"Double quotes\" or 'single quotes'\n * keep spaces inside one argument; a backslash escapes the next character.\n * @example tokenizeArgs(`ban @user \"being rude\"`) // [\"ban\", \"@user\", \"being rude\"]\n */\nexport function tokenizeArgs(input: string): string[] {\n const args: string[] = [];\n let current = \"\";\n let quote: string | null = null;\n let started = false;\n for (let index = 0; index < input.length; index++) {\n const character = input[index]!;\n if (character === \"\\\\\" && index + 1 < input.length) {\n current += input[++index];\n started = true;\n } else if (quote) {\n if (character === quote) quote = null;\n else current += character;\n } else if (character === '\"' || character === \"'\") {\n // A quote opens a quoted part only at the start of an argument.\n if (started) current += character;\n else {\n quote = character;\n started = true;\n }\n } else if (/\\s/.test(character)) {\n if (started) args.push(current);\n current = \"\";\n started = false;\n } else {\n current += character;\n started = true;\n }\n }\n if (started) args.push(current);\n return args;\n}\n\n/** The user ID in `<@id>`, `<@!id>` or a bare ID; null otherwise. */\nexport function parseUserMention(value: string): string | null {\n const id = /^<@!?(\\d{16,22})>$/.exec(value)?.[1] ?? value;\n return SNOWFLAKE.test(id) ? id : null;\n}\n\n/** The role ID in `<@&id>` or a bare ID; null otherwise. */\nexport function parseRoleMention(value: string): string | null {\n const id = /^<@&(\\d{16,22})>$/.exec(value)?.[1] ?? value;\n return SNOWFLAKE.test(id) ? id : null;\n}\n\n/** The channel ID in `<#id>` or a bare ID; null otherwise. */\nexport function parseChannelMention(value: string): string | null {\n const id = /^<#(\\d{16,22})>$/.exec(value)?.[1] ?? value;\n return SNOWFLAKE.test(id) ? id : null;\n}\n\n/** A user or role mention; a bare ID reads as a user. Null otherwise. */\nexport function parseMentionable(value: string): MentionableArg | null {\n const role = /^<@&(\\d{16,22})>$/.exec(value)?.[1];\n if (role) return { id: role, type: \"role\" };\n const user = parseUserMention(value);\n return user ? { id: user, type: \"user\" } : null;\n}\n\nfunction readOne(\n spec: PrefixArgSpec,\n raw: string,\n): { value: PrefixArgValue } | { error: string } {\n switch (spec.type) {\n case \"string\":\n case \"rest\":\n if (spec.maxLength !== undefined && raw.length > spec.maxLength)\n return {\n error: `must be at most ${spec.maxLength} characters`,\n };\n if (\n spec.choices &&\n !spec.choices.some(\n (choice) =>\n String(choice).toLowerCase() === raw.toLowerCase(),\n )\n )\n return { error: `must be one of: ${spec.choices.join(\", \")}` };\n return { value: raw };\n case \"integer\":\n case \"number\": {\n const value = Number(raw);\n if (!Number.isFinite(value) || raw.trim() === \"\")\n return { error: \"must be a number\" };\n if (spec.type === \"integer\" && !Number.isSafeInteger(value))\n return { error: \"must be a whole number\" };\n if (spec.min !== undefined && value < spec.min)\n return { error: `must be at least ${spec.min}` };\n if (spec.max !== undefined && value > spec.max)\n return { error: `must be at most ${spec.max}` };\n if (spec.choices && !spec.choices.includes(value))\n return { error: `must be one of: ${spec.choices.join(\", \")}` };\n return { value };\n }\n case \"boolean\": {\n const word = raw.toLowerCase();\n if (TRUE_WORDS.has(word)) return { value: true };\n if (FALSE_WORDS.has(word)) return { value: false };\n return { error: \"must be yes or no\" };\n }\n case \"user\": {\n const id = parseUserMention(raw);\n return id\n ? { value: id }\n : { error: \"must be a user mention or ID\" };\n }\n case \"role\": {\n const id = parseRoleMention(raw);\n return id\n ? { value: id }\n : { error: \"must be a role mention or ID\" };\n }\n case \"channel\": {\n const id = parseChannelMention(raw);\n return id\n ? { value: id }\n : { error: \"must be a channel mention or ID\" };\n }\n case \"mentionable\": {\n const value = parseMentionable(raw);\n return value\n ? { value }\n : { error: \"must be a user or role mention\" };\n }\n }\n}\n\n/**\n * Reads prefix-command arguments by position, as typed values. IDs come back\n * as strings (user, role, channel); a mentionable says which it was. The first\n * problem is reported, with the argument's name, instead of throwing.\n * @param input The text after the command name, or already-split arguments.\n * @param specs The expected arguments in order; a `rest` argument must be last.\n * @example\n * const result = parsePrefixArgs(`@user 10 spamming links`, [\n * { name: \"user\", type: \"user\", required: true },\n * { name: \"minutes\", type: \"integer\", min: 1, max: 40320 },\n * { name: \"reason\", type: \"rest\" },\n * ]);\n * if (!result.ok) return message.reply(`\\`${result.arg}\\` ${result.error}.`);\n */\nexport function parsePrefixArgs(\n input: string | readonly string[],\n specs: readonly PrefixArgSpec[],\n): PrefixArgsResult {\n const args = typeof input === \"string\" ? tokenizeArgs(input) : [...input];\n const values: Record<string, PrefixArgValue | undefined> = {};\n let position = 0;\n for (const [index, spec] of specs.entries()) {\n if (spec.type === \"rest\" && index !== specs.length - 1)\n throw new TypeError(\n `The rest argument \"${spec.name}\" must be the last one.`,\n );\n const raw =\n spec.type === \"rest\"\n ? args.slice(position).join(\" \")\n : args[position];\n if (raw === undefined || raw === \"\") {\n if (spec.required)\n return { ok: false, arg: spec.name, error: \"is required\" };\n values[spec.name] = undefined;\n continue;\n }\n const read = readOne(spec, raw);\n if (\"error\" in read)\n return { ok: false, arg: spec.name, error: read.error };\n values[spec.name] = read.value;\n position += spec.type === \"rest\" ? args.length : 1;\n }\n return { ok: true, values };\n}\n\n/** Discord application-command option types, as numbers (this package has no dependencies). */\nconst OPTION_TYPES: Readonly<Record<number, PrefixArgType>> = {\n 3: \"string\",\n 4: \"integer\",\n 5: \"boolean\",\n 6: \"user\",\n 7: \"channel\",\n 8: \"role\",\n 9: \"mentionable\",\n 10: \"number\",\n};\n\n/**\n * Argument specs from a slash command's options, so one definition serves both\n * `/command` and the prefix command. Subcommands and attachments are left out.\n * @param options The command's (or subcommand's) `options` as sent to Discord.\n * @param restLast Read the last string option as the rest of the message (handy for reasons).\n */\nexport function argsFromCommandOptions(\n options: readonly {\n name: string;\n type: number;\n required?: boolean;\n min_value?: number;\n max_value?: number;\n max_length?: number;\n choices?: readonly { value: string | number }[];\n }[],\n restLast = false,\n): PrefixArgSpec[] {\n const specs: PrefixArgSpec[] = [];\n for (const option of options) {\n const type = OPTION_TYPES[option.type];\n if (!type) continue;\n specs.push({\n name: option.name,\n type,\n required: option.required,\n min: option.min_value,\n max: option.max_value,\n maxLength: option.max_length,\n choices: option.choices?.map((choice) => choice.value),\n });\n }\n const last = specs[specs.length - 1];\n if (restLast && last?.type === \"string\") last.type = \"rest\";\n return specs;\n}\n",
13
+ "/** Retention policy for a {@link Collection}. */\nexport interface CollectionOptions<K = unknown, V = unknown> {\n /** Default sliding TTL in ms for `set()`. Omit for no expiry. */\n ttl?: number;\n /** Fraction (0-1) of each entry's TTL randomly shaved off when it is set, so entries stored together do not expire together. Default `0`. */\n jitter?: number;\n /** Maximum entries stored with `set()`; least-recently-used are evicted past it. `setWithoutTTL()` entries are never counted or evicted. */\n maxSize?: number;\n /** Whether a read restarts a TTL entry's window. Default `true`; with `false` an entry lapses a fixed time after it was set, and reads only mark it recently used. */\n slide?: boolean;\n /** Called after an entry is removed automatically, with why. Exceptions are swallowed. */\n onEvict?: (key: K, value: V, reason: EvictionReason) => void;\n}\n\n/** Why an entry was removed automatically. */\nexport type EvictionReason = \"expired\" | \"evicted\";\n\n/** Cumulative counters from {@link Collection.stats}. */\nexport interface CollectionStats {\n /** `get`/`peek` calls that found a value. */\n hits: number;\n /** `get`/`peek` calls that found nothing. */\n misses: number;\n /** Entries removed because their TTL lapsed. */\n expired: number;\n /** Entries removed to stay within `maxSize`. */\n evicted: number;\n}\n\n/**\n * Everything the policy knows about one key: its place in the recency list\n * and its TTL. One record serves the policy map, the recency list and the\n * expiry heap, so a write touches one extra hash entry and allocates once.\n */\ntype Entry<K, V> = {\n key: K;\n /** A copy of the stored value, so a read needs one lookup instead of two. */\n value: V;\n /** Neighbours in recency order; meaningful while `inLru`. */\n older: Entry<K, V> | undefined;\n newer: Entry<K, V> | undefined;\n inLru: boolean;\n /** TTL window in ms; 0 when the entry does not expire (and is not in the heap). */\n window: number;\n /** The current deadline; a read moves it later without touching the heap. */\n deadline: number;\n /** The deadline the heap ordered this record by. */\n filed: number;\n};\n\n/**\n * Everything a retention policy needs. A Collection without `ttl` or\n * `maxSize` never creates one, so plain collections cost no more than a Map.\n */\ntype Policy<K, V> = {\n /** Keys with a TTL or a recency position; `setWithoutTTL()` keys are absent. */\n entries: Map<K, Entry<K, V>>;\n /** Oldest and newest entries of the recency list; only `maxSize` collections use it. */\n oldest: Entry<K, V> | undefined;\n newest: Entry<K, V> | undefined;\n lruSize: number;\n /** Min-heap by `filed`. A record that is no longer its key's map value is stale and dropped lazily. */\n heap: Entry<K, V>[];\n timer?: ReturnType<typeof setTimeout>;\n armedFor: number;\n /** The options, kept here so a plain collection carries none of them. */\n ttl: number | undefined;\n jitter: number;\n maxSize: number | undefined;\n slide: boolean;\n /** Stored loosely typed so the callback does not make Collection invariant in K and V. */\n onEvict:\n | ((key: unknown, value: unknown, reason: EvictionReason) => void)\n | undefined;\n expired: number;\n evicted: number;\n};\n\nfunction newPolicy<K, V>(options: CollectionOptions<K, V> = {}): Policy<K, V> {\n return {\n ttl: options.ttl,\n jitter: options.jitter ?? 0,\n maxSize: options.maxSize,\n slide: options.slide ?? true,\n onEvict: options.onEvict as Policy<K, V>[\"onEvict\"],\n expired: 0,\n evicted: 0,\n entries: new Map(),\n oldest: undefined,\n newest: undefined,\n lruSize: 0,\n heap: [],\n armedFor: Infinity,\n };\n}\n\n/**\n * Reads a value that `has()` just confirmed, without touching a Lunibee\n * collection's TTL, recency or hit counters.\n */\nfunction peekOf<K, V>(\n collection: ReadonlyCollection<K, V>,\n key: K,\n): V | undefined {\n return collection instanceof Map\n ? (Map.prototype.get.call(collection, key) as V | undefined)\n : collection.get(key);\n}\n\n/** What `merge()` does with one entry: keep it with `value`, or drop it. */\nexport type Keep<V> = { keep: true; value: V } | { keep: false };\n\n/**\n * A `Collection` seen read-only: every method that does not change it. Pass it\n * where you only read, so a function cannot add to or remove from the cache.\n */\nexport type ReadonlyCollection<K, V> = Omit<\n Collection<K, V>,\n | \"set\"\n | \"setWithoutTTL\"\n | \"delete\"\n | \"clear\"\n | \"ensure\"\n | \"forEach\"\n | \"get\"\n | \"sweep\"\n | \"purge\"\n> &\n ReadonlyMap<K, V>;\n\nconst mapGet = Map.prototype.get as (\n this: Map<unknown, unknown>,\n key: unknown,\n) => unknown;\nconst mapHas = Map.prototype.has as (\n this: Map<unknown, unknown>,\n key: unknown,\n) => boolean;\n\n/** Picks `amount` different items at random (a partial Fisher-Yates shuffle of `items`). */\nfunction sample<T>(items: T[], amount: number): T[] {\n if (!Number.isInteger(amount) || amount < 0)\n throw new RangeError(\"amount must be a non-negative integer.\");\n const count = Math.min(amount, items.length);\n for (let i = 0; i < count; i++) {\n const j = i + Math.floor(Math.random() * (items.length - i));\n [items[i], items[j]] = [items[j]!, items[i]!];\n }\n items.length = count;\n return items;\n}\n\nfunction assertTTL(ttl: number | undefined): void {\n if (ttl !== undefined && (!Number.isFinite(ttl) || ttl <= 0))\n throw new RangeError(\"TTL must be a positive number, or omitted.\");\n}\n\n/**\n * A keyed collection for Lunibee resource and application state.\n *\n * - `set(key, value, ttl?)` is TTL/LRU-aware: with a TTL (the default from\n * options, or per call) the entry expires after that window of inactivity,\n * and with `maxSize` it counts toward the cap.\n * - `setWithoutTTL(key, value)` never expires: no deadline, no heap record,\n * no timer, and exempt from `maxSize` eviction. Resource managers store\n * Discord state this way, so it leaves only through an explicit delete.\n *\n * Without options, a Collection behaves like a plain Map.\n */\nexport class Collection<K, V> extends Map<K, V> {\n /** Created with any option, or by the first `set()` with its own TTL. */\n #policy?: Policy<K, V>;\n #hits = 0;\n #misses = 0;\n\n /**\n * @param entries Initial entries, stored with `set()`.\n * @param options TTL and size policy.\n * @throws {RangeError} On a non-positive TTL or non-integer `maxSize`.\n */\n public constructor(\n entries?: Iterable<readonly [K, V]> | null,\n options: CollectionOptions<K, V> = {},\n ) {\n super();\n assertTTL(options.ttl);\n if (\n options.jitter !== undefined &&\n !(options.jitter >= 0 && options.jitter <= 1)\n )\n throw new RangeError(\"jitter must be between 0 and 1.\");\n if (\n options.maxSize !== undefined &&\n (!Number.isInteger(options.maxSize) || options.maxSize <= 0)\n )\n throw new RangeError(\"maxSize must be a positive integer.\");\n if (\n options.ttl !== undefined ||\n options.jitter !== undefined ||\n options.maxSize !== undefined ||\n options.slide !== undefined ||\n options.onEvict !== undefined\n )\n this.#policy = newPolicy(options);\n if (entries) for (const [key, value] of entries) this.set(key, value);\n }\n\n /**\n * Stores an entry with the default TTL (or `ttl`), marks it most recently\n * used, and enforces `maxSize`. Turns a `setWithoutTTL()` entry back into\n * a TTL/LRU entry.\n */\n public override set(key: K, value: V, ttl?: number): this {\n if (ttl === undefined && this.#policy === undefined)\n return super.set(key, value);\n assertTTL(ttl);\n let window = ttl ?? this.#policy?.ttl;\n const jitter = this.#policy?.jitter ?? 0;\n if (window !== undefined && jitter > 0)\n window = Math.max(1, window * (1 - jitter * Math.random()));\n if (window !== undefined) this.#policy ??= newPolicy();\n if (!this.#policy) return super.set(key, value);\n // A key that was not stored before has no policy entry.\n const before = super.size;\n super.set(key, value);\n this.#track(key, value, window, super.size !== before);\n this.#enforceCap();\n return this;\n }\n\n /**\n * Stores an entry that never expires: no deadline, heap record, timer or\n * LRU eviction. It leaves only through `delete`, `sweep`, `clear`, or a\n * later `set()`.\n */\n public setWithoutTTL(key: K, value: V): this {\n if (this.#policy) this.#forget(key);\n super.set(key, value);\n return this;\n }\n\n /** Reads a value; restarts a TTL entry's window and promotes it. */\n public override get(key: K): V | undefined {\n const policy = this.#policy;\n const entry = policy?.entries.get(key);\n if (entry === undefined) {\n const value = mapGet.call(this, key) as V | undefined;\n if (value !== undefined || mapHas.call(this, key)) {\n this.#hits++;\n return value;\n }\n this.#misses++;\n return undefined;\n }\n const timed = entry.window !== 0;\n const now = timed ? Date.now() : 0;\n if (timed && entry.deadline <= now) {\n this.#expire(entry);\n this.#misses++;\n return undefined;\n }\n this.#hits++;\n if (timed && policy!.slide) entry.deadline = now + entry.window;\n if (entry.inLru) this.#promote(policy!, entry);\n return entry.value;\n }\n\n /**\n * Returns the value for `key`, or stores and returns what `factory`\n * makes. Reading counts as a `get()` (restarts the TTL, marks it recently\n * used); creating stores with `set()`, so `ttl` applies.\n * @param factory Called with the key and this collection only when the key is missing; if it throws, nothing is stored.\n * @param ttl TTL in ms for a created entry; defaults to the collection's.\n */\n public ensure(\n key: K,\n factory: (key: K, collection: this) => V,\n ttl?: number,\n ): V {\n const existing = this.get(key);\n if (existing !== undefined || super.has(key)) return existing as V;\n const created = factory(key, this);\n this.set(key, created, ttl);\n return created;\n }\n\n /** Reads a value without restarting its TTL or promoting it. */\n public peek(key: K): V | undefined {\n if (!this.#expireIfDue(key) && super.has(key)) {\n this.#hits++;\n return super.get(key);\n }\n this.#misses++;\n return undefined;\n }\n\n /** Cumulative hit, miss, expiry and eviction counters (a copy). */\n public get stats(): CollectionStats {\n return {\n hits: this.#hits,\n misses: this.#misses,\n expired: this.#policy?.expired ?? 0,\n evicted: this.#policy?.evicted ?? 0,\n };\n }\n\n public override has(key: K): boolean {\n return !this.#expireIfDue(key) && super.has(key);\n }\n\n public override delete(key: K): boolean {\n if (this.#expireIfDue(key)) return false;\n if (this.#policy) this.#forget(key);\n return super.delete(key);\n }\n\n public override clear(): void {\n super.clear();\n const policy = this.#policy;\n if (!policy) return;\n policy.entries.clear();\n policy.oldest = policy.newest = undefined;\n policy.lruSize = 0;\n policy.heap.length = 0;\n if (policy.timer) clearTimeout(policy.timer);\n policy.timer = undefined;\n policy.armedFor = Infinity;\n }\n\n public override get size(): number {\n this.purge();\n return super.size;\n }\n\n public override entries(): MapIterator<[K, V]> {\n this.purge();\n return super.entries();\n }\n\n public override keys(): MapIterator<K> {\n this.purge();\n return super.keys();\n }\n\n public override values(): MapIterator<V> {\n this.purge();\n return super.values();\n }\n\n public override [Symbol.iterator](): MapIterator<[K, V]> {\n return this.entries();\n }\n\n public override forEach(\n callback: (value: V, key: K, map: Map<K, V>) => void,\n thisArg?: unknown,\n ): void {\n this.purge();\n super.forEach(callback, thisArg);\n }\n\n /** Milliseconds until a key lapses, or undefined if absent or never expiring. */\n public ttlRemaining(key: K): number | undefined {\n if (this.#expireIfDue(key)) return undefined;\n const entry = this.#policy?.entries.get(key);\n return entry && entry.window !== 0\n ? Math.max(0, entry.deadline - Date.now())\n : undefined;\n }\n\n /** Drops every lapsed TTL entry now. @returns How many were dropped. */\n public purge(): number {\n if (!this.#policy || this.#policy.heap.length === 0) return 0;\n const now = Date.now();\n let removed = 0;\n const dropped: [K, V][] = [];\n while (this.#nextDeadline() <= now) {\n const due = this.#heapPop()!;\n dropped.push([due.key, super.get(due.key)!]);\n this.#remove(due.key);\n removed++;\n }\n this.#policy!.expired += removed;\n this.#rearm();\n for (const [key, value] of dropped) this.#notify(key, value, \"expired\");\n return removed;\n }\n\n /** Drops `key` if its TTL has lapsed. @returns Whether it did. */\n #expireIfDue(key: K): boolean {\n const entry = this.#policy?.entries.get(key);\n if (!entry || entry.window === 0 || entry.deadline > Date.now())\n return false;\n this.#expire(entry);\n return true;\n }\n\n #expire(entry: Entry<K, V>): void {\n const value = super.get(entry.key)!;\n this.#remove(entry.key);\n this.#policy!.expired++;\n this.#notify(entry.key, value, \"expired\");\n }\n\n #remove(key: K): void {\n this.#forget(key);\n super.delete(key);\n }\n\n /** Drops a key's policy entry (recency position and TTL); its heap record goes stale. */\n #forget(key: K): void {\n const policy = this.#policy!;\n const entry = policy.entries.get(key);\n if (!entry) return;\n if (entry.inLru) this.#unlink(policy, entry);\n policy.entries.delete(key);\n }\n\n /**\n * Brings the key's policy entry in line with a `set()`: marks it newest\n * when `maxSize` is set, and gives it a deadline when `window` is defined.\n * Only a new entry, or a deadline that moves earlier, gets a heap record;\n * a later one is a number write and the record re-files itself when it\n * surfaces.\n */\n #track(key: K, value: V, window: number | undefined, isNew: boolean): void {\n const policy = this.#policy!;\n const lru = policy.maxSize !== undefined;\n let entry = isNew ? undefined : policy.entries.get(key);\n if (entry) entry.value = value;\n if (window === undefined) {\n if (entry && entry.window !== 0) {\n // It had a TTL and now has none.\n if (lru) entry = this.#replace(policy, entry, 0, 0);\n else {\n this.#forget(key);\n return;\n }\n }\n if (!entry && lru) {\n entry = this.#create(key, value, 0, 0);\n policy.entries.set(key, entry);\n }\n if (entry) this.#promote(policy, entry);\n return;\n }\n const deadline = Date.now() + window;\n if (entry && entry.window !== 0) {\n entry.deadline = deadline;\n entry.window = window;\n if (deadline < entry.filed)\n // The heap cannot move a record up, and this one is in it: file a fresh one.\n entry = this.#replace(policy, entry, window, deadline);\n else {\n if (entry.inLru) this.#promote(policy, entry);\n return;\n }\n } else if (entry) {\n entry.window = window;\n entry.deadline = entry.filed = deadline;\n } else {\n entry = this.#create(key, value, window, deadline);\n policy.entries.set(key, entry);\n }\n if (lru) this.#promote(policy, entry);\n this.#heapPush(entry);\n if (policy.heap.length > 2 * policy.entries.size + 8) this.#compact();\n // A timer already armed for an earlier deadline stays correct.\n if (policy.timer === undefined || deadline < policy.armedFor)\n this.#rearm();\n }\n\n #create(key: K, value: V, window: number, deadline: number): Entry<K, V> {\n return {\n key,\n value,\n older: undefined,\n newer: undefined,\n inLru: false,\n window,\n deadline,\n filed: deadline,\n };\n }\n\n /** Swaps in a fresh record for `old` (which goes stale), keeping its recency position. */\n #replace(\n policy: Policy<K, V>,\n old: Entry<K, V>,\n window: number,\n deadline: number,\n ): Entry<K, V> {\n const entry: Entry<K, V> = {\n ...old,\n window,\n deadline,\n filed: deadline,\n };\n if (old.inLru) {\n if (old.older) old.older.newer = entry;\n else policy.oldest = entry;\n if (old.newer) old.newer.older = entry;\n else policy.newest = entry;\n }\n policy.entries.set(old.key, entry);\n return entry;\n }\n\n /** Makes an entry the newest in recency order, linking it first if needed. */\n #promote(policy: Policy<K, V>, entry: Entry<K, V>): void {\n if (entry === policy.newest) return;\n if (entry.inLru) this.#unlink(policy, entry, true);\n else {\n entry.inLru = true;\n policy.lruSize++;\n }\n entry.older = policy.newest;\n entry.newer = undefined;\n if (policy.newest) policy.newest.newer = entry;\n else policy.oldest = entry;\n policy.newest = entry;\n }\n\n /** Takes an entry out of the recency list; `keepCount` is for a move within it. */\n #unlink(policy: Policy<K, V>, entry: Entry<K, V>, keepCount = false): void {\n if (entry.older) entry.older.newer = entry.newer;\n else policy.oldest = entry.newer;\n if (entry.newer) entry.newer.older = entry.older;\n else policy.newest = entry.older;\n entry.older = entry.newer = undefined;\n if (!keepCount) {\n entry.inLru = false;\n policy.lruSize--;\n }\n }\n\n /**\n * An empty collection of the species this one derives, so `filter()` and\n * friends on a subclass return the subclass. It is built without\n * arguments and carries no `ttl` or `maxSize`.\n */\n #derived(): this {\n const Species =\n (\n this.constructor as {\n [Symbol.species]?: new () => Collection<K, V>;\n }\n )[Symbol.species] ?? Collection;\n return new Species() as this;\n }\n\n #notify(key: K, value: V, reason: EvictionReason): void {\n const onEvict = this.#policy?.onEvict;\n if (!onEvict) return;\n try {\n onEvict(key, value, reason);\n } catch {\n // A throwing callback must not leave the collection inconsistent.\n }\n }\n\n /** Evicts least-recently-used `set()` entries past `maxSize`; O(1) per eviction. */\n #enforceCap(): void {\n const policy = this.#policy!;\n const max = policy.maxSize;\n if (max === undefined) return;\n // Lapsed entries must not push live ones out.\n if (\n policy.lruSize > max &&\n policy.heap.length > 0 &&\n policy.heap[0]!.filed <= Date.now()\n )\n this.purge();\n while (policy.lruSize > max) {\n const oldest = policy.oldest!;\n const value = policy.onEvict ? super.get(oldest.key) : undefined;\n this.#unlink(policy, oldest);\n policy.entries.delete(oldest.key);\n super.delete(oldest.key);\n policy.evicted++;\n this.#notify(oldest.key, value as V, \"evicted\");\n }\n }\n\n #nextDeadline(): number {\n const policy = this.#policy!;\n for (;;) {\n const top = policy.heap[0];\n if (top === undefined) return Infinity;\n if (policy.entries.get(top.key) !== top) {\n this.#heapPop();\n continue;\n }\n if (top.deadline === top.filed) return top.filed;\n // Extended since it was filed: re-file for its current deadline.\n this.#heapPop();\n top.filed = top.deadline;\n this.#heapPush(top);\n }\n }\n\n #compact(): void {\n const policy = this.#policy!;\n const live = policy.heap.filter(\n (entry) => policy.entries.get(entry.key) === entry,\n );\n policy.heap.length = 0;\n for (const entry of live) this.#heapPush(entry);\n }\n\n #rearm(): void {\n const p = this.#policy!;\n const deadline = this.#nextDeadline();\n if (p.timer !== undefined && deadline >= p.armedFor) return;\n if (p.timer) clearTimeout(p.timer);\n p.timer = undefined;\n p.armedFor = deadline;\n if (deadline === Infinity) return;\n p.timer = setTimeout(\n () => {\n p.timer = undefined;\n p.armedFor = Infinity;\n this.purge();\n },\n Math.max(0, deadline - Date.now()),\n );\n // Pending expiry is housekeeping, not a reason to keep the process alive.\n (p.timer as { unref?: () => void }).unref?.();\n }\n\n #heapPush(entry: Entry<K, V>): void {\n const heap = this.#policy!.heap;\n let i = heap.length;\n heap.push(entry);\n while (i > 0) {\n const parent = (i - 1) >> 1;\n const above = heap[parent]!;\n if (above.filed <= entry.filed) break;\n heap[i] = above;\n i = parent;\n }\n heap[i] = entry;\n }\n\n #heapPop(): Entry<K, V> | undefined {\n const heap = this.#policy!.heap;\n const top = heap[0];\n const last = heap.pop();\n if (top === undefined || heap.length === 0) return top;\n let i = 0;\n for (;;) {\n let child = 2 * i + 1;\n if (child >= heap.length) break;\n if (\n child + 1 < heap.length &&\n heap[child + 1]!.filed < heap[child]!.filed\n )\n child++;\n if (heap[child]!.filed >= last!.filed) break;\n heap[i] = heap[child]!;\n i = child;\n }\n heap[i] = last!;\n return top;\n }\n\n /** Returns the first stored value. */\n public first(): V | undefined {\n for (const value of this.values()) return value;\n return undefined;\n }\n /** Returns the first stored key. */\n public firstKey(): K | undefined {\n for (const key of this.keys()) return key;\n return undefined;\n }\n /** Returns the last stored value. */\n public last(): V | undefined {\n let value: V | undefined;\n for (const item of this.values()) value = item;\n return value;\n }\n /** Returns the last stored key. */\n public lastKey(): K | undefined {\n let key: K | undefined;\n for (const item of this.keys()) key = item;\n return key;\n }\n /** Finds the first value matching a predicate. */\n public find(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): V | undefined {\n for (const [key, value] of this) {\n if (predicate(value, key, this)) return value;\n }\n return undefined;\n }\n /** Finds the last value (in insertion order) matching a predicate. */\n public findLast(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): V | undefined {\n const keys = this.keyArray();\n const values = this.array();\n for (let i = values.length - 1; i >= 0; i--)\n if (predicate(values[i]!, keys[i]!, this)) return values[i];\n return undefined;\n }\n /** Finds the key of the last entry (in insertion order) matching a predicate. */\n public findLastKey(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): K | undefined {\n const keys = this.keyArray();\n const values = this.array();\n for (let i = values.length - 1; i >= 0; i--)\n if (predicate(values[i]!, keys[i]!, this)) return keys[i];\n return undefined;\n }\n /** Returns all values matching a predicate. */\n public filter(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): this {\n const result = this.#derived();\n // forEach walks the entries without allocating a [key, value] pair each.\n this.forEach((value, key) => {\n if (predicate(value, key, this)) result.set(key, value);\n });\n return result;\n }\n /** Transforms every stored value into an array. */\n public map<T>(transform: (value: V, key: K, collection: this) => T): T[] {\n const result: T[] = [];\n this.forEach((value, key) => {\n result.push(transform(value, key, this));\n });\n return result;\n }\n /** Returns whether at least one stored value satisfies a predicate. */\n public some(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): boolean {\n for (const [key, value] of this) {\n if (predicate(value, key, this)) return true;\n }\n return false;\n }\n /** Returns whether every stored value satisfies a predicate. */\n public every(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): boolean {\n for (const [key, value] of this) {\n if (!predicate(value, key, this)) return false;\n }\n return true;\n }\n /** Runs a callback for each stored value. */\n public each(\n callback: (value: V, key: K, collection: this) => unknown,\n ): this {\n this.forEach((value, key) => {\n callback(value, key, this);\n });\n return this;\n }\n /** Returns an array containing all stored values. */\n public array(): V[] {\n return [...this.values()];\n }\n /** Returns an array containing all stored keys. */\n public keyArray(): K[] {\n return [...this.keys()];\n }\n /** Returns a plain array of entries. */\n public entriesArray(): [K, V][] {\n return [...this.entries()];\n }\n /** Returns a new collection with the same entries. */\n public clone(): this {\n const copy = this.#derived();\n this.forEach((value, key) => {\n copy.set(key, value);\n });\n return copy;\n }\n /** Returns whether all supplied keys are present. */\n public hasAll(...keys: K[]): boolean {\n for (let i = 0; i < keys.length; i++) {\n if (!this.has(keys[i]!)) return false;\n }\n return true;\n }\n /** Returns whether at least one supplied key is present. */\n public hasAny(...keys: K[]): boolean {\n for (let i = 0; i < keys.length; i++) {\n if (this.has(keys[i]!)) return true;\n }\n return false;\n }\n /** Returns the first key whose value matches a predicate. */\n public findKey(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): K | undefined {\n for (const [key, value] of this) {\n if (predicate(value, key, this)) return key;\n }\n return undefined;\n }\n /** Returns whether a predicate matches at least one entry. */\n public someEntry(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): boolean {\n return this.some(predicate);\n }\n /** Removes every entry matching a predicate and returns the number removed. */\n public sweep(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): number {\n let removed = 0;\n for (const [key, value] of this) {\n if (predicate(value, key, this) && this.delete(key)) removed++;\n }\n return removed;\n }\n /** Returns the collection's first matching entry as a tuple. */\n public firstEntry(): [K, V] | undefined {\n for (const [key, value] of this) return [key, value];\n return undefined;\n }\n /** Returns the collection's last matching entry as a tuple. */\n public lastEntry(): [K, V] | undefined {\n let entry: [K, V] | undefined;\n for (const item of this) entry = [item[0], item[1]];\n return entry;\n }\n /** Returns a new Collection containing elements from both collections. */\n public union(other: ReadonlyCollection<K, V>): this {\n const result = this.clone();\n for (const [key, value] of other) result.set(key, value);\n return result;\n }\n /** Returns a new Collection containing only elements present in both collections. */\n public intersection(other: ReadonlyCollection<K, V>): this {\n const result = this.#derived();\n for (const [key, value] of this) {\n if (other.has(key)) result.set(key, value);\n }\n return result;\n }\n /** Returns a new Collection containing elements present in this collection but not the other. */\n public difference(other: ReadonlyCollection<K, V>): this {\n const result = this.#derived();\n for (const [key, value] of this) {\n if (!other.has(key)) result.set(key, value);\n }\n return result;\n }\n /** Splits the collection into two collections based on a predicate.\n * @returns `[passing, failing]` — entries satisfying the predicate, then those that don't.\n */\n public partition(\n predicate: (value: V, key: K, collection: this) => boolean,\n ): [this, this] {\n const pass = this.#derived();\n const fail = this.#derived();\n for (const [key, value] of this) {\n if (predicate(value, key, this)) pass.set(key, value);\n else fail.set(key, value);\n }\n return [pass, fail];\n }\n /** Returns the entries of both collections that are in only one of them. */\n public symmetricDifference(other: ReadonlyCollection<K, V>): this {\n const result = this.#derived();\n for (const [key, value] of this)\n if (!other.has(key)) result.set(key, value);\n for (const [key, value] of other)\n if (!this.has(key)) result.set(key, value);\n return result;\n }\n /** Returns a new Collection with this one's entries followed by each of `collections`'; a later collection wins a shared key. */\n public concat(...collections: ReadonlyCollection<K, V>[]): this {\n const result = this.clone();\n for (const collection of collections)\n for (const [key, value] of collection) result.set(key, value);\n return result;\n }\n /**\n * Combines this collection with `other`, deciding per key what to keep.\n * @param whenInSelf Called for a key only in this collection.\n * @param whenInOther Called for a key only in `other`.\n * @param whenInBoth Called for a key in both.\n * @returns A new collection of the entries the callbacks kept, in this collection's order, then `other`'s new keys.\n */\n public merge<T, R>(\n other: ReadonlyCollection<K, T>,\n whenInSelf: (value: V, key: K) => Keep<R>,\n whenInOther: (valueOther: T, key: K) => Keep<R>,\n whenInBoth: (value: V, valueOther: T, key: K) => Keep<R>,\n ): Collection<K, R> {\n const result = this.#derived() as unknown as Collection<K, R>;\n const decide = (key: K, kept: Keep<R>): void => {\n if (kept.keep) result.set(key, kept.value);\n };\n for (const [key, value] of this) {\n decide(\n key,\n other.has(key)\n ? whenInBoth(value, peekOf(other, key) as T, key)\n : whenInSelf(value, key),\n );\n }\n for (const [key, value] of other)\n if (!this.has(key)) decide(key, whenInOther(value, key));\n return result;\n }\n /** Returns whether `other` holds the same keys with `===` equal values. Neither side's TTL or recency is touched. */\n public equals(other: ReadonlyCollection<K, V> | null | undefined): boolean {\n if (!other) return false;\n if (other === (this as unknown)) return true;\n if (this.size !== other.size) return false;\n for (const [key, value] of this) {\n if (!other.has(key)) return false;\n if (value !== peekOf(other, key)) return false;\n }\n return true;\n }\n /** Returns a new collection with the same keys and each value passed through `transform`. */\n public mapValues<T>(\n transform: (value: V, key: K, collection: this) => T,\n ): Collection<K, T> {\n const result = this.#derived() as unknown as Collection<K, T>;\n for (const [key, value] of this)\n result.set(key, transform(value, key, this));\n return result;\n }\n /** Returns a new collection with the entries in reverse order. */\n public toReversed(): this {\n const result = this.#derived();\n const entries = [...this];\n for (let i = entries.length - 1; i >= 0; i--)\n result.set(entries[i]![0], entries[i]![1]);\n return result;\n }\n /** Same as {@link sorted}, under the name the standard `Array` uses. */\n public toSorted(\n comparator?: (a: V, b: V, aKey: K, bKey: K) => number,\n ): this {\n return this.sorted(comparator);\n }\n /**\n * Groups `items` by the key `keySelector` returns for each.\n * @param keySelector Called with each item and its index.\n * @returns A new collection from each key to its items, in input order.\n */\n public static override groupBy<K, V>(\n items: Iterable<V>,\n keySelector: (item: V, index: number) => K,\n ): Collection<K, V[]> {\n const groups = new Collection<K, V[]>();\n let index = 0;\n for (const item of items)\n groups.ensure(keySelector(item, index++), () => []).push(item);\n return groups;\n }\n /**\n * Builds a collection from `entries`, merging values that share a key.\n * @param combine Called with the value stored so far, the new one and the key; its result is stored.\n */\n public static combineEntries<K, V>(\n entries: Iterable<readonly [K, V]>,\n combine: (firstValue: V, secondValue: V, key: K) => V,\n ): Collection<K, V> {\n const result = new Collection<K, V>();\n for (const [key, value] of entries)\n result.set(\n key,\n result.has(key) ? combine(result.get(key)!, value, key) : value,\n );\n return result;\n }\n /** Calls `fn` with this collection and returns the collection unchanged.\n * Useful for inserting debug side-effects in a chain without breaking the flow.\n */\n public tap(fn: (collection: this) => unknown): this {\n fn(this);\n return this;\n }\n /** Maps every entry to an array of items and flattens the results. */\n public flatMap<T>(\n transform: (value: V, key: K, collection: this) => T[],\n ): T[] {\n const result: T[] = [];\n for (const [key, value] of this) {\n for (const item of transform(value, key, this)) result.push(item);\n }\n return result;\n }\n /** Reduces the collection to a single value. */\n public reduce<T>(\n fn: (accumulator: T, value: V, key: K, collection: this) => T,\n initialValue: T,\n ): T {\n let acc = initialValue;\n for (const [key, value] of this) acc = fn(acc, value, key, this);\n return acc;\n }\n /** Like {@link reduce}, but from the last entry to the first. */\n public reduceRight<T>(\n fn: (accumulator: T, value: V, key: K, collection: this) => T,\n initialValue: T,\n ): T {\n const entries = [...this];\n let acc = initialValue;\n for (let i = entries.length - 1; i >= 0; i--)\n acc = fn(acc, entries[i]![1], entries[i]![0], this);\n return acc;\n }\n /** Returns a new Collection with entries sorted by comparator (non-mutating).\n * Defaults to insertion order if no comparator is provided.\n */\n public sorted(comparator?: (a: V, b: V, aKey: K, bKey: K) => number): this {\n // Decorate with the original insertion index and use it as a tiebreaker so\n // equal elements keep their insertion order (a stable sort independent of\n // the engine's Array.prototype.sort stability guarantees).\n const decorated = [...this.entries()].map((entry, index) => ({\n entry,\n index,\n }));\n if (comparator)\n decorated.sort((x, y) => {\n const comparison = comparator(\n x.entry[1],\n y.entry[1],\n x.entry[0],\n y.entry[0],\n );\n return comparison !== 0 ? comparison : x.index - y.index;\n });\n const result = this.#derived();\n for (const { entry } of decorated) result.set(entry[0], entry[1]);\n return result;\n }\n /**\n * Returns a random value, or `undefined` if empty. With `amount`, returns\n * that many different values (all of them, shuffled, when `amount` is at\n * least the size).\n * Uses `Math.random()` (fast, non-cryptographic): do not use it for\n * security-sensitive selection such as tokens or secrets.\n * @param amount How many values to pick.\n * @throws {RangeError} If `amount` is not a non-negative integer.\n */\n public random(): V | undefined;\n public random(amount: number): V[];\n public random(amount?: number): V | V[] | undefined {\n if (amount !== undefined) return sample([...this.values()], amount);\n const size = this.size;\n if (size === 0) return undefined;\n let index = Math.floor(Math.random() * size);\n for (const value of this.values()) if (index-- === 0) return value;\n return undefined;\n }\n /**\n * Returns a random key, or `undefined` if empty. With `amount`, returns\n * that many different keys. Same randomness and errors as {@link random}.\n * @param amount How many keys to pick.\n */\n public randomKey(): K | undefined;\n public randomKey(amount: number): K[];\n public randomKey(amount?: number): K | K[] | undefined {\n if (amount !== undefined) return sample([...this.keys()], amount);\n const size = this.size;\n if (size === 0) return undefined;\n let index = Math.floor(Math.random() * size);\n for (const key of this.keys()) if (index-- === 0) return key;\n return undefined;\n }\n /** Returns the value at a given insertion-order index (supports negative indices). */\n public at(index: number): V | undefined {\n let remaining = index < 0 ? this.size + index : index;\n if (remaining < 0) return undefined;\n for (const value of this.values()) if (remaining-- === 0) return value;\n return undefined;\n }\n /** Returns the key at a given insertion-order index (supports negative indices). */\n public keyAt(index: number): K | undefined {\n let remaining = index < 0 ? this.size + index : index;\n if (remaining < 0) return undefined;\n for (const key of this.keys()) if (remaining-- === 0) return key;\n return undefined;\n }\n /** Serializes the collection to a plain `[key, value]` array. */\n public toJSON(): [K, V][] {\n return [...this.entries()];\n }\n}\n\nexport { Cache } from \"./cache.js\";\nexport type { CacheOptions } from \"./cache.js\";\n",
14
+ "/** Library version and source URL used for the Discord-compliant User-Agent. */\nimport packageJson from \"../package.json\" with { type: \"json\" };\nconst LIBRARY_VERSION = packageJson.version;\nconst LIBRARY_URL = \"https://github.com/Ekretos/lunibee\";\nconst USER_AGENT = `DiscordBot (${LIBRARY_URL}, ${LIBRARY_VERSION})`;\n\nimport { MemoryRateLimitStore, type RateLimitStore } from \"./store.js\";\nimport { RESTError, abortError, redactPath, sleep } from \"./errors.js\";\nimport {\n createRouteKey,\n serializeQuery,\n type RESTQuery,\n type RouteKey,\n} from \"./route.js\";\nimport { RequestScheduler } from \"./scheduler.js\";\nimport { RateLimiter } from \"./limiter.js\";\nimport { HttpTransport, TransportError } from \"./transport.js\";\nimport { ResponseDecoder } from \"./decoder.js\";\n\n/**\n * Refuses a path that URL normalization would rewrite into another route:\n * `.` / `..` segments (also percent-encoded) and backslashes. Without this,\n * an id like `../../channels/1` sends the bot token to a route the caller\n * never asked for. The path is left out of the message: it may hold a token.\n */\nfunction assertSafePath(path: string): void {\n const end = path.search(/[?#]/);\n const pathname = end === -1 ? path : path.slice(0, end);\n if (pathname.includes(\"\\\\\"))\n throw new TypeError(\"REST paths must not contain backslashes.\");\n for (const segment of pathname.split(\"/\")) {\n let decoded: string;\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n throw new TypeError(\"REST path has malformed percent-encoding.\");\n }\n if (decoded === \".\" || decoded === \"..\")\n throw new TypeError(\n \"REST paths must not contain '.' or '..' segments.\",\n );\n }\n}\n\n/** A file attachment sent as part of a multipart REST request. */\nexport interface RESTFileAttachment {\n name: string;\n data: Blob | Uint8Array | ArrayBuffer;\n contentType?: string;\n}\n\n/**\n * Options controlling an individual REST request.\n *\n * Lunibee's canonical call shape is positional (`post(path, body)`); these options\n * add the Discord.js-`@discordjs/rest`-familiar per-request knobs (`query`, `headers`,\n * `reason`, `auth`) additively without changing that positional default.\n */\nexport interface RESTRequestOptions {\n /** Abort signal used to cancel the request and any queued wait. */\n signal?: AbortSignal;\n /** Query-string appended to the path (`URLSearchParams`, a record, or a raw string). */\n query?: RESTQuery;\n /** Extra request headers merged in (library headers such as `Authorization` win). */\n headers?: Record<string, string>;\n /** Audit-log reason, sent as the `X-Audit-Log-Reason` header. */\n reason?: string;\n /** Set `false` to omit the `Authorization` header for this request. Defaults to `true`. */\n auth?: boolean;\n}\n\n/**\n * Discord.js-familiar request payload. Superset of {@link RESTRequestOptions} that also\n * carries the `body` and `files`, matching `@discordjs/rest`'s `RequestData`. It powers the\n * additive `method(path, { body })` overloads without breaking the positional signature.\n */\nexport interface RequestData extends RESTRequestOptions {\n /** Request body. Encoded as JSON unless `files` are present (then multipart). */\n body?: unknown;\n /** File attachments; presence upgrades the request to `multipart/form-data`. */\n files?: RESTFileAttachment[];\n}\n\n/** Keys recognised on a {@link RequestData} wrapper, used to disambiguate it from a raw body. */\nconst REQUEST_DATA_KEYS = new Set([\n \"body\",\n \"files\",\n \"query\",\n \"headers\",\n \"reason\",\n \"auth\",\n \"signal\",\n]);\n\n/**\n * Detects a Discord.js-style `RequestData` wrapper so verb helpers can accept both\n * `post(path, rawBody)` (Lunibee-canonical) and `post(path, { body })` (Discord.js-familiar).\n * Conservative by design: only a plain object whose every own key is a known `RequestData`\n * key counts — a raw Discord payload (which always carries entity keys like `content`/`name`)\n * never matches, so existing positional callers are unaffected.\n */\nfunction isRequestData(value: unknown): value is RequestData {\n if (value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return false;\n if (typeof FormData !== \"undefined\" && value instanceof FormData)\n return false;\n if (\n value instanceof Blob ||\n value instanceof Uint8Array ||\n value instanceof ArrayBuffer\n )\n return false;\n const keys = Object.keys(value);\n if (keys.length === 0) return false;\n return keys.every((key) => REQUEST_DATA_KEYS.has(key));\n}\n\n// ─── REST Hooks ───────────────────────────────────────────────────────────────\n\n/** Context passed to `RESTHooks.onRequest`. */\nexport interface RESTRequestContext {\n method: string;\n path: string;\n attempt: number;\n}\n/** Context passed to `RESTHooks.onResponse`. */\nexport interface RESTResponseContext {\n method: string;\n path: string;\n status: number;\n durationMs: number;\n}\n/** Context passed to `RESTHooks.onRateLimit`. */\nexport interface RESTRateLimitContext {\n method: string;\n path: string;\n retryAfterMs: number;\n global: boolean;\n bucket?: string;\n}\n/** Context passed to `RESTHooks.onRetry`. */\nexport interface RESTRetryContext {\n method: string;\n path: string;\n attempt: number;\n status: number;\n delayMs: number;\n}\n\n/**\n * Lightweight callback hooks for REST request lifecycle events.\n *\n * All callbacks are optional. They are dispatched in isolation from the request\n * path (deferred to a microtask, and any thrown error is swallowed), so a hook\n * cannot break or reject a request. Even so, hooks **must** be fast and\n * non-blocking: heavy synchronous work in a hook still steals event-loop time\n * from in-flight requests. Offload anything expensive to your own queue.\n */\nexport interface RESTHooks {\n /** Called just before every HTTP attempt. */\n onRequest?(ctx: RESTRequestContext): void;\n /** Called after a successful or failed response is received. */\n onResponse?(ctx: RESTResponseContext): void;\n /** Called when a rate limit is encountered and the client is about to wait. */\n onRateLimit?(ctx: RESTRateLimitContext): void;\n /** Called when a failed request is about to be retried. */\n onRetry?(ctx: RESTRetryContext): void;\n}\n\n/** Configures which REST failures may be retried. */\nexport interface RetryPolicy {\n /** Maximum retry attempts. */\n maxRetries: number;\n /** Determines whether a request may be retried. @param method HTTP method. @param status HTTP status, or zero for transport errors. @returns True when retrying is safe under the policy. */\n shouldRetry(method: string, status: number): boolean;\n /** Calculates delay before the next attempt. @param attempt Zero-based retry number. @param retryAfter Server-provided delay, when available. @returns Delay in milliseconds. */\n getDelay(attempt: number, retryAfter?: number): number;\n}\n/** Creates the default conservative REST retry policy. @param maxRetries Maximum retries. @returns Retry policy that retries rate limits and idempotent transient failures. @throws {TypeError} If maxRetries is negative or not finite. */\nexport function createRetryPolicy(maxRetries = 2): RetryPolicy {\n if (!Number.isFinite(maxRetries) || maxRetries < 0)\n throw new TypeError(\"maxRetries must be a non-negative finite number.\");\n return {\n maxRetries: Math.floor(maxRetries),\n shouldRetry(method, status) {\n const normalized = method.toUpperCase();\n const idempotent = [\"GET\", \"HEAD\", \"PUT\", \"DELETE\"].includes(\n normalized,\n );\n // Status 0 is a transport failure (DNS, reset connection, TLS):\n // no response reached Discord's handlers, so replaying an\n // idempotent request is as safe as replaying it after a 5xx.\n if (status === 0) return idempotent;\n return (\n status === 429 || (status >= 500 && status <= 599 && idempotent)\n );\n },\n getDelay(attempt, retryAfter) {\n if (retryAfter !== undefined) return Math.max(0, retryAfter * 1000);\n return Math.min(10_000, 500 * 2 ** attempt) + Math.random() * 250;\n },\n };\n}\n\n/** Bun-native REST transport with Discord bucket-aware rate limiting, retries, and cancellation. */\nexport class REST {\n readonly #retryPolicy: RetryPolicy;\n #token?: string;\n /** Rate-limit state: when a request may go out, what a response says. */\n readonly #limiter: RateLimiter;\n /** Per-bucket ordering. */\n readonly #scheduler = new RequestScheduler();\n /** One HTTP attempt, with timeout and cancellation. */\n readonly #transport: HttpTransport;\n /** Response payload and error metadata. */\n readonly #decoder = new ResponseDecoder();\n #hooks: RESTHooks = {};\n /** Whether requests on a known bucket may run concurrently. */\n readonly #concurrentBuckets: boolean;\n /** Creates a REST transport. @param options Transport configuration. @throws {TypeError} If retry configuration is invalid. */\n public constructor(\n options: {\n token?: string;\n timeout?: number;\n retries?: number;\n retryPolicy?: RetryPolicy;\n baseURL?: string;\n hooks?: RESTHooks;\n store?: RateLimitStore;\n /** Replaces the HTTP stage, e.g. with a recording transport in tests. */\n transport?: HttpTransport;\n /**\n * Lets requests on a bucket whose limit is known run concurrently, up\n * to its `remaining` allowance, instead of one at a time. Requires a\n * store with `reserve`. Requests on one bucket may then complete out\n * of order (e.g. messages to one channel). Defaults to `false`.\n */\n concurrentBuckets?: boolean;\n } = {},\n ) {\n this.#token = options.token;\n this.#retryPolicy =\n options.retryPolicy ?? createRetryPolicy(options.retries ?? 2);\n this.#transport =\n options.transport ??\n new HttpTransport({\n baseURL: options.baseURL,\n timeout: options.timeout,\n });\n const store = options.store ?? new MemoryRateLimitStore();\n this.#concurrentBuckets =\n (options.concurrentBuckets ?? true) &&\n typeof store.reserve === \"function\";\n this.#limiter = new RateLimiter(store, {\n concurrent: this.#concurrentBuckets,\n });\n if (options.hooks) this.#hooks = options.hooks;\n }\n /** The rate-limit store backing this transport. */\n public get store(): RateLimitStore {\n return this.#limiter.store;\n }\n /** Replaces the current hook set. Pass an empty object to clear all hooks. */\n public setHooks(hooks: RESTHooks): this {\n this.#hooks = hooks;\n return this;\n }\n /** Sets the authentication token. @param token Discord bot token. @returns Nothing. @throws {TypeError} If token is empty. */\n public setToken(token: string): void {\n if (!token.trim())\n throw new TypeError(\"A Discord bot token is required.\");\n this.#token = token;\n }\n /** Executes an HTTP request with Discord bucket/global rate limits, retry handling, and AbortSignal support.\n * Accepts a JSON body, a FormData body (for file uploads), or undefined.\n * @param method HTTP method.\n * @param path API path.\n * @param body Optional JSON body, FormData for file uploads, or undefined.\n * @param options Request options: cancellation `signal` plus the Discord.js-familiar\n * `query`, `headers`, `reason`, `auth`, and `files` (which upgrade to multipart).\n * @returns Decoded response body.\n * @throws {RESTError} If Discord or transport rejects the request.\n */\n public async request<T>(\n method: string,\n path: string,\n body?: unknown,\n options: RequestData = {},\n ): Promise<T> {\n if (!method.toUpperCase())\n throw new TypeError(\"REST method is required.\");\n if (!path.startsWith(\"/\"))\n throw new TypeError(\"REST paths must start with '/'.\");\n assertSafePath(path);\n const route = createRouteKey(method, path);\n // Upgrade to multipart when file attachments are supplied via options.\n const files = options.files;\n if (files && files.length > 0 && !(body instanceof FormData))\n body = this.#fileForm(body, files);\n const query = serializeQuery(options.query);\n const requestPath = query ? `${path}${query}` : path;\n\n // Discord scopes a rate limit by (bucket hash, major parameter): two\n // channels sharing an endpoint have independent limits, while two\n // different routes can share one hash. The key is therefore resolved\n // again once the slot is acquired, so a request that queued under its\n // route-derived key joins the shared bucket's queue if one was\n // discovered while it waited.\n return this.#scheduler.runResolved(\n () => this.#limiter.resolveBucketKey(route.route, route.major),\n options.signal,\n path,\n (bucketKey, release) =>\n this.#attempts<T>(\n route,\n requestPath,\n body,\n options,\n bucketKey,\n release,\n ),\n );\n }\n /**\n * Runs the retry loop for one scheduled request: acquire limits, send,\n * record what the response says, decode, and decide whether to try again.\n */\n async #attempts<T>(\n route: RouteKey,\n requestPath: string,\n body: unknown,\n options: RequestData,\n initialBucketKey: string,\n release: () => void,\n ): Promise<T> {\n const { method, path } = route;\n let bucketKey = initialBucketKey;\n for (\n let attempt = 0;\n attempt <= this.#retryPolicy.maxRetries;\n attempt++\n ) {\n await this.#limiter.acquire(bucketKey, options.signal, path);\n // The reservation already claimed this request's unit, so once the\n // bucket's window is known the next request need not wait for our\n // response. An unknown bucket stays serial until a response\n // reveals its limit.\n if (this.#concurrentBuckets) {\n const bucket = await this.#limiter.store.getBucket(bucketKey);\n if (bucket && bucket.resetAt > Date.now()) release();\n }\n this.#emit(this.#hooks.onRequest, { method, path, attempt });\n const requestStart = Date.now();\n let response: Response;\n try {\n response = await this.#transport.send({\n method,\n path: requestPath,\n headers: this.#headers(body, options),\n body: this.#encodeBody(body),\n signal: options.signal,\n });\n } catch (error) {\n if (error instanceof RESTError) throw error;\n if (options.signal?.aborted)\n throw abortError(path, options.signal.reason);\n const failure =\n error instanceof TransportError\n ? error\n : new TransportError(\n \"Discord REST request failed\",\n false,\n error,\n );\n if (\n !failure.timedOut &&\n attempt < this.#retryPolicy.maxRetries &&\n this.#retryPolicy.shouldRetry(method, 0)\n ) {\n await sleep(\n this.#retryPolicy.getDelay(attempt),\n options.signal,\n path,\n );\n continue;\n }\n throw new RESTError(failure.message, 0, undefined, undefined, {\n method,\n path,\n cause: failure.cause ?? failure,\n kind: failure.timedOut ? \"timeout\" : \"network\",\n });\n }\n this.#emit(this.#hooks.onResponse, {\n method,\n path,\n status: response.status,\n durationMs: Date.now() - requestStart,\n });\n bucketKey = await this.#limiter.applyResponse(\n response,\n bucketKey,\n route.route,\n route.major,\n );\n const payload = await this.#decoder.read(response);\n if (response.ok)\n return (response.status === 204 ? undefined : payload) as T;\n\n const data = this.#decoder.errorData(payload);\n const retryAfter =\n response.status === 429\n ? this.#decoder.retryAfter(response, data)\n : undefined;\n if (data.global && retryAfter !== undefined)\n await this.#limiter.noteGlobalReset(\n Date.now() + retryAfter * 1000,\n );\n // Fire for ANY 429, including a global limit that arrives without a\n // Retry-After header; fall back to 1s in that case.\n if (response.status === 429)\n this.#emit(this.#hooks.onRateLimit, {\n method,\n path,\n retryAfterMs: (retryAfter ?? 1) * 1000,\n global: data.global ?? false,\n bucket: await this.#limiter.store.getBucketHash(\n route.route,\n ),\n });\n if (\n attempt < this.#retryPolicy.maxRetries &&\n this.#retryPolicy.shouldRetry(method, response.status)\n ) {\n const delay = this.#retryPolicy.getDelay(attempt, retryAfter);\n this.#emit(this.#hooks.onRetry, {\n method,\n path,\n attempt,\n status: response.status,\n delayMs: delay,\n });\n await sleep(delay, options.signal, path);\n continue;\n }\n throw new RESTError(\n data.message ??\n response.statusText ??\n `Discord REST request failed with status ${response.status}`,\n response.status,\n data.code,\n payload,\n { method, path },\n );\n }\n throw new RESTError(\n \"Discord REST request exhausted its retry attempts\",\n 0,\n undefined,\n undefined,\n { method, path },\n );\n }\n /** Builds the header set for one attempt; library headers win over caller headers. */\n #headers(body: unknown, options: RequestData): Record<string, string> {\n const isFormData =\n typeof FormData !== \"undefined\" && body instanceof FormData;\n const headers: Record<string, string> = { ...options.headers };\n // Header names are case-insensitive: drop the caller's spelling first,\n // or `authorization` and `Authorization` are joined into one value.\n const set = (name: string, value: string): void => {\n for (const key of Object.keys(headers))\n if (key.toLowerCase() === name.toLowerCase())\n delete headers[key];\n headers[name] = value;\n };\n if (options.auth !== false && this.#token)\n set(\"Authorization\", `Bot ${this.#token}`);\n set(\"User-Agent\", USER_AGENT);\n if (options.reason !== undefined)\n set(\"X-Audit-Log-Reason\", encodeURIComponent(options.reason));\n if (!isFormData) set(\"Content-Type\", \"application/json\");\n return headers;\n }\n /** Encodes a body as multipart (passed through) or JSON. */\n #encodeBody(body: unknown): BodyInit | undefined {\n if (typeof FormData !== \"undefined\" && body instanceof FormData)\n return body;\n return body === undefined ? undefined : JSON.stringify(body);\n }\n /**\n * Normalizes a verb helper's second argument into `(body, options)`.\n * Supports both `verb(path, rawBody, options?)` (Lunibee-canonical positional) and the\n * Discord.js-familiar `verb(path, { body, query, headers, reason, files })` wrapper.\n */\n #dispatch<T>(\n method: string,\n path: string,\n bodyOrOptions?: unknown,\n options?: RequestData,\n ): Promise<T> {\n if (options === undefined && isRequestData(bodyOrOptions))\n return this.request<T>(\n method,\n path,\n bodyOrOptions.body,\n bodyOrOptions,\n );\n return this.request<T>(method, path, bodyOrOptions, options);\n }\n /** Sends a GET request. @param path API path. @param options Request options (`query`, `headers`, `signal`, …). @returns Decoded response. @throws {RESTError} When the request fails. */\n public get<T>(path: string, options?: RequestData): Promise<T> {\n return this.request<T>(\"GET\", path, options?.body, options);\n }\n /** Sends a POST request. Accepts a raw body (`post(path, body)`) or a Discord.js-familiar `post(path, { body })`. @param path API path. @param body Optional JSON body, or a `RequestData` wrapper. @param options Request options. @returns Decoded response. @throws {RESTError} When the request fails. */\n public post<T>(path: string, options: RequestData): Promise<T>;\n public post<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T>;\n public post<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T> {\n return this.#dispatch<T>(\"POST\", path, body, options);\n }\n /** Sends a PATCH request. Accepts a raw body (`patch(path, body)`) or a Discord.js-familiar `patch(path, { body })`. @param path API path. @param body Optional JSON body, or a `RequestData` wrapper. @param options Request options. @returns Decoded response. @throws {RESTError} When the request fails. */\n public patch<T>(path: string, options: RequestData): Promise<T>;\n public patch<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T>;\n public patch<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T> {\n return this.#dispatch<T>(\"PATCH\", path, body, options);\n }\n /** Sends a PUT request. Accepts a raw body (`put(path, body)`) or a Discord.js-familiar `put(path, { body })`. @param path API path. @param body Optional JSON body, or a `RequestData` wrapper. @param options Request options. @returns Decoded response. @throws {RESTError} When the request fails. */\n public put<T>(path: string, options: RequestData): Promise<T>;\n public put<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T>;\n public put<T>(\n path: string,\n body?: unknown,\n options?: RequestData,\n ): Promise<T> {\n return this.#dispatch<T>(\"PUT\", path, body, options);\n }\n /** Sends a DELETE request. @param path API path. @param options Request options (`reason`, `headers`, `signal`, …). @returns Decoded response. @throws {RESTError} When the request fails. */\n public delete<T>(path: string, options?: RequestData): Promise<T> {\n return this.request<T>(\"DELETE\", path, options?.body, options);\n }\n /**\n * Builds a multipart form with a JSON payload and file attachments.\n */\n #fileForm(payload: unknown, files: RESTFileAttachment[]): FormData {\n const form = new FormData();\n form.append(\"payload_json\", JSON.stringify(payload));\n for (let i = 0; i < files.length; i++) {\n const file = files[i]!;\n const blob =\n file.data instanceof Blob\n ? file.data\n : new Blob([file.data as ArrayBuffer], {\n type: file.contentType ?? \"application/octet-stream\",\n });\n form.append(`files[${i}]`, blob, file.name);\n }\n return form;\n }\n\n /**\n * Sends a multipart/form-data POST request for file uploads.\n * Attaches a JSON payload as `payload_json` and files as additional fields.\n * @param path API path.\n * @param payload JSON payload (e.g. message content, embeds).\n * @param files Array of file attachments.\n * @param options Cancellation options.\n * @returns Decoded response.\n * @throws {RESTError} When the request fails.\n */\n public postWithFiles<T>(\n path: string,\n payload: unknown,\n files: RESTFileAttachment[],\n options?: RESTRequestOptions,\n ): Promise<T> {\n return this.request<T>(\n \"POST\",\n path,\n this.#fileForm(payload, files),\n options,\n );\n }\n\n /**\n * Sends a multipart/form-data PATCH request for editing messages with files.\n * @param path API path.\n * @param payload JSON payload.\n * @param files Array of file attachments.\n * @param options Cancellation options.\n * @returns Decoded response.\n * @throws {RESTError} When the request fails.\n */\n public patchWithFiles<T>(\n path: string,\n payload: unknown,\n files: RESTFileAttachment[],\n options?: RESTRequestOptions,\n ): Promise<T> {\n return this.request<T>(\n \"PATCH\",\n path,\n this.#fileForm(payload, files),\n options,\n );\n }\n /** Dispatches a lifecycle hook in isolation: deferred to a microtask so it\n * cannot block the request path, with any thrown error swallowed so a faulty\n * hook cannot reject the request. @param hook Optional callback. @param ctx Event context. */\n #emit<C>(hook: ((ctx: C) => void) | undefined, ctx: C): void {\n if (!hook) return;\n const withPath = ctx as { path?: unknown };\n if (typeof withPath.path === \"string\")\n ctx = { ...ctx, path: redactPath(withPath.path) };\n Promise.resolve()\n .then(() => hook(ctx))\n .catch(() => {});\n }\n}\n\nexport { Routes } from \"./routes.js\";\nexport {\n RESTError,\n abortError,\n redactPath,\n type RESTErrorKind,\n} from \"./errors.js\";\nexport { RESTErrorCode } from \"./error-codes.js\";\nexport {\n createRouteKey,\n normalizeRoutePath,\n majorParameter,\n scopeBucket,\n serializeQuery,\n type RouteKey,\n type RESTQuery,\n} from \"./route.js\";\nexport { RequestScheduler } from \"./scheduler.js\";\nexport { RateLimiter } from \"./limiter.js\";\nexport {\n HttpTransport,\n TransportError,\n type TransportRequest,\n type FetchLike,\n} from \"./transport.js\";\nexport { ResponseDecoder, type DecodedError } from \"./decoder.js\";\nexport {\n type RateLimitStore,\n type BucketState,\n type Reservation,\n MemoryRateLimitStore,\n} from \"./store.js\";\nexport {\n RedisRateLimitStore,\n type RedisRateLimitStoreOptions,\n type MinimalRedisClient,\n} from \"./redis.js\";\n\nexport {\n WebhookClient,\n type WebhookClientOptions,\n type WebhookMessageOptions,\n} from \"./webhook.js\";\n\n/**\n * Discord.js-familiar alias for {@link RESTError}. `@discordjs/rest` throws `DiscordAPIError`\n * on a Discord-rejected request; Lunibee keeps `RESTError` as the canonical class and exports\n * this alias so Discord.js-shaped `catch (err) { if (err instanceof DiscordAPIError) … }` works.\n */\nexport { RESTError as DiscordAPIError };\n",
15
+ "import { Manager, ResourceManager, splitReason } from \"./base.js\";\nexport { Manager, ResourceManager } from \"./base.js\";\n/** Discord.js-familiar alias for {@link ResourceManager}. */\nexport { ResourceManager as CachedManager } from \"./base.js\";\nimport { REST, Routes } from \"@lunibee/rest\";\nimport type {\n AllowedMentions,\n APIForumTag,\n ForumTagInput,\n MessageCreateOptions,\n MessageEditOptions,\n} from \"@lunibee/types\";\nimport {\n Channel,\n createChannel,\n Message,\n User,\n type ResourceContext,\n} from \"@lunibee/structures\";\nimport {\n MessageManager,\n toRequest,\n type MessageCacheOptions,\n} from \"./message.js\";\nimport { ThreadManager } from \"./thread.js\";\n\nexport { UserManager } from \"./user.js\";\nexport { GuildManager } from \"./guild.js\";\nexport type { AuditLogEntry, AuditLogResponse } from \"./guild.js\";\nexport { AuditLogEvent } from \"./guild.js\";\n\nexport type { MessageCreateOptions, MessageEditOptions } from \"./message.js\";\n/** Discord only bulk-deletes messages younger than two weeks. */\nconst BULK_DELETE_MAX_AGE_MS = 14 * 24 * 60 * 60_000;\n/** Creation time (ms) encoded in a snowflake. */\nfunction snowflakeTime(id: string): number {\n return Number((BigInt(id) >> 22n) + 1_420_070_400_000n);\n}\nexport interface MessageFetchOptions {\n cache?: boolean;\n}\nexport interface MessageQueryOptions {\n before?: string;\n after?: string;\n around?: string;\n limit?: number;\n}\nexport interface MessageThreadOptions {\n name: string;\n autoArchiveDuration?: 60 | 1440 | 4320 | 10080;\n rateLimitPerUser?: number;\n}\nexport interface ReactionFetchOptions {\n limit?: number;\n after?: string;\n}\n\nexport interface ChannelCreateOptions extends Record<string, unknown> {\n /** Audit-log reason. */\n reason?: string;\n name: string;\n type: number;\n guild_id?: string;\n parent_id?: string | null;\n}\nexport type ChannelEditOptions = Record<string, unknown> & {\n /** Audit-log reason. */\n reason?: string;\n};\n\nimport { PermissionOverwriteManager } from \"./guild-resources.js\";\n\nexport class ChannelManager extends Manager<string, Channel> {\n readonly #rest: REST;\n readonly #context: ResourceContext;\n readonly #messageManagers = new Map<string, MessageManager>();\n readonly #messageCache?: MessageCacheOptions;\n readonly #allowedMentions?: AllowedMentions;\n /**\n * @param options.messageCache Enables a bounded per-channel message cache; messages are not cached by default.\n * @param options.allowedMentions Default `allowed_mentions` for sends and edits without their own.\n */\n public constructor(\n rest: REST,\n options: {\n messageCache?: MessageCacheOptions;\n allowedMentions?: AllowedMentions;\n } = {},\n ) {\n super();\n this.#rest = rest;\n this.#messageCache = options.messageCache;\n this.#allowedMentions = options.allowedMentions;\n this.#context = {\n sendMessage: (channelId, options) => this.send(channelId, options),\n editMessage: (channelId, messageId, options) =>\n this.editMessage(channelId, messageId, options),\n deleteMessage: (channelId, messageId, reason) =>\n this.deleteMessage(channelId, messageId, reason),\n crosspostMessage: (channelId, messageId) =>\n this.crosspostMessage(channelId, messageId),\n editChannel: (channelId, options) => this.edit(channelId, options),\n deleteChannel: (channelId, reason) =>\n this.remove(channelId, reason),\n addReaction: (channelId, messageId, emoji) =>\n this.addReaction(channelId, messageId, emoji),\n removeOwnReaction: (channelId, messageId, emoji) =>\n this.removeOwnReaction(channelId, messageId, emoji),\n removeReaction: (channelId, messageId, emoji, userId) =>\n this.removeReaction(channelId, messageId, emoji, userId),\n removeAllReactions: (channelId, messageId) =>\n this.removeAllReactions(channelId, messageId),\n pinMessage: (channelId, messageId, reason) =>\n this.pinMessage(channelId, messageId, reason),\n unpinMessage: (channelId, messageId, reason) =>\n this.unpinMessage(channelId, messageId, reason),\n };\n }\n public messages(channelId: string): MessageManager {\n let manager = this.#messageManagers.get(channelId);\n if (!manager) {\n manager = new MessageManager(\n this.#rest,\n this.#context,\n channelId,\n this.#messageCache,\n this.#allowedMentions,\n );\n this.#messageManagers.set(channelId, manager);\n }\n return manager;\n }\n /** Permission overwrite manager for a channel. */\n public permissionOverwrites(channelId: string): PermissionOverwriteManager {\n return new PermissionOverwriteManager(\n this.#rest,\n channelId,\n () => this.get(channelId)?.permissionOverwrites,\n );\n }\n public threads(channelId: string): ThreadManager {\n return new ThreadManager(this.#rest, this.#context, channelId);\n }\n /** Fetches a channel; concurrent fetches share a request and a stale result never overwrites newer state. */\n public fetch(channelId: string): Promise<Channel> {\n return this.fetchOnce(\n channelId,\n async () =>\n createChannel(\n await this.#rest.get<\n ConstructorParameters<typeof Channel>[0]\n >(Routes.channel(channelId)),\n this.#context,\n ),\n (channel) => this.#merge(channel),\n );\n }\n public async resolve(channelId: string): Promise<Channel> {\n return this.get(channelId) ?? this.fetch(channelId);\n }\n public upsert(data: ConstructorParameters<typeof Channel>[0]): Channel {\n return this.#merge(createChannel(data, this.#context));\n }\n /** Merges into the cached instance; a type change (e.g. text -> announcement) needs the new subclass. */\n #merge(channel: Channel): Channel {\n const existing = this.get(channel.id);\n if (existing && existing.type === channel.type) {\n Object.assign(existing, channel);\n return existing;\n }\n this.set(channel.id, channel);\n return channel;\n }\n public update(channel: Channel): this {\n return this.set(channel.id, channel);\n }\n /** Removes every cached channel that belongs to a guild. @returns Number removed. */\n public deleteGuildChannels(guildId: string): number {\n let removed = 0;\n for (const channel of this.values())\n if (channel.guildId === guildId && this.delete(channel.id))\n removed++;\n return removed;\n }\n /** Ends a poll now; returns the updated message. */\n public async endPoll(\n channelId: string,\n messageId: string,\n ): Promise<Message> {\n return this.messages(channelId).upsert(\n await this.#rest.post<ConstructorParameters<typeof Message>[0]>(\n Routes.pollExpire(channelId, messageId),\n ),\n );\n }\n /** Fetches users who voted for one poll answer. @param options.limit 1-100 (default 25). */\n public async fetchPollVoters(\n channelId: string,\n messageId: string,\n answerId: number,\n options: { after?: string; limit?: number } = {},\n ): Promise<User[]> {\n if (\n options.limit !== undefined &&\n (!Number.isInteger(options.limit) ||\n options.limit < 1 ||\n options.limit > 100)\n )\n throw new RangeError(\"Poll voter limit must be 1-100.\");\n const params = new URLSearchParams();\n if (options.after) params.set(\"after\", options.after);\n if (options.limit !== undefined)\n params.set(\"limit\", String(options.limit));\n const suffix = params.toString();\n const { users } = await this.#rest.get<{\n users: ConstructorParameters<typeof User>[0][];\n }>(\n `${Routes.pollAnswerVoters(channelId, messageId, answerId)}${suffix ? `?${suffix}` : \"\"}`,\n );\n return users.map((user) => new User(user));\n }\n /** Plays a soundboard sound in a voice channel the bot is connected to. */\n public async sendSoundboardSound(\n channelId: string,\n options: { soundId: string; sourceGuildId?: string },\n ): Promise<void> {\n await this.#rest.post(Routes.sendSoundboardSound(channelId), {\n sound_id: options.soundId,\n source_guild_id: options.sourceGuildId,\n });\n }\n /** Returns the message manager for a channel only if one already exists. */\n public cachedMessages(channelId: string): MessageManager | undefined {\n return this.#messageManagers.get(channelId);\n }\n public async create(\n guildId: string,\n options: ChannelCreateOptions,\n ): Promise<Channel> {\n const [payload, reason] = splitReason(options);\n return this.upsert(\n await this.#rest.post<ConstructorParameters<typeof Channel>[0]>(\n Routes.guildChannels(guildId),\n payload,\n { reason },\n ),\n );\n }\n public async edit(\n channelId: string,\n options: ChannelEditOptions,\n ): Promise<Channel> {\n const [payload, reason] = splitReason(options);\n return this.upsert(\n await this.#rest.patch<ConstructorParameters<typeof Channel>[0]>(\n Routes.channel(channelId),\n payload,\n { reason },\n ),\n );\n }\n\n /** Deletes a channel (or closes a DM). @param reason Audit-log reason. */\n public async remove(channelId: string, reason?: string): Promise<void> {\n await this.#rest.delete(Routes.channel(channelId), { reason });\n this.delete(channelId);\n }\n /** Evicts a channel, dropping its per-channel message manager with it.\n * Overrides {@link Manager.delete} so cache eviction driven by a Gateway\n * `CHANNEL_DELETE`/`THREAD_DELETE` — which calls `delete` rather than\n * {@link remove} — releases the message manager and its cached\n * messages too, instead of retaining them for the client's lifetime. */\n public override delete(channelId: string): boolean {\n this.#messageManagers.delete(channelId);\n return super.delete(channelId);\n }\n public send(\n channelId: string,\n options: MessageCreateOptions,\n ): Promise<Message> {\n return this.messages(channelId).send(options);\n }\n public async fetchMessage(\n channelId: string,\n messageId: string,\n options: MessageFetchOptions = {},\n ): Promise<Message> {\n void options;\n return this.messages(channelId).fetch(messageId);\n }\n public fetchMessages(\n channelId: string,\n query: MessageQueryOptions | Iterable<string>,\n ): Promise<Message[]> {\n if (isMessageQuery(query)) {\n const params = new URLSearchParams();\n if (query.before) params.set(\"before\", query.before);\n if (query.after) params.set(\"after\", query.after);\n if (query.around) params.set(\"around\", query.around);\n if (query.limit !== undefined)\n params.set(\"limit\", String(query.limit));\n const suffix = params.toString();\n return this.#rest\n .get<ConstructorParameters<typeof Message>[0][]>(\n `${Routes.channelMessages(channelId)}${suffix ? `?${suffix}` : \"\"}`,\n )\n .then((data) =>\n data.map((item) => this.messages(channelId).upsert(item)),\n );\n }\n return this.messages(channelId).fetchMany(query);\n }\n public upsertMessage(\n data: ConstructorParameters<typeof Message>[0],\n ): Message {\n return this.messages(data.channel_id).upsert(data);\n }\n public async editMessage(\n channelId: string,\n messageId: string,\n options: MessageEditOptions,\n ): Promise<Message> {\n return this.messages(channelId).upsert(\n await this.#rest.patch<ConstructorParameters<typeof Message>[0]>(\n Routes.message(channelId, messageId),\n toRequest(options, this.#allowedMentions),\n ),\n );\n }\n /** Deletes a message. @param reason Audit-log reason (shown when deleting someone else's message). */\n public async deleteMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void> {\n await this.#rest.delete(Routes.message(channelId, messageId), {\n reason,\n });\n this.messages(channelId).delete(messageId);\n }\n public deleteCachedMessage(channelId: string, messageId: string): boolean {\n return this.messages(channelId).delete(messageId);\n }\n public async crosspostMessage(\n channelId: string,\n messageId: string,\n ): Promise<Message> {\n return this.messages(channelId).upsert(\n await this.#rest.post<ConstructorParameters<typeof Message>[0]>(\n Routes.crosspostMessage(channelId, messageId),\n ),\n );\n }\n /** Bulk-deletes messages in a channel. Duplicate IDs are ignored and a\n * single ID falls back to a normal delete.\n * @throws {RangeError} If no IDs or more than 100 are provided, or any\n * message is older than 14 days (Discord refuses to bulk-delete those). */\n public async bulkDeleteMessages(\n channelId: string,\n messageIds: Iterable<string>,\n reason?: string,\n ): Promise<void> {\n const ids = [...new Set(messageIds)];\n if (ids.length < 1 || ids.length > 100)\n throw new RangeError(\n \"bulkDelete requires between 1 and 100 message IDs.\",\n );\n if (ids.length === 1)\n return this.deleteMessage(channelId, ids[0]!, reason);\n const cutoff = Date.now() - BULK_DELETE_MAX_AGE_MS;\n const tooOld = ids.filter((id) => snowflakeTime(id) < cutoff);\n if (tooOld.length)\n throw new RangeError(\n `bulkDelete cannot delete messages older than 14 days: ${tooOld.join(\", \")}`,\n );\n await this.#rest.post(\n Routes.channelBulkDelete(channelId),\n { messages: ids },\n { reason },\n );\n for (const id of ids) this.messages(channelId).delete(id);\n }\n /**\n * Iterates a channel's history newest-first, 100 messages per request,\n * starting before `before` (or the latest message) and stopping after\n * `limit` messages or at the start of the channel.\n */\n public async *iterateMessages(\n channelId: string,\n options: { before?: string; limit?: number } = {},\n ): AsyncGenerator<Message, void, undefined> {\n let before = options.before;\n let remaining = options.limit ?? Infinity;\n while (remaining > 0) {\n const page = await this.fetchMessages(channelId, {\n before,\n limit: Math.min(100, remaining),\n });\n for (const message of page) yield message;\n remaining -= page.length;\n if (page.length < 100) return;\n before = page.at(-1)!.id;\n }\n }\n public async addReaction(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void> {\n // Discord's create-reaction endpoint is\n // PUT .../reactions/{emoji}/@me — the bare .../reactions/{emoji} path\n // is not a valid target for PUT.\n await this.#rest.put(\n Routes.messageReactionMe(channelId, messageId, emoji),\n );\n }\n public async fetchReactions(\n channelId: string,\n messageId: string,\n emoji: string,\n options: ReactionFetchOptions = {},\n ): Promise<User[]> {\n const params = new URLSearchParams();\n if (options.limit !== undefined)\n params.set(\"limit\", String(options.limit));\n if (options.after) params.set(\"after\", options.after);\n const suffix = params.toString();\n const data = await this.#rest.get<\n ConstructorParameters<typeof User>[0][]\n >(\n `${Routes.messageReactions(channelId, messageId, emoji)}${suffix ? `?${suffix}` : \"\"}`,\n );\n return data.map((user) => new User(user));\n }\n public async removeOwnReaction(\n channelId: string,\n messageId: string,\n emoji: string,\n ): Promise<void> {\n await this.#rest.delete(\n Routes.messageReactionMe(channelId, messageId, emoji),\n );\n }\n public async removeReaction(\n channelId: string,\n messageId: string,\n emoji: string,\n userId: string,\n ): Promise<void> {\n await this.#rest.delete(\n Routes.messageReactionUser(channelId, messageId, emoji, userId),\n );\n }\n public async removeAllReactions(\n channelId: string,\n messageId: string,\n ): Promise<void> {\n await this.#rest.delete(\n Routes.messageReactionsAll(channelId, messageId),\n );\n }\n /** Fetches the newest pinned messages (one page, up to 50, like the endpoint it replaces). */\n public async fetchPinnedMessages(channelId: string): Promise<Message[]> {\n const data = await this.#rest.get<{\n items: { message: ConstructorParameters<typeof Message>[0] }[];\n }>(Routes.channelMessagesPins(channelId));\n return data.items.map((item) =>\n this.messages(channelId).upsert(item.message),\n );\n }\n /** Fetches pinned messages a page at a time, newest first (`limit` 1-50, `before` an ISO timestamp from the previous page). */\n public async fetchPins(\n channelId: string,\n options: { before?: string; limit?: number } = {},\n ): Promise<{ messages: Message[]; hasMore: boolean }> {\n const params = new URLSearchParams();\n if (options.before) params.set(\"before\", options.before);\n if (options.limit !== undefined)\n params.set(\n \"limit\",\n String(Math.min(50, Math.max(1, options.limit))),\n );\n const query = params.toString();\n const data = await this.#rest.get<{\n items: {\n pinned_at: string;\n message: ConstructorParameters<typeof Message>[0];\n }[];\n has_more: boolean;\n }>(\n `${Routes.channelMessagesPins(channelId)}${query ? `?${query}` : \"\"}`,\n );\n return {\n messages: data.items.map((item) =>\n this.messages(channelId).upsert(item.message),\n ),\n hasMore: data.has_more,\n };\n }\n /** Shows \"the bot is typing…\" for about ten seconds, or until it sends a message. */\n public async triggerTyping(channelId: string): Promise<void> {\n await this.#rest.post(Routes.channelTyping(channelId));\n }\n /** Adds a tag to a forum or media channel and returns the channel's tags. @param reason Audit-log reason. */\n public async createForumTag(\n channelId: string,\n tag: ForumTagInput,\n reason?: string,\n ): Promise<APIForumTag[]> {\n const tags = await this.#forumTags(channelId);\n return this.#saveForumTags(channelId, [...tags, tag], reason);\n }\n /** Changes a forum tag and returns the channel's tags. */\n public async editForumTag(\n channelId: string,\n tagId: string,\n changes: Partial<ForumTagInput>,\n reason?: string,\n ): Promise<APIForumTag[]> {\n const tags = await this.#forumTags(channelId);\n if (!tags.some((tag) => tag.id === tagId))\n throw new Error(`Channel ${channelId} has no tag ${tagId}.`);\n return this.#saveForumTags(\n channelId,\n tags.map((tag) =>\n tag.id === tagId ? { ...tag, ...changes } : tag,\n ),\n reason,\n );\n }\n /** Removes a forum tag and returns the channel's remaining tags. */\n public async removeForumTag(\n channelId: string,\n tagId: string,\n reason?: string,\n ): Promise<APIForumTag[]> {\n const tags = await this.#forumTags(channelId);\n if (!tags.some((tag) => tag.id === tagId))\n throw new Error(`Channel ${channelId} has no tag ${tagId}.`);\n return this.#saveForumTags(\n channelId,\n tags.filter((tag) => tag.id !== tagId),\n reason,\n );\n }\n /** The channel's current tags, read fresh so edits never clobber newer ones. */\n async #forumTags(channelId: string): Promise<APIForumTag[]> {\n const channel = await this.#rest.get<{\n available_tags?: APIForumTag[];\n }>(Routes.channel(channelId));\n return channel.available_tags ?? [];\n }\n /** Discord replaces the whole list; tags that keep their `id` are kept. */\n async #saveForumTags(\n channelId: string,\n tags: Array<ForumTagInput & { id?: string }>,\n reason?: string,\n ): Promise<APIForumTag[]> {\n const updated = await this.#rest.patch<{\n available_tags?: APIForumTag[];\n }>(Routes.channel(channelId), { available_tags: tags }, { reason });\n return updated.available_tags ?? [];\n }\n /** Pins a message. @param reason Audit-log reason. */\n public async pinMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void> {\n await this.#rest.put(\n Routes.channelMessagesPin(channelId, messageId),\n undefined,\n { reason },\n );\n }\n /** Unpins a message. @param reason Audit-log reason. */\n public async unpinMessage(\n channelId: string,\n messageId: string,\n reason?: string,\n ): Promise<void> {\n await this.#rest.delete(\n Routes.channelMessagesPin(channelId, messageId),\n { reason },\n );\n }\n /** Creates a webhook in a channel. @param options Name, optional avatar data URI, and audit-log `reason`. */\n public async createWebhook(\n channelId: string,\n options: { name: string; avatar?: string | null; reason?: string },\n ): Promise<import(\"@lunibee/types\").APIWebhook> {\n const [payload, reason] = splitReason(options);\n return this.#rest.post(Routes.channelWebhooks(channelId), payload, {\n reason,\n });\n }\n public createThreadFromMessage(\n channelId: string,\n messageId: string,\n options: MessageThreadOptions,\n ): Promise<Channel> {\n return this.threads(channelId).createFromMessage(messageId, options);\n }\n /**\n * Fetches a page of messages with cursor metadata.\n * @param channelId Channel to fetch from.\n * @param options Page options — `before`, `after`, `around`, and `limit` (max 100).\n * @returns `{ messages, before, after, hasMore }` — use `before` or `after` as cursors for the next page.\n */\n public async fetchPage(\n channelId: string,\n options: MessageQueryOptions = {},\n ): Promise<{\n messages: Message[];\n before?: string;\n after?: string;\n hasMore: boolean;\n }> {\n const limit = Math.min(100, Math.max(1, options.limit ?? 50));\n const messages = await this.fetchMessages(channelId, {\n ...options,\n limit,\n });\n return {\n messages,\n before: messages[0]?.id,\n after: messages[messages.length - 1]?.id,\n hasMore: messages.length === limit,\n };\n }\n public override clear(): void {\n this.#messageManagers.clear();\n super.clear();\n }\n}\n\nfunction isMessageQuery(\n value: MessageQueryOptions | Iterable<string>,\n): value is MessageQueryOptions {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !(Symbol.iterator in value)\n );\n}\nexport type CreateMessageOptions = MessageCreateOptions;\nexport {\n MessageManager,\n toRequest,\n type MessageCacheOptions,\n type MessageFile,\n} from \"./message.js\";\nexport { ThreadManager } from \"./thread.js\";\nexport {\n RoleManager,\n type RoleCreateOptions,\n type RoleEditOptions,\n} from \"./role.js\";\nexport {\n GuildMemberManager,\n type MemberEditOptions,\n type BanOptions,\n} from \"./member.js\";\nexport { ApplicationCommandManager } from \"./application.js\";\nexport {\n GuildBanManager,\n GuildScheduledEventManager,\n StageInstanceManager,\n PermissionOverwriteManager,\n type APIBan,\n type GuildBanCreateOptions,\n type GuildScheduledEventOptions,\n type StageInstanceCreateOptions,\n type PermissionOverwriteOptions,\n type PermissionOverwriteTargetType,\n type PermissionOverwriteUpdate,\n} from \"./guild-resources.js\";\nexport {\n EmojiManager,\n type EmojiCreateOptions,\n type EmojiEditOptions,\n} from \"./emoji.js\";\nexport {\n GuildStickerManager,\n GuildSoundboardManager,\n MonetizationManager,\n ApplicationEmojiManager,\n type APIEntitlement,\n type APISKU,\n type APISoundboardSound,\n type APISubscription,\n type EntitlementQuery,\n type GuildStickerCreateOptions,\n type SoundboardSoundCreateOptions,\n} from \"./advanced.js\";\n",
11
16
  "/**\n * Discord Gateway close codes.\n *\n * Discord.js-familiar names and numeric values, matching the Discord Gateway\n * protocol. Exposed so consumers can branch on named codes instead of magic\n * numbers; {@link Gateway} uses them internally to decide resume/identify/stop.\n */\nexport const GatewayCloseCodes = {\n UnknownError: 4000,\n UnknownOpcode: 4001,\n DecodeError: 4002,\n NotAuthenticated: 4003,\n AuthenticationFailed: 4004,\n AlreadyAuthenticated: 4005,\n InvalidSeq: 4007,\n RateLimited: 4008,\n SessionTimedOut: 4009,\n InvalidShard: 4010,\n ShardingRequired: 4011,\n InvalidAPIVersion: 4012,\n InvalidIntents: 4013,\n DisallowedIntents: 4014,\n} as const;\n",
12
- "/**\n * Reconnect policy and scheduling for one Gateway connection.\n *\n * Owns how a close code is classified, whether another attempt is allowed, how\n * long to wait, and the coordination that keeps at most one logical connection\n * attempt in flight. It owns no socket, no session state, no heartbeat and no\n * event emission: it is told a close code and whether a resume is possible, and\n * answers with a decision.\n */\nimport { GatewayCloseCodes } from \"./close-codes.js\";\n\n/** What a closed connection should do next. */\nexport type CloseAction =\n /** Reconnect and RESUME the existing session. */\n | \"resume\"\n /** Reconnect, but IDENTIFY afresh: the session cannot be resumed. */\n | \"identify\"\n /** Do not reconnect; the condition will not fix itself. */\n | \"stop\";\n\n/**\n * Close codes that no reconnect can recover from: bad token, bad shard\n * configuration, bad API version, or intents the application is not approved\n * for. Retrying these hammers Discord with a request that cannot succeed.\n */\nexport const FATAL_CLOSE_CODES: readonly number[] = [\n GatewayCloseCodes.AuthenticationFailed,\n GatewayCloseCodes.InvalidShard,\n GatewayCloseCodes.ShardingRequired,\n GatewayCloseCodes.InvalidAPIVersion,\n GatewayCloseCodes.InvalidIntents,\n GatewayCloseCodes.DisallowedIntents,\n];\n\n/**\n * Close codes that keep the connection recoverable but destroy the session, so\n * the next connection must IDENTIFY rather than RESUME.\n */\nexport const IDENTIFY_CLOSE_CODES: readonly number[] = [\n GatewayCloseCodes.InvalidSeq,\n GatewayCloseCodes.SessionTimedOut,\n];\n\n/**\n * Classifies a close code.\n *\n * Any code outside the two tables above is **reconnectable**: transport-level\n * closes (`1006`), server restarts (`1001`), Discord's own `4000`, and the\n * `1000` the Gateway itself sends after a non-resumable `op 9` all belong here.\n * Whether that reconnect resumes or identifies is not a property of the code —\n * it is whether a session survives, which is why `canResume` is a parameter\n * rather than something this module works out for itself.\n *\n * @param code WebSocket close code.\n * @param canResume Whether the session can still be resumed.\n */\nexport function classifyCloseCode(\n code: number,\n canResume: boolean,\n): CloseAction {\n if (FATAL_CLOSE_CODES.includes(code)) return \"stop\";\n if (IDENTIFY_CLOSE_CODES.includes(code)) return \"identify\";\n return canResume ? \"resume\" : \"identify\";\n}\n\n/** Why a reconnect was not scheduled. */\nexport type ScheduleRefusal =\n /** Automatic reconnect is disabled for this Gateway. */\n | \"disabled\"\n /** A reconnect is already armed; a second would open a second socket. */\n | \"pending\"\n /** The attempt budget is spent. */\n | \"exhausted\";\n\n/** Outcome of asking for a reconnect. */\nexport type ScheduleResult =\n | { scheduled: true; delayMs: number; attempt: number }\n | { scheduled: false; reason: ScheduleRefusal };\n\n/** Configuration for {@link GatewayReconnect}. */\nexport interface ReconnectOptions {\n /** Whether automatic reconnect is permitted at all. */\n enabled: boolean;\n /** Maximum consecutive attempts before giving up. */\n maxAttempts: number;\n /** Delay for the first attempt, doubled per attempt. */\n baseDelay: number;\n /** Ceiling for the backoff. */\n maxDelay: number;\n /** Randomness source for jitter; injected in tests. */\n random?: () => number;\n}\n\n/** Reconnect scheduling, backoff and attempt coordination. */\nexport class GatewayReconnect {\n readonly #options: ReconnectOptions;\n readonly #random: () => number;\n #attempt = 0;\n #timer?: ReturnType<typeof setTimeout>;\n #promise?: Promise<void>;\n #resolve?: () => void;\n #reject?: (error: Error) => void;\n\n public constructor(options: ReconnectOptions) {\n this.#options = options;\n this.#random = options.random ?? Math.random;\n }\n\n /** Whether automatic reconnect is permitted. */\n public get enabled(): boolean {\n return this.#options.enabled;\n }\n\n /** Consecutive attempts made since the last {@link reset}. */\n public get attempts(): number {\n return this.#attempt;\n }\n\n /** Whether a reconnect timer is currently armed. */\n public get pending(): boolean {\n return this.#timer !== undefined;\n }\n\n /** Whether the attempt budget is spent. */\n public get exhausted(): boolean {\n return this.#attempt >= this.#options.maxAttempts;\n }\n\n /** Whether a connection attempt is currently in flight. */\n public get connecting(): boolean {\n return this.#promise !== undefined;\n }\n\n /** The in-flight attempt, or undefined when none is active. */\n public get attemptPromise(): Promise<void> | undefined {\n return this.#promise;\n }\n\n /** Classifies a close code against this Gateway's policy. */\n public classifyClose(code: number, canResume: boolean): CloseAction {\n return classifyCloseCode(code, canResume);\n }\n\n /** Whether another reconnect is currently allowed. */\n public canReconnect(): boolean {\n return this.#options.enabled && !this.exhausted;\n }\n\n /**\n * Arms a reconnect, unless one is already armed or no attempt is allowed.\n *\n * Refusing while `pending` is what keeps repeated closes from stacking\n * timers: several closes in a row produce one reconnect, not several\n * competing sockets.\n */\n public schedule(run: () => void): ScheduleResult {\n if (!this.#options.enabled)\n return { scheduled: false, reason: \"disabled\" };\n if (this.#timer) return { scheduled: false, reason: \"pending\" };\n if (this.exhausted) return { scheduled: false, reason: \"exhausted\" };\n\n const attempt = this.#attempt;\n const delay = Math.min(\n this.#options.maxDelay,\n this.#options.baseDelay * 2 ** this.#attempt++,\n );\n // Jitter must scale with the delay: a fixed ceiling would reconnect\n // every shard inside the same narrow window after a gateway-wide\n // restart, which is exactly when decorrelation matters.\n const jitter = this.#random() * Math.max(1, delay * 0.25);\n const delayMs = delay + jitter;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n run();\n }, delayMs);\n return { scheduled: true, delayMs, attempt };\n }\n\n /** Cancels an armed reconnect. Safe to call when none is armed. */\n public cancel(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n }\n\n /** Clears the attempt counter after a connection succeeds. */\n public reset(): void {\n this.#attempt = 0;\n }\n\n /**\n * Coordinates one logical connection attempt.\n *\n * Callers that ask while an attempt is in flight join it instead of\n * starting a second: three `connect()` calls produce one socket attempt and\n * one shared promise.\n *\n * @param start Invoked exactly once, when this call begins a new attempt.\n */\n public attempt(start: () => void): Promise<void> {\n if (this.#promise) return this.#promise;\n this.#promise = new Promise<void>((resolve, reject) => {\n this.#resolve = resolve;\n this.#reject = reject;\n start();\n });\n return this.#promise;\n }\n\n /** Settles the in-flight attempt, resolving it or rejecting with `error`. */\n public settle(error?: Error): void {\n const resolve = this.#resolve;\n const reject = this.#reject;\n this.#resolve = undefined;\n this.#reject = undefined;\n this.#promise = undefined;\n if (error) reject?.(error);\n else resolve?.();\n }\n}\n",
13
- "import { BaseStructure, Channel, User, CDN_BASE, cdnURL } from \"./base.js\";\nimport { PermissionsBitField } from \"@lunibee/core\";\nimport type { ImageURLOptions, ResourceContext } from \"./base.js\";\n\n/** Parses a Discord ISO timestamp into a Date, returning null for absent or invalid values. */\nfunction toDateOrNull(value?: string | null): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n// ─── GuildMember ───────────────────────────────────────────────────────────────\n\n/** A Discord guild member. */\nexport class GuildMember {\n /** User represented by the member. */ public readonly user: User;\n /** Guild containing the member. */ public readonly guildId: string;\n /** Nickname, if configured. */ public nickname: string | null;\n /** Role IDs assigned to the member. */ public readonly roleIds: string[];\n /** Whether the member is pending membership screening. */ public pending: boolean;\n /** Member join timestamp. */ public joinedAt?: Date;\n /** Member-specific avatar hash, if set. */ public avatarHash:\n string | null;\n /** When the member started boosting the guild. */ public premiumSince: Date | null;\n /** When the member's timeout expires (null if not timed out). */ public timedOutUntil: Date | null;\n /** Member flags bitfield. */ public flags: number;\n /** Permissions Discord sent with the member (interactions only). */\n readonly #suppliedPermissions?: PermissionsBitField;\n readonly #context?: ResourceContext;\n\n /** Creates a guild member from Discord data. @param data Discord guild-member payload. @throws {TypeError} If the guild ID is invalid. @throws {RangeError} If joined_at is invalid. */\n public constructor(\n data: {\n user: {\n id: string;\n username: string;\n global_name?: string | null;\n avatar?: string | null;\n bot?: boolean;\n system?: boolean;\n public_flags?: number;\n discriminator?: string;\n };\n guild_id: string;\n nick?: string | null;\n roles?: string[];\n pending?: boolean;\n joined_at?: string;\n permissions?: string;\n avatar?: string | null;\n premium_since?: string | null;\n communication_disabled_until?: string | null;\n flags?: number;\n },\n context?: ResourceContext,\n ) {\n this.user = new User(data.user);\n this.#context = context;\n if (!/^\\d{1,20}$/.test(data.guild_id))\n throw new TypeError(\"Member guild_id must be a valid snowflake.\");\n this.guildId = data.guild_id;\n this.nickname = data.nick ?? null;\n this.roleIds = [...(data.roles ?? [])];\n this.pending = data.pending ?? false;\n this.joinedAt = data.joined_at ? new Date(data.joined_at) : undefined;\n if (this.joinedAt?.toString() === \"Invalid Date\")\n throw new RangeError(\"Member joined_at must be a valid date.\");\n if (data.permissions !== undefined)\n this.#suppliedPermissions = new PermissionsBitField(\n data.permissions,\n );\n this.avatarHash = data.avatar ?? null;\n // Like joinedAt, coerce malformed timestamps to null instead of an Invalid Date.\n this.premiumSince = toDateOrNull(data.premium_since);\n this.timedOutUntil = toDateOrNull(data.communication_disabled_until);\n this.flags = data.flags ?? 0;\n }\n\n /**\n * The member's permissions. Discord sends them with interactions (already\n * resolved for the channel); anywhere else they are computed at guild\n * level from the cached roles each time they are read, so they follow role\n * changes. Empty when the guild's roles are not cached.\n */\n public get permissions(): PermissionsBitField {\n if (this.#suppliedPermissions) return this.#suppliedPermissions;\n return new PermissionsBitField(\n this.#context?.memberPermissions?.(\n this.guildId,\n this.user.id,\n this.roleIds,\n ) ?? 0n,\n );\n }\n\n /** The member's permissions in a channel, with its overwrites. Null when the channel or guild is not cached. @param channelId Channel ID. */\n public permissionsIn(channelId: string): PermissionsBitField | null {\n const computed = this.#context?.memberPermissions?.(\n this.guildId,\n this.user.id,\n this.roleIds,\n channelId,\n );\n return computed ? new PermissionsBitField(computed) : null;\n }\n\n #action<K extends keyof ResourceContext>(\n name: K,\n ): NonNullable<ResourceContext[K]> {\n const action = this.#context?.[name];\n if (!action)\n throw new Error(\"This member is not attached to a client.\");\n return action as NonNullable<ResourceContext[K]>;\n }\n\n /** Kicks this member. @param reason Audit-log reason. */\n public kick(reason?: string): Promise<void> {\n return this.#action(\"kickMember\")(this.guildId, this.user.id, reason);\n }\n\n /** Bans this member. @param options Audit-log reason and seconds of messages to delete. */\n public ban(\n options: { reason?: string; deleteMessageSeconds?: number } = {},\n ): Promise<void> {\n return this.#action(\"banMember\")(this.guildId, this.user.id, options);\n }\n\n /** Edits this member (nickname, roles, voice state, timeout). @param options Discord member fields. @param reason Audit-log reason. */\n public edit(\n options: Record<string, unknown>,\n reason?: string,\n ): Promise<GuildMember> {\n return this.#action(\"editMember\")(\n this.guildId,\n this.user.id,\n options,\n reason,\n );\n }\n\n /** Times this member out, or clears the timeout with null. @param milliseconds Timeout length (Discord allows up to 28 days). @param reason Audit-log reason. */\n public timeout(\n milliseconds: number | null,\n reason?: string,\n ): Promise<GuildMember> {\n if (milliseconds !== null && !(milliseconds > 0))\n throw new RangeError(\n \"Timeout length must be a positive number of milliseconds.\",\n );\n return this.edit(\n {\n communication_disabled_until:\n milliseconds === null\n ? null\n : new Date(Date.now() + milliseconds).toISOString(),\n },\n reason,\n );\n }\n\n /** Sets or clears (null) this member's nickname. @param nickname New nickname. @param reason Audit-log reason. */\n public setNickname(\n nickname: string | null,\n reason?: string,\n ): Promise<GuildMember> {\n return this.edit({ nick: nickname }, reason);\n }\n\n /** Gives this member a role. @param roleId Role ID. @param reason Audit-log reason. */\n public addRole(roleId: string, reason?: string): Promise<void> {\n return this.#action(\"addMemberRole\")(\n this.guildId,\n this.user.id,\n roleId,\n reason,\n );\n }\n\n /** Takes a role from this member. @param roleId Role ID. @param reason Audit-log reason. */\n public removeRole(roleId: string, reason?: string): Promise<void> {\n return this.#action(\"removeMemberRole\")(\n this.guildId,\n this.user.id,\n roleId,\n reason,\n );\n }\n\n /** Effective member display name — nickname, falling back to user display name. */\n public get displayName(): string {\n return this.nickname ?? this.user.displayName;\n }\n\n /** Whether this member is currently timed out. */\n public get isTimedOut(): boolean {\n return this.timedOutUntil !== null && this.timedOutUntil > new Date();\n }\n\n /** Returns the member-specific avatar URL, falling back to the user's avatar, or null if none. */\n public avatarURL(options: ImageURLOptions = {}): string | null {\n if (this.avatarHash)\n return cdnURL(\n `/guilds/${this.guildId}/users/${this.user.id}/avatars`,\n this.avatarHash,\n options,\n );\n // User always exposes avatarURL(); returns null when the user has no avatar.\n return this.user.avatarURL(options);\n }\n\n /** Returns the resolved avatar URL — member avatar, user avatar, or default. */\n public displayAvatarURL(options: ImageURLOptions = {}): string {\n return this.avatarURL(options) ?? this.user.displayAvatarURL(options);\n }\n\n /** Returns the Discord user mention for this member. */\n public toString(): string {\n return this.user.toString();\n }\n}\n\n// ─── Role ──────────────────────────────────────────────────────────────────────\n\n/** A Discord guild role. */\nexport class Role extends BaseStructure {\n /** Role name. */ public name: string;\n /** Role color as a 24-bit RGB integer. */ public color: number;\n /** Whether the role is hoisted. */ public hoist: boolean;\n /** Permission bitfield. */ public permissions: PermissionsBitField;\n /** Whether the role is managed by an integration. */ public managed: boolean;\n /** Whether the role is mentionable. */ public mentionable: boolean;\n /** Role position in the hierarchy. */ public position: number;\n /** Unicode emoji used as the role icon, if any. */ public unicodeEmoji:\n string | null;\n /** Hash of the role's custom icon image, if any. */ public iconHash:\n string | null;\n /** Role tags metadata (bot, premium subscriber, etc). */ public tags: Record<\n string,\n unknown\n > | null;\n\n /** Creates a role from Discord data. @param data Discord role payload. */\n public constructor(data: {\n id: string;\n name: string;\n color?: number;\n hoist?: boolean;\n permissions?: string;\n managed?: boolean;\n mentionable?: boolean;\n position?: number;\n unicode_emoji?: string | null;\n icon?: string | null;\n tags?: Record<string, unknown> | null;\n }) {\n super(data.id);\n if (!data.name) throw new TypeError(\"Role name cannot be empty.\");\n this.name = data.name;\n this.color = data.color ?? 0;\n this.hoist = data.hoist ?? false;\n this.permissions = new PermissionsBitField(data.permissions ?? 0n);\n this.managed = data.managed ?? false;\n this.mentionable = data.mentionable ?? false;\n this.position = data.position ?? 0;\n this.unicodeEmoji = data.unicode_emoji ?? null;\n this.iconHash = data.icon ?? null;\n this.tags = data.tags ?? null;\n }\n\n /** Returns the role's color as a `#RRGGBB` hex string. Returns `#000000` for colorless roles. */\n public get colorHex(): string {\n return `#${this.color.toString(16).padStart(6, \"0\").toUpperCase()}`;\n }\n\n /** Returns the role's custom icon URL, or null if the role has no icon. */\n public iconURL(options: ImageURLOptions = {}): string | null {\n if (!this.iconHash) return null;\n return cdnURL(`/role-icons/${this.id}`, this.iconHash, options);\n }\n\n /** Whether this is the `@everyone` base role (its ID equals the guild ID). */\n public isEveryone(guildId: string): boolean {\n return this.id === guildId;\n }\n\n /** Discord role mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<@&${this.id}>`;\n }\n}\n\n// ─── TextChannel ──────────────────────────────────────────────────────────────\n\n/** A Discord text-capable channel. */\nexport class TextChannel extends Channel {\n /** Creates a text channel from Discord data. @param data Discord channel payload. */\n public constructor(\n data: {\n id: string;\n type: number;\n name?: string | null;\n parent_id?: string | null;\n guild_id?: string;\n } & Partial<import(\"@lunibee/types\").APIChannel>,\n context?: import(\"./base.js\").ResourceContext,\n ) {\n super(data, context);\n }\n /** Discord channel mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<#${this.id}>`;\n }\n}\n\n// ─── Invite ───────────────────────────────────────────────────────────────────\n\n/** A Discord invite link and its metadata. */\nexport class Invite {\n /** Invite code (the unique part of the URL). */ public readonly code: string;\n /** Guild this invite belongs to, if any. */ public readonly guildId:\n string | null;\n /** Channel this invite points to, if any. */ public readonly channelId:\n string | null;\n /** User who created the invite, if available. */ public readonly inviter: User | null;\n /** Number of times the invite has been used. */ public uses: number;\n /** Maximum number of uses (0 = unlimited). */ public maxUses: number;\n /** Duration in seconds until the invite expires (0 = never). */ public maxAge: number;\n /** Whether the invite is temporary (kicks uninducted members on disconnect). */ public temporary: boolean;\n /** When the invite was created. */ public readonly createdAt: Date | null;\n /** When the invite expires, or null if it never expires. */ public readonly expiresAt: Date | null;\n\n /** Creates an invite from Discord data. */\n public constructor(data: {\n code: string;\n guild?: { id: string } | null;\n channel?: { id: string } | null;\n inviter?: {\n id: string;\n username: string;\n global_name?: string | null;\n avatar?: string | null;\n bot?: boolean;\n system?: boolean;\n public_flags?: number;\n discriminator?: string;\n } | null;\n uses?: number;\n max_uses?: number;\n max_age?: number;\n temporary?: boolean;\n created_at?: string | null;\n expires_at?: string | null;\n }) {\n if (!data.code) throw new TypeError(\"An invite requires a code.\");\n this.code = data.code;\n this.guildId = data.guild?.id ?? null;\n this.channelId = data.channel?.id ?? null;\n this.inviter = data.inviter ? new User(data.inviter) : null;\n this.uses = data.uses ?? 0;\n this.maxUses = data.max_uses ?? 0;\n this.maxAge = data.max_age ?? 0;\n this.temporary = data.temporary ?? false;\n this.createdAt = data.created_at ? new Date(data.created_at) : null;\n this.expiresAt = data.expires_at ? new Date(data.expires_at) : null;\n }\n\n /** The full invite URL. */\n public get url(): string {\n return `https://discord.gg/${this.code}`;\n }\n\n /** Returns the invite URL. Used automatically in template literals. */\n public toString(): string {\n return this.url;\n }\n}\n\n// ─── Webhook ──────────────────────────────────────────────────────────────────\n\n/** Webhook type constants. */\nexport const WebhookEnum = {\n Incoming: 1,\n ChannelFollower: 2,\n Application: 3,\n} as const;\n/** One {@link WebhookEnum} value, usable as a type. */\nexport type WebhookEnum = (typeof WebhookEnum)[keyof typeof WebhookEnum];\n\n/** A Discord webhook — an HTTP endpoint that can post messages to a channel. */\nexport class Webhook extends BaseStructure {\n /** Webhook type. */ public readonly type: number;\n /** Webhook display name. */ public name: string | null;\n /** Webhook avatar hash. */ public avatarHash: string | null;\n /** Channel this webhook posts to. */ public readonly channelId:\n string | null;\n /** Guild this webhook belongs to. */ public readonly guildId:\n string | null;\n /** Application that created this webhook, if any. */ public readonly applicationId:\n string | null;\n /** Webhook token (only present for incoming webhooks). */ public readonly token:\n string | null;\n\n /** Creates a webhook from Discord data. */\n public constructor(data: {\n id: string;\n type?: number;\n name?: string | null;\n avatar?: string | null;\n channel_id?: string | null;\n guild_id?: string | null;\n application_id?: string | null;\n token?: string;\n }) {\n super(data.id);\n this.type = data.type ?? WebhookEnum.Incoming;\n this.name = data.name ?? null;\n this.avatarHash = data.avatar ?? null;\n this.channelId = data.channel_id ?? null;\n this.guildId = data.guild_id ?? null;\n this.applicationId = data.application_id ?? null;\n this.token = data.token ?? null;\n }\n\n /** Returns the webhook avatar URL, or null if no avatar is set. */\n public avatarURL(options: ImageURLOptions = {}): string | null {\n if (!this.avatarHash) return null;\n return cdnURL(`/avatars/${this.id}`, this.avatarHash, options);\n }\n\n /** Returns the webhook execution URL, or null if no token is set. */\n public get url(): string | null {\n return this.token\n ? `https://discord.com/api/webhooks/${this.id}/${this.token}`\n : null;\n }\n\n /** Returns the webhook URL or its ID as a string. */\n public override toString(): string {\n return this.url ?? this.id;\n }\n}\n\n// ─── Emoji ────────────────────────────────────────────────────────────────────\n\n/** A Discord emoji. */\nexport class Emoji extends BaseStructure {\n /** Emoji name. */ public name: string | null;\n /** Roles allowed to use this emoji. */ public roleIds: string[];\n /** User that created this emoji. */ public user: User | null;\n /** Whether this emoji must be wrapped in colons. */ public requireColons: boolean;\n /** Whether this emoji is managed. */ public managed: boolean;\n /** Whether this emoji is animated. */ public animated: boolean;\n /** Whether this emoji can be used, may be false due to loss of Server Boosts. */ public available: boolean;\n\n /** Creates an emoji from Discord data. */\n public constructor(data: {\n id: string | null;\n name: string | null;\n roles?: string[];\n user?: import(\"@lunibee/types\").UserData;\n require_colons?: boolean;\n managed?: boolean;\n animated?: boolean;\n available?: boolean;\n }) {\n // Unicode emoji have no snowflake: pass the base check with a\n // placeholder, then expose the documented \"unicode\" sentinel id.\n super(data.id ?? \"0\");\n if (data.id === null) (this as { id: string }).id = \"unicode\";\n this.name = data.name;\n this.roleIds = data.roles ?? [];\n this.user = data.user ? new User(data.user) : null;\n this.requireColons = data.require_colons ?? false;\n this.managed = data.managed ?? false;\n this.animated = data.animated ?? false;\n this.available = data.available ?? true;\n }\n\n /** Returns the URL for this emoji if it is custom, or null for unicode emojis. */\n public url(options: ImageURLOptions = {}): string | null {\n if (!this.id || this.id === \"unicode\") return null;\n const ext = options.extension ?? (this.animated ? \"gif\" : \"png\");\n const size = options.size ? `?size=${options.size}` : \"\";\n return `${CDN_BASE}/emojis/${this.id}.${ext}${size}`;\n }\n\n /** Returns the text required to render this emoji in Discord. */\n public override toString(): string {\n return this.id !== \"unicode\"\n ? `<${this.animated ? \"a\" : \"\"}:${this.name}:${this.id}>`\n : (this.name ?? \"\");\n }\n}\n\n// --- AutoModerationRule --------------------------------------------------------\n\n/** A Discord AutoModeration Rule. */\nexport class AutoModerationRule extends BaseStructure {\n public guildId: string;\n public name: string;\n public creatorId: string;\n public eventType: number;\n public triggerType: number;\n public triggerMetadata: Record<string, unknown>;\n public actions: import(\"@lunibee/types\").APIAutoModerationAction[];\n public enabled: boolean;\n public exemptRoles: string[];\n public exemptChannels: string[];\n\n /** Creates an auto moderation rule from Discord data. */\n public constructor(data: import(\"@lunibee/types\").APIAutoModerationRule) {\n super(data.id);\n if (!/^\\d{1,20}$/.test(data.guild_id))\n throw new TypeError(\n \"AutoModerationRule guild_id must be a valid snowflake.\",\n );\n this.guildId = data.guild_id;\n this.name = data.name;\n this.creatorId = data.creator_id;\n this.eventType = data.event_type;\n this.triggerType = data.trigger_type;\n this.triggerMetadata = data.trigger_metadata;\n this.actions = data.actions;\n this.enabled = data.enabled;\n this.exemptRoles = data.exempt_roles;\n this.exemptChannels = data.exempt_channels;\n }\n\n public toJSON(): Record<string, unknown> {\n return {\n id: this.id,\n guildId: this.guildId,\n name: this.name,\n creatorId: this.creatorId,\n eventType: this.eventType,\n triggerType: this.triggerType,\n triggerMetadata: this.triggerMetadata,\n actions: this.actions,\n enabled: this.enabled,\n exemptRoles: this.exemptRoles,\n exemptChannels: this.exemptChannels,\n };\n }\n}\n\n// --- Welcome Screen -----------------------------------------------------------\n\n/** A channel listed in a guild's Welcome Screen. */\nexport class WelcomeScreenChannel {\n public channelId: string;\n public description: string;\n public emojiId: string | null;\n public emojiName: string | null;\n\n public constructor(data: import(\"@lunibee/types\").APIWelcomeScreenChannel) {\n this.channelId = data.channel_id;\n this.description = data.description;\n this.emojiId = data.emoji_id;\n this.emojiName = data.emoji_name;\n }\n}\n\n/** A Discord Guild Welcome Screen. */\nexport class GuildWelcomeScreen {\n public description: string | null;\n public channels: WelcomeScreenChannel[];\n\n public constructor(data: import(\"@lunibee/types\").APIGuildWelcomeScreen) {\n this.description = data.description;\n this.channels = data.welcome_channels.map(\n (c) => new WelcomeScreenChannel(c),\n );\n }\n}\n\n// --- Guild Onboarding ---------------------------------------------------------\n\n/** An option within a Guild Onboarding Prompt. */\nexport class OnboardingPromptOption extends BaseStructure {\n public channelIds: string[];\n public roleIds: string[];\n public emoji: import(\"@lunibee/types\").APIPartialEmoji | undefined;\n public title: string;\n public description: string | null;\n\n public constructor(\n data: import(\"@lunibee/types\").APIOnboardingPromptOption,\n ) {\n super(data.id);\n this.channelIds = data.channel_ids;\n this.roleIds = data.role_ids;\n this.emoji = data.emoji;\n this.title = data.title;\n this.description = data.description;\n }\n}\n\n/** A prompt shown during Guild Onboarding. */\nexport class OnboardingPrompt extends BaseStructure {\n public type: number;\n public options: OnboardingPromptOption[];\n public title: string;\n public singleSelect: boolean;\n public required: boolean;\n public inOnboarding: boolean;\n\n public constructor(data: import(\"@lunibee/types\").APIOnboardingPrompt) {\n super(data.id);\n this.type = data.type;\n this.options = data.options.map((o) => new OnboardingPromptOption(o));\n this.title = data.title;\n this.singleSelect = data.single_select;\n this.required = data.required;\n this.inOnboarding = data.in_onboarding;\n }\n}\n\n/** A Discord Guild Onboarding setup. */\nexport class GuildOnboarding extends BaseStructure {\n public prompts: OnboardingPrompt[];\n public defaultChannelIds: string[];\n public enabled: boolean;\n public mode: number;\n\n public constructor(data: import(\"@lunibee/types\").APIGuildOnboarding) {\n super(data.guild_id);\n this.prompts = data.prompts.map((p) => new OnboardingPrompt(p));\n this.defaultChannelIds = data.default_channel_ids;\n this.enabled = data.enabled;\n this.mode = data.mode;\n }\n}\n\n/** @deprecated Use {@link WebhookEnum}. Removed in 0.3.0. */\nexport const WebhookType = WebhookEnum;\n/** @deprecated Use {@link WebhookEnum}. Removed in 0.3.0. */\nexport type WebhookType = WebhookEnum;\n",
14
- "import { Channel, User, type ResourceContext } from \"./base.js\";\nimport { TextChannel } from \"./resources.js\";\nimport type {\n APIChannel,\n APIForumTag,\n APIPartialEmoji,\n APIThreadMetadata,\n} from \"@lunibee/types\";\n\n// Discord.js-familiar channel subclasses. Every class extends Channel, so\n// existing `instanceof Channel` checks and Channel methods keep working.\n\n/** A guild announcement (news) channel. */\nexport class NewsChannel extends TextChannel {}\n\n/** A direct-message or group DM channel. */\nexport class DMChannel extends Channel {\n /** Users in the conversation. */ public readonly recipients: User[];\n /** Owner of a group DM. */ public readonly ownerId: string | null;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.recipients = (data.recipients ?? []).map((u) => new User(u));\n this.ownerId = data.owner_id ?? null;\n }\n}\n\n/** A guild voice channel. */\nexport class VoiceChannel extends Channel {\n /** Bitrate in bits per second. */ public bitrate: number;\n /** User limit (0 = unlimited). */ public userLimit: number;\n /** Voice region override, or null for automatic. */ public rtcRegion:\n string | null;\n /** Camera video quality mode. */ public videoQualityMode: number;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.bitrate = data.bitrate ?? 64000;\n this.userLimit = data.user_limit ?? 0;\n this.rtcRegion = data.rtc_region ?? null;\n this.videoQualityMode = data.video_quality_mode ?? 1;\n }\n}\n\n/** A guild stage channel. */\nexport class StageChannel extends VoiceChannel {}\n\n/** A guild category. */\nexport class CategoryChannel extends Channel {}\n\n/** A thread (announcement, public or private). */\nexport class ThreadChannel extends Channel {\n /** User who created the thread. */ public readonly ownerId: string | null;\n /** Approximate message count. */ public messageCount: number;\n /** Approximate member count (stops counting at 50). */ public memberCount: number;\n /** Thread metadata. */ public metadata: APIThreadMetadata | null;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.ownerId = data.owner_id ?? null;\n this.messageCount = data.message_count ?? 0;\n this.memberCount = data.member_count ?? 0;\n this.metadata = data.thread_metadata ?? null;\n }\n\n /** Whether the thread is archived. */\n public get archived(): boolean {\n return this.metadata?.archived ?? false;\n }\n\n /** Whether the thread is locked. */\n public get locked(): boolean {\n return this.metadata?.locked ?? false;\n }\n\n /** Minutes of inactivity before the thread auto-archives. */\n public get autoArchiveDuration(): number | null {\n return this.metadata?.auto_archive_duration ?? null;\n }\n}\n\n/** A guild forum channel. */\nexport class ForumChannel extends Channel {\n /** Tags that threads can apply. */ public availableTags: APIForumTag[];\n /** Default reaction for new threads. */ public defaultReactionEmoji: APIPartialEmoji | null;\n /** Default slowmode for new threads. */ public defaultThreadRateLimitPerUser: number;\n /** Default auto-archive duration for new threads. */ public defaultAutoArchiveDuration:\n number | null;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.availableTags = data.available_tags ?? [];\n this.defaultReactionEmoji = data.default_reaction_emoji ?? null;\n this.defaultThreadRateLimitPerUser =\n data.default_thread_rate_limit_per_user ?? 0;\n this.defaultAutoArchiveDuration =\n data.default_auto_archive_duration ?? null;\n }\n}\n\n/** A guild media channel. */\nexport class MediaChannel extends ForumChannel {}\n\n/**\n * Builds the most specific channel class for a payload's `type`, falling back\n * to {@link Channel} for types without a dedicated class.\n */\nexport function createChannel(\n data: APIChannel,\n context?: ResourceContext,\n): Channel {\n switch (data.type) {\n case 0:\n return new TextChannel(data, context);\n case 1:\n case 3:\n return new DMChannel(data, context);\n case 2:\n return new VoiceChannel(data, context);\n case 4:\n return new CategoryChannel(data, context);\n case 5:\n return new NewsChannel(data, context);\n case 10:\n case 11:\n case 12:\n return new ThreadChannel(data, context);\n case 13:\n return new StageChannel(data, context);\n case 15:\n return new ForumChannel(data, context);\n case 16:\n return new MediaChannel(data, context);\n default:\n return new Channel(data, context);\n }\n}\n",
17
+ "/**\n * Reconnect policy and scheduling for one Gateway connection.\n *\n * Owns how a close code is classified, whether another attempt is allowed, how\n * long to wait, and the coordination that keeps at most one logical connection\n * attempt in flight. It owns no socket, no session state, no heartbeat and no\n * event emission: it is told a close code and whether a resume is possible, and\n * answers with a decision.\n */\nimport { GatewayCloseCodes } from \"./close-codes.js\";\n\n/** What a closed connection should do next. */\nexport type CloseAction =\n /** Reconnect and RESUME the existing session. */\n | \"resume\"\n /** Reconnect, but IDENTIFY afresh: the session cannot be resumed. */\n | \"identify\"\n /** Do not reconnect; the condition will not fix itself. */\n | \"stop\";\n\n/**\n * Close codes that no reconnect can recover from: bad token, bad shard\n * configuration, bad API version, or intents the application is not approved\n * for. Retrying these hammers Discord with a request that cannot succeed.\n */\nexport const FATAL_CLOSE_CODES: readonly number[] = [\n GatewayCloseCodes.AuthenticationFailed,\n GatewayCloseCodes.InvalidShard,\n GatewayCloseCodes.ShardingRequired,\n GatewayCloseCodes.InvalidAPIVersion,\n GatewayCloseCodes.InvalidIntents,\n GatewayCloseCodes.DisallowedIntents,\n];\n\n/**\n * Close codes that keep the connection recoverable but destroy the session, so\n * the next connection must IDENTIFY rather than RESUME.\n */\nexport const IDENTIFY_CLOSE_CODES: readonly number[] = [\n GatewayCloseCodes.InvalidSeq,\n GatewayCloseCodes.SessionTimedOut,\n];\n\n/**\n * Classifies a close code.\n *\n * Any code outside the two tables above is **reconnectable**: transport-level\n * closes (`1006`), server restarts (`1001`), Discord's own `4000`, and the\n * `1000` the Gateway itself sends after a non-resumable `op 9` all belong here.\n * Whether that reconnect resumes or identifies is not a property of the code —\n * it is whether a session survives, which is why `canResume` is a parameter\n * rather than something this module works out for itself.\n *\n * @param code WebSocket close code.\n * @param canResume Whether the session can still be resumed.\n */\nexport function classifyCloseCode(\n code: number,\n canResume: boolean,\n): CloseAction {\n if (FATAL_CLOSE_CODES.includes(code)) return \"stop\";\n if (IDENTIFY_CLOSE_CODES.includes(code)) return \"identify\";\n return canResume ? \"resume\" : \"identify\";\n}\n\n/** Why a reconnect was not scheduled. */\nexport type ScheduleRefusal =\n /** Automatic reconnect is disabled for this Gateway. */\n | \"disabled\"\n /** A reconnect is already armed; a second would open a second socket. */\n | \"pending\"\n /** The attempt budget is spent. */\n | \"exhausted\";\n\n/** Outcome of asking for a reconnect. */\nexport type ScheduleResult =\n | {\n scheduled: true;\n delayMs: number;\n attempt: number;\n /** Set when reconnects are coming too fast: the delay was raised. */\n unstable?: { reconnects: number };\n }\n | { scheduled: false; reason: ScheduleRefusal };\n\n/** Configuration for {@link GatewayReconnect}. */\nexport interface ReconnectOptions {\n /** Whether automatic reconnect is permitted at all. */\n enabled: boolean;\n /** Maximum consecutive attempts before giving up. */\n maxAttempts: number;\n /** Delay for the first attempt, doubled per attempt. */\n baseDelay: number;\n /** Ceiling for the backoff. */\n maxDelay: number;\n /** Randomness source for jitter; injected in tests. */\n random?: () => number;\n /** Reconnects inside `stormWindow` before the link counts as unstable (default 5). */\n stormLimit?: number;\n /** The span over which reconnects are counted, in ms (default 60,000). */\n stormWindow?: number;\n /** Clock in ms; injected in tests. */\n now?: () => number;\n}\n\n/** Reconnect scheduling, backoff and attempt coordination. */\nexport class GatewayReconnect {\n readonly #options: ReconnectOptions;\n readonly #random: () => number;\n #attempt = 0;\n /** When recent reconnects were scheduled. A successful connection does not clear it, so a link that connects and drops again keeps backing off. */\n readonly #recent: number[] = [];\n #timer?: ReturnType<typeof setTimeout>;\n #promise?: Promise<void>;\n #resolve?: () => void;\n #reject?: (error: Error) => void;\n\n public constructor(options: ReconnectOptions) {\n this.#options = options;\n this.#random = options.random ?? Math.random;\n }\n\n /** Whether automatic reconnect is permitted. */\n public get enabled(): boolean {\n return this.#options.enabled;\n }\n\n /** Consecutive attempts made since the last {@link reset}. */\n public get attempts(): number {\n return this.#attempt;\n }\n\n /** Whether a reconnect timer is currently armed. */\n public get pending(): boolean {\n return this.#timer !== undefined;\n }\n\n /** Whether the attempt budget is spent. */\n public get exhausted(): boolean {\n return this.#attempt >= this.#options.maxAttempts;\n }\n\n /** Whether a connection attempt is currently in flight. */\n public get connecting(): boolean {\n return this.#promise !== undefined;\n }\n\n /** The in-flight attempt, or undefined when none is active. */\n public get attemptPromise(): Promise<void> | undefined {\n return this.#promise;\n }\n\n /** Classifies a close code against this Gateway's policy. */\n public classifyClose(code: number, canResume: boolean): CloseAction {\n return classifyCloseCode(code, canResume);\n }\n\n /** Whether another reconnect is currently allowed. */\n public canReconnect(): boolean {\n return this.#options.enabled && !this.exhausted;\n }\n\n /**\n * Arms a reconnect, unless one is already armed or no attempt is allowed.\n *\n * Refusing while `pending` is what keeps repeated closes from stacking\n * timers: several closes in a row produce one reconnect, not several\n * competing sockets.\n */\n public schedule(run: () => void): ScheduleResult {\n if (!this.#options.enabled)\n return { scheduled: false, reason: \"disabled\" };\n if (this.#timer) return { scheduled: false, reason: \"pending\" };\n if (this.exhausted) return { scheduled: false, reason: \"exhausted\" };\n\n const attempt = this.#attempt;\n const now = (this.#options.now ?? Date.now)();\n const window = this.#options.stormWindow ?? 60_000;\n const limit = this.#options.stormLimit ?? 5;\n while (this.#recent.length && now - this.#recent[0]! >= window)\n this.#recent.shift();\n const over = this.#recent.length - limit;\n this.#recent.push(now);\n let delay = Math.min(\n this.#options.maxDelay,\n this.#options.baseDelay * 2 ** this.#attempt++,\n );\n const unstable = over >= 0;\n // Past the limit, every further reconnect in the window doubles the\n // wait, even when each connection succeeded and reset the attempt count.\n if (unstable)\n delay = Math.min(\n this.#options.maxDelay,\n Math.max(delay, this.#options.baseDelay * 2 ** (over + 1)),\n );\n // Jitter must scale with the delay: a fixed ceiling would reconnect\n // every shard inside the same narrow window after a gateway-wide\n // restart, which is exactly when decorrelation matters.\n const jitter = this.#random() * Math.max(1, delay * 0.25);\n const delayMs = delay + jitter;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n run();\n }, delayMs);\n return {\n scheduled: true,\n delayMs,\n attempt,\n ...(unstable\n ? { unstable: { reconnects: this.#recent.length } }\n : {}),\n };\n }\n\n /** Cancels an armed reconnect. Safe to call when none is armed. */\n public cancel(): void {\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n }\n\n /** Clears the attempt counter after a connection succeeds. */\n public reset(): void {\n this.#attempt = 0;\n }\n\n /**\n * Coordinates one logical connection attempt.\n *\n * Callers that ask while an attempt is in flight join it instead of\n * starting a second: three `connect()` calls produce one socket attempt and\n * one shared promise.\n *\n * @param start Invoked exactly once, when this call begins a new attempt.\n */\n public attempt(start: () => void): Promise<void> {\n if (this.#promise) return this.#promise;\n this.#promise = new Promise<void>((resolve, reject) => {\n this.#resolve = resolve;\n this.#reject = reject;\n start();\n });\n return this.#promise;\n }\n\n /** Settles the in-flight attempt, resolving it or rejecting with `error`. */\n public settle(error?: Error): void {\n const resolve = this.#resolve;\n const reject = this.#reject;\n this.#resolve = undefined;\n this.#reject = undefined;\n this.#promise = undefined;\n if (error) reject?.(error);\n else resolve?.();\n }\n}\n",
18
+ "import { BaseStructure, Channel, User, CDN_BASE, cdnURL } from \"./base.js\";\nimport { PermissionsBitField } from \"@lunibee/core\";\nimport type { ImageURLOptions, ResourceContext } from \"./base.js\";\n\n/** Parses a Discord ISO timestamp into a Date, returning null for absent or invalid values. */\nfunction toDateOrNull(value?: string | null): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n// ─── GuildMember ───────────────────────────────────────────────────────────────\n\n/** A Discord guild member. */\nexport class GuildMember {\n /** User represented by the member. */\n public readonly user: User;\n /** Guild containing the member. */\n public readonly guildId: string;\n /** Nickname, if configured. */\n public nickname: string | null;\n /** Role IDs assigned to the member. */\n public readonly roleIds: string[];\n /** Whether the member is pending membership screening. */\n public pending: boolean;\n /** Member join timestamp. */\n public joinedAt?: Date;\n /** Member-specific avatar hash, if set. */\n public avatarHash: string | null;\n /** When the member started boosting the guild. */\n public premiumSince: Date | null;\n /** When the member's timeout expires (null if not timed out). */\n public timedOutUntil: Date | null;\n /** Member flags bitfield. */\n public flags: number;\n /** Permissions Discord sent with the member (interactions only). */\n readonly #suppliedPermissions?: PermissionsBitField;\n readonly #context?: ResourceContext;\n\n /** Creates a guild member from Discord data. @param data Discord guild-member payload. @throws {TypeError} If the guild ID is invalid. @throws {RangeError} If joined_at is invalid. */\n public constructor(\n data: {\n user: {\n id: string;\n username: string;\n global_name?: string | null;\n avatar?: string | null;\n bot?: boolean;\n system?: boolean;\n public_flags?: number;\n discriminator?: string;\n };\n guild_id: string;\n nick?: string | null;\n roles?: string[];\n pending?: boolean;\n joined_at?: string;\n permissions?: string;\n avatar?: string | null;\n premium_since?: string | null;\n communication_disabled_until?: string | null;\n flags?: number;\n },\n context?: ResourceContext,\n ) {\n this.user = new User(data.user);\n this.#context = context;\n if (!/^\\d{1,20}$/.test(data.guild_id))\n throw new TypeError(\"Member guild_id must be a valid snowflake.\");\n this.guildId = data.guild_id;\n this.nickname = data.nick ?? null;\n this.roleIds = [...(data.roles ?? [])];\n this.pending = data.pending ?? false;\n this.joinedAt = data.joined_at ? new Date(data.joined_at) : undefined;\n if (this.joinedAt?.toString() === \"Invalid Date\")\n throw new RangeError(\"Member joined_at must be a valid date.\");\n if (data.permissions !== undefined)\n this.#suppliedPermissions = new PermissionsBitField(\n data.permissions,\n );\n this.avatarHash = data.avatar ?? null;\n // Like joinedAt, coerce malformed timestamps to null instead of an Invalid Date.\n this.premiumSince = toDateOrNull(data.premium_since);\n this.timedOutUntil = toDateOrNull(data.communication_disabled_until);\n this.flags = data.flags ?? 0;\n }\n\n /**\n * The member's permissions. Discord sends them with interactions (already\n * resolved for the channel); anywhere else they are computed at guild\n * level from the cached roles each time they are read, so they follow role\n * changes. Empty when the guild's roles are not cached.\n */\n public get permissions(): PermissionsBitField {\n if (this.#suppliedPermissions) return this.#suppliedPermissions;\n return new PermissionsBitField(\n this.#context?.memberPermissions?.(\n this.guildId,\n this.user.id,\n this.roleIds,\n undefined,\n this.timedOutUntil,\n ) ?? 0n,\n );\n }\n\n /** The member's permissions in a channel, with its overwrites. Null when the channel or guild is not cached. @param channelId Channel ID. */\n public permissionsIn(channelId: string): PermissionsBitField | null {\n const computed = this.#context?.memberPermissions?.(\n this.guildId,\n this.user.id,\n this.roleIds,\n channelId,\n this.timedOutUntil,\n );\n return computed ? new PermissionsBitField(computed) : null;\n }\n\n #action<K extends keyof ResourceContext>(\n name: K,\n ): NonNullable<ResourceContext[K]> {\n const action = this.#context?.[name];\n if (!action)\n throw new Error(\"This member is not attached to a client.\");\n return action as NonNullable<ResourceContext[K]>;\n }\n\n /** Kicks this member. @param reason Audit-log reason. */\n public kick(reason?: string): Promise<void> {\n return this.#action(\"kickMember\")(this.guildId, this.user.id, reason);\n }\n\n /** Bans this member. @param options Audit-log reason and seconds of messages to delete. */\n public ban(\n options: { reason?: string; deleteMessageSeconds?: number } = {},\n ): Promise<void> {\n return this.#action(\"banMember\")(this.guildId, this.user.id, options);\n }\n\n /** Edits this member (nickname, roles, voice state, timeout). @param options Discord member fields. @param reason Audit-log reason. */\n public edit(\n options: Record<string, unknown>,\n reason?: string,\n ): Promise<GuildMember> {\n return this.#action(\"editMember\")(\n this.guildId,\n this.user.id,\n options,\n reason,\n );\n }\n\n /** Times this member out, or clears the timeout with null. @param milliseconds Timeout length (Discord allows up to 28 days). @param reason Audit-log reason. */\n public timeout(\n milliseconds: number | null,\n reason?: string,\n ): Promise<GuildMember> {\n if (milliseconds !== null && !(milliseconds > 0))\n throw new RangeError(\n \"Timeout length must be a positive number of milliseconds.\",\n );\n return this.edit(\n {\n communication_disabled_until:\n milliseconds === null\n ? null\n : new Date(Date.now() + milliseconds).toISOString(),\n },\n reason,\n );\n }\n\n /** Sets or clears (null) this member's nickname. @param nickname New nickname. @param reason Audit-log reason. */\n public setNickname(\n nickname: string | null,\n reason?: string,\n ): Promise<GuildMember> {\n return this.edit({ nick: nickname }, reason);\n }\n\n /** Gives this member a role. @param roleId Role ID. @param reason Audit-log reason. */\n public addRole(roleId: string, reason?: string): Promise<void> {\n return this.#action(\"addMemberRole\")(\n this.guildId,\n this.user.id,\n roleId,\n reason,\n );\n }\n\n /** Takes a role from this member. @param roleId Role ID. @param reason Audit-log reason. */\n public removeRole(roleId: string, reason?: string): Promise<void> {\n return this.#action(\"removeMemberRole\")(\n this.guildId,\n this.user.id,\n roleId,\n reason,\n );\n }\n\n /** Effective member display name — nickname, falling back to user display name. */\n public get displayName(): string {\n return this.nickname ?? this.user.displayName;\n }\n\n /** Whether this member is currently timed out. */\n public get isTimedOut(): boolean {\n return this.timedOutUntil !== null && this.timedOutUntil > new Date();\n }\n\n /** Returns the member-specific avatar URL, falling back to the user's avatar, or null if none. */\n public avatarURL(options: ImageURLOptions = {}): string | null {\n if (this.avatarHash)\n return cdnURL(\n `/guilds/${this.guildId}/users/${this.user.id}/avatars`,\n this.avatarHash,\n options,\n );\n // User always exposes avatarURL(); returns null when the user has no avatar.\n return this.user.avatarURL(options);\n }\n\n /** Returns the resolved avatar URL — member avatar, user avatar, or default. */\n public displayAvatarURL(options: ImageURLOptions = {}): string {\n return this.avatarURL(options) ?? this.user.displayAvatarURL(options);\n }\n\n /** Returns the Discord user mention for this member. */\n public toString(): string {\n return this.user.toString();\n }\n}\n\n// ─── Role ──────────────────────────────────────────────────────────────────────\n\n/** A Discord guild role. */\nexport class Role extends BaseStructure {\n /** Role name. */\n public name: string;\n /** Role color as a 24-bit RGB integer. */\n public color: number;\n /** Whether the role is hoisted. */\n public hoist: boolean;\n /** Permission bitfield. */\n public permissions: PermissionsBitField;\n /** Whether the role is managed by an integration. */\n public managed: boolean;\n /** Whether the role is mentionable. */\n public mentionable: boolean;\n /** Role position in the hierarchy. */\n public position: number;\n /** Unicode emoji used as the role icon, if any. */\n public unicodeEmoji: string | null;\n /** Hash of the role's custom icon image, if any. */\n public iconHash: string | null;\n /** Gradient or holographic colours, when the role has more than a solid colour. */\n public colors: {\n primary: number;\n secondary: number | null;\n tertiary: number | null;\n } | null;\n /** Role tags metadata (bot, premium subscriber, etc). */\n public tags: Record<string, unknown> | null;\n\n /** Creates a role from Discord data. @param data Discord role payload. */\n public constructor(data: {\n id: string;\n name: string;\n color?: number;\n hoist?: boolean;\n permissions?: string;\n managed?: boolean;\n mentionable?: boolean;\n position?: number;\n unicode_emoji?: string | null;\n icon?: string | null;\n colors?: {\n primary_color: number;\n secondary_color: number | null;\n tertiary_color: number | null;\n };\n tags?: Record<string, unknown> | null;\n }) {\n super(data.id);\n if (!data.name) throw new TypeError(\"Role name cannot be empty.\");\n this.name = data.name;\n this.color = data.color ?? 0;\n this.hoist = data.hoist ?? false;\n this.permissions = new PermissionsBitField(data.permissions ?? 0n);\n this.managed = data.managed ?? false;\n this.mentionable = data.mentionable ?? false;\n this.position = data.position ?? 0;\n this.unicodeEmoji = data.unicode_emoji ?? null;\n this.colors = data.colors\n ? {\n primary: data.colors.primary_color,\n secondary: data.colors.secondary_color,\n tertiary: data.colors.tertiary_color,\n }\n : null;\n this.iconHash = data.icon ?? null;\n this.tags = data.tags ?? null;\n }\n\n /** Returns the role's color as a `#RRGGBB` hex string. Returns `#000000` for colorless roles. */\n public get colorHex(): string {\n return `#${this.color.toString(16).padStart(6, \"0\").toUpperCase()}`;\n }\n\n /** Returns the role's custom icon URL, or null if the role has no icon. */\n public iconURL(options: ImageURLOptions = {}): string | null {\n if (!this.iconHash) return null;\n return cdnURL(`/role-icons/${this.id}`, this.iconHash, options);\n }\n\n /** Whether this is the `@everyone` base role (its ID equals the guild ID). */\n public isEveryone(guildId: string): boolean {\n return this.id === guildId;\n }\n\n /** Discord role mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<@&${this.id}>`;\n }\n}\n\n// ─── TextChannel ──────────────────────────────────────────────────────────────\n\n/** A Discord text-capable channel. */\nexport class TextChannel extends Channel {\n /** Creates a text channel from Discord data. @param data Discord channel payload. */\n public constructor(\n data: {\n id: string;\n type: number;\n name?: string | null;\n parent_id?: string | null;\n guild_id?: string;\n } & Partial<import(\"@lunibee/types\").APIChannel>,\n context?: import(\"./base.js\").ResourceContext,\n ) {\n super(data, context);\n }\n /** Discord channel mention string. Used automatically in template literals. */\n public override toString(): string {\n return `<#${this.id}>`;\n }\n}\n\n// ─── Invite ───────────────────────────────────────────────────────────────────\n\n/** A Discord invite link and its metadata. */\nexport class Invite {\n /** Invite code (the unique part of the URL). */\n public readonly code: string;\n /** Guild this invite belongs to, if any. */\n public readonly guildId: string | null;\n /** Channel this invite points to, if any. */\n public readonly channelId: string | null;\n /** User who created the invite, if available. */\n public readonly inviter: User | null;\n /** Number of times the invite has been used. */\n public uses: number;\n /** Maximum number of uses (0 = unlimited). */\n public maxUses: number;\n /** Duration in seconds until the invite expires (0 = never). */\n public maxAge: number;\n /** Whether the invite is temporary (kicks uninducted members on disconnect). */\n public temporary: boolean;\n /** When the invite was created. */\n public readonly createdAt: Date | null;\n /** When the invite expires, or null if it never expires. */\n public readonly expiresAt: Date | null;\n\n /** Creates an invite from Discord data. */\n public constructor(data: {\n code: string;\n guild?: { id: string } | null;\n channel?: { id: string } | null;\n inviter?: {\n id: string;\n username: string;\n global_name?: string | null;\n avatar?: string | null;\n bot?: boolean;\n system?: boolean;\n public_flags?: number;\n discriminator?: string;\n } | null;\n uses?: number;\n max_uses?: number;\n max_age?: number;\n temporary?: boolean;\n created_at?: string | null;\n expires_at?: string | null;\n }) {\n if (!data.code) throw new TypeError(\"An invite requires a code.\");\n this.code = data.code;\n this.guildId = data.guild?.id ?? null;\n this.channelId = data.channel?.id ?? null;\n this.inviter = data.inviter ? new User(data.inviter) : null;\n this.uses = data.uses ?? 0;\n this.maxUses = data.max_uses ?? 0;\n this.maxAge = data.max_age ?? 0;\n this.temporary = data.temporary ?? false;\n this.createdAt = data.created_at ? new Date(data.created_at) : null;\n this.expiresAt = data.expires_at ? new Date(data.expires_at) : null;\n }\n\n /** The full invite URL. */\n public get url(): string {\n return `https://discord.gg/${this.code}`;\n }\n\n /** Returns the invite URL. Used automatically in template literals. */\n public toString(): string {\n return this.url;\n }\n}\n\n// ─── Webhook ──────────────────────────────────────────────────────────────────\n\n/** Webhook type constants. */\nexport const WebhookEnum = {\n Incoming: 1,\n ChannelFollower: 2,\n Application: 3,\n} as const;\n/** One {@link WebhookEnum} value, usable as a type. */\nexport type WebhookEnum = (typeof WebhookEnum)[keyof typeof WebhookEnum];\n\n/** A Discord webhook — an HTTP endpoint that can post messages to a channel. */\nexport class Webhook extends BaseStructure {\n /** Webhook type. */\n public readonly type: number;\n /** Webhook display name. */\n public name: string | null;\n /** Webhook avatar hash. */\n public avatarHash: string | null;\n /** Channel this webhook posts to. */\n public readonly channelId: string | null;\n /** Guild this webhook belongs to. */\n public readonly guildId: string | null;\n /** Application that created this webhook, if any. */\n public readonly applicationId: string | null;\n /** Webhook token (only present for incoming webhooks). */\n public readonly token: string | null;\n\n /** Creates a webhook from Discord data. */\n public constructor(data: {\n id: string;\n type?: number;\n name?: string | null;\n avatar?: string | null;\n channel_id?: string | null;\n guild_id?: string | null;\n application_id?: string | null;\n token?: string;\n }) {\n super(data.id);\n this.type = data.type ?? WebhookEnum.Incoming;\n this.name = data.name ?? null;\n this.avatarHash = data.avatar ?? null;\n this.channelId = data.channel_id ?? null;\n this.guildId = data.guild_id ?? null;\n this.applicationId = data.application_id ?? null;\n this.token = data.token ?? null;\n }\n\n /** Returns the webhook avatar URL, or null if no avatar is set. */\n public avatarURL(options: ImageURLOptions = {}): string | null {\n if (!this.avatarHash) return null;\n return cdnURL(`/avatars/${this.id}`, this.avatarHash, options);\n }\n\n /** Returns the webhook execution URL, or null if no token is set. */\n public get url(): string | null {\n return this.token\n ? `https://discord.com/api/webhooks/${this.id}/${this.token}`\n : null;\n }\n\n /** Returns the webhook URL or its ID as a string. */\n public override toString(): string {\n return this.url ?? this.id;\n }\n}\n\n// ─── Emoji ────────────────────────────────────────────────────────────────────\n\n/** A Discord emoji. */\nexport class Emoji extends BaseStructure {\n /** Emoji name. */\n public name: string | null;\n /** Roles allowed to use this emoji. */\n public roleIds: string[];\n /** User that created this emoji. */\n public user: User | null;\n /** Whether this emoji must be wrapped in colons. */\n public requireColons: boolean;\n /** Whether this emoji is managed. */\n public managed: boolean;\n /** Whether this emoji is animated. */\n public animated: boolean;\n /** Whether this emoji can be used, may be false due to loss of Server Boosts. */\n public available: boolean;\n\n /** Creates an emoji from Discord data. */\n public constructor(data: {\n id: string | null;\n name: string | null;\n roles?: string[];\n user?: import(\"@lunibee/types\").UserData;\n require_colons?: boolean;\n managed?: boolean;\n animated?: boolean;\n available?: boolean;\n }) {\n // Unicode emoji have no snowflake: pass the base check with a\n // placeholder, then expose the documented \"unicode\" sentinel id.\n super(data.id ?? \"0\");\n if (data.id === null) (this as { id: string }).id = \"unicode\";\n this.name = data.name;\n this.roleIds = data.roles ?? [];\n this.user = data.user ? new User(data.user) : null;\n this.requireColons = data.require_colons ?? false;\n this.managed = data.managed ?? false;\n this.animated = data.animated ?? false;\n this.available = data.available ?? true;\n }\n\n /** Returns the URL for this emoji if it is custom, or null for unicode emojis. */\n public url(options: ImageURLOptions = {}): string | null {\n if (!this.id || this.id === \"unicode\") return null;\n const ext = options.extension ?? (this.animated ? \"gif\" : \"png\");\n const size = options.size ? `?size=${options.size}` : \"\";\n return `${CDN_BASE}/emojis/${this.id}.${ext}${size}`;\n }\n\n /** Returns the text required to render this emoji in Discord. */\n public override toString(): string {\n return this.id !== \"unicode\"\n ? `<${this.animated ? \"a\" : \"\"}:${this.name}:${this.id}>`\n : (this.name ?? \"\");\n }\n}\n\n// --- AutoModerationRule --------------------------------------------------------\n\n/** A Discord AutoModeration Rule. */\nexport class AutoModerationRule extends BaseStructure {\n public guildId: string;\n public name: string;\n public creatorId: string;\n public eventType: number;\n public triggerType: number;\n public triggerMetadata: Record<string, unknown>;\n public actions: import(\"@lunibee/types\").APIAutoModerationAction[];\n public enabled: boolean;\n public exemptRoles: string[];\n public exemptChannels: string[];\n\n /** Creates an auto moderation rule from Discord data. */\n public constructor(data: import(\"@lunibee/types\").APIAutoModerationRule) {\n super(data.id);\n if (!/^\\d{1,20}$/.test(data.guild_id))\n throw new TypeError(\n \"AutoModerationRule guild_id must be a valid snowflake.\",\n );\n this.guildId = data.guild_id;\n this.name = data.name;\n this.creatorId = data.creator_id;\n this.eventType = data.event_type;\n this.triggerType = data.trigger_type;\n this.triggerMetadata = data.trigger_metadata;\n this.actions = data.actions;\n this.enabled = data.enabled;\n this.exemptRoles = data.exempt_roles;\n this.exemptChannels = data.exempt_channels;\n }\n\n public toJSON(): Record<string, unknown> {\n return {\n id: this.id,\n guildId: this.guildId,\n name: this.name,\n creatorId: this.creatorId,\n eventType: this.eventType,\n triggerType: this.triggerType,\n triggerMetadata: this.triggerMetadata,\n actions: this.actions,\n enabled: this.enabled,\n exemptRoles: this.exemptRoles,\n exemptChannels: this.exemptChannels,\n };\n }\n}\n\n// --- Welcome Screen -----------------------------------------------------------\n\n/** A channel listed in a guild's Welcome Screen. */\nexport class WelcomeScreenChannel {\n public channelId: string;\n public description: string;\n public emojiId: string | null;\n public emojiName: string | null;\n\n public constructor(data: import(\"@lunibee/types\").APIWelcomeScreenChannel) {\n this.channelId = data.channel_id;\n this.description = data.description;\n this.emojiId = data.emoji_id;\n this.emojiName = data.emoji_name;\n }\n}\n\n/** A Discord Guild Welcome Screen. */\nexport class GuildWelcomeScreen {\n public description: string | null;\n public channels: WelcomeScreenChannel[];\n\n public constructor(data: import(\"@lunibee/types\").APIGuildWelcomeScreen) {\n this.description = data.description;\n this.channels = data.welcome_channels.map(\n (c) => new WelcomeScreenChannel(c),\n );\n }\n}\n\n// --- Guild Onboarding ---------------------------------------------------------\n\n/** An option within a Guild Onboarding Prompt. */\nexport class OnboardingPromptOption extends BaseStructure {\n public channelIds: string[];\n public roleIds: string[];\n public emoji: import(\"@lunibee/types\").APIPartialEmoji | undefined;\n public title: string;\n public description: string | null;\n\n public constructor(\n data: import(\"@lunibee/types\").APIOnboardingPromptOption,\n ) {\n super(data.id);\n this.channelIds = data.channel_ids;\n this.roleIds = data.role_ids;\n this.emoji = data.emoji;\n this.title = data.title;\n this.description = data.description;\n }\n}\n\n/** A prompt shown during Guild Onboarding. */\nexport class OnboardingPrompt extends BaseStructure {\n public type: number;\n public options: OnboardingPromptOption[];\n public title: string;\n public singleSelect: boolean;\n public required: boolean;\n public inOnboarding: boolean;\n\n public constructor(data: import(\"@lunibee/types\").APIOnboardingPrompt) {\n super(data.id);\n this.type = data.type;\n this.options = data.options.map((o) => new OnboardingPromptOption(o));\n this.title = data.title;\n this.singleSelect = data.single_select;\n this.required = data.required;\n this.inOnboarding = data.in_onboarding;\n }\n}\n\n/** A Discord Guild Onboarding setup. */\nexport class GuildOnboarding extends BaseStructure {\n public prompts: OnboardingPrompt[];\n public defaultChannelIds: string[];\n public enabled: boolean;\n public mode: number;\n\n public constructor(data: import(\"@lunibee/types\").APIGuildOnboarding) {\n super(data.guild_id);\n this.prompts = data.prompts.map((p) => new OnboardingPrompt(p));\n this.defaultChannelIds = data.default_channel_ids;\n this.enabled = data.enabled;\n this.mode = data.mode;\n }\n}\n",
19
+ "import { Channel, User, type ResourceContext } from \"./base.js\";\nimport { TextChannel } from \"./resources.js\";\nimport type {\n APIChannel,\n APIForumTag,\n APIPartialEmoji,\n APIThreadMetadata,\n} from \"@lunibee/types\";\n\n// Every channel class extends Channel, so `instanceof Channel` checks and\n// Channel methods keep working.\n\n/** A guild announcement (news) channel. */\nexport class NewsChannel extends TextChannel {}\n\n/** A direct-message or group DM channel. */\nexport class DMChannel extends Channel {\n /** Users in the conversation. */\n public readonly recipients: User[];\n /** Owner of a group DM. */\n public readonly ownerId: string | null;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.recipients = (data.recipients ?? []).map((u) => new User(u));\n this.ownerId = data.owner_id ?? null;\n }\n}\n\n/** A guild voice channel. */\nexport class VoiceChannel extends Channel {\n /** Bitrate in bits per second. */\n public bitrate: number;\n /** User limit (0 = unlimited). */\n public userLimit: number;\n /** Voice region override, or null for automatic. */\n public rtcRegion: string | null;\n /** Camera video quality mode. */\n public videoQualityMode: number;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.bitrate = data.bitrate ?? 64000;\n this.userLimit = data.user_limit ?? 0;\n this.rtcRegion = data.rtc_region ?? null;\n this.videoQualityMode = data.video_quality_mode ?? 1;\n }\n}\n\n/** A guild stage channel. */\nexport class StageChannel extends VoiceChannel {}\n\n/** A guild category. */\nexport class CategoryChannel extends Channel {}\n\n/** A thread (announcement, public or private). */\nexport class ThreadChannel extends Channel {\n /** User who created the thread. */\n public readonly ownerId: string | null;\n /** Approximate message count. */\n public messageCount: number;\n /** Approximate member count (stops counting at 50). */\n public memberCount: number;\n /** Thread metadata. */\n public metadata: APIThreadMetadata | null;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.ownerId = data.owner_id ?? null;\n this.messageCount = data.message_count ?? 0;\n this.memberCount = data.member_count ?? 0;\n this.metadata = data.thread_metadata ?? null;\n }\n\n /** Whether the thread is archived. */\n public get archived(): boolean {\n return this.metadata?.archived ?? false;\n }\n\n /** Whether the thread is locked. */\n public get locked(): boolean {\n return this.metadata?.locked ?? false;\n }\n\n /** Minutes of inactivity before the thread auto-archives. */\n public get autoArchiveDuration(): number | null {\n return this.metadata?.auto_archive_duration ?? null;\n }\n}\n\n/** A guild forum channel. */\nexport class ForumChannel extends Channel {\n /** Tags that threads can apply. */\n public availableTags: APIForumTag[];\n /** Default reaction for new threads. */\n public defaultReactionEmoji: APIPartialEmoji | null;\n /** Default slowmode for new threads. */\n public defaultThreadRateLimitPerUser: number;\n /** Default auto-archive duration for new threads. */\n public defaultAutoArchiveDuration: number | null;\n\n public constructor(data: APIChannel, context?: ResourceContext) {\n super(data, context);\n this.availableTags = data.available_tags ?? [];\n this.defaultReactionEmoji = data.default_reaction_emoji ?? null;\n this.defaultThreadRateLimitPerUser =\n data.default_thread_rate_limit_per_user ?? 0;\n this.defaultAutoArchiveDuration =\n data.default_auto_archive_duration ?? null;\n }\n}\n\n/** A guild media channel. */\nexport class MediaChannel extends ForumChannel {}\n\n/**\n * Builds the most specific channel class for a payload's `type`, falling back\n * to {@link Channel} for types without a dedicated class.\n */\nexport function createChannel(\n data: APIChannel,\n context?: ResourceContext,\n): Channel {\n switch (data.type) {\n case 0:\n return new TextChannel(data, context);\n case 1:\n case 3:\n return new DMChannel(data, context);\n case 2:\n return new VoiceChannel(data, context);\n case 4:\n return new CategoryChannel(data, context);\n case 5:\n return new NewsChannel(data, context);\n case 10:\n case 11:\n case 12:\n return new ThreadChannel(data, context);\n case 13:\n return new StageChannel(data, context);\n case 15:\n return new ForumChannel(data, context);\n case 16:\n return new MediaChannel(data, context);\n default:\n return new Channel(data, context);\n }\n}\n\n/** The class of each channel kind, so `channel.is(\"voice\")` can narrow to `VoiceChannel`. */\nexport interface ChannelsByKind {\n text: TextChannel;\n announcement: NewsChannel;\n voice: VoiceChannel;\n stage: StageChannel;\n category: CategoryChannel;\n thread: ThreadChannel;\n forum: ForumChannel;\n media: MediaChannel;\n dm: DMChannel;\n \"group-dm\": DMChannel;\n directory: Channel;\n unknown: Channel;\n}\n\n/** The channel class for a kind (or a union of them). */\nexport type ChannelOfKind<K extends keyof ChannelsByKind> = ChannelsByKind[K];\n",
15
20
  "// ─── Raw option type from Discord ────────────────────────────────────────────\n\n/** Raw Discord application command interaction data option. */\nexport interface APIInteractionDataOption {\n name: string;\n type: number;\n value?: string | number | boolean;\n options?: APIInteractionDataOption[];\n focused?: boolean;\n}\n\n// ─── CommandOptions resolver ──────────────────────────────────────────────────\n\n/** Application command option types mirroring Discord's enum. */\nconst OptionType = {\n SubCommand: 1,\n SubCommandGroup: 2,\n String: 3,\n Integer: 4,\n Boolean: 5,\n User: 6,\n Channel: 7,\n Role: 8,\n Mentionable: 9,\n Number: 10,\n Attachment: 11,\n} as const;\n\n/**\n * Typed resolver for application command options.\n * Attached as `CommandInteraction.options`.\n */\nexport class CommandOptions {\n readonly #options: APIInteractionDataOption[];\n readonly #resolved: Record<string, unknown>;\n /** `resolved[kind][id]` from Discord's interaction data, if present. */\n #lookup(kind: string, id: string): Record<string, unknown> | undefined {\n const group = this.#resolved?.[kind];\n if (typeof group !== \"object\" || group === null) return undefined;\n const entry = (group as Record<string, unknown>)[id];\n return typeof entry === \"object\" && entry !== null\n ? (entry as Record<string, unknown>)\n : undefined;\n }\n\n /** @internal */\n public constructor(\n options: APIInteractionDataOption[],\n resolved: Record<string, unknown> = {},\n ) {\n let currentOptions = options;\n let group: string | null = null;\n let sub: string | null = null;\n\n // Drill down to the deepest options level for nested subcommands\n while (currentOptions.length === 1) {\n const opt = currentOptions[0]!;\n if (opt.type === OptionType.SubCommandGroup) {\n group = opt.name;\n currentOptions = opt.options ?? [];\n } else if (opt.type === OptionType.SubCommand) {\n sub = opt.name;\n currentOptions = opt.options ?? [];\n } else {\n break;\n }\n }\n\n this.#options = currentOptions;\n this.#resolved = resolved;\n this.#subcommandGroup = group;\n this.#subcommand = sub;\n }\n\n readonly #subcommandGroup: string | null;\n readonly #subcommand: string | null;\n\n /** Finds a raw option by name (case-insensitive). */\n #get(name: string): APIInteractionDataOption | undefined {\n return this.#options.find(\n (o) => o.name.toLowerCase() === name.toLowerCase(),\n );\n }\n\n // ── Subcommand resolution ──────────────────────────────────────────────────\n\n /** Returns the invoked subcommand name, or null if none. */\n public getSubcommand(required?: false): string | null;\n public getSubcommand(required: true): string;\n public getSubcommand(required = false): string | null {\n if (!this.#subcommand && required) {\n throw new TypeError(\"No subcommand was provided.\");\n }\n return this.#subcommand;\n }\n\n /** Returns the invoked subcommand group name, or null if none. */\n public getSubcommandGroup(required?: false): string | null;\n public getSubcommandGroup(required: true): string;\n public getSubcommandGroup(required = false): string | null {\n if (!this.#subcommandGroup && required) {\n throw new TypeError(\"No subcommand group was provided.\");\n }\n return this.#subcommandGroup;\n }\n\n // ── Autocomplete ───────────────────────────────────────────────────────────\n\n /** Returns the focused option's value (autocomplete), or the full option when `full` is true. @throws {TypeError} If no option is focused. */\n public getFocused(full: true): APIInteractionDataOption;\n public getFocused(full?: false): string | number | boolean;\n public getFocused(\n full = false,\n ): APIInteractionDataOption | string | number | boolean {\n const focused = this.#options.find((o) => o.focused);\n if (!focused) throw new TypeError(\"No focused option was provided.\");\n return full ? focused : (focused.value ?? \"\");\n }\n\n // ── Primitive value options ────────────────────────────────────────────────\n\n /** Gets a string option. @param name Option name. @param required If true, throws when missing. */\n public getString(name: string, required?: false): string | null;\n public getString(name: string, required: true): string;\n public getString(name: string, required = false): string | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.String) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (string) is missing.`,\n );\n return null;\n }\n return typeof opt.value === \"string\" ? opt.value : null;\n }\n\n /** Gets an integer option. @param name Option name. @param required If true, throws when missing. */\n public getInteger(name: string, required?: false): number | null;\n public getInteger(name: string, required: true): number;\n public getInteger(name: string, required = false): number | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Integer) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (integer) is missing.`,\n );\n return null;\n }\n return typeof opt.value === \"number\" ? Math.trunc(opt.value) : null;\n }\n\n /** Gets a number (float) option. @param name Option name. @param required If true, throws when missing. */\n public getNumber(name: string, required?: false): number | null;\n public getNumber(name: string, required: true): number;\n public getNumber(name: string, required = false): number | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Number) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (number) is missing.`,\n );\n return null;\n }\n return typeof opt.value === \"number\" ? opt.value : null;\n }\n\n /** Gets a boolean option. @param name Option name. @param required If true, throws when missing. */\n public getBoolean(name: string, required?: false): boolean | null;\n public getBoolean(name: string, required: true): boolean;\n public getBoolean(name: string, required = false): boolean | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Boolean) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (boolean) is missing.`,\n );\n return null;\n }\n return typeof opt.value === \"boolean\" ? opt.value : null;\n }\n\n // ── Resolved entity options ────────────────────────────────────────────────\n\n /** Gets the raw resolved user data for a user option. @param name Option name. @param required If true, throws when missing. */\n public getUser(\n name: string,\n required?: false,\n ): Record<string, unknown> | null;\n public getUser(name: string, required: true): Record<string, unknown>;\n public getUser(\n name: string,\n required = false,\n ): Record<string, unknown> | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.User) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (user) is missing.`,\n );\n return null;\n }\n const userId = String(opt.value);\n const resolved = this.#lookup(\"users\", userId) ?? null;\n if (!resolved && required)\n throw new TypeError(\n `Resolved user for option \"${name}\" is missing.`,\n );\n return resolved;\n }\n\n /** Gets the raw resolved channel data for a channel option. @param name Option name. @param required If true, throws when missing. */\n public getChannel(\n name: string,\n required?: false,\n ): Record<string, unknown> | null;\n public getChannel(name: string, required: true): Record<string, unknown>;\n public getChannel(\n name: string,\n required = false,\n ): Record<string, unknown> | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Channel) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (channel) is missing.`,\n );\n return null;\n }\n const channelId = String(opt.value);\n const resolved = this.#lookup(\"channels\", channelId) ?? null;\n if (!resolved && required)\n throw new TypeError(\n `Resolved channel for option \"${name}\" is missing.`,\n );\n return resolved;\n }\n\n /** Gets the raw resolved role data for a role option. @param name Option name. @param required If true, throws when missing. */\n public getRole(\n name: string,\n required?: false,\n ): Record<string, unknown> | null;\n public getRole(name: string, required: true): Record<string, unknown>;\n public getRole(\n name: string,\n required = false,\n ): Record<string, unknown> | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Role) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (role) is missing.`,\n );\n return null;\n }\n const roleId = String(opt.value);\n const resolved = this.#lookup(\"roles\", roleId) ?? null;\n if (!resolved && required)\n throw new TypeError(\n `Resolved role for option \"${name}\" is missing.`,\n );\n return resolved;\n }\n\n /** Gets the raw resolved user or role data for a mentionable option. @param name Option name. @param required If true, throws when missing. */\n public getMentionable(\n name: string,\n required?: false,\n ): Record<string, unknown> | null;\n public getMentionable(\n name: string,\n required: true,\n ): Record<string, unknown>;\n public getMentionable(\n name: string,\n required = false,\n ): Record<string, unknown> | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Mentionable) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (mentionable) is missing.`,\n );\n return null;\n }\n const id = String(opt.value);\n const resolved =\n this.#lookup(\"users\", id) ?? this.#lookup(\"roles\", id) ?? null;\n if (!resolved && required)\n throw new TypeError(\n `Resolved mentionable for option \"${name}\" is missing.`,\n );\n return resolved;\n }\n\n /** Whether a mentionable option picked a user or a role; null when the option is missing. @param name Option name. */\n public getMentionableType(name: string): \"user\" | \"role\" | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Mentionable) return null;\n const id = String(opt.value);\n if (this.#lookup(\"users\", id)) return \"user\";\n if (this.#lookup(\"roles\", id)) return \"role\";\n return null;\n }\n\n /** Gets the raw resolved attachment data for an attachment option. @param name Option name. @param required If true, throws when missing. */\n public getAttachment(\n name: string,\n required?: false,\n ): Record<string, unknown> | null;\n public getAttachment(name: string, required: true): Record<string, unknown>;\n public getAttachment(\n name: string,\n required = false,\n ): Record<string, unknown> | null {\n const opt = this.#get(name);\n if (!opt || opt.type !== OptionType.Attachment) {\n if (required)\n throw new TypeError(\n `Required option \"${name}\" (attachment) is missing.`,\n );\n return null;\n }\n const attachmentId = String(opt.value);\n const resolved = this.#lookup(\"attachments\", attachmentId) ?? null;\n if (!resolved && required)\n throw new TypeError(\n `Resolved attachment for option \"${name}\" is missing.`,\n );\n return resolved;\n }\n\n /** Returns the raw option list for advanced use cases. */\n public get raw(): readonly APIInteractionDataOption[] {\n return this.#options;\n }\n}\n",
16
- "import { InteractionResponseEnum } from \"@lunibee/types\";\nimport { User, type ResourceContext } from \"./base.js\";\nimport { GuildMember } from \"./resources.js\";\n// A cycle with index.ts: Message is only used lazily (in a getter), after both modules loaded.\nimport { Message } from \"./index.js\";\n\n/** Discord interaction type constants. */\nexport const InteractionEnum = {\n Ping: 1,\n ApplicationCommand: 2,\n MessageComponent: 3,\n ApplicationCommandAutocomplete: 4,\n ModalSubmit: 5,\n} as const;\n/** One {@link InteractionEnum} value, usable as a type. */\nexport type InteractionEnum =\n (typeof InteractionEnum)[keyof typeof InteractionEnum];\n// Re-export for consumers who import from structures directly\nexport {\n InteractionResponseEnum,\n InteractionResponseType,\n} from \"@lunibee/types\";\n/** Data shared by Discord interactions. */\nexport interface InteractionData {\n /** Interaction identifier. */ id: string;\n /** Application identifier. */ application_id: string;\n /** Interaction type. */ type: number;\n /** Interaction token. */ token: string;\n /** Gateway/API version. */ version?: number;\n /** Guild identifier. */ guild_id?: string;\n /** Channel identifier. */ channel_id?: string;\n /** Interaction-specific data. */ data?: Record<string, unknown>;\n [key: string]: unknown;\n}\n/** Options for an interaction response message. */\nexport interface InteractionReplyOptions {\n /** Message content. */ content?: string;\n /** Whether the response is ephemeral. */ ephemeral?: boolean;\n /** Message components. */ components?: unknown[];\n /** Message embeds. */ embeds?: unknown[];\n /** Discord message flags. */ flags?: number;\n /** On `reply()` / `update()`: return the created message (one request, no `fetchReply()`). */ withResponse?: boolean;\n [key: string]: unknown;\n}\n/** Transport required by an interaction structure. */\nexport interface InteractionClient {\n /** Sends the initial interaction callback. @param id Interaction identifier. @param token Interaction token. @param response Callback payload. @returns Discord response. @throws {Error} When REST fails. */ postInteractionResponse(\n id: string,\n token: string,\n response: InteractionResponse,\n ): Promise<unknown>;\n /** Edits the original interaction response. @param token Interaction token. @param data Message payload. @returns Discord response. @throws {Error} When REST fails. */ editInteractionReply(\n token: string,\n data: InteractionReplyOptions,\n ): Promise<unknown>;\n /** Deletes the original interaction response. @param token Interaction token. @returns Promise fulfilled after deletion. @throws {Error} When REST fails. */ deleteInteractionReply(\n token: string,\n ): Promise<void>;\n /** Sends a follow-up interaction webhook message. @param token Interaction token. @param data Message payload. @returns Discord response. @throws {Error} When REST fails. */ followUpInteraction(\n token: string,\n data: InteractionReplyOptions,\n ): Promise<unknown>;\n /** Reads, edits or deletes an interaction webhook message (`@original` or a follow-up ID). Optional; required for {@link Interaction.fetchReply}, {@link Interaction.editFollowUp} and {@link Interaction.deleteFollowUp}. */\n interactionWebhookMessage?(\n method: \"GET\" | \"PATCH\" | \"DELETE\",\n applicationId: string,\n token: string,\n messageId: string,\n data?: InteractionReplyOptions,\n ): Promise<unknown>;\n /** Lets structures built from an interaction (such as {@link Interaction.member}) act through the client. Optional. */\n readonly resourceContext?: ResourceContext;\n}\n\n/** Discord's ephemeral message flag. */\nconst EPHEMERAL = 64;\n/** Application command types (`data.type`): slash, user context menu, message context menu. */\nconst COMMAND_CHAT_INPUT = 1;\nconst COMMAND_USER = 2;\nconst COMMAND_MESSAGE = 3;\n/** Interaction tokens stay valid for 15 minutes. */\nconst TOKEN_LIFETIME_MS = 15 * 60_000;\nconst DISCORD_EPOCH = 1_420_070_400_000n;\n\n/** Takes the local-only `withResponse` key off reply options. */\nfunction splitWithResponse(options: InteractionReplyOptions | string): {\n withResponse: boolean;\n rest: InteractionReplyOptions | string;\n} {\n if (typeof options === \"string\")\n return { withResponse: false, rest: options };\n const { withResponse, ...rest } = options;\n return { withResponse: withResponse === true, rest };\n}\n\n/** Turns `{ ephemeral: true }` into Discord's flag and drops the local-only key. */\nfunction toMessageData(\n options: InteractionReplyOptions | string,\n): InteractionReplyOptions {\n if (typeof options === \"string\") return { content: options };\n const { ephemeral, ...data } = options;\n if (ephemeral)\n data.flags =\n (typeof data.flags === \"number\" ? data.flags : 0) | EPHEMERAL;\n return data;\n}\n\nexport { CommandOptions, type APIInteractionDataOption } from \"./options.js\";\nimport { CommandOptions, type APIInteractionDataOption } from \"./options.js\";\n\n// ─── Response class ───────────────────────────────────────────────────────────\n\n/** A Discord interaction callback payload. */\nexport class InteractionResponse {\n readonly type: number;\n readonly data?: InteractionReplyOptions;\n /** Ask Discord to return the created message (`?with_response=true`); not part of the body. */\n public withResponse = false;\n /** Creates a response payload. @param type Discord callback type. @param data Optional callback data. @throws {TypeError} If type is not finite. */\n public constructor(type: number, data?: InteractionReplyOptions) {\n if (!Number.isFinite(type))\n throw new TypeError(\"Interaction response type must be finite.\");\n this.type = type;\n this.data = data;\n }\n /** Serializes the response for Discord. @returns Discord callback payload. */ public toJSON(): {\n type: number;\n data?: InteractionReplyOptions;\n } {\n return this.data === undefined\n ? { type: this.type }\n : { type: this.type, data: this.data };\n }\n /** Creates an immediate message response. @param options Response message options. @returns Callback payload. */ public static message(\n options: InteractionReplyOptions,\n ): InteractionResponse {\n return new InteractionResponse(\n InteractionResponseEnum.ChannelMessage,\n toMessageData(options),\n );\n }\n /** Creates a deferred channel response. @param ephemeral Whether the eventual response is ephemeral. @returns Callback payload. */ public static defer(\n ephemeral = false,\n ): InteractionResponse {\n return new InteractionResponse(\n InteractionResponseEnum.DeferredChannelMessage,\n ephemeral ? { flags: EPHEMERAL } : undefined,\n );\n }\n /** Creates a Pong response. @returns Callback payload. */ public static pong(): InteractionResponse {\n return new InteractionResponse(InteractionResponseEnum.Pong);\n }\n}\n\n// ─── Base Interaction ─────────────────────────────────────────────────────────\n\n/** Base interaction structure. */\nexport class Interaction<TData extends InteractionData = InteractionData> {\n /** Interaction identifier. */ public readonly id: string;\n /** Application identifier. */ public readonly applicationId: string;\n /** Interaction token. */ public readonly token: string;\n /** Guild identifier. */ public readonly guildId?: string;\n /** Channel identifier. */ public readonly channelId?: string;\n /** Interaction type. */ public readonly type: number;\n /** Raw interaction data. */ public readonly data: TData;\n /** Whether the initial response was sent. */ public replied = false;\n /** Whether the initial response was deferred. */ public deferred = false;\n readonly #client: InteractionClient;\n /** An initial response is in flight; a second one must not be sent. */\n #acknowledging = false;\n /** Creates an interaction from a Gateway payload. @param client Interaction transport. @param data Gateway interaction payload. @throws {TypeError} If required identifiers are missing. */ public constructor(\n client: InteractionClient,\n data: TData,\n ) {\n if (!data.id || !data.token)\n throw new TypeError(\"Interaction ID and token are required.\");\n this.#client = client;\n this.id = data.id;\n this.applicationId = data.application_id;\n this.token = data.token;\n this.guildId = data.guild_id;\n this.channelId = data.channel_id;\n this.type = data.type;\n this.data = data;\n }\n /** The application command's own type (1 chat input, 2 user, 3 message); 0 when this is not a command. */\n #commandType(): number {\n if (this.type !== InteractionEnum.ApplicationCommand) return 0;\n const type = this.data.data?.type;\n return typeof type === \"number\" ? type : COMMAND_CHAT_INPUT;\n }\n /** Whether this interaction is any application command: slash or context menu. */\n public isCommand(): this is CommandInteraction {\n return this.type === InteractionEnum.ApplicationCommand;\n }\n /**\n * Whether this interaction is a slash (chat input) command. Since 0.2.2 this\n * is false for context-menu commands; use {@link isCommand} for both.\n */\n public isChatInputCommand(): this is CommandInteraction {\n return this.#commandType() === COMMAND_CHAT_INPUT;\n }\n /** Whether this interaction is a user or message context-menu command. */\n public isContextMenuCommand(): this is ContextMenuCommandInteraction {\n const type = this.#commandType();\n return type === COMMAND_USER || type === COMMAND_MESSAGE;\n }\n /** Whether this interaction is a user context-menu command (right-click a user). */\n public isUserContextMenuCommand(): this is ContextMenuCommandInteraction {\n return this.#commandType() === COMMAND_USER;\n }\n /** Whether this interaction is a message context-menu command (right-click a message). */\n public isMessageContextMenuCommand(): this is ContextMenuCommandInteraction {\n return this.#commandType() === COMMAND_MESSAGE;\n }\n /** The client context structures built from this interaction act through. */\n protected get resourceContext(): ResourceContext | undefined {\n return this.#client.resourceContext;\n }\n /**\n * Waits for this user to submit a modal, typically one this interaction\n * just opened with {@link showModal}.\n * @param options `time` (required, ms); optional `customId` and `filter`.\n * @returns The submission. @throws {Error} When time runs out first or no client is attached.\n * @example const submitted = await interaction.awaitModalSubmit({ time: 60_000, customId: \"feedback\" });\n */\n public awaitModalSubmit(options: {\n time: number;\n customId?: string;\n filter?: (\n interaction: ModalSubmitInteraction,\n ) => boolean | Promise<boolean>;\n }): Promise<ModalSubmitInteraction> {\n const collect = this.#client.resourceContext?.collectInteractions;\n if (!collect)\n return Promise.reject(\n new Error(\"This interaction is not attached to a client.\"),\n );\n if (!(options.time > 0))\n return Promise.reject(\n new RangeError(\"awaitModalSubmit needs a positive time.\"),\n );\n const userId = this.user?.id;\n const collector = collect({\n time: options.time,\n max: 1,\n filter: async (interaction) =>\n interaction.isModalSubmit() &&\n interaction.user?.id === userId &&\n (options.customId === undefined ||\n interaction.customId === options.customId) &&\n (options.filter ? await options.filter(interaction) : true),\n });\n return collector.next() as Promise<ModalSubmitInteraction>;\n }\n /** Whether this interaction is a message component. @returns True for component interactions. */ public isMessageComponent(): this is ComponentInteraction {\n return this.type === InteractionEnum.MessageComponent;\n }\n /** Whether this interaction is a modal submission. @returns True for modal submissions. */ public isModalSubmit(): this is ModalSubmitInteraction {\n return this.type === InteractionEnum.ModalSubmit;\n }\n /** Whether this interaction is autocomplete. @returns True for autocomplete interactions. */ public isAutocomplete(): this is AutocompleteInteraction {\n return this.type === InteractionEnum.ApplicationCommandAutocomplete;\n }\n /** Message component type of this interaction, or 0 when it is not a component. */\n #componentType(): number {\n return this.isMessageComponent()\n ? ((this.data.data?.component_type as number | undefined) ?? 0)\n : 0;\n }\n /** Whether this is a button interaction. */ public isButton(): this is ComponentInteraction {\n return this.#componentType() === 2;\n }\n /** Whether this is a string select menu interaction. */ public isStringSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 3;\n }\n /** Whether this is a user select menu interaction. */ public isUserSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 5;\n }\n /** Whether this is a role select menu interaction. */ public isRoleSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 6;\n }\n /** Whether this is a mentionable select menu interaction. */ public isMentionableSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 7;\n }\n /** Whether this is a channel select menu interaction. */ public isChannelSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 8;\n }\n /** Whether this is any select menu interaction. */ public isAnySelectMenu(): this is ComponentInteraction {\n return [3, 5, 6, 7, 8].includes(this.#componentType());\n }\n /** Ensures the interaction has not already been acknowledged. @returns Nothing. @throws {Error} When already acknowledged. */ protected assertUnacknowledged(): void {\n if (this.replied || this.deferred || this.#acknowledging)\n throw new Error(\"Interaction has already been acknowledged.\");\n }\n /**\n * Sends the initial response exactly once. The in-flight flag is set\n * before the request, so two concurrent calls cannot both send; it is\n * cleared if the request fails so the caller may try again.\n */\n protected async acknowledge(\n response: InteractionResponse,\n state: \"replied\" | \"deferred\",\n ): Promise<unknown> {\n this.assertUnacknowledged();\n this.#acknowledging = true;\n try {\n const result = await this.postResponse(response);\n this[state] = true;\n return result;\n } finally {\n this.#acknowledging = false;\n }\n }\n /** The invoking user (from `member.user` in guilds, `user` in DMs). */\n public get user(): User | null {\n const raw =\n (this.data.member as { user?: unknown } | undefined)?.user ??\n this.data.user;\n return raw\n ? new User(raw as ConstructorParameters<typeof User>[0])\n : null;\n }\n /** The invoking guild member, or null outside a guild. */\n public get member(): GuildMember | null {\n const raw = this.data.member;\n if (!raw || !this.guildId) return null;\n return new GuildMember(\n {\n ...(raw as Omit<\n ConstructorParameters<typeof GuildMember>[0],\n \"guild_id\"\n >),\n guild_id: this.guildId,\n },\n this.#client.resourceContext,\n );\n }\n /** Unix timestamp (ms) at which the interaction was created, from its snowflake. */\n public get createdTimestamp(): number {\n return Number((BigInt(this.id) >> 22n) + DISCORD_EPOCH);\n }\n /** When the interaction token stops working (15 minutes after creation). */\n public get expiresAt(): Date {\n return new Date(this.createdTimestamp + TOKEN_LIFETIME_MS);\n }\n /** Whether the token has expired; no response, edit or follow-up can succeed after that. */\n public get isExpired(): boolean {\n return Date.now() >= this.createdTimestamp + TOKEN_LIFETIME_MS;\n }\n #webhookMessage(\n method: \"GET\" | \"PATCH\" | \"DELETE\",\n messageId: string,\n data?: InteractionReplyOptions,\n ): Promise<unknown> {\n if (!this.#client.interactionWebhookMessage)\n return Promise.reject(\n new Error(\n \"This interaction client does not support webhook message access.\",\n ),\n );\n return this.#client.interactionWebhookMessage(\n method,\n this.applicationId,\n this.token,\n messageId,\n data,\n );\n }\n /** Fetches the original response message. */\n public fetchReply(): Promise<unknown> {\n this.assertAcknowledged();\n return this.#webhookMessage(\"GET\", \"@original\");\n }\n /** Edits a follow-up message. @param messageId Follow-up message ID. */\n public editFollowUp(\n messageId: string,\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n return this.#webhookMessage(\"PATCH\", messageId, toMessageData(options));\n }\n /** Deletes a follow-up message. @param messageId Follow-up message ID. */\n public async deleteFollowUp(messageId: string): Promise<void> {\n await this.#webhookMessage(\"DELETE\", messageId);\n }\n /** Ensures the interaction has been acknowledged. @returns Nothing. @throws {Error} When not acknowledged. */ protected assertAcknowledged(): void {\n if (!this.replied && !this.deferred)\n throw new Error(\"Interaction has not been acknowledged.\");\n }\n /** Posts a raw interaction response callback. */\n protected postResponse(response: InteractionResponse): Promise<unknown> {\n return this.#client.postInteractionResponse(\n this.id,\n this.token,\n response,\n );\n }\n /**\n * Sends a response and, when `withResponse` is set, turns the callback\n * resource Discord returns into the created message.\n */\n protected async acknowledgeWith(\n response: InteractionResponse,\n state: \"replied\" | \"deferred\",\n withResponse: boolean,\n ): Promise<unknown> {\n response.withResponse = withResponse;\n const result = await this.acknowledge(response, state);\n if (!withResponse) return result;\n const message = (result as { resource?: { message?: unknown } } | null)\n ?.resource?.message;\n return message\n ? new Message(\n message as ConstructorParameters<typeof Message>[0],\n this.#client.resourceContext,\n )\n : null;\n }\n /**\n * Sends the initial interaction response. With `withResponse: true` it\n * returns the created {@link Message} in the same request (no `fetchReply()`).\n * @throws {Error} When already acknowledged or REST fails.\n */\n public async reply(\n options: InteractionReplyOptions & { withResponse: true },\n ): Promise<Message | null>;\n public async reply(\n options: InteractionReplyOptions | string,\n ): Promise<unknown>;\n public async reply(\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n const { withResponse, rest } = splitWithResponse(options);\n return this.acknowledgeWith(\n InteractionResponse.message(toMessageData(rest)),\n \"replied\",\n withResponse,\n );\n }\n /**\n * Defers the initial interaction response. `true` or `{ ephemeral: true }`\n * makes the eventual response private; `withResponse: true` returns the\n * placeholder message. @throws {Error} When already acknowledged or REST fails.\n */\n public async deferReply(options: {\n ephemeral?: boolean;\n withResponse: true;\n }): Promise<Message | null>;\n public async deferReply(\n options?: boolean | { ephemeral?: boolean; withResponse?: boolean },\n ): Promise<void>;\n public async deferReply(\n options:\n boolean | { ephemeral?: boolean; withResponse?: boolean } = false,\n ): Promise<Message | null | void> {\n const ephemeral =\n typeof options === \"boolean\" ? options : options.ephemeral === true;\n const withResponse =\n typeof options === \"object\" && options.withResponse === true;\n const result = await this.acknowledgeWith(\n InteractionResponse.defer(ephemeral),\n \"deferred\",\n withResponse,\n );\n if (withResponse) return result as Message | null;\n }\n /** Edits the original response. @param options Replacement message options. @returns Discord response. @throws {Error} When not acknowledged or REST fails. */ public editReply(\n options: InteractionReplyOptions,\n ): Promise<unknown> {\n this.assertAcknowledged();\n return this.#client.editInteractionReply(\n this.token,\n toMessageData(options),\n );\n }\n /** Deletes the original response. @returns Promise fulfilled after deletion. @throws {Error} When not acknowledged or REST fails. */ public deleteReply(): Promise<void> {\n this.assertAcknowledged();\n return this.#client.deleteInteractionReply(this.token);\n }\n /** Sends a follow-up message using the interaction webhook. @param options Follow-up message options. @returns Discord response. @throws {Error} When REST fails. */ public followUp(\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n return this.#client.followUpInteraction(\n this.token,\n toMessageData(options),\n );\n }\n /**\n * Updates the message a component is on. With `withResponse: true` it\n * returns the updated {@link Message}.\n */\n public async update(\n options: InteractionReplyOptions & { withResponse: true },\n ): Promise<Message | null>;\n public async update(\n options: InteractionReplyOptions | string,\n ): Promise<unknown>;\n public async update(\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n const { withResponse, rest } = splitWithResponse(options);\n return this.acknowledgeWith(\n new InteractionResponse(\n InteractionResponseEnum.MessageUpdate,\n toMessageData(rest),\n ),\n \"replied\",\n withResponse,\n );\n }\n /** Opens a modal dialog in the user's client. @param modal Modal builder output or raw modal callback data. @returns Discord response. @throws {Error} When already acknowledged or REST fails. */\n public async showModal(\n modal:\n | {\n toJSON(): {\n custom_id: string;\n title: string;\n components: unknown[];\n };\n }\n // No index signature: an interface such as the builder's\n // `APIModalComponent` (what `toJSON()` returns) must be assignable.\n | {\n custom_id: string;\n title: string;\n components: readonly unknown[];\n },\n ): Promise<unknown> {\n const data =\n \"toJSON\" in modal && typeof modal.toJSON === \"function\"\n ? modal.toJSON()\n : modal;\n return this.acknowledge(\n new InteractionResponse(\n InteractionResponseEnum.Modal,\n data as InteractionReplyOptions,\n ),\n \"replied\",\n );\n }\n}\n\n// ─── CommandInteraction ───────────────────────────────────────────────────────\n\n/** Application command interaction with fully typed option resolver. */\nexport class CommandInteraction extends Interaction {\n /** Typed option resolver. Access slash command options with full type safety. */\n public readonly options: CommandOptions;\n\n /** Invoked command name. @returns Command name or an empty string. */ public get commandName(): string {\n return typeof this.data.data?.name === \"string\"\n ? this.data.data.name\n : \"\";\n }\n\n public constructor(client: InteractionClient, data: InteractionData) {\n super(client, data);\n const rawOptions =\n (data.data?.options as APIInteractionDataOption[]) ?? [];\n const resolved = (data.data?.resolved as Record<string, unknown>) ?? {};\n // Hand the resolver the *top-level* options. CommandOptions performs the\n // subcommand/group drill itself and records the names it walks through;\n // pre-drilling here would strip those wrappers before it sees them, so\n // getSubcommand()/getSubcommandGroup() would report null.\n this.options = new CommandOptions(rawOptions, resolved);\n }\n}\n\n// ─── ContextMenuCommandInteraction ───────────────────────────────────────────\n\n/** A user or message context-menu command, with what was right-clicked. */\nexport class ContextMenuCommandInteraction extends CommandInteraction {\n #resolved(): Record<string, Record<string, unknown> | undefined> {\n return (this.data.data?.resolved ?? {}) as Record<\n string,\n Record<string, unknown> | undefined\n >;\n }\n /** ID of the user or message the command was used on. */\n public get targetId(): string | null {\n const id = this.data.data?.target_id;\n return typeof id === \"string\" ? id : null;\n }\n /** The user a user command was used on. */\n public get targetUser(): User | null {\n const id = this.targetId;\n const raw = id ? this.#resolved().users?.[id] : undefined;\n return raw\n ? new User(raw as ConstructorParameters<typeof User>[0])\n : null;\n }\n /** The member a user command was used on (in a guild), with member actions when attached to a client. */\n public get targetMember(): GuildMember | null {\n const id = this.targetId;\n const raw = id ? this.#resolved().members?.[id] : undefined;\n const user = id ? this.#resolved().users?.[id] : undefined;\n if (!raw || !user || !this.guildId) return null;\n return new GuildMember(\n {\n ...(raw as Omit<\n ConstructorParameters<typeof GuildMember>[0],\n \"guild_id\" | \"user\"\n >),\n user: user as ConstructorParameters<\n typeof GuildMember\n >[0][\"user\"],\n guild_id: this.guildId,\n },\n this.resourceContext,\n );\n }\n /** The message a message command was used on. */\n public get targetMessage(): Message | null {\n const id = this.targetId;\n const raw = id ? this.#resolved().messages?.[id] : undefined;\n return raw\n ? new Message(\n raw as unknown as ConstructorParameters<typeof Message>[0],\n this.resourceContext,\n )\n : null;\n }\n}\n\n// ─── ComponentInteraction ─────────────────────────────────────────────────────\n\n/** Message component interaction. */\nexport class ComponentInteraction extends Interaction {\n /** Gets component custom ID. */\n public get customId(): string {\n const id = this.data.data?.custom_id;\n return typeof id === \"string\" ? id : \"\";\n }\n /** ID of the message the component is on. */\n public get messageId(): string | undefined {\n return (this.data.message as { id?: string } | undefined)?.id;\n }\n /** Gets component type. */\n public get componentType(): number {\n const type = this.data.data?.component_type;\n return typeof type === \"number\" ? type : 0;\n }\n /** Gets selected values for select menu component interactions. */\n public get values(): string[] {\n const values = this.data.data?.values;\n return Array.isArray(values) ? (values as string[]) : [];\n }\n /** Defers updating the message to which the component was attached. */\n public async deferUpdate(options: {\n withResponse: true;\n }): Promise<Message | null>;\n public async deferUpdate(options?: {\n withResponse?: boolean;\n }): Promise<void>;\n public async deferUpdate(\n options: { withResponse?: boolean } = {},\n ): Promise<Message | null | void> {\n const withResponse = options.withResponse === true;\n const result = await this.acknowledgeWith(\n new InteractionResponse(\n InteractionResponseEnum.DeferredMessageUpdate,\n ),\n \"deferred\",\n withResponse,\n );\n if (withResponse) return result as Message | null;\n }\n}\n\n// ─── ModalSubmitInteraction ───────────────────────────────────────────────────\n\n/** Represents a Discord modal submission interaction. */\nexport class ModalSubmitInteraction extends Interaction {\n /** Gets the submitted modal custom ID. */\n public get customId(): string {\n const id = this.data.data?.custom_id;\n return typeof id === \"string\" ? id : \"\";\n }\n\n /** Retrieves the text value for a specific text input custom ID. @param customId The custom_id of the text input component. @returns The submitted text, or undefined if not found. */\n public getInputValue(customId: string): string | undefined {\n const rows =\n (this.data.data?.components as\n | { components?: { custom_id?: string; value?: string }[] }[]\n | undefined) ?? [];\n for (const row of rows) {\n for (const comp of row.components ?? []) {\n if (comp.custom_id === customId) return comp.value;\n }\n }\n return undefined;\n }\n\n /** Retrieves the text value for a text input, throwing if missing. @param customId The custom_id of the text input component. @returns The submitted text. @throws {TypeError} If the field is not found. */\n public getRequiredInputValue(customId: string): string {\n const value = this.getInputValue(customId);\n if (value === undefined)\n throw new TypeError(\n `Modal input \"${customId}\" was not found in the submission.`,\n );\n return value;\n }\n}\n\n// ─── AutocompleteInteraction ──────────────────────────────────────────────────\n\n/** Represents a Discord slash command autocomplete interaction. */\nexport class AutocompleteInteraction extends Interaction {\n /** Option resolver; use `options.getFocused()` for the focused value. */\n public readonly options: CommandOptions;\n\n public constructor(client: InteractionClient, data: InteractionData) {\n super(client, data);\n this.options = new CommandOptions(\n (data.data?.options as APIInteractionDataOption[]) ?? [],\n );\n }\n\n /** Gets the target command name. */\n public get commandName(): string {\n const name = this.data.data?.name;\n return typeof name === \"string\" ? name : \"\";\n }\n\n /** Gets the currently focused autocomplete option. */\n public get focusedOption():\n { name: string; value: unknown; type: number } | undefined {\n const options = this.data.data?.options;\n return findFocused(\n Array.isArray(options) ? (options as FocusableOption[]) : [],\n );\n }\n\n /** Responds to Discord with autocomplete choices. @param choices Array of name/value pairs to show. @throws {TypeError} If choices is not an array. */\n public async respond(\n choices: { name: string; value: string | number }[],\n ): Promise<void> {\n if (!Array.isArray(choices))\n throw new TypeError(\"Autocomplete choices must be an array.\");\n const response = new InteractionResponse(\n InteractionResponseEnum.Autocomplete,\n { choices } as InteractionReplyOptions,\n );\n await this.acknowledge(response, \"replied\");\n }\n}\n\n/** An option as Discord sends it in autocomplete data. */\ninterface FocusableOption {\n name: string;\n value?: unknown;\n type: number;\n focused?: boolean;\n options?: FocusableOption[];\n}\n\n/** Recursively finds the focused option in a nested options tree. */\nfunction findFocused(\n options: FocusableOption[],\n): { name: string; value: unknown; type: number } | undefined {\n for (const opt of options) {\n if (opt.focused)\n return { name: opt.name, value: opt.value, type: opt.type };\n if (Array.isArray(opt.options)) {\n const found = findFocused(opt.options);\n if (found) return found;\n }\n }\n return undefined;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/**\n * Creates a specialized interaction structure for a Gateway payload.\n * @param client Interaction transport.\n * @param data Gateway interaction payload.\n * @returns Specialized interaction structure.\n * @throws {TypeError} If required identifiers are missing.\n */\nexport function createInteraction(\n client: InteractionClient,\n data: InteractionData,\n): Interaction {\n switch (data.type) {\n case InteractionEnum.ApplicationCommand: {\n const commandType = data.data?.type;\n return commandType === COMMAND_USER ||\n commandType === COMMAND_MESSAGE\n ? new ContextMenuCommandInteraction(client, data)\n : new CommandInteraction(client, data);\n }\n case InteractionEnum.ApplicationCommandAutocomplete:\n return new AutocompleteInteraction(client, data);\n case InteractionEnum.MessageComponent:\n return new ComponentInteraction(client, data);\n case InteractionEnum.ModalSubmit:\n return new ModalSubmitInteraction(client, data);\n default:\n return new Interaction(client, data);\n }\n}\n\n/** @deprecated Use {@link InteractionEnum}. Removed in 0.3.0. */\nexport const InteractionType = InteractionEnum;\n/** @deprecated Use {@link InteractionEnum}. Removed in 0.3.0. */\nexport type InteractionType = InteractionEnum;\n",
21
+ "import {\n InteractionResponseEnum,\n type APIEntitlement,\n type InteractionReplyOptions,\n} from \"@lunibee/types\";\nimport { User, type ResourceContext } from \"./base.js\";\nimport { GuildMember } from \"./resources.js\";\n// A cycle with index.ts: Message is only used lazily (in a getter), after both modules loaded.\nimport { Message } from \"./index.js\";\n\n/** Discord interaction type constants. */\nexport const InteractionEnum = {\n Ping: 1,\n ApplicationCommand: 2,\n MessageComponent: 3,\n ApplicationCommandAutocomplete: 4,\n ModalSubmit: 5,\n} as const;\n/** One {@link InteractionEnum} value, usable as a type. */\nexport type InteractionEnum =\n (typeof InteractionEnum)[keyof typeof InteractionEnum];\n// Re-export for consumers who import from structures directly\nexport { InteractionResponseEnum } from \"@lunibee/types\";\n/** Data shared by Discord interactions. */\nexport interface InteractionData {\n /** Interaction identifier. */\n id: string;\n /** Application identifier. */\n application_id: string;\n /** Interaction type. */\n type: number;\n /** Interaction token. */\n token: string;\n /** Gateway/API version. */\n version?: number;\n /** Guild identifier. */\n guild_id?: string;\n /** Channel identifier. */\n channel_id?: string;\n /** Interaction-specific data. */\n data?: Record<string, unknown>;\n [key: string]: unknown;\n}\nexport type { InteractionReplyOptions };\n/** Transport required by an interaction structure. */\nexport interface InteractionClient {\n /** Sends the initial interaction callback. @param id Interaction identifier. @param token Interaction token. @param response Callback payload. @returns Discord response. @throws {Error} When REST fails. */\n postInteractionResponse(\n id: string,\n token: string,\n response: InteractionResponse,\n ): Promise<unknown>;\n /** Edits the original interaction response. @param token Interaction token. @param data Message payload. @returns Discord response. @throws {Error} When REST fails. */\n editInteractionReply(\n token: string,\n data: InteractionReplyOptions,\n ): Promise<unknown>;\n /** Deletes the original interaction response. @param token Interaction token. @returns Promise fulfilled after deletion. @throws {Error} When REST fails. */\n deleteInteractionReply(token: string): Promise<void>;\n /** Sends a follow-up interaction webhook message. @param token Interaction token. @param data Message payload. @returns Discord response. @throws {Error} When REST fails. */\n followUpInteraction(\n token: string,\n data: InteractionReplyOptions,\n ): Promise<unknown>;\n /** Reads, edits or deletes an interaction webhook message (`@original` or a follow-up ID). Optional; required for {@link Interaction.fetchReply}, {@link Interaction.editFollowUp} and {@link Interaction.deleteFollowUp}. */\n interactionWebhookMessage?(\n method: \"GET\" | \"PATCH\" | \"DELETE\",\n applicationId: string,\n token: string,\n messageId: string,\n data?: InteractionReplyOptions,\n ): Promise<unknown>;\n /** Lets structures built from an interaction (such as {@link Interaction.member}) act through the client. Optional. */\n readonly resourceContext?: ResourceContext;\n}\n\n/** Discord's ephemeral message flag. */\nconst EPHEMERAL = 64;\n/** Application command types (`data.type`): slash, user context menu, message context menu. */\nconst COMMAND_CHAT_INPUT = 1;\nconst COMMAND_USER = 2;\nconst COMMAND_MESSAGE = 3;\n/** Interaction tokens stay valid for 15 minutes. */\nconst TOKEN_LIFETIME_MS = 15 * 60_000;\nconst DISCORD_EPOCH = 1_420_070_400_000n;\n\n/** Takes the local-only `withResponse` key off reply options. */\nfunction splitWithResponse(options: InteractionReplyOptions | string): {\n withResponse: boolean;\n rest: InteractionReplyOptions | string;\n} {\n if (typeof options === \"string\")\n return { withResponse: false, rest: options };\n const { withResponse, ...rest } = options;\n return { withResponse: withResponse === true, rest };\n}\n\n/** Turns `{ ephemeral: true }` into Discord's flag and drops the local-only key. */\nfunction toMessageData(\n options: InteractionReplyOptions | string,\n): InteractionReplyOptions {\n if (typeof options === \"string\") return { content: options };\n const { ephemeral, ...data } = options;\n if (ephemeral)\n data.flags =\n (typeof data.flags === \"number\" ? data.flags : 0) | EPHEMERAL;\n return data;\n}\n\nexport { CommandOptions, type APIInteractionDataOption } from \"./options.js\";\nimport { CommandOptions, type APIInteractionDataOption } from \"./options.js\";\n\n// ─── Response class ───────────────────────────────────────────────────────────\n\n/** A Discord interaction callback payload. */\nexport class InteractionResponse {\n readonly type: number;\n readonly data?: InteractionReplyOptions;\n /** Ask Discord to return the created message (`?with_response=true`); not part of the body. */\n public withResponse = false;\n /** Creates a response payload. @param type Discord callback type. @param data Optional callback data. @throws {TypeError} If type is not finite. */\n public constructor(type: number, data?: InteractionReplyOptions) {\n if (!Number.isFinite(type))\n throw new TypeError(\"Interaction response type must be finite.\");\n this.type = type;\n this.data = data;\n }\n /** Serializes the response for Discord. @returns Discord callback payload. */\n public toJSON(): {\n type: number;\n data?: InteractionReplyOptions;\n } {\n return this.data === undefined\n ? { type: this.type }\n : { type: this.type, data: this.data };\n }\n /** Creates an immediate message response. @param options Response message options. @returns Callback payload. */\n public static message(\n options: InteractionReplyOptions,\n ): InteractionResponse {\n return new InteractionResponse(\n InteractionResponseEnum.ChannelMessage,\n toMessageData(options),\n );\n }\n /** Creates a deferred channel response. @param ephemeral Whether the eventual response is ephemeral. @returns Callback payload. */\n public static defer(ephemeral = false): InteractionResponse {\n return new InteractionResponse(\n InteractionResponseEnum.DeferredChannelMessage,\n ephemeral ? { flags: EPHEMERAL } : undefined,\n );\n }\n /** Creates a Pong response. @returns Callback payload. */\n public static pong(): InteractionResponse {\n return new InteractionResponse(InteractionResponseEnum.Pong);\n }\n}\n\n// ─── Base Interaction ─────────────────────────────────────────────────────────\n\n/** Base interaction structure. */\nexport class Interaction<TData extends InteractionData = InteractionData> {\n /** Interaction identifier. */\n public readonly id: string;\n /** Application identifier. */\n public readonly applicationId: string;\n /** Interaction token. */\n public readonly token: string;\n /** Guild identifier. */\n public readonly guildId?: string;\n /** Channel identifier. */\n public readonly channelId?: string;\n /** Interaction type. */\n public readonly type: number;\n /** Raw interaction data. */\n public readonly data: TData;\n /** Whether the initial response was sent. */\n public replied = false;\n /** Whether the initial response was deferred. */\n public deferred = false;\n readonly #client: InteractionClient;\n /** An initial response is in flight; a second one must not be sent. */\n #acknowledging = false;\n /** Creates an interaction from a Gateway payload. @param client Interaction transport. @param data Gateway interaction payload. @throws {TypeError} If required identifiers are missing. */\n public constructor(client: InteractionClient, data: TData) {\n if (!data.id || !data.token)\n throw new TypeError(\"Interaction ID and token are required.\");\n this.#client = client;\n this.id = data.id;\n this.applicationId = data.application_id;\n this.token = data.token;\n this.guildId = data.guild_id;\n this.channelId = data.channel_id;\n this.type = data.type;\n this.data = data;\n }\n /** The entitlements of the person (and guild) that ran this interaction: what they own from your SKUs. */\n public get entitlements(): readonly APIEntitlement[] {\n const entitlements = this.data.entitlements;\n return Array.isArray(entitlements)\n ? (entitlements as APIEntitlement[])\n : [];\n }\n /** Whether the interaction carries an active entitlement for a SKU. */\n public hasEntitlement(skuId: string): boolean {\n const now = Date.now();\n return this.entitlements.some(\n (entitlement) =>\n entitlement.sku_id === skuId &&\n !entitlement.deleted &&\n (!entitlement.ends_at || Date.parse(entitlement.ends_at) > now),\n );\n }\n /** The application command's own type (1 chat input, 2 user, 3 message); 0 when this is not a command. */\n #commandType(): number {\n if (this.type !== InteractionEnum.ApplicationCommand) return 0;\n const type = this.data.data?.type;\n return typeof type === \"number\" ? type : COMMAND_CHAT_INPUT;\n }\n /** Whether this interaction is any application command: slash or context menu. */\n public isCommand(): this is CommandInteraction {\n return this.type === InteractionEnum.ApplicationCommand;\n }\n /**\n * Whether this interaction is a slash (chat input) command. Since 0.2.2 this\n * is false for context-menu commands; use {@link isCommand} for both.\n */\n public isChatInputCommand(): this is CommandInteraction {\n return this.#commandType() === COMMAND_CHAT_INPUT;\n }\n /** Whether this interaction is a user or message context-menu command. */\n public isContextMenuCommand(): this is ContextMenuCommandInteraction {\n const type = this.#commandType();\n return type === COMMAND_USER || type === COMMAND_MESSAGE;\n }\n /** Whether this interaction is a user context-menu command (right-click a user). */\n public isUserContextMenuCommand(): this is ContextMenuCommandInteraction {\n return this.#commandType() === COMMAND_USER;\n }\n /** Whether this interaction is a message context-menu command (right-click a message). */\n public isMessageContextMenuCommand(): this is ContextMenuCommandInteraction {\n return this.#commandType() === COMMAND_MESSAGE;\n }\n /** The client context structures built from this interaction act through. */\n protected get resourceContext(): ResourceContext | undefined {\n return this.#client.resourceContext;\n }\n /**\n * Waits for this user to submit a modal, typically one this interaction\n * just opened with {@link showModal}.\n * @param options `time` (required, ms); optional `customId` and `filter`.\n * @returns The submission. @throws {Error} When time runs out first or no client is attached.\n * @example const submitted = await interaction.awaitModalSubmit({ time: 60_000, customId: \"feedback\" });\n */\n public awaitModalSubmit(options: {\n time: number;\n customId?: string;\n filter?: (\n interaction: ModalSubmitInteraction,\n ) => boolean | Promise<boolean>;\n }): Promise<ModalSubmitInteraction> {\n const collect = this.#client.resourceContext?.collectInteractions;\n if (!collect)\n return Promise.reject(\n new Error(\"This interaction is not attached to a client.\"),\n );\n if (!(options.time > 0))\n return Promise.reject(\n new RangeError(\"awaitModalSubmit needs a positive time.\"),\n );\n const userId = this.user?.id;\n const collector = collect({\n time: options.time,\n max: 1,\n filter: async (interaction) =>\n interaction.isModalSubmit() &&\n interaction.user?.id === userId &&\n (options.customId === undefined ||\n interaction.customId === options.customId) &&\n (options.filter ? await options.filter(interaction) : true),\n });\n return collector.next() as Promise<ModalSubmitInteraction>;\n }\n /** Whether this interaction is a message component. @returns True for component interactions. */\n public isMessageComponent(): this is ComponentInteraction {\n return this.type === InteractionEnum.MessageComponent;\n }\n /** Whether this interaction is a modal submission. @returns True for modal submissions. */\n public isModalSubmit(): this is ModalSubmitInteraction {\n return this.type === InteractionEnum.ModalSubmit;\n }\n /** Whether this interaction is autocomplete. @returns True for autocomplete interactions. */\n public isAutocomplete(): this is AutocompleteInteraction {\n return this.type === InteractionEnum.ApplicationCommandAutocomplete;\n }\n /** Message component type of this interaction, or 0 when it is not a component. */\n #componentType(): number {\n return this.isMessageComponent()\n ? ((this.data.data?.component_type as number | undefined) ?? 0)\n : 0;\n }\n /** Whether this is a button interaction. */\n public isButton(): this is ComponentInteraction {\n return this.#componentType() === 2;\n }\n /** Whether this is a string select menu interaction. */\n public isStringSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 3;\n }\n /** Whether this is a user select menu interaction. */\n public isUserSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 5;\n }\n /** Whether this is a role select menu interaction. */\n public isRoleSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 6;\n }\n /** Whether this is a mentionable select menu interaction. */\n public isMentionableSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 7;\n }\n /** Whether this is a channel select menu interaction. */\n public isChannelSelectMenu(): this is ComponentInteraction {\n return this.#componentType() === 8;\n }\n /** Whether this is any select menu interaction. */\n public isAnySelectMenu(): this is ComponentInteraction {\n return [3, 5, 6, 7, 8].includes(this.#componentType());\n }\n /** Ensures the interaction has not already been acknowledged. @returns Nothing. @throws {Error} When already acknowledged. */\n protected assertUnacknowledged(): void {\n if (this.replied || this.deferred || this.#acknowledging)\n throw new Error(\"Interaction has already been acknowledged.\");\n }\n /**\n * Sends the initial response exactly once. The in-flight flag is set\n * before the request, so two concurrent calls cannot both send; it is\n * cleared if the request fails so the caller may try again.\n */\n protected async acknowledge(\n response: InteractionResponse,\n state: \"replied\" | \"deferred\",\n ): Promise<unknown> {\n this.assertUnacknowledged();\n this.#acknowledging = true;\n try {\n const result = await this.postResponse(response);\n this[state] = true;\n return result;\n } finally {\n this.#acknowledging = false;\n }\n }\n /** The invoking user (from `member.user` in guilds, `user` in DMs). */\n public get user(): User | null {\n const raw =\n (this.data.member as { user?: unknown } | undefined)?.user ??\n this.data.user;\n return raw\n ? new User(raw as ConstructorParameters<typeof User>[0])\n : null;\n }\n /** The invoking guild member, or null outside a guild. */\n public get member(): GuildMember | null {\n const raw = this.data.member;\n if (!raw || !this.guildId) return null;\n return new GuildMember(\n {\n ...(raw as Omit<\n ConstructorParameters<typeof GuildMember>[0],\n \"guild_id\"\n >),\n guild_id: this.guildId,\n },\n this.#client.resourceContext,\n );\n }\n /** Unix timestamp (ms) at which the interaction was created, from its snowflake. */\n public get createdTimestamp(): number {\n return Number((BigInt(this.id) >> 22n) + DISCORD_EPOCH);\n }\n /** When the interaction token stops working (15 minutes after creation). */\n public get expiresAt(): Date {\n return new Date(this.createdTimestamp + TOKEN_LIFETIME_MS);\n }\n /** Whether the token has expired; no response, edit or follow-up can succeed after that. */\n public get isExpired(): boolean {\n return Date.now() >= this.createdTimestamp + TOKEN_LIFETIME_MS;\n }\n #webhookMessage(\n method: \"GET\" | \"PATCH\" | \"DELETE\",\n messageId: string,\n data?: InteractionReplyOptions,\n ): Promise<unknown> {\n if (!this.#client.interactionWebhookMessage)\n return Promise.reject(\n new Error(\n \"This interaction client does not support webhook message access.\",\n ),\n );\n return this.#client.interactionWebhookMessage(\n method,\n this.applicationId,\n this.token,\n messageId,\n data,\n );\n }\n /** Fetches the original response message. */\n public fetchReply(): Promise<unknown> {\n this.assertAcknowledged();\n return this.#webhookMessage(\"GET\", \"@original\");\n }\n /** Edits a follow-up message. @param messageId Follow-up message ID. */\n public editFollowUp(\n messageId: string,\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n return this.#webhookMessage(\"PATCH\", messageId, toMessageData(options));\n }\n /** Deletes a follow-up message. @param messageId Follow-up message ID. */\n public async deleteFollowUp(messageId: string): Promise<void> {\n await this.#webhookMessage(\"DELETE\", messageId);\n }\n /** Ensures the interaction has been acknowledged. @returns Nothing. @throws {Error} When not acknowledged. */\n protected assertAcknowledged(): void {\n if (!this.replied && !this.deferred)\n throw new Error(\"Interaction has not been acknowledged.\");\n }\n /** Posts a raw interaction response callback. */\n protected postResponse(response: InteractionResponse): Promise<unknown> {\n return this.#client.postInteractionResponse(\n this.id,\n this.token,\n response,\n );\n }\n /**\n * Sends a response and, when `withResponse` is set, turns the callback\n * resource Discord returns into the created message.\n */\n protected async acknowledgeWith(\n response: InteractionResponse,\n state: \"replied\" | \"deferred\",\n withResponse: boolean,\n ): Promise<unknown> {\n response.withResponse = withResponse;\n const result = await this.acknowledge(response, state);\n if (!withResponse) return result;\n const message = (result as { resource?: { message?: unknown } } | null)\n ?.resource?.message;\n return message\n ? new Message(\n message as ConstructorParameters<typeof Message>[0],\n this.#client.resourceContext,\n )\n : null;\n }\n /**\n * Sends the initial interaction response. With `withResponse: true` it\n * returns the created {@link Message} in the same request (no `fetchReply()`).\n * @throws {Error} When already acknowledged or REST fails.\n */\n public async reply(\n options: InteractionReplyOptions & { withResponse: true },\n ): Promise<Message | null>;\n public async reply(\n options: InteractionReplyOptions | string,\n ): Promise<unknown>;\n public async reply(\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n const { withResponse, rest } = splitWithResponse(options);\n return this.acknowledgeWith(\n InteractionResponse.message(toMessageData(rest)),\n \"replied\",\n withResponse,\n );\n }\n /**\n * Defers the initial interaction response. `true` or `{ ephemeral: true }`\n * makes the eventual response private; `withResponse: true` returns the\n * placeholder message. @throws {Error} When already acknowledged or REST fails.\n */\n public async deferReply(options: {\n ephemeral?: boolean;\n withResponse: true;\n }): Promise<Message | null>;\n public async deferReply(\n options?: boolean | { ephemeral?: boolean; withResponse?: boolean },\n ): Promise<void>;\n public async deferReply(\n options:\n boolean | { ephemeral?: boolean; withResponse?: boolean } = false,\n ): Promise<Message | null | void> {\n const ephemeral =\n typeof options === \"boolean\" ? options : options.ephemeral === true;\n const withResponse =\n typeof options === \"object\" && options.withResponse === true;\n const result = await this.acknowledgeWith(\n InteractionResponse.defer(ephemeral),\n \"deferred\",\n withResponse,\n );\n if (withResponse) return result as Message | null;\n }\n /** Edits the original response. @param options Replacement message options. @returns Discord response. @throws {Error} When not acknowledged or REST fails. */\n public editReply(options: InteractionReplyOptions): Promise<unknown> {\n this.assertAcknowledged();\n return this.#client.editInteractionReply(\n this.token,\n toMessageData(options),\n );\n }\n /** Deletes the original response. @returns Promise fulfilled after deletion. @throws {Error} When not acknowledged or REST fails. */\n public deleteReply(): Promise<void> {\n this.assertAcknowledged();\n return this.#client.deleteInteractionReply(this.token);\n }\n /** Sends a follow-up message using the interaction webhook. @param options Follow-up message options. @returns Discord response. @throws {Error} When REST fails. */\n public followUp(\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n return this.#client.followUpInteraction(\n this.token,\n toMessageData(options),\n );\n }\n /**\n * Updates the message a component is on. With `withResponse: true` it\n * returns the updated {@link Message}.\n */\n public async update(\n options: InteractionReplyOptions & { withResponse: true },\n ): Promise<Message | null>;\n public async update(\n options: InteractionReplyOptions | string,\n ): Promise<unknown>;\n public async update(\n options: InteractionReplyOptions | string,\n ): Promise<unknown> {\n const { withResponse, rest } = splitWithResponse(options);\n return this.acknowledgeWith(\n new InteractionResponse(\n InteractionResponseEnum.MessageUpdate,\n toMessageData(rest),\n ),\n \"replied\",\n withResponse,\n );\n }\n /** Opens a modal dialog in the user's client. @param modal Modal builder output or raw modal callback data. @returns Discord response. @throws {Error} When already acknowledged or REST fails. */\n public async showModal(\n modal:\n | {\n toJSON(): {\n custom_id: string;\n title: string;\n components: unknown[];\n };\n }\n // No index signature: an interface such as the builder's\n // `APIModalComponent` (what `toJSON()` returns) must be assignable.\n | {\n custom_id: string;\n title: string;\n components: readonly unknown[];\n },\n ): Promise<unknown> {\n const data =\n \"toJSON\" in modal && typeof modal.toJSON === \"function\"\n ? modal.toJSON()\n : modal;\n return this.acknowledge(\n new InteractionResponse(\n InteractionResponseEnum.Modal,\n data as InteractionReplyOptions,\n ),\n \"replied\",\n );\n }\n}\n\n// ─── CommandInteraction ───────────────────────────────────────────────────────\n\n/** Application command interaction with fully typed option resolver. */\nexport class CommandInteraction extends Interaction {\n /** Typed option resolver. Access slash command options with full type safety. */\n public readonly options: CommandOptions;\n\n /** Invoked command name. @returns Command name or an empty string. */\n public get commandName(): string {\n return typeof this.data.data?.name === \"string\"\n ? this.data.data.name\n : \"\";\n }\n\n public constructor(client: InteractionClient, data: InteractionData) {\n super(client, data);\n const rawOptions =\n (data.data?.options as APIInteractionDataOption[]) ?? [];\n const resolved = (data.data?.resolved as Record<string, unknown>) ?? {};\n // Hand the resolver the *top-level* options. CommandOptions performs the\n // subcommand/group drill itself and records the names it walks through;\n // pre-drilling here would strip those wrappers before it sees them, so\n // getSubcommand()/getSubcommandGroup() would report null.\n this.options = new CommandOptions(rawOptions, resolved);\n }\n}\n\n// ─── ContextMenuCommandInteraction ───────────────────────────────────────────\n\n/** A user or message context-menu command, with what was right-clicked. */\nexport class ContextMenuCommandInteraction extends CommandInteraction {\n #resolved(): Record<string, Record<string, unknown> | undefined> {\n return (this.data.data?.resolved ?? {}) as Record<\n string,\n Record<string, unknown> | undefined\n >;\n }\n /** ID of the user or message the command was used on. */\n public get targetId(): string | null {\n const id = this.data.data?.target_id;\n return typeof id === \"string\" ? id : null;\n }\n /** The user a user command was used on. */\n public get targetUser(): User | null {\n const id = this.targetId;\n const raw = id ? this.#resolved().users?.[id] : undefined;\n return raw\n ? new User(raw as ConstructorParameters<typeof User>[0])\n : null;\n }\n /** The member a user command was used on (in a guild), with member actions when attached to a client. */\n public get targetMember(): GuildMember | null {\n const id = this.targetId;\n const raw = id ? this.#resolved().members?.[id] : undefined;\n const user = id ? this.#resolved().users?.[id] : undefined;\n if (!raw || !user || !this.guildId) return null;\n return new GuildMember(\n {\n ...(raw as Omit<\n ConstructorParameters<typeof GuildMember>[0],\n \"guild_id\" | \"user\"\n >),\n user: user as ConstructorParameters<\n typeof GuildMember\n >[0][\"user\"],\n guild_id: this.guildId,\n },\n this.resourceContext,\n );\n }\n /** The message a message command was used on. */\n public get targetMessage(): Message | null {\n const id = this.targetId;\n const raw = id ? this.#resolved().messages?.[id] : undefined;\n return raw\n ? new Message(\n raw as unknown as ConstructorParameters<typeof Message>[0],\n this.resourceContext,\n )\n : null;\n }\n}\n\n// ─── ComponentInteraction ─────────────────────────────────────────────────────\n\n/** Message component interaction. */\nexport class ComponentInteraction extends Interaction {\n /** Gets component custom ID. */\n public get customId(): string {\n const id = this.data.data?.custom_id;\n return typeof id === \"string\" ? id : \"\";\n }\n /** ID of the message the component is on. */\n public get messageId(): string | undefined {\n return (this.data.message as { id?: string } | undefined)?.id;\n }\n /** Gets component type. */\n public get componentType(): number {\n const type = this.data.data?.component_type;\n return typeof type === \"number\" ? type : 0;\n }\n /** Gets selected values for select menu component interactions. */\n public get values(): string[] {\n const values = this.data.data?.values;\n return Array.isArray(values) ? (values as string[]) : [];\n }\n /** Defers updating the message to which the component was attached. */\n public async deferUpdate(options: {\n withResponse: true;\n }): Promise<Message | null>;\n public async deferUpdate(options?: {\n withResponse?: boolean;\n }): Promise<void>;\n public async deferUpdate(\n options: { withResponse?: boolean } = {},\n ): Promise<Message | null | void> {\n const withResponse = options.withResponse === true;\n const result = await this.acknowledgeWith(\n new InteractionResponse(\n InteractionResponseEnum.DeferredMessageUpdate,\n ),\n \"deferred\",\n withResponse,\n );\n if (withResponse) return result as Message | null;\n }\n}\n\n// ─── ModalSubmitInteraction ───────────────────────────────────────────────────\n\n/** Represents a Discord modal submission interaction. */\nexport class ModalSubmitInteraction extends Interaction {\n /** Gets the submitted modal custom ID. */\n public get customId(): string {\n const id = this.data.data?.custom_id;\n return typeof id === \"string\" ? id : \"\";\n }\n\n /** Retrieves the text value for a specific text input custom ID. @param customId The custom_id of the text input component. @returns The submitted text, or undefined if not found. */\n public getInputValue(customId: string): string | undefined {\n const rows =\n (this.data.data?.components as\n | { components?: { custom_id?: string; value?: string }[] }[]\n | undefined) ?? [];\n for (const row of rows) {\n for (const comp of row.components ?? []) {\n if (comp.custom_id === customId) return comp.value;\n }\n }\n return undefined;\n }\n\n /** Retrieves the text value for a text input, throwing if missing. @param customId The custom_id of the text input component. @returns The submitted text. @throws {TypeError} If the field is not found. */\n public getRequiredInputValue(customId: string): string {\n const value = this.getInputValue(customId);\n if (value === undefined)\n throw new TypeError(\n `Modal input \"${customId}\" was not found in the submission.`,\n );\n return value;\n }\n}\n\n// ─── AutocompleteInteraction ──────────────────────────────────────────────────\n\n/** Represents a Discord slash command autocomplete interaction. */\nexport class AutocompleteInteraction extends Interaction {\n /** Option resolver; use `options.getFocused()` for the focused value. */\n public readonly options: CommandOptions;\n\n public constructor(client: InteractionClient, data: InteractionData) {\n super(client, data);\n this.options = new CommandOptions(\n (data.data?.options as APIInteractionDataOption[]) ?? [],\n );\n }\n\n /** Gets the target command name. */\n public get commandName(): string {\n const name = this.data.data?.name;\n return typeof name === \"string\" ? name : \"\";\n }\n\n /** Gets the currently focused autocomplete option. */\n public get focusedOption():\n { name: string; value: unknown; type: number } | undefined {\n const options = this.data.data?.options;\n return findFocused(\n Array.isArray(options) ? (options as FocusableOption[]) : [],\n );\n }\n\n /** Responds to Discord with autocomplete choices. @param choices Array of name/value pairs to show. @throws {TypeError} If choices is not an array. */\n public async respond(\n choices: { name: string; value: string | number }[],\n ): Promise<void> {\n if (!Array.isArray(choices))\n throw new TypeError(\"Autocomplete choices must be an array.\");\n const response = new InteractionResponse(\n InteractionResponseEnum.Autocomplete,\n { choices } as InteractionReplyOptions,\n );\n await this.acknowledge(response, \"replied\");\n }\n}\n\n/** An option as Discord sends it in autocomplete data. */\ninterface FocusableOption {\n name: string;\n value?: unknown;\n type: number;\n focused?: boolean;\n options?: FocusableOption[];\n}\n\n/** Recursively finds the focused option in a nested options tree. */\nfunction findFocused(\n options: FocusableOption[],\n): { name: string; value: unknown; type: number } | undefined {\n for (const opt of options) {\n if (opt.focused)\n return { name: opt.name, value: opt.value, type: opt.type };\n if (Array.isArray(opt.options)) {\n const found = findFocused(opt.options);\n if (found) return found;\n }\n }\n return undefined;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────────\n\n/**\n * Creates a specialized interaction structure for a Gateway payload.\n * @param client Interaction transport.\n * @param data Gateway interaction payload.\n * @returns Specialized interaction structure.\n * @throws {TypeError} If required identifiers are missing.\n */\nexport function createInteraction(\n client: InteractionClient,\n data: InteractionData,\n): Interaction {\n switch (data.type) {\n case InteractionEnum.ApplicationCommand: {\n const commandType = data.data?.type;\n return commandType === COMMAND_USER ||\n commandType === COMMAND_MESSAGE\n ? new ContextMenuCommandInteraction(client, data)\n : new CommandInteraction(client, data);\n }\n case InteractionEnum.ApplicationCommandAutocomplete:\n return new AutocompleteInteraction(client, data);\n case InteractionEnum.MessageComponent:\n return new ComponentInteraction(client, data);\n case InteractionEnum.ModalSubmit:\n return new ModalSubmitInteraction(client, data);\n default:\n return new Interaction(client, data);\n }\n}\n",
17
22
  "import type {\n APIEmbed,\n APIEmbedAuthor,\n APIEmbedField,\n APIEmbedFooter,\n APIEmbedMedia,\n} from \"@lunibee/types\";\n\n/**\n * A rich Embed structure that wraps a Discord API embed object.\n * Provides typed accessors and a fluent builder interface.\n */\nexport class Embed {\n #data: APIEmbed;\n\n /** Creates an Embed from raw Discord API data, or starts a blank embed. */\n public constructor(data: APIEmbed = {}) {\n this.#data = { ...data };\n if (this.#data.fields) this.#data.fields = [...this.#data.fields];\n }\n\n // ── Read accessors ───────────────────────────────────────────────────────\n\n /** Embed title. */\n public get title(): string | undefined {\n return this.#data.title;\n }\n /** Embed description. */\n public get description(): string | undefined {\n return this.#data.description;\n }\n /** Embed URL. */\n public get url(): string | undefined {\n return this.#data.url;\n }\n /** Embed color as an integer. */\n public get color(): number | undefined {\n return this.#data.color;\n }\n /** Embed timestamp ISO 8601 string. */\n public get timestamp(): string | undefined {\n return this.#data.timestamp;\n }\n /** Embed timestamp as a Date object, or undefined. */\n public get createdAt(): Date | undefined {\n return this.#data.timestamp\n ? new Date(this.#data.timestamp)\n : undefined;\n }\n /** Embed footer. */\n public get footer(): APIEmbedFooter | undefined {\n return this.#data.footer;\n }\n /** Embed image. */\n public get image(): APIEmbedMedia | undefined {\n return this.#data.image;\n }\n /** Embed thumbnail. */\n public get thumbnail(): APIEmbedMedia | undefined {\n return this.#data.thumbnail;\n }\n /** Embed video. */\n public get video(): APIEmbedMedia | undefined {\n return this.#data.video;\n }\n /** Embed author. */\n public get author(): APIEmbedAuthor | undefined {\n return this.#data.author;\n }\n /** Embed fields (read-only copy). */\n public get fields(): readonly APIEmbedField[] {\n return this.#data.fields ?? [];\n }\n\n // ── Fluent builder methods ────────────────────────────────────────────────\n\n /** Sets the embed title. @param title Embed title text (max 256 chars). @throws {TypeError} If title exceeds 256 characters. */\n public setTitle(title: string): this {\n if (title.length > 256)\n throw new TypeError(\"Embed title must not exceed 256 characters.\");\n this.#data.title = title;\n return this;\n }\n\n /** Sets the embed description. @param description Embed description (max 4096 chars). @throws {TypeError} If description exceeds 4096 characters. */\n public setDescription(description: string): this {\n if (description.length > 4096)\n throw new TypeError(\n \"Embed description must not exceed 4096 characters.\",\n );\n this.#data.description = description;\n return this;\n }\n\n /** Sets the embed URL. @param url A valid URL string. */\n public setURL(url: string): this {\n this.#data.url = url;\n return this;\n }\n\n /** Sets the embed color. Accepts a hex number (0xff0000), decimal integer, or hex string (\"#ff0000\"). @param color Color value. */\n public setColor(color: number | string): this {\n if (typeof color === \"string\") {\n const hex = color.replace(/^#/, \"\");\n this.#data.color = parseInt(hex, 16);\n } else {\n this.#data.color = color;\n }\n return this;\n }\n\n /** Sets the embed timestamp. Accepts a Date, ISO string, or number (ms since epoch). Defaults to now. */\n public setTimestamp(timestamp: Date | string | number = Date.now()): this {\n this.#data.timestamp = new Date(timestamp).toISOString();\n return this;\n }\n\n /** Sets the embed footer. @param text Footer text (max 2048 chars). @param iconURL Optional footer icon URL. */\n public setFooter(text: string, iconURL?: string): this {\n if (text.length > 2048)\n throw new TypeError(\n \"Embed footer text must not exceed 2048 characters.\",\n );\n this.#data.footer = iconURL ? { text, icon_url: iconURL } : { text };\n return this;\n }\n\n /** Sets the embed image. @param url Image URL. */\n public setImage(url: string): this {\n this.#data.image = { url };\n return this;\n }\n\n /** Sets the embed thumbnail. @param url Thumbnail URL. */\n public setThumbnail(url: string): this {\n this.#data.thumbnail = { url };\n return this;\n }\n\n /** Sets the embed author. @param name Author name (max 256 chars). @param options Optional URL and icon URL. */\n public setAuthor(\n name: string,\n options: { url?: string; iconURL?: string } = {},\n ): this {\n if (name.length > 256)\n throw new TypeError(\n \"Embed author name must not exceed 256 characters.\",\n );\n this.#data.author = {\n name,\n url: options.url,\n icon_url: options.iconURL,\n };\n return this;\n }\n\n /** Adds one or more fields to the embed. @param fields Fields to add (max 25 total). @throws {TypeError} If adding exceeds 25 fields. */\n public addFields(...fields: APIEmbedField[]): this {\n const existing = this.#data.fields ?? [];\n if (existing.length + fields.length > 25)\n throw new TypeError(\"Embeds cannot have more than 25 fields.\");\n for (const field of fields) {\n if (field.name.length > 256)\n throw new TypeError(\n \"Embed field name must not exceed 256 characters.\",\n );\n if (field.value.length > 1024)\n throw new TypeError(\n \"Embed field value must not exceed 1024 characters.\",\n );\n }\n this.#data.fields = [...existing, ...fields];\n return this;\n }\n\n /** Removes all fields from the embed. */\n public clearFields(): this {\n this.#data.fields = [];\n return this;\n }\n\n /** Splices the fields array, replacing, inserting, or deleting fields. @param index Start index. @param deleteCount Number of fields to remove. @param fields Replacement fields. */\n public spliceFields(\n index: number,\n deleteCount: number,\n ...fields: APIEmbedField[]\n ): this {\n const next = [...(this.#data.fields ?? [])];\n next.splice(index, deleteCount, ...fields);\n if (next.length > 25)\n throw new TypeError(\"Embeds cannot have more than 25 fields.\");\n for (const field of fields) {\n if (field.name.length > 256)\n throw new TypeError(\n \"Embed field name must not exceed 256 characters.\",\n );\n if (field.value.length > 1024)\n throw new TypeError(\n \"Embed field value must not exceed 1024 characters.\",\n );\n }\n this.#data.fields = next;\n return this;\n }\n\n // ── Serialization ─────────────────────────────────────────────────────────\n\n /** Returns the raw Discord API embed payload. */\n public toJSON(): APIEmbed {\n const json = { ...this.#data };\n if (json.fields) json.fields = [...json.fields];\n return json;\n }\n\n /** Creates an Embed from an existing raw API embed object. */\n public static from(data: APIEmbed): Embed {\n return new Embed(data);\n }\n}\n",
18
- "import { BaseStructure } from \"./base.js\";\nimport type {\n APIAuditLog,\n APIAuditLogEntry,\n APIAuditLogChange,\n APIAuditLogOptions,\n} from \"@lunibee/types\";\n\n/** Represents a single entry in a Discord audit log. */\nexport class AuditLogEntry extends BaseStructure {\n /** The ID of the affected entity. */\n public readonly targetId: string | null;\n /** The ID of the user who made the changes. */\n public readonly userId: string | null;\n /** The action type of this entry. */\n public readonly actionType: number;\n /** The changes made to the target. */\n public readonly changes: APIAuditLogChange[];\n /** Additional info for certain action types. */\n public readonly options: APIAuditLogOptions | null;\n /** The reason for the change, if any. */\n public readonly reason: string | null;\n\n /** Creates an audit log entry. */\n public constructor(data: APIAuditLogEntry) {\n super(data.id);\n this.targetId = data.target_id;\n this.userId = data.user_id;\n this.actionType = data.action_type;\n this.changes = data.changes ?? [];\n this.options = data.options ?? null;\n this.reason = data.reason ?? null;\n }\n}\n\n/** Represents a Discord audit log. */\nexport class AuditLog {\n /** The entries in the audit log. */\n public readonly entries: Map<string, AuditLogEntry>;\n // Depending on what else is needed, we could parse the users, webhooks, etc.\n // However, the typical structure mainly exposes the entries.\n\n /** Creates an audit log. */\n public constructor(data: APIAuditLog) {\n this.entries = new Map();\n for (const entryData of data.audit_log_entries) {\n this.entries.set(entryData.id, new AuditLogEntry(entryData));\n }\n }\n}\n",
19
- "/** Resource structures for Discord messages and related entities. */\nimport { BaseStructure, Channel, User } from \"./base.js\";\nimport { GuildMember } from \"./resources.js\";\nimport type { ComponentInteraction } from \"./interactions.js\";\nimport type { Collector, CollectorOptions } from \"@lunibee/core\";\n\n/** Interaction tokens last 15 minutes, so a component collector with no limit of its own stops then. */\nconst COMPONENT_COLLECTOR_DEFAULT_TIME = 15 * 60_000;\n\n/** Options for {@link Message.createComponentCollector}. */\nexport interface ComponentCollectorOptions extends CollectorOptions<ComponentInteraction> {\n /** Only this component type (2 button, 3 string select...). */\n componentType?: number;\n}\nimport type { ResourceContext } from \"./base.js\";\n\n/** discord.js user-authored (non-system) message types: Default, Reply,\n * ChatInputCommand and ContextMenuCommand. Any other type is a system message. */\nconst NON_SYSTEM_MESSAGE_TYPES = new Set([0, 19, 20, 23]);\n\nexport {\n BaseStructure,\n Channel,\n Guild,\n User,\n CDN_BASE,\n cdnURL,\n} from \"./base.js\";\nexport type { ResourceContext, ImageURLOptions } from \"./base.js\";\n\nexport class Message extends BaseStructure {\n public content: string;\n public author: User;\n public channelId: string;\n public readonly channel: Channel;\n public guildId?: string;\n public flags: number;\n /** Message creation timestamp (from timestamp field or snowflake). */\n public readonly timestamp: Date;\n public readonly attachments: import(\"@lunibee/types\").APIAttachment[];\n public readonly embeds: import(\"@lunibee/types\").APIEmbed[];\n public readonly mentions: User[];\n public readonly mentionRoles: string[];\n public pinned: boolean;\n public mentionEveryone: boolean;\n public type: number;\n public readonly reference?: import(\"@lunibee/types\").APIMessageReference;\n public readonly components: import(\"@lunibee/types\").APIMessageComponent[];\n public readonly referencedMessage?: Message | null;\n /** Stickers sent with the message (`sticker_items`). */\n public readonly stickers: import(\"@lunibee/types\").APIStickerItem[];\n /** The poll, when the message is one. */\n public readonly poll: import(\"@lunibee/types\").APIPoll | null;\n /** For a forwarded message, the snapshot of the original. */\n public readonly messageSnapshots: import(\"@lunibee/types\").APIMessageSnapshot[];\n /**\n * The author as a guild member, on guild messages from the Gateway. Its\n * `permissions` are computed from the cached roles; `member.kick()` and the\n * other member actions work when the message came from a client.\n */\n public member: GuildMember | null;\n readonly #context?: ResourceContext;\n\n /** Creates a message structure from Discord message data. */\n public constructor(\n data: import(\"@lunibee/types\").APIMessage,\n context?: ResourceContext,\n ) {\n super(data.id);\n if (!/^\\d{1,20}$/.test(data.channel_id))\n throw new TypeError(\n \"Message channel_id must be a valid snowflake.\",\n );\n this.content = data.content ?? \"\";\n this.author = new User(data.author);\n this.channelId = data.channel_id;\n this.guildId = data.guild_id;\n this.flags = data.flags ?? 0;\n this.timestamp = new Date(\n data.timestamp ?? Number((BigInt(this.id) >> 22n) + 1420070400000n),\n );\n this.attachments = data.attachments ?? [];\n this.embeds = data.embeds ?? [];\n this.components = data.components ?? [];\n this.mentions = (data.mentions ?? []).map((user) => new User(user));\n this.mentionRoles = data.mention_roles ?? [];\n this.pinned = data.pinned ?? false;\n this.mentionEveryone = data.mention_everyone ?? false;\n this.type = data.type ?? 0;\n this.reference = data.message_reference;\n this.stickers =\n data.sticker_items ??\n (data.stickers ?? []).map(({ id, name, format_type }) => ({\n id,\n name,\n format_type,\n }));\n this.poll = data.poll ?? null;\n this.messageSnapshots = data.message_snapshots ?? [];\n this.referencedMessage = data.referenced_message\n ? new Message(data.referenced_message, context)\n : data.referenced_message === null\n ? null\n : undefined;\n this.#context = context;\n this.member =\n data.member && data.guild_id\n ? new GuildMember(\n {\n ...data.member,\n user: data.member.user ?? data.author,\n guild_id: data.guild_id,\n },\n context,\n )\n : null;\n this.channel = new Channel(\n { id: data.channel_id, type: 0, guild_id: data.guild_id },\n context,\n );\n }\n\n /** Whether embeds are suppressed on this message. */\n public get embedsSuppressed(): boolean {\n return (this.flags & 4) !== 0;\n }\n\n /** Unix timestamp (ms) at which the message was created — discord.js parity.\n * Derived from the message `timestamp`, which itself falls back to the id snowflake. */\n public get createdTimestamp(): number {\n return this.timestamp.getTime();\n }\n\n /** Date at which the message was created — discord.js parity. Overrides the\n * snowflake-only `BaseStructure.createdAt` to honour the message `timestamp`. */\n public override get createdAt(): Date {\n return this.timestamp;\n }\n\n /** Edits this message. @param options Message fields to change. @returns The updated message. @throws {Error} If the message is not attached to a client. */\n public edit(\n options: Record<string, unknown> & { content?: string },\n ): Promise<Message> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.editMessage(this.channelId, this.id, options);\n }\n\n /** Updates this message using the same resource operation as edit. @param options Message fields to change. @returns The updated message. @throws {Error} If the message is not attached to a client. */\n public update(\n options: Record<string, unknown> & { content?: string },\n ): Promise<Message> {\n return this.edit(options);\n }\n\n /** Deletes this message. @param reason Audit-log reason (shown when deleting someone else's message). @returns A promise fulfilled when Discord confirms deletion. @throws {Error} If the message is not attached to a client. */\n public delete(reason?: string): Promise<void> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.deleteMessage(this.channelId, this.id, reason);\n }\n\n /** Replies to this message. @param options Message content or payload. @returns The created reply message. @throws {Error} If the message is not attached to a client. */\n public reply(\n options: string | (Record<string, unknown> & { content?: string }),\n ): Promise<Message> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n const payload =\n typeof options === \"string\" ? { content: options } : { ...options };\n payload.message_reference = {\n message_id: this.id,\n channel_id: this.channelId,\n guild_id: this.guildId,\n };\n return this.#context.sendMessage(this.channelId, payload);\n }\n\n /** Crossposts this message. @returns The resulting message. @throws {Error} If the message is not attached to a client. */\n public crosspost(): Promise<Message> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.crosspostMessage(this.channelId, this.id);\n }\n\n /**\n * Collects clicks and picks on this message's components. It always ends:\n * after `time`, or 15 minutes (an interaction token's life) when neither\n * `time` nor `idle` is set.\n * @example\n * const collector = message.createComponentCollector({ filter: (i) => i.user?.id === authorId, time: 60_000 });\n * collector.on(\"collect\", (i) => i.update({ content: `Picked ${i.customId}` }));\n */\n public createComponentCollector(\n options: ComponentCollectorOptions = {},\n ): Collector<string, ComponentInteraction> {\n const collect = this.#context?.collectInteractions;\n if (!collect)\n throw new Error(\"This message is not attached to a client.\");\n const { componentType, filter, ...rest } = options;\n return collect({\n ...rest,\n time:\n rest.time ??\n (rest.idle ? undefined : COMPONENT_COLLECTOR_DEFAULT_TIME),\n filter: async (interaction) =>\n interaction.isMessageComponent() &&\n interaction.messageId === this.id &&\n (componentType === undefined ||\n interaction.componentType === componentType) &&\n (filter ? await filter(interaction) : true),\n }) as unknown as Collector<string, ComponentInteraction>;\n }\n\n /**\n * Waits for the next click or pick on this message's components.\n * @param options `time` (default 15 minutes), `filter`, `componentType`.\n * @returns The interaction. @throws {Error} When time runs out first.\n */\n public awaitComponent(\n options: Omit<ComponentCollectorOptions, \"max\"> = {},\n ): Promise<ComponentInteraction> {\n return this.createComponentCollector({ ...options, max: 1 }).next();\n }\n\n /** Adds a reaction to this message. @param emoji Emoji identifier. @returns A promise fulfilled when the reaction is added. @throws {Error} If reactions are unavailable. */\n public react(emoji: string): Promise<void> {\n if (!this.#context?.addReaction)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.addReaction(this.channelId, this.id, emoji);\n }\n\n /** Removes a reaction from this message. @param emoji Emoji identifier. @param userId User whose reaction should be removed; omit to remove the current user's reaction. @returns A promise fulfilled when the reaction is removed. @throws {Error} If reaction operations are unavailable. */\n public removeReaction(emoji: string, userId?: string): Promise<void> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return userId\n ? (this.#context.removeReaction?.(\n this.channelId,\n this.id,\n emoji,\n userId,\n ) ??\n Promise.reject(\n new Error(\"Reaction operations are unavailable.\"),\n ))\n : (this.#context.removeOwnReaction?.(\n this.channelId,\n this.id,\n emoji,\n ) ??\n Promise.reject(\n new Error(\"Reaction operations are unavailable.\"),\n ));\n }\n\n /** Removes all reactions from this message. @returns A promise fulfilled when reactions are removed. @throws {Error} If reaction operations are unavailable. */\n public removeAllReactions(): Promise<void> {\n if (!this.#context?.removeAllReactions)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.removeAllReactions(this.channelId, this.id);\n }\n\n /** Pins this message. @param reason Audit-log reason. @returns A promise fulfilled when the message is pinned. @throws {Error} If pin operations are unavailable. */\n public pin(reason?: string): Promise<void> {\n if (!this.#context?.pinMessage)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.pinMessage(this.channelId, this.id, reason);\n }\n\n /** Unpins this message. @param reason Audit-log reason. @returns A promise fulfilled when the message is unpinned. @throws {Error} If pin operations are unavailable. */\n public unpin(reason?: string): Promise<void> {\n if (!this.#context?.unpinMessage)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.unpinMessage(this.channelId, this.id, reason);\n }\n\n // ─── Flag-based getters ───────────────────────────────────────────────────────\n\n /** Whether this message was sent ephemerally (only visible to the recipient). */\n public get isEphemeral(): boolean {\n return (this.flags & 64) !== 0;\n }\n\n /** Whether this message is currently pinned in its channel. */\n public get isPinned(): boolean {\n return this.pinned;\n }\n\n /** Whether this is a system-generated message (join, boost, etc). Mirrors\n * discord.js: a message is \"system\" unless its type is one of the user-authored\n * types — Default (0), Reply (19), ChatInputCommand (20) or ContextMenuCommand (23). */\n public get isSystemMessage(): boolean {\n return !NON_SYSTEM_MESSAGE_TYPES.has(this.type);\n }\n\n /** Whether this message was crossposted from an announcement channel. */\n public get isCrosspost(): boolean {\n return (this.flags & 2) !== 0;\n }\n\n /** Whether this message has file attachments. */\n public get hasAttachments(): boolean {\n return this.attachments.length > 0;\n }\n\n /** Whether this message contains embeds. */\n public get hasEmbeds(): boolean {\n return this.embeds.length > 0;\n }\n\n /** Whether this message contains interactive components. */\n public get hasComponents(): boolean {\n return this.components.length > 0;\n }\n\n /** Edits this message to suppress its embeds. @returns The updated message. */\n public suppressEmbeds(): Promise<Message> {\n return this.edit({ flags: this.flags | 4 });\n }\n\n /** Returns a plain-object snapshot of all message fields. */\n public toJSON(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n channelId: this.channelId,\n guildId: this.guildId,\n flags: this.flags,\n pinned: this.pinned,\n mentionEveryone: this.mentionEveryone,\n type: this.type,\n timestamp: this.timestamp.toISOString(),\n author: { id: this.author.id, username: this.author.username },\n attachments: [...this.attachments],\n embeds: [...this.embeds],\n components: [...this.components],\n mentions: this.mentions.map((u) => u.id),\n mentionRoles: [...this.mentionRoles],\n reference: this.reference,\n referencedMessage: this.referencedMessage\n ? this.referencedMessage.id\n : this.referencedMessage,\n };\n }\n}\n\nexport {\n GuildMember,\n Role,\n TextChannel,\n Invite,\n Webhook,\n WebhookEnum,\n WebhookType,\n Emoji,\n AutoModerationRule,\n WelcomeScreenChannel,\n GuildWelcomeScreen,\n OnboardingPromptOption,\n OnboardingPrompt,\n GuildOnboarding,\n} from \"./resources.js\";\nexport {\n NewsChannel,\n DMChannel,\n VoiceChannel,\n StageChannel,\n CategoryChannel,\n ThreadChannel,\n ForumChannel,\n MediaChannel,\n createChannel,\n} from \"./channels.js\";\nexport * from \"./interactions.js\";\nexport { Embed } from \"./embed.js\";\nexport { AuditLog, AuditLogEntry } from \"./audit-log.js\";\n// KI-4: PermissionsBitField lives canonically in @lunibee/core (single source of\n// truth). Re-export it here for discord.js-style top-level access from structures,\n// replacing the former structures-local duplicate.\nexport { PermissionsBitField } from \"@lunibee/core\";\n"
23
+ "import { BaseStructure } from \"./base.js\";\nimport type {\n APIAuditLog,\n APIAuditLogEntry,\n APIAuditLogChange,\n APIAuditLogOptions,\n} from \"@lunibee/types\";\n\n/** What `info` holds for each action type that carries extra details (numbers are parsed from Discord's strings). */\nexport interface AuditLogInfoByType {\n /** Overwrite created, updated or deleted: a role (`type` 0) or a member (`type` 1). */\n 13: AuditLogOverwriteInfo;\n 14: AuditLogOverwriteInfo;\n 15: AuditLogOverwriteInfo;\n /** Member prune. */\n 21: { deleteMemberDays: number; membersRemoved: number };\n /** Members moved between voice channels. */\n 26: { channelId: string; count: number };\n /** Members disconnected from voice. */\n 27: { count: number };\n /** Message deleted in a channel. */\n 72: { channelId: string; count: number };\n /** Messages bulk deleted. */\n 73: { count: number };\n /** Message pinned or unpinned. */\n 74: { channelId: string; messageId: string };\n 75: { channelId: string; messageId: string };\n /** Stage instance created, updated or deleted. */\n 83: { channelId: string };\n 84: { channelId: string };\n 85: { channelId: string };\n /** Application command permissions updated. */\n 121: { applicationId: string };\n /** AutoMod blocked a message, flagged it, or timed a member out. */\n 143: AuditLogAutoModInfo;\n 144: AuditLogAutoModInfo;\n 145: AuditLogAutoModInfo;\n}\n\n/** The overwrite an audit entry is about. */\nexport interface AuditLogOverwriteInfo {\n /** The role or user the overwrite is for. */\n id: string;\n /** 0 role, 1 member. */\n type: number;\n roleName?: string;\n}\n\n/** The rule behind an AutoMod audit entry. */\nexport interface AuditLogAutoModInfo {\n ruleName: string;\n ruleTriggerType: number;\n channelId?: string;\n}\n\n/** The details object of an action type, or `undefined` when the type has none. */\nexport type AuditLogInfo<T extends number> = number extends T\n ? AuditLogInfoByType[keyof AuditLogInfoByType] | undefined\n : T extends keyof AuditLogInfoByType\n ? AuditLogInfoByType[T]\n : undefined;\n\nfunction int(value: string | undefined): number {\n return Number(value ?? 0);\n}\n\n/** Reads Discord's string-valued options into the typed `info` of one action type. */\nfunction parseInfo(\n type: number,\n options: APIAuditLogOptions | undefined,\n): AuditLogInfoByType[keyof AuditLogInfoByType] | undefined {\n if (!options) return undefined;\n switch (type) {\n case 13:\n case 14:\n case 15:\n return {\n id: options.id ?? \"\",\n type: int(options.type),\n roleName: options.role_name,\n };\n case 21:\n return {\n deleteMemberDays: int(options.delete_member_days),\n membersRemoved: int(options.members_removed),\n };\n case 26:\n case 72:\n return {\n channelId: options.channel_id ?? \"\",\n count: int(options.count),\n };\n case 27:\n case 73:\n return { count: int(options.count) };\n case 74:\n case 75:\n return {\n channelId: options.channel_id ?? \"\",\n messageId: options.message_id ?? \"\",\n };\n case 83:\n case 84:\n case 85:\n return { channelId: options.channel_id ?? \"\" };\n case 121:\n return { applicationId: options.app_id ?? \"\" };\n case 143:\n case 144:\n case 145:\n return {\n ruleName: options.auto_moderation_rule_name ?? \"\",\n ruleTriggerType: int(options.auto_moderation_rule_trigger_type),\n channelId: options.channel_id,\n };\n default:\n return undefined;\n }\n}\n\n/** Represents a single entry in a Discord audit log. */\nexport class AuditLogEntry<T extends number = number> extends BaseStructure {\n /** The ID of the affected entity. */\n public readonly targetId: string | null;\n /** The ID of the user who made the changes. */\n public readonly userId: string | null;\n /** The action type of this entry. */\n public readonly actionType: T;\n /** The changes made to the target. */\n public readonly changes: APIAuditLogChange[];\n /** Additional info for certain action types. */\n public readonly options: APIAuditLogOptions | null;\n /** The action's details with numbers parsed, typed by action type (`undefined` for types that have none). `options` is Discord's raw object. */\n public readonly info: AuditLogInfo<T>;\n /** The reason for the change, if any. */\n public readonly reason: string | null;\n\n /** Creates an audit log entry. */\n public constructor(data: APIAuditLogEntry) {\n super(data.id);\n this.targetId = data.target_id;\n this.userId = data.user_id;\n this.actionType = data.action_type as T;\n this.info = parseInfo(\n data.action_type,\n data.options,\n ) as AuditLogInfo<T>;\n this.changes = data.changes ?? [];\n this.options = data.options ?? null;\n this.reason = data.reason ?? null;\n }\n\n /** Narrows the entry to one action type, so `info` is typed for it. */\n public is<K extends number>(type: K): this is AuditLogEntry<K> {\n return (this.actionType as number) === type;\n }\n\n /** One change by its key (`\"nick\"`, `\"permissions\"`...), or `undefined`. */\n public change(key: string): { old: unknown; new: unknown } | undefined {\n const found = this.changes.find((change) => change.key === key);\n return found && { old: found.old_value, new: found.new_value };\n }\n}\n\n/** Which entries {@link AuditLog.find} and {@link AuditLog.filter} keep. Every field given must match. */\nexport interface AuditLogQuery<T extends number = number> {\n /** One action type, or any of several. */\n type?: T | readonly T[];\n /** The affected entity. */\n targetId?: string;\n /** Who did it. */\n userId?: string;\n /** Only entries created at or after this time (a Date, an ISO string or milliseconds). */\n since?: Date | string | number;\n}\n\n/** Represents a Discord audit log. */\nexport class AuditLog {\n /** The entries in the audit log. */\n public readonly entries: Map<string, AuditLogEntry>;\n // Depending on what else is needed, we could parse the users, webhooks, etc.\n // However, the typical structure mainly exposes the entries.\n\n /** Creates an audit log. */\n public constructor(data: APIAuditLog) {\n this.entries = new Map();\n for (const entryData of data.audit_log_entries) {\n this.entries.set(entryData.id, new AuditLogEntry(entryData));\n }\n }\n\n /** The entries that match `query`, newest first (the order Discord returns them in). */\n public filter<T extends number = number>(\n query: AuditLogQuery<T>,\n ): AuditLogEntry<T>[] {\n const types =\n query.type === undefined\n ? undefined\n : Array.isArray(query.type)\n ? (query.type as readonly number[])\n : [query.type as number];\n const since =\n query.since === undefined\n ? undefined\n : new Date(query.since).getTime();\n const matches: AuditLogEntry<T>[] = [];\n for (const entry of this.entries.values()) {\n if (types && !types.includes(entry.actionType)) continue;\n if (\n query.targetId !== undefined &&\n entry.targetId !== query.targetId\n )\n continue;\n if (query.userId !== undefined && entry.userId !== query.userId)\n continue;\n if (since !== undefined && entry.createdAt.getTime() < since)\n continue;\n matches.push(entry as unknown as AuditLogEntry<T>);\n }\n return matches;\n }\n\n /** The newest entry that matches `query`, or `undefined`. */\n public find<T extends number = number>(\n query: AuditLogQuery<T>,\n ): AuditLogEntry<T> | undefined {\n return this.filter(query)[0];\n }\n}\n",
24
+ "import {\n StickerFormatEnum,\n type APISticker,\n type APIStickerItem,\n type UserData,\n} from \"@lunibee/types\";\nimport { BaseStructure } from \"./base.js\";\n\n/** Where a sticker's image lives on Discord's CDN, by format. Lottie stickers are JSON, GIFs come from the media host. */\nexport function stickerURL(\n id: string,\n format: number,\n options: { size?: number } = {},\n): string {\n const size = options.size === undefined ? \"\" : `?size=${options.size}`;\n if (format === StickerFormatEnum.Lottie)\n return `https://cdn.discordapp.com/stickers/${id}.json`;\n if (format === StickerFormatEnum.GIF)\n return `https://media.discordapp.net/stickers/${id}.gif${size}`;\n return `https://cdn.discordapp.com/stickers/${id}.png${size}`;\n}\n\n/** A sticker: a guild's own, one from a Nitro pack, or a standard one. */\nexport class Sticker extends BaseStructure {\n public readonly name: string;\n public readonly description: string | null;\n /** Comma-separated autocomplete tags. */\n public readonly tags: string;\n /** 1 standard (from a pack), 2 guild. */\n public readonly type: number;\n /** 1 PNG, 2 APNG, 3 Lottie, 4 GIF. */\n public readonly formatType: number;\n /** Whether the sticker can be used (guild stickers become unavailable when the boost level drops). */\n public readonly available: boolean;\n public readonly guildId: string | null;\n public readonly packId: string | null;\n public readonly sortValue: number | null;\n /** Who uploaded it, for guild stickers. */\n public readonly user: UserData | null;\n\n public constructor(data: APISticker) {\n super(data.id);\n this.name = data.name;\n this.description = data.description ?? null;\n this.tags = data.tags ?? \"\";\n this.type = data.type ?? 2;\n this.formatType = data.format_type;\n this.available = data.available ?? true;\n this.guildId = data.guild_id ?? null;\n this.packId = data.pack_id ?? null;\n this.sortValue = data.sort_value ?? null;\n this.user = data.user ?? null;\n }\n\n /** Whether the sticker moves: APNG, Lottie or GIF. */\n public get animated(): boolean {\n return this.formatType !== StickerFormatEnum.PNG;\n }\n\n /** The sticker's image URL (a `.json` file for Lottie). */\n public url(options: { size?: number } = {}): string {\n return stickerURL(this.id, this.formatType, options);\n }\n\n /** The sticker as a message carries it. */\n public toItem(): APIStickerItem {\n return { id: this.id, name: this.name, format_type: this.formatType };\n }\n}\n",
25
+ "/** Resource structures for Discord messages and related entities. */\nimport type { MessageCreateOptions, MessageEditOptions } from \"@lunibee/types\";\nimport { BaseStructure, Channel, User } from \"./base.js\";\nimport { GuildMember } from \"./resources.js\";\nimport type { ComponentInteraction } from \"./interactions.js\";\nimport type { Collector, CollectorOptions } from \"@lunibee/core\";\n\n/** Interaction tokens last 15 minutes, so a component collector with no limit of its own stops then. */\nconst COMPONENT_COLLECTOR_DEFAULT_TIME = 15 * 60_000;\n\n/** Options for {@link Message.createComponentCollector}. */\nexport interface ComponentCollectorOptions extends CollectorOptions<ComponentInteraction> {\n /** Only this component type (2 button, 3 string select...). */\n componentType?: number;\n}\nimport type { ResourceContext } from \"./base.js\";\n\n/** discord.js user-authored (non-system) message types: Default, Reply,\n * ChatInputCommand and ContextMenuCommand. Any other type is a system message. */\nconst NON_SYSTEM_MESSAGE_TYPES = new Set([0, 19, 20, 23]);\n\nexport {\n BaseStructure,\n Channel,\n Guild,\n User,\n CDN_BASE,\n cdnURL,\n} from \"./base.js\";\nexport type { ResourceContext, ImageURLOptions } from \"./base.js\";\n\nexport class Message extends BaseStructure {\n public content: string;\n public author: User;\n public channelId: string;\n public readonly channel: Channel;\n public guildId?: string;\n public flags: number;\n /** Message creation timestamp (from timestamp field or snowflake). */\n public readonly timestamp: Date;\n public readonly attachments: import(\"@lunibee/types\").APIAttachment[];\n public readonly embeds: import(\"@lunibee/types\").APIEmbed[];\n public readonly mentions: User[];\n public readonly mentionRoles: string[];\n public pinned: boolean;\n public mentionEveryone: boolean;\n public type: number;\n public readonly reference?: import(\"@lunibee/types\").APIMessageReference;\n public readonly components: import(\"@lunibee/types\").APIMessageComponent[];\n public readonly referencedMessage?: Message | null;\n /** Stickers sent with the message (`sticker_items`). */\n public readonly stickers: import(\"@lunibee/types\").APIStickerItem[];\n /** The poll, when the message is one. */\n public readonly poll: import(\"@lunibee/types\").APIPoll | null;\n /** For a forwarded message, the snapshot of the original. */\n public readonly messageSnapshots: import(\"@lunibee/types\").APIMessageSnapshot[];\n /**\n * The author as a guild member, on guild messages from the Gateway. Its\n * `permissions` are computed from the cached roles; `member.kick()` and the\n * other member actions work when the message came from a client.\n */\n public member: GuildMember | null;\n readonly #context?: ResourceContext;\n\n /** Creates a message structure from Discord message data. */\n public constructor(\n data: import(\"@lunibee/types\").APIMessage,\n context?: ResourceContext,\n ) {\n super(data.id);\n if (!/^\\d{1,20}$/.test(data.channel_id))\n throw new TypeError(\n \"Message channel_id must be a valid snowflake.\",\n );\n this.content = data.content ?? \"\";\n this.author = new User(data.author);\n this.channelId = data.channel_id;\n this.guildId = data.guild_id;\n this.flags = data.flags ?? 0;\n this.timestamp = new Date(\n data.timestamp ?? Number((BigInt(this.id) >> 22n) + 1420070400000n),\n );\n this.attachments = data.attachments ?? [];\n this.embeds = data.embeds ?? [];\n this.components = data.components ?? [];\n this.mentions = (data.mentions ?? []).map((user) => new User(user));\n this.mentionRoles = data.mention_roles ?? [];\n this.pinned = data.pinned ?? false;\n this.mentionEveryone = data.mention_everyone ?? false;\n this.type = data.type ?? 0;\n this.reference = data.message_reference;\n this.stickers =\n data.sticker_items ??\n (data.stickers ?? []).map(({ id, name, format_type }) => ({\n id,\n name,\n format_type,\n }));\n this.poll = data.poll ?? null;\n this.messageSnapshots = data.message_snapshots ?? [];\n this.referencedMessage = data.referenced_message\n ? new Message(data.referenced_message, context)\n : data.referenced_message === null\n ? null\n : undefined;\n this.#context = context;\n this.member =\n data.member && data.guild_id\n ? new GuildMember(\n {\n ...data.member,\n user: data.member.user ?? data.author,\n guild_id: data.guild_id,\n },\n context,\n )\n : null;\n this.channel = new Channel(\n { id: data.channel_id, type: 0, guild_id: data.guild_id },\n context,\n );\n }\n\n /** Whether embeds are suppressed on this message. */\n public get embedsSuppressed(): boolean {\n return (this.flags & 4) !== 0;\n }\n\n /** Unix timestamp (ms) at which the message was created — discord.js parity.\n * Derived from the message `timestamp`, which itself falls back to the id snowflake. */\n public override get createdTimestamp(): number {\n return this.timestamp.getTime();\n }\n\n /** Date at which the message was created — discord.js parity. Overrides the\n * snowflake-only `BaseStructure.createdAt` to honour the message `timestamp`. */\n public override get createdAt(): Date {\n return this.timestamp;\n }\n\n /** Edits this message. @param options Message fields to change. @returns The updated message. @throws {Error} If the message is not attached to a client. */\n public edit(options: MessageEditOptions): Promise<Message> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.editMessage(this.channelId, this.id, options);\n }\n\n /** Updates this message using the same resource operation as edit. @param options Message fields to change. @returns The updated message. @throws {Error} If the message is not attached to a client. */\n public update(options: MessageEditOptions): Promise<Message> {\n return this.edit(options);\n }\n\n /** Deletes this message. @param reason Audit-log reason (shown when deleting someone else's message). @returns A promise fulfilled when Discord confirms deletion. @throws {Error} If the message is not attached to a client. */\n public delete(reason?: string): Promise<void> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.deleteMessage(this.channelId, this.id, reason);\n }\n\n /** Replies to this message. @param options Message content or payload. @returns The created reply message. @throws {Error} If the message is not attached to a client. */\n public reply(options: string | MessageCreateOptions): Promise<Message> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n const payload =\n typeof options === \"string\" ? { content: options } : { ...options };\n payload.message_reference = {\n message_id: this.id,\n channel_id: this.channelId,\n guild_id: this.guildId,\n };\n return this.#context.sendMessage(this.channelId, payload);\n }\n\n /** Crossposts this message. @returns The resulting message. @throws {Error} If the message is not attached to a client. */\n public crosspost(): Promise<Message> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.crosspostMessage(this.channelId, this.id);\n }\n\n /**\n * Collects clicks and picks on this message's components. It always ends:\n * after `time`, or 15 minutes (an interaction token's life) when neither\n * `time` nor `idle` is set.\n * @example\n * const collector = message.createComponentCollector({ filter: (i) => i.user?.id === authorId, time: 60_000 });\n * collector.on(\"collect\", (i) => i.update({ content: `Picked ${i.customId}` }));\n */\n public createComponentCollector(\n options: ComponentCollectorOptions = {},\n ): Collector<string, ComponentInteraction> {\n const collect = this.#context?.collectInteractions;\n if (!collect)\n throw new Error(\"This message is not attached to a client.\");\n const { componentType, filter, ...rest } = options;\n return collect({\n ...rest,\n time:\n rest.time ??\n (rest.idle ? undefined : COMPONENT_COLLECTOR_DEFAULT_TIME),\n filter: async (interaction) =>\n interaction.isMessageComponent() &&\n interaction.messageId === this.id &&\n (componentType === undefined ||\n interaction.componentType === componentType) &&\n (filter ? await filter(interaction) : true),\n }) as unknown as Collector<string, ComponentInteraction>;\n }\n\n /**\n * Waits for the next click or pick on this message's components.\n * @param options `time` (default 15 minutes), `filter`, `componentType`.\n * @returns The interaction. @throws {Error} When time runs out first.\n */\n public awaitComponent(\n options: Omit<ComponentCollectorOptions, \"max\"> = {},\n ): Promise<ComponentInteraction> {\n return this.createComponentCollector({ ...options, max: 1 }).next();\n }\n\n /** Adds a reaction to this message. @param emoji Emoji identifier. @returns A promise fulfilled when the reaction is added. @throws {Error} If reactions are unavailable. */\n public react(emoji: string): Promise<void> {\n if (!this.#context?.addReaction)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.addReaction(this.channelId, this.id, emoji);\n }\n\n /** Removes a reaction from this message. @param emoji Emoji identifier. @param userId User whose reaction should be removed; omit to remove the current user's reaction. @returns A promise fulfilled when the reaction is removed. @throws {Error} If reaction operations are unavailable. */\n public removeReaction(emoji: string, userId?: string): Promise<void> {\n if (!this.#context)\n throw new Error(\"This message is not attached to a client.\");\n return userId\n ? (this.#context.removeReaction?.(\n this.channelId,\n this.id,\n emoji,\n userId,\n ) ??\n Promise.reject(\n new Error(\"Reaction operations are unavailable.\"),\n ))\n : (this.#context.removeOwnReaction?.(\n this.channelId,\n this.id,\n emoji,\n ) ??\n Promise.reject(\n new Error(\"Reaction operations are unavailable.\"),\n ));\n }\n\n /** Removes all reactions from this message. @returns A promise fulfilled when reactions are removed. @throws {Error} If reaction operations are unavailable. */\n public removeAllReactions(): Promise<void> {\n if (!this.#context?.removeAllReactions)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.removeAllReactions(this.channelId, this.id);\n }\n\n /** Pins this message. @param reason Audit-log reason. @returns A promise fulfilled when the message is pinned. @throws {Error} If pin operations are unavailable. */\n public pin(reason?: string): Promise<void> {\n if (!this.#context?.pinMessage)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.pinMessage(this.channelId, this.id, reason);\n }\n\n /** Unpins this message. @param reason Audit-log reason. @returns A promise fulfilled when the message is unpinned. @throws {Error} If pin operations are unavailable. */\n public unpin(reason?: string): Promise<void> {\n if (!this.#context?.unpinMessage)\n throw new Error(\"This message is not attached to a client.\");\n return this.#context.unpinMessage(this.channelId, this.id, reason);\n }\n\n // ─── Flag-based getters ───────────────────────────────────────────────────────\n\n /** Whether this message was sent ephemerally (only visible to the recipient). */\n public get isEphemeral(): boolean {\n return (this.flags & 64) !== 0;\n }\n\n /** Whether this message is currently pinned in its channel. */\n public get isPinned(): boolean {\n return this.pinned;\n }\n\n /** Whether this is a system-generated message (join, boost, etc). Mirrors\n * discord.js: a message is \"system\" unless its type is one of the user-authored\n * types — Default (0), Reply (19), ChatInputCommand (20) or ContextMenuCommand (23). */\n public get isSystemMessage(): boolean {\n return !NON_SYSTEM_MESSAGE_TYPES.has(this.type);\n }\n\n /** Whether this message was crossposted from an announcement channel. */\n public get isCrosspost(): boolean {\n return (this.flags & 2) !== 0;\n }\n\n /** Whether this message has file attachments. */\n public get hasAttachments(): boolean {\n return this.attachments.length > 0;\n }\n\n /** Whether this message contains embeds. */\n public get hasEmbeds(): boolean {\n return this.embeds.length > 0;\n }\n\n /** Whether this message contains interactive components. */\n public get hasComponents(): boolean {\n return this.components.length > 0;\n }\n\n /** Edits this message to suppress its embeds. @returns The updated message. */\n public suppressEmbeds(): Promise<Message> {\n return this.edit({ flags: this.flags | 4 });\n }\n\n /** Returns a plain-object snapshot of all message fields. */\n public toJSON(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n channelId: this.channelId,\n guildId: this.guildId,\n flags: this.flags,\n pinned: this.pinned,\n mentionEveryone: this.mentionEveryone,\n type: this.type,\n timestamp: this.timestamp.toISOString(),\n author: { id: this.author.id, username: this.author.username },\n attachments: [...this.attachments],\n embeds: [...this.embeds],\n components: [...this.components],\n mentions: this.mentions.map((u) => u.id),\n mentionRoles: [...this.mentionRoles],\n reference: this.reference,\n referencedMessage: this.referencedMessage\n ? this.referencedMessage.id\n : this.referencedMessage,\n };\n }\n}\n\nexport {\n GuildMember,\n Role,\n TextChannel,\n Invite,\n Webhook,\n WebhookEnum,\n Emoji,\n AutoModerationRule,\n WelcomeScreenChannel,\n GuildWelcomeScreen,\n OnboardingPromptOption,\n OnboardingPrompt,\n GuildOnboarding,\n} from \"./resources.js\";\nexport {\n NewsChannel,\n DMChannel,\n VoiceChannel,\n StageChannel,\n CategoryChannel,\n ThreadChannel,\n ForumChannel,\n MediaChannel,\n createChannel,\n type ChannelOfKind,\n type ChannelsByKind,\n} from \"./channels.js\";\nexport * from \"./interactions.js\";\nexport { Embed } from \"./embed.js\";\nexport {\n AuditLog,\n AuditLogEntry,\n type AuditLogAutoModInfo,\n type AuditLogInfo,\n type AuditLogInfoByType,\n type AuditLogOverwriteInfo,\n type AuditLogQuery,\n} from \"./audit-log.js\";\nexport { Sticker, stickerURL } from \"./sticker.js\";\nexport { PermissionsBitField } from \"@lunibee/core\";\n"
20
26
  ],
21
- "mappings": ";;AACO,MAAM,cAAc;AAAA,EACP;AAAA,EACT,WAAW,CAAC,IAAY;AAAA,IAC3B,IAAI,CAAC,aAAa,KAAK,EAAE;AAAA,MACrB,MAAM,IAAI,UACN,oDACJ;AAAA,IACJ,KAAK,KAAK;AAAA;AAAA,EAGP,QAAQ,GAAW;AAAA,IACtB,OAAO,KAAK;AAAA;AAAA,MAGL,SAAS,GAAS;AAAA,IACzB,OAAO,IAAI,KAAK,QAAQ,OAAO,KAAK,EAAE,KAAK,OAAO,cAAc,CAAC;AAAA;AAEzE;AAuHO,IAAM,WAAW;AAajB,SAAS,MAAM,CAClB,MACA,MACA,UAA2B,CAAC,GACtB;AAAA,EACN,MAAM,aAAa,KAAK,WAAW,IAAI,KAAK,CAAC,QAAQ;AAAA,EACrD,MAAM,MAAM,QAAQ,cAAc,aAAa,QAAQ;AAAA,EACvD,MAAM,OAAO,QAAQ,OAAO,SAAS,QAAQ,SAAS;AAAA,EACtD,OAAO,GAAG,WAAW,QAAQ,QAAQ,MAAM;AAAA;AAAA;AAKxC,MAAM,aAAa,cAAc;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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