SupportBot 7.3
This commit is contained in:
1 parent
19a12f6c8f
commit
09f0873f27
4762 files changed
+504608
-52
No files matched your search
+7
@@ -0,0 +1,7 @@
|
||||
export * from './lib/CDN';
|
||||
export * from './lib/errors/DiscordAPIError';
|
||||
export * from './lib/errors/HTTPError';
|
||||
export * from './lib/RequestManager';
|
||||
export * from './lib/REST';
|
||||
export * from './lib/utils/constants';
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"./","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,8BAA8B,CAAC;AAC7C,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,YAAY,CAAC;AAC3B,cAAc,uBAAuB,CAAC"}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const tslib_1 = require("tslib");
|
||||
tslib_1.__exportStar(require("./lib/CDN"), exports);
|
||||
tslib_1.__exportStar(require("./lib/errors/DiscordAPIError"), exports);
|
||||
tslib_1.__exportStar(require("./lib/errors/HTTPError"), exports);
|
||||
tslib_1.__exportStar(require("./lib/RequestManager"), exports);
|
||||
tslib_1.__exportStar(require("./lib/REST"), exports);
|
||||
tslib_1.__exportStar(require("./lib/utils/constants"), exports);
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"./","sources":["index.ts"],"names":[],"mappings":";;;AAAA,oDAA0B;AAC1B,uEAA6C;AAC7C,iEAAuC;AACvC,+DAAqC;AACrC,qDAA2B;AAC3B,gEAAsC"}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import { ImageExtension, ImageSize } from './utils/constants';
|
||||
export interface ImageURLOptions {
|
||||
extension?: ImageExtension;
|
||||
size?: ImageSize;
|
||||
dynamic?: boolean;
|
||||
}
|
||||
/**
|
||||
* The CDN link builder
|
||||
*/
|
||||
export declare class CDN {
|
||||
private readonly base;
|
||||
constructor(base?: string);
|
||||
/**
|
||||
* Generates an app asset URL for a client's asset.
|
||||
* @param clientID The client ID that has the asset
|
||||
* @param assetHash The hash provided by Discord for this asset
|
||||
* @param options Optional options for the asset
|
||||
*/
|
||||
appAsset(clientID: string, assetHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates an app icon URL for a client's icon.
|
||||
* @param clientID The client ID that has the icon
|
||||
* @param iconHash The hash provided by Discord for this icon
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
appIcon(clientID: string, iconHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates the default avatar URL for a discriminator.
|
||||
* @param discriminator The discriminator modulo 5
|
||||
*/
|
||||
defaultAvatar(discriminator: number): string;
|
||||
/**
|
||||
* Generates a discovery splash URL for a guild's discovery splash.
|
||||
* @param guildID The guild ID that has the discovery splash
|
||||
* @param splashHash The hash provided by Discord for this splash
|
||||
* @param options Optional options for the splash
|
||||
*/
|
||||
discoverySplash(guildID: string, splashHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates an emoji's URL for an emoji.
|
||||
* @param emojiID The emoji ID
|
||||
* @param extension The extension of the emoji
|
||||
*/
|
||||
emoji(emojiID: string, extension?: ImageExtension): string;
|
||||
/**
|
||||
* Generates a group DM icon URL for a group DM.
|
||||
* @param channelID The group channel ID that has the icon
|
||||
* @param iconHash The hash provided by Discord for this group DM channel
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
groupDMIcon(channelID: string, iconHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates a banner URL for a guild's banner.
|
||||
* @param guildID The guild ID that has the banner splash
|
||||
* @param bannerHash The hash provided by Discord for this banner
|
||||
* @param options Optional options for the banner
|
||||
*/
|
||||
guildBanner(guildID: string, bannerHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates an icon URL for a guild's icon.
|
||||
* @param guildID The guild ID that has the icon splash
|
||||
* @param iconHash The hash provided by Discord for this icon
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
guildIcon(guildID: string, iconHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates a guild invite splash URL for a guild's invite splash.
|
||||
* @param guildID The guild ID that has the invite splash
|
||||
* @param splashHash The hash provided by Discord for this splash
|
||||
* @param options Optional options for the splash
|
||||
*/
|
||||
splash(guildID: string, splashHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates a team icon URL for a team's icon.
|
||||
* @param teamID The team ID that has the icon
|
||||
* @param iconHash The hash provided by Discord for this icon
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
teamIcon(teamID: string, iconHash: string, options?: ImageURLOptions): string;
|
||||
/**
|
||||
* Generates a user avatar URL for a user's avatar.
|
||||
* @param userID The user ID that has the icon
|
||||
* @param avatarHash The hash provided by Discord for this avatar
|
||||
* @param options Optional options for the avatar
|
||||
*/
|
||||
userAvatar(userID: string, avatarHash: string, { dynamic, ...options }?: ImageURLOptions): string;
|
||||
/**
|
||||
* Constructs the URL for the resource
|
||||
* @param base The base cdn route
|
||||
* @param options The extension/size options for the link
|
||||
*/
|
||||
private makeURL;
|
||||
}
|
||||
//# sourceMappingURL=CDN.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"CDN.d.ts","sourceRoot":"./","sources":["lib/CDN.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyD,cAAc,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAErH,MAAM,WAAW,eAAe;IAC/B,SAAS,CAAC,EAAE,cAAc,CAAC;IAC3B,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,qBAAa,GAAG;IACI,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,GAAE,MAA+B;IAEzE;;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,eAAoB,GAAG,MAAM;IAQpH;;;;OAIG;IACH,OAAO,CAAC,OAAO;CAqBf"}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CDN = void 0;
|
||||
const constants_1 = require("./utils/constants");
|
||||
/**
|
||||
* The CDN link builder
|
||||
*/
|
||||
class CDN {
|
||||
constructor(base = constants_1.DefaultRestOptions.cdn) {
|
||||
this.base = base;
|
||||
}
|
||||
/**
|
||||
* Generates an app asset URL for a client's asset.
|
||||
* @param clientID The client ID that has the asset
|
||||
* @param assetHash The hash provided by Discord for this asset
|
||||
* @param options Optional options for the asset
|
||||
*/
|
||||
appAsset(clientID, assetHash, options) {
|
||||
return this.makeURL(`/app-assets/${clientID}/${assetHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates an app icon URL for a client's icon.
|
||||
* @param clientID The client ID that has the icon
|
||||
* @param iconHash The hash provided by Discord for this icon
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
appIcon(clientID, iconHash, options) {
|
||||
return this.makeURL(`/app-icons/${clientID}/${iconHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates the default avatar URL for a discriminator.
|
||||
* @param discriminator The discriminator modulo 5
|
||||
*/
|
||||
defaultAvatar(discriminator) {
|
||||
return this.makeURL(`/embed/avatars/${discriminator}`);
|
||||
}
|
||||
/**
|
||||
* Generates a discovery splash URL for a guild's discovery splash.
|
||||
* @param guildID The guild ID that has the discovery splash
|
||||
* @param splashHash The hash provided by Discord for this splash
|
||||
* @param options Optional options for the splash
|
||||
*/
|
||||
discoverySplash(guildID, splashHash, options) {
|
||||
return this.makeURL(`/discovery-splashes/${guildID}/${splashHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates an emoji's URL for an emoji.
|
||||
* @param emojiID The emoji ID
|
||||
* @param extension The extension of the emoji
|
||||
*/
|
||||
emoji(emojiID, extension) {
|
||||
return this.makeURL(`/emojis/${emojiID}`, { extension });
|
||||
}
|
||||
/**
|
||||
* Generates a group DM icon URL for a group DM.
|
||||
* @param channelID The group channel ID that has the icon
|
||||
* @param iconHash The hash provided by Discord for this group DM channel
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
groupDMIcon(channelID, iconHash, options) {
|
||||
return this.makeURL(`/channel-icons/${channelID}/${iconHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates a banner URL for a guild's banner.
|
||||
* @param guildID The guild ID that has the banner splash
|
||||
* @param bannerHash The hash provided by Discord for this banner
|
||||
* @param options Optional options for the banner
|
||||
*/
|
||||
guildBanner(guildID, bannerHash, options) {
|
||||
return this.makeURL(`/banners/${guildID}/${bannerHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates an icon URL for a guild's icon.
|
||||
* @param guildID The guild ID that has the icon splash
|
||||
* @param iconHash The hash provided by Discord for this icon
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
guildIcon(guildID, iconHash, options) {
|
||||
return this.makeURL(`/icons/${guildID}/${iconHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates a guild invite splash URL for a guild's invite splash.
|
||||
* @param guildID The guild ID that has the invite splash
|
||||
* @param splashHash The hash provided by Discord for this splash
|
||||
* @param options Optional options for the splash
|
||||
*/
|
||||
splash(guildID, splashHash, options) {
|
||||
return this.makeURL(`/splashes/${guildID}/${splashHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates a team icon URL for a team's icon.
|
||||
* @param teamID The team ID that has the icon
|
||||
* @param iconHash The hash provided by Discord for this icon
|
||||
* @param options Optional options for the icon
|
||||
*/
|
||||
teamIcon(teamID, iconHash, options) {
|
||||
return this.makeURL(`/team-icons/${teamID}/${iconHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Generates a user avatar URL for a user's avatar.
|
||||
* @param userID The user ID that has the icon
|
||||
* @param avatarHash The hash provided by Discord for this avatar
|
||||
* @param options Optional options for the avatar
|
||||
*/
|
||||
userAvatar(userID, avatarHash, { dynamic = false, ...options } = {}) {
|
||||
if (dynamic && avatarHash.startsWith('a_')) {
|
||||
options.extension = 'gif';
|
||||
}
|
||||
return this.makeURL(`/avatars/${userID}/${avatarHash}`, options);
|
||||
}
|
||||
/**
|
||||
* Constructs the URL for the resource
|
||||
* @param base The base cdn route
|
||||
* @param options The extension/size options for the link
|
||||
*/
|
||||
makeURL(base, { extension = 'png', size } = {}) {
|
||||
extension = String(extension).toLowerCase();
|
||||
if (!constants_1.ALLOWED_EXTENSIONS.includes(extension)) {
|
||||
throw new RangeError(`Invalid extension provided: ${extension}\nMust be one of: ${constants_1.ALLOWED_EXTENSIONS.join(', ')}`);
|
||||
}
|
||||
if (size && !constants_1.ALLOWED_SIZES.includes(size)) {
|
||||
throw new RangeError(`Invalid size provided: ${size}\nMust be one of: ${constants_1.ALLOWED_SIZES.join(', ')}`);
|
||||
}
|
||||
const url = new URL(`${this.base}${base}.${extension}`);
|
||||
if (size) {
|
||||
url.searchParams.set('size', String(size));
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
}
|
||||
exports.CDN = CDN;
|
||||
//# sourceMappingURL=CDN.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"CDN.js","sourceRoot":"./","sources":["lib/CDN.ts"],"names":[],"mappings":";;;AAAA,iDAAqH;AAQrH;;GAEG;AACH,MAAa,GAAG;IACf,YAAoC,OAAe,8BAAkB,CAAC,GAAG;QAArC,SAAI,GAAJ,IAAI,CAAiC;IAAG,CAAC;IAE7E;;;;;OAKG;IACI,QAAQ,CAAC,QAAgB,EAAE,SAAiB,EAAE,OAAyB;QAC7E,OAAO,IAAI,CAAC,OAAO,CAAC,eAAe,QAAQ,IAAI,SAAS,EAAE,EAAE,OAAO,CAAC,CAAC;IACtE,CAAC;IAED;;;;;OAKG;IACI,OAAO,CAAC,QAAgB,EAAE,QAAgB,EAAE,OAAyB;QAC3E,OAAO,IAAI,CAAC,OAAO,CAAC,cAAc,QAAQ,IAAI,QAAQ,EAAE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ACvB,CAAC;CACD;AA5ID,kBA4IC"}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
/// <reference types="node" />
|
||||
import { EventEmitter } from 'events';
|
||||
import { CDN } from './CDN';
|
||||
import { InternalRequest, RequestData, RequestManager, RouteLike } from './RequestManager';
|
||||
/**
|
||||
* Options to be passed when creating the REST instance
|
||||
*/
|
||||
export interface RESTOptions {
|
||||
/**
|
||||
* The base api path, without version
|
||||
* @default 'https://discord.com/api'
|
||||
*/
|
||||
api: string;
|
||||
/**
|
||||
* The cdn path
|
||||
* @default 'https://cdn.discordapp.com'
|
||||
*/
|
||||
cdn: string;
|
||||
/**
|
||||
* The extra offset to add to rate limits in milliseconds
|
||||
* @default 50
|
||||
*/
|
||||
offset: number;
|
||||
/**
|
||||
* The number of retries for errors with the 500 code, or errors
|
||||
* that timeout
|
||||
* @default 3
|
||||
*/
|
||||
retries: number;
|
||||
/**
|
||||
* The time to wait in milliseconds before a request is aborted
|
||||
* @default 15_000
|
||||
*/
|
||||
timeout: number;
|
||||
/**
|
||||
* Extra information to add to the user agent
|
||||
* @default `Node.js ${process.version}`
|
||||
*/
|
||||
userAgentAppendix: string;
|
||||
/**
|
||||
* The version of the API to use
|
||||
* @default '8'
|
||||
*/
|
||||
version: string;
|
||||
}
|
||||
/**
|
||||
* Data emitted on `RESTEvents.Debug`
|
||||
*/
|
||||
export interface RatelimitData {
|
||||
/**
|
||||
* The time, in milliseconds, until the request-lock is reset
|
||||
*/
|
||||
timeToReset: number;
|
||||
/**
|
||||
* The amount of requests we can perform before locking requests
|
||||
*/
|
||||
limit: number;
|
||||
/**
|
||||
* The HTTP method being performed
|
||||
*/
|
||||
method: string;
|
||||
/**
|
||||
* The bucket hash for this request
|
||||
*/
|
||||
hash: string;
|
||||
/**
|
||||
* The route being hit in this request
|
||||
*/
|
||||
route: string;
|
||||
/**
|
||||
* The major parameter of the route
|
||||
*
|
||||
* For example, in `/channels/x`, this will be `x`.
|
||||
* If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.
|
||||
*/
|
||||
majorParameter: string;
|
||||
}
|
||||
interface RestEvents {
|
||||
restDebug: [info: string];
|
||||
rateLimited: [rateLimitInfo: RatelimitData];
|
||||
}
|
||||
export interface REST {
|
||||
on<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void): this;
|
||||
on<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void): this;
|
||||
once<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void): this;
|
||||
once<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void): this;
|
||||
emit<K extends keyof RestEvents>(event: K, ...args: RestEvents[K]): boolean;
|
||||
emit<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, ...args: any[]): boolean;
|
||||
off<K extends keyof RestEvents>(event: K, listener: (...args: RestEvents[K]) => void): this;
|
||||
off<S extends string | symbol>(event: Exclude<S, keyof RestEvents>, listener: (...args: any[]) => void): this;
|
||||
removeAllListeners<K extends keyof RestEvents>(event?: K): this;
|
||||
removeAllListeners<S extends string | symbol>(event?: Exclude<S, keyof RestEvents>): this;
|
||||
}
|
||||
export declare class REST extends EventEmitter {
|
||||
readonly cdn: CDN;
|
||||
readonly requestManager: RequestManager;
|
||||
constructor(options?: Partial<RESTOptions>);
|
||||
/**
|
||||
* Sets the authorization token that should be used for requests
|
||||
* @param token The authorization token to use
|
||||
*/
|
||||
setToken(token: string): this;
|
||||
/**
|
||||
* Runs a get request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
get(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
|
||||
/**
|
||||
* Runs a delete request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
delete(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
|
||||
/**
|
||||
* Runs a post request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
post(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
|
||||
/**
|
||||
* Runs a put request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
put(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
|
||||
/**
|
||||
* Runs a patch request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
patch(fullRoute: RouteLike, options?: RequestData): Promise<unknown>;
|
||||
/**
|
||||
* Runs a request from the api
|
||||
* @param options Request options
|
||||
*/
|
||||
request(options: InternalRequest): Promise<unknown>;
|
||||
}
|
||||
export {};
|
||||
//# sourceMappingURL=REST.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"REST.d.ts","sourceRoot":"./","sources":["lib/REST.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,cAAc,EAAiB,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAG1G;;GAEG;AACH,MAAM,WAAW,WAAW;IAC3B;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC7B;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;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AAO,GAAE,WAAgB;IAI5D;;;OAGG;IACI,OAAO,CAAC,OAAO,EAAE,eAAe;CAGvC"}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.REST = void 0;
|
||||
const events_1 = require("events");
|
||||
const CDN_1 = require("./CDN");
|
||||
const RequestManager_1 = require("./RequestManager");
|
||||
const constants_1 = require("./utils/constants");
|
||||
class REST extends events_1.EventEmitter {
|
||||
constructor(options = {}) {
|
||||
super();
|
||||
this.cdn = new CDN_1.CDN(options.cdn ?? constants_1.DefaultRestOptions.cdn);
|
||||
this.requestManager = new RequestManager_1.RequestManager(options)
|
||||
.on("restDebug" /* Debug */, this.emit.bind(this, "restDebug" /* Debug */))
|
||||
.on("rateLimited" /* RateLimited */, this.emit.bind(this, "rateLimited" /* RateLimited */));
|
||||
}
|
||||
/**
|
||||
* Sets the authorization token that should be used for requests
|
||||
* @param token The authorization token to use
|
||||
*/
|
||||
setToken(token) {
|
||||
this.requestManager.setToken(token);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Runs a get request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
get(fullRoute, options = {}) {
|
||||
return this.request({ ...options, fullRoute, method: "get" /* Get */ });
|
||||
}
|
||||
/**
|
||||
* Runs a delete request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
delete(fullRoute, options = {}) {
|
||||
return this.request({ ...options, fullRoute, method: "delete" /* Delete */ });
|
||||
}
|
||||
/**
|
||||
* Runs a post request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
post(fullRoute, options = {}) {
|
||||
return this.request({ ...options, fullRoute, method: "post" /* Post */ });
|
||||
}
|
||||
/**
|
||||
* Runs a put request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
put(fullRoute, options = {}) {
|
||||
return this.request({ ...options, fullRoute, method: "put" /* Put */ });
|
||||
}
|
||||
/**
|
||||
* Runs a patch request from the api
|
||||
* @param fullRoute The full route to query
|
||||
* @param options Optional request options
|
||||
*/
|
||||
patch(fullRoute, options = {}) {
|
||||
return this.request({ ...options, fullRoute, method: "patch" /* Patch */ });
|
||||
}
|
||||
/**
|
||||
* Runs a request from the api
|
||||
* @param options Request options
|
||||
*/
|
||||
request(options) {
|
||||
return this.requestManager.queueRequest(options);
|
||||
}
|
||||
}
|
||||
exports.REST = REST;
|
||||
//# sourceMappingURL=REST.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"REST.js","sourceRoot":"./","sources":["lib/REST.ts"],"names":[],"mappings":";;;AAAA,mCAAsC;AACtC,+BAA4B;AAC5B,qDAA0G;AAC1G,iDAAmE;AAmGnE,MAAa,IAAK,SAAQ,qBAAY;IAIrC,YAAmB,UAAgC,EAAE;QACpD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,GAAG,GAAG,IAAI,SAAG,CAAC,OAAO,CAAC,GAAG,IAAI,8BAAkB,CAAC,GAAG,CAAC,CAAC;QAC1D,IAAI,CAAC,cAAc,GAAG,IAAI,+BAAc,CAAC,OAAO,CAAC;aAC/C,EAAE,0BAAmB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,0BAAmB,CAAC;aAC5D,EAAE,kCAAyB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,kCAAyB,CAAC,CAAC;IAC5E,CAAC;IAED;;;OAGG;IACI,QAAQ,CAAC,KAAa;QAC5B,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC;IACb,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAC,SAAoB,EAAE,UAAuB,EAAE;QACzD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAmB,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,SAAoB,EAAE,UAAuB,EAAE;QAC5D,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAsB,EAAE,CAAC,CAAC;IAC9E,CAAC;IAED;;;;OAIG;IACI,IAAI,CAAC,SAAoB,EAAE,UAAuB,EAAE;QAC1D,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAoB,EAAE,CAAC,CAAC;IAC5E,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAC,SAAoB,EAAE,UAAuB,EAAE;QACzD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAmB,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED;;;;OAIG;IACI,KAAK,CAAC,SAAoB,EAAE,UAAuB,EAAE;QAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED;;;OAGG;IACI,OAAO,CAAC,OAAwB;QACtC,OAAO,IAAI,CAAC,cAAc,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;CACD;AAzED,oBAyEC"}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
/// <reference types="node" />
|
||||
import Collection from '@discordjs/collection';
|
||||
import { EventEmitter } from 'events';
|
||||
import type { IHandler } from './handlers/IHandler';
|
||||
import type { RESTOptions } from './REST';
|
||||
/**
|
||||
* Represents an attachment to be added to the request
|
||||
*/
|
||||
export interface RawAttachment {
|
||||
fileName: string;
|
||||
rawBuffer: Buffer;
|
||||
}
|
||||
/**
|
||||
* Represents possible data to be given to an endpoint
|
||||
*/
|
||||
export interface RequestData {
|
||||
/**
|
||||
* Files to be attached to this request
|
||||
*/
|
||||
attachments?: RawAttachment[];
|
||||
/**
|
||||
* If this request needs the `Authorization` header
|
||||
* @default true
|
||||
*/
|
||||
auth?: boolean;
|
||||
/**
|
||||
* The authorization prefix to use for this request, useful if you use this with bearer tokens
|
||||
* @default 'Bot'
|
||||
*/
|
||||
authPrefix?: 'Bot' | 'Bearer';
|
||||
/**
|
||||
* The body to send to this request
|
||||
*/
|
||||
body?: unknown;
|
||||
/**
|
||||
* Additional headers to add to this request
|
||||
*/
|
||||
headers?: Record<string, string>;
|
||||
/**
|
||||
* Query string parameters to append to the called endpoint
|
||||
*/
|
||||
query?: URLSearchParams;
|
||||
/**
|
||||
* Reason to show in the audit logs
|
||||
*/
|
||||
reason?: string;
|
||||
/**
|
||||
* If this request should be versioned
|
||||
* @default true
|
||||
*/
|
||||
versioned?: boolean;
|
||||
}
|
||||
/**
|
||||
* Possible headers for an API call
|
||||
*/
|
||||
export interface RequestHeaders {
|
||||
Authorization?: string;
|
||||
'User-Agent': string;
|
||||
'X-Audit-Log-Reason'?: string;
|
||||
}
|
||||
/**
|
||||
* Possible API methods to be used when doing requests
|
||||
*/
|
||||
export declare const enum RequestMethod {
|
||||
Delete = "delete",
|
||||
Get = "get",
|
||||
Patch = "patch",
|
||||
Post = "post",
|
||||
Put = "put"
|
||||
}
|
||||
export declare type RouteLike = `/${string}`;
|
||||
/**
|
||||
* Internal request options
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export interface InternalRequest extends RequestData {
|
||||
method: RequestMethod;
|
||||
fullRoute: RouteLike;
|
||||
}
|
||||
/**
|
||||
* Parsed route data for an endpoint
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
export interface RouteData {
|
||||
majorParameter: string;
|
||||
bucketRoute: string;
|
||||
original: string;
|
||||
}
|
||||
/**
|
||||
* Represents the class that manages handlers for endpoints
|
||||
*/
|
||||
export declare class RequestManager extends EventEmitter {
|
||||
#private;
|
||||
/**
|
||||
* A timeout promise that is set when we hit the global rate limit
|
||||
* @default null
|
||||
*/
|
||||
globalTimeout: Promise<void> | null;
|
||||
/**
|
||||
* API bucket hashes that are cached from provided routes
|
||||
*/
|
||||
readonly hashes: Collection<string, string>;
|
||||
/**
|
||||
* Request handlers created from the bucket hash and the major parameters
|
||||
*/
|
||||
readonly handlers: Collection<string, IHandler>;
|
||||
readonly options: RESTOptions;
|
||||
constructor(options: Partial<RESTOptions>);
|
||||
/**
|
||||
* Sets the authorization token that should be used for requests
|
||||
* @param token The authorization token to use
|
||||
*/
|
||||
setToken(token: string): this;
|
||||
/**
|
||||
* Queues a request to be sent
|
||||
* @param request All the information needed to make a request
|
||||
* @returns The response from the api request
|
||||
*/
|
||||
queueRequest(request: InternalRequest): Promise<unknown>;
|
||||
/**
|
||||
* Creates a new rate limit handler from a hash, based on the hash and the major parameter
|
||||
* @param hash The hash for the route
|
||||
* @param majorParameter The major parameter for this handler
|
||||
* @private
|
||||
*/
|
||||
private createHandler;
|
||||
/**
|
||||
* Formats the request data to a usable format for fetch
|
||||
* @param request The request data
|
||||
*/
|
||||
private resolveRequest;
|
||||
/**
|
||||
* Generates route data for an endpoint:method
|
||||
* @param endpoint The raw endpoint to generalize
|
||||
* @param method The HTTP method this endpoint is called without
|
||||
* @private
|
||||
*/
|
||||
private static generateRouteData;
|
||||
}
|
||||
//# sourceMappingURL=RequestManager.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"RequestManager.d.ts","sourceRoot":"./","sources":["lib/RequestManager.ts"],"names":[],"mappings":";AAAA,OAAO,UAAU,MAAM,uBAAuB,CAAC;AAG/C,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAK1C;;GAEG;AACH,MAAM,WAAW,aAAa;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,C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D;;OAEG;IACH,SAAgB,QAAQ,+BAAsC;IAK9D,SAAgB,OAAO,EAAE,WAAW,CAAC;gBAElB,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC;IAMhD;;;OAGG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM;IAK7B;;;;OAIG;IACU,YAAY,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC;IAkBrE;;;;;OAKG;IACH,OAAO,CAAC,aAAa;IASrB;;;OAGG;IACH,OAAO,CAAC,cAAc;IA4EtB;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,iBAAiB;CA8BhC"}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
"use strict";
|
||||
var _RequestManager_token;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.RequestManager = exports.RequestMethod = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const collection_1 = tslib_1.__importDefault(require("@discordjs/collection"));
|
||||
const form_data_1 = tslib_1.__importDefault(require("form-data"));
|
||||
const snowflake_1 = require("@sapphire/snowflake");
|
||||
const events_1 = require("events");
|
||||
const https_1 = require("https");
|
||||
const SequentialHandler_1 = require("./handlers/SequentialHandler");
|
||||
const constants_1 = require("./utils/constants");
|
||||
const agent = new https_1.Agent({ keepAlive: true });
|
||||
/**
|
||||
* Possible API methods to be used when doing requests
|
||||
*/
|
||||
var RequestMethod;
|
||||
(function (RequestMethod) {
|
||||
RequestMethod["Delete"] = "delete";
|
||||
RequestMethod["Get"] = "get";
|
||||
RequestMethod["Patch"] = "patch";
|
||||
RequestMethod["Post"] = "post";
|
||||
RequestMethod["Put"] = "put";
|
||||
})(RequestMethod = exports.RequestMethod || (exports.RequestMethod = {}));
|
||||
/**
|
||||
* Represents the class that manages handlers for endpoints
|
||||
*/
|
||||
class RequestManager extends events_1.EventEmitter {
|
||||
constructor(options) {
|
||||
super();
|
||||
/**
|
||||
* A timeout promise that is set when we hit the global rate limit
|
||||
* @default null
|
||||
*/
|
||||
this.globalTimeout = null;
|
||||
/**
|
||||
* API bucket hashes that are cached from provided routes
|
||||
*/
|
||||
this.hashes = new collection_1.default();
|
||||
/**
|
||||
* Request handlers created from the bucket hash and the major parameters
|
||||
*/
|
||||
this.handlers = new collection_1.default();
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
|
||||
_RequestManager_token.set(this, null);
|
||||
this.options = { ...constants_1.DefaultRestOptions, ...options };
|
||||
this.options.offset = Math.max(0, this.options.offset);
|
||||
}
|
||||
/**
|
||||
* Sets the authorization token that should be used for requests
|
||||
* @param token The authorization token to use
|
||||
*/
|
||||
setToken(token) {
|
||||
tslib_1.__classPrivateFieldSet(this, _RequestManager_token, token, "f");
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Queues a request to be sent
|
||||
* @param request All the information needed to make a request
|
||||
* @returns The response from the api request
|
||||
*/
|
||||
async queueRequest(request) {
|
||||
// Generalize the endpoint to its route data
|
||||
const routeID = RequestManager.generateRouteData(request.fullRoute, request.method);
|
||||
// Get the bucket hash for the generic route, or point to a global route otherwise
|
||||
const hash = this.hashes.get(`${request.method}:${routeID.bucketRoute}`) ?? `Global(${request.method}:${routeID.bucketRoute})`;
|
||||
// Get the request handler for the obtained hash, with its major parameter
|
||||
const handler = this.handlers.get(`${hash}:${routeID.majorParameter}`) ?? this.createHandler(hash, routeID.majorParameter);
|
||||
// Resolve the request into usable fetch/node-fetch options
|
||||
const { url, fetchOptions } = this.resolveRequest(request);
|
||||
// Queue the request
|
||||
return handler.queueRequest(routeID, url, fetchOptions);
|
||||
}
|
||||
/**
|
||||
* Creates a new rate limit handler from a hash, based on the hash and the major parameter
|
||||
* @param hash The hash for the route
|
||||
* @param majorParameter The major parameter for this handler
|
||||
* @private
|
||||
*/
|
||||
createHandler(hash, majorParameter) {
|
||||
// Create the async request queue to handle requests
|
||||
const queue = new SequentialHandler_1.SequentialHandler(this, hash, majorParameter);
|
||||
// Save the queue based on its ID
|
||||
this.handlers.set(queue.id, queue);
|
||||
return queue;
|
||||
}
|
||||
/**
|
||||
* Formats the request data to a usable format for fetch
|
||||
* @param request The request data
|
||||
*/
|
||||
resolveRequest(request) {
|
||||
const { options } = this;
|
||||
let query = '';
|
||||
// If a query option is passed, use it
|
||||
if (request.query) {
|
||||
query = `?${request.query.toString()}`;
|
||||
}
|
||||
// Create the required headers
|
||||
const headers = {
|
||||
'User-Agent': `${constants_1.DefaultUserAgent} ${options.userAgentAppendix}`.trim(),
|
||||
};
|
||||
// If this request requires authorization (allowing non-"authorized" requests for webhooks)
|
||||
if (request.auth !== false) {
|
||||
// If we haven't received a token, throw an error
|
||||
if (!tslib_1.__classPrivateFieldGet(this, _RequestManager_token, "f")) {
|
||||
throw new Error('Expected token to be set for this request, but none was present');
|
||||
}
|
||||
headers.Authorization = `${request.authPrefix ?? 'Bot'} ${tslib_1.__classPrivateFieldGet(this, _RequestManager_token, "f")}`;
|
||||
}
|
||||
// If a reason was set, set it's appropriate header
|
||||
if (request.reason?.length) {
|
||||
headers['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);
|
||||
}
|
||||
// Format the full request URL (api base, optional version, endpoint, optional querystring)
|
||||
const url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${request.fullRoute}${query}`;
|
||||
let finalBody;
|
||||
let additionalHeaders = {};
|
||||
if (request.attachments?.length) {
|
||||
const formData = new form_data_1.default();
|
||||
// Attach all files to the request
|
||||
for (const attachment of request.attachments) {
|
||||
formData.append(attachment.fileName, attachment.rawBuffer, attachment.fileName);
|
||||
}
|
||||
// If a JSON body was added as well, attach it to the form data
|
||||
// eslint-disable-next-line no-eq-null
|
||||
if (request.body != null) {
|
||||
formData.append('payload_json', JSON.stringify(request.body));
|
||||
}
|
||||
// Set the final body to the form data
|
||||
finalBody = formData;
|
||||
// Set the additional headers to the form data ones
|
||||
additionalHeaders = formData.getHeaders();
|
||||
// eslint-disable-next-line no-eq-null
|
||||
}
|
||||
else if (request.body != null) {
|
||||
// Stringify the JSON data
|
||||
finalBody = JSON.stringify(request.body);
|
||||
// Set the additional headers to specify the content-type
|
||||
additionalHeaders = { 'Content-Type': 'application/json' };
|
||||
}
|
||||
const fetchOptions = {
|
||||
agent,
|
||||
body: finalBody,
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
||||
headers: { ...(request.headers ?? {}), ...additionalHeaders, ...headers },
|
||||
method: request.method,
|
||||
};
|
||||
return { url, fetchOptions };
|
||||
}
|
||||
/**
|
||||
* Generates route data for an endpoint:method
|
||||
* @param endpoint The raw endpoint to generalize
|
||||
* @param method The HTTP method this endpoint is called without
|
||||
* @private
|
||||
*/
|
||||
static generateRouteData(endpoint, method) {
|
||||
const majorIDMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint);
|
||||
// Get the major ID for this route - global otherwise
|
||||
const majorID = majorIDMatch?.[1] ?? 'global';
|
||||
const baseRoute = endpoint
|
||||
// Strip out all IDs
|
||||
.replace(/\d{16,19}/g, ':id')
|
||||
// Strip out reaction as they fall under the same bucket
|
||||
.replace(/\/reactions\/(.*)/, '/reactions/:reaction');
|
||||
let exceptions = '';
|
||||
// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)
|
||||
// https://github.com/discord/discord-api-docs/issues/1295
|
||||
if (method === "delete" /* Delete */ && baseRoute === '/channels/:id/messages/:id') {
|
||||
const id = /\d{16,19}$/.exec(endpoint)[0];
|
||||
const snowflake = snowflake_1.DiscordSnowflake.deconstruct(id);
|
||||
if (Date.now() - Number(snowflake.timestamp) > 1000 * 60 * 60 * 24 * 14) {
|
||||
exceptions += '/Delete Old Message';
|
||||
}
|
||||
}
|
||||
return {
|
||||
majorParameter: majorID,
|
||||
bucketRoute: baseRoute + exceptions,
|
||||
original: endpoint,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.RequestManager = RequestManager;
|
||||
_RequestManager_token = new WeakMap();
|
||||
//# sourceMappingURL=RequestManager.js.map
|
||||
+1
@@ -0,0 +1 @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AAE;YAClF,MAAM,EAAE,GAAG,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAE,CAAC,CAAC,CAAC,CAAC;YAC3C,MAAM,SAAS,GAAG,4BAAgB,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;YACnD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;gBACxE,UAAU,IAAI,qBAAqB,CAAC;aACpC;SACD;QAED,OAAO;YACN,cAAc,EAAE,OAAO;YACvB,WAAW,EAAE,SAAS,GAAG,UAAU;YACnC,QAAQ,EAAE,QAAQ;SAClB,CAAC;IACH,CAAC;CACD;AA/LD,wCA+LC"}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
interface DiscordErrorFieldInformation {
|
||||
code: string;
|
||||
message: string;
|
||||
}
|
||||
interface DiscordErrorGroupWrapper {
|
||||
_errors: DiscordError[];
|
||||
}
|
||||
declare type DiscordError = DiscordErrorGroupWrapper | DiscordErrorFieldInformation | {
|
||||
[k: string]: DiscordError;
|
||||
} | string;
|
||||
export interface DiscordErrorData {
|
||||
code: number;
|
||||
message: string;
|
||||
errors?: DiscordError;
|
||||
}
|
||||
/**
|
||||
* Represents an API error returned by Discord
|
||||
* @extends Error
|
||||
*/
|
||||
export declare class DiscordAPIError extends Error {
|
||||
rawError: DiscordErrorData;
|
||||
code: number;
|
||||
status: number;
|
||||
method: string;
|
||||
url: string;
|
||||
/**
|
||||
* @param rawError The error reported by Discord
|
||||
* @param code The error code reported by Discord
|
||||
* @param status The status code of the response
|
||||
* @param method The method of the request that erred
|
||||
* @param url The url of the request that erred
|
||||
*/
|
||||
constructor(rawError: DiscordErrorData, code: number, status: number, method: string, url: string);
|
||||
/**
|
||||
* The name of the error
|
||||
*/
|
||||
get name(): string;
|
||||
private static getMessage;
|
||||
private static flattenDiscordError;
|
||||
}
|
||||
export {};
|
||||
//# sourceMappingURL=DiscordAPIError.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"DiscordAPIError.d.ts","sourceRoot":"./","sources":["lib/errors/DiscordAPIError.ts"],"names":[],"mappings":"AAAA,UAAU,4BAA4B;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,UAAU,wBAAwB;IACjC,OAAO,EAAE,YAAY,EAAE,CAAC;CACxB;AAED,aAAK,YAAY,GAAG,wBAAwB,GAAG,4BAA4B,GAAG;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,YAAY,CAAA;CAAE,GAAG,MAAM,CAAC;AAErH,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,YAAY,CAAC;CACtB;AAUD;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IASjC,QAAQ,EAAE,gBAAgB;IAC1B,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,MAAM;IACd,MAAM,EAAE,MAAM;IACd,GAAG,EAAE,MAAM;IAZnB;;;;;;OAMG;gBAEK,QAAQ,EAAE,gBAAgB,EAC1B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM;IAKnB;;OAEG;IACH,IAAW,IAAI,IAAI,MAAM,CAExB;IAED,OAAO,CAAC,MAAM,CAAC,UAAU;IAUzB,OAAO,CAAC,MAAM,CAAE,mBAAmB;CAmBnC"}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DiscordAPIError = void 0;
|
||||
function isErrorGroupWrapper(error) {
|
||||
return Reflect.has(error, '_errors');
|
||||
}
|
||||
function isErrorResponse(error) {
|
||||
return typeof Reflect.get(error, 'message') === 'string';
|
||||
}
|
||||
/**
|
||||
* Represents an API error returned by Discord
|
||||
* @extends Error
|
||||
*/
|
||||
class DiscordAPIError extends Error {
|
||||
/**
|
||||
* @param rawError The error reported by Discord
|
||||
* @param code The error code reported by Discord
|
||||
* @param status The status code of the response
|
||||
* @param method The method of the request that erred
|
||||
* @param url The url of the request that erred
|
||||
*/
|
||||
constructor(rawError, code, status, method, url) {
|
||||
super(DiscordAPIError.getMessage(rawError));
|
||||
this.rawError = rawError;
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
this.method = method;
|
||||
this.url = url;
|
||||
}
|
||||
/**
|
||||
* The name of the error
|
||||
*/
|
||||
get name() {
|
||||
return `${DiscordAPIError.name}[${this.code}]`;
|
||||
}
|
||||
static getMessage(error) {
|
||||
let flattened = '';
|
||||
if (error.errors) {
|
||||
flattened = [...this.flattenDiscordError(error.errors)].join('\n');
|
||||
}
|
||||
return error.message && flattened
|
||||
? `${error.message}\n${flattened}`
|
||||
: error.message || flattened || 'Unknown Error';
|
||||
}
|
||||
static *flattenDiscordError(obj, key = '') {
|
||||
if (isErrorResponse(obj)) {
|
||||
return yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();
|
||||
}
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
const nextKey = k.startsWith('_') ? key : key ? (Number.isNaN(Number(k)) ? `${key}.${k}` : `${key}[${k}]`) : k;
|
||||
if (typeof v === 'string') {
|
||||
yield v;
|
||||
}
|
||||
else if (isErrorGroupWrapper(v)) {
|
||||
for (const error of v._errors) {
|
||||
yield* this.flattenDiscordError(error, nextKey);
|
||||
}
|
||||
}
|
||||
else {
|
||||
yield* this.flattenDiscordError(v, nextKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.DiscordAPIError = DiscordAPIError;
|
||||
//# sourceMappingURL=DiscordAPIError.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"DiscordAPIError.js","sourceRoot":"./","sources":["lib/errors/DiscordAPIError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D,IAAI,eAAe,CAAC,GAAG,CAAC,EAAE;YACzB,OAAO,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC;SAC5F;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YACzC,MAAM,OAAO,GAAG,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAE/G,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE;gBAC1B,MAAM,CAAC,CAAC;aACR;iBAAM,IAAI,mBAAmB,CAAC,CAAC,CAAC,EAAE;gBAClC,KAAK,MAAM,KAAK,IAAI,CAAC,CAAC,OAAO,EAAE;oBAC9B,KAAK,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;iBAChD;aACD;iBAAM;gBACN,KAAK,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;aAC5C;SACD;IACF,CAAC;CACD;AAtDD,0CAsDC"}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Represents a HTTP error
|
||||
*/
|
||||
export declare class HTTPError extends Error {
|
||||
name: string;
|
||||
status: number;
|
||||
method: string;
|
||||
url: string;
|
||||
/**
|
||||
* @param message The error message
|
||||
* @param name The name of the error
|
||||
* @param status The status code of the response
|
||||
* @param method The method of the request that erred
|
||||
* @param url The url of the request that erred
|
||||
*/
|
||||
constructor(message: string, name: string, status: number, method: string, url: string);
|
||||
}
|
||||
//# sourceMappingURL=HTTPError.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"HTTPError.d.ts","sourceRoot":"./","sources":["lib/errors/HTTPError.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAU3B,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,MAAM;IACd,MAAM,EAAE,MAAM;IACd,GAAG,EAAE,MAAM;IAZnB;;;;;;OAMG;gBAEF,OAAO,EAAE,MAAM,EACR,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM;CAInB"}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.HTTPError = void 0;
|
||||
/**
|
||||
* Represents a HTTP error
|
||||
*/
|
||||
class HTTPError extends Error {
|
||||
/**
|
||||
* @param message The error message
|
||||
* @param name The name of the error
|
||||
* @param status The status code of the response
|
||||
* @param method The method of the request that erred
|
||||
* @param url The url of the request that erred
|
||||
*/
|
||||
constructor(message, name, status, method, url) {
|
||||
super(message);
|
||||
this.name = name;
|
||||
this.status = status;
|
||||
this.method = method;
|
||||
this.url = url;
|
||||
}
|
||||
}
|
||||
exports.HTTPError = HTTPError;
|
||||
//# sourceMappingURL=HTTPError.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"HTTPError.js","sourceRoot":"./","sources":["lib/errors/HTTPError.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,SAAU,SAAQ,KAAK;IACnC;;;;;;OAMG;IACH,YACC,OAAe,EACR,IAAY,EACZ,MAAc,EACd,MAAc,EACd,GAAW;QAElB,KAAK,CAAC,OAAO,CAAC,CAAC;QALR,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;QACd,QAAG,GAAH,GAAG,CAAQ;IAGnB,CAAC;CACD;AAjBD,8BAiBC"}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import type { RequestInit } from 'node-fetch';
|
||||
import type { RouteData } from '../RequestManager';
|
||||
export interface IHandler {
|
||||
queueRequest(routeID: RouteData, url: string, options: RequestInit): Promise<unknown>;
|
||||
}
|
||||
//# sourceMappingURL=IHandler.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"IHandler.d.ts","sourceRoot":"./","sources":["lib/handlers/IHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,MAAM,WAAW,QAAQ;IACxB,YAAY,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACtF"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=IHandler.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"IHandler.js","sourceRoot":"./","sources":["lib/handlers/IHandler.ts"],"names":[],"mappings":""}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { RequestInit } from 'node-fetch';
|
||||
import type { RequestManager, RouteData } from '../RequestManager';
|
||||
/**
|
||||
* The structure used to handle requests for a given bucket
|
||||
*/
|
||||
export declare class SequentialHandler {
|
||||
#private;
|
||||
private readonly manager;
|
||||
private readonly hash;
|
||||
private readonly majorParameter;
|
||||
/**
|
||||
* The unique ID of the handler
|
||||
*/
|
||||
readonly id: string;
|
||||
/**
|
||||
* The time this rate limit bucket will reset
|
||||
*/
|
||||
private reset;
|
||||
/**
|
||||
* The remaining requests that can be made before we are rate limited
|
||||
*/
|
||||
private remaining;
|
||||
/**
|
||||
* The total number of requests that can be made before we are rate limited
|
||||
*/
|
||||
private limit;
|
||||
/**
|
||||
* @param manager The request manager
|
||||
* @param hash The hash that this RequestHandler handles
|
||||
* @param majorParameter The major parameter for this handler
|
||||
*/
|
||||
constructor(manager: RequestManager, hash: string, majorParameter: string);
|
||||
/**
|
||||
* If the bucket is currently inactive (no pending requests)
|
||||
*/
|
||||
get inactive(): boolean;
|
||||
/**
|
||||
* If the rate limit bucket is currently limited
|
||||
*/
|
||||
private get limited();
|
||||
/**
|
||||
* The time until queued requests can continue
|
||||
*/
|
||||
private get timeToReset();
|
||||
/**
|
||||
* Emits a debug message
|
||||
* @param message The message to debug
|
||||
*/
|
||||
private debug;
|
||||
/**
|
||||
* Queues a request to be sent
|
||||
* @param routeID The generalized api route with literal ids for major parameters
|
||||
* @param url The url to do the request on
|
||||
* @param options All the information needed to make a request
|
||||
*/
|
||||
queueRequest(routeID: RouteData, url: string, options: RequestInit): Promise<unknown>;
|
||||
/**
|
||||
* The method that actually makes the request to the api, and updates info about the bucket accordingly
|
||||
* @param routeID The generalized api route with literal ids for major parameters
|
||||
* @param url The fully resolved url to make the request to
|
||||
* @param options The node-fetch options needed to make the request
|
||||
* @param retries The number of retries this request has already attempted (recursion)
|
||||
*/
|
||||
private runRequest;
|
||||
}
|
||||
//# sourceMappingURL=SequentialHandler.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"SequentialHandler.d.ts","sourceRoot":"./","sources":["lib/handlers/SequentialHandler.ts"],"names":[],"mappings":"AAGA,OAAc,EAAE,WAAW,EAAY,MAAM,YAAY,CAAC;AAG1D,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAInE;;GAEG;AACH,qBAAa,iBAAiB;;IAiC5B,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,cAAc;IAlChC;;OAEG;IACH,SAAgB,EAAE,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,OAAO,CAAC,KAAK,CAAM;IAEnB;;OAEG;IACH,OAAO,CAAC,SAAS,CAAK;IAEtB;;OAEG;IACH,OAAO,CAAC,KAAK,CAAY;IAQzB;;;;OAIG;gBAEe,OAAO,EAAE,cAAc,EACvB,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM;IAKxC;;OAEG;IACH,IAAW,QAAQ,IAAI,OAAO,CAE7B;IAED;;OAEG;IACH,OAAO,KAAK,OAAO,GAElB;IAED;;OAEG;IACH,OAAO,KAAK,WAAW,GAEtB;IAED;;;OAGG;IACH,OAAO,CAAC,KAAK;IAIb;;;;;OAKG;IACU,YAAY,CAAC,OAAO,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC;IA6BlG;;;;;;OAMG;YACW,UAAU;CA+FxB"}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
"use strict";
|
||||
var _SequentialHandler_asyncQueue;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SequentialHandler = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
const promises_1 = require("timers/promises");
|
||||
const async_queue_1 = require("@sapphire/async-queue");
|
||||
const abort_controller_1 = tslib_1.__importDefault(require("abort-controller"));
|
||||
const node_fetch_1 = tslib_1.__importDefault(require("node-fetch"));
|
||||
const DiscordAPIError_1 = require("../errors/DiscordAPIError");
|
||||
const HTTPError_1 = require("../errors/HTTPError");
|
||||
require("../utils/constants");
|
||||
const utils_1 = require("../utils/utils");
|
||||
/**
|
||||
* The structure used to handle requests for a given bucket
|
||||
*/
|
||||
class SequentialHandler {
|
||||
/**
|
||||
* @param manager The request manager
|
||||
* @param hash The hash that this RequestHandler handles
|
||||
* @param majorParameter The major parameter for this handler
|
||||
*/
|
||||
constructor(manager, hash, majorParameter) {
|
||||
this.manager = manager;
|
||||
this.hash = hash;
|
||||
this.majorParameter = majorParameter;
|
||||
/**
|
||||
* The time this rate limit bucket will reset
|
||||
*/
|
||||
this.reset = -1;
|
||||
/**
|
||||
* The remaining requests that can be made before we are rate limited
|
||||
*/
|
||||
this.remaining = 1;
|
||||
/**
|
||||
* The total number of requests that can be made before we are rate limited
|
||||
*/
|
||||
this.limit = Infinity;
|
||||
/**
|
||||
* The interface used to sequence async requests sequentially
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
|
||||
_SequentialHandler_asyncQueue.set(this, new async_queue_1.AsyncQueue());
|
||||
this.id = `${hash}:${majorParameter}`;
|
||||
}
|
||||
/**
|
||||
* If the bucket is currently inactive (no pending requests)
|
||||
*/
|
||||
get inactive() {
|
||||
return tslib_1.__classPrivateFieldGet(this, _SequentialHandler_asyncQueue, "f").remaining === 0 && !this.limited;
|
||||
}
|
||||
/**
|
||||
* If the rate limit bucket is currently limited
|
||||
*/
|
||||
get limited() {
|
||||
return this.remaining <= 0 && Date.now() < this.reset;
|
||||
}
|
||||
/**
|
||||
* The time until queued requests can continue
|
||||
*/
|
||||
get timeToReset() {
|
||||
return this.reset - Date.now();
|
||||
}
|
||||
/**
|
||||
* Emits a debug message
|
||||
* @param message The message to debug
|
||||
*/
|
||||
debug(message) {
|
||||
this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`);
|
||||
}
|
||||
/**
|
||||
* Queues a request to be sent
|
||||
* @param routeID The generalized api route with literal ids for major parameters
|
||||
* @param url The url to do the request on
|
||||
* @param options All the information needed to make a request
|
||||
*/
|
||||
async queueRequest(routeID, url, options) {
|
||||
// Wait for any previous requests to be completed before this one is run
|
||||
await tslib_1.__classPrivateFieldGet(this, _SequentialHandler_asyncQueue, "f").wait();
|
||||
try {
|
||||
// Wait for any global rate limits to pass before continuing to process requests
|
||||
await this.manager.globalTimeout;
|
||||
// Check if this request handler is currently rate limited
|
||||
if (this.limited) {
|
||||
// Let library users know they have hit a rate limit
|
||||
this.manager.emit("rateLimited" /* RateLimited */, {
|
||||
timeToReset: this.timeToReset,
|
||||
limit: this.limit,
|
||||
method: options.method,
|
||||
hash: this.hash,
|
||||
route: routeID.bucketRoute,
|
||||
majorParameter: this.majorParameter,
|
||||
});
|
||||
this.debug(`Waiting ${this.timeToReset}ms for rate limit to pass`);
|
||||
// Wait the remaining time left before the rate limit resets
|
||||
await promises_1.setTimeout(this.timeToReset);
|
||||
}
|
||||
// Make the request, and return the results
|
||||
return await this.runRequest(routeID, url, options);
|
||||
}
|
||||
finally {
|
||||
// Allow the next request to fire
|
||||
tslib_1.__classPrivateFieldGet(this, _SequentialHandler_asyncQueue, "f").shift();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The method that actually makes the request to the api, and updates info about the bucket accordingly
|
||||
* @param routeID The generalized api route with literal ids for major parameters
|
||||
* @param url The fully resolved url to make the request to
|
||||
* @param options The node-fetch options needed to make the request
|
||||
* @param retries The number of retries this request has already attempted (recursion)
|
||||
*/
|
||||
async runRequest(routeID, url, options, retries = 0) {
|
||||
const controller = new abort_controller_1.default();
|
||||
const timeout = setTimeout(() => controller.abort(), this.manager.options.timeout);
|
||||
let res;
|
||||
try {
|
||||
res = await node_fetch_1.default(url, { ...options, signal: controller.signal });
|
||||
}
|
||||
catch (error) {
|
||||
const err = error;
|
||||
// Retry the specified number of times for possible timed out requests
|
||||
if (err.name === 'AbortError' && retries !== this.manager.options.retries) {
|
||||
return this.runRequest(routeID, url, options, ++retries);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
let retryAfter = 0;
|
||||
const method = options.method ?? 'get';
|
||||
const limit = res.headers.get('X-RateLimit-Limit');
|
||||
const remaining = res.headers.get('X-RateLimit-Remaining');
|
||||
const reset = res.headers.get('X-RateLimit-Reset-After');
|
||||
const hash = res.headers.get('X-RateLimit-Bucket');
|
||||
const retry = res.headers.get('Retry-After');
|
||||
// Update the total number of requests that can be made before the rate limit resets
|
||||
this.limit = limit ? Number(limit) : Infinity;
|
||||
// Update the number of remaining requests that can be made before the rate limit resets
|
||||
this.remaining = remaining ? Number(remaining) : 1;
|
||||
// Update the time when this rate limit resets (reset-after is in seconds)
|
||||
this.reset = reset ? Number(reset) * 1000 + Date.now() + this.manager.options.offset : Date.now();
|
||||
// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)
|
||||
if (retry)
|
||||
retryAfter = Number(retry) * 1000 + this.manager.options.offset;
|
||||
// Handle buckets via the hash header retroactively
|
||||
if (hash && hash !== this.hash) {
|
||||
// Let library users know when rate limit buckets have been updated
|
||||
this.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\n'));
|
||||
// This queue will eventually be eliminated via attrition
|
||||
this.manager.hashes.set(`${method}:${routeID.bucketRoute}`, hash);
|
||||
}
|
||||
// Handle global rate limit
|
||||
if (res.headers.get('X-RateLimit-Global')) {
|
||||
this.debug(`We are globally rate limited, blocking all requests for ${retryAfter}ms`);
|
||||
// Set the manager's global timeout as the promise for other requests to "wait"
|
||||
this.manager.globalTimeout = promises_1.setTimeout(retryAfter).then(() => {
|
||||
// After the timer is up, clear the promise
|
||||
this.manager.globalTimeout = null;
|
||||
});
|
||||
}
|
||||
if (res.ok) {
|
||||
return utils_1.parseResponse(res);
|
||||
}
|
||||
else if (res.status === 429) {
|
||||
// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited
|
||||
this.debug([
|
||||
'Encountered unexpected 429 rate limit',
|
||||
` Bucket : ${routeID.bucketRoute}`,
|
||||
` Major parameter: ${routeID.majorParameter}`,
|
||||
` Hash : ${this.hash}`,
|
||||
` Retry After : ${retryAfter}ms`,
|
||||
].join('\n'));
|
||||
// Wait the retryAfter amount of time before retrying the request
|
||||
await promises_1.setTimeout(retryAfter);
|
||||
// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter
|
||||
return this.runRequest(routeID, url, options, retries);
|
||||
}
|
||||
else if (res.status >= 500 && res.status < 600) {
|
||||
// Retry the specified number of times for possible server side issues
|
||||
if (retries !== this.manager.options.retries) {
|
||||
return this.runRequest(routeID, url, options, ++retries);
|
||||
}
|
||||
// We are out of retries, throw an error
|
||||
throw new HTTPError_1.HTTPError(res.statusText, res.constructor.name, res.status, method, url);
|
||||
}
|
||||
else {
|
||||
// Handle possible malformed requests
|
||||
if (res.status >= 400 && res.status < 500) {
|
||||
// If we receive this status code, it means the token we had is no longer valid.
|
||||
if (res.status === 401) {
|
||||
this.manager.setToken(null);
|
||||
}
|
||||
// The request will not succeed for some reason, parse the error returned from the api
|
||||
const data = (await utils_1.parseResponse(res));
|
||||
// throw the API error
|
||||
throw new DiscordAPIError_1.DiscordAPIError(data, data.code, res.status, method, url);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.SequentialHandler = SequentialHandler;
|
||||
_SequentialHandler_asyncQueue = new WeakMap();
|
||||
//# sourceMappingURL=SequentialHandler.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"SequentialHandler.js","sourceRoot":"./","sources":["lib/handlers/SequentialHandler.ts"],"names":[],"mappings":";;;;;AAAA,8CAAsD;AACtD,uDAAmD;AACnD,gFAA+C;AAC/C,oEAA0D;AAC1D,+DAA8E;AAC9E,mDAAgD;AAEhD,8BAAgD;AAChD,0CAA+C;AAE/C;;GAEG;AACH,MAAa,iBAAiB;IA2B7B;;;;OAIG;IACH,YACkB,OAAuB,EACvB,IAAY,EACZ,cAAsB;QAFtB,YAAO,GAAP,OAAO,CAAgB;QACvB,SAAI,GAAJ,IAAI,CAAQ;QACZ,mBAAc,GAAd,cAAc,CAAQ;QA7BxC;;WAEG;QACK,UAAK,GAAG,CAAC,CAAC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,OAAO,CAAC,CAAC;SACvD;aAAM,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;YACjD,sEAAsE;YACtE,IAAI,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE;gBAC7C,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,OAAO,CAAC,CAAC;aACzD;YACD,wCAAwC;YACxC,MAAM,IAAI,qBAAS,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,CAALine truncated
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import type { RESTOptions } from '../REST';
|
||||
export declare const DefaultUserAgent: string;
|
||||
export declare const DefaultRestOptions: Required<RESTOptions>;
|
||||
/**
|
||||
* The events that the REST manager emits
|
||||
*/
|
||||
export declare const enum RESTEvents {
|
||||
Debug = "restDebug",
|
||||
RateLimited = "rateLimited"
|
||||
}
|
||||
export declare const ALLOWED_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif"];
|
||||
export declare const ALLOWED_SIZES: readonly [16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
|
||||
export declare type ImageExtension = typeof ALLOWED_EXTENSIONS[number];
|
||||
export declare type ImageSize = typeof ALLOWED_SIZES[number];
|
||||
//# sourceMappingURL=constants.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"constants.d.ts","sourceRoot":"./","sources":["lib/utils/constants.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAK3C,eAAO,MAAM,gBAAgB,QAAyD,CAAC;AAEvF,eAAO,MAAM,kBAAkB,EAAE,QAAQ,CAAC,WAAW,CAQpD,CAAC;AAEF;;GAEG;AACH,0BAAkB,UAAU;IAC3B,KAAK,cAAc;IACnB,WAAW,gBAAgB;CAC3B;AAED,eAAO,MAAM,kBAAkB,gDAAiD,CAAC;AACjF,eAAO,MAAM,aAAa,wDAAyD,CAAC;AAEpF,oBAAY,cAAc,GAAG,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAC;AAC/D,oBAAY,SAAS,GAAG,OAAO,aAAa,CAAC,MAAM,CAAC,CAAC"}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ALLOWED_SIZES = exports.ALLOWED_EXTENSIONS = exports.RESTEvents = exports.DefaultRestOptions = exports.DefaultUserAgent = void 0;
|
||||
const v8_1 = require("discord-api-types/v8");
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
|
||||
const Package = require('../../../package.json');
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
exports.DefaultUserAgent = `DiscordBot (${Package.homepage}, ${Package.version})`;
|
||||
exports.DefaultRestOptions = {
|
||||
api: 'https://discord.com/api',
|
||||
cdn: 'https://cdn.discordapp.com',
|
||||
offset: 50,
|
||||
retries: 3,
|
||||
timeout: 15000,
|
||||
userAgentAppendix: `Node.js ${process.version}`,
|
||||
version: v8_1.APIVersion,
|
||||
};
|
||||
/**
|
||||
* The events that the REST manager emits
|
||||
*/
|
||||
var RESTEvents;
|
||||
(function (RESTEvents) {
|
||||
RESTEvents["Debug"] = "restDebug";
|
||||
RESTEvents["RateLimited"] = "rateLimited";
|
||||
})(RESTEvents = exports.RESTEvents || (exports.RESTEvents = {}));
|
||||
exports.ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'];
|
||||
exports.ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096];
|
||||
//# sourceMappingURL=constants.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"constants.js","sourceRoot":"./","sources":["lib/utils/constants.ts"],"names":[],"mappings":";;;AAAA,6CAAkD;AAElD,qGAAqG;AACrG,MAAM,OAAO,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;AAEjD,4EAA4E;AAC/D,QAAA,gBAAgB,GAAG,eAAe,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,OAAO,GAAG,CAAC;AAE1E,QAAA,kBAAkB,GAA0B;IACxD,GAAG,EAAE,yBAAyB;IAC9B,GAAG,EAAE,4BAA4B;IACjC,MAAM,EAAE,EAAE;IACV,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,KAAM;IACf,iBAAiB,EAAE,WAAW,OAAO,CAAC,OAAO,EAAE;IAC/C,OAAO,EAAE,eAAU;CACnB,CAAC;AAEF;;GAEG;AACH,IAAkB,UAGjB;AAHD,WAAkB,UAAU;IAC3B,iCAAmB,CAAA;IACnB,yCAA2B,CAAA;AAC5B,CAAC,EAHiB,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAG3B;AAEY,QAAA,kBAAkB,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAU,CAAC;AACpE,QAAA,aAAa,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAU,CAAC"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { Response } from 'node-fetch';
|
||||
/**
|
||||
* Converts the response to usable data
|
||||
* @param res The node-fetch response
|
||||
*/
|
||||
export declare function parseResponse(res: Response): Promise<unknown>;
|
||||
//# sourceMappingURL=utils.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"utils.d.ts","sourceRoot":"./","sources":["lib/utils/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C;;;GAGG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAM7D"}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.parseResponse = void 0;
|
||||
/**
|
||||
* Converts the response to usable data
|
||||
* @param res The node-fetch response
|
||||
*/
|
||||
function parseResponse(res) {
|
||||
if (res.headers.get('Content-Type')?.startsWith('application/json')) {
|
||||
return res.json();
|
||||
}
|
||||
return res.buffer();
|
||||
}
|
||||
exports.parseResponse = parseResponse;
|
||||
//# sourceMappingURL=utils.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"utils.js","sourceRoot":"./","sources":["lib/utils/utils.ts"],"names":[],"mappings":";;;AAEA;;;GAGG;AACH,SAAgB,aAAa,CAAC,GAAa;IAC1C,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,UAAU,CAAC,kBAAkB,CAAC,EAAE;QACpE,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;KAClB;IAED,OAAO,GAAG,CAAC,MAAM,EAAE,CAAC;AACrB,CAAC;AAND,sCAMC"}
|
||||
Reference in new issue
Block a user