seyfert 0.1.0 → 1.0.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 (193) hide show
  1. package/README.md +19 -30
  2. package/lib/api/CDN.d.ts +0 -8
  3. package/lib/api/CDN.js +7 -13
  4. package/lib/api/Router.d.ts +2 -2
  5. package/lib/api/Router.js +1 -1
  6. package/lib/api/Routes/applications.d.ts +1 -1
  7. package/lib/api/Routes/channels.d.ts +1 -1
  8. package/lib/api/Routes/gateway.d.ts +1 -1
  9. package/lib/api/Routes/guilds.d.ts +1 -1
  10. package/lib/api/Routes/interactions.d.ts +1 -1
  11. package/lib/api/Routes/invites.d.ts +1 -1
  12. package/lib/api/Routes/stage-instances.d.ts +1 -1
  13. package/lib/api/Routes/stickers.d.ts +1 -1
  14. package/lib/api/Routes/users.d.ts +1 -1
  15. package/lib/api/Routes/voice.d.ts +1 -1
  16. package/lib/api/Routes/webhooks.d.ts +1 -1
  17. package/lib/api/api.d.ts +39 -0
  18. package/lib/api/api.js +318 -0
  19. package/lib/api/bucket.d.ts +19 -0
  20. package/lib/api/bucket.js +71 -0
  21. package/lib/api/index.d.ts +1 -1
  22. package/lib/api/index.js +1 -1
  23. package/lib/api/shared.d.ts +31 -5
  24. package/lib/api/shared.js +2 -7
  25. package/lib/api/utils/constants.d.ts +1 -30
  26. package/lib/api/utils/constants.js +2 -41
  27. package/lib/api/utils/types.d.ts +1 -320
  28. package/lib/api/utils/utils.d.ts +0 -38
  29. package/lib/api/utils/utils.js +1 -139
  30. package/lib/builders/ActionRow.js +1 -1
  31. package/lib/builders/Attachment.d.ts +14 -6
  32. package/lib/builders/Attachment.js +30 -7
  33. package/lib/builders/Button.d.ts +3 -12
  34. package/lib/builders/Button.js +0 -11
  35. package/lib/builders/{MessageEmbed.d.ts → Embed.d.ts} +15 -15
  36. package/lib/builders/{MessageEmbed.js → Embed.js} +16 -16
  37. package/lib/builders/Modal.js +1 -1
  38. package/lib/builders/SelectMenu.d.ts +14 -15
  39. package/lib/builders/SelectMenu.js +19 -18
  40. package/lib/builders/index.d.ts +1 -1
  41. package/lib/builders/index.js +1 -1
  42. package/lib/builders/types.d.ts +2 -2
  43. package/lib/cache/adapters/default.js +2 -2
  44. package/lib/cache/adapters/redis.d.ts +2 -3
  45. package/lib/cache/adapters/redis.js +13 -5
  46. package/lib/cache/adapters/workeradapter.d.ts +9 -1
  47. package/lib/cache/adapters/workeradapter.js +7 -3
  48. package/lib/cache/index.d.ts +20 -6
  49. package/lib/cache/index.js +26 -10
  50. package/lib/cache/resources/channels.d.ts +6 -2
  51. package/lib/cache/resources/channels.js +12 -6
  52. package/lib/cache/resources/default/base.d.ts +17 -16
  53. package/lib/cache/resources/default/base.js +25 -24
  54. package/lib/cache/resources/default/guild-based.d.ts +22 -19
  55. package/lib/cache/resources/default/guild-based.js +32 -31
  56. package/lib/cache/resources/default/guild-related.d.ts +22 -19
  57. package/lib/cache/resources/default/guild-related.js +37 -43
  58. package/lib/cache/resources/emojis.d.ts +4 -2
  59. package/lib/cache/resources/emojis.js +8 -6
  60. package/lib/cache/resources/guilds.d.ts +4 -2
  61. package/lib/cache/resources/guilds.js +15 -8
  62. package/lib/cache/resources/members.d.ts +4 -2
  63. package/lib/cache/resources/members.js +16 -13
  64. package/lib/cache/resources/overwrites.d.ts +25 -0
  65. package/lib/cache/resources/overwrites.js +39 -0
  66. package/lib/cache/resources/presence.js +3 -4
  67. package/lib/cache/resources/roles.d.ts +4 -2
  68. package/lib/cache/resources/roles.js +8 -6
  69. package/lib/cache/resources/stickers.d.ts +4 -2
  70. package/lib/cache/resources/stickers.js +8 -6
  71. package/lib/cache/resources/threads.d.ts +4 -2
  72. package/lib/cache/resources/threads.js +8 -6
  73. package/lib/cache/resources/users.d.ts +4 -2
  74. package/lib/cache/resources/users.js +8 -6
  75. package/lib/cache/resources/voice-states.d.ts +3 -3
  76. package/lib/cache/resources/voice-states.js +6 -7
  77. package/lib/client/base.d.ts +49 -16
  78. package/lib/client/base.js +21 -17
  79. package/lib/client/client.d.ts +14 -3
  80. package/lib/client/client.js +21 -21
  81. package/lib/client/httpclient.d.ts +3 -5
  82. package/lib/client/httpclient.js +29 -16
  83. package/lib/client/{oninteraction.d.ts → oninteractioncreate.d.ts} +1 -1
  84. package/lib/client/{oninteraction.js → oninteractioncreate.js} +34 -23
  85. package/lib/client/onmessagecreate.d.ts +3 -0
  86. package/lib/client/onmessagecreate.js +337 -0
  87. package/lib/client/workerclient.d.ts +5 -1
  88. package/lib/client/workerclient.js +67 -44
  89. package/lib/collection.d.ts +1 -1
  90. package/lib/collection.js +9 -6
  91. package/lib/commands/applications/chat.d.ts +32 -25
  92. package/lib/commands/applications/chat.js +51 -34
  93. package/lib/commands/applications/chatcontext.d.ts +34 -16
  94. package/lib/commands/applications/chatcontext.js +99 -20
  95. package/lib/commands/applications/menu.d.ts +9 -8
  96. package/lib/commands/applications/menu.js +14 -5
  97. package/lib/commands/applications/menucontext.d.ts +27 -10
  98. package/lib/commands/applications/menucontext.js +51 -7
  99. package/lib/commands/applications/options.d.ts +13 -13
  100. package/lib/commands/applications/shared.d.ts +7 -2
  101. package/lib/commands/decorators.d.ts +14 -14
  102. package/lib/commands/decorators.js +9 -5
  103. package/lib/commands/handler.d.ts +2 -1
  104. package/lib/commands/handler.js +60 -14
  105. package/lib/commands/index.d.ts +1 -1
  106. package/lib/commands/index.js +2 -1
  107. package/lib/commands/optionresolver.d.ts +6 -5
  108. package/lib/commands/optionresolver.js +10 -6
  109. package/lib/common/bot/watcher.d.ts +3 -3
  110. package/lib/common/bot/watcher.js +3 -1
  111. package/lib/common/index.d.ts +1 -1
  112. package/lib/common/index.js +2 -1
  113. package/lib/common/it/logger.d.ts +11 -0
  114. package/lib/common/it/logger.js +51 -2
  115. package/lib/common/it/utils.d.ts +3 -13
  116. package/lib/common/it/utils.js +9 -30
  117. package/lib/common/shorters/channels.d.ts +55 -5
  118. package/lib/common/shorters/channels.js +59 -0
  119. package/lib/common/shorters/guilds.d.ts +5 -2
  120. package/lib/common/shorters/guilds.js +18 -0
  121. package/lib/common/shorters/messages.js +0 -2
  122. package/lib/common/shorters/overwrites.d.ts +29 -0
  123. package/lib/common/shorters/overwrites.js +63 -0
  124. package/lib/common/shorters/roles.js +3 -3
  125. package/lib/common/shorters/webhook.d.ts +2 -2
  126. package/lib/common/types/util.d.ts +2 -1
  127. package/lib/common/types/write.d.ts +3 -7
  128. package/lib/components/handler.d.ts +12 -18
  129. package/lib/components/handler.js +58 -103
  130. package/lib/components/index.d.ts +0 -1
  131. package/lib/components/index.js +0 -1
  132. package/lib/components/listener.d.ts +2 -2
  133. package/lib/components/listener.js +2 -3
  134. package/lib/events/event.d.ts +2 -2
  135. package/lib/events/handler.d.ts +3 -2
  136. package/lib/events/handler.js +14 -6
  137. package/lib/events/hooks/dispatch.d.ts +2 -1
  138. package/lib/events/hooks/dispatch.js +5 -1
  139. package/lib/events/hooks/thread.d.ts +63 -63
  140. package/lib/index.d.ts +8 -5
  141. package/lib/index.js +20 -10
  142. package/lib/langs/handler.d.ts +6 -4
  143. package/lib/langs/handler.js +10 -8
  144. package/lib/langs/router.d.ts +8 -9
  145. package/lib/langs/router.js +5 -5
  146. package/lib/structures/ClientUser.d.ts +1 -16
  147. package/lib/structures/ClientUser.js +0 -31
  148. package/lib/structures/Guild.d.ts +1 -1
  149. package/lib/structures/GuildMember.d.ts +12 -0
  150. package/lib/structures/GuildMember.js +14 -0
  151. package/lib/structures/GuildRole.d.ts +4 -2
  152. package/lib/structures/GuildRole.js +4 -1
  153. package/lib/structures/GuildTemplate.js +1 -1
  154. package/lib/structures/Interaction.d.ts +2 -0
  155. package/lib/structures/Interaction.js +12 -13
  156. package/lib/structures/Message.d.ts +7 -2
  157. package/lib/structures/Message.js +6 -3
  158. package/lib/structures/Sticker.d.ts +1 -1
  159. package/lib/structures/Sticker.js +1 -1
  160. package/lib/structures/User.d.ts +5 -0
  161. package/lib/structures/User.js +3 -0
  162. package/lib/structures/Webhook.d.ts +1 -1
  163. package/lib/structures/Webhook.js +1 -1
  164. package/lib/structures/channels.d.ts +45 -6
  165. package/lib/structures/channels.js +23 -7
  166. package/lib/structures/extra/BitField.d.ts +9 -6
  167. package/lib/structures/extra/BitField.js +27 -3
  168. package/lib/structures/extra/Permissions.d.ts +6 -1
  169. package/lib/structures/extra/Permissions.js +7 -0
  170. package/lib/websocket/discord/basesocket.js +0 -1
  171. package/lib/websocket/discord/workermanager.d.ts +9 -1
  172. package/lib/websocket/discord/workermanager.js +21 -13
  173. package/package.json +21 -20
  174. package/lib/api/REST.d.ts +0 -127
  175. package/lib/api/REST.js +0 -424
  176. package/lib/api/errors/DiscordAPIError.d.ts +0 -51
  177. package/lib/api/errors/DiscordAPIError.js +0 -81
  178. package/lib/api/errors/HTTPError.d.ts +0 -20
  179. package/lib/api/errors/HTTPError.js +0 -28
  180. package/lib/api/errors/RateLimitError.d.ts +0 -19
  181. package/lib/api/errors/RateLimitError.js +0 -37
  182. package/lib/api/handlers/BurstHandler.d.ts +0 -51
  183. package/lib/api/handlers/BurstHandler.js +0 -124
  184. package/lib/api/handlers/SequentialHandler.d.ts +0 -81
  185. package/lib/api/handlers/SequentialHandler.js +0 -365
  186. package/lib/api/handlers/Shared.d.ts +0 -14
  187. package/lib/api/handlers/Shared.js +0 -125
  188. package/lib/api/interfaces/Handler.d.ts +0 -21
  189. package/lib/api/interfaces/Handler.js +0 -2
  190. package/lib/websocket/discord/handlemessage.d.ts +0 -0
  191. package/lib/websocket/discord/handlemessage.js +0 -1
  192. package/lib/websocket/discord/memberUpdate.d.ts +0 -16
  193. package/lib/websocket/discord/memberUpdate.js +0 -47
package/lib/api/REST.js DELETED
@@ -1,424 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REST = void 0;
4
- const magic_bytes_js_1 = require("magic-bytes.js");
5
- const collection_1 = require("../collection");
6
- const common_1 = require("../common");
7
- const logger_1 = require("../common/it/logger");
8
- const functions_1 = require("../structures/extra/functions");
9
- const CDN_1 = require("./CDN");
10
- const BurstHandler_1 = require("./handlers/BurstHandler");
11
- const SequentialHandler_1 = require("./handlers/SequentialHandler");
12
- const constants_1 = require("./utils/constants");
13
- const types_1 = require("./utils/types");
14
- const utils_1 = require("./utils/utils");
15
- /**
16
- * Represents the class that manages handlers for endpoints
17
- */
18
- class REST {
19
- /**
20
- * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests
21
- * performed by this manager.
22
- */
23
- agent = null;
24
- /**
25
- * The number of requests remaining in the global bucket
26
- */
27
- globalRemaining;
28
- /**
29
- * The promise used to wait out the global rate limit
30
- */
31
- globalDelay = null;
32
- /**
33
- * The timestamp at which the global bucket resets
34
- */
35
- globalReset = -1;
36
- /**
37
- * API bucket hashes that are cached from provided routes
38
- */
39
- hashes = new collection_1.Collection();
40
- /**
41
- * Request handlers created from the bucket hash and the major parameters
42
- */
43
- handlers = new collection_1.Collection();
44
- cdn;
45
- #token = null;
46
- hashTimer;
47
- handlerTimer;
48
- options;
49
- debugger;
50
- constructor(options) {
51
- this.options = (0, common_1.MergeOptions)(constants_1.DefaultRestOptions, options);
52
- this.options.offset = Math.max(0, this.options.offset);
53
- this.globalRemaining = Math.max(1, this.options.globalRequestsPerSecond);
54
- this.agent = options.agent ?? null;
55
- this.#token = options.token;
56
- this.cdn = new CDN_1.CDN();
57
- if (options.debug) {
58
- this.debugger = new logger_1.Logger({
59
- name: '[REST]',
60
- });
61
- }
62
- // Start sweepers
63
- this.setupSweepers();
64
- }
65
- setupSweepers() {
66
- // eslint-disable-next-line unicorn/consistent-function-scoping
67
- const validateMaxInterval = (interval) => {
68
- if (interval > 14_400_000) {
69
- throw new Error('Cannot set an interval greater than 4 hours');
70
- }
71
- };
72
- if (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {
73
- validateMaxInterval(this.options.hashSweepInterval);
74
- this.hashTimer = setInterval(() => {
75
- const sweptHashes = new collection_1.Collection();
76
- const currentDate = Date.now();
77
- // Begin sweeping hash based on lifetimes
78
- this.hashes.sweep((val, key) => {
79
- // `-1` indicates a global hash
80
- if (val.lastAccess === -1)
81
- return false;
82
- // Check if lifetime has been exceeded
83
- const shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;
84
- // Add hash to collection of swept hashes
85
- if (shouldSweep) {
86
- // Add to swept hashes
87
- sweptHashes.set(key, val);
88
- // Emit debug information
89
- this.debugger?.info(`Hash ${val.value} for ${key} swept due to lifetime being exceeded`);
90
- }
91
- return shouldSweep;
92
- });
93
- // Fire event
94
- this.debugger?.info(sweptHashes);
95
- }, this.options.hashSweepInterval);
96
- this.hashTimer.unref?.();
97
- }
98
- if (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {
99
- validateMaxInterval(this.options.handlerSweepInterval);
100
- this.handlerTimer = setInterval(() => {
101
- const sweptHandlers = new collection_1.Collection();
102
- // Begin sweeping handlers based on activity
103
- this.handlers.sweep((val, key) => {
104
- // Collect inactive handlers
105
- if (val.inactive) {
106
- sweptHandlers.set(key, val);
107
- this.debugger?.info(`Handler ${val.id} for ${key} swept due to being inactive`);
108
- }
109
- return val.inactive;
110
- });
111
- // Fire event
112
- this.debugger?.info(sweptHandlers);
113
- }, this.options.handlerSweepInterval);
114
- this.handlerTimer.unref?.();
115
- }
116
- }
117
- /**
118
- * Runs a get request from the api
119
- *
120
- * @param route - The full route to query
121
- * @param options - Optional request options
122
- */
123
- async get(route, options) {
124
- const data = await this.request({
125
- ...options,
126
- method: types_1.RequestMethod.Get,
127
- fullRoute: route,
128
- query: options?.query ? new URLSearchParams(options.query) : undefined,
129
- });
130
- return data;
131
- }
132
- /**
133
- * Runs a delete request from the api
134
- *
135
- * @param route - The full route to query
136
- * @param options - Optional request options
137
- */
138
- async delete(route, options) {
139
- const data = await this.request({
140
- ...options,
141
- fullRoute: route,
142
- method: types_1.RequestMethod.Delete,
143
- query: options?.query ? new URLSearchParams(options.query) : undefined,
144
- });
145
- return data;
146
- }
147
- /**
148
- * Runs a post request from the api
149
- *
150
- * @param route - The full route to query
151
- * @param options - Optional request options
152
- */
153
- async post(route, body) {
154
- const data = await this.request({
155
- fullRoute: route,
156
- method: types_1.RequestMethod.Post,
157
- ...body,
158
- body: body?.body,
159
- query: body?.query ? new URLSearchParams(body.query) : undefined,
160
- files: body?.files,
161
- });
162
- return data;
163
- }
164
- /**
165
- * Runs a put request from the api
166
- *
167
- * @param route - The full route to query
168
- * @param options - Optional request options
169
- */
170
- async put(route, body) {
171
- const data = await this.request({
172
- ...body,
173
- body: body?.body,
174
- query: body?.query ? new URLSearchParams(body.query) : undefined,
175
- files: body?.files,
176
- fullRoute: route,
177
- method: types_1.RequestMethod.Put,
178
- });
179
- return data;
180
- }
181
- /**
182
- * Runs a patch request from the api
183
- *
184
- * @param route - The full route to query
185
- * @param options - Optional request options
186
- */
187
- async patch(route, body) {
188
- const data = await this.request({
189
- ...body,
190
- body: body?.body,
191
- query: body?.query ? new URLSearchParams(body.query) : undefined,
192
- files: body?.files,
193
- fullRoute: route,
194
- method: types_1.RequestMethod.Patch,
195
- });
196
- return data;
197
- }
198
- /**
199
- * Runs a request from the api
200
- *
201
- * @param options - Request options
202
- */
203
- async request(options) {
204
- const response = await this.queueRequest(options);
205
- return (0, utils_1.parseResponse)(response);
206
- }
207
- /**
208
- * Sets the default agent to use for requests performed by this manager
209
- *
210
- * @param agent - The agent to use
211
- */
212
- setAgent(agent) {
213
- this.agent = agent;
214
- return this;
215
- }
216
- /**
217
- * Sets the authorization token that should be used for requests
218
- *
219
- * @param token - The authorization token to use
220
- */
221
- setToken(token) {
222
- this.#token = token;
223
- return this;
224
- }
225
- /**
226
- * Queues a request to be sent
227
- *
228
- * @param request - All the information needed to make a request
229
- * @returns The response from the api request
230
- */
231
- async queueRequest(request) {
232
- // Generalize the endpoint to its route data
233
- const routeId = REST.generateRouteData(request.fullRoute, request.method);
234
- // Get the bucket hash for the generic route, or point to a global route otherwise
235
- const hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {
236
- value: `Global(${request.method}:${routeId.bucketRoute})`,
237
- lastAccess: -1,
238
- };
239
- // Get the request handler for the obtained hash, with its major parameter
240
- const handler = this.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??
241
- this.createHandler(hash.value, routeId.majorParameter);
242
- // Resolve the request into usable fetch options
243
- const { url, fetchOptions } = await this.resolveRequest(request);
244
- // Queue the request
245
- return handler.queueRequest(routeId, url, fetchOptions, {
246
- body: request.body,
247
- files: request.files,
248
- auth: request.auth !== false,
249
- signal: request.signal,
250
- });
251
- }
252
- /**
253
- * Creates a new rate limit handler from a hash, based on the hash and the major parameter
254
- *
255
- * @param hash - The hash for the route
256
- * @param majorParameter - The major parameter for this handler
257
- * @internal
258
- */
259
- createHandler(hash, majorParameter) {
260
- // Create the async request queue to handle requests
261
- const queue = majorParameter === constants_1.BurstHandlerMajorIdKey
262
- ? new BurstHandler_1.BurstHandler(this, hash, majorParameter)
263
- : new SequentialHandler_1.SequentialHandler(this, hash, majorParameter);
264
- // Save the queue based on its id
265
- this.handlers.set(queue.id, queue);
266
- return queue;
267
- }
268
- /**
269
- * Formats the request data to a usable format for fetch
270
- *
271
- * @param request - The request data
272
- */
273
- async resolveRequest(request) {
274
- let query = '';
275
- // If a query option is passed, use it
276
- if (request.query) {
277
- const resolvedQuery = request.query.toString();
278
- if (resolvedQuery !== '') {
279
- query = `?${resolvedQuery}`;
280
- }
281
- }
282
- // Create the required headers
283
- const headers = {
284
- ...this.options.headers,
285
- 'User-Agent': `${constants_1.DefaultUserAgent} ${this.options.userAgentAppendix}`.trim(),
286
- };
287
- // If this request requires authorization (allowing non-"authorized" requests for webhooks)
288
- if (request.auth !== false) {
289
- // If we haven't received a token, throw an error
290
- if (!this.#token) {
291
- throw new Error('Expected token to be set for this request, but none was present');
292
- }
293
- headers.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;
294
- }
295
- // If a reason was set, set its appropriate header
296
- if (request.reason?.length) {
297
- headers['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);
298
- }
299
- // Format the full request URL (api base, optional version, endpoint, optional querystring)
300
- const url = `${this.options.api}${request.versioned === false ? '' : `/v${this.options.version}`}${request.fullRoute}${query}`;
301
- let finalBody;
302
- let additionalHeaders = {};
303
- if (request.files?.length) {
304
- const formData = new FormData();
305
- // Attach all files to the request
306
- for (const [index, file] of request.files.entries()) {
307
- const fileKey = file.key ?? `files[${index}]`;
308
- // https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters
309
- // FormData.append only accepts a string or Blob.
310
- // https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters
311
- // The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.
312
- if ((0, utils_1.isBufferLike)(file.data)) {
313
- // Try to infer the content type from the buffer if one isn't passed
314
- let contentType = file.contentType;
315
- if (!contentType) {
316
- const [parsedType] = (0, magic_bytes_js_1.filetypeinfo)(file.data);
317
- if (parsedType) {
318
- contentType =
319
- constants_1.OverwrittenMimeTypes[parsedType.mime] ??
320
- parsedType.mime ??
321
- 'application/octet-stream';
322
- }
323
- }
324
- formData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);
325
- }
326
- else {
327
- formData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);
328
- }
329
- }
330
- // If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified
331
- if (request.body != null) {
332
- if (request.appendToFormData) {
333
- for (const [key, value] of Object.entries(request.body)) {
334
- // @ts-expect-error
335
- formData.append(key, value);
336
- }
337
- }
338
- else {
339
- formData.append('payload_json', JSON.stringify(request.body));
340
- }
341
- }
342
- // Set the final body to the form data
343
- // @ts-expect-error
344
- finalBody = formData;
345
- // eslint-disable-next-line no-eq-null, eqeqeq
346
- }
347
- else if (request.body != null) {
348
- if (request.passThroughBody) {
349
- finalBody = request.body;
350
- }
351
- else {
352
- // Stringify the JSON data
353
- finalBody = JSON.stringify(request.body);
354
- // Set the additional headers to specify the content-type
355
- additionalHeaders = { 'Content-Type': 'application/json' };
356
- }
357
- }
358
- const method = request.method.toUpperCase();
359
- // The non null assertions in the following block are due to exactOptionalPropertyTypes, they have been tested to work with undefined
360
- const fetchOptions = {
361
- // Set body to null on get / head requests. This does not follow fetch spec (likely because it causes subtle bugs) but is aligned with what request was doing
362
- body: ['GET', 'HEAD'].includes(method) ? null : finalBody,
363
- headers: { ...request.headers, ...additionalHeaders, ...headers },
364
- method,
365
- // Prioritize setting an agent per request, use the agent for this instance otherwise.
366
- dispatcher: request.dispatcher ?? this.agent ?? undefined,
367
- };
368
- return { url, fetchOptions };
369
- }
370
- /**
371
- * Stops the hash sweeping interval
372
- */
373
- clearHashSweeper() {
374
- clearInterval(this.hashTimer);
375
- }
376
- /**
377
- * Stops the request handler sweeping interval
378
- */
379
- clearHandlerSweeper() {
380
- clearInterval(this.handlerTimer);
381
- }
382
- /**
383
- * Generates route data for an endpoint:method
384
- *
385
- * @param endpoint - The raw endpoint to generalize
386
- * @param method - The HTTP method this endpoint is called without
387
- * @internal
388
- */
389
- static generateRouteData(endpoint, method) {
390
- if (endpoint.startsWith('/interactions/') && endpoint.endsWith('/callback')) {
391
- return {
392
- majorParameter: constants_1.BurstHandlerMajorIdKey,
393
- bucketRoute: '/interactions/:id/:token/callback',
394
- original: endpoint,
395
- };
396
- }
397
- const majorIdMatch = /(?:^\/webhooks\/(\d{17,19}\/[^/?]+))|(?:^\/(?:channels|guilds|webhooks)\/(\d{17,19}))/.exec(endpoint);
398
- // Get the major id or id + token for this route - global otherwise
399
- const majorId = majorIdMatch?.[2] ?? majorIdMatch?.[1] ?? 'global';
400
- const baseRoute = endpoint
401
- // Strip out all ids
402
- .replaceAll(/\d{17,19}/g, ':id')
403
- // Strip out reaction as they fall under the same bucket
404
- .replace(/\/reactions\/(.*)/, '/reactions/:reaction')
405
- // Strip out webhook tokens
406
- .replace(/\/webhooks\/:id\/[^/?]+/, '/webhooks/:id/:token');
407
- let exceptions = '';
408
- // Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)
409
- // https://github.com/discord/discord-api-docs/issues/1295
410
- if (method === types_1.RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {
411
- const id = /\d{17,19}$/.exec(endpoint)[0];
412
- const timestamp = Number((0, functions_1.snowflakeToTimestamp)(id));
413
- if (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {
414
- exceptions += '/Delete Old Message';
415
- }
416
- }
417
- return {
418
- majorParameter: majorId,
419
- bucketRoute: baseRoute + exceptions,
420
- original: endpoint,
421
- };
422
- }
423
- }
424
- exports.REST = REST;
@@ -1,51 +0,0 @@
1
- import type { InternalRequest, RawFile } from '../utils/types.js';
2
- interface DiscordErrorFieldInformation {
3
- code: string;
4
- message: string;
5
- }
6
- interface DiscordErrorGroupWrapper {
7
- _errors: DiscordError[];
8
- }
9
- type DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | {
10
- [k: string]: DiscordError;
11
- };
12
- export interface DiscordErrorData {
13
- code: number;
14
- errors?: DiscordError;
15
- message: string;
16
- }
17
- export interface OAuthErrorData {
18
- error: string;
19
- error_description?: string;
20
- }
21
- export interface RequestBody {
22
- files: RawFile[] | undefined;
23
- json: unknown | undefined;
24
- }
25
- /**
26
- * Represents an API error returned by Discord
27
- */
28
- export declare class DiscordAPIError extends Error {
29
- rawError: DiscordErrorData | OAuthErrorData;
30
- code: number | string;
31
- status: number;
32
- method: string;
33
- url: string;
34
- requestBody: RequestBody;
35
- /**
36
- * @param rawError - The error reported by Discord
37
- * @param code - The error code reported by Discord
38
- * @param status - The status code of the response
39
- * @param method - The method of the request that erred
40
- * @param url - The url of the request that erred
41
- * @param bodyData - The unparsed data for the request that errored
42
- */
43
- constructor(rawError: DiscordErrorData | OAuthErrorData, code: number | string, status: number, method: string, url: string, bodyData: Pick<InternalRequest, 'body' | 'files'>);
44
- /**
45
- * The name of the error
46
- */
47
- get name(): string;
48
- private static getMessage;
49
- private static flattenDiscordError;
50
- }
51
- export {};
@@ -1,81 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DiscordAPIError = void 0;
4
- function isErrorGroupWrapper(error) {
5
- return Reflect.has(error, '_errors');
6
- }
7
- function isErrorResponse(error) {
8
- return typeof Reflect.get(error, 'message') === 'string';
9
- }
10
- /**
11
- * Represents an API error returned by Discord
12
- */
13
- class DiscordAPIError extends Error {
14
- rawError;
15
- code;
16
- status;
17
- method;
18
- url;
19
- requestBody;
20
- /**
21
- * @param rawError - The error reported by Discord
22
- * @param code - The error code reported by Discord
23
- * @param status - The status code of the response
24
- * @param method - The method of the request that erred
25
- * @param url - The url of the request that erred
26
- * @param bodyData - The unparsed data for the request that errored
27
- */
28
- constructor(rawError, code, status, method, url, bodyData) {
29
- super(DiscordAPIError.getMessage(rawError));
30
- this.rawError = rawError;
31
- this.code = code;
32
- this.status = status;
33
- this.method = method;
34
- this.url = url;
35
- this.requestBody = { files: bodyData.files, json: bodyData.body };
36
- }
37
- /**
38
- * The name of the error
39
- */
40
- get name() {
41
- return `${DiscordAPIError.name}[${this.code}]`;
42
- }
43
- static getMessage(error) {
44
- let flattened = '';
45
- if ('code' in error) {
46
- if (error.errors) {
47
- flattened = [...this.flattenDiscordError(error.errors)].join('\n');
48
- }
49
- return error.message && flattened
50
- ? `${error.message}\n${flattened}`
51
- : error.message || flattened || 'Unknown Error';
52
- }
53
- return error.error_description ?? 'No Description';
54
- }
55
- static *flattenDiscordError(obj, key = '') {
56
- if (isErrorResponse(obj)) {
57
- return yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();
58
- }
59
- for (const [otherKey, val] of Object.entries(obj)) {
60
- const nextKey = otherKey.startsWith('_')
61
- ? key
62
- : key
63
- ? Number.isNaN(Number(otherKey))
64
- ? `${key}.${otherKey}`
65
- : `${key}[${otherKey}]`
66
- : otherKey;
67
- if (typeof val === 'string') {
68
- yield val;
69
- }
70
- else if (isErrorGroupWrapper(val)) {
71
- for (const error of val._errors) {
72
- yield* this.flattenDiscordError(error, nextKey);
73
- }
74
- }
75
- else {
76
- yield* this.flattenDiscordError(val, nextKey);
77
- }
78
- }
79
- }
80
- }
81
- exports.DiscordAPIError = DiscordAPIError;
@@ -1,20 +0,0 @@
1
- import type { InternalRequest } from '../utils/types.js';
2
- import type { RequestBody } from './DiscordAPIError.js';
3
- /**
4
- * Represents a HTTP error
5
- */
6
- export declare class HTTPError extends Error {
7
- status: number;
8
- method: string;
9
- url: string;
10
- requestBody: RequestBody;
11
- name: string;
12
- /**
13
- * @param status - The status code of the response
14
- * @param statusText - The status text of the response
15
- * @param method - The method of the request that erred
16
- * @param url - The url of the request that erred
17
- * @param bodyData - The unparsed data for the request that errored
18
- */
19
- constructor(status: number, statusText: string, method: string, url: string, bodyData: Pick<InternalRequest, 'body' | 'files'>);
20
- }
@@ -1,28 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HTTPError = void 0;
4
- /**
5
- * Represents a HTTP error
6
- */
7
- class HTTPError extends Error {
8
- status;
9
- method;
10
- url;
11
- requestBody;
12
- name = HTTPError.name;
13
- /**
14
- * @param status - The status code of the response
15
- * @param statusText - The status text of the response
16
- * @param method - The method of the request that erred
17
- * @param url - The url of the request that erred
18
- * @param bodyData - The unparsed data for the request that errored
19
- */
20
- constructor(status, statusText, method, url, bodyData) {
21
- super(statusText);
22
- this.status = status;
23
- this.method = method;
24
- this.url = url;
25
- this.requestBody = { files: bodyData.files, json: bodyData.body };
26
- }
27
- }
28
- exports.HTTPError = HTTPError;
@@ -1,19 +0,0 @@
1
- import type { RateLimitData } from '../utils/types.js';
2
- export declare class RateLimitError extends Error implements RateLimitData {
3
- timeToReset: number;
4
- limit: number;
5
- method: string;
6
- hash: string;
7
- url: string;
8
- route: string;
9
- majorParameter: string;
10
- global: boolean;
11
- retryAfter: number;
12
- sublimitTimeout: number;
13
- scope: RateLimitData['scope'];
14
- constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global, retryAfter, sublimitTimeout, scope, }: RateLimitData);
15
- /**
16
- * The name of the error
17
- */
18
- get name(): string;
19
- }
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RateLimitError = void 0;
4
- class RateLimitError extends Error {
5
- timeToReset;
6
- limit;
7
- method;
8
- hash;
9
- url;
10
- route;
11
- majorParameter;
12
- global;
13
- retryAfter;
14
- sublimitTimeout;
15
- scope;
16
- constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global, retryAfter, sublimitTimeout, scope, }) {
17
- super();
18
- this.timeToReset = timeToReset;
19
- this.limit = limit;
20
- this.method = method;
21
- this.hash = hash;
22
- this.url = url;
23
- this.route = route;
24
- this.majorParameter = majorParameter;
25
- this.global = global;
26
- this.retryAfter = retryAfter;
27
- this.sublimitTimeout = sublimitTimeout;
28
- this.scope = scope;
29
- }
30
- /**
31
- * The name of the error
32
- */
33
- get name() {
34
- return `${RateLimitError.name}[${this.route}]`;
35
- }
36
- }
37
- exports.RateLimitError = RateLimitError;