From ac8cab8967685204a7d7779dda38f233c12687eb Mon Sep 17 00:00:00 2001 From: iCrawl Date: Tue, 5 Sep 2017 19:39:05 +0200 Subject: [PATCH] Cleanup webpack --- discord.11.0.0.js | 23084 ------------------ discord.11.0.0.min.js | 20 - discord.11.1-dev-datastores.js | 27017 --------------------- discord.11.1-dev-datastores.min.js | 1 - discord.11.1-dev.min.js | 1 - discord.11.1.0.js | 26070 -------------------- discord.11.1.0.min.js | 1 - discord.11.2.0.js | 4 +- discord.11.2.0.min.js | 2 +- discord.11.1-dev.js => discord.11.2.1.js | 4 +- discord.11.2.1.min.js | 1 + discord.data-store-refactor-11.2.js | 26756 -------------------- discord.data-store-refactor-11.2.min.js | 1 - discord.data-store-refactor.js | 26756 -------------------- discord.data-store-refactor.min.js | 1 - discord.stable.js | 2 +- discord.stable.min.js | 2 +- 17 files changed, 8 insertions(+), 129715 deletions(-) delete mode 100644 discord.11.0.0.js delete mode 100644 discord.11.0.0.min.js delete mode 100644 discord.11.1-dev-datastores.js delete mode 100644 discord.11.1-dev-datastores.min.js delete mode 100644 discord.11.1-dev.min.js delete mode 100644 discord.11.1.0.js delete mode 100644 discord.11.1.0.min.js rename discord.11.1-dev.js => discord.11.2.1.js (99%) create mode 100644 discord.11.2.1.min.js delete mode 100644 discord.data-store-refactor-11.2.js delete mode 100644 discord.data-store-refactor-11.2.min.js delete mode 100644 discord.data-store-refactor.js delete mode 100644 discord.data-store-refactor.min.js diff --git a/discord.11.0.0.js b/discord.11.0.0.js deleted file mode 100644 index 70840e72..00000000 --- a/discord.11.0.0.js +++ /dev/null @@ -1,23084 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.l = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // identity function for calling harmony imports with the correct context -/******/ __webpack_require__.i = function(value) { return value; }; - -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); -/******/ } -/******/ }; - -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; - -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 57); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process) {exports.Package = __webpack_require__(27); - -/** - * Options for a Client. - * @typedef {Object} ClientOptions - * @property {string} [apiRequestMethod='sequential'] 'sequential' or 'burst'. Sequential executes all requests in - * the order they are triggered, whereas burst runs multiple at a time, and doesn't guarantee a particular order. - * @property {number} [shardId=0] The ID of this shard - * @property {number} [shardCount=0] The number of shards - * @property {number} [messageCacheMaxSize=200] Maximum number of messages to cache per channel - * (-1 or Infinity for unlimited - don't do this without message sweeping, otherwise memory usage will climb - * indefinitely) - * @property {number} [messageCacheLifetime=0] How long until a message should be uncached by the message sweeping - * (in seconds, 0 for forever) - * @property {number} [messageSweepInterval=0] How frequently to remove messages from the cache that are older than - * the message cache lifetime (in seconds, 0 for never) - * @property {boolean} [fetchAllMembers=false] Whether to cache all guild members and users upon startup, as well as - * upon joining a guild - * @property {boolean} [disableEveryone=false] Default value for MessageOptions.disableEveryone - * @property {boolean} [sync=false] Whether to periodically sync guilds (for userbots) - * @property {number} [restWsBridgeTimeout=5000] Maximum time permitted between REST responses and their - * corresponding websocket events - * @property {number} [restTimeOffset=500] The extra time in millseconds to wait before continuing to make REST - * requests (higher values will reduce rate-limiting errors on bad connections) - * @property {WSEventType[]} [disabledEvents] An array of disabled websocket events. Events in this array will not be - * processed, potentially resulting in performance improvements for larger bots. Only disable events you are - * 100% certain you don't need, as many are important, but not obviously so. The safest one to disable with the - * most impact is typically `TYPING_START`. - * @property {WebsocketOptions} [ws] Options for the websocket - */ -exports.DefaultOptions = { - apiRequestMethod: 'sequential', - shardId: 0, - shardCount: 0, - messageCacheMaxSize: 200, - messageCacheLifetime: 0, - messageSweepInterval: 0, - fetchAllMembers: false, - disableEveryone: false, - sync: false, - restWsBridgeTimeout: 5000, - disabledEvents: [], - restTimeOffset: 500, - - /** - * Websocket options. These are left as snake_case to match the API. - * @typedef {Object} WebsocketOptions - * @property {number} [large_threshold=250] Number of members in a guild to be considered large - * @property {boolean} [compress=true] Whether to compress data sent on the connection. - * Defaults to `false` for browsers. - */ - ws: { - large_threshold: 250, - compress: typeof window === 'undefined', - properties: { - $os: process ? process.platform : 'discord.js', - $browser: 'discord.js', - $device: 'discord.js', - $referrer: '', - $referring_domain: '', - }, - }, -}; - -exports.Errors = { - NO_TOKEN: 'Request to use token, but token was unavailable to the client.', - NO_BOT_ACCOUNT: 'Only bot accounts are able to make use of this feature.', - NO_USER_ACCOUNT: 'Only user accounts are able to make use of this feature.', - BAD_WS_MESSAGE: 'A bad message was received from the websocket; either bad compression, or not JSON.', - TOOK_TOO_LONG: 'Something took too long to do.', - NOT_A_PERMISSION: 'Invalid permission string or number.', - INVALID_RATE_LIMIT_METHOD: 'Unknown rate limiting method.', - BAD_LOGIN: 'Incorrect login details were provided.', - INVALID_SHARD: 'Invalid shard settings were provided.', - INVALID_TOKEN: 'An invalid token was provided.', -}; - -const PROTOCOL_VERSION = exports.PROTOCOL_VERSION = 6; -const HOST = exports.HOST = `https://discordapp.com`; -const API = exports.API = `${HOST}/api/v${PROTOCOL_VERSION}`; -const Endpoints = exports.Endpoints = { - // general - login: `${API}/auth/login`, - logout: `${API}/auth/logout`, - gateway: `${API}/gateway`, - botGateway: `${API}/gateway/bot`, - invite: (id) => `${API}/invite/${id}`, - inviteLink: (id) => `https://discord.gg/${id}`, - assets: (asset) => `${HOST}/assets/${asset}`, - CDN: 'https://cdn.discordapp.com', - - // users - user: (userID) => `${API}/users/${userID}`, - userChannels: (userID) => `${Endpoints.user(userID)}/channels`, - userProfile: (userID) => `${Endpoints.user(userID)}/profile`, - avatar: (userID, avatar) => { - if (userID === '1') return avatar; - return `${Endpoints.CDN}/avatars/${userID}/${avatar}.${avatar.startsWith('a_') ? 'gif' : 'jpg'}?size=1024`; - }, - me: `${API}/users/@me`, - meGuild: (guildID) => `${Endpoints.me}/guilds/${guildID}`, - meMentions: (limit, roles, everyone, guildID) => - `users/@me/mentions?limit=${limit}&roles=${roles}&everyone=${everyone}${guildID ? `&guild_id=${guildID}` : ''}`, - relationships: (userID) => `${Endpoints.user(userID)}/relationships`, - note: (userID) => `${Endpoints.me}/notes/${userID}`, - - // guilds - guilds: `${API}/guilds`, - guild: (guildID) => `${Endpoints.guilds}/${guildID}`, - guildIcon: (guildID, hash) => `${Endpoints.CDN}/icons/${guildID}/${hash}.jpg`, - guildSplash: (guildID, hash) => `${Endpoints.CDN}/splashes/${guildID}/${hash}.jpg`, - guildPrune: (guildID) => `${Endpoints.guild(guildID)}/prune`, - guildEmbed: (guildID) => `${Endpoints.guild(guildID)}/embed`, - guildInvites: (guildID) => `${Endpoints.guild(guildID)}/invites`, - guildRoles: (guildID) => `${Endpoints.guild(guildID)}/roles`, - guildRole: (guildID, roleID) => `${Endpoints.guildRoles(guildID)}/${roleID}`, - guildBans: (guildID) => `${Endpoints.guild(guildID)}/bans`, - guildIntegrations: (guildID) => `${Endpoints.guild(guildID)}/integrations`, - guildMembers: (guildID) => `${Endpoints.guild(guildID)}/members`, - guildMember: (guildID, memberID) => `${Endpoints.guildMembers(guildID)}/${memberID}`, - guildMemberRole: (guildID, memberID, roleID) => `${Endpoints.guildMember(guildID, memberID)}/roles/${roleID}`, - guildMemberNickname: (guildID) => `${Endpoints.guildMember(guildID, '@me')}/nick`, - guildChannels: (guildID) => `${Endpoints.guild(guildID)}/channels`, - guildEmojis: (guildID) => `${Endpoints.guild(guildID)}/emojis`, - - // channels - channels: `${API}/channels`, - channel: (channelID) => `${Endpoints.channels}/${channelID}`, - channelMessages: (channelID) => `${Endpoints.channel(channelID)}/messages`, - channelInvites: (channelID) => `${Endpoints.channel(channelID)}/invites`, - channelTyping: (channelID) => `${Endpoints.channel(channelID)}/typing`, - channelPermissions: (channelID) => `${Endpoints.channel(channelID)}/permissions`, - channelMessage: (channelID, messageID) => `${Endpoints.channelMessages(channelID)}/${messageID}`, - channelWebhooks: (channelID) => `${Endpoints.channel(channelID)}/webhooks`, - - // message reactions - messageReactions: (channelID, messageID) => `${Endpoints.channelMessage(channelID, messageID)}/reactions`, - messageReaction: - (channel, msg, emoji, limit) => - `${Endpoints.messageReactions(channel, msg)}/${emoji}` + - `${limit ? `?limit=${limit}` : ''}`, - selfMessageReaction: (channel, msg, emoji, limit) => - `${Endpoints.messageReaction(channel, msg, emoji, limit)}/@me`, - userMessageReaction: (channel, msg, emoji, limit, id) => - `${Endpoints.messageReaction(channel, msg, emoji, limit)}/${id}`, - - // webhooks - webhook: (webhookID, token) => `${API}/webhooks/${webhookID}${token ? `/${token}` : ''}`, - - // oauth - myApplication: `${API}/oauth2/applications/@me`, - getApp: (id) => `${API}/oauth2/authorize?client_id=${id}`, - - // emoji - emoji: (emojiID) => `${Endpoints.CDN}/emojis/${emojiID}.png`, -}; - -exports.Status = { - READY: 0, - CONNECTING: 1, - RECONNECTING: 2, - IDLE: 3, - NEARLY: 4, - DISCONNECTED: 5, -}; - -exports.ChannelTypes = { - text: 0, - DM: 1, - voice: 2, - groupDM: 3, -}; - -exports.OPCodes = { - DISPATCH: 0, - HEARTBEAT: 1, - IDENTIFY: 2, - STATUS_UPDATE: 3, - VOICE_STATE_UPDATE: 4, - VOICE_GUILD_PING: 5, - RESUME: 6, - RECONNECT: 7, - REQUEST_GUILD_MEMBERS: 8, - INVALID_SESSION: 9, - HELLO: 10, - HEARTBEAT_ACK: 11, -}; - -exports.VoiceOPCodes = { - IDENTIFY: 0, - SELECT_PROTOCOL: 1, - READY: 2, - HEARTBEAT: 3, - SESSION_DESCRIPTION: 4, - SPEAKING: 5, -}; - -exports.Events = { - READY: 'ready', - GUILD_CREATE: 'guildCreate', - GUILD_DELETE: 'guildDelete', - GUILD_UPDATE: 'guildUpdate', - GUILD_UNAVAILABLE: 'guildUnavailable', - GUILD_AVAILABLE: 'guildAvailable', - GUILD_MEMBER_ADD: 'guildMemberAdd', - GUILD_MEMBER_REMOVE: 'guildMemberRemove', - GUILD_MEMBER_UPDATE: 'guildMemberUpdate', - GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable', - GUILD_MEMBER_SPEAKING: 'guildMemberSpeaking', - GUILD_MEMBERS_CHUNK: 'guildMembersChunk', - GUILD_ROLE_CREATE: 'roleCreate', - GUILD_ROLE_DELETE: 'roleDelete', - GUILD_ROLE_UPDATE: 'roleUpdate', - GUILD_EMOJI_CREATE: 'emojiCreate', - GUILD_EMOJI_DELETE: 'emojiDelete', - GUILD_EMOJI_UPDATE: 'emojiUpdate', - GUILD_BAN_ADD: 'guildBanAdd', - GUILD_BAN_REMOVE: 'guildBanRemove', - CHANNEL_CREATE: 'channelCreate', - CHANNEL_DELETE: 'channelDelete', - CHANNEL_UPDATE: 'channelUpdate', - CHANNEL_PINS_UPDATE: 'channelPinsUpdate', - MESSAGE_CREATE: 'message', - MESSAGE_DELETE: 'messageDelete', - MESSAGE_UPDATE: 'messageUpdate', - MESSAGE_BULK_DELETE: 'messageDeleteBulk', - MESSAGE_REACTION_ADD: 'messageReactionAdd', - MESSAGE_REACTION_REMOVE: 'messageReactionRemove', - MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll', - USER_UPDATE: 'userUpdate', - USER_NOTE_UPDATE: 'userNoteUpdate', - PRESENCE_UPDATE: 'presenceUpdate', - VOICE_STATE_UPDATE: 'voiceStateUpdate', - TYPING_START: 'typingStart', - TYPING_STOP: 'typingStop', - DISCONNECT: 'disconnect', - RECONNECTING: 'reconnecting', - ERROR: 'error', - WARN: 'warn', - DEBUG: 'debug', -}; - -/** - * The type of a websocket message event, e.g. `MESSAGE_CREATE`. Here are the available events: - * - READY - * - GUILD_SYNC - * - GUILD_CREATE - * - GUILD_DELETE - * - GUILD_UPDATE - * - GUILD_MEMBER_ADD - * - GUILD_MEMBER_REMOVE - * - GUILD_MEMBER_UPDATE - * - GUILD_MEMBERS_CHUNK - * - GUILD_ROLE_CREATE - * - GUILD_ROLE_DELETE - * - GUILD_ROLE_UPDATE - * - GUILD_BAN_ADD - * - GUILD_BAN_REMOVE - * - CHANNEL_CREATE - * - CHANNEL_DELETE - * - CHANNEL_UPDATE - * - CHANNEL_PINS_UPDATE - * - MESSAGE_CREATE - * - MESSAGE_DELETE - * - MESSAGE_UPDATE - * - MESSAGE_DELETE_BULK - * - MESSAGE_REACTION_ADD - * - MESSAGE_REACTION_REMOVE - * - MESSAGE_REACTION_REMOVE_ALL - * - USER_UPDATE - * - USER_NOTE_UPDATE - * - PRESENCE_UPDATE - * - VOICE_STATE_UPDATE - * - TYPING_START - * - VOICE_SERVER_UPDATE - * - RELATIONSHIP_ADD - * - RELATIONSHIP_REMOVE - * @typedef {string} WSEventType - */ -exports.WSEvents = { - READY: 'READY', - GUILD_SYNC: 'GUILD_SYNC', - GUILD_CREATE: 'GUILD_CREATE', - GUILD_DELETE: 'GUILD_DELETE', - GUILD_UPDATE: 'GUILD_UPDATE', - GUILD_MEMBER_ADD: 'GUILD_MEMBER_ADD', - GUILD_MEMBER_REMOVE: 'GUILD_MEMBER_REMOVE', - GUILD_MEMBER_UPDATE: 'GUILD_MEMBER_UPDATE', - GUILD_MEMBERS_CHUNK: 'GUILD_MEMBERS_CHUNK', - GUILD_ROLE_CREATE: 'GUILD_ROLE_CREATE', - GUILD_ROLE_DELETE: 'GUILD_ROLE_DELETE', - GUILD_ROLE_UPDATE: 'GUILD_ROLE_UPDATE', - GUILD_BAN_ADD: 'GUILD_BAN_ADD', - GUILD_BAN_REMOVE: 'GUILD_BAN_REMOVE', - GUILD_EMOJIS_UPDATE: 'GUILD_EMOJIS_UPDATE', - CHANNEL_CREATE: 'CHANNEL_CREATE', - CHANNEL_DELETE: 'CHANNEL_DELETE', - CHANNEL_UPDATE: 'CHANNEL_UPDATE', - CHANNEL_PINS_UPDATE: 'CHANNEL_PINS_UPDATE', - MESSAGE_CREATE: 'MESSAGE_CREATE', - MESSAGE_DELETE: 'MESSAGE_DELETE', - MESSAGE_UPDATE: 'MESSAGE_UPDATE', - MESSAGE_DELETE_BULK: 'MESSAGE_DELETE_BULK', - MESSAGE_REACTION_ADD: 'MESSAGE_REACTION_ADD', - MESSAGE_REACTION_REMOVE: 'MESSAGE_REACTION_REMOVE', - MESSAGE_REACTION_REMOVE_ALL: 'MESSAGE_REACTION_REMOVE_ALL', - USER_UPDATE: 'USER_UPDATE', - USER_NOTE_UPDATE: 'USER_NOTE_UPDATE', - PRESENCE_UPDATE: 'PRESENCE_UPDATE', - VOICE_STATE_UPDATE: 'VOICE_STATE_UPDATE', - TYPING_START: 'TYPING_START', - VOICE_SERVER_UPDATE: 'VOICE_SERVER_UPDATE', - RELATIONSHIP_ADD: 'RELATIONSHIP_ADD', - RELATIONSHIP_REMOVE: 'RELATIONSHIP_REMOVE', -}; - -exports.MessageTypes = { - 0: 'DEFAULT', - 1: 'RECIPIENT_ADD', - 2: 'RECIPIENT_REMOVE', - 3: 'CALL', - 4: 'CHANNEL_NAME_CHANGE', - 5: 'CHANNEL_ICON_CHANGE', - 6: 'PINS_ADD', -}; - -exports.DefaultAvatars = { - BLURPLE: '6debd47ed13483642cf09e832ed0bc1b', - GREY: '322c936a8c8be1b803cd94861bdfa868', - GREEN: 'dd4dbc0016779df1378e7812eabaa04d', - ORANGE: '0e291f67c9274a1abdddeb3fd919cbaa', - RED: '1cbd08c76f8af6dddce02c5138971129', -}; - -const PermissionFlags = exports.PermissionFlags = { - CREATE_INSTANT_INVITE: 1 << 0, - KICK_MEMBERS: 1 << 1, - BAN_MEMBERS: 1 << 2, - ADMINISTRATOR: 1 << 3, - MANAGE_CHANNELS: 1 << 4, - MANAGE_GUILD: 1 << 5, - ADD_REACTIONS: 1 << 6, - - READ_MESSAGES: 1 << 10, - SEND_MESSAGES: 1 << 11, - SEND_TTS_MESSAGES: 1 << 12, - MANAGE_MESSAGES: 1 << 13, - EMBED_LINKS: 1 << 14, - ATTACH_FILES: 1 << 15, - READ_MESSAGE_HISTORY: 1 << 16, - MENTION_EVERYONE: 1 << 17, - EXTERNAL_EMOJIS: 1 << 18, - - CONNECT: 1 << 20, - SPEAK: 1 << 21, - MUTE_MEMBERS: 1 << 22, - DEAFEN_MEMBERS: 1 << 23, - MOVE_MEMBERS: 1 << 24, - USE_VAD: 1 << 25, - - CHANGE_NICKNAME: 1 << 26, - MANAGE_NICKNAMES: 1 << 27, - MANAGE_ROLES_OR_PERMISSIONS: 1 << 28, - MANAGE_WEBHOOKS: 1 << 29, - MANAGE_EMOJIS: 1 << 30, -}; - -let _ALL_PERMISSIONS = 0; -for (const key in PermissionFlags) _ALL_PERMISSIONS |= PermissionFlags[key]; -exports.ALL_PERMISSIONS = _ALL_PERMISSIONS; -exports.DEFAULT_PERMISSIONS = 104324097; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24))) - -/***/ }, -/* 1 */ -/***/ function(module, exports) { - -class AbstractHandler { - constructor(packetManager) { - this.packetManager = packetManager; - } - - handle(packet) { - return packet; - } -} - -module.exports = AbstractHandler; - - -/***/ }, -/* 2 */ -/***/ function(module, exports) { - -/* - -ABOUT ACTIONS - -Actions are similar to WebSocket Packet Handlers, but since introducing -the REST API methods, in order to prevent rewriting code to handle data, -"actions" have been introduced. They're basically what Packet Handlers -used to be but they're strictly for manipulating data and making sure -that WebSocket events don't clash with REST methods. - -*/ - -class GenericAction { - constructor(client) { - this.client = client; - } - - handle(data) { - return data; - } -} - -module.exports = GenericAction; - - -/***/ }, -/* 3 */ -/***/ function(module, exports) { - -/** - * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has - * an ID, for significantly improved performance and ease-of-use. - * @extends {Map} - */ -class Collection extends Map { - constructor(iterable) { - super(iterable); - - /** - * Cached array for the `array()` method - will be reset to `null` whenever `set()` or `delete()` are called. - * @type {?Array} - * @private - */ - this._array = null; - - /** - * Cached array for the `keyArray()` method - will be reset to `null` whenever `set()` or `delete()` are called. - * @type {?Array} - * @private - */ - this._keyArray = null; - } - - set(key, val) { - this._array = null; - this._keyArray = null; - return super.set(key, val); - } - - delete(key) { - this._array = null; - this._keyArray = null; - return super.delete(key); - } - - /** - * Creates an ordered array of the values of this collection, and caches it internally. The array will only be - * reconstructed if an item is added to or removed from the collection, or if you change the length of the array - * itself. If you don't want this caching behaviour, use `Array.from(collection.values())` instead. - * @returns {Array} - */ - array() { - if (!this._array || this._array.length !== this.size) this._array = Array.from(this.values()); - return this._array; - } - - /** - * Creates an ordered array of the keys of this collection, and caches it internally. The array will only be - * reconstructed if an item is added to or removed from the collection, or if you change the length of the array - * itself. If you don't want this caching behaviour, use `Array.from(collection.keys())` instead. - * @returns {Array} - */ - keyArray() { - if (!this._keyArray || this._keyArray.length !== this.size) this._keyArray = Array.from(this.keys()); - return this._keyArray; - } - - /** - * Obtains the first item in this collection. - * @returns {*} - */ - first() { - return this.values().next().value; - } - - /** - * Obtains the first key in this collection. - * @returns {*} - */ - firstKey() { - return this.keys().next().value; - } - - /** - * Obtains the last item in this collection. This relies on the `array()` method, and thus the caching mechanism - * applies here as well. - * @returns {*} - */ - last() { - const arr = this.array(); - return arr[arr.length - 1]; - } - - /** - * Obtains the last key in this collection. This relies on the `keyArray()` method, and thus the caching mechanism - * applies here as well. - * @returns {*} - */ - lastKey() { - const arr = this.keyArray(); - return arr[arr.length - 1]; - } - - /** - * Obtains a random item from this collection. This relies on the `array()` method, and thus the caching mechanism - * applies here as well. - * @returns {*} - */ - random() { - const arr = this.array(); - return arr[Math.floor(Math.random() * arr.length)]; - } - - /** - * Obtains a random key from this collection. This relies on the `keyArray()` method, and thus the caching mechanism - * applies here as well. - * @returns {*} - */ - randomKey() { - const arr = this.keyArray(); - return arr[Math.floor(Math.random() * arr.length)]; - } - - /** - * Searches for all items where their specified property's value is identical to the given value - * (`item[prop] === value`). - * @param {string} prop The property to test against - * @param {*} value The expected value - * @returns {Array} - * @example - * collection.findAll('username', 'Bob'); - */ - findAll(prop, value) { - if (typeof prop !== 'string') throw new TypeError('Key must be a string.'); - if (typeof value === 'undefined') throw new Error('Value must be specified.'); - const results = []; - for (const item of this.values()) { - if (item[prop] === value) results.push(item); - } - return results; - } - - /** - * Searches for a single item where its specified property's value is identical to the given value - * (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is identical to - * [Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). - * Do not use this to obtain an item by its ID. Instead, use `collection.get(id)`. See - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get) for details. - * @param {string|Function} propOrFn The property to test against, or the function to test with - * @param {*} [value] The expected value - only applicable and required if using a property for the first argument - * @returns {*} - * @example - * collection.find('username', 'Bob'); - * @example - * collection.find(val => val.username === 'Bob'); - */ - find(propOrFn, value) { - if (typeof propOrFn === 'string') { - if (typeof value === 'undefined') throw new Error('Value must be specified.'); - if (propOrFn === 'id') throw new RangeError('Don\'t use .find() with IDs. Instead, use .get(id).'); - for (const item of this.values()) { - if (item[propOrFn] === value) return item; - } - return null; - } else if (typeof propOrFn === 'function') { - for (const [key, val] of this) { - if (propOrFn(val, key, this)) return val; - } - return null; - } else { - throw new Error('First argument must be a property string or a function.'); - } - } - - /* eslint-disable max-len */ - /** - * Searches for the key of a single item where its specified property's value is identical to the given value - * (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is identical to - * [Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex). - * @param {string|Function} propOrFn The property to test against, or the function to test with - * @param {*} [value] The expected value - only applicable and required if using a property for the first argument - * @returns {*} - * @example - * collection.findKey('username', 'Bob'); - * @example - * collection.findKey(val => val.username === 'Bob'); - */ - /* eslint-enable max-len */ - findKey(propOrFn, value) { - if (typeof propOrFn === 'string') { - if (typeof value === 'undefined') throw new Error('Value must be specified.'); - for (const [key, val] of this) { - if (val[propOrFn] === value) return key; - } - return null; - } else if (typeof propOrFn === 'function') { - for (const [key, val] of this) { - if (propOrFn(val, key, this)) return key; - } - return null; - } else { - throw new Error('First argument must be a property string or a function.'); - } - } - - /** - * Searches for the existence of a single item where its specified property's value is identical to the given value - * (`item[prop] === value`). - * Do not use this to check for an item by its ID. Instead, use `collection.has(id)`. See - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has) for details. - * @param {string} prop The property to test against - * @param {*} value The expected value - * @returns {boolean} - * @example - * if (collection.exists('username', 'Bob')) { - * console.log('user here!'); - * } - */ - exists(prop, value) { - if (prop === 'id') throw new RangeError('Don\'t use .exists() with IDs. Instead, use .has(id).'); - return Boolean(this.find(prop, value)); - } - - /** - * Identical to - * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), - * but returns a Collection instead of an Array. - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {Collection} - */ - filter(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - const results = new Collection(); - for (const [key, val] of this) { - if (fn(val, key, this)) results.set(key, val); - } - return results; - } - - /** - * Identical to - * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {Array} - */ - filterArray(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - const results = []; - for (const [key, val] of this) { - if (fn(val, key, this)) results.push(val); - } - return results; - } - - /** - * Identical to - * [Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). - * @param {Function} fn Function that produces an element of the new array, taking three arguments - * @param {*} [thisArg] Value to use as `this` when executing function - * @returns {Array} - */ - map(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - const arr = new Array(this.size); - let i = 0; - for (const [key, val] of this) arr[i++] = fn(val, key, this); - return arr; - } - - /** - * Identical to - * [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some). - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {boolean} - */ - some(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - for (const [key, val] of this) { - if (fn(val, key, this)) return true; - } - return false; - } - - /** - * Identical to - * [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {boolean} - */ - every(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - for (const [key, val] of this) { - if (!fn(val, key, this)) return false; - } - return true; - } - - /** - * Identical to - * [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). - * @param {Function} fn Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, - * and `collection` - * @param {*} [initialValue] Starting value for the accumulator - * @returns {*} - */ - reduce(fn, initialValue) { - let accumulator; - if (typeof initialValue !== 'undefined') { - accumulator = initialValue; - for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); - } else { - let first = true; - for (const [key, val] of this) { - if (first) { - accumulator = val; - first = false; - continue; - } - accumulator = fn(accumulator, val, key, this); - } - } - return accumulator; - } - - /** - * Combines this collection with others into a new collection. None of the source collections are modified. - * @param {...Collection} collections Collections to merge - * @returns {Collection} - * @example const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); - */ - concat(...collections) { - const newColl = new this.constructor(); - for (const [key, val] of this) newColl.set(key, val); - for (const coll of collections) { - for (const [key, val] of coll) newColl.set(key, val); - } - return newColl; - } - - /** - * Calls the `delete()` method on all items that have it. - * @returns {Promise[]} - */ - deleteAll() { - const returns = []; - for (const item of this.values()) { - if (item.delete) returns.push(item.delete()); - } - return returns; - } - - /** - * Checks if this collection shares identical key-value pairings with another. - * This is different to checking for equality using equal-signs, because - * the collections may be different objects, but contain the same data. - * @param {Collection} collection Collection to compare with - * @returns {boolean} Whether the collections have identical contents - */ - equals(collection) { - if (!collection) return false; - if (this === collection) return true; - if (this.size !== collection.size) return false; - return !this.find((value, key) => { - const testVal = collection.get(key); - return testVal !== value || (testVal === undefined && !collection.has(key)); - }); - } -} - -module.exports = Collection; - - -/***/ }, -/* 4 */ -/***/ function(module, exports) { - -module.exports = function cloneObject(obj) { - const cloned = Object.create(obj); - Object.assign(cloned, obj); - return cloned; -}; - - -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -var TYPED_OK = (typeof Uint8Array !== 'undefined') && - (typeof Uint16Array !== 'undefined') && - (typeof Int32Array !== 'undefined'); - - -exports.assign = function (obj /*from1, from2, from3, ...*/) { - var sources = Array.prototype.slice.call(arguments, 1); - while (sources.length) { - var source = sources.shift(); - if (!source) { continue; } - - if (typeof source !== 'object') { - throw new TypeError(source + 'must be non-object'); - } - - for (var p in source) { - if (source.hasOwnProperty(p)) { - obj[p] = source[p]; - } - } - } - - return obj; -}; - - -// reduce buffer size, avoiding mem copy -exports.shrinkBuf = function (buf, size) { - if (buf.length === size) { return buf; } - if (buf.subarray) { return buf.subarray(0, size); } - buf.length = size; - return buf; -}; - - -var fnTyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - if (src.subarray && dest.subarray) { - dest.set(src.subarray(src_offs, src_offs + len), dest_offs); - return; - } - // Fallback to ordinary array - for (var i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - var i, l, len, pos, chunk, result; - - // calculate data length - len = 0; - for (i = 0, l = chunks.length; i < l; i++) { - len += chunks[i].length; - } - - // join chunks - result = new Uint8Array(len); - pos = 0; - for (i = 0, l = chunks.length; i < l; i++) { - chunk = chunks[i]; - result.set(chunk, pos); - pos += chunk.length; - } - - return result; - } -}; - -var fnUntyped = { - arraySet: function (dest, src, src_offs, len, dest_offs) { - for (var i = 0; i < len; i++) { - dest[dest_offs + i] = src[src_offs + i]; - } - }, - // Join array of chunks to single array. - flattenChunks: function (chunks) { - return [].concat.apply([], chunks); - } -}; - - -// Enable/Disable typed arrays use, for testing -// -exports.setTyped = function (on) { - if (on) { - exports.Buf8 = Uint8Array; - exports.Buf16 = Uint16Array; - exports.Buf32 = Int32Array; - exports.assign(exports, fnTyped); - } else { - exports.Buf8 = Array; - exports.Buf16 = Array; - exports.Buf32 = Array; - exports.assign(exports, fnUntyped); - } -}; - -exports.setTyped(TYPED_OK); - - -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { - -const TextBasedChannel = __webpack_require__(12); -const Constants = __webpack_require__(0); -const Presence = __webpack_require__(7).Presence; - -/** - * Represents a user on Discord. - * @implements {TextBasedChannel} - */ -class User { - constructor(client, data) { - /** - * The Client that created the instance of the the User. - * @name User#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - if (data) this.setup(data); - } - - setup(data) { - /** - * The ID of the user - * @type {string} - */ - this.id = data.id; - - /** - * The username of the user - * @type {string} - */ - this.username = data.username; - - /** - * A discriminator based on username for the user - * @type {string} - */ - this.discriminator = data.discriminator; - - /** - * The ID of the user's avatar - * @type {string} - */ - this.avatar = data.avatar; - - /** - * Whether or not the user is a bot. - * @type {boolean} - */ - this.bot = Boolean(data.bot); - - /** - * The ID of the last message sent by the user, if one was sent. - * @type {?string} - */ - this.lastMessageID = null; - } - - patch(data) { - for (const prop of ['id', 'username', 'discriminator', 'avatar', 'bot']) { - if (typeof data[prop] !== 'undefined') this[prop] = data[prop]; - } - if (data.token) this.client.token = data.token; - } - - /** - * The timestamp the user was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return (this.id / 4194304) + 1420070400000; - } - - /** - * The time the user was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The presence of this user - * @type {Presence} - * @readonly - */ - get presence() { - if (this.client.presences.has(this.id)) return this.client.presences.get(this.id); - for (const guild of this.client.guilds.values()) { - if (guild.presences.has(this.id)) return guild.presences.get(this.id); - } - return new Presence(); - } - - /** - * A link to the user's avatar (if they have one, otherwise null) - * @type {?string} - * @readonly - */ - get avatarURL() { - if (!this.avatar) return null; - return Constants.Endpoints.avatar(this.id, this.avatar); - } - - /** - * A link to the user's default avatar - * @type {string} - * @readonly - */ - get defaultAvatarURL() { - let defaultAvatars = Object.values(Constants.DefaultAvatars); - let defaultAvatar = this.discriminator % defaultAvatars.length; - return Constants.Endpoints.assets(`${defaultAvatars[defaultAvatar]}.png`); - } - - /** - * A link to the user's avatar if they have one. Otherwise a link to their default avatar will be returned - * @type {string} - * @readonly - */ - get displayAvatarURL() { - return this.avatarURL || this.defaultAvatarURL; - } - - /** - * The note that is set for the user - * This is only available when using a user account. - * @type {?string} - * @readonly - */ - get note() { - return this.client.user.notes.get(this.id) || null; - } - - /** - * Check whether the user is typing in a channel. - * @param {ChannelResolvable} channel The channel to check in - * @returns {boolean} - */ - typingIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - return channel._typing.has(this.id); - } - - /** - * Get the time that the user started typing. - * @param {ChannelResolvable} channel The channel to get the time in - * @returns {?Date} - */ - typingSinceIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - return channel._typing.has(this.id) ? new Date(channel._typing.get(this.id).since) : null; - } - - /** - * Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing. - * @param {ChannelResolvable} channel The channel to get the time in - * @returns {number} - */ - typingDurationIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - return channel._typing.has(this.id) ? channel._typing.get(this.id).elapsedTime : -1; - } - - /** - * The DM between the client's user and this user - * @type {?DMChannel} - */ - get dmChannel() { - return this.client.channels.filter(c => c.type === 'dm').find(c => c.recipient.id === this.id); - } - - /** - * Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful. - * @returns {Promise} - */ - deleteDM() { - return this.client.rest.methods.deleteChannel(this); - } - - /** - * Sends a friend request to the user - * This is only available when using a user account. - * @returns {Promise} - */ - addFriend() { - return this.client.rest.methods.addFriend(this); - } - - /** - * Removes the user from your friends - * This is only available when using a user account. - * @returns {Promise} - */ - removeFriend() { - return this.client.rest.methods.removeFriend(this); - } - - /** - * Blocks the user - * This is only available when using a user account. - * @returns {Promise} - */ - block() { - return this.client.rest.methods.blockUser(this); - } - - /** - * Unblocks the user - * This is only available when using a user account. - * @returns {Promise} - */ - unblock() { - return this.client.rest.methods.unblockUser(this); - } - - /** - * Get the profile of the user - * This is only available when using a user account. - * @returns {Promise} - */ - fetchProfile() { - return this.client.rest.methods.fetchUserProfile(this); - } - - /** - * Sets a note for the user - * This is only available when using a user account. - * @param {string} note The note to set for the user - * @returns {Promise} - */ - setNote(note) { - return this.client.rest.methods.setNote(this, note); - } - - /** - * Checks if the user is equal to another. It compares ID, username, discriminator, avatar, and bot flags. - * It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties. - * @param {User} user User to compare with - * @returns {boolean} - */ - equals(user) { - let equal = user && - this.id === user.id && - this.username === user.username && - this.discriminator === user.discriminator && - this.avatar === user.avatar && - this.bot === Boolean(user.bot); - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the user's mention instead of the User object. - * @returns {string} - * @example - * // logs: Hello from <@123456789>! - * console.log(`Hello from ${user}!`); - */ - toString() { - return `<@${this.id}>`; - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - send() { return; } - sendMessage() { return; } - sendEmbed() { return; } - sendFile() { return; } - sendCode() { return; } -} - -TextBasedChannel.applyToClass(User); - -module.exports = User; - - -/***/ }, -/* 7 */ -/***/ function(module, exports) { - -/** - * Represents a user's presence - */ -class Presence { - constructor(data = {}) { - /** - * The status of the presence: - * - * * **`online`** - user is online - * * **`offline`** - user is offline or invisible - * * **`idle`** - user is AFK - * * **`dnd`** - user is in Do not Disturb - * @type {string} - */ - this.status = data.status || 'offline'; - - /** - * The game that the user is playing, `null` if they aren't playing a game. - * @type {?Game} - */ - this.game = data.game ? new Game(data.game) : null; - } - - update(data) { - this.status = data.status || this.status; - this.game = data.game ? new Game(data.game) : null; - } - - /** - * Whether this presence is equal to another - * @param {Presence} presence Presence to compare with - * @returns {boolean} - */ - equals(presence) { - return this === presence || ( - presence && - this.status === presence.status && - this.game ? this.game.equals(presence.game) : !presence.game - ); - } -} - -/** - * Represents a game that is part of a user's presence. - */ -class Game { - constructor(data) { - /** - * The name of the game being played - * @type {string} - */ - this.name = data.name; - - /** - * The type of the game status - * @type {number} - */ - this.type = data.type; - - /** - * If the game is being streamed, a link to the stream - * @type {?string} - */ - this.url = data.url || null; - } - - /** - * Whether or not the game is being streamed - * @type {boolean} - * @readonly - */ - get streaming() { - return this.type === 1; - } - - /** - * Whether this game is equal to another game - * @param {Game} game Game to compare with - * @returns {boolean} - */ - equals(game) { - return this === game || ( - game && - this.name === game.name && - this.type === game.type && - this.url === game.url - ); - } -} - -exports.Presence = Presence; -exports.Game = Game; - - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -/** - * Represents a role on Discord - */ -class Role { - constructor(guild, data) { - /** - * The client that instantiated the role - * @name Role#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: guild.client }); - - /** - * The guild that the role belongs to - * @type {Guild} - */ - this.guild = guild; - - if (data) this.setup(data); - } - - setup(data) { - /** - * The ID of the role (unique to the guild it is part of) - * @type {string} - */ - this.id = data.id; - - /** - * The name of the role - * @type {string} - */ - this.name = data.name; - - /** - * The base 10 color of the role - * @type {number} - */ - this.color = data.color; - - /** - * If true, users that are part of this role will appear in a separate category in the users list - * @type {boolean} - */ - this.hoist = data.hoist; - - /** - * The position of the role in the role manager - * @type {number} - */ - this.position = data.position; - - /** - * The evaluated permissions number - * @type {number} - */ - this.permissions = data.permissions; - - /** - * Whether or not the role is managed by an external service - * @type {boolean} - */ - this.managed = data.managed; - - /** - * Whether or not the role can be mentioned by anyone - * @type {boolean} - */ - this.mentionable = data.mentionable; - } - - /** - * The timestamp the role was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return (this.id / 4194304) + 1420070400000; - } - - /** - * The time the role was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The hexadecimal version of the role color, with a leading hashtag. - * @type {string} - * @readonly - */ - get hexColor() { - let col = this.color.toString(16); - while (col.length < 6) col = `0${col}`; - return `#${col}`; - } - - /** - * The cached guild members that have this role. - * @type {Collection} - * @readonly - */ - get members() { - return this.guild.members.filter(m => m.roles.has(this.id)); - } - - /** - * Whether the role is editable by the client user. - * @type {boolean} - * @readonly - */ - get editable() { - if (this.managed) return false; - const clientMember = this.guild.member(this.client.user); - if (!clientMember.hasPermission(Constants.PermissionFlags.MANAGE_ROLES_OR_PERMISSIONS)) return false; - return clientMember.highestRole.comparePositionTo(this) > 0; - } - - /** - * Get an object mapping permission names to whether or not the role enables that permission - * @returns {Object} - * @example - * // print the serialized role - * console.log(role.serialize()); - */ - serialize() { - const serializedPermissions = {}; - for (const permissionName in Constants.PermissionFlags) { - serializedPermissions[permissionName] = this.hasPermission(permissionName); - } - return serializedPermissions; - } - - /** - * Checks if the role has a permission. - * @param {PermissionResolvable} permission The permission to check for - * @param {boolean} [explicit=false] Whether to require the role to explicitly have the exact permission - * @returns {boolean} - * @example - * // see if a role can ban a member - * if (role.hasPermission('BAN_MEMBERS')) { - * console.log('This role can ban members'); - * } else { - * console.log('This role can\'t ban members'); - * } - */ - hasPermission(permission, explicit = false) { - permission = this.client.resolver.resolvePermission(permission); - if (!explicit && (this.permissions & Constants.PermissionFlags.ADMINISTRATOR) > 0) return true; - return (this.permissions & permission) > 0; - } - - /** - * Checks if the role has all specified permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the role to explicitly have the exact permissions - * @returns {boolean} - */ - hasPermissions(permissions, explicit = false) { - return permissions.every(p => this.hasPermission(p, explicit)); - } - - /** - * Compares this role's position to another role's. - * @param {Role} role Role to compare to this one - * @returns {number} Negative number if the this role's position is lower (other role's is higher), - * positive number if the this one is higher (other's is lower), 0 if equal - */ - comparePositionTo(role) { - return this.constructor.comparePositions(this, role); - } - - /** - * The data for a role - * @typedef {Object} RoleData - * @property {string} [name] The name of the role - * @property {number|string} [color] The color of the role, either a hex string or a base 10 number - * @property {boolean} [hoist] Whether or not the role should be hoisted - * @property {number} [position] The position of the role - * @property {string[]} [permissions] The permissions of the role - * @property {boolean} [mentionable] Whether or not the role should be mentionable - */ - - /** - * Edits the role - * @param {RoleData} data The new data for the role - * @returns {Promise} - * @example - * // edit a role - * role.edit({name: 'new role'}) - * .then(r => console.log(`Edited role ${r}`)) - * .catch(console.error); - */ - edit(data) { - return this.client.rest.methods.updateGuildRole(this, data); - } - - /** - * Set a new name for the role - * @param {string} name The new name of the role - * @returns {Promise} - * @example - * // set the name of the role - * role.setName('new role') - * .then(r => console.log(`Edited name of role ${r}`)) - * .catch(console.error); - */ - setName(name) { - return this.edit({ name }); - } - - /** - * Set a new color for the role - * @param {number|string} color The new color for the role, either a hex string or a base 10 number - * @returns {Promise} - * @example - * // set the color of a role - * role.setColor('#FF0000') - * .then(r => console.log(`Set color of role ${r}`)) - * .catch(console.error); - */ - setColor(color) { - return this.edit({ color }); - } - - /** - * Set whether or not the role should be hoisted - * @param {boolean} hoist Whether or not to hoist the role - * @returns {Promise} - * @example - * // set the hoist of the role - * role.setHoist(true) - * .then(r => console.log(`Role hoisted: ${r.hoist}`)) - * .catch(console.error); - */ - setHoist(hoist) { - return this.edit({ hoist }); - } - - /** - * Set the position of the role - * @param {number} position The position of the role - * @returns {Promise} - * @example - * // set the position of the role - * role.setPosition(1) - * .then(r => console.log(`Role position: ${r.position}`)) - * .catch(console.error); - */ - setPosition(position) { - return this.guild.setRolePosition(this, position).then(() => this); - } - - /** - * Set the permissions of the role - * @param {string[]} permissions The permissions of the role - * @returns {Promise} - * @example - * // set the permissions of the role - * role.setPermissions(['KICK_MEMBERS', 'BAN_MEMBERS']) - * .then(r => console.log(`Role updated ${r}`)) - * .catch(console.error); - */ - setPermissions(permissions) { - return this.edit({ permissions }); - } - - /** - * Set whether this role is mentionable - * @param {boolean} mentionable Whether this role should be mentionable - * @returns {Promise} - * @example - * // make the role mentionable - * role.setMentionable(true) - * .then(r => console.log(`Role updated ${r}`)) - * .catch(console.error); - */ - setMentionable(mentionable) { - return this.edit({ mentionable }); - } - - /** - * Deletes the role - * @returns {Promise} - * @example - * // delete a role - * role.delete() - * .then(r => console.log(`Deleted role ${r}`)) - * .catch(console.error); - */ - delete() { - return this.client.rest.methods.deleteGuildRole(this); - } - - /** - * Whether this role equals another role. It compares all properties, so for most operations - * it is advisable to just compare `role.id === role2.id` as it is much faster and is often - * what most users need. - * @param {Role} role Role to compare with - * @returns {boolean} - */ - equals(role) { - return role && - this.id === role.id && - this.name === role.name && - this.color === role.color && - this.hoist === role.hoist && - this.position === role.position && - this.permissions === role.permissions && - this.managed === role.managed; - } - - /** - * When concatenated with a string, this automatically concatenates the role mention rather than the Role object. - * @returns {string} - */ - toString() { - if (this.id === this.guild.id) return '@everyone'; - return `<@&${this.id}>`; - } - - /** - * Compares the positions of two roles. - * @param {Role} role1 First role to compare - * @param {Role} role2 Second role to compare - * @returns {number} Negative number if the first role's position is lower (second role's is higher), - * positive number if the first's is higher (second's is lower), 0 if equal - */ - static comparePositions(role1, role2) { - if (role1.position === role2.position) return role2.id - role1.id; - return role1.position - role2.position; - } -} - -module.exports = Role; - - -/***/ }, -/* 9 */ -/***/ function(module, exports) { - -/** - * Represents any channel on Discord - */ -class Channel { - constructor(client, data) { - /** - * The client that instantiated the Channel - * @name Channel#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * The type of the channel, either: - * * `dm` - a DM channel - * * `group` - a Group DM channel - * * `text` - a guild text channel - * * `voice` - a guild voice channel - * @type {string} - */ - this.type = null; - - if (data) this.setup(data); - } - - setup(data) { - /** - * The unique ID of the channel - * @type {string} - */ - this.id = data.id; - } - - /** - * The timestamp the channel was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return (this.id / 4194304) + 1420070400000; - } - - /** - * The time the channel was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * Deletes the channel - * @returns {Promise} - * @example - * // delete the channel - * channel.delete() - * .then() // success - * .catch(console.error); // log error - */ - delete() { - return this.client.rest.methods.deleteChannel(this); - } -} - -module.exports = Channel; - - -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); - -/** - * Represents a custom emoji - */ -class Emoji { - constructor(guild, data) { - /** - * The Client that instantiated this object - * @name Emoji#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: guild.client }); - - /** - * The guild this emoji is part of - * @type {Guild} - */ - this.guild = guild; - - this.setup(data); - } - - setup(data) { - /** - * The ID of the emoji - * @type {string} - */ - this.id = data.id; - - /** - * The name of the emoji - * @type {string} - */ - this.name = data.name; - - /** - * Whether or not this emoji requires colons surrounding it - * @type {boolean} - */ - this.requiresColons = data.require_colons; - - /** - * Whether this emoji is managed by an external service - * @type {boolean} - */ - this.managed = data.managed; - - this._roles = data.roles; - } - - /** - * The timestamp the emoji was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return (this.id / 4194304) + 1420070400000; - } - - /** - * The time the emoji was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * A collection of roles this emoji is active for (empty if all), mapped by role ID. - * @type {Collection} - * @readonly - */ - get roles() { - const roles = new Collection(); - for (const role of this._roles) { - if (this.guild.roles.has(role)) roles.set(role, this.guild.roles.get(role)); - } - return roles; - } - - /** - * The URL to the emoji file - * @type {string} - * @readonly - */ - get url() { - return Constants.Endpoints.emoji(this.id); - } - - /** - * When concatenated with a string, this automatically returns the emoji mention rather than the object. - * @returns {string} - * @example - * // send an emoji: - * const emoji = guild.emojis.first(); - * msg.reply(`Hello! ${emoji}`); - */ - toString() { - return this.requiresColons ? `<:${this.name}:${this.id}>` : this.name; - } - - /** - * Whether this emoji is the same as another one - * @param {Emoji|Object} other the emoji to compare it to - * @returns {boolean} whether the emoji is equal to the given emoji or not - */ - equals(other) { - if (other instanceof Emoji) { - return ( - other.id === this.id && - other.name === this.name && - other.managed === this.managed && - other.requiresColons === this.requiresColons - ); - } else { - return ( - other.id === this.id && - other.name === this.name - ); - } - } - - /** - * The identifier of this emoji, used for message reactions - * @readonly - * @type {string} - */ - get identifier() { - if (this.id) { - return `${this.name}:${this.id}`; - } - return encodeURIComponent(this.name); - } -} - -module.exports = Emoji; - - -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { - -const Attachment = __webpack_require__(33); -const Embed = __webpack_require__(35); -const MessageReaction = __webpack_require__(36); -const Collection = __webpack_require__(3); -const Constants = __webpack_require__(0); -const escapeMarkdown = __webpack_require__(15); - -// Done purely for GuildMember, which would cause a bad circular dependency -const Discord = __webpack_require__(57); - -/** - * Represents a message on Discord - */ -class Message { - constructor(channel, data, client) { - /** - * The Client that instantiated the Message - * @name Message#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * The channel that the message was sent in - * @type {TextChannel|DMChannel|GroupDMChannel} - */ - this.channel = channel; - - if (data) this.setup(data); - } - - setup(data) { // eslint-disable-line complexity - /** - * The ID of the message (unique in the channel it was sent) - * @type {string} - */ - this.id = data.id; - - /** - * The type of the message - * @type {string} - */ - this.type = Constants.MessageTypes[data.type]; - - /** - * The content of the message - * @type {string} - */ - this.content = data.content; - - /** - * The author of the message - * @type {User} - */ - this.author = this.client.dataManager.newUser(data.author); - - /** - * Represents the author of the message as a guild member. Only available if the message comes from a guild - * where the author is still a member. - * @type {GuildMember} - */ - this.member = this.guild ? this.guild.member(this.author) || null : null; - - /** - * Whether or not this message is pinned - * @type {boolean} - */ - this.pinned = data.pinned; - - /** - * Whether or not the message was Text-To-Speech - * @type {boolean} - */ - this.tts = data.tts; - - /** - * A random number used for checking message delivery - * @type {string} - */ - this.nonce = data.nonce; - - /** - * Whether or not this message was sent by Discord, not actually a user (e.g. pin notifications) - * @type {boolean} - */ - this.system = data.type === 6; - - /** - * A list of embeds in the message - e.g. YouTube Player - * @type {MessageEmbed[]} - */ - this.embeds = data.embeds.map(e => new Embed(this, e)); - - /** - * A collection of attachments in the message - e.g. Pictures - mapped by their ID. - * @type {Collection} - */ - this.attachments = new Collection(); - for (const attachment of data.attachments) this.attachments.set(attachment.id, new Attachment(this, attachment)); - - /** - * The timestamp the message was sent at - * @type {number} - */ - this.createdTimestamp = new Date(data.timestamp).getTime(); - - /** - * The timestamp the message was last edited at (if applicable) - * @type {?number} - */ - this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; - - /** - * An object containing a further users, roles or channels collections - * @type {Object} - * @property {Collection} mentions.users Mentioned users, maps their ID to the user object. - * @property {Collection} mentions.roles Mentioned roles, maps their ID to the role object. - * @property {Collection} mentions.channels Mentioned channels, - * maps their ID to the channel object. - * @property {boolean} mentions.everyone Whether or not @everyone was mentioned. - */ - this.mentions = { - users: new Collection(), - roles: new Collection(), - channels: new Collection(), - everyone: data.mention_everyone, - }; - - for (const mention of data.mentions) { - let user = this.client.users.get(mention.id); - if (user) { - this.mentions.users.set(user.id, user); - } else { - user = this.client.dataManager.newUser(mention); - this.mentions.users.set(user.id, user); - } - } - - if (data.mention_roles) { - for (const mention of data.mention_roles) { - const role = this.channel.guild.roles.get(mention); - if (role) this.mentions.roles.set(role.id, role); - } - } - - if (this.channel.guild) { - const channMentionsRaw = data.content.match(/<#([0-9]{14,20})>/g) || []; - for (const raw of channMentionsRaw) { - const chan = this.channel.guild.channels.get(raw.match(/([0-9]{14,20})/g)[0]); - if (chan) this.mentions.channels.set(chan.id, chan); - } - } - - this._edits = []; - - /** - * A collection of reactions to this message, mapped by the reaction "id". - * @type {Collection} - */ - this.reactions = new Collection(); - - if (data.reactions && data.reactions.length > 0) { - for (const reaction of data.reactions) { - const id = reaction.emoji.id ? `${reaction.emoji.name}:${reaction.emoji.id}` : reaction.emoji.name; - this.reactions.set(id, new MessageReaction(this, reaction.emoji, reaction.count, reaction.me)); - } - } - - /** - * ID of the webhook that sent the message, if applicable - * @type {?string} - */ - this.webhookID = data.webhook_id || null; - } - - patch(data) { // eslint-disable-line complexity - if (data.author) { - this.author = this.client.users.get(data.author.id); - if (this.guild) this.member = this.guild.member(this.author); - } - if (data.content) this.content = data.content; - if (data.timestamp) this.createdTimestamp = new Date(data.timestamp).getTime(); - if (data.edited_timestamp) { - this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; - } - if ('tts' in data) this.tts = data.tts; - if ('mention_everyone' in data) this.mentions.everyone = data.mention_everyone; - if (data.nonce) this.nonce = data.nonce; - if (data.embeds) this.embeds = data.embeds.map(e => new Embed(this, e)); - if (data.type > -1) { - this.system = false; - if (data.type === 6) this.system = true; - } - if (data.attachments) { - this.attachments = new Collection(); - for (const attachment of data.attachments) { - this.attachments.set(attachment.id, new Attachment(this, attachment)); - } - } - if (data.mentions) { - for (const mention of data.mentions) { - let user = this.client.users.get(mention.id); - if (user) { - this.mentions.users.set(user.id, user); - } else { - user = this.client.dataManager.newUser(mention); - this.mentions.users.set(user.id, user); - } - } - } - if (data.mention_roles) { - for (const mention of data.mention_roles) { - const role = this.channel.guild.roles.get(mention); - if (role) this.mentions.roles.set(role.id, role); - } - } - if (data.id) this.id = data.id; - if (this.channel.guild && data.content) { - const channMentionsRaw = data.content.match(/<#([0-9]{14,20})>/g) || []; - for (const raw of channMentionsRaw) { - const chan = this.channel.guild.channels.get(raw.match(/([0-9]{14,20})/g)[0]); - if (chan) this.mentions.channels.set(chan.id, chan); - } - } - if (data.reactions) { - this.reactions = new Collection(); - if (data.reactions.length > 0) { - for (const reaction of data.reactions) { - const id = reaction.emoji.id ? `${reaction.emoji.name}:${reaction.emoji.id}` : reaction.emoji.name; - this.reactions.set(id, new MessageReaction(this, data.emoji, data.count, data.me)); - } - } - } - } - - /** - * The time the message was sent - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The time the message was last edited at (if applicable) - * @type {?Date} - * @readonly - */ - get editedAt() { - return this.editedTimestamp ? new Date(this.editedTimestamp) : null; - } - - /** - * The guild the message was sent in (if in a guild channel) - * @type {?Guild} - * @readonly - */ - get guild() { - return this.channel.guild || null; - } - - /** - * The message contents with all mentions replaced by the equivalent text. If mentions cannot be resolved to a name, - * the relevant mention in the message content will not be converted. - * @type {string} - * @readonly - */ - get cleanContent() { - return this.content - .replace(/@(everyone|here)/g, '@\u200b$1') - .replace(/<@!?[0-9]+>/g, (input) => { - const id = input.replace(/<|!|>|@/g, ''); - if (this.channel.type === 'dm' || this.channel.type === 'group') { - return this.client.users.has(id) ? `@${this.client.users.get(id).username}` : input; - } - - const member = this.channel.guild.members.get(id); - if (member) { - if (member.nickname) return `@${member.nickname}`; - return `@${member.user.username}`; - } else { - const user = this.client.users.get(id); - if (user) return `@${user.username}`; - return input; - } - }) - .replace(/<#[0-9]+>/g, (input) => { - const channel = this.client.channels.get(input.replace(/<|#|>/g, '')); - if (channel) return `#${channel.name}`; - return input; - }) - .replace(/<@&[0-9]+>/g, (input) => { - if (this.channel.type === 'dm' || this.channel.type === 'group') return input; - const role = this.guild.roles.get(input.replace(/<|@|>|&/g, '')); - if (role) return `@${role.name}`; - return input; - }); - } - - /** - * An array of cached versions of the message, including the current version. - * Sorted from latest (first) to oldest (last). - * @type {Message[]} - * @readonly - */ - get edits() { - const copy = this._edits.slice(); - copy.unshift(this); - return copy; - } - - /** - * Whether the message is editable by the client user. - * @type {boolean} - * @readonly - */ - get editable() { - return this.author.id === this.client.user.id; - } - - /** - * Whether the message is deletable by the client user. - * @type {boolean} - * @readonly - */ - get deletable() { - return this.author.id === this.client.user.id || (this.guild && - this.channel.permissionsFor(this.client.user).hasPermission(Constants.PermissionFlags.MANAGE_MESSAGES) - ); - } - - /** - * Whether the message is pinnable by the client user. - * @type {boolean} - * @readonly - */ - get pinnable() { - return !this.guild || - this.channel.permissionsFor(this.client.user).hasPermission(Constants.PermissionFlags.MANAGE_MESSAGES); - } - - /** - * Whether or not a user, channel or role is mentioned in this message. - * @param {GuildChannel|User|Role|string} data either a guild channel, user or a role object, or a string representing - * the ID of any of these. - * @returns {boolean} - */ - isMentioned(data) { - data = data && data.id ? data.id : data; - return this.mentions.users.has(data) || this.mentions.channels.has(data) || this.mentions.roles.has(data); - } - - /** - * Whether or not a guild member is mentioned in this message. Takes into account - * user mentions, role mentions, and @everyone/@here mentions. - * @param {GuildMember|User} member Member/user to check for a mention of - * @returns {boolean} - */ - isMemberMentioned(member) { - if (this.mentions.everyone) return true; - if (this.mentions.users.has(member.id)) return true; - if (member instanceof Discord.GuildMember && member.roles.some(r => this.mentions.roles.has(r.id))) return true; - return false; - } - - /** - * Options that can be passed into editMessage - * @typedef {Object} MessageEditOptions - * @property {Object} [embed] An embed to be added/edited - * @property {string|boolean} [code] Language for optional codeblock formatting to apply - */ - - /** - * Edit the content of the message - * @param {StringResolvable} [content] The new content for the message - * @param {MessageEditOptions} [options] The options to provide - * @returns {Promise} - * @example - * // update the content of a message - * message.edit('This is my new content!') - * .then(msg => console.log(`Updated the content of a message from ${msg.author}`)) - * .catch(console.error); - */ - edit(content, options) { - if (!options && typeof content === 'object') { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - return this.client.rest.methods.updateMessage(this, content, options); - } - - /** - * Edit the content of the message, with a code block - * @param {string} lang Language for the code block - * @param {StringResolvable} content The new content for the message - * @returns {Promise} - */ - editCode(lang, content) { - content = escapeMarkdown(this.client.resolver.resolveString(content), true); - return this.edit(`\`\`\`${lang || ''}\n${content}\n\`\`\``); - } - - /** - * Pins this message to the channel's pinned messages - * @returns {Promise} - */ - pin() { - return this.client.rest.methods.pinMessage(this); - } - - /** - * Unpins this message from the channel's pinned messages - * @returns {Promise} - */ - unpin() { - return this.client.rest.methods.unpinMessage(this); - } - - /** - * Add a reaction to the message - * @param {string|Emoji|ReactionEmoji} emoji Emoji to react with - * @returns {Promise} - */ - react(emoji) { - emoji = this.client.resolver.resolveEmojiIdentifier(emoji); - if (!emoji) throw new TypeError('Emoji must be a string or Emoji/ReactionEmoji'); - - return this.client.rest.methods.addMessageReaction(this, emoji); - } - - /** - * Remove all reactions from a message - * @returns {Promise} - */ - clearReactions() { - return this.client.rest.methods.removeMessageReactions(this); - } - - /** - * Deletes the message - * @param {number} [timeout=0] How long to wait to delete the message in milliseconds - * @returns {Promise} - * @example - * // delete a message - * message.delete() - * .then(msg => console.log(`Deleted message from ${msg.author}`)) - * .catch(console.error); - */ - delete(timeout = 0) { - if (timeout <= 0) { - return this.client.rest.methods.deleteMessage(this); - } else { - return new Promise(resolve => { - this.client.setTimeout(() => { - resolve(this.delete()); - }, timeout); - }); - } - } - - /** - * Reply to the message - * @param {StringResolvable} content The content for the message - * @param {MessageOptions} [options = {}] The options to provide - * @returns {Promise} - * @example - * // reply to a message - * message.reply('Hey, I\'m a reply!') - * .then(msg => console.log(`Sent a reply to ${msg.author}`)) - * .catch(console.error); - */ - reply(content, options = {}) { - content = `${this.guild || this.channel.type === 'group' ? `${this.author}, ` : ''}${content}`; - return this.channel.send(content, options); - } - - /** - * Fetches the webhook used to create this message. - * @returns {Promise} - */ - fetchWebhook() { - if (!this.webhookID) return Promise.reject(new Error('The message was not sent by a webhook.')); - return this.client.fetchWebhook(this.webhookID); - } - - /** - * Used mainly internally. Whether two messages are identical in properties. If you want to compare messages - * without checking all the properties, use `message.id === message2.id`, which is much more efficient. This - * method allows you to see if there are differences in content, embeds, attachments, nonce and tts properties. - * @param {Message} message The message to compare it to - * @param {Object} rawData Raw data passed through the WebSocket about this message - * @returns {boolean} - */ - equals(message, rawData) { - if (!message) return false; - const embedUpdate = !message.author && !message.attachments; - if (embedUpdate) return this.id === message.id && this.embeds.length === message.embeds.length; - - let equal = this.id === message.id && - this.author.id === message.author.id && - this.content === message.content && - this.tts === message.tts && - this.nonce === message.nonce && - this.embeds.length === message.embeds.length && - this.attachments.length === message.attachments.length; - - if (equal && rawData) { - equal = this.mentions.everyone === message.mentions.everyone && - this.createdTimestamp === new Date(rawData.timestamp).getTime() && - this.editedTimestamp === new Date(rawData.edited_timestamp).getTime(); - } - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the message's content instead of the object. - * @returns {string} - * @example - * // logs: Message: This is a message! - * console.log(`Message: ${message}`); - */ - toString() { - return this.content; - } - - _addReaction(emoji, user) { - const emojiID = emoji.id ? `${emoji.name}:${emoji.id}` : emoji.name; - let reaction; - if (this.reactions.has(emojiID)) { - reaction = this.reactions.get(emojiID); - if (!reaction.me) reaction.me = user.id === this.client.user.id; - } else { - reaction = new MessageReaction(this, emoji, 0, user.id === this.client.user.id); - this.reactions.set(emojiID, reaction); - } - if (!reaction.users.has(user.id)) { - reaction.users.set(user.id, user); - reaction.count++; - return reaction; - } - return null; - } - - _removeReaction(emoji, user) { - const emojiID = emoji.id || emoji; - if (this.reactions.has(emojiID)) { - const reaction = this.reactions.get(emojiID); - if (reaction.users.has(user.id)) { - reaction.users.delete(user.id); - reaction.count--; - if (user.id === this.client.user.id) reaction.me = false; - return reaction; - } - } - return null; - } - - _clearReactions() { - this.reactions.clear(); - } -} - -module.exports = Message; - - -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { - -const path = __webpack_require__(23); -const Message = __webpack_require__(11); -const MessageCollector = __webpack_require__(34); -const Collection = __webpack_require__(3); - - -/** - * Interface for classes that have text-channel-like features - * @interface - */ -class TextBasedChannel { - constructor() { - /** - * A collection containing the messages sent to this channel. - * @type {Collection} - */ - this.messages = new Collection(); - - /** - * The ID of the last message in the channel, if one was sent. - * @type {?string} - */ - this.lastMessageID = null; - } - - /** - * Options that can be passed into send, sendMessage, sendFile, sendEmbed, sendCode, and Message#reply - * @typedef {Object} MessageOptions - * @property {boolean} [tts=false] Whether or not the message should be spoken aloud - * @property {string} [nonce=''] The nonce for the message - * @property {Object} [embed] An embed for the message - * (see [here](https://discordapp.com/developers/docs/resources/channel#embed-object) for more details) - * @property {boolean} [disableEveryone=this.client.options.disableEveryone] Whether or not @everyone and @here - * should be replaced with plain-text - * @property {FileOptions|string} [file] A file to send with the message - * @property {string|boolean} [code] Language for optional codeblock formatting to apply - * @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if - * it exceeds the character limit. If an object is provided, these are the options for splitting the message. - */ - - /** - * @typedef {Object} FileOptions - * @property {BufferResolvable} attachment - * @property {string} [name='file.jpg'] - */ - - /** - * Options for splitting a message - * @typedef {Object} SplitOptions - * @property {number} [maxLength=1950] Maximum character length per message piece - * @property {string} [char='\n'] Character to split the message with - * @property {string} [prepend=''] Text to prepend to every piece except the first - * @property {string} [append=''] Text to append to every piece except the last - */ - - /** - * Send a message to this channel - * @param {StringResolvable} [content] Text for the message - * @param {MessageOptions} [options={}] Options for the message - * @returns {Promise} - * @example - * // send a message - * channel.send('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - send(content, options) { - if (!options && typeof content === 'object' && !(content instanceof Array)) { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - if (options.file) { - if (typeof options.file === 'string') options.file = { attachment: options.file }; - if (!options.file.name) { - if (typeof options.file.attachment === 'string') { - options.file.name = path.basename(options.file.attachment); - } else if (options.file.attachment && options.file.attachment.path) { - options.file.name = path.basename(options.file.attachment.path); - } else { - options.file.name = 'file.jpg'; - } - } - return this.client.resolver.resolveBuffer(options.file.attachment).then(file => - this.client.rest.methods.sendMessage(this, content, options, { - file, - name: options.file.name, - }) - ); - } - return this.client.rest.methods.sendMessage(this, content, options); - } - - /** - * Send a message to this channel - * @param {StringResolvable} content Text for the message - * @param {MessageOptions} [options={}] Options for the message - * @returns {Promise} - * @example - * // send a message - * channel.sendMessage('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - sendMessage(content, options) { - return this.send(content, options); - } - - /** - * Send an embed to this channel - * @param {RichEmbed|Object} embed Embed for the message - * @param {string} [content] Text for the message - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - */ - sendEmbed(embed, content, options) { - if (!options && typeof content === 'object') { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - return this.send(content, Object.assign(options, { embed })); - } - - /** - * Send a file to this channel - * @param {BufferResolvable} attachment File to send - * @param {string} [name='file.jpg'] Name and extension of the file - * @param {StringResolvable} [content] Text for the message - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - */ - sendFile(attachment, name, content, options = {}) { - return this.send(content, Object.assign(options, { file: { attachment, name } })); - } - - /** - * Send a code block to this channel - * @param {string} lang Language for the code block - * @param {StringResolvable} content Content of the code block - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - */ - sendCode(lang, content, options = {}) { - return this.send(content, Object.assign(options, { code: lang })); - } - - /** - * Gets a single message from this channel, regardless of it being cached or not. - * This is only available when using a bot account. - * @param {string} messageID ID of the message to get - * @returns {Promise} - * @example - * // get message - * channel.fetchMessage('99539446449315840') - * .then(message => console.log(message.content)) - * .catch(console.error); - */ - fetchMessage(messageID) { - return this.client.rest.methods.getChannelMessage(this, messageID).then(data => { - const msg = data instanceof Message ? data : new Message(this, data, this.client); - this._cacheMessage(msg); - return msg; - }); - } - - /** - * The parameters to pass in when requesting previous messages from a channel. `around`, `before` and - * `after` are mutually exclusive. All the parameters are optional. - * @typedef {Object} ChannelLogsQueryOptions - * @property {number} [limit=50] Number of messages to acquire - * @property {string} [before] ID of a message to get the messages that were posted before it - * @property {string} [after] ID of a message to get the messages that were posted after it - * @property {string} [around] ID of a message to get the messages that were posted around it - */ - - /** - * Gets the past messages sent in this channel. Resolves with a collection mapping message ID's to Message objects. - * @param {ChannelLogsQueryOptions} [options={}] Query parameters to pass in - * @returns {Promise>} - * @example - * // get messages - * channel.fetchMessages({limit: 10}) - * .then(messages => console.log(`Received ${messages.size} messages`)) - * .catch(console.error); - */ - fetchMessages(options = {}) { - return this.client.rest.methods.getChannelMessages(this, options).then(data => { - const messages = new Collection(); - for (const message of data) { - const msg = new Message(this, message, this.client); - messages.set(message.id, msg); - this._cacheMessage(msg); - } - return messages; - }); - } - - /** - * Fetches the pinned messages of this channel and returns a collection of them. - * @returns {Promise>} - */ - fetchPinnedMessages() { - return this.client.rest.methods.getChannelPinnedMessages(this).then(data => { - const messages = new Collection(); - for (const message of data) { - const msg = new Message(this, message, this.client); - messages.set(message.id, msg); - this._cacheMessage(msg); - } - return messages; - }); - } - - /** - * Starts a typing indicator in the channel. - * @param {number} [count] The number of times startTyping should be considered to have been called - * @example - * // start typing in a channel - * channel.startTyping(); - */ - startTyping(count) { - if (typeof count !== 'undefined' && count < 1) throw new RangeError('Count must be at least 1.'); - if (!this.client.user._typing.has(this.id)) { - this.client.user._typing.set(this.id, { - count: count || 1, - interval: this.client.setInterval(() => { - this.client.rest.methods.sendTyping(this.id); - }, 4000), - }); - this.client.rest.methods.sendTyping(this.id); - } else { - const entry = this.client.user._typing.get(this.id); - entry.count = count || entry.count + 1; - } - } - - /** - * Stops the typing indicator in the channel. - * The indicator will only stop if this is called as many times as startTyping(). - * It can take a few seconds for the client user to stop typing. - * @param {boolean} [force=false] Whether or not to reset the call count and force the indicator to stop - * @example - * // stop typing in a channel - * channel.stopTyping(); - * @example - * // force typing to fully stop in a channel - * channel.stopTyping(true); - */ - stopTyping(force = false) { - if (this.client.user._typing.has(this.id)) { - const entry = this.client.user._typing.get(this.id); - entry.count--; - if (entry.count <= 0 || force) { - this.client.clearInterval(entry.interval); - this.client.user._typing.delete(this.id); - } - } - } - - /** - * Whether or not the typing indicator is being shown in the channel. - * @type {boolean} - * @readonly - */ - get typing() { - return this.client.user._typing.has(this.id); - } - - /** - * Number of times `startTyping` has been called. - * @type {number} - * @readonly - */ - get typingCount() { - if (this.client.user._typing.has(this.id)) return this.client.user._typing.get(this.id).count; - return 0; - } - - /** - * Creates a Message Collector - * @param {CollectorFilterFunction} filter The filter to create the collector with - * @param {CollectorOptions} [options={}] The options to pass to the collector - * @returns {MessageCollector} - * @example - * // create a message collector - * const collector = channel.createCollector( - * m => m.content.includes('discord'), - * { time: 15000 } - * ); - * collector.on('message', m => console.log(`Collected ${m.content}`)); - * collector.on('end', collected => console.log(`Collected ${collected.size} items`)); - */ - createCollector(filter, options = {}) { - return new MessageCollector(this, filter, options); - } - - /** - * An object containing the same properties as CollectorOptions, but a few more: - * @typedef {CollectorOptions} AwaitMessagesOptions - * @property {string[]} [errors] Stop/end reasons that cause the promise to reject - */ - - /** - * Similar to createCollector but in promise form. Resolves with a collection of messages that pass the specified - * filter. - * @param {CollectorFilterFunction} filter The filter function to use - * @param {AwaitMessagesOptions} [options={}] Optional options to pass to the internal collector - * @returns {Promise>} - * @example - * // await !vote messages - * const filter = m => m.content.startsWith('!vote'); - * // errors: ['time'] treats ending because of the time limit as an error - * channel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] }) - * .then(collected => console.log(collected.size)) - * .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`)); - */ - awaitMessages(filter, options = {}) { - return new Promise((resolve, reject) => { - const collector = this.createCollector(filter, options); - collector.on('end', (collection, reason) => { - if (options.errors && options.errors.includes(reason)) { - reject(collection); - } else { - resolve(collection); - } - }); - }); - } - - /** - * Bulk delete given messages. - * This is only available when using a bot account. - * @param {Collection|Message[]|number} messages Messages to delete, or number of messages to delete - * @returns {Promise>} Deleted messages - */ - bulkDelete(messages) { - if (!isNaN(messages)) return this.fetchMessages({ limit: messages }).then(msgs => this.bulkDelete(msgs)); - if (messages instanceof Array || messages instanceof Collection) { - const messageIDs = messages instanceof Collection ? messages.keyArray() : messages.map(m => m.id); - return this.client.rest.methods.bulkDeleteMessages(this, messageIDs); - } - throw new TypeError('The messages must be an Array, Collection, or number.'); - } - - _cacheMessage(message) { - const maxSize = this.client.options.messageCacheMaxSize; - if (maxSize === 0) return null; - if (this.messages.size >= maxSize && maxSize > 0) this.messages.delete(this.messages.firstKey()); - this.messages.set(message.id, message); - return message; - } -} - -exports.applyToClass = (structure, full = false) => { - const props = ['send', 'sendMessage', 'sendEmbed', 'sendFile', 'sendCode']; - if (full) { - props.push( - '_cacheMessage', - 'fetchMessages', - 'fetchMessage', - 'bulkDelete', - 'startTyping', - 'stopTyping', - 'typing', - 'typingCount', - 'fetchPinnedMessages', - 'createCollector', - 'awaitMessages' - ); - } - for (const prop of props) { - Object.defineProperty(structure.prototype, prop, Object.getOwnPropertyDescriptor(TextBasedChannel.prototype, prop)); - } -}; - - -/***/ }, -/* 13 */ -/***/ function(module, exports, __webpack_require__) { - -const Channel = __webpack_require__(9); -const Role = __webpack_require__(8); -const PermissionOverwrites = __webpack_require__(40); -const EvaluatedPermissions = __webpack_require__(16); -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); - -/** - * Represents a guild channel (i.e. text channels and voice channels) - * @extends {Channel} - */ -class GuildChannel extends Channel { - constructor(guild, data) { - super(guild.client, data); - - /** - * The guild the channel is in - * @type {Guild} - */ - this.guild = guild; - } - - setup(data) { - super.setup(data); - - /** - * The name of the guild channel - * @type {string} - */ - this.name = data.name; - - /** - * The position of the channel in the list. - * @type {number} - */ - this.position = data.position; - - /** - * A map of permission overwrites in this channel for roles and users. - * @type {Collection} - */ - this.permissionOverwrites = new Collection(); - if (data.permission_overwrites) { - for (const overwrite of data.permission_overwrites) { - this.permissionOverwrites.set(overwrite.id, new PermissionOverwrites(this, overwrite)); - } - } - } - - /** - * Gets the overall set of permissions for a user in this channel, taking into account roles and permission - * overwrites. - * @param {GuildMemberResolvable} member The user that you want to obtain the overall permissions for - * @returns {?EvaluatedPermissions} - */ - permissionsFor(member) { - member = this.client.resolver.resolveGuildMember(this.guild, member); - if (!member) return null; - if (member.id === this.guild.ownerID) return new EvaluatedPermissions(member, Constants.ALL_PERMISSIONS); - - let permissions = 0; - - const roles = member.roles; - for (const role of roles.values()) permissions |= role.permissions; - - const overwrites = this.overwritesFor(member, true, roles); - for (const overwrite of overwrites.role.concat(overwrites.member)) { - permissions &= ~overwrite.deny; - permissions |= overwrite.allow; - } - - const admin = Boolean(permissions & Constants.PermissionFlags.ADMINISTRATOR); - if (admin) permissions = Constants.ALL_PERMISSIONS; - - return new EvaluatedPermissions(member, permissions); - } - - overwritesFor(member, verified = false, roles = null) { - if (!verified) member = this.client.resolver.resolveGuildMember(this.guild, member); - if (!member) return []; - - roles = roles || member.roles; - const roleOverwrites = []; - const memberOverwrites = []; - - for (const overwrite of this.permissionOverwrites.values()) { - if (overwrite.id === member.id) { - memberOverwrites.push(overwrite); - } else if (roles.has(overwrite.id)) { - roleOverwrites.push(overwrite); - } - } - - return { - role: roleOverwrites, - member: memberOverwrites, - }; - } - - /** - * An object mapping permission flags to `true` (enabled) or `false` (disabled) - * ```js - * { - * 'SEND_MESSAGES': true, - * 'ATTACH_FILES': false, - * } - * ``` - * @typedef {Object} PermissionOverwriteOptions - */ - - /** - * Overwrites the permissions for a user or role in this channel. - * @param {RoleResolvable|UserResolvable} userOrRole The user or role to update - * @param {PermissionOverwriteOptions} options The configuration for the update - * @returns {Promise} - * @example - * // overwrite permissions for a message author - * message.channel.overwritePermissions(message.author, { - * SEND_MESSAGES: false - * }) - * .then(() => console.log('Done!')) - * .catch(console.error); - */ - overwritePermissions(userOrRole, options) { - const payload = { - allow: 0, - deny: 0, - }; - - if (userOrRole instanceof Role) { - payload.type = 'role'; - } else if (this.guild.roles.has(userOrRole)) { - userOrRole = this.guild.roles.get(userOrRole); - payload.type = 'role'; - } else { - userOrRole = this.client.resolver.resolveUser(userOrRole); - payload.type = 'member'; - if (!userOrRole) return Promise.reject(new TypeError('Supplied parameter was neither a User nor a Role.')); - } - - payload.id = userOrRole.id; - - const prevOverwrite = this.permissionOverwrites.get(userOrRole.id); - - if (prevOverwrite) { - payload.allow = prevOverwrite.allow; - payload.deny = prevOverwrite.deny; - } - - for (const perm in options) { - if (options[perm] === true) { - payload.allow |= Constants.PermissionFlags[perm] || 0; - payload.deny &= ~(Constants.PermissionFlags[perm] || 0); - } else if (options[perm] === false) { - payload.allow &= ~(Constants.PermissionFlags[perm] || 0); - payload.deny |= Constants.PermissionFlags[perm] || 0; - } else if (options[perm] === null) { - payload.allow &= ~(Constants.PermissionFlags[perm] || 0); - payload.deny &= ~(Constants.PermissionFlags[perm] || 0); - } - } - - return this.client.rest.methods.setChannelOverwrite(this, payload); - } - - /** - * The data for a guild channel - * @typedef {Object} ChannelData - * @property {string} [name] The name of the channel - * @property {number} [position] The position of the channel - * @property {string} [topic] The topic of the text channel - * @property {number} [bitrate] The bitrate of the voice channel - * @property {number} [userLimit] The user limit of the channel - */ - - /** - * Edits the channel - * @param {ChannelData} data The new data for the channel - * @returns {Promise} - * @example - * // edit a channel - * channel.edit({name: 'new-channel'}) - * .then(c => console.log(`Edited channel ${c}`)) - * .catch(console.error); - */ - edit(data) { - return this.client.rest.methods.updateChannel(this, data); - } - - /** - * Set a new name for the guild channel - * @param {string} name The new name for the guild channel - * @returns {Promise} - * @example - * // set a new channel name - * channel.setName('not_general') - * .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`)) - * .catch(console.error); - */ - setName(name) { - return this.edit({ name }); - } - - /** - * Set a new position for the guild channel - * @param {number} position The new position for the guild channel - * @returns {Promise} - * @example - * // set a new channel position - * channel.setPosition(2) - * .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`)) - * .catch(console.error); - */ - setPosition(position) { - return this.client.rest.methods.updateChannel(this, { position }); - } - - /** - * Set a new topic for the guild channel - * @param {string} topic The new topic for the guild channel - * @returns {Promise} - * @example - * // set a new channel topic - * channel.setTopic('needs more rate limiting') - * .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`)) - * .catch(console.error); - */ - setTopic(topic) { - return this.client.rest.methods.updateChannel(this, { topic }); - } - - /** - * Options given when creating a guild channel invite - * @typedef {Object} InviteOptions - * @property {boolean} [temporary=false] Whether the invite should kick users after 24hrs if they are not given a role - * @property {number} [maxAge=0] Time in seconds the invite expires in - * @property {number} [maxUses=0] Maximum amount of uses for this invite - */ - - /** - * Create an invite to this guild channel - * @param {InviteOptions} [options={}] The options for the invite - * @returns {Promise} - */ - createInvite(options = {}) { - return this.client.rest.methods.createChannelInvite(this, options); - } - - /** - * Clone this channel - * @param {string} [name=this.name] Optional name for the new channel, otherwise it has the name of this channel - * @param {boolean} [withPermissions=true] Whether to clone the channel with this channel's permission overwrites - * @returns {Promise} - */ - clone(name = this.name, withPermissions = true) { - return this.guild.createChannel(name, this.type, withPermissions ? this.permissionOverwrites : []); - } - - /** - * Checks if this channel has the same type, topic, position, name, overwrites and ID as another channel. - * In most cases, a simple `channel.id === channel2.id` will do, and is much faster too. - * @param {GuildChannel} channel Channel to compare with - * @returns {boolean} - */ - equals(channel) { - let equal = channel && - this.id === channel.id && - this.type === channel.type && - this.topic === channel.topic && - this.position === channel.position && - this.name === channel.name; - - if (equal) { - if (this.permissionOverwrites && channel.permissionOverwrites) { - equal = this.permissionOverwrites.equals(channel.permissionOverwrites); - } else { - equal = !this.permissionOverwrites && !channel.permissionOverwrites; - } - } - - return equal; - } - - /** - * When concatenated with a string, this automatically returns the channel's mention instead of the Channel object. - * @returns {string} - * @example - * // Outputs: Hello from #general - * console.log(`Hello from ${channel}`); - * @example - * // Outputs: Hello from #general - * console.log('Hello from ' + channel); - */ - toString() { - return `<#${this.id}>`; - } -} - -module.exports = GuildChannel; - - -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { - -const TextBasedChannel = __webpack_require__(12); -const Role = __webpack_require__(8); -const EvaluatedPermissions = __webpack_require__(16); -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); -const Presence = __webpack_require__(7).Presence; - -/** - * Represents a member of a guild on Discord - * @implements {TextBasedChannel} - */ -class GuildMember { - constructor(guild, data) { - /** - * The Client that instantiated this GuildMember - * @name GuildMember#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: guild.client }); - - /** - * The guild that this member is part of - * @type {Guild} - */ - this.guild = guild; - - /** - * The user that this guild member instance Represents - * @type {User} - */ - this.user = {}; - - this._roles = []; - if (data) this.setup(data); - - /** - * The ID of the last message sent by the member in their guild, if one was sent. - * @type {?string} - */ - this.lastMessageID = null; - } - - setup(data) { - /** - * Whether this member is deafened server-wide - * @type {boolean} - */ - this.serverDeaf = data.deaf; - - /** - * Whether this member is muted server-wide - * @type {boolean} - */ - this.serverMute = data.mute; - - /** - * Whether this member is self-muted - * @type {boolean} - */ - this.selfMute = data.self_mute; - - /** - * Whether this member is self-deafened - * @type {boolean} - */ - this.selfDeaf = data.self_deaf; - - /** - * The voice session ID of this member, if any - * @type {?string} - */ - this.voiceSessionID = data.session_id; - - /** - * The voice channel ID of this member, if any - * @type {?string} - */ - this.voiceChannelID = data.channel_id; - - /** - * Whether this member is speaking - * @type {boolean} - */ - this.speaking = false; - - /** - * The nickname of this guild member, if they have one - * @type {?string} - */ - this.nickname = data.nick || null; - - /** - * The timestamp the member joined the guild at - * @type {number} - */ - this.joinedTimestamp = new Date(data.joined_at).getTime(); - - this.user = data.user; - this._roles = data.roles; - } - - /** - * The time the member joined the guild - * @type {Date} - * @readonly - */ - get joinedAt() { - return new Date(this.joinedTimestamp); - } - - /** - * The presence of this guild member - * @type {Presence} - * @readonly - */ - get presence() { - return this.frozenPresence || this.guild.presences.get(this.id) || new Presence(); - } - - /** - * A list of roles that are applied to this GuildMember, mapped by the role ID. - * @type {Collection} - * @readonly - */ - get roles() { - const list = new Collection(); - const everyoneRole = this.guild.roles.get(this.guild.id); - - if (everyoneRole) list.set(everyoneRole.id, everyoneRole); - - for (const roleID of this._roles) { - const role = this.guild.roles.get(roleID); - if (role) list.set(role.id, role); - } - - return list; - } - - /** - * The role of the member with the highest position. - * @type {Role} - * @readonly - */ - get highestRole() { - return this.roles.reduce((prev, role) => !prev || role.comparePositionTo(prev) > 0 ? role : prev); - } - - /** - * Whether this member is muted in any way - * @type {boolean} - * @readonly - */ - get mute() { - return this.selfMute || this.serverMute; - } - - /** - * Whether this member is deafened in any way - * @type {boolean} - * @readonly - */ - get deaf() { - return this.selfDeaf || this.serverDeaf; - } - - /** - * The voice channel this member is in, if any - * @type {?VoiceChannel} - * @readonly - */ - get voiceChannel() { - return this.guild.channels.get(this.voiceChannelID); - } - - /** - * The ID of this user - * @type {string} - * @readonly - */ - get id() { - return this.user.id; - } - - /** - * The nickname of the member, or their username if they don't have one - * @type {string} - * @readonly - */ - get displayName() { - return this.nickname || this.user.username; - } - - /** - * The overall set of permissions for the guild member, taking only roles into account - * @type {EvaluatedPermissions} - * @readonly - */ - get permissions() { - if (this.user.id === this.guild.ownerID) return new EvaluatedPermissions(this, Constants.ALL_PERMISSIONS); - - let permissions = 0; - const roles = this.roles; - for (const role of roles.values()) permissions |= role.permissions; - - const admin = Boolean(permissions & Constants.PermissionFlags.ADMINISTRATOR); - if (admin) permissions = Constants.ALL_PERMISSIONS; - - return new EvaluatedPermissions(this, permissions); - } - - /** - * Whether the member is kickable by the client user. - * @type {boolean} - * @readonly - */ - get kickable() { - if (this.user.id === this.guild.ownerID) return false; - if (this.user.id === this.client.user.id) return false; - const clientMember = this.guild.member(this.client.user); - if (!clientMember.hasPermission(Constants.PermissionFlags.KICK_MEMBERS)) return false; - return clientMember.highestRole.comparePositionTo(this.highestRole) > 0; - } - - /** - * Whether the member is bannable by the client user. - * @type {boolean} - * @readonly - */ - get bannable() { - if (this.user.id === this.guild.ownerID) return false; - if (this.user.id === this.client.user.id) return false; - const clientMember = this.guild.member(this.client.user); - if (!clientMember.hasPermission(Constants.PermissionFlags.BAN_MEMBERS)) return false; - return clientMember.highestRole.comparePositionTo(this.highestRole) > 0; - } - - /** - * Returns `channel.permissionsFor(guildMember)`. Returns evaluated permissions for a member in a guild channel. - * @param {ChannelResolvable} channel Guild channel to use as context - * @returns {?EvaluatedPermissions} - */ - permissionsIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - if (!channel || !channel.guild) throw new Error('Could not resolve channel to a guild channel.'); - return channel.permissionsFor(this); - } - - /** - * Checks if any of the member's roles have a permission. - * @param {PermissionResolvable} permission The permission to check for - * @param {boolean} [explicit=false] Whether to require the roles to explicitly have the exact permission - * @returns {boolean} - */ - hasPermission(permission, explicit = false) { - if (!explicit && this.user.id === this.guild.ownerID) return true; - return this.roles.some(r => r.hasPermission(permission, explicit)); - } - - /** - * Checks whether the roles of the member allows them to perform specific actions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions - * @returns {boolean} - */ - hasPermissions(permissions, explicit = false) { - if (!explicit && this.user.id === this.guild.ownerID) return true; - return permissions.every(p => this.hasPermission(p, explicit)); - } - - /** - * Checks whether the roles of the member allows them to perform specific actions, and lists any missing permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions - * @returns {PermissionResolvable[]} - */ - missingPermissions(permissions, explicit = false) { - return permissions.filter(p => !this.hasPermission(p, explicit)); - } - - /** - * Edit a guild member - * @param {GuildmemberEditData} data The data to edit the member with - * @returns {Promise} - */ - edit(data) { - return this.client.rest.methods.updateGuildMember(this, data); - } - - /** - * Mute/unmute a user - * @param {boolean} mute Whether or not the member should be muted - * @returns {Promise} - */ - setMute(mute) { - return this.edit({ mute }); - } - - /** - * Deafen/undeafen a user - * @param {boolean} deaf Whether or not the member should be deafened - * @returns {Promise} - */ - setDeaf(deaf) { - return this.edit({ deaf }); - } - - /** - * Moves the guild member to the given channel. - * @param {ChannelResolvable} channel The channel to move the member to - * @returns {Promise} - */ - setVoiceChannel(channel) { - return this.edit({ channel }); - } - - /** - * Sets the roles applied to the member. - * @param {Collection|Role[]|string[]} roles The roles or role IDs to apply - * @returns {Promise} - */ - setRoles(roles) { - return this.edit({ roles }); - } - - /** - * Adds a single role to the member. - * @param {Role|string} role The role or ID of the role to add - * @returns {Promise} - */ - addRole(role) { - if (!(role instanceof Role)) role = this.guild.roles.get(role); - return this.client.rest.methods.addMemberRole(this, role); - } - - /** - * Adds multiple roles to the member. - * @param {Collection|Role[]|string[]} roles The roles or role IDs to add - * @returns {Promise} - */ - addRoles(roles) { - let allRoles; - if (roles instanceof Collection) { - allRoles = this._roles.slice(); - for (const role of roles.values()) allRoles.push(role.id); - } else { - allRoles = this._roles.concat(roles); - } - return this.edit({ roles: allRoles }); - } - - /** - * Removes a single role from the member. - * @param {Role|string} role The role or ID of the role to remove - * @returns {Promise} - */ - removeRole(role) { - if (!(role instanceof Role)) role = this.guild.roles.get(role); - return this.client.rest.methods.removeMemberRole(this, role); - } - - /** - * Removes multiple roles from the member. - * @param {Collection|Role[]|string[]} roles The roles or role IDs to remove - * @returns {Promise} - */ - removeRoles(roles) { - const allRoles = this._roles.slice(); - if (roles instanceof Collection) { - for (const role of roles.values()) { - const index = allRoles.indexOf(role.id); - if (index >= 0) allRoles.splice(index, 1); - } - } else { - for (const role of roles) { - const index = allRoles.indexOf(role instanceof Role ? role.id : role); - if (index >= 0) allRoles.splice(index, 1); - } - } - return this.edit({ roles: allRoles }); - } - - /** - * Set the nickname for the guild member - * @param {string} nick The nickname for the guild member - * @returns {Promise} - */ - setNickname(nick) { - return this.edit({ nick }); - } - - /** - * Deletes any DMs with this guild member - * @returns {Promise} - */ - deleteDM() { - return this.client.rest.methods.deleteChannel(this); - } - - /** - * Kick this member from the guild - * @returns {Promise} - */ - kick() { - return this.client.rest.methods.kickGuildMember(this.guild, this); - } - - /** - * Ban this guild member - * @param {number} [deleteDays=0] The amount of days worth of messages from this member that should - * also be deleted. Between `0` and `7`. - * @returns {Promise} - * @example - * // ban a guild member - * guildMember.ban(7); - */ - ban(deleteDays = 0) { - return this.client.rest.methods.banGuildMember(this.guild, this, deleteDays); - } - - /** - * When concatenated with a string, this automatically concatenates the user's mention instead of the Member object. - * @returns {string} - * @example - * // logs: Hello from <@123456789>! - * console.log(`Hello from ${member}!`); - */ - toString() { - return `<@${this.nickname ? '!' : ''}${this.user.id}>`; - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - send() { return; } - sendMessage() { return; } - sendEmbed() { return; } - sendFile() { return; } - sendCode() { return; } -} - -TextBasedChannel.applyToClass(GuildMember); - -module.exports = GuildMember; - - -/***/ }, -/* 15 */ -/***/ function(module, exports) { - -module.exports = function escapeMarkdown(text, onlyCodeBlock = false, onlyInlineCode = false) { - if (onlyCodeBlock) return text.replace(/```/g, '`\u200b``'); - if (onlyInlineCode) return text.replace(/\\(`|\\)/g, '$1').replace(/(`|\\)/g, '\\$1'); - return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '\\$1'); -}; - - -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -/** - * The final evaluated permissions for a member in a channel - */ -class EvaluatedPermissions { - constructor(member, raw) { - /** - * The member this permissions refer to - * @type {GuildMember} - */ - this.member = member; - - /** - * A number representing the packed permissions - * @type {number} - */ - this.raw = raw; - } - - /** - * Get an object mapping permission name, e.g. `READ_MESSAGES` to a boolean - whether the user - * can perform this or not. - * @returns {Object} - */ - serialize() { - const serializedPermissions = {}; - for (const permissionName in Constants.PermissionFlags) { - serializedPermissions[permissionName] = this.hasPermission(permissionName); - } - return serializedPermissions; - } - - /** - * Checks whether the user has a certain permission, e.g. `READ_MESSAGES`. - * @param {PermissionResolvable} permission The permission to check for - * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permission - * @returns {boolean} - */ - hasPermission(permission, explicit = false) { - permission = this.member.client.resolver.resolvePermission(permission); - if (!explicit && (this.raw & Constants.PermissionFlags.ADMINISTRATOR) > 0) return true; - return (this.raw & permission) > 0; - } - - /** - * Checks whether the user has all specified permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions - * @returns {boolean} - */ - hasPermissions(permissions, explicit = false) { - return permissions.every(p => this.hasPermission(p, explicit)); - } - - /** - * Checks whether the user has all specified permissions, and lists any missing permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions - * @returns {PermissionResolvable[]} - */ - missingPermissions(permissions, explicit = false) { - return permissions.filter(p => !this.hasPermission(p, explicit)); - } -} - -module.exports = EvaluatedPermissions; - - -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { - -const User = __webpack_require__(6); -const Role = __webpack_require__(8); -const Emoji = __webpack_require__(10); -const Presence = __webpack_require__(7).Presence; -const GuildMember = __webpack_require__(14); -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); -const cloneObject = __webpack_require__(4); -const arraysEqual = __webpack_require__(153); - -/** - * Represents a guild (or a server) on Discord. - * It's recommended to see if a guild is available before performing operations or reading data from it. You can - * check this with `guild.available`. - */ -class Guild { - constructor(client, data) { - /** - * The Client that created the instance of the the Guild. - * @name Guild#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * A collection of members that are in this guild. The key is the member's ID, the value is the member. - * @type {Collection} - */ - this.members = new Collection(); - - /** - * A collection of channels that are in this guild. The key is the channel's ID, the value is the channel. - * @type {Collection} - */ - this.channels = new Collection(); - - /** - * A collection of roles that are in this guild. The key is the role's ID, the value is the role. - * @type {Collection} - */ - this.roles = new Collection(); - - /** - * A collection of presences in this guild - * @type {Collection} - */ - this.presences = new Collection(); - - if (!data) return; - if (data.unavailable) { - /** - * Whether the guild is available to access. If it is not available, it indicates a server outage. - * @type {boolean} - */ - this.available = false; - - /** - * The Unique ID of the Guild, useful for comparisons. - * @type {string} - */ - this.id = data.id; - } else { - this.available = true; - this.setup(data); - } - } - - /** - * Sets up the Guild - * @param {*} data The raw data of the guild - * @private - */ - setup(data) { - /** - * The name of the guild - * @type {string} - */ - this.name = data.name; - - /** - * The hash of the guild icon, or null if there is no icon. - * @type {?string} - */ - this.icon = data.icon; - - /** - * The hash of the guild splash image, or null if no splash (VIP only) - * @type {?string} - */ - this.splash = data.splash; - - /** - * The region the guild is located in - * @type {string} - */ - this.region = data.region; - - /** - * The full amount of members in this guild as of `READY` - * @type {number} - */ - this.memberCount = data.member_count || this.memberCount; - - /** - * Whether the guild is "large" (has more than 250 members) - * @type {boolean} - */ - this.large = data.large || this.large; - - /** - * An array of guild features. - * @type {Object[]} - */ - this.features = data.features; - - /** - * The ID of the application that created this guild (if applicable) - * @type {?string} - */ - this.applicationID = data.application_id; - - /** - * A collection of emojis that are in this guild. The key is the emoji's ID, the value is the emoji. - * @type {Collection} - */ - this.emojis = new Collection(); - for (const emoji of data.emojis) this.emojis.set(emoji.id, new Emoji(this, emoji)); - - /** - * The time in seconds before a user is counted as "away from keyboard". - * @type {?number} - */ - this.afkTimeout = data.afk_timeout; - - /** - * The ID of the voice channel where AFK members are moved. - * @type {?string} - */ - this.afkChannelID = data.afk_channel_id; - - /** - * Whether embedded images are enabled on this guild. - * @type {boolean} - */ - this.embedEnabled = data.embed_enabled; - - /** - * The verification level of the guild. - * @type {number} - */ - this.verificationLevel = data.verification_level; - - /** - * The timestamp the client user joined the guild at - * @type {number} - */ - this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp; - - this.id = data.id; - this.available = !data.unavailable; - this.features = data.features || this.features || []; - - if (data.members) { - this.members.clear(); - for (const guildUser of data.members) this._addMember(guildUser, false); - } - - if (data.owner_id) { - /** - * The user ID of this guild's owner. - * @type {string} - */ - this.ownerID = data.owner_id; - } - - if (data.channels) { - this.channels.clear(); - for (const channel of data.channels) this.client.dataManager.newChannel(channel, this); - } - - if (data.roles) { - this.roles.clear(); - for (const role of data.roles) { - const newRole = new Role(this, role); - this.roles.set(newRole.id, newRole); - } - } - - if (data.presences) { - for (const presence of data.presences) { - this._setPresence(presence.user.id, presence); - } - } - - this._rawVoiceStates = new Collection(); - if (data.voice_states) { - for (const voiceState of data.voice_states) { - this._rawVoiceStates.set(voiceState.user_id, voiceState); - const member = this.members.get(voiceState.user_id); - if (member) { - member.serverMute = voiceState.mute; - member.serverDeaf = voiceState.deaf; - member.selfMute = voiceState.self_mute; - member.selfDeaf = voiceState.self_deaf; - member.voiceSessionID = voiceState.session_id; - member.voiceChannelID = voiceState.channel_id; - this.channels.get(voiceState.channel_id).members.set(member.user.id, member); - } - } - } - } - - /** - * The timestamp the guild was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return (this.id / 4194304) + 1420070400000; - } - - /** - * The time the guild was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The time the client user joined the guild - * @type {Date} - * @readonly - */ - get joinedAt() { - return new Date(this.joinedTimestamp); - } - - /** - * Gets the URL to this guild's icon (if it has one, otherwise it returns null) - * @type {?string} - * @readonly - */ - get iconURL() { - if (!this.icon) return null; - return Constants.Endpoints.guildIcon(this.id, this.icon); - } - - /** - * Gets the URL to this guild's splash (if it has one, otherwise it returns null) - * @type {?string} - * @readonly - */ - get splashURL() { - if (!this.splash) return null; - return Constants.Endpoints.guildSplash(this.id, this.splash); - } - - /** - * The owner of the guild - * @type {GuildMember} - * @readonly - */ - get owner() { - return this.members.get(this.ownerID); - } - - /** - * If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection. - * @type {?VoiceConnection} - * @readonly - */ - get voiceConnection() { - if (this.client.browser) return null; - return this.client.voice.connections.get(this.id) || null; - } - - /** - * The `#general` GuildChannel of the server. - * @type {GuildChannel} - * @readonly - */ - get defaultChannel() { - return this.channels.get(this.id); - } - - /** - * Returns the GuildMember form of a User object, if the user is present in the guild. - * @param {UserResolvable} user The user that you want to obtain the GuildMember of - * @returns {?GuildMember} - * @example - * // get the guild member of a user - * const member = guild.member(message.author); - */ - member(user) { - return this.client.resolver.resolveGuildMember(this, user); - } - - /** - * Fetch a collection of banned users in this guild. - * @returns {Promise>} - */ - fetchBans() { - return this.client.rest.methods.getGuildBans(this); - } - - /** - * Fetch a collection of invites to this guild. Resolves with a collection mapping invites by their codes. - * @returns {Promise>} - */ - fetchInvites() { - return this.client.rest.methods.getGuildInvites(this); - } - - /** - * Fetch all webhooks for the guild. - * @returns {Collection} - */ - fetchWebhooks() { - return this.client.rest.methods.getGuildWebhooks(this); - } - - /** - * Fetch a single guild member from a user. - * @param {UserResolvable} user The user to fetch the member for - * @returns {Promise} - */ - fetchMember(user) { - if (this._fetchWaiter) return Promise.reject(new Error('Already fetching guild members.')); - user = this.client.resolver.resolveUser(user); - if (!user) return Promise.reject(new Error('User is not cached. Use Client.fetchUser first.')); - if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id)); - return this.client.rest.methods.getGuildMember(this, user); - } - - /** - * Fetches all the members in the guild, even if they are offline. If the guild has less than 250 members, - * this should not be necessary. - * @param {string} [query=''] An optional query to provide when fetching members - * @returns {Promise} - */ - fetchMembers(query = '') { - return new Promise((resolve, reject) => { - if (this._fetchWaiter) throw new Error('Already fetching guild members in ${this.id}.'); - if (this.memberCount === this.members.size) { - resolve(this); - return; - } - this._fetchWaiter = resolve; - this.client.ws.send({ - op: Constants.OPCodes.REQUEST_GUILD_MEMBERS, - d: { - guild_id: this.id, - query, - limit: 0, - }, - }); - this._checkChunks(); - this.client.setTimeout(() => reject(new Error('Members didn\'t arrive in time.')), 120 * 1000); - }); - } - - /** - * The data for editing a guild - * @typedef {Object} GuildEditData - * @property {string} [name] The name of the guild - * @property {string} [region] The region of the guild - * @property {number} [verificationLevel] The verification level of the guild - * @property {ChannelResolvable} [afkChannel] The AFK channel of the guild - * @property {number} [afkTimeout] The AFK timeout of the guild - * @property {Base64Resolvable} [icon] The icon of the guild - * @property {GuildMemberResolvable} [owner] The owner of the guild - * @property {Base64Resolvable} [splash] The splash screen of the guild - */ - - /** - * Updates the Guild with new information - e.g. a new name. - * @param {GuildEditData} data The data to update the guild with - * @returns {Promise} - * @example - * // set the guild name and region - * guild.edit({ - * name: 'Discord Guild', - * region: 'london', - * }) - * .then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`)) - * .catch(console.error); - */ - edit(data) { - return this.client.rest.methods.updateGuild(this, data); - } - - /** - * Edit the name of the guild. - * @param {string} name The new name of the guild - * @returns {Promise} - * @example - * // edit the guild name - * guild.setName('Discord Guild') - * .then(updated => console.log(`Updated guild name to ${guild.name}`)) - * .catch(console.error); - */ - setName(name) { - return this.edit({ name }); - } - - /** - * Edit the region of the guild. - * @param {string} region The new region of the guild. - * @returns {Promise} - * @example - * // edit the guild region - * guild.setRegion('london') - * .then(updated => console.log(`Updated guild region to ${guild.region}`)) - * .catch(console.error); - */ - setRegion(region) { - return this.edit({ region }); - } - - /** - * Edit the verification level of the guild. - * @param {number} verificationLevel The new verification level of the guild - * @returns {Promise} - * @example - * // edit the guild verification level - * guild.setVerificationLevel(1) - * .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`)) - * .catch(console.error); - */ - setVerificationLevel(verificationLevel) { - return this.edit({ verificationLevel }); - } - - /** - * Edit the AFK channel of the guild. - * @param {ChannelResolvable} afkChannel The new AFK channel - * @returns {Promise} - * @example - * // edit the guild AFK channel - * guild.setAFKChannel(channel) - * .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`)) - * .catch(console.error); - */ - setAFKChannel(afkChannel) { - return this.edit({ afkChannel }); - } - - /** - * Edit the AFK timeout of the guild. - * @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK - * @returns {Promise} - * @example - * // edit the guild AFK channel - * guild.setAFKTimeout(60) - * .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`)) - * .catch(console.error); - */ - setAFKTimeout(afkTimeout) { - return this.edit({ afkTimeout }); - } - - /** - * Set a new guild icon. - * @param {Base64Resolvable} icon The new icon of the guild - * @returns {Promise} - * @example - * // edit the guild icon - * guild.setIcon(fs.readFileSync('./icon.png')) - * .then(updated => console.log('Updated the guild icon')) - * .catch(console.error); - */ - setIcon(icon) { - return this.edit({ icon }); - } - - /** - * Sets a new owner of the guild. - * @param {GuildMemberResolvable} owner The new owner of the guild - * @returns {Promise} - * @example - * // edit the guild owner - * guild.setOwner(guilds.members[0]) - * .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`)) - * .catch(console.error); - */ - setOwner(owner) { - return this.edit({ owner }); - } - - /** - * Set a new guild splash screen. - * @param {Base64Resolvable} splash The new splash screen of the guild - * @returns {Promise} - * @example - * // edit the guild splash - * guild.setIcon(fs.readFileSync('./splash.png')) - * .then(updated => console.log('Updated the guild splash')) - * .catch(console.error); - */ - setSplash(splash) { - return this.edit({ splash }); - } - - /** - * Bans a user from the guild. - * @param {UserResolvable} user The user to ban - * @param {number} [deleteDays=0] The amount of days worth of messages from this user that should - * also be deleted. Between `0` and `7`. - * @returns {Promise} Result object will be resolved as specifically as possible. - * If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot - * be resolved, the user ID will be the result. - * @example - * // ban a user - * guild.ban('123123123123'); - */ - ban(user, deleteDays = 0) { - return this.client.rest.methods.banGuildMember(this, user, deleteDays); - } - - /** - * Unbans a user from the guild. - * @param {UserResolvable} user The user to unban - * @returns {Promise} - * @example - * // unban a user - * guild.unban('123123123123') - * .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`)) - * .catch(reject); - */ - unban(user) { - return this.client.rest.methods.unbanGuildMember(this, user); - } - - /** - * Prunes members from the guild based on how long they have been inactive. - * @param {number} days Number of days of inactivity required to kick - * @param {boolean} [dry=false] If true, will return number of users that will be kicked, without actually doing it - * @returns {Promise} The number of members that were/will be kicked - * @example - * // see how many members will be pruned - * guild.pruneMembers(12, true) - * .then(pruned => console.log(`This will prune ${pruned} people!`); - * .catch(console.error); - * @example - * // actually prune the members - * guild.pruneMembers(12) - * .then(pruned => console.log(`I just pruned ${pruned} people!`); - * .catch(console.error); - */ - pruneMembers(days, dry = false) { - if (typeof days !== 'number') throw new TypeError('Days must be a number.'); - return this.client.rest.methods.pruneGuildMembers(this, days, dry); - } - - /** - * Syncs this guild (already done automatically every 30 seconds). - * This is only available when using a user account. - */ - sync() { - if (!this.client.user.bot) this.client.syncGuilds([this]); - } - - /** - * Creates a new channel in the guild. - * @param {string} name The name of the new channel - * @param {string} type The type of the new channel, either `text` or `voice` - * @param {Array} overwrites Permission overwrites to apply to the new channel - * @returns {Promise} - * @example - * // create a new text channel - * guild.createChannel('new-general', 'text') - * .then(channel => console.log(`Created new channel ${channel}`)) - * .catch(console.error); - */ - createChannel(name, type, overwrites) { - return this.client.rest.methods.createChannel(this, name, type, overwrites); - } - - /** - * Creates a new role in the guild, and optionally updates it with the given information. - * @param {RoleData} [data] The data to update the role with - * @returns {Promise} - * @example - * // create a new role - * guild.createRole() - * .then(role => console.log(`Created role ${role}`)) - * .catch(console.error); - * @example - * // create a new role with data - * guild.createRole({ name: 'Super Cool People' }) - * .then(role => console.log(`Created role ${role}`)) - * .catch(console.error) - */ - createRole(data) { - const create = this.client.rest.methods.createGuildRole(this); - if (!data) return create; - return create.then(role => role.edit(data)); - } - - /** - * Creates a new custom emoji in the guild. - * @param {BufferResolvable} attachment The image for the emoji. - * @param {string} name The name for the emoji. - * @returns {Promise} The created emoji. - * @example - * // create a new emoji from a url - * guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip') - * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) - * .catch(console.error); - * @example - * // create a new emoji from a file on your computer - * guild.createEmoji('./memes/banana.png', 'banana') - * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) - * .catch(console.error); - */ - createEmoji(attachment, name) { - return new Promise(resolve => { - if (attachment.startsWith('data:')) { - resolve(this.client.rest.methods.createEmoji(this, attachment, name)); - } else { - this.client.resolver.resolveBuffer(attachment).then(data => - resolve(this.client.rest.methods.createEmoji(this, data, name)) - ); - } - }); - } - - /** - * Delete an emoji. - * @param {Emoji|string} emoji The emoji to delete. - * @returns {Promise} - */ - deleteEmoji(emoji) { - if (!(emoji instanceof Emoji)) emoji = this.emojis.get(emoji); - return this.client.rest.methods.deleteEmoji(emoji); - } - - /** - * Causes the Client to leave the guild. - * @returns {Promise} - * @example - * // leave a guild - * guild.leave() - * .then(g => console.log(`Left the guild ${g}`)) - * .catch(console.error); - */ - leave() { - return this.client.rest.methods.leaveGuild(this); - } - - /** - * Causes the Client to delete the guild. - * @returns {Promise} - * @example - * // delete a guild - * guild.delete() - * .then(g => console.log(`Deleted the guild ${g}`)) - * .catch(console.error); - */ - delete() { - return this.client.rest.methods.deleteGuild(this); - } - - /** - * Set the position of a role in this guild - * @param {string|Role} role the role to edit, can be a role object or a role ID. - * @param {number} position the new position of the role - * @returns {Promise} - */ - setRolePosition(role, position) { - if (typeof role === 'string') { - role = this.roles.get(role); - if (!role) return Promise.reject(new Error('Supplied role is not a role or string.')); - } - - position = Number(position); - if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); - - const lowestAffected = Math.min(role.position, position); - const highestAffected = Math.max(role.position, position); - - const rolesToUpdate = this.roles.filter(r => r.position >= lowestAffected && r.position <= highestAffected); - - // stop role positions getting stupidly inflated - if (position > role.position) { - position = rolesToUpdate.first().position; - } else { - position = rolesToUpdate.last().position; - } - - const updatedRoles = []; - - for (const uRole of rolesToUpdate.values()) { - updatedRoles.push({ - id: uRole.id, - position: uRole.id === role.id ? position : uRole.position + (position < role.position ? 1 : -1), - }); - } - - return this.client.rest.methods.setRolePositions(this.id, updatedRoles); - } - - /** - * Whether this Guild equals another Guild. It compares all properties, so for most operations - * it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often - * what most users need. - * @param {Guild} guild Guild to compare with - * @returns {boolean} - */ - equals(guild) { - let equal = - guild && - this.id === guild.id && - this.available === !guild.unavailable && - this.splash === guild.splash && - this.region === guild.region && - this.name === guild.name && - this.memberCount === guild.member_count && - this.large === guild.large && - this.icon === guild.icon && - arraysEqual(this.features, guild.features) && - this.ownerID === guild.owner_id && - this.verificationLevel === guild.verification_level && - this.embedEnabled === guild.embed_enabled; - - if (equal) { - if (this.embedChannel) { - if (this.embedChannel.id !== guild.embed_channel_id) equal = false; - } else if (guild.embed_channel_id) { - equal = false; - } - } - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the guild's name instead of the Guild object. - * @returns {string} - * @example - * // logs: Hello from My Guild! - * console.log(`Hello from ${guild}!`); - * @example - * // logs: Hello from My Guild! - * console.log(`Hello from ' + guild + '!'); - */ - toString() { - return this.name; - } - - _addMember(guildUser, emitEvent = true) { - const existing = this.members.has(guildUser.user.id); - if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user); - - guildUser.joined_at = guildUser.joined_at || 0; - const member = new GuildMember(this, guildUser); - this.members.set(member.id, member); - - if (this._rawVoiceStates && this._rawVoiceStates.has(member.user.id)) { - const voiceState = this._rawVoiceStates.get(member.user.id); - member.serverMute = voiceState.mute; - member.serverDeaf = voiceState.deaf; - member.selfMute = voiceState.self_mute; - member.selfDeaf = voiceState.self_deaf; - member.voiceSessionID = voiceState.session_id; - member.voiceChannelID = voiceState.channel_id; - if (this.client.channels.has(voiceState.channel_id)) { - this.client.channels.get(voiceState.channel_id).members.set(member.user.id, member); - } else { - this.client.emit('warn', `Member ${member.id} added in guild ${this.id} with an uncached voice channel`); - } - } - - /** - * Emitted whenever a user joins a guild. - * @event Client#guildMemberAdd - * @param {GuildMember} member The member that has joined a guild - */ - if (this.client.ws.status === Constants.Status.READY && emitEvent && !existing) { - this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member); - } - - this._checkChunks(); - return member; - } - - _updateMember(member, data) { - const oldMember = cloneObject(member); - - if (data.roles) member._roles = data.roles; - if (typeof data.nick !== 'undefined') member.nickname = data.nick; - - const notSame = member.nickname !== oldMember.nickname || !arraysEqual(member._roles, oldMember._roles); - - if (this.client.ws.status === Constants.Status.READY && notSame) { - /** - * Emitted whenever a guild member changes - i.e. new role, removed role, nickname - * @event Client#guildMemberUpdate - * @param {GuildMember} oldMember The member before the update - * @param {GuildMember} newMember The member after the update - */ - this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member); - } - - return { - old: oldMember, - mem: member, - }; - } - - _removeMember(guildMember) { - this.members.delete(guildMember.id); - this._checkChunks(); - } - - _memberSpeakUpdate(user, speaking) { - const member = this.members.get(user); - if (member && member.speaking !== speaking) { - member.speaking = speaking; - /** - * Emitted once a guild member starts/stops speaking - * @event Client#guildMemberSpeaking - * @param {GuildMember} member The member that started/stopped speaking - * @param {boolean} speaking Whether or not the member is speaking - */ - this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking); - } - } - - _setPresence(id, presence) { - if (this.presences.get(id)) { - this.presences.get(id).update(presence); - return; - } - this.presences.set(id, new Presence(presence)); - } - - _checkChunks() { - if (this._fetchWaiter) { - if (this.members.size === this.memberCount) { - this._fetchWaiter(this); - this._fetchWaiter = null; - } - } - } -} - -module.exports = Guild; - - -/***/ }, -/* 18 */ -/***/ function(module, exports) { - -/** - * Represents a limited emoji set used for both custom and unicode emojis. Custom emojis - * will use this class opposed to the Emoji class when the client doesn't know enough - * information about them. - */ -class ReactionEmoji { - constructor(reaction, name, id) { - /** - * The message reaction this emoji refers to - * @type {MessageReaction} - */ - this.reaction = reaction; - - /** - * The name of this reaction emoji. - * @type {string} - */ - this.name = name; - - /** - * The ID of this reaction emoji. - * @type {string} - */ - this.id = id; - } - - /** - * The identifier of this emoji, used for message reactions - * @readonly - * @type {string} - */ - get identifier() { - if (this.id) return `${this.name}:${this.id}`; - return encodeURIComponent(this.name); - } - - /** - * Creates the text required to form a graphical emoji on Discord. - * @example - * // send the emoji used in a reaction to the channel the reaction is part of - * reaction.message.channel.sendMessage(`The emoji used is ${reaction.emoji}`); - * @returns {string} - */ - toString() { - return this.id ? `<:${this.name}:${this.id}>` : this.name; - } -} - -module.exports = ReactionEmoji; - - -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { - -const path = __webpack_require__(23); -const escapeMarkdown = __webpack_require__(15); - -/** - * Represents a webhook - */ -class Webhook { - constructor(client, dataOrID, token) { - if (client) { - /** - * The Client that instantiated the Webhook - * @name Webhook#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - if (dataOrID) this.setup(dataOrID); - } else { - this.id = dataOrID; - this.token = token; - Object.defineProperty(this, 'client', { value: this }); - } - } - - setup(data) { - /** - * The name of the webhook - * @type {string} - */ - this.name = data.name; - - /** - * The token for the webhook - * @type {string} - */ - this.token = data.token; - - /** - * The avatar for the webhook - * @type {string} - */ - this.avatar = data.avatar; - - /** - * The ID of the webhook - * @type {string} - */ - this.id = data.id; - - /** - * The guild the webhook belongs to - * @type {string} - */ - this.guildID = data.guild_id; - - /** - * The channel the webhook belongs to - * @type {string} - */ - this.channelID = data.channel_id; - - /** - * The owner of the webhook - * @type {User} - */ - if (data.user) this.owner = data.user; - } - - /** - * Options that can be passed into sendMessage, sendTTSMessage, sendFile, sendCode - * @typedef {Object} WebhookMessageOptions - * @property {boolean} [tts=false] Whether or not the message should be spoken aloud - * @property {boolean} [disableEveryone=this.options.disableEveryone] Whether or not @everyone and @here - * should be replaced with plain-text - */ - - /** - * Send a message with this webhook - * @param {StringResolvable} content The content to send. - * @param {WebhookMessageOptions} [options={}] The options to provide. - * @returns {Promise} - * @example - * // send a message - * webhook.sendMessage('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - sendMessage(content, options = {}) { - return this.client.rest.methods.sendWebhookMessage(this, content, options); - } - - /** - * Send a raw slack message with this webhook - * @param {Object} body The raw body to send. - * @returns {Promise} - * @example - * // send a slack message - * webhook.sendSlackMessage({ - * 'username': 'Wumpus', - * 'attachments': [{ - * 'pretext': 'this looks pretty cool', - * 'color': '#F0F', - * 'footer_icon': 'http://snek.s3.amazonaws.com/topSnek.png', - * 'footer': 'Powered by sneks', - * 'ts': Date.now() / 1000 - * }] - * }).catch(console.error); - */ - sendSlackMessage(body) { - return this.client.rest.methods.sendSlackWebhookMessage(this, body); - } - - /** - * Send a text-to-speech message with this webhook - * @param {StringResolvable} content The content to send - * @param {WebhookMessageOptions} [options={}] The options to provide - * @returns {Promise} - * @example - * // send a TTS message - * webhook.sendTTSMessage('hello!') - * .then(message => console.log(`Sent tts message: ${message.content}`)) - * .catch(console.error); - */ - sendTTSMessage(content, options = {}) { - Object.assign(options, { tts: true }); - return this.client.rest.methods.sendWebhookMessage(this, content, options); - } - - /** - * Send a file with this webhook - * @param {BufferResolvable} attachment The file to send - * @param {string} [fileName="file.jpg"] The name and extension of the file - * @param {StringResolvable} [content] Text message to send with the attachment - * @param {WebhookMessageOptions} [options] The options to provide - * @returns {Promise} - */ - sendFile(attachment, fileName, content, options = {}) { - if (!fileName) { - if (typeof attachment === 'string') { - fileName = path.basename(attachment); - } else if (attachment && attachment.path) { - fileName = path.basename(attachment.path); - } else { - fileName = 'file.jpg'; - } - } - return this.client.resolver.resolveBuffer(attachment).then(file => - this.client.rest.methods.sendWebhookMessage(this, content, options, { - file, - name: fileName, - }) - ); - } - - /** - * Send a code block with this webhook - * @param {string} lang Language for the code block - * @param {StringResolvable} content Content of the code block - * @param {WebhookMessageOptions} options The options to provide - * @returns {Promise} - */ - sendCode(lang, content, options = {}) { - if (options.split) { - if (typeof options.split !== 'object') options.split = {}; - if (!options.split.prepend) options.split.prepend = `\`\`\`${lang || ''}\n`; - if (!options.split.append) options.split.append = '\n```'; - } - content = escapeMarkdown(this.client.resolver.resolveString(content), true); - return this.sendMessage(`\`\`\`${lang || ''}\n${content}\n\`\`\``, options); - } - - /** - * Edit the webhook. - * @param {string} name The new name for the Webhook - * @param {BufferResolvable} avatar The new avatar for the Webhook. - * @returns {Promise} - */ - edit(name = this.name, avatar) { - if (avatar) { - return this.client.resolver.resolveBuffer(avatar).then(file => { - const dataURI = this.client.resolver.resolveBase64(file); - return this.client.rest.methods.editWebhook(this, name, dataURI); - }); - } - return this.client.rest.methods.editWebhook(this, name).then(data => { - this.setup(data); - return this; - }); - } - - /** - * Delete the webhook - * @returns {Promise} - */ - delete() { - return this.client.rest.methods.deleteWebhook(this); - } -} - -module.exports = Webhook; - - -/***/ }, -/* 20 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - - - -var base64 = __webpack_require__(63) -var ieee754 = __webpack_require__(65) -var isArray = __webpack_require__(66) - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} - -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} - -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} - -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that -} - -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} - -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(80))) - -/***/ }, -/* 21 */ -/***/ function(module, exports) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - - -/***/ }, -/* 22 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = { - 2: 'need dictionary', /* Z_NEED_DICT 2 */ - 1: 'stream end', /* Z_STREAM_END 1 */ - 0: '', /* Z_OK 0 */ - '-1': 'file error', /* Z_ERRNO (-1) */ - '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ - '-3': 'data error', /* Z_DATA_ERROR (-3) */ - '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ - '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ - '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ -}; - - -/***/ }, -/* 23 */ -/***/ function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; - - -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; - -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24))) - -/***/ }, -/* 24 */ -/***/ function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { - -/** - * Root reference for iframes. - */ - -var root; -if (typeof window !== 'undefined') { // Browser window - root = window; -} else if (typeof self !== 'undefined') { // Web Worker - root = self; -} else { // Other environments - console.warn("Using browser-only version of superagent in non-browser environment"); - root = this; -} - -var Emitter = __webpack_require__(64); -var RequestBase = __webpack_require__(77); -var isObject = __webpack_require__(26); -var isFunction = __webpack_require__(76); -var ResponseBase = __webpack_require__(78); - -/** - * Noop. - */ - -function noop(){}; - -/** - * Expose `request`. - */ - -var request = exports = module.exports = function(method, url) { - // callback - if ('function' == typeof url) { - return new exports.Request('GET', method).end(url); - } - - // url first - if (1 == arguments.length) { - return new exports.Request('GET', method); - } - - return new exports.Request(method, url); -} - -exports.Request = Request; - -/** - * Determine XHR. - */ - -request.getXHR = function () { - if (root.XMLHttpRequest - && (!root.location || 'file:' != root.location.protocol - || !root.ActiveXObject)) { - return new XMLHttpRequest; - } else { - try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} - try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} - try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} - try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} - } - throw Error("Browser-only verison of superagent could not find XHR"); -}; - -/** - * Removes leading and trailing whitespace, added to support IE. - * - * @param {String} s - * @return {String} - * @api private - */ - -var trim = ''.trim - ? function(s) { return s.trim(); } - : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; - -/** - * Serialize the given `obj`. - * - * @param {Object} obj - * @return {String} - * @api private - */ - -function serialize(obj) { - if (!isObject(obj)) return obj; - var pairs = []; - for (var key in obj) { - pushEncodedKeyValuePair(pairs, key, obj[key]); - } - return pairs.join('&'); -} - -/** - * Helps 'serialize' with serializing arrays. - * Mutates the pairs array. - * - * @param {Array} pairs - * @param {String} key - * @param {Mixed} val - */ - -function pushEncodedKeyValuePair(pairs, key, val) { - if (val != null) { - if (Array.isArray(val)) { - val.forEach(function(v) { - pushEncodedKeyValuePair(pairs, key, v); - }); - } else if (isObject(val)) { - for(var subkey in val) { - pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); - } - } else { - pairs.push(encodeURIComponent(key) - + '=' + encodeURIComponent(val)); - } - } else if (val === null) { - pairs.push(encodeURIComponent(key)); - } -} - -/** - * Expose serialization method. - */ - - request.serializeObject = serialize; - - /** - * Parse the given x-www-form-urlencoded `str`. - * - * @param {String} str - * @return {Object} - * @api private - */ - -function parseString(str) { - var obj = {}; - var pairs = str.split('&'); - var pair; - var pos; - - for (var i = 0, len = pairs.length; i < len; ++i) { - pair = pairs[i]; - pos = pair.indexOf('='); - if (pos == -1) { - obj[decodeURIComponent(pair)] = ''; - } else { - obj[decodeURIComponent(pair.slice(0, pos))] = - decodeURIComponent(pair.slice(pos + 1)); - } - } - - return obj; -} - -/** - * Expose parser. - */ - -request.parseString = parseString; - -/** - * Default MIME type map. - * - * superagent.types.xml = 'application/xml'; - * - */ - -request.types = { - html: 'text/html', - json: 'application/json', - xml: 'application/xml', - urlencoded: 'application/x-www-form-urlencoded', - 'form': 'application/x-www-form-urlencoded', - 'form-data': 'application/x-www-form-urlencoded' -}; - -/** - * Default serialization map. - * - * superagent.serialize['application/xml'] = function(obj){ - * return 'generated xml here'; - * }; - * - */ - - request.serialize = { - 'application/x-www-form-urlencoded': serialize, - 'application/json': JSON.stringify - }; - - /** - * Default parsers. - * - * superagent.parse['application/xml'] = function(str){ - * return { object parsed from str }; - * }; - * - */ - -request.parse = { - 'application/x-www-form-urlencoded': parseString, - 'application/json': JSON.parse -}; - -/** - * Parse the given header `str` into - * an object containing the mapped fields. - * - * @param {String} str - * @return {Object} - * @api private - */ - -function parseHeader(str) { - var lines = str.split(/\r?\n/); - var fields = {}; - var index; - var line; - var field; - var val; - - lines.pop(); // trailing CRLF - - for (var i = 0, len = lines.length; i < len; ++i) { - line = lines[i]; - index = line.indexOf(':'); - field = line.slice(0, index).toLowerCase(); - val = trim(line.slice(index + 1)); - fields[field] = val; - } - - return fields; -} - -/** - * Check if `mime` is json or has +json structured syntax suffix. - * - * @param {String} mime - * @return {Boolean} - * @api private - */ - -function isJSON(mime) { - return /[\/+]json\b/.test(mime); -} - -/** - * Initialize a new `Response` with the given `xhr`. - * - * - set flags (.ok, .error, etc) - * - parse header - * - * Examples: - * - * Aliasing `superagent` as `request` is nice: - * - * request = superagent; - * - * We can use the promise-like API, or pass callbacks: - * - * request.get('/').end(function(res){}); - * request.get('/', function(res){}); - * - * Sending data can be chained: - * - * request - * .post('/user') - * .send({ name: 'tj' }) - * .end(function(res){}); - * - * Or passed to `.send()`: - * - * request - * .post('/user') - * .send({ name: 'tj' }, function(res){}); - * - * Or passed to `.post()`: - * - * request - * .post('/user', { name: 'tj' }) - * .end(function(res){}); - * - * Or further reduced to a single call for simple cases: - * - * request - * .post('/user', { name: 'tj' }, function(res){}); - * - * @param {XMLHTTPRequest} xhr - * @param {Object} options - * @api private - */ - -function Response(req, options) { - options = options || {}; - this.req = req; - this.xhr = this.req.xhr; - // responseText is accessible only if responseType is '' or 'text' and on older browsers - this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') - ? this.xhr.responseText - : null; - this.statusText = this.req.xhr.statusText; - var status = this.xhr.status; - // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - if (status === 1223) { - status = 204; - } - this._setStatusProperties(status); - this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); - // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but - // getResponseHeader still works. so we get content-type even if getting - // other headers fails. - this.header['content-type'] = this.xhr.getResponseHeader('content-type'); - this._setHeaderProperties(this.header); - - if (null === this.text && req._responseType) { - this.body = this.xhr.response; - } else { - this.body = this.req.method != 'HEAD' - ? this._parseBody(this.text ? this.text : this.xhr.response) - : null; - } -} - -ResponseBase(Response.prototype); - -/** - * Parse the given body `str`. - * - * Used for auto-parsing of bodies. Parsers - * are defined on the `superagent.parse` object. - * - * @param {String} str - * @return {Mixed} - * @api private - */ - -Response.prototype._parseBody = function(str){ - var parse = request.parse[this.type]; - if(this.req._parser) { - return this.req._parser(this, str); - } - if (!parse && isJSON(this.type)) { - parse = request.parse['application/json']; - } - return parse && str && (str.length || str instanceof Object) - ? parse(str) - : null; -}; - -/** - * Return an `Error` representative of this response. - * - * @return {Error} - * @api public - */ - -Response.prototype.toError = function(){ - var req = this.req; - var method = req.method; - var url = req.url; - - var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; - var err = new Error(msg); - err.status = this.status; - err.method = method; - err.url = url; - - return err; -}; - -/** - * Expose `Response`. - */ - -request.Response = Response; - -/** - * Initialize a new `Request` with the given `method` and `url`. - * - * @param {String} method - * @param {String} url - * @api public - */ - -function Request(method, url) { - var self = this; - this._query = this._query || []; - this.method = method; - this.url = url; - this.header = {}; // preserves header name case - this._header = {}; // coerces header names to lowercase - this.on('end', function(){ - var err = null; - var res = null; - - try { - res = new Response(self); - } catch(e) { - err = new Error('Parser is unable to parse the response'); - err.parse = true; - err.original = e; - // issue #675: return the raw response if the response parsing fails - if (self.xhr) { - // ie9 doesn't have 'response' property - err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; - // issue #876: return the http status code if the response parsing fails - err.status = self.xhr.status ? self.xhr.status : null; - err.statusCode = err.status; // backwards-compat only - } else { - err.rawResponse = null; - err.status = null; - } - - return self.callback(err); - } - - self.emit('response', res); - - var new_err; - try { - if (!self._isResponseOK(res)) { - new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); - new_err.original = err; - new_err.response = res; - new_err.status = res.status; - } - } catch(e) { - new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android - } - - // #1000 don't catch errors from the callback to avoid double calling it - if (new_err) { - self.callback(new_err, res); - } else { - self.callback(null, res); - } - }); -} - -/** - * Mixin `Emitter` and `RequestBase`. - */ - -Emitter(Request.prototype); -RequestBase(Request.prototype); - -/** - * Set Content-Type to `type`, mapping values from `request.types`. - * - * Examples: - * - * superagent.types.xml = 'application/xml'; - * - * request.post('/') - * .type('xml') - * .send(xmlstring) - * .end(callback); - * - * request.post('/') - * .type('application/xml') - * .send(xmlstring) - * .end(callback); - * - * @param {String} type - * @return {Request} for chaining - * @api public - */ - -Request.prototype.type = function(type){ - this.set('Content-Type', request.types[type] || type); - return this; -}; - -/** - * Set Accept to `type`, mapping values from `request.types`. - * - * Examples: - * - * superagent.types.json = 'application/json'; - * - * request.get('/agent') - * .accept('json') - * .end(callback); - * - * request.get('/agent') - * .accept('application/json') - * .end(callback); - * - * @param {String} accept - * @return {Request} for chaining - * @api public - */ - -Request.prototype.accept = function(type){ - this.set('Accept', request.types[type] || type); - return this; -}; - -/** - * Set Authorization field value with `user` and `pass`. - * - * @param {String} user - * @param {String} pass - * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') - * @return {Request} for chaining - * @api public - */ - -Request.prototype.auth = function(user, pass, options){ - if (!options) { - options = { - type: 'function' === typeof btoa ? 'basic' : 'auto', - } - } - - switch (options.type) { - case 'basic': - this.set('Authorization', 'Basic ' + btoa(user + ':' + pass)); - break; - - case 'auto': - this.username = user; - this.password = pass; - break; - } - return this; -}; - -/** -* Add query-string `val`. -* -* Examples: -* -* request.get('/shoes') -* .query('size=10') -* .query({ color: 'blue' }) -* -* @param {Object|String} val -* @return {Request} for chaining -* @api public -*/ - -Request.prototype.query = function(val){ - if ('string' != typeof val) val = serialize(val); - if (val) this._query.push(val); - return this; -}; - -/** - * Queue the given `file` as an attachment to the specified `field`, - * with optional `options` (or filename). - * - * ``` js - * request.post('/upload') - * .attach('content', new Blob(['hey!'], { type: "text/html"})) - * .end(callback); - * ``` - * - * @param {String} field - * @param {Blob|File} file - * @param {String|Object} options - * @return {Request} for chaining - * @api public - */ - -Request.prototype.attach = function(field, file, options){ - if (this._data) { - throw Error("superagent can't mix .send() and .attach()"); - } - - this._getFormData().append(field, file, options || file.name); - return this; -}; - -Request.prototype._getFormData = function(){ - if (!this._formData) { - this._formData = new root.FormData(); - } - return this._formData; -}; - -/** - * Invoke the callback with `err` and `res` - * and handle arity check. - * - * @param {Error} err - * @param {Response} res - * @api private - */ - -Request.prototype.callback = function(err, res){ - var fn = this._callback; - this.clearTimeout(); - - if (err) { - this.emit('error', err); - } - - fn(err, res); -}; - -/** - * Invoke callback with x-domain error. - * - * @api private - */ - -Request.prototype.crossDomainError = function(){ - var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); - err.crossDomain = true; - - err.status = this.status; - err.method = this.method; - err.url = this.url; - - this.callback(err); -}; - -// This only warns, because the request is still likely to work -Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ - console.warn("This is not supported in browser version of superagent"); - return this; -}; - -// This throws, because it can't send/receive data as expected -Request.prototype.pipe = Request.prototype.write = function(){ - throw Error("Streaming is not supported in browser version of superagent"); -}; - -/** - * Compose querystring to append to req.url - * - * @api private - */ - -Request.prototype._appendQueryString = function(){ - var query = this._query.join('&'); - if (query) { - this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query; - } - - if (this._sort) { - var index = this.url.indexOf('?'); - if (index >= 0) { - var queryArr = this.url.substring(index + 1).split('&'); - if (isFunction(this._sort)) { - queryArr.sort(this._sort); - } else { - queryArr.sort(); - } - this.url = this.url.substring(0, index) + '?' + queryArr.join('&'); - } - } -}; - -/** - * Check if `obj` is a host object, - * we don't want to serialize these :) - * - * @param {Object} obj - * @return {Boolean} - * @api private - */ -Request.prototype._isHost = function _isHost(obj) { - // Native objects stringify to [object File], [object Blob], [object FormData], etc. - return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; -} - -/** - * Initiate request, invoking callback `fn(res)` - * with an instanceof `Response`. - * - * @param {Function} fn - * @return {Request} for chaining - * @api public - */ - -Request.prototype.end = function(fn){ - var self = this; - var xhr = this.xhr = request.getXHR(); - var data = this._formData || this._data; - - if (this._endCalled) { - console.warn("Warning: .end() was called twice. This is not supported in superagent"); - } - this._endCalled = true; - - // store callback - this._callback = fn || noop; - - // state change - xhr.onreadystatechange = function(){ - var readyState = xhr.readyState; - if (readyState >= 2 && self._responseTimeoutTimer) { - clearTimeout(self._responseTimeoutTimer); - } - if (4 != readyState) { - return; - } - - // In IE9, reads to any property (e.g. status) off of an aborted XHR will - // result in the error "Could not complete the operation due to error c00c023f" - var status; - try { status = xhr.status } catch(e) { status = 0; } - - if (!status) { - if (self.timedout || self._aborted) return; - return self.crossDomainError(); - } - self.emit('end'); - }; - - // progress - var handleProgress = function(direction, e) { - if (e.total > 0) { - e.percent = e.loaded / e.total * 100; - } - e.direction = direction; - self.emit('progress', e); - } - if (this.hasListeners('progress')) { - try { - xhr.onprogress = handleProgress.bind(null, 'download'); - if (xhr.upload) { - xhr.upload.onprogress = handleProgress.bind(null, 'upload'); - } - } catch(e) { - // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. - // Reported here: - // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context - } - } - - // querystring - this._appendQueryString(); - - this._setTimeouts(); - - // initiate request - if (this.username && this.password) { - xhr.open(this.method, this.url, true, this.username, this.password); - } else { - xhr.open(this.method, this.url, true); - } - - // CORS - if (this._withCredentials) xhr.withCredentials = true; - - // body - if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { - // serialize stuff - var contentType = this._header['content-type']; - var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; - if (!serialize && isJSON(contentType)) { - serialize = request.serialize['application/json']; - } - if (serialize) data = serialize(data); - } - - // set header fields - for (var field in this.header) { - if (null == this.header[field]) continue; - xhr.setRequestHeader(field, this.header[field]); - } - - if (this._responseType) { - xhr.responseType = this._responseType; - } - - // send stuff - this.emit('request', this); - - // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) - // We need null here if data is undefined - xhr.send(typeof data !== 'undefined' ? data : null); - return this; -}; - -/** - * GET `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -request.get = function(url, data, fn){ - var req = request('GET', url); - if ('function' == typeof data) fn = data, data = null; - if (data) req.query(data); - if (fn) req.end(fn); - return req; -}; - -/** - * HEAD `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -request.head = function(url, data, fn){ - var req = request('HEAD', url); - if ('function' == typeof data) fn = data, data = null; - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; - -/** - * OPTIONS query to `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -request.options = function(url, data, fn){ - var req = request('OPTIONS', url); - if ('function' == typeof data) fn = data, data = null; - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; - -/** - * DELETE `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -function del(url, fn){ - var req = request('DELETE', url); - if (fn) req.end(fn); - return req; -}; - -request['del'] = del; -request['delete'] = del; - -/** - * PATCH `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed} [data] - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -request.patch = function(url, data, fn){ - var req = request('PATCH', url); - if ('function' == typeof data) fn = data, data = null; - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; - -/** - * POST `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed} [data] - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -request.post = function(url, data, fn){ - var req = request('POST', url); - if ('function' == typeof data) fn = data, data = null; - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; - -/** - * PUT `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ - -request.put = function(url, data, fn){ - var req = request('PUT', url); - if ('function' == typeof data) fn = data, data = null; - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; - - -/***/ }, -/* 26 */ -/***/ function(module, exports) { - -/** - * Check if `obj` is an object. - * - * @param {Object} obj - * @return {Boolean} - * @api private - */ - -function isObject(obj) { - return null !== obj && 'object' === typeof obj; -} - -module.exports = isObject; - - -/***/ }, -/* 27 */ -/***/ function(module, exports) { - -module.exports = { - "name": "discord.js", - "version": "11.0.0", - "description": "A powerful library for interacting with the Discord API", - "main": "./src/index", - "types": "./typings/index.d.ts", - "scripts": { - "test": "eslint src && docgen --source src --custom docs/index.yml", - "docs": "docgen --source src --custom docs/index.yml --output docs/docs.json", - "test-docs": "docgen --source src --custom docs", - "lint": "eslint src", - "web-dist": "node ./node_modules/parallel-webpack/bin/run.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/hydrabolt/discord.js.git" - }, - "keywords": [ - "discord", - "api", - "bot", - "client", - "node", - "discordapp" - ], - "author": "Amish Shah ", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/hydrabolt/discord.js/issues" - }, - "homepage": "https://github.com/hydrabolt/discord.js#readme", - "runkitExampleFilename": "./docs/examples/ping.js", - "dependencies": { - "@types/node": "^6.0.0", - "pako": "^1.0.0", - "superagent": "^3.3.0", - "tweetnacl": "^0.14.0", - "ws": "^1.1.0" - }, - "peerDependencies": { - "erlpack": "hammerandchisel/erlpack#master", - "node-opus": "^0.2.0", - "opusscript": "^0.0.1", - "uws": "^0.12.0" - }, - "devDependencies": { - "discord.js-docgen": "hydrabolt/discord.js-docgen#master", - "eslint": "^3.12.0", - "parallel-webpack": "^1.6.0", - "uglify-js": "mishoo/UglifyJS2#harmony", - "webpack": "2.2.0-rc.3" - }, - "engines": { - "node": ">=6.0.0" - }, - "browser": { - "ws": false, - "uws": false, - "erlpack": false, - "opusscript": false, - "node-opus": false, - "tweet-nacl": false, - "src/sharding/Shard.js": false, - "src/sharding/ShardClientUtil.js": false, - "src/sharding/ShardingManager.js": false, - "src/client/voice/dispatcher/StreamDispatcher.js": false, - "src/client/voice/opus/BaseOpusEngine.js": false, - "src/client/voice/opus/NodeOpusEngine.js": false, - "src/client/voice/opus/OpusEngineList.js": false, - "src/client/voice/opus/OpusScriptEngine.js": false, - "src/client/voice/pcm/ConverterEngine.js": false, - "src/client/voice/pcm/ConverterEngineList.js": false, - "src/client/voice/pcm/FfmpegConverterEngine.js": false, - "src/client/voice/player/AudioPlayer.js": false, - "src/client/voice/player/BasePlayer.js": false, - "src/client/voice/player/DefaultPlayer.js": false, - "src/client/voice/receiver/VoiceReadable.js": false, - "src/client/voice/receiver/VoiceReceiver.js": false, - "src/client/voice/util/SecretKey.js": false, - "src/client/voice/ClientVoiceManager.js": false, - "src/client/voice/VoiceConnection.js": false, - "src/client/voice/VoiceUDPClient.js": false, - "src/client/voice/VoiceWebSocket.js": false - } -}; - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - -const User = __webpack_require__(6); -const OAuth2Application = __webpack_require__(37); - -/** - * Represents the client's OAuth2 Application - * @extends {OAuth2Application} - */ -class ClientOAuth2Application extends OAuth2Application { - setup(data) { - super.setup(data); - - /** - * The app's flags - * @type {number} - */ - this.flags = data.flags; - - /** - * The app's owner - * @type {User} - */ - this.owner = new User(this.client, data.owner); - } -} - -module.exports = ClientOAuth2Application; - - -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { - -const User = __webpack_require__(6); -const Collection = __webpack_require__(3); - -/** - * Represents the logged in client's Discord user - * @extends {User} - */ -class ClientUser extends User { - setup(data) { - super.setup(data); - - /** - * Whether or not this account has been verified - * @type {boolean} - */ - this.verified = data.verified; - - /** - * The email of this account - * @type {string} - */ - this.email = data.email; - this.localPresence = {}; - this._typing = new Map(); - - /** - * A Collection of friends for the logged in user. - * This is only filled when using a user account. - * @type {Collection} - */ - this.friends = new Collection(); - - /** - * A Collection of blocked users for the logged in user. - * This is only filled when using a user account. - * @type {Collection} - */ - this.blocked = new Collection(); - - /** - * A Collection of notes for the logged in user. - * This is only filled when using a user account. - * @type {Collection} - */ - this.notes = new Collection(); - } - - edit(data) { - return this.client.rest.methods.updateCurrentUser(data); - } - - /** - * Set the username of the logged in Client. - * Changing usernames in Discord is heavily rate limited, with only 2 requests - * every hour. Use this sparingly! - * @param {string} username The new username - * @param {string} [password] Current password (only for user accounts) - * @returns {Promise} - * @example - * // set username - * client.user.setUsername('discordjs') - * .then(user => console.log(`My new username is ${user.username}`)) - * .catch(console.error); - */ - setUsername(username, password) { - return this.client.rest.methods.updateCurrentUser({ username }, password); - } - - /** - * Changes the email for the client user's account. - * This is only available when using a user account. - * @param {string} email New email to change to - * @param {string} password Current password - * @returns {Promise} - * @example - * // set email - * client.user.setEmail('bob@gmail.com', 'some amazing password 123') - * .then(user => console.log(`My new email is ${user.email}`)) - * .catch(console.error); - */ - setEmail(email, password) { - return this.client.rest.methods.updateCurrentUser({ email }, password); - } - - /** - * Changes the password for the client user's account. - * This is only available when using a user account. - * @param {string} newPassword New password to change to - * @param {string} oldPassword Current password - * @returns {Promise} - * @example - * // set password - * client.user.setPassword('some new amazing password 456', 'some amazing password 123') - * .then(user => console.log('New password set!')) - * .catch(console.error); - */ - setPassword(newPassword, oldPassword) { - return this.client.rest.methods.updateCurrentUser({ password: newPassword }, oldPassword); - } - - /** - * Set the avatar of the logged in Client. - * @param {BufferResolvable|Base64Resolvable} avatar The new avatar - * @returns {Promise} - * @example - * // set avatar - * client.user.setAvatar('./avatar.png') - * .then(user => console.log(`New avatar set!`)) - * .catch(console.error); - */ - setAvatar(avatar) { - if (avatar.startsWith('data:')) { - return this.client.rest.methods.updateCurrentUser({ avatar }); - } else { - return this.client.resolver.resolveBuffer(avatar).then(data => - this.client.rest.methods.updateCurrentUser({ avatar: data }) - ); - } - } - - /** - * Data resembling a raw Discord presence - * @typedef {Object} PresenceData - * @property {PresenceStatus} [status] Status of the user - * @property {boolean} [afk] Whether the user is AFK - * @property {Object} [game] Game the user is playing - * @property {string} [game.name] Name of the game - * @property {string} [game.url] Twitch stream URL - */ - - /** - * Sets the full presence of the client user. - * @param {PresenceData} data Data for the presence - * @returns {Promise} - */ - setPresence(data) { - // {"op":3,"d":{"status":"dnd","since":0,"game":null,"afk":false}} - return new Promise(resolve => { - let status = this.localPresence.status || this.presence.status; - let game = this.localPresence.game; - let afk = this.localPresence.afk || this.presence.afk; - - if (!game && this.presence.game) { - game = { - name: this.presence.game.name, - type: this.presence.game.type, - url: this.presence.game.url, - }; - } - - if (data.status) { - if (typeof data.status !== 'string') throw new TypeError('Status must be a string'); - status = data.status; - } - - if (data.game) { - game = data.game; - if (game.url) game.type = 1; - } - - if (typeof data.afk !== 'undefined') afk = data.afk; - afk = Boolean(afk); - - this.localPresence = { status, game, afk }; - this.localPresence.since = 0; - this.localPresence.game = this.localPresence.game || null; - - this.client.ws.send({ - op: 3, - d: this.localPresence, - }); - - this.client._setPresence(this.id, this.localPresence); - - resolve(this); - }); - } - - /** - * A user's status. Must be one of: - * - `online` - * - `idle` - * - `invisible` - * - `dnd` (do not disturb) - * @typedef {string} PresenceStatus - */ - - /** - * Sets the status of the client user. - * @param {PresenceStatus} status Status to change to - * @returns {Promise} - */ - setStatus(status) { - return this.setPresence({ status }); - } - - /** - * Sets the game the client user is playing. - * @param {string} game Game being played - * @param {string} [streamingURL] Twitch stream URL - * @returns {Promise} - */ - setGame(game, streamingURL) { - return this.setPresence({ game: { - name: game, - url: streamingURL, - } }); - } - - /** - * Sets/removes the AFK flag for the client user. - * @param {boolean} afk Whether or not the user is AFK - * @returns {Promise} - */ - setAFK(afk) { - return this.setPresence({ afk }); - } - - /** - * Fetches messages that mentioned the client's user - * @param {Object} [options] Options for the fetch - * @param {number} [options.limit=25] Maximum number of mentions to retrieve - * @param {boolean} [options.roles=true] Whether to include role mentions - * @param {boolean} [options.everyone=true] Whether to include everyone/here mentions - * @param {Guild|string} [options.guild] Limit the search to a specific guild - * @returns {Promise} - */ - fetchMentions(options = { limit: 25, roles: true, everyone: true, guild: null }) { - return this.client.rest.methods.fetchMentions(options); - } - - /** - * Send a friend request - * This is only available when using a user account. - * @param {UserResolvable} user The user to send the friend request to. - * @returns {Promise} The user the friend request was sent to. - */ - addFriend(user) { - user = this.client.resolver.resolveUser(user); - return this.client.rest.methods.addFriend(user); - } - - /** - * Remove a friend - * This is only available when using a user account. - * @param {UserResolvable} user The user to remove from your friends - * @returns {Promise} The user that was removed - */ - removeFriend(user) { - user = this.client.resolver.resolveUser(user); - return this.client.rest.methods.removeFriend(user); - } - - /** - * Creates a guild - * This is only available when using a user account. - * @param {string} name The name of the guild - * @param {string} region The region for the server - * @param {BufferResolvable|Base64Resolvable} [icon=null] The icon for the guild - * @returns {Promise} The guild that was created - */ - createGuild(name, region, icon = null) { - if (!icon) return this.client.rest.methods.createGuild({ name, icon, region }); - if (icon.startsWith('data:')) { - return this.client.rest.methods.createGuild({ name, icon, region }); - } else { - return this.client.resolver.resolveBuffer(icon).then(data => - this.client.rest.methods.createGuild({ name, icon: data, region }) - ); - } - } -} - -module.exports = ClientUser; - - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - -const Channel = __webpack_require__(9); -const TextBasedChannel = __webpack_require__(12); -const Collection = __webpack_require__(3); - -/** - * Represents a direct message channel between two users. - * @extends {Channel} - * @implements {TextBasedChannel} - */ -class DMChannel extends Channel { - constructor(client, data) { - super(client, data); - this.type = 'dm'; - this.messages = new Collection(); - this._typing = new Map(); - } - - setup(data) { - super.setup(data); - - /** - * The recipient on the other end of the DM - * @type {User} - */ - this.recipient = this.client.dataManager.newUser(data.recipients[0]); - - this.lastMessageID = data.last_message_id; - } - - /** - * When concatenated with a string, this automatically concatenates the recipient's mention instead of the - * DM channel object. - * @returns {string} - */ - toString() { - return this.recipient.toString(); - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - send() { return; } - sendMessage() { return; } - sendEmbed() { return; } - sendFile() { return; } - sendCode() { return; } - fetchMessage() { return; } - fetchMessages() { return; } - fetchPinnedMessages() { return; } - startTyping() { return; } - stopTyping() { return; } - get typing() { return; } - get typingCount() { return; } - createCollector() { return; } - awaitMessages() { return; } - bulkDelete() { return; } - _cacheMessage() { return; } -} - -TextBasedChannel.applyToClass(DMChannel, true); - -module.exports = DMChannel; - - -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { - -const Channel = __webpack_require__(9); -const TextBasedChannel = __webpack_require__(12); -const Collection = __webpack_require__(3); - -/* -{ type: 3, - recipients: - [ { username: 'Charlie', - id: '123', - discriminator: '6631', - avatar: '123' }, - { username: 'Ben', - id: '123', - discriminator: '2055', - avatar: '123' }, - { username: 'Adam', - id: '123', - discriminator: '2406', - avatar: '123' } ], - owner_id: '123', - name: null, - last_message_id: '123', - id: '123', - icon: null } -*/ - -/** - * Represents a Group DM on Discord - * @extends {Channel} - * @implements {TextBasedChannel} - */ -class GroupDMChannel extends Channel { - constructor(client, data) { - super(client, data); - this.type = 'group'; - this.messages = new Collection(); - this._typing = new Map(); - } - - setup(data) { - super.setup(data); - - /** - * The name of this Group DM, can be null if one isn't set. - * @type {string} - */ - this.name = data.name; - - /** - * A hash of the Group DM icon. - * @type {string} - */ - this.icon = data.icon; - - /** - * The user ID of this Group DM's owner. - * @type {string} - */ - this.ownerID = data.owner_id; - - if (!this.recipients) { - /** - * A collection of the recipients of this DM, mapped by their ID. - * @type {Collection} - */ - this.recipients = new Collection(); - } - - if (data.recipients) { - for (const recipient of data.recipients) { - const user = this.client.dataManager.newUser(recipient); - this.recipients.set(user.id, user); - } - } - - this.lastMessageID = data.last_message_id; - } - - /** - * The owner of this Group DM. - * @type {User} - * @readonly - */ - get owner() { - return this.client.users.get(this.ownerID); - } - - /** - * Whether this channel equals another channel. It compares all properties, so for most operations - * it is advisable to just compare `channel.id === channel2.id` as it is much faster and is often - * what most users need. - * @param {GroupDMChannel} channel Channel to compare with - * @returns {boolean} - */ - equals(channel) { - const equal = channel && - this.id === channel.id && - this.name === channel.name && - this.icon === channel.icon && - this.ownerID === channel.ownerID; - - if (equal) { - return this.recipients.equals(channel.recipients); - } - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the channel's name instead of the Channel object. - * @returns {string} - * @example - * // logs: Hello from My Group DM! - * console.log(`Hello from ${channel}!`); - * @example - * // logs: Hello from My Group DM! - * console.log(`Hello from ' + channel + '!'); - */ - toString() { - return this.name; - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - send() { return; } - sendMessage() { return; } - sendEmbed() { return; } - sendFile() { return; } - sendCode() { return; } - fetchMessage() { return; } - fetchMessages() { return; } - fetchPinnedMessages() { return; } - startTyping() { return; } - stopTyping() { return; } - get typing() { return; } - get typingCount() { return; } - createCollector() { return; } - awaitMessages() { return; } - bulkDelete() { return; } - _cacheMessage() { return; } -} - -TextBasedChannel.applyToClass(GroupDMChannel, true); - -module.exports = GroupDMChannel; - - -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { - -const PartialGuild = __webpack_require__(38); -const PartialGuildChannel = __webpack_require__(39); -const Constants = __webpack_require__(0); - -/* -{ max_age: 86400, - code: 'CG9A5', - guild: - { splash: null, - id: '123123123', - icon: '123123123', - name: 'name' }, - created_at: '2016-08-28T19:07:04.763368+00:00', - temporary: false, - uses: 0, - max_uses: 0, - inviter: - { username: '123', - discriminator: '4204', - bot: true, - id: '123123123', - avatar: '123123123' }, - channel: { type: 0, id: '123123', name: 'heavy-testing' } } -*/ - -/** - * Represents an invitation to a guild channel. - * The only guaranteed properties are `code`, `guild` and `channel`. Other properties can be missing. - */ -class Invite { - constructor(client, data) { - /** - * The client that instantiated the invite - * @name Invite#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The guild the invite is for. If this guild is already known, this will be a Guild object. If the guild is - * unknown, this will be a PartialGuild object. - * @type {Guild|PartialGuild} - */ - this.guild = this.client.guilds.get(data.guild.id) || new PartialGuild(this.client, data.guild); - - /** - * The code for this invite - * @type {string} - */ - this.code = data.code; - - /** - * Whether or not this invite is temporary - * @type {boolean} - */ - this.temporary = data.temporary; - - /** - * The maximum age of the invite, in seconds - * @type {?number} - */ - this.maxAge = data.max_age; - - /** - * How many times this invite has been used - * @type {number} - */ - this.uses = data.uses; - - /** - * The maximum uses of this invite - * @type {number} - */ - this.maxUses = data.max_uses; - - if (data.inviter) { - /** - * The user who created this invite - * @type {User} - */ - this.inviter = this.client.dataManager.newUser(data.inviter); - } - - /** - * The channel the invite is for. If this channel is already known, this will be a GuildChannel object. - * If the channel is unknown, this will be a PartialGuildChannel object. - * @type {GuildChannel|PartialGuildChannel} - */ - this.channel = this.client.channels.get(data.channel.id) || new PartialGuildChannel(this.client, data.channel); - - /** - * The timestamp the invite was created at - * @type {number} - */ - this.createdTimestamp = new Date(data.created_at).getTime(); - } - - /** - * The time the invite was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The timestamp the invite will expire at - * @type {number} - * @readonly - */ - get expiresTimestamp() { - return this.createdTimestamp + (this.maxAge * 1000); - } - - /** - * The time the invite will expire - * @type {Date} - * @readonly - */ - get expiresAt() { - return new Date(this.expiresTimestamp); - } - - /** - * The URL to the invite - * @type {string} - * @readonly - */ - get url() { - return Constants.Endpoints.inviteLink(this.code); - } - - /** - * Deletes this invite - * @returns {Promise} - */ - delete() { - return this.client.rest.methods.deleteInvite(this); - } - - /** - * When concatenated with a string, this automatically concatenates the invite's URL instead of the object. - * @returns {string} - * @example - * // logs: Invite: https://discord.gg/A1b2C3 - * console.log(`Invite: ${invite}`); - */ - toString() { - return this.url; - } -} - -module.exports = Invite; - - -/***/ }, -/* 33 */ -/***/ function(module, exports) { - -/** - * Represents an attachment in a message - */ -class MessageAttachment { - constructor(message, data) { - /** - * The Client that instantiated this MessageAttachment. - * @name MessageAttachment#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: message.client }); - - /** - * The message this attachment is part of. - * @type {Message} - */ - this.message = message; - - this.setup(data); - } - - setup(data) { - /** - * The ID of this attachment - * @type {string} - */ - this.id = data.id; - - /** - * The file name of this attachment - * @type {string} - */ - this.filename = data.filename; - - /** - * The size of this attachment in bytes - * @type {number} - */ - this.filesize = data.size; - - /** - * The URL to this attachment - * @type {string} - */ - this.url = data.url; - - /** - * The Proxy URL to this attachment - * @type {string} - */ - this.proxyURL = data.proxy_url; - - /** - * The height of this attachment (if an image) - * @type {?number} - */ - this.height = data.height; - - /** - * The width of this attachment (if an image) - * @type {?number} - */ - this.width = data.width; - } -} - -module.exports = MessageAttachment; - - -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { - -const EventEmitter = __webpack_require__(21).EventEmitter; -const Collection = __webpack_require__(3); - -/** - * Collects messages based on a specified filter, then emits them. - * @extends {EventEmitter} - */ -class MessageCollector extends EventEmitter { - /** - * A function that takes a Message object and a MessageCollector and returns a boolean. - * ```js - * function(message, collector) { - * if (message.content.includes('discord')) { - * return true; // passed the filter test - * } - * return false; // failed the filter test - * } - * ``` - * @typedef {Function} CollectorFilterFunction - */ - - /** - * An object containing options used to configure a MessageCollector. All properties are optional. - * @typedef {Object} CollectorOptions - * @property {number} [time] Duration for the collector in milliseconds - * @property {number} [max] Maximum number of messages to handle - * @property {number} [maxMatches] Maximum number of successfully filtered messages to obtain - */ - - /** - * @param {Channel} channel The channel to collect messages in - * @param {CollectorFilterFunction} filter The filter function - * @param {CollectorOptions} [options] Options for the collector - */ - constructor(channel, filter, options = {}) { - super(); - - /** - * The channel this collector is operating on - * @type {Channel} - */ - this.channel = channel; - - /** - * A function used to filter messages that the collector collects. - * @type {CollectorFilterFunction} - */ - this.filter = filter; - - /** - * Options for the collecor. - * @type {CollectorOptions} - */ - this.options = options; - - /** - * Whether this collector has stopped collecting messages. - * @type {boolean} - */ - this.ended = false; - - /** - * A collection of collected messages, mapped by message ID. - * @type {Collection} - */ - this.collected = new Collection(); - - this.listener = message => this.verify(message); - this.channel.client.on('message', this.listener); - if (options.time) this.channel.client.setTimeout(() => this.stop('time'), options.time); - } - - /** - * Verifies a message against the filter and options - * @private - * @param {Message} message The message - * @returns {boolean} - */ - verify(message) { - if (this.channel ? this.channel.id !== message.channel.id : false) return false; - if (this.filter(message, this)) { - this.collected.set(message.id, message); - /** - * Emitted whenever the collector receives a message that passes the filter test. - * @param {Message} message The received message - * @param {MessageCollector} collector The collector the message passed through - * @event MessageCollector#message - */ - this.emit('message', message, this); - if (this.collected.size >= this.options.maxMatches) this.stop('matchesLimit'); - else if (this.options.max && this.collected.size === this.options.max) this.stop('limit'); - return true; - } - return false; - } - - /** - * Returns a promise that resolves when a valid message is sent. Rejects - * with collected messages if the Collector ends before receiving a message. - * @type {Promise} - * @readonly - */ - get next() { - return new Promise((resolve, reject) => { - if (this.ended) { - reject(this.collected); - return; - } - - const cleanup = () => { - this.removeListener('message', onMessage); - this.removeListener('end', onEnd); - }; - - const onMessage = (...args) => { - cleanup(); - resolve(...args); - }; - - const onEnd = (...args) => { - cleanup(); - reject(...args); - }; - - this.once('message', onMessage); - this.once('end', onEnd); - }); - } - - /** - * Stops the collector and emits `end`. - * @param {string} [reason='user'] An optional reason for stopping the collector - */ - stop(reason = 'user') { - if (this.ended) return; - this.ended = true; - this.channel.client.removeListener('message', this.listener); - /** - * Emitted when the Collector stops collecting. - * @param {Collection} collection A collection of messages collected - * during the lifetime of the collector, mapped by the ID of the messages. - * @param {string} reason The reason for the end of the collector. If it ended because it reached the specified time - * limit, this would be `time`. If you invoke `.stop()` without specifying a reason, this would be `user`. If it - * ended because it reached its message limit, it will be `limit`. - * @event MessageCollector#end - */ - this.emit('end', this.collected, reason); - } -} - -module.exports = MessageCollector; - - -/***/ }, -/* 35 */ -/***/ function(module, exports) { - -/** - * Represents an embed in a message (image/video preview, rich embed, etc.) - */ -class MessageEmbed { - constructor(message, data) { - /** - * The client that instantiated this embed - * @name MessageEmbed#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: message.client }); - - /** - * The message this embed is part of - * @type {Message} - */ - this.message = message; - - this.setup(data); - } - - setup(data) { - /** - * The type of this embed - * @type {string} - */ - this.type = data.type; - - /** - * The title of this embed, if there is one - * @type {?string} - */ - this.title = data.title; - - /** - * The description of this embed, if there is one - * @type {?string} - */ - this.description = data.description; - - /** - * The URL of this embed - * @type {string} - */ - this.url = data.url; - - /** - * The color of the embed - * @type {number} - */ - this.color = data.color; - - /** - * The fields of this embed - * @type {MessageEmbedField[]} - */ - this.fields = []; - if (data.fields) for (const field of data.fields) this.fields.push(new MessageEmbedField(this, field)); - - /** - * The timestamp of this embed - * @type {number} - */ - this.createdTimestamp = data.timestamp; - - /** - * The thumbnail of this embed, if there is one - * @type {MessageEmbedThumbnail} - */ - this.thumbnail = data.thumbnail ? new MessageEmbedThumbnail(this, data.thumbnail) : null; - - /** - * The author of this embed, if there is one - * @type {MessageEmbedAuthor} - */ - this.author = data.author ? new MessageEmbedAuthor(this, data.author) : null; - - /** - * The provider of this embed, if there is one - * @type {MessageEmbedProvider} - */ - this.provider = data.provider ? new MessageEmbedProvider(this, data.provider) : null; - - /** - * The footer of this embed - * @type {MessageEmbedFooter} - */ - this.footer = data.footer ? new MessageEmbedFooter(this, data.footer) : null; - } - - /** - * The date this embed was created - * @type {Date} - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The hexadecimal version of the embed color, with a leading hash. - * @type {string} - * @readonly - */ - get hexColor() { - let col = this.color.toString(16); - while (col.length < 6) col = `0${col}`; - return `#${col}`; - } -} - -/** - * Represents a thumbnail for a message embed - */ -class MessageEmbedThumbnail { - constructor(embed, data) { - /** - * The embed this thumbnail is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The URL for this thumbnail - * @type {string} - */ - this.url = data.url; - - /** - * The Proxy URL for this thumbnail - * @type {string} - */ - this.proxyURL = data.proxy_url; - - /** - * The height of the thumbnail - * @type {number} - */ - this.height = data.height; - - /** - * The width of the thumbnail - * @type {number} - */ - this.width = data.width; - } -} - -/** - * Represents a provider for a message embed - */ -class MessageEmbedProvider { - constructor(embed, data) { - /** - * The embed this provider is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The name of this provider - * @type {string} - */ - this.name = data.name; - - /** - * The URL of this provider - * @type {string} - */ - this.url = data.url; - } -} - -/** - * Represents an author for a message embed - */ -class MessageEmbedAuthor { - constructor(embed, data) { - /** - * The embed this author is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The name of this author - * @type {string} - */ - this.name = data.name; - - /** - * The URL of this author - * @type {string} - */ - this.url = data.url; - - /** - * The icon URL of this author - * @type {string} - */ - this.iconURL = data.icon_url; - } -} - -/** - * Represents a field for a message embed - */ -class MessageEmbedField { - constructor(embed, data) { - /** - * The embed this footer is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The name of this field - * @type {string} - */ - this.name = data.name; - - /** - * The value of this field - * @type {string} - */ - this.value = data.value; - - /** - * If this field is displayed inline - * @type {boolean} - */ - this.inline = data.inline; - } -} - -/** - * Represents the footer of a message embed - */ -class MessageEmbedFooter { - constructor(embed, data) { - /** - * The embed this footer is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The text in this footer - * @type {string} - */ - this.text = data.text; - - /** - * The icon URL of this footer - * @type {string} - */ - this.iconURL = data.icon_url; - - /** - * The proxy icon URL of this footer - * @type {string} - */ - this.proxyIconUrl = data.proxy_icon_url; - } -} - -MessageEmbed.Thumbnail = MessageEmbedThumbnail; -MessageEmbed.Provider = MessageEmbedProvider; -MessageEmbed.Author = MessageEmbedAuthor; -MessageEmbed.Field = MessageEmbedField; -MessageEmbed.Footer = MessageEmbedFooter; - -module.exports = MessageEmbed; - - -/***/ }, -/* 36 */ -/***/ function(module, exports, __webpack_require__) { - -const Collection = __webpack_require__(3); -const Emoji = __webpack_require__(10); -const ReactionEmoji = __webpack_require__(18); - -/** - * Represents a reaction to a message - */ -class MessageReaction { - constructor(message, emoji, count, me) { - /** - * The message that this reaction refers to - * @type {Message} - */ - this.message = message; - - /** - * Whether the client has given this reaction - * @type {boolean} - */ - this.me = me; - - /** - * The number of people that have given the same reaction. - * @type {number} - */ - this.count = count || 0; - - /** - * The users that have given this reaction, mapped by their ID. - * @type {Collection} - */ - this.users = new Collection(); - - this._emoji = new ReactionEmoji(this, emoji.name, emoji.id); - } - - /** - * The emoji of this reaction, either an Emoji object for known custom emojis, or a ReactionEmoji - * object which has fewer properties. Whatever the prototype of the emoji, it will still have - * `name`, `id`, `identifier` and `toString()` - * @type {Emoji|ReactionEmoji} - */ - get emoji() { - if (this._emoji instanceof Emoji) return this._emoji; - // check to see if the emoji has become known to the client - if (this._emoji.id) { - const emojis = this.message.client.emojis; - if (emojis.has(this._emoji.id)) { - const emoji = emojis.get(this._emoji.id); - this._emoji = emoji; - return emoji; - } - } - return this._emoji; - } - - /** - * Removes a user from this reaction. - * @param {UserResolvable} [user=this.message.client.user] User to remove the reaction of - * @returns {Promise} - */ - remove(user = this.message.client.user) { - const message = this.message; - user = this.message.client.resolver.resolveUserID(user); - if (!user) return Promise.reject('Couldn\'t resolve the user ID to remove from the reaction.'); - return message.client.rest.methods.removeMessageReaction( - message, this.emoji.identifier, user - ); - } - - /** - * Fetch all the users that gave this reaction. Resolves with a collection of users, mapped by their IDs. - * @param {number} [limit=100] the maximum amount of users to fetch, defaults to 100 - * @returns {Promise>} - */ - fetchUsers(limit = 100) { - const message = this.message; - return message.client.rest.methods.getMessageReactionUsers( - message, this.emoji.identifier, limit - ).then(users => { - this.users = new Collection(); - for (const rawUser of users) { - const user = this.message.client.dataManager.newUser(rawUser); - this.users.set(user.id, user); - } - this.count = this.users.size; - return users; - }); - } -} - -module.exports = MessageReaction; - - -/***/ }, -/* 37 */ -/***/ function(module, exports) { - -/** - * Represents an OAuth2 Application - */ -class OAuth2Application { - constructor(client, data) { - /** - * The client that instantiated the application - * @name OAuth2Application#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The ID of the app - * @type {string} - */ - this.id = data.id; - - /** - * The name of the app - * @type {string} - */ - this.name = data.name; - - /** - * The app's description - * @type {string} - */ - this.description = data.description; - - /** - * The app's icon hash - * @type {string} - */ - this.icon = data.icon; - - /** - * The app's icon URL - * @type {string} - */ - this.iconURL = `https://cdn.discordapp.com/app-icons/${this.id}/${this.icon}.jpg`; - - /** - * The app's RPC origins - * @type {Array} - */ - this.rpcOrigins = data.rpc_origins; - } - - /** - * The timestamp the app was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return (this.id / 4194304) + 1420070400000; - } - - /** - * The time the app was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * When concatenated with a string, this automatically concatenates the app name rather than the app object. - * @returns {string} - */ - toString() { - return this.name; - } -} - -module.exports = OAuth2Application; - - -/***/ }, -/* 38 */ -/***/ function(module, exports) { - -/* -{ splash: null, - id: '123123123', - icon: '123123123', - name: 'name' } -*/ - -/** - * Represents a guild that the client only has limited information for - e.g. from invites. - */ -class PartialGuild { - constructor(client, data) { - /** - * The Client that instantiated this PartialGuild - * @name PartialGuild#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The ID of this guild - * @type {string} - */ - this.id = data.id; - - /** - * The name of this guild - * @type {string} - */ - this.name = data.name; - - /** - * The hash of this guild's icon, or null if there is none. - * @type {?string} - */ - this.icon = data.icon; - - /** - * The hash of the guild splash image, or null if no splash (VIP only) - * @type {?string} - */ - this.splash = data.splash; - } -} - -module.exports = PartialGuild; - - -/***/ }, -/* 39 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -/* -{ type: 0, id: '123123', name: 'heavy-testing' } } -*/ - -/** - * Represents a guild channel that the client only has limited information for - e.g. from invites. - */ -class PartialGuildChannel { - constructor(client, data) { - /** - * The Client that instantiated this PartialGuildChannel - * @name PartialGuildChannel#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The ID of this guild channel - * @type {string} - */ - this.id = data.id; - - /** - * The name of this guild channel - * @type {string} - */ - this.name = data.name; - - /** - * The type of this guild channel - `text` or `voice` - * @type {string} - */ - this.type = Constants.ChannelTypes.text === data.type ? 'text' : 'voice'; - } -} - -module.exports = PartialGuildChannel; - - -/***/ }, -/* 40 */ -/***/ function(module, exports) { - -/** - * Represents a permission overwrite for a role or member in a guild channel. - */ -class PermissionOverwrites { - constructor(guildChannel, data) { - /** - * The GuildChannel this overwrite is for - * @name PermissionOverwrites#channel - * @type {GuildChannel} - * @readonly - */ - Object.defineProperty(this, 'channel', { value: guildChannel }); - - if (data) this.setup(data); - } - - setup(data) { - /** - * The ID of this overwrite, either a user ID or a role ID - * @type {string} - */ - this.id = data.id; - - /** - * The type of this overwrite - * @type {string} - */ - this.type = data.type; - - this.deny = data.deny; - this.allow = data.allow; - } - - /** - * Delete this Permission Overwrite. - * @returns {Promise} - */ - delete() { - return this.channel.client.rest.methods.deletePermissionOverwrites(this); - } -} - -module.exports = PermissionOverwrites; - - -/***/ }, -/* 41 */ -/***/ function(module, exports, __webpack_require__) { - -const GuildChannel = __webpack_require__(13); -const TextBasedChannel = __webpack_require__(12); -const Collection = __webpack_require__(3); - -/** - * Represents a guild text channel on Discord. - * @extends {GuildChannel} - * @implements {TextBasedChannel} - */ -class TextChannel extends GuildChannel { - constructor(guild, data) { - super(guild, data); - this.type = 'text'; - this.messages = new Collection(); - this._typing = new Map(); - } - - setup(data) { - super.setup(data); - - /** - * The topic of the text channel, if there is one. - * @type {?string} - */ - this.topic = data.topic; - - this.lastMessageID = data.last_message_id; - } - - /** - * A collection of members that can see this channel, mapped by their ID. - * @type {Collection} - * @readonly - */ - get members() { - const members = new Collection(); - for (const member of this.guild.members.values()) { - if (this.permissionsFor(member).hasPermission('READ_MESSAGES')) { - members.set(member.id, member); - } - } - return members; - } - - /** - * Fetch all webhooks for the channel. - * @returns {Promise>} - */ - fetchWebhooks() { - return this.client.rest.methods.getChannelWebhooks(this); - } - - /** - * Create a webhook for the channel. - * @param {string} name The name of the webhook. - * @param {BufferResolvable} avatar The avatar for the webhook. - * @returns {Promise} webhook The created webhook. - * @example - * channel.createWebhook('Snek', 'http://snek.s3.amazonaws.com/topSnek.png') - * .then(webhook => console.log(`Created Webhook ${webhook}`)) - * .catch(console.error) - */ - createWebhook(name, avatar) { - return new Promise(resolve => { - if (avatar.startsWith('data:')) { - resolve(this.client.rest.methods.createWebhook(this, name, avatar)); - } else { - this.client.resolver.resolveBuffer(avatar).then(data => - resolve(this.client.rest.methods.createWebhook(this, name, data)) - ); - } - }); - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - send() { return; } - sendMessage() { return; } - sendEmbed() { return; } - sendFile() { return; } - sendCode() { return; } - fetchMessage() { return; } - fetchMessages() { return; } - fetchPinnedMessages() { return; } - startTyping() { return; } - stopTyping() { return; } - get typing() { return; } - get typingCount() { return; } - createCollector() { return; } - awaitMessages() { return; } - bulkDelete() { return; } - _cacheMessage() { return; } -} - -TextBasedChannel.applyToClass(TextChannel, true); - -module.exports = TextChannel; - - -/***/ }, -/* 42 */ -/***/ function(module, exports, __webpack_require__) { - -const GuildChannel = __webpack_require__(13); -const Collection = __webpack_require__(3); - -/** - * Represents a guild voice channel on Discord. - * @extends {GuildChannel} - */ -class VoiceChannel extends GuildChannel { - constructor(guild, data) { - super(guild, data); - - /** - * The members in this voice channel. - * @type {Collection} - */ - this.members = new Collection(); - - this.type = 'voice'; - } - - setup(data) { - super.setup(data); - - /** - * The bitrate of this voice channel - * @type {number} - */ - this.bitrate = data.bitrate; - - /** - * The maximum amount of users allowed in this channel - 0 means unlimited. - * @type {number} - */ - this.userLimit = data.user_limit; - } - - /** - * The voice connection for this voice channel, if the client is connected - * @type {?VoiceConnection} - * @readonly - */ - get connection() { - const connection = this.guild.voiceConnection; - if (connection && connection.channel.id === this.id) return connection; - return null; - } - - /** - * Checks if the client has permission join the voice channel - * @type {boolean} - */ - get joinable() { - if (this.client.browser) return false; - return this.permissionsFor(this.client.user).hasPermission('CONNECT'); - } - - /** - * Checks if the client has permission to send audio to the voice channel - * @type {boolean} - */ - get speakable() { - return this.permissionsFor(this.client.user).hasPermission('SPEAK'); - } - - /** - * Sets the bitrate of the channel - * @param {number} bitrate The new bitrate - * @returns {Promise} - * @example - * // set the bitrate of a voice channel - * voiceChannel.setBitrate(48000) - * .then(vc => console.log(`Set bitrate to ${vc.bitrate} for ${vc.name}`)) - * .catch(console.error); - */ - setBitrate(bitrate) { - return this.edit({ bitrate }); - } - - /** - * Sets the user limit of the channel - * @param {number} userLimit The new user limit - * @returns {Promise} - * @example - * // set the user limit of a voice channel - * voiceChannel.setUserLimit(42) - * .then(vc => console.log(`Set user limit to ${vc.userLimit} for ${vc.name}`)) - * .catch(console.error); - */ - setUserLimit(userLimit) { - return this.edit({ userLimit }); - } - - /** - * Attempts to join this voice channel - * @returns {Promise} - * @example - * // join a voice channel - * voiceChannel.join() - * .then(connection => console.log('Connected!')) - * .catch(console.error); - */ - join() { - if (this.client.browser) return Promise.reject(new Error('Voice connections are not available in browsers.')); - return this.client.voice.joinChannel(this); - } - - /** - * Leaves this voice channel - * @example - * // leave a voice channel - * voiceChannel.leave(); - */ - leave() { - if (this.client.browser) return; - const connection = this.client.voice.connections.get(this.guild.id); - if (connection && connection.channel.id === this.id) connection.disconnect(); - } -} - -module.exports = VoiceChannel; - - -/***/ }, -/* 43 */ -/***/ function(module, exports) { - -module.exports = function splitMessage(text, { maxLength = 1950, char = '\n', prepend = '', append = '' } = {}) { - if (text.length <= maxLength) return text; - const splitText = text.split(char); - if (splitText.length === 1) throw new Error('Message exceeds the max length and contains no split characters.'); - const messages = ['']; - let msg = 0; - for (let i = 0; i < splitText.length; i++) { - if (messages[msg].length + splitText[i].length + 1 > maxLength) { - messages[msg] += append; - messages.push(prepend); - msg++; - } - messages[msg] += (messages[msg].length > 0 && messages[msg] !== prepend ? char : '') + splitText[i]; - } - return messages; -}; - - -/***/ }, -/* 44 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; -// String encode/decode helpers - - - -var utils = __webpack_require__(5); - - -// Quick check if we can use fast array to bin string conversion -// -// - apply(Array) can fail on Android 2.2 -// - apply(Uint8Array) can fail on iOS 5.1 Safary -// -var STR_APPLY_OK = true; -var STR_APPLY_UIA_OK = true; - -try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } -try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } - - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -var _utf8len = new utils.Buf8(256); -for (var q = 0; q < 256; q++) { - _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); -} -_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start - - -// convert string to array (typed, when possible) -exports.string2buf = function (str) { - var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - buf = new utils.Buf8(buf_len); - - // convert - for (i = 0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { - c2 = str.charCodeAt(m_pos + 1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | (c >>> 6); - buf[i++] = 0x80 | (c & 0x3f); - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | (c >>> 12); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } else { - /* four bytes */ - buf[i++] = 0xf0 | (c >>> 18); - buf[i++] = 0x80 | (c >>> 12 & 0x3f); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } - } - - return buf; -}; - -// Helper (used in 2 places) -function buf2binstring(buf, len) { - // use fallback for big arrays to avoid stack overflow - if (len < 65537) { - if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { - return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); - } - } - - var result = ''; - for (var i = 0; i < len; i++) { - result += String.fromCharCode(buf[i]); - } - return result; -} - - -// Convert byte array to binary string -exports.buf2binstring = function (buf) { - return buf2binstring(buf, buf.length); -}; - - -// Convert binary string (typed, when possible) -exports.binstring2buf = function (str) { - var buf = new utils.Buf8(str.length); - for (var i = 0, len = buf.length; i < len; i++) { - buf[i] = str.charCodeAt(i); - } - return buf; -}; - - -// convert array to string -exports.buf2string = function (buf, max) { - var i, out, c, c_len; - var len = max || buf.length; - - // Reserve max possible length (2 words per char) - // NB: by unknown reasons, Array is significantly faster for - // String.fromCharCode.apply than Uint16Array. - var utf16buf = new Array(len * 2); - - for (out = 0, i = 0; i < len;) { - c = buf[i++]; - // quick process ascii - if (c < 0x80) { utf16buf[out++] = c; continue; } - - c_len = _utf8len[c]; - // skip 5 & 6 byte codes - if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } - - // apply mask on first byte - c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; - // join the rest - while (c_len > 1 && i < len) { - c = (c << 6) | (buf[i++] & 0x3f); - c_len--; - } - - // terminated by end of string? - if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } - - if (c < 0x10000) { - utf16buf[out++] = c; - } else { - c -= 0x10000; - utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); - utf16buf[out++] = 0xdc00 | (c & 0x3ff); - } - } - - return buf2binstring(utf16buf, out); -}; - - -// Calculate max possible position in utf8 buffer, -// that will not break sequence. If that's not possible -// - (very small limits) return max size as is. -// -// buf[] - utf8 bytes array -// max - length limit (mandatory); -exports.utf8border = function (buf, max) { - var pos; - - max = max || buf.length; - if (max > buf.length) { max = buf.length; } - - // go back from last position, until start of sequence found - pos = max - 1; - while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } - - // Fuckup - very small and broken sequence, - // return max, because we should return something anyway. - if (pos < 0) { return max; } - - // If we came to start of buffer - that means vuffer is too small, - // return max too. - if (pos === 0) { return max; } - - return (pos + _utf8len[buf[pos]] > max) ? pos : max; -}; - - -/***/ }, -/* 45 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - -// Note: adler32 takes 12% for level 0 and 2% for level 6. -// It doesn't worth to make additional optimizationa as in original. -// Small size is preferable. - -function adler32(adler, buf, len, pos) { - var s1 = (adler & 0xffff) |0, - s2 = ((adler >>> 16) & 0xffff) |0, - n = 0; - - while (len !== 0) { - // Set limit ~ twice less than 5552, to keep - // s2 in 31-bits, because we force signed ints. - // in other case %= will fail. - n = len > 2000 ? 2000 : len; - len -= n; - - do { - s1 = (s1 + buf[pos++]) |0; - s2 = (s2 + s1) |0; - } while (--n); - - s1 %= 65521; - s2 %= 65521; - } - - return (s1 | (s2 << 16)) |0; -} - - -module.exports = adler32; - - -/***/ }, -/* 46 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -module.exports = { - - /* Allowed flush values; see deflate() and inflate() below for details */ - Z_NO_FLUSH: 0, - Z_PARTIAL_FLUSH: 1, - Z_SYNC_FLUSH: 2, - Z_FULL_FLUSH: 3, - Z_FINISH: 4, - Z_BLOCK: 5, - Z_TREES: 6, - - /* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - Z_OK: 0, - Z_STREAM_END: 1, - Z_NEED_DICT: 2, - Z_ERRNO: -1, - Z_STREAM_ERROR: -2, - Z_DATA_ERROR: -3, - //Z_MEM_ERROR: -4, - Z_BUF_ERROR: -5, - //Z_VERSION_ERROR: -6, - - /* compression levels */ - Z_NO_COMPRESSION: 0, - Z_BEST_SPEED: 1, - Z_BEST_COMPRESSION: 9, - Z_DEFAULT_COMPRESSION: -1, - - - Z_FILTERED: 1, - Z_HUFFMAN_ONLY: 2, - Z_RLE: 3, - Z_FIXED: 4, - Z_DEFAULT_STRATEGY: 0, - - /* Possible values of the data_type field (though see inflate()) */ - Z_BINARY: 0, - Z_TEXT: 1, - //Z_ASCII: 1, // = Z_TEXT (deprecated) - Z_UNKNOWN: 2, - - /* The deflate compression method */ - Z_DEFLATED: 8 - //Z_NULL: null // Use -1 or null inline, depending on var type -}; - - -/***/ }, -/* 47 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - -// Note: we can't get significant speed boost here. -// So write code to minimize size - no pregenerated tables -// and array tools dependencies. - - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - var c, table = []; - - for (var n = 0; n < 256; n++) { - c = n; - for (var k = 0; k < 8; k++) { - c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -var crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - var t = crcTable, - end = pos + len; - - crc ^= -1; - - for (var i = pos; i < end; i++) { - crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return (crc ^ (-1)); // >>> 0; -} - - -module.exports = crc32; - - -/***/ }, -/* 48 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -function ZStream() { - /* next input byte */ - this.input = null; // JS specific, because we have no pointers - this.next_in = 0; - /* number of bytes available at input */ - this.avail_in = 0; - /* total number of input bytes read so far */ - this.total_in = 0; - /* next output byte should be put there */ - this.output = null; // JS specific, because we have no pointers - this.next_out = 0; - /* remaining free space at output */ - this.avail_out = 0; - /* total number of bytes output so far */ - this.total_out = 0; - /* last error message, NULL if no error */ - this.msg = ''/*Z_NULL*/; - /* not visible by applications */ - this.state = null; - /* best guess about the data type: binary or text */ - this.data_type = 2/*Z_UNKNOWN*/; - /* adler32 value of the uncompressed data */ - this.adler = 0; -} - -module.exports = ZStream; - - -/***/ }, -/* 49 */ -/***/ function(module, exports) { - - - -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const path = __webpack_require__(23); -const fs = __webpack_require__(49); -const request = __webpack_require__(25); - -const Constants = __webpack_require__(0); -const convertArrayBuffer = __webpack_require__(53); -const User = __webpack_require__(6); -const Message = __webpack_require__(11); -const Guild = __webpack_require__(17); -const Channel = __webpack_require__(9); -const GuildMember = __webpack_require__(14); -const Emoji = __webpack_require__(10); -const ReactionEmoji = __webpack_require__(18); - -/** - * The DataResolver identifies different objects and tries to resolve a specific piece of information from them, e.g. - * extracting a User from a Message object. - * @private - */ -class ClientDataResolver { - /** - * @param {Client} client The client the resolver is for - */ - constructor(client) { - this.client = client; - } - - /** - * Data that resolves to give a User object. This can be: - * * A User object - * * A user ID - * * A Message object (resolves to the message author) - * * A Guild object (owner of the guild) - * * A GuildMember object - * @typedef {User|string|Message|Guild|GuildMember} UserResolvable - */ - - /** - * Resolves a UserResolvable to a User object - * @param {UserResolvable} user The UserResolvable to identify - * @returns {?User} - */ - resolveUser(user) { - if (user instanceof User) return user; - if (typeof user === 'string') return this.client.users.get(user) || null; - if (user instanceof GuildMember) return user.user; - if (user instanceof Message) return user.author; - if (user instanceof Guild) return user.owner; - return null; - } - - /** - * Resolves a UserResolvable to a user ID string - * @param {UserResolvable} user The UserResolvable to identify - * @returns {?string} - */ - resolveUserID(user) { - if (user instanceof User || user instanceof GuildMember) return user.id; - if (typeof user === 'string') return user || null; - if (user instanceof Message) return user.author.id; - if (user instanceof Guild) return user.ownerID; - return null; - } - - /** - * Data that resolves to give a Guild object. This can be: - * * A Guild object - * * A Guild ID - * @typedef {Guild|string} GuildResolvable - */ - - /** - * Resolves a GuildResolvable to a Guild object - * @param {GuildResolvable} guild The GuildResolvable to identify - * @returns {?Guild} - */ - resolveGuild(guild) { - if (guild instanceof Guild) return guild; - if (typeof guild === 'string') return this.client.guilds.get(guild) || null; - return null; - } - - /** - * Data that resolves to give a GuildMember object. This can be: - * * A GuildMember object - * * A User object - * @typedef {Guild} GuildMemberResolvable - */ - - /** - * Resolves a GuildMemberResolvable to a GuildMember object - * @param {GuildResolvable} guild The guild that the member is part of - * @param {UserResolvable} user The user that is part of the guild - * @returns {?GuildMember} - */ - resolveGuildMember(guild, user) { - if (user instanceof GuildMember) return user; - guild = this.resolveGuild(guild); - user = this.resolveUser(user); - if (!guild || !user) return null; - return guild.members.get(user.id) || null; - } - - /** - * Data that can be resolved to give a Channel. This can be: - * * A Channel object - * * A Message object (the channel the message was sent in) - * * A Guild object (the #general channel) - * * A channel ID - * @typedef {Channel|Guild|Message|string} ChannelResolvable - */ - - /** - * Resolves a ChannelResolvable to a Channel object - * @param {ChannelResolvable} channel The channel resolvable to resolve - * @returns {?Channel} - */ - resolveChannel(channel) { - if (channel instanceof Channel) return channel; - if (channel instanceof Message) return channel.channel; - if (channel instanceof Guild) return channel.channels.get(channel.id) || null; - if (typeof channel === 'string') return this.client.channels.get(channel) || null; - return null; - } - - /** - * Data that can be resolved to give an invite code. This can be: - * * An invite code - * * An invite URL - * @typedef {string} InviteResolvable - */ - - /** - * Resolves InviteResolvable to an invite code - * @param {InviteResolvable} data The invite resolvable to resolve - * @returns {string} - */ - resolveInviteCode(data) { - const inviteRegex = /discord(?:app)?\.(?:gg|com\/invite)\/([a-z0-9]{5})/i; - const match = inviteRegex.exec(data); - if (match && match[1]) return match[1]; - return data; - } - - /** - * Data that can be resolved to give a permission number. This can be: - * * A string - * * A permission number - * - * Possible strings: - * ```js - * [ - * "CREATE_INSTANT_INVITE", - * "KICK_MEMBERS", - * "BAN_MEMBERS", - * "ADMINISTRATOR", - * "MANAGE_CHANNELS", - * "MANAGE_GUILD", - * "ADD_REACTIONS", // add reactions to messages - * "READ_MESSAGES", - * "SEND_MESSAGES", - * "SEND_TTS_MESSAGES", - * "MANAGE_MESSAGES", - * "EMBED_LINKS", - * "ATTACH_FILES", - * "READ_MESSAGE_HISTORY", - * "MENTION_EVERYONE", - * "EXTERNAL_EMOJIS", // use external emojis - * "CONNECT", // connect to voice - * "SPEAK", // speak on voice - * "MUTE_MEMBERS", // globally mute members on voice - * "DEAFEN_MEMBERS", // globally deafen members on voice - * "MOVE_MEMBERS", // move member's voice channels - * "USE_VAD", // use voice activity detection - * "CHANGE_NICKNAME", - * "MANAGE_NICKNAMES", // change nicknames of others - * "MANAGE_ROLES_OR_PERMISSIONS", - * "MANAGE_WEBHOOKS", - * "MANAGE_EMOJIS" - * ] - * ``` - * @typedef {string|number} PermissionResolvable - */ - - /** - * Resolves a PermissionResolvable to a permission number - * @param {PermissionResolvable} permission The permission resolvable to resolve - * @returns {number} - */ - resolvePermission(permission) { - if (typeof permission === 'string') permission = Constants.PermissionFlags[permission]; - if (typeof permission !== 'number' || permission < 1) throw new Error(Constants.Errors.NOT_A_PERMISSION); - return permission; - } - - /** - * Turn an array of permissions into a valid Discord permission bitfield - * @param {PermissionResolvable[]} permissions Permissions to resolve together - * @returns {number} - */ - resolvePermissions(permissions) { - let bitfield = 0; - for (const permission of permissions) bitfield |= this.resolvePermission(permission); - return bitfield; - } - - /** - * Data that can be resolved to give a string. This can be: - * * A string - * * An array (joined with a new line delimiter to give a string) - * * Any value - * @typedef {string|Array|*} StringResolvable - */ - - /** - * Resolves a StringResolvable to a string - * @param {StringResolvable} data The string resolvable to resolve - * @returns {string} - */ - resolveString(data) { - if (typeof data === 'string') return data; - if (data instanceof Array) return data.join('\n'); - return String(data); - } - - /** - * Data that resolves to give a Base64 string, typically for image uploading. This can be: - * * A Buffer - * * A base64 string - * @typedef {Buffer|string} Base64Resolvable - */ - - /** - * Resolves a Base64Resolvable to a Base 64 image - * @param {Base64Resolvable} data The base 64 resolvable you want to resolve - * @returns {?string} - */ - resolveBase64(data) { - if (data instanceof Buffer) return `data:image/jpg;base64,${data.toString('base64')}`; - return data; - } - - /** - * Data that can be resolved to give a Buffer. This can be: - * * A Buffer - * * The path to a local file - * * A URL - * @typedef {string|Buffer} BufferResolvable - */ - - /** - * Resolves a BufferResolvable to a Buffer - * @param {BufferResolvable} resource The buffer resolvable to resolve - * @returns {Promise} - */ - resolveBuffer(resource) { - if (resource instanceof Buffer) return Promise.resolve(resource); - if (this.client.browser && resource instanceof ArrayBuffer) return Promise.resolve(convertArrayBuffer(resource)); - - if (typeof resource === 'string') { - return new Promise((resolve, reject) => { - if (/^https?:\/\//.test(resource)) { - const req = request.get(resource).set('Content-Type', 'blob'); - if (this.client.browser) req.responseType('arraybuffer'); - req.end((err, res) => { - if (err) return reject(err); - if (this.client.browser) return resolve(convertArrayBuffer(res.xhr.response)); - if (!(res.body instanceof Buffer)) return reject(new TypeError('The response body isn\'t a Buffer.')); - return resolve(res.body); - }); - } else { - const file = path.resolve(resource); - fs.stat(file, (err, stats) => { - if (err) reject(err); - if (!stats || !stats.isFile()) throw new Error(`The file could not be found: ${file}`); - fs.readFile(file, (err2, data) => { - if (err2) reject(err2); else resolve(data); - }); - }); - } - }); - } - - return Promise.reject(new TypeError('The resource must be a string or Buffer.')); - } - - /** - * Data that can be resolved to give an emoji identifier. This can be: - * * A string - * * An Emoji - * * A ReactionEmoji - * @typedef {string|Emoji|ReactionEmoji} EmojiIdentifierResolvable - */ - - /** - * Resolves an EmojiResolvable to an emoji identifier - * @param {EmojiIdentifierResolvable} emoji The emoji resolvable to resolve - * @returns {string} - */ - resolveEmojiIdentifier(emoji) { - if (emoji instanceof Emoji || emoji instanceof ReactionEmoji) return emoji.identifier; - if (typeof emoji === 'string') { - if (!emoji.includes('%')) return encodeURIComponent(emoji); - } - return null; - } -} - -module.exports = ClientDataResolver; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) - -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { - -const UserAgentManager = __webpack_require__(114); -const RESTMethods = __webpack_require__(111); -const SequentialRequestHandler = __webpack_require__(113); -const BurstRequestHandler = __webpack_require__(112); -const APIRequest = __webpack_require__(110); -const Constants = __webpack_require__(0); - -class RESTManager { - constructor(client) { - this.client = client; - this.handlers = {}; - this.userAgentManager = new UserAgentManager(this); - this.methods = new RESTMethods(this); - this.rateLimitedEndpoints = {}; - this.globallyRateLimited = false; - } - - push(handler, apiRequest) { - return new Promise((resolve, reject) => { - handler.push({ - request: apiRequest, - resolve, - reject, - }); - }); - } - - getRequestHandler() { - switch (this.client.options.apiRequestMethod) { - case 'sequential': - return SequentialRequestHandler; - case 'burst': - return BurstRequestHandler; - default: - throw new Error(Constants.Errors.INVALID_RATE_LIMIT_METHOD); - } - } - - makeRequest(method, url, auth, data, file) { - const apiRequest = new APIRequest(this, method, url, auth, data, file); - - if (!this.handlers[apiRequest.route]) { - const RequestHandlerType = this.getRequestHandler(); - this.handlers[apiRequest.route] = new RequestHandlerType(this, apiRequest.route); - } - - return this.push(this.handlers[apiRequest.route], apiRequest); - } -} - -module.exports = RESTManager; - - -/***/ }, -/* 52 */ -/***/ function(module, exports) { - -/** - * A base class for different types of rate limiting handlers for the REST API. - * @private - */ -class RequestHandler { - /** - * @param {RESTManager} restManager The REST manager to use - */ - constructor(restManager) { - /** - * The RESTManager that instantiated this RequestHandler - * @type {RESTManager} - */ - this.restManager = restManager; - - /** - * A list of requests that have yet to be processed. - * @type {APIRequest[]} - */ - this.queue = []; - } - - /** - * Whether or not the client is being rate limited on every endpoint. - * @type {boolean} - */ - get globalLimit() { - return this.restManager.globallyRateLimited; - } - - set globalLimit(value) { - this.restManager.globallyRateLimited = value; - } - - /** - * Push a new API request into this bucket - * @param {APIRequest} request The new request to push into the queue - */ - push(request) { - this.queue.push(request); - } - - /** - * Attempts to get this RequestHandler to process its current queue - */ - handle() { - return; - } -} - -module.exports = RequestHandler; - - -/***/ }, -/* 53 */ -/***/ function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {function arrayBufferToBuffer(ab) { - const buffer = new Buffer(ab.byteLength); - const view = new Uint8Array(ab); - for (var i = 0; i < buffer.length; ++i) buffer[i] = view[i]; - return buffer; -} - -function str2ab(str) { - const buffer = new ArrayBuffer(str.length * 2); - const view = new Uint16Array(buffer); - for (var i = 0, strLen = str.length; i < strLen; i++) view[i] = str.charCodeAt(i); - return buffer; -} - -module.exports = function convertArrayBuffer(x) { - if (typeof x === 'string') x = str2ab(x); - return arrayBufferToBuffer(x); -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) - -/***/ }, -/* 54 */ -/***/ function(module, exports) { - -module.exports = function merge(def, given) { - if (!given) return def; - for (const key in def) { - if (!{}.hasOwnProperty.call(given, key)) { - given[key] = def[key]; - } else if (given[key] === Object(given[key])) { - given[key] = merge(def[key], given[key]); - } - } - - return given; -}; - - -/***/ }, -/* 55 */ -/***/ function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process) {const EventEmitter = __webpack_require__(21).EventEmitter; -const mergeDefault = __webpack_require__(54); -const Constants = __webpack_require__(0); -const RESTManager = __webpack_require__(51); -const ClientDataManager = __webpack_require__(81); -const ClientManager = __webpack_require__(82); -const ClientDataResolver = __webpack_require__(50); -const ClientVoiceManager = __webpack_require__(156); -const WebSocketManager = __webpack_require__(115); -const ActionsManager = __webpack_require__(83); -const Collection = __webpack_require__(3); -const Presence = __webpack_require__(7).Presence; -const ShardClientUtil = __webpack_require__(155); - -/** - * The starting point for making a Discord Bot. - * @extends {EventEmitter} - */ -class Client extends EventEmitter { - /** - * @param {ClientOptions} [options] Options for the client - */ - constructor(options = {}) { - super(); - - // Obtain shard details from environment - if (!options.shardId && 'SHARD_ID' in process.env) options.shardId = Number(process.env.SHARD_ID); - if (!options.shardCount && 'SHARD_COUNT' in process.env) options.shardCount = Number(process.env.SHARD_COUNT); - - /** - * The options the client was instantiated with - * @type {ClientOptions} - */ - this.options = mergeDefault(Constants.DefaultOptions, options); - this._validateOptions(); - - /** - * The REST manager of the client - * @type {RESTManager} - * @private - */ - this.rest = new RESTManager(this); - - /** - * The data manager of the Client - * @type {ClientDataManager} - * @private - */ - this.dataManager = new ClientDataManager(this); - - /** - * The manager of the Client - * @type {ClientManager} - * @private - */ - this.manager = new ClientManager(this); - - /** - * The WebSocket Manager of the Client - * @type {WebSocketManager} - * @private - */ - this.ws = new WebSocketManager(this); - - /** - * The Data Resolver of the Client - * @type {ClientDataResolver} - * @private - */ - this.resolver = new ClientDataResolver(this); - - /** - * The Action Manager of the Client - * @type {ActionsManager} - * @private - */ - this.actions = new ActionsManager(this); - - /** - * The Voice Manager of the Client (`null` in browsers) - * @type {?ClientVoiceManager} - * @private - */ - this.voice = !this.browser ? new ClientVoiceManager(this) : null; - - /** - * The shard helpers for the client (only if the process was spawned as a child, such as from a ShardingManager) - * @type {?ShardClientUtil} - */ - this.shard = process.send ? ShardClientUtil.singleton(this) : null; - - /** - * A collection of the Client's stored users - * @type {Collection} - */ - this.users = new Collection(); - - /** - * A collection of the Client's stored guilds - * @type {Collection} - */ - this.guilds = new Collection(); - - /** - * A collection of the Client's stored channels - * @type {Collection} - */ - this.channels = new Collection(); - - /** - * A collection of presences for friends of the logged in user. - * This is only filled when using a user account. - * @type {Collection} - */ - this.presences = new Collection(); - - if (!this.token && 'CLIENT_TOKEN' in process.env) { - /** - * The authorization token for the logged in user/bot. - * @type {?string} - */ - this.token = process.env.CLIENT_TOKEN; - } else { - this.token = null; - } - - /** - * The ClientUser representing the logged in Client - * @type {?ClientUser} - */ - this.user = null; - - /** - * The date at which the Client was regarded as being in the `READY` state. - * @type {?Date} - */ - this.readyAt = null; - - /** - * The previous heartbeat pings of the websocket (most recent first, limited to three elements) - * @type {number[]} - */ - this.pings = []; - - this._pingTimestamp = 0; - this._timeouts = new Set(); - this._intervals = new Set(); - - if (this.options.messageSweepInterval > 0) { - this.setInterval(this.sweepMessages.bind(this), this.options.messageSweepInterval * 1000); - } - } - - /** - * The status for the logged in Client. - * @type {?number} - * @readonly - */ - get status() { - return this.ws.status; - } - - /** - * The uptime for the logged in Client. - * @type {?number} - * @readonly - */ - get uptime() { - return this.readyAt ? Date.now() - this.readyAt : null; - } - - /** - * The average heartbeat ping of the websocket - * @type {number} - * @readonly - */ - get ping() { - return this.pings.reduce((prev, p) => prev + p, 0) / this.pings.length; - } - - /** - * Returns a collection, mapping guild ID to voice connections. - * @type {Collection} - * @readonly - */ - get voiceConnections() { - if (this.browser) return new Collection(); - return this.voice.connections; - } - - /** - * The emojis that the client can use. Mapped by emoji ID. - * @type {Collection} - * @readonly - */ - get emojis() { - const emojis = new Collection(); - for (const guild of this.guilds.values()) { - for (const emoji of guild.emojis.values()) emojis.set(emoji.id, emoji); - } - return emojis; - } - - /** - * The timestamp that the client was last ready at - * @type {?number} - * @readonly - */ - get readyTimestamp() { - return this.readyAt ? this.readyAt.getTime() : null; - } - - /** - * Whether the client is in a browser environment - * @type {boolean} - * @readonly - */ - get browser() { - return typeof window !== 'undefined'; - } - - /** - * Logs the client in. If successful, resolves with the account's token. If you're making a bot, it's - * much better to use a bot account rather than a user account. - * Bot accounts have higher rate limits and have access to some features user accounts don't have. User bots - * that are making a lot of API requests can even be banned. - * @param {string} token The token used for the account. - * @returns {Promise} - * @example - * // log the client in using a token - * const token = 'my token'; - * client.login(token); - * @example - * // log the client in using email and password - * const email = 'user@email.com'; - * const password = 'supersecret123'; - * client.login(email, password); - */ - login(token) { - return this.rest.methods.login(token); - } - - /** - * Destroys the client and logs out. - * @returns {Promise} - */ - destroy() { - for (const t of this._timeouts) clearTimeout(t); - for (const i of this._intervals) clearInterval(i); - this._timeouts.clear(); - this._intervals.clear(); - return this.manager.destroy(); - } - - /** - * This shouldn't really be necessary to most developers as it is automatically invoked every 30 seconds, however - * if you wish to force a sync of guild data, you can use this. - * This is only available when using a user account. - * @param {Guild[]|Collection} [guilds=this.guilds] An array or collection of guilds to sync - */ - syncGuilds(guilds = this.guilds) { - if (this.user.bot) return; - this.ws.send({ - op: 12, - d: guilds instanceof Collection ? guilds.keyArray() : guilds.map(g => g.id), - }); - } - - /** - * Caches a user, or obtains it from the cache if it's already cached. - * This is only available when using a bot account. - * @param {string} id The ID of the user to obtain - * @returns {Promise} - */ - fetchUser(id) { - if (this.users.has(id)) return Promise.resolve(this.users.get(id)); - return this.rest.methods.getUser(id); - } - - /** - * Fetches an invite object from an invite code. - * @param {InviteResolvable} invite An invite code or URL - * @returns {Promise} - */ - fetchInvite(invite) { - const code = this.resolver.resolveInviteCode(invite); - return this.rest.methods.getInvite(code); - } - - /** - * Fetch a webhook by ID. - * @param {string} id ID of the webhook - * @param {string} [token] Token for the webhook - * @returns {Promise} - */ - fetchWebhook(id, token) { - return this.rest.methods.getWebhook(id, token); - } - - /** - * Sweeps all channels' messages and removes the ones older than the max message lifetime. - * If the message has been edited, the time of the edit is used rather than the time of the original message. - * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds) - * will be removed from the caches. The default is based on the client's `messageCacheLifetime` option. - * @returns {number} Amount of messages that were removed from the caches, - * or -1 if the message cache lifetime is unlimited - */ - sweepMessages(lifetime = this.options.messageCacheLifetime) { - if (typeof lifetime !== 'number' || isNaN(lifetime)) throw new TypeError('The lifetime must be a number.'); - if (lifetime <= 0) { - this.emit('debug', 'Didn\'t sweep messages - lifetime is unlimited'); - return -1; - } - - const lifetimeMs = lifetime * 1000; - const now = Date.now(); - let channels = 0; - let messages = 0; - - for (const channel of this.channels.values()) { - if (!channel.messages) continue; - channels++; - - for (const message of channel.messages.values()) { - if (now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs) { - channel.messages.delete(message.id); - messages++; - } - } - } - - this.emit('debug', `Swept ${messages} messages older than ${lifetime} seconds in ${channels} text-based channels`); - return messages; - } - - /** - * Gets the bot's OAuth2 application. - * This is only available when using a bot account. - * @returns {Promise} - */ - fetchApplication() { - if (!this.user.bot) throw new Error(Constants.Errors.NO_BOT_ACCOUNT); - return this.rest.methods.getMyApplication(); - } - - /** - * Generate an invite link for your bot - * @param {PermissionResolvable[]|number} [permissions] An array of permissions to request - * @returns {Promise} The invite link - * @example - * client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE']) - * .then(link => { - * console.log(`Generated bot invite link: ${link}`); - * }); - */ - generateInvite(permissions) { - if (permissions) { - if (permissions instanceof Array) permissions = this.resolver.resolvePermissions(permissions); - } else { - permissions = 0; - } - return this.fetchApplication().then(application => - `https://discordapp.com/oauth2/authorize?client_id=${application.id}&permissions=${permissions}&scope=bot` - ); - } - - /** - * Sets a timeout that will be automatically cancelled if the client is destroyed. - * @param {Function} fn Function to execute - * @param {number} delay Time to wait before executing (in milliseconds) - * @param {...*} args Arguments for the function - * @returns {Timeout} - */ - setTimeout(fn, delay, ...args) { - const timeout = setTimeout(() => { - fn(); - this._timeouts.delete(timeout); - }, delay, ...args); - this._timeouts.add(timeout); - return timeout; - } - - /** - * Clears a timeout - * @param {Timeout} timeout Timeout to cancel - */ - clearTimeout(timeout) { - clearTimeout(timeout); - this._timeouts.delete(timeout); - } - - /** - * Sets an interval that will be automatically cancelled if the client is destroyed. - * @param {Function} fn Function to execute - * @param {number} delay Time to wait before executing (in milliseconds) - * @param {...*} args Arguments for the function - * @returns {Timeout} - */ - setInterval(fn, delay, ...args) { - const interval = setInterval(fn, delay, ...args); - this._intervals.add(interval); - return interval; - } - - /** - * Clears an interval - * @param {Timeout} interval Interval to cancel - */ - clearInterval(interval) { - clearInterval(interval); - this._intervals.delete(interval); - } - - _pong(startTime) { - this.pings.unshift(Date.now() - startTime); - if (this.pings.length > 3) this.pings.length = 3; - this.ws.lastHeartbeatAck = true; - } - - _setPresence(id, presence) { - if (this.presences.get(id)) { - this.presences.get(id).update(presence); - return; - } - this.presences.set(id, new Presence(presence)); - } - - _eval(script) { - return eval(script); - } - - _validateOptions(options = this.options) { - if (typeof options.shardCount !== 'number' || isNaN(options.shardCount)) { - throw new TypeError('The shardCount option must be a number.'); - } - if (typeof options.shardId !== 'number' || isNaN(options.shardId)) { - throw new TypeError('The shardId option must be a number.'); - } - if (options.shardCount < 0) throw new RangeError('The shardCount option must be at least 0.'); - if (options.shardId < 0) throw new RangeError('The shardId option must be at least 0.'); - if (options.shardId !== 0 && options.shardId >= options.shardCount) { - throw new RangeError('The shardId option must be less than shardCount.'); - } - if (typeof options.messageCacheMaxSize !== 'number' || isNaN(options.messageCacheMaxSize)) { - throw new TypeError('The messageCacheMaxSize option must be a number.'); - } - if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) { - throw new TypeError('The messageCacheLifetime option must be a number.'); - } - if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) { - throw new TypeError('The messageSweepInterval option must be a number.'); - } - if (typeof options.fetchAllMembers !== 'boolean') { - throw new TypeError('The fetchAllMembers option must be a boolean.'); - } - if (typeof options.disableEveryone !== 'boolean') { - throw new TypeError('The disableEveryone option must be a boolean.'); - } - if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) { - throw new TypeError('The restWsBridgeTimeout option must be a number.'); - } - if (!(options.disabledEvents instanceof Array)) throw new TypeError('The disabledEvents option must be an Array.'); - } -} - -module.exports = Client; - -/** - * Emitted for general warnings - * @event Client#warn - * @param {string} info The warning - */ - -/** - * Emitted for general debugging information - * @event Client#debug - * @param {string} info The debug information - */ - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24))) - -/***/ }, -/* 56 */ -/***/ function(module, exports, __webpack_require__) { - -const Webhook = __webpack_require__(19); -const RESTManager = __webpack_require__(51); -const ClientDataResolver = __webpack_require__(50); -const mergeDefault = __webpack_require__(54); -const Constants = __webpack_require__(0); - -/** - * The Webhook Client - * @extends {Webhook} - */ -class WebhookClient extends Webhook { - /** - * @param {string} id The id of the webhook. - * @param {string} token the token of the webhook. - * @param {ClientOptions} [options] Options for the client - * @example - * // create a new webhook and send a message - * let hook = new Discord.WebhookClient('1234', 'abcdef') - * hook.sendMessage('This will send a message').catch(console.error) - */ - constructor(id, token, options) { - super(null, id, token); - - /** - * The options the client was instantiated with - * @type {ClientOptions} - */ - this.options = mergeDefault(Constants.DefaultOptions, options); - - /** - * The REST manager of the client - * @type {RESTManager} - * @private - */ - this.rest = new RESTManager(this); - - /** - * The Data Resolver of the Client - * @type {ClientDataResolver} - * @private - */ - this.resolver = new ClientDataResolver(this); - } -} - -module.exports = WebhookClient; - - -/***/ }, -/* 57 */ -/***/ function(module, exports, __webpack_require__) { - -module.exports = { - Client: __webpack_require__(55), - WebhookClient: __webpack_require__(56), - Shard: __webpack_require__(60), - ShardClientUtil: __webpack_require__(61), - ShardingManager: __webpack_require__(62), - - Collection: __webpack_require__(3), - splitMessage: __webpack_require__(43), - escapeMarkdown: __webpack_require__(15), - fetchRecommendedShards: __webpack_require__(59), - - Channel: __webpack_require__(9), - ClientOAuth2Application: __webpack_require__(28), - ClientUser: __webpack_require__(29), - DMChannel: __webpack_require__(30), - Emoji: __webpack_require__(10), - EvaluatedPermissions: __webpack_require__(16), - Game: __webpack_require__(7).Game, - GroupDMChannel: __webpack_require__(31), - Guild: __webpack_require__(17), - GuildChannel: __webpack_require__(13), - GuildMember: __webpack_require__(14), - Invite: __webpack_require__(32), - Message: __webpack_require__(11), - MessageAttachment: __webpack_require__(33), - MessageCollector: __webpack_require__(34), - MessageEmbed: __webpack_require__(35), - MessageReaction: __webpack_require__(36), - OAuth2Application: __webpack_require__(37), - PartialGuild: __webpack_require__(38), - PartialGuildChannel: __webpack_require__(39), - PermissionOverwrites: __webpack_require__(40), - Presence: __webpack_require__(7).Presence, - ReactionEmoji: __webpack_require__(18), - RichEmbed: __webpack_require__(58), - Role: __webpack_require__(8), - TextChannel: __webpack_require__(41), - User: __webpack_require__(6), - VoiceChannel: __webpack_require__(42), - Webhook: __webpack_require__(19), - - version: __webpack_require__(27).version, - Constants: __webpack_require__(0), -}; - -if (typeof window !== 'undefined') window.Discord = module.exports; // eslint-disable-line no-undef - - -/***/ }, -/* 58 */ -/***/ function(module, exports) { - -/** - * A rich embed to be sent with a message - * @param {Object} [data] Data to set in the rich embed - */ -class RichEmbed { - constructor(data = {}) { - /** - * Title for this Embed - * @type {string} - */ - this.title = data.title; - - /** - * Description for this Embed - * @type {string} - */ - this.description = data.description; - - /** - * URL for this Embed - * @type {string} - */ - this.url = data.url; - - /** - * Color for this Embed - * @type {number} - */ - this.color = data.color; - - /** - * Author for this Embed - * @type {Object} - */ - this.author = data.author; - - /** - * Timestamp for this Embed - * @type {Date} - */ - this.timestamp = data.timestamp; - - /** - * Fields for this Embed - * @type {Object[]} - */ - this.fields = data.fields || []; - - /** - * Thumbnail for this Embed - * @type {Object} - */ - this.thumbnail = data.thumbnail; - - /** - * Image for this Embed - * @type {Object} - */ - this.image = data.image; - - /** - * Footer for this Embed - * @type {Object} - */ - this.footer = data.footer; - } - - /** - * Sets the title of this embed - * @param {StringResolvable} title The title - * @returns {RichEmbed} This embed - */ - setTitle(title) { - title = resolveString(title); - if (title.length > 256) throw new RangeError('RichEmbed titles may not exceed 256 characters.'); - this.title = title; - return this; - } - - /** - * Sets the description of this embed - * @param {StringResolvable} description The description - * @returns {RichEmbed} This embed - */ - setDescription(description) { - description = resolveString(description); - if (description.length > 2048) throw new RangeError('RichEmbed descriptions may not exceed 2048 characters.'); - this.description = description; - return this; - } - - /** - * Sets the URL of this embed - * @param {string} url The URL - * @returns {RichEmbed} This embed - */ - setURL(url) { - this.url = url; - return this; - } - - /** - * Sets the color of this embed - * @param {string|number|number[]} color The color to set - * @returns {RichEmbed} This embed - */ - setColor(color) { - let radix = 10; - if (color instanceof Array) { - color = (color[0] << 16) + (color[1] << 8) + color[2]; - } else if (typeof color === 'string' && color.startsWith('#')) { - radix = 16; - color = color.replace('#', ''); - } - color = parseInt(color, radix); - if (color < 0 || color > 0xFFFFFF) { - throw new RangeError('RichEmbed color must be within the range 0 - 16777215 (0xFFFFFF).'); - } else if (color && isNaN(color)) { - throw new TypeError('Unable to convert RichEmbed color to a number.'); - } - this.color = color; - return this; - } - - /** - * Sets the author of this embed - * @param {StringResolvable} name The name of the author - * @param {string} [icon] The icon URL of the author - * @param {string} [url] The URL of the author - * @returns {RichEmbed} This embed - */ - setAuthor(name, icon, url) { - this.author = { name: resolveString(name), icon_url: icon, url }; - return this; - } - - /** - * Sets the timestamp of this embed - * @param {Date} [timestamp=current date] The timestamp - * @returns {RichEmbed} This embed - */ - setTimestamp(timestamp = new Date()) { - this.timestamp = timestamp; - return this; - } - - /** - * Adds a field to the embed (max 25) - * @param {StringResolvable} name The name of the field - * @param {StringResolvable} value The value of the field - * @param {boolean} [inline=false] Set the field to display inline - * @returns {RichEmbed} This embed - */ - addField(name, value, inline = false) { - if (this.fields.length >= 25) throw new RangeError('RichEmbeds may not exceed 25 fields.'); - name = resolveString(name); - if (name.length > 256) throw new RangeError('RichEmbed field names may not exceed 256 characters.'); - value = resolveString(value); - if (value.length > 1024) throw new RangeError('RichEmbed field values may not exceed 1024 characters.'); - this.fields.push({ name: String(name), value: value, inline }); - return this; - } - - /** - * Set the thumbnail of this embed - * @param {string} url The URL of the thumbnail - * @returns {RichEmbed} This embed - */ - setThumbnail(url) { - this.thumbnail = { url }; - return this; - } - - /** - * Set the image of this embed - * @param {string} url The URL of the thumbnail - * @returns {RichEmbed} This embed - */ - setImage(url) { - this.image = { url }; - return this; - } - - /** - * Sets the footer of this embed - * @param {StringResolvable} text The text of the footer - * @param {string} [icon] The icon URL of the footer - * @returns {RichEmbed} This embed - */ - setFooter(text, icon) { - text = resolveString(text); - if (text.length > 2048) throw new RangeError('RichEmbed footer text may not exceed 2048 characters.'); - this.footer = { text, icon_url: icon }; - return this; - } -} - -module.exports = RichEmbed; - -function resolveString(data) { - if (typeof data === 'string') return data; - if (data instanceof Array) return data.join('\n'); - return String(data); -} - - -/***/ }, -/* 59 */ -/***/ function(module, exports, __webpack_require__) { - -const superagent = __webpack_require__(25); -const botGateway = __webpack_require__(0).Endpoints.botGateway; - -/** - * Gets the recommended shard count from Discord - * @param {number} token Discord auth token - * @returns {Promise} the recommended number of shards - */ -module.exports = function fetchRecommendedShards(token) { - return new Promise((resolve, reject) => { - if (!token) throw new Error('A token must be provided.'); - superagent.get(botGateway) - .set('Authorization', `Bot ${token.replace(/^Bot\s*/i, '')}`) - .end((err, res) => { - if (err) reject(err); - resolve(res.body.shards); - }); - }); -}; - - -/***/ }, -/* 60 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 61 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 62 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 63 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} - -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return b64.length * 3 / 4 - placeHoldersCount(b64) -} - -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) - - arr = new Arr(len * 3 / 4 - placeHolders) - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len - - var L = 0 - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } - - parts.push(output) - - return parts.join('') -} - - -/***/ }, -/* 64 */ -/***/ function(module, exports, __webpack_require__) { - - -/** - * Expose `Emitter`. - */ - -if (true) { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; - - -/***/ }, -/* 65 */ -/***/ function(module, exports) { - -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - - -/***/ }, -/* 66 */ -/***/ function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }, -/* 67 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; -// Top level file is just a mixin of submodules & constants - - -var assign = __webpack_require__(5).assign; - -var deflate = __webpack_require__(68); -var inflate = __webpack_require__(69); -var constants = __webpack_require__(46); - -var pako = {}; - -assign(pako, deflate, inflate, constants); - -module.exports = pako; - - -/***/ }, -/* 68 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -var zlib_deflate = __webpack_require__(70); -var utils = __webpack_require__(5); -var strings = __webpack_require__(44); -var msg = __webpack_require__(22); -var ZStream = __webpack_require__(48); - -var toString = Object.prototype.toString; - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - -var Z_NO_FLUSH = 0; -var Z_FINISH = 4; - -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_SYNC_FLUSH = 2; - -var Z_DEFAULT_COMPRESSION = -1; - -var Z_DEFAULT_STRATEGY = 0; - -var Z_DEFLATED = 8; - -/* ===========================================================================*/ - - -/** - * class Deflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[deflate]], - * [[deflateRaw]] and [[gzip]]. - **/ - -/* internal - * Deflate.chunks -> Array - * - * Chunks of output data, if [[Deflate#onData]] not overriden. - **/ - -/** - * Deflate.result -> Uint8Array|Array - * - * Compressed result, generated by default [[Deflate#onData]] - * and [[Deflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Deflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Deflate.err -> Number - * - * Error code after deflate finished. 0 (Z_OK) on success. - * You will not need it in real life, because deflate errors - * are possible only on wrong options or bad `onData` / `onEnd` - * custom handlers. - **/ - -/** - * Deflate.msg -> String - * - * Error message, if [[Deflate.err]] != 0 - **/ - - -/** - * new Deflate(options) - * - options (Object): zlib deflate options. - * - * Creates new deflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `level` - * - `windowBits` - * - `memLevel` - * - `strategy` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw deflate - * - `gzip` (Boolean) - create gzip wrapper - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - `header` (Object) - custom header for gzip - * - `text` (Boolean) - true if compressed data believed to be text - * - `time` (Number) - modification time, unix timestamp - * - `os` (Number) - operation system code - * - `extra` (Array) - array of bytes with extra data (max 65536) - * - `name` (String) - file name (binary string) - * - `comment` (String) - comment (binary string) - * - `hcrc` (Boolean) - true if header crc should be added - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var deflate = new pako.Deflate({ level: 3}); - * - * deflate.push(chunk1, false); - * deflate.push(chunk2, true); // true -> last chunk - * - * if (deflate.err) { throw new Error(deflate.err); } - * - * console.log(deflate.result); - * ``` - **/ -function Deflate(options) { - if (!(this instanceof Deflate)) return new Deflate(options); - - this.options = utils.assign({ - level: Z_DEFAULT_COMPRESSION, - method: Z_DEFLATED, - chunkSize: 16384, - windowBits: 15, - memLevel: 8, - strategy: Z_DEFAULT_STRATEGY, - to: '' - }, options || {}); - - var opt = this.options; - - if (opt.raw && (opt.windowBits > 0)) { - opt.windowBits = -opt.windowBits; - } - - else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { - opt.windowBits += 16; - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = zlib_deflate.deflateInit2( - this.strm, - opt.level, - opt.method, - opt.windowBits, - opt.memLevel, - opt.strategy - ); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - if (opt.header) { - zlib_deflate.deflateSetHeader(this.strm, opt.header); - } - - if (opt.dictionary) { - var dict; - // Convert data if needed - if (typeof opt.dictionary === 'string') { - // If we need to compress text, change encoding to utf8. - dict = strings.string2buf(opt.dictionary); - } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { - dict = new Uint8Array(opt.dictionary); - } else { - dict = opt.dictionary; - } - - status = zlib_deflate.deflateSetDictionary(this.strm, dict); - - if (status !== Z_OK) { - throw new Error(msg[status]); - } - - this._dict_set = true; - } -} - -/** - * Deflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be - * converted to utf8 byte sequence. - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. - * - * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with - * new compressed chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the compression context. - * - * On fail call [[Deflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * array format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ -Deflate.prototype.push = function (data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var status, _mode; - - if (this.ended) { return false; } - - _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // If we need to compress text, change encoding to utf8. - strm.input = strings.string2buf(data); - } else if (toString.call(data) === '[object ArrayBuffer]') { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new utils.Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ - - if (status !== Z_STREAM_END && status !== Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { - if (this.options.to === 'string') { - this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); - } else { - this.onData(utils.shrinkBuf(strm.output, strm.next_out)); - } - } - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); - - // Finalize on the last chunk. - if (_mode === Z_FINISH) { - status = zlib_deflate.deflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === Z_SYNC_FLUSH) { - this.onEnd(Z_OK); - strm.avail_out = 0; - return true; - } - - return true; -}; - - -/** - * Deflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): ouput data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ -Deflate.prototype.onData = function (chunk) { - this.chunks.push(chunk); -}; - - -/** - * Deflate#onEnd(status) -> Void - * - status (Number): deflate status. 0 (Z_OK) on success, - * other if not. - * - * Called once after you tell deflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ -Deflate.prototype.onEnd = function (status) { - // On success - join - if (status === Z_OK) { - if (this.options.to === 'string') { - this.result = this.chunks.join(''); - } else { - this.result = utils.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; -}; - - -/** - * deflate(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * Compress `data` with deflate algorithm and `options`. - * - * Supported options are: - * - * - level - * - windowBits - * - memLevel - * - strategy - * - dictionary - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be "binary string" - * (each char code [0..255]) - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); - * - * console.log(pako.deflate(data)); - * ``` - **/ -function deflate(input, options) { - var deflator = new Deflate(options); - - deflator.push(input, true); - - // That will never happens, if you don't cheat with options :) - if (deflator.err) { throw deflator.msg || msg[deflator.err]; } - - return deflator.result; -} - - -/** - * deflateRaw(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * The same as [[deflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ -function deflateRaw(input, options) { - options = options || {}; - options.raw = true; - return deflate(input, options); -} - - -/** - * gzip(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to compress. - * - options (Object): zlib deflate options. - * - * The same as [[deflate]], but create gzip wrapper instead of - * deflate one. - **/ -function gzip(input, options) { - options = options || {}; - options.gzip = true; - return deflate(input, options); -} - - -exports.Deflate = Deflate; -exports.deflate = deflate; -exports.deflateRaw = deflateRaw; -exports.gzip = gzip; - - -/***/ }, -/* 69 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -var zlib_inflate = __webpack_require__(73); -var utils = __webpack_require__(5); -var strings = __webpack_require__(44); -var c = __webpack_require__(46); -var msg = __webpack_require__(22); -var ZStream = __webpack_require__(48); -var GZheader = __webpack_require__(71); - -var toString = Object.prototype.toString; - -/** - * class Inflate - * - * Generic JS-style wrapper for zlib calls. If you don't need - * streaming behaviour - use more simple functions: [[inflate]] - * and [[inflateRaw]]. - **/ - -/* internal - * inflate.chunks -> Array - * - * Chunks of output data, if [[Inflate#onData]] not overriden. - **/ - -/** - * Inflate.result -> Uint8Array|Array|String - * - * Uncompressed result, generated by default [[Inflate#onData]] - * and [[Inflate#onEnd]] handlers. Filled after you push last chunk - * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you - * push a chunk with explicit flush (call [[Inflate#push]] with - * `Z_SYNC_FLUSH` param). - **/ - -/** - * Inflate.err -> Number - * - * Error code after inflate finished. 0 (Z_OK) on success. - * Should be checked if broken data possible. - **/ - -/** - * Inflate.msg -> String - * - * Error message, if [[Inflate.err]] != 0 - **/ - - -/** - * new Inflate(options) - * - options (Object): zlib inflate options. - * - * Creates new inflator instance with specified params. Throws exception - * on bad params. Supported options: - * - * - `windowBits` - * - `dictionary` - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information on these. - * - * Additional options, for internal needs: - * - * - `chunkSize` - size of generated data chunks (16K by default) - * - `raw` (Boolean) - do raw inflate - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * By default, when no options set, autodetect deflate/gzip data format via - * wrapper header. - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) - * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); - * - * var inflate = new pako.Inflate({ level: 3}); - * - * inflate.push(chunk1, false); - * inflate.push(chunk2, true); // true -> last chunk - * - * if (inflate.err) { throw new Error(inflate.err); } - * - * console.log(inflate.result); - * ``` - **/ -function Inflate(options) { - if (!(this instanceof Inflate)) return new Inflate(options); - - this.options = utils.assign({ - chunkSize: 16384, - windowBits: 0, - to: '' - }, options || {}); - - var opt = this.options; - - // Force window size for `raw` data, if not set directly, - // because we have no header for autodetect. - if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { - opt.windowBits = -opt.windowBits; - if (opt.windowBits === 0) { opt.windowBits = -15; } - } - - // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate - if ((opt.windowBits >= 0) && (opt.windowBits < 16) && - !(options && options.windowBits)) { - opt.windowBits += 32; - } - - // Gzip header has no info about windows size, we can do autodetect only - // for deflate. So, if window size not set, force it to max when gzip possible - if ((opt.windowBits > 15) && (opt.windowBits < 48)) { - // bit 3 (16) -> gzipped data - // bit 4 (32) -> autodetect gzip/deflate - if ((opt.windowBits & 15) === 0) { - opt.windowBits |= 15; - } - } - - this.err = 0; // error code, if happens (0 = Z_OK) - this.msg = ''; // error message - this.ended = false; // used to avoid multiple onEnd() calls - this.chunks = []; // chunks of compressed data - - this.strm = new ZStream(); - this.strm.avail_out = 0; - - var status = zlib_inflate.inflateInit2( - this.strm, - opt.windowBits - ); - - if (status !== c.Z_OK) { - throw new Error(msg[status]); - } - - this.header = new GZheader(); - - zlib_inflate.inflateGetHeader(this.strm, this.header); -} - -/** - * Inflate#push(data[, mode]) -> Boolean - * - data (Uint8Array|Array|ArrayBuffer|String): input data - * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. - * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. - * - * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with - * new output chunks. Returns `true` on success. The last data block must have - * mode Z_FINISH (or `true`). That will flush internal pending buffers and call - * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you - * can use mode Z_SYNC_FLUSH, keeping the decompression context. - * - * On fail call [[Inflate#onEnd]] with error code and return false. - * - * We strongly recommend to use `Uint8Array` on input for best speed (output - * format is detected automatically). Also, don't skip last param and always - * use the same type in your code (boolean or number). That will improve JS speed. - * - * For regular `Array`-s make sure all elements are [0..255]. - * - * ##### Example - * - * ```javascript - * push(chunk, false); // push one of data chunks - * ... - * push(chunk, true); // push last chunk - * ``` - **/ -Inflate.prototype.push = function (data, mode) { - var strm = this.strm; - var chunkSize = this.options.chunkSize; - var dictionary = this.options.dictionary; - var status, _mode; - var next_out_utf8, tail, utf8str; - var dict; - - // Flag to properly process Z_BUF_ERROR on testing inflate call - // when we check that all output data was flushed. - var allowBufError = false; - - if (this.ended) { return false; } - _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); - - // Convert data if needed - if (typeof data === 'string') { - // Only binary strings can be decompressed on practice - strm.input = strings.binstring2buf(data); - } else if (toString.call(data) === '[object ArrayBuffer]') { - strm.input = new Uint8Array(data); - } else { - strm.input = data; - } - - strm.next_in = 0; - strm.avail_in = strm.input.length; - - do { - if (strm.avail_out === 0) { - strm.output = new utils.Buf8(chunkSize); - strm.next_out = 0; - strm.avail_out = chunkSize; - } - - status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ - - if (status === c.Z_NEED_DICT && dictionary) { - // Convert data if needed - if (typeof dictionary === 'string') { - dict = strings.string2buf(dictionary); - } else if (toString.call(dictionary) === '[object ArrayBuffer]') { - dict = new Uint8Array(dictionary); - } else { - dict = dictionary; - } - - status = zlib_inflate.inflateSetDictionary(this.strm, dict); - - } - - if (status === c.Z_BUF_ERROR && allowBufError === true) { - status = c.Z_OK; - allowBufError = false; - } - - if (status !== c.Z_STREAM_END && status !== c.Z_OK) { - this.onEnd(status); - this.ended = true; - return false; - } - - if (strm.next_out) { - if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { - - if (this.options.to === 'string') { - - next_out_utf8 = strings.utf8border(strm.output, strm.next_out); - - tail = strm.next_out - next_out_utf8; - utf8str = strings.buf2string(strm.output, next_out_utf8); - - // move tail - strm.next_out = tail; - strm.avail_out = chunkSize - tail; - if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } - - this.onData(utf8str); - - } else { - this.onData(utils.shrinkBuf(strm.output, strm.next_out)); - } - } - } - - // When no more input data, we should check that internal inflate buffers - // are flushed. The only way to do it when avail_out = 0 - run one more - // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. - // Here we set flag to process this error properly. - // - // NOTE. Deflate does not return error in this case and does not needs such - // logic. - if (strm.avail_in === 0 && strm.avail_out === 0) { - allowBufError = true; - } - - } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); - - if (status === c.Z_STREAM_END) { - _mode = c.Z_FINISH; - } - - // Finalize on the last chunk. - if (_mode === c.Z_FINISH) { - status = zlib_inflate.inflateEnd(this.strm); - this.onEnd(status); - this.ended = true; - return status === c.Z_OK; - } - - // callback interim results if Z_SYNC_FLUSH. - if (_mode === c.Z_SYNC_FLUSH) { - this.onEnd(c.Z_OK); - strm.avail_out = 0; - return true; - } - - return true; -}; - - -/** - * Inflate#onData(chunk) -> Void - * - chunk (Uint8Array|Array|String): ouput data. Type of array depends - * on js engine support. When string output requested, each chunk - * will be string. - * - * By default, stores data blocks in `chunks[]` property and glue - * those in `onEnd`. Override this handler, if you need another behaviour. - **/ -Inflate.prototype.onData = function (chunk) { - this.chunks.push(chunk); -}; - - -/** - * Inflate#onEnd(status) -> Void - * - status (Number): inflate status. 0 (Z_OK) on success, - * other if not. - * - * Called either after you tell inflate that the input stream is - * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) - * or if an error happened. By default - join collected chunks, - * free memory and fill `results` / `err` properties. - **/ -Inflate.prototype.onEnd = function (status) { - // On success - join - if (status === c.Z_OK) { - if (this.options.to === 'string') { - // Glue & convert here, until we teach pako to send - // utf8 alligned strings to onData - this.result = this.chunks.join(''); - } else { - this.result = utils.flattenChunks(this.chunks); - } - } - this.chunks = []; - this.err = status; - this.msg = this.strm.msg; -}; - - -/** - * inflate(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * Decompress `data` with inflate/ungzip and `options`. Autodetect - * format via wrapper header by default. That's why we don't provide - * separate `ungzip` method. - * - * Supported options are: - * - * - windowBits - * - * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) - * for more information. - * - * Sugar (options): - * - * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify - * negative windowBits implicitly. - * - `to` (String) - if equal to 'string', then result will be converted - * from utf8 to utf16 (javascript) string. When string output requested, - * chunk length can differ from `chunkSize`, depending on content. - * - * - * ##### Example: - * - * ```javascript - * var pako = require('pako') - * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) - * , output; - * - * try { - * output = pako.inflate(input); - * } catch (err) - * console.log(err); - * } - * ``` - **/ -function inflate(input, options) { - var inflator = new Inflate(options); - - inflator.push(input, true); - - // That will never happens, if you don't cheat with options :) - if (inflator.err) { throw inflator.msg || msg[inflator.err]; } - - return inflator.result; -} - - -/** - * inflateRaw(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * The same as [[inflate]], but creates raw data, without wrapper - * (header and adler32 crc). - **/ -function inflateRaw(input, options) { - options = options || {}; - options.raw = true; - return inflate(input, options); -} - - -/** - * ungzip(data[, options]) -> Uint8Array|Array|String - * - data (Uint8Array|Array|String): input data to decompress. - * - options (Object): zlib inflate options. - * - * Just shortcut to [[inflate]], because it autodetects format - * by header.content. Done for convenience. - **/ - - -exports.Inflate = Inflate; -exports.inflate = inflate; -exports.inflateRaw = inflateRaw; -exports.ungzip = inflate; - - -/***/ }, -/* 70 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(5); -var trees = __webpack_require__(75); -var adler32 = __webpack_require__(45); -var crc32 = __webpack_require__(47); -var msg = __webpack_require__(22); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -var Z_NO_FLUSH = 0; -var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -//var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -//var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -//var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - - -/* compression levels */ -//var Z_NO_COMPRESSION = 0; -//var Z_BEST_SPEED = 1; -//var Z_BEST_COMPRESSION = 9; -var Z_DEFAULT_COMPRESSION = -1; - - -var Z_FILTERED = 1; -var Z_HUFFMAN_ONLY = 2; -var Z_RLE = 3; -var Z_FIXED = 4; -var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -//var Z_BINARY = 0; -//var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - - -/* The deflate compression method */ -var Z_DEFLATED = 8; - -/*============================================================================*/ - - -var MAX_MEM_LEVEL = 9; -/* Maximum value for memLevel in deflateInit2 */ -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_MEM_LEVEL = 8; - - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ -var LITERALS = 256; -/* number of literal bytes 0..255 */ -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ -var D_CODES = 30; -/* number of distance codes */ -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ -var HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); - -var PRESET_DICT = 0x20; - -var INIT_STATE = 42; -var EXTRA_STATE = 69; -var NAME_STATE = 73; -var COMMENT_STATE = 91; -var HCRC_STATE = 103; -var BUSY_STATE = 113; -var FINISH_STATE = 666; - -var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ -var BS_BLOCK_DONE = 2; /* block flush performed */ -var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ -var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ - -var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. - -function err(strm, errorCode) { - strm.msg = msg[errorCode]; - return errorCode; -} - -function rank(f) { - return ((f) << 1) - ((f) > 4 ? 9 : 0); -} - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->output buffer and copying into it. - * (See also read_buf()). - */ -function flush_pending(strm) { - var s = strm.state; - - //_tr_flush_bits(s); - var len = s.pending; - if (len > strm.avail_out) { - len = strm.avail_out; - } - if (len === 0) { return; } - - utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); - strm.next_out += len; - s.pending_out += len; - strm.total_out += len; - strm.avail_out -= len; - s.pending -= len; - if (s.pending === 0) { - s.pending_out = 0; - } -} - - -function flush_block_only(s, last) { - trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); - s.block_start = s.strstart; - flush_pending(s.strm); -} - - -function put_byte(s, b) { - s.pending_buf[s.pending++] = b; -} - - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -function putShortMSB(s, b) { -// put_byte(s, (Byte)(b >> 8)); -// put_byte(s, (Byte)(b & 0xff)); - s.pending_buf[s.pending++] = (b >>> 8) & 0xff; - s.pending_buf[s.pending++] = b & 0xff; -} - - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->input buffer and copying from it. - * (See also flush_pending()). - */ -function read_buf(strm, buf, start, size) { - var len = strm.avail_in; - - if (len > size) { len = size; } - if (len === 0) { return 0; } - - strm.avail_in -= len; - - // zmemcpy(buf, strm->next_in, len); - utils.arraySet(buf, strm.input, strm.next_in, len, start); - if (strm.state.wrap === 1) { - strm.adler = adler32(strm.adler, buf, len, start); - } - - else if (strm.state.wrap === 2) { - strm.adler = crc32(strm.adler, buf, len, start); - } - - strm.next_in += len; - strm.total_in += len; - - return len; -} - - -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -function longest_match(s, cur_match) { - var chain_length = s.max_chain_length; /* max hash chain length */ - var scan = s.strstart; /* current string */ - var match; /* matched string */ - var len; /* length of current match */ - var best_len = s.prev_length; /* best match length so far */ - var nice_match = s.nice_match; /* stop if match long enough */ - var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? - s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; - - var _win = s.window; // shortcut - - var wmask = s.w_mask; - var prev = s.prev; - - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - - var strend = s.strstart + MAX_MATCH; - var scan_end1 = _win[scan + best_len - 1]; - var scan_end = _win[scan + best_len]; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s.prev_length >= s.good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (nice_match > s.lookahead) { nice_match = s.lookahead; } - - // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - // Assert(cur_match < s->strstart, "no future"); - match = cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ - - if (_win[match + best_len] !== scan_end || - _win[match + best_len - 1] !== scan_end1 || - _win[match] !== _win[scan] || - _win[++match] !== _win[scan + 1]) { - continue; - } - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2; - match++; - // Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - /*jshint noempty:false*/ - } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && - scan < strend); - - // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (strend - scan); - scan = strend - MAX_MATCH; - - if (len > best_len) { - s.match_start = cur_match; - best_len = len; - if (len >= nice_match) { - break; - } - scan_end1 = _win[scan + best_len - 1]; - scan_end = _win[scan + best_len]; - } - } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); - - if (best_len <= s.lookahead) { - return best_len; - } - return s.lookahead; -} - - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -function fill_window(s) { - var _w_size = s.w_size; - var p, n, m, more, str; - - //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); - - do { - more = s.window_size - s.lookahead - s.strstart; - - // JS ints have 32 bit, block below not needed - /* Deal with !@#$% 64K limit: */ - //if (sizeof(int) <= 2) { - // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - // more = wsize; - // - // } else if (more == (unsigned)(-1)) { - // /* Very unlikely, but possible on 16 bit machine if - // * strstart == 0 && lookahead == 1 (input done a byte at time) - // */ - // more--; - // } - //} - - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { - - utils.arraySet(s.window, s.window, _w_size, _w_size, 0); - s.match_start -= _w_size; - s.strstart -= _w_size; - /* we now have strstart >= MAX_DIST */ - s.block_start -= _w_size; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - - n = s.hash_size; - p = n; - do { - m = s.head[--p]; - s.head[p] = (m >= _w_size ? m - _w_size : 0); - } while (--n); - - n = _w_size; - p = n; - do { - m = s.prev[--p]; - s.prev[p] = (m >= _w_size ? m - _w_size : 0); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); - - more += _w_size; - } - if (s.strm.avail_in === 0) { - break; - } - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - //Assert(more >= 2, "more < 2"); - n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); - s.lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s.lookahead + s.insert >= MIN_MATCH) { - str = s.strstart - s.insert; - s.ins_h = s.window[str]; - - /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; -//#if MIN_MATCH != 3 -// Call update_hash() MIN_MATCH-3 more times -//#endif - while (s.insert) { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = str; - str++; - s.insert--; - if (s.lookahead + s.insert < MIN_MATCH) { - break; - } - } - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); - - /* If the WIN_INIT bytes after the end of the current data have never been - * written, then zero those bytes in order to avoid memory check reports of - * the use of uninitialized (or uninitialised as Julian writes) bytes by - * the longest match routines. Update the high water mark for the next - * time through here. WIN_INIT is set to MAX_MATCH since the longest match - * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. - */ -// if (s.high_water < s.window_size) { -// var curr = s.strstart + s.lookahead; -// var init = 0; -// -// if (s.high_water < curr) { -// /* Previous high water mark below current data -- zero WIN_INIT -// * bytes or up to end of window, whichever is less. -// */ -// init = s.window_size - curr; -// if (init > WIN_INIT) -// init = WIN_INIT; -// zmemzero(s->window + curr, (unsigned)init); -// s->high_water = curr + init; -// } -// else if (s->high_water < (ulg)curr + WIN_INIT) { -// /* High water mark at or above current data, but below current data -// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up -// * to end of window, whichever is less. -// */ -// init = (ulg)curr + WIN_INIT - s->high_water; -// if (init > s->window_size - s->high_water) -// init = s->window_size - s->high_water; -// zmemzero(s->window + s->high_water, (unsigned)init); -// s->high_water += init; -// } -// } -// -// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, -// "not enough room for search"); -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -function deflate_stored(s, flush) { - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - var max_block_size = 0xffff; - - if (max_block_size > s.pending_buf_size - 5) { - max_block_size = s.pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s.lookahead <= 1) { - - //Assert(s->strstart < s->w_size+MAX_DIST(s) || - // s->block_start >= (long)s->w_size, "slide too late"); -// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || -// s.block_start >= s.w_size)) { -// throw new Error("slide too late"); -// } - - fill_window(s); - if (s.lookahead === 0 && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - - if (s.lookahead === 0) { - break; - } - /* flush the current block */ - } - //Assert(s->block_start >= 0L, "block gone"); -// if (s.block_start < 0) throw new Error("block gone"); - - s.strstart += s.lookahead; - s.lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - var max_start = s.block_start + max_block_size; - - if (s.strstart === 0 || s.strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s.lookahead = s.strstart - max_start; - s.strstart = max_start; - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - - - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - - s.insert = 0; - - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - - if (s.strstart > s.block_start) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_NEED_MORE; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -function deflate_fast(s, flush) { - var hash_head; /* head of the hash chain */ - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { - break; /* flush the current block */ - } - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - } - if (s.match_length >= MIN_MATCH) { - // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only - - /*** _tr_tally_dist(s, s.strstart - s.match_start, - s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ - if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { - s.match_length--; /* string at strstart already in table */ - do { - s.strstart++; - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s.match_length !== 0); - s.strstart++; - } else - { - s.strstart += s.match_length; - s.match_length = 0; - s.ins_h = s.window[s.strstart]; - /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; - -//#if MIN_MATCH != 3 -// Call UPDATE_HASH() MIN_MATCH-3 more times -//#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s.window[s.strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -function deflate_slow(s, flush) { - var hash_head; /* head of hash chain */ - var bflush; /* set if current block must be flushed */ - - var max_insert; - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s.lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - hash_head = 0/*NIL*/; - if (s.lookahead >= MIN_MATCH) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - - /* Find the longest match, discarding those <= prev_length. - */ - s.prev_length = s.match_length; - s.prev_match = s.match_start; - s.match_length = MIN_MATCH - 1; - - if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && - s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - s.match_length = longest_match(s, hash_head); - /* longest_match() sets match_start */ - - if (s.match_length <= 5 && - (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s.match_length = MIN_MATCH - 1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { - max_insert = s.strstart + s.lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - //check_match(s, s.strstart-1, s.prev_match, s.prev_length); - - /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, - s.prev_length - MIN_MATCH, bflush);***/ - bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s.lookahead -= s.prev_length - 1; - s.prev_length -= 2; - do { - if (++s.strstart <= max_insert) { - /*** INSERT_STRING(s, s.strstart, hash_head); ***/ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; - hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; - s.head[s.ins_h] = s.strstart; - /***/ - } - } while (--s.prev_length !== 0); - s.match_available = 0; - s.match_length = MIN_MATCH - 1; - s.strstart++; - - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - } else if (s.match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - - if (bflush) { - /*** FLUSH_BLOCK_ONLY(s, 0) ***/ - flush_block_only(s, false); - /***/ - } - s.strstart++; - s.lookahead--; - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s.match_available = 1; - s.strstart++; - s.lookahead--; - } - } - //Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s.match_available) { - //Tracevv((stderr,"%c", s->window[s->strstart-1])); - /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); - - s.match_available = 0; - } - s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - - return BS_BLOCK_DONE; -} - - -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -function deflate_rle(s, flush) { - var bflush; /* set if current block must be flushed */ - var prev; /* byte at distance one to match */ - var scan, strend; /* scan goes up to strend for length of run */ - - var _win = s.window; - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest run, plus one for the unrolled loop. - */ - if (s.lookahead <= MAX_MATCH) { - fill_window(s); - if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - if (s.lookahead === 0) { break; } /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - s.match_length = 0; - if (s.lookahead >= MIN_MATCH && s.strstart > 0) { - scan = s.strstart - 1; - prev = _win[scan]; - if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { - strend = s.strstart + MAX_MATCH; - do { - /*jshint noempty:false*/ - } while (prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - prev === _win[++scan] && prev === _win[++scan] && - scan < strend); - s.match_length = MAX_MATCH - (strend - scan); - if (s.match_length > s.lookahead) { - s.match_length = s.lookahead; - } - } - //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (s.match_length >= MIN_MATCH) { - //check_match(s, s.strstart, s.strstart - 1, s.match_length); - - /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ - bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); - - s.lookahead -= s.match_length; - s.strstart += s.match_length; - s.match_length = 0; - } else { - /* No match, output a literal byte */ - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - - s.lookahead--; - s.strstart++; - } - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* =========================================================================== - * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. - * (It will be regenerated if this run of deflate switches away from Huffman.) - */ -function deflate_huff(s, flush) { - var bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we have a literal to write. */ - if (s.lookahead === 0) { - fill_window(s); - if (s.lookahead === 0) { - if (flush === Z_NO_FLUSH) { - return BS_NEED_MORE; - } - break; /* flush the current block */ - } - } - - /* Output a literal byte */ - s.match_length = 0; - //Tracevv((stderr,"%c", s->window[s->strstart])); - /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ - bflush = trees._tr_tally(s, 0, s.window[s.strstart]); - s.lookahead--; - s.strstart++; - if (bflush) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - } - s.insert = 0; - if (flush === Z_FINISH) { - /*** FLUSH_BLOCK(s, 1); ***/ - flush_block_only(s, true); - if (s.strm.avail_out === 0) { - return BS_FINISH_STARTED; - } - /***/ - return BS_FINISH_DONE; - } - if (s.last_lit) { - /*** FLUSH_BLOCK(s, 0); ***/ - flush_block_only(s, false); - if (s.strm.avail_out === 0) { - return BS_NEED_MORE; - } - /***/ - } - return BS_BLOCK_DONE; -} - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -function Config(good_length, max_lazy, nice_length, max_chain, func) { - this.good_length = good_length; - this.max_lazy = max_lazy; - this.nice_length = nice_length; - this.max_chain = max_chain; - this.func = func; -} - -var configuration_table; - -configuration_table = [ - /* good lazy nice chain */ - new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ - new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ - new Config(4, 5, 16, 8, deflate_fast), /* 2 */ - new Config(4, 6, 32, 32, deflate_fast), /* 3 */ - - new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ - new Config(8, 16, 32, 32, deflate_slow), /* 5 */ - new Config(8, 16, 128, 128, deflate_slow), /* 6 */ - new Config(8, 32, 128, 256, deflate_slow), /* 7 */ - new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ - new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ -]; - - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -function lm_init(s) { - s.window_size = 2 * s.w_size; - - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - - /* Set the default configuration parameters: - */ - s.max_lazy_match = configuration_table[s.level].max_lazy; - s.good_match = configuration_table[s.level].good_length; - s.nice_match = configuration_table[s.level].nice_length; - s.max_chain_length = configuration_table[s.level].max_chain; - - s.strstart = 0; - s.block_start = 0; - s.lookahead = 0; - s.insert = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - s.ins_h = 0; -} - - -function DeflateState() { - this.strm = null; /* pointer back to this zlib stream */ - this.status = 0; /* as the name implies */ - this.pending_buf = null; /* output still pending */ - this.pending_buf_size = 0; /* size of pending_buf */ - this.pending_out = 0; /* next pending byte to output to the stream */ - this.pending = 0; /* nb of bytes in the pending buffer */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.gzhead = null; /* gzip header information to write */ - this.gzindex = 0; /* where in extra, name, or comment */ - this.method = Z_DEFLATED; /* can only be DEFLATED */ - this.last_flush = -1; /* value of flush param for previous deflate call */ - - this.w_size = 0; /* LZ77 window size (32K by default) */ - this.w_bits = 0; /* log2(w_size) (8..16) */ - this.w_mask = 0; /* w_size - 1 */ - - this.window = null; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. - */ - - this.window_size = 0; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - this.prev = null; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - this.head = null; /* Heads of the hash chains or NIL. */ - - this.ins_h = 0; /* hash index of string to be inserted */ - this.hash_size = 0; /* number of elements in hash table */ - this.hash_bits = 0; /* log2(hash_size) */ - this.hash_mask = 0; /* hash_size-1 */ - - this.hash_shift = 0; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - this.block_start = 0; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - this.match_length = 0; /* length of best match */ - this.prev_match = 0; /* previous match */ - this.match_available = 0; /* set if previous match exists */ - this.strstart = 0; /* start of string to insert */ - this.match_start = 0; /* start of matching string */ - this.lookahead = 0; /* number of valid bytes ahead in window */ - - this.prev_length = 0; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - this.max_chain_length = 0; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - this.max_lazy_match = 0; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ - // That's alias to max_lazy_match, don't use directly - //this.max_insert_length = 0; - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - this.level = 0; /* compression level (1..9) */ - this.strategy = 0; /* favor or force Huffman coding*/ - - this.good_match = 0; - /* Use a faster search when the previous match is longer than this */ - - this.nice_match = 0; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - - /* Didn't use ct_data typedef below to suppress compiler warning */ - - // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - // Use flat array of DOUBLE size, with interleaved fata, - // because JS does not support effective - this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); - this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); - this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); - zero(this.dyn_ltree); - zero(this.dyn_dtree); - zero(this.bl_tree); - - this.l_desc = null; /* desc. for literal tree */ - this.d_desc = null; /* desc. for distance tree */ - this.bl_desc = null; /* desc. for bit length tree */ - - //ush bl_count[MAX_BITS+1]; - this.bl_count = new utils.Buf16(MAX_BITS + 1); - /* number of codes at each bit length for an optimal tree */ - - //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ - zero(this.heap); - - this.heap_len = 0; /* number of elements in the heap */ - this.heap_max = 0; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; - zero(this.depth); - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - this.l_buf = 0; /* buffer index for literals or lengths */ - - this.lit_bufsize = 0; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - this.last_lit = 0; /* running index in l_buf */ - - this.d_buf = 0; - /* Buffer index for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - this.opt_len = 0; /* bit length of current block with optimal trees */ - this.static_len = 0; /* bit length of current block with static trees */ - this.matches = 0; /* number of string matches in current block */ - this.insert = 0; /* bytes at end of window left to insert */ - - - this.bi_buf = 0; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - this.bi_valid = 0; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - - // Used for window memory init. We safely ignore it for JS. That makes - // sense only for pointers and memory check tools. - //this.high_water = 0; - /* High water mark offset in window for initialized bytes -- bytes above - * this are set to zero in order to avoid memory check warnings when - * longest match routines access bytes past the input. This is then - * updated to the new high water mark. - */ -} - - -function deflateResetKeep(strm) { - var s; - - if (!strm || !strm.state) { - return err(strm, Z_STREAM_ERROR); - } - - strm.total_in = strm.total_out = 0; - strm.data_type = Z_UNKNOWN; - - s = strm.state; - s.pending = 0; - s.pending_out = 0; - - if (s.wrap < 0) { - s.wrap = -s.wrap; - /* was made negative by deflate(..., Z_FINISH); */ - } - s.status = (s.wrap ? INIT_STATE : BUSY_STATE); - strm.adler = (s.wrap === 2) ? - 0 // crc32(0, Z_NULL, 0) - : - 1; // adler32(0, Z_NULL, 0) - s.last_flush = Z_NO_FLUSH; - trees._tr_init(s); - return Z_OK; -} - - -function deflateReset(strm) { - var ret = deflateResetKeep(strm); - if (ret === Z_OK) { - lm_init(strm.state); - } - return ret; -} - - -function deflateSetHeader(strm, head) { - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } - strm.state.gzhead = head; - return Z_OK; -} - - -function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { - if (!strm) { // === Z_NULL - return Z_STREAM_ERROR; - } - var wrap = 1; - - if (level === Z_DEFAULT_COMPRESSION) { - level = 6; - } - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } - - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } - - - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return err(strm, Z_STREAM_ERROR); - } - - - if (windowBits === 8) { - windowBits = 9; - } - /* until 256-byte window bug fixed */ - - var s = new DeflateState(); - - strm.state = s; - s.strm = strm; - - s.wrap = wrap; - s.gzhead = null; - s.w_bits = windowBits; - s.w_size = 1 << s.w_bits; - s.w_mask = s.w_size - 1; - - s.hash_bits = memLevel + 7; - s.hash_size = 1 << s.hash_bits; - s.hash_mask = s.hash_size - 1; - s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); - - s.window = new utils.Buf8(s.w_size * 2); - s.head = new utils.Buf16(s.hash_size); - s.prev = new utils.Buf16(s.w_size); - - // Don't need mem init magic for JS. - //s.high_water = 0; /* nothing written to s->window yet */ - - s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - s.pending_buf_size = s.lit_bufsize * 4; - - //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - //s->pending_buf = (uchf *) overlay; - s.pending_buf = new utils.Buf8(s.pending_buf_size); - - // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) - //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s.d_buf = 1 * s.lit_bufsize; - - //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - s.l_buf = (1 + 2) * s.lit_bufsize; - - s.level = level; - s.strategy = strategy; - s.method = method; - - return deflateReset(strm); -} - -function deflateInit(strm, level) { - return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); -} - - -function deflate(strm, flush) { - var old_flush, s; - var beg, val; // for gzip header write only - - if (!strm || !strm.state || - flush > Z_BLOCK || flush < 0) { - return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; - } - - s = strm.state; - - if (!strm.output || - (!strm.input && strm.avail_in !== 0) || - (s.status === FINISH_STATE && flush !== Z_FINISH)) { - return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); - } - - s.strm = strm; /* just in case */ - old_flush = s.last_flush; - s.last_flush = flush; - - /* Write the header */ - if (s.status === INIT_STATE) { - - if (s.wrap === 2) { // GZIP header - strm.adler = 0; //crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (!s.gzhead) { // s->gzhead == Z_NULL - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s.status = BUSY_STATE; - } - else { - put_byte(s, (s.gzhead.text ? 1 : 0) + - (s.gzhead.hcrc ? 2 : 0) + - (!s.gzhead.extra ? 0 : 4) + - (!s.gzhead.name ? 0 : 8) + - (!s.gzhead.comment ? 0 : 16) - ); - put_byte(s, s.gzhead.time & 0xff); - put_byte(s, (s.gzhead.time >> 8) & 0xff); - put_byte(s, (s.gzhead.time >> 16) & 0xff); - put_byte(s, (s.gzhead.time >> 24) & 0xff); - put_byte(s, s.level === 9 ? 2 : - (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? - 4 : 0)); - put_byte(s, s.gzhead.os & 0xff); - if (s.gzhead.extra && s.gzhead.extra.length) { - put_byte(s, s.gzhead.extra.length & 0xff); - put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); - } - if (s.gzhead.hcrc) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); - } - s.gzindex = 0; - s.status = EXTRA_STATE; - } - } - else // DEFLATE header - { - var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; - var level_flags = -1; - - if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { - level_flags = 0; - } else if (s.level < 6) { - level_flags = 1; - } else if (s.level === 6) { - level_flags = 2; - } else { - level_flags = 3; - } - header |= (level_flags << 6); - if (s.strstart !== 0) { header |= PRESET_DICT; } - header += 31 - (header % 31); - - s.status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s.strstart !== 0) { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - strm.adler = 1; // adler32(0L, Z_NULL, 0); - } - } - -//#ifdef GZIP - if (s.status === EXTRA_STATE) { - if (s.gzhead.extra/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - - while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - break; - } - } - put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); - s.gzindex++; - } - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (s.gzindex === s.gzhead.extra.length) { - s.gzindex = 0; - s.status = NAME_STATE; - } - } - else { - s.status = NAME_STATE; - } - } - if (s.status === NAME_STATE) { - if (s.gzhead.name/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.name.length) { - val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.gzindex = 0; - s.status = COMMENT_STATE; - } - } - else { - s.status = COMMENT_STATE; - } - } - if (s.status === COMMENT_STATE) { - if (s.gzhead.comment/* != Z_NULL*/) { - beg = s.pending; /* start of bytes to update crc */ - //int val; - - do { - if (s.pending === s.pending_buf_size) { - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - flush_pending(strm); - beg = s.pending; - if (s.pending === s.pending_buf_size) { - val = 1; - break; - } - } - // JS specific: little magic to add zero terminator to end of string - if (s.gzindex < s.gzhead.comment.length) { - val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; - } else { - val = 0; - } - put_byte(s, val); - } while (val !== 0); - - if (s.gzhead.hcrc && s.pending > beg) { - strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); - } - if (val === 0) { - s.status = HCRC_STATE; - } - } - else { - s.status = HCRC_STATE; - } - } - if (s.status === HCRC_STATE) { - if (s.gzhead.hcrc) { - if (s.pending + 2 > s.pending_buf_size) { - flush_pending(strm); - } - if (s.pending + 2 <= s.pending_buf_size) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - strm.adler = 0; //crc32(0L, Z_NULL, 0); - s.status = BUSY_STATE; - } - } - else { - s.status = BUSY_STATE; - } - } -//#endif - - /* Flush as much pending output as possible */ - if (s.pending !== 0) { - flush_pending(strm); - if (strm.avail_out === 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s.last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && - flush !== Z_FINISH) { - return err(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s.status === FINISH_STATE && strm.avail_in !== 0) { - return err(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm.avail_in !== 0 || s.lookahead !== 0 || - (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { - var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : - (s.strategy === Z_RLE ? deflate_rle(s, flush) : - configuration_table[s.level].func(s, flush)); - - if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { - s.status = FINISH_STATE; - } - if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { - if (strm.avail_out === 0) { - s.last_flush = -1; - /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate === BS_BLOCK_DONE) { - if (flush === Z_PARTIAL_FLUSH) { - trees._tr_align(s); - } - else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ - - trees._tr_stored_block(s, 0, 0, false); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush === Z_FULL_FLUSH) { - /*** CLEAR_HASH(s); ***/ /* forget history */ - zero(s.head); // Fill with NIL (= 0); - - if (s.lookahead === 0) { - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - } - } - flush_pending(strm); - if (strm.avail_out === 0) { - s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - //Assert(strm->avail_out > 0, "bug2"); - //if (strm.avail_out <= 0) { throw new Error("bug2");} - - if (flush !== Z_FINISH) { return Z_OK; } - if (s.wrap <= 0) { return Z_STREAM_END; } - - /* Write the trailer */ - if (s.wrap === 2) { - put_byte(s, strm.adler & 0xff); - put_byte(s, (strm.adler >> 8) & 0xff); - put_byte(s, (strm.adler >> 16) & 0xff); - put_byte(s, (strm.adler >> 24) & 0xff); - put_byte(s, strm.total_in & 0xff); - put_byte(s, (strm.total_in >> 8) & 0xff); - put_byte(s, (strm.total_in >> 16) & 0xff); - put_byte(s, (strm.total_in >> 24) & 0xff); - } - else - { - putShortMSB(s, strm.adler >>> 16); - putShortMSB(s, strm.adler & 0xffff); - } - - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s.wrap > 0) { s.wrap = -s.wrap; } - /* write the trailer only once! */ - return s.pending !== 0 ? Z_OK : Z_STREAM_END; -} - -function deflateEnd(strm) { - var status; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - status = strm.state.status; - if (status !== INIT_STATE && - status !== EXTRA_STATE && - status !== NAME_STATE && - status !== COMMENT_STATE && - status !== HCRC_STATE && - status !== BUSY_STATE && - status !== FINISH_STATE - ) { - return err(strm, Z_STREAM_ERROR); - } - - strm.state = null; - - return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; -} - - -/* ========================================================================= - * Initializes the compression dictionary from the given byte - * sequence without producing any compressed output. - */ -function deflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - - var s; - var str, n; - var wrap; - var avail; - var next; - var input; - var tmpDict; - - if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { - return Z_STREAM_ERROR; - } - - s = strm.state; - wrap = s.wrap; - - if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { - return Z_STREAM_ERROR; - } - - /* when using zlib wrappers, compute Adler-32 for provided dictionary */ - if (wrap === 1) { - /* adler32(strm->adler, dictionary, dictLength); */ - strm.adler = adler32(strm.adler, dictionary, dictLength, 0); - } - - s.wrap = 0; /* avoid computing Adler-32 in read_buf */ - - /* if dictionary would fill window, just replace the history */ - if (dictLength >= s.w_size) { - if (wrap === 0) { /* already empty otherwise */ - /*** CLEAR_HASH(s); ***/ - zero(s.head); // Fill with NIL (= 0); - s.strstart = 0; - s.block_start = 0; - s.insert = 0; - } - /* use the tail */ - // dictionary = dictionary.slice(dictLength - s.w_size); - tmpDict = new utils.Buf8(s.w_size); - utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); - dictionary = tmpDict; - dictLength = s.w_size; - } - /* insert dictionary into window and hash */ - avail = strm.avail_in; - next = strm.next_in; - input = strm.input; - strm.avail_in = dictLength; - strm.next_in = 0; - strm.input = dictionary; - fill_window(s); - while (s.lookahead >= MIN_MATCH) { - str = s.strstart; - n = s.lookahead - (MIN_MATCH - 1); - do { - /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ - s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; - - s.prev[str & s.w_mask] = s.head[s.ins_h]; - - s.head[s.ins_h] = str; - str++; - } while (--n); - s.strstart = str; - s.lookahead = MIN_MATCH - 1; - fill_window(s); - } - s.strstart += s.lookahead; - s.block_start = s.strstart; - s.insert = s.lookahead; - s.lookahead = 0; - s.match_length = s.prev_length = MIN_MATCH - 1; - s.match_available = 0; - strm.next_in = next; - strm.input = input; - strm.avail_in = avail; - s.wrap = wrap; - return Z_OK; -} - - -exports.deflateInit = deflateInit; -exports.deflateInit2 = deflateInit2; -exports.deflateReset = deflateReset; -exports.deflateResetKeep = deflateResetKeep; -exports.deflateSetHeader = deflateSetHeader; -exports.deflate = deflate; -exports.deflateEnd = deflateEnd; -exports.deflateSetDictionary = deflateSetDictionary; -exports.deflateInfo = 'pako deflate (from Nodeca project)'; - -/* Not implemented -exports.deflateBound = deflateBound; -exports.deflateCopy = deflateCopy; -exports.deflateParams = deflateParams; -exports.deflatePending = deflatePending; -exports.deflatePrime = deflatePrime; -exports.deflateTune = deflateTune; -*/ - - -/***/ }, -/* 71 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -function GZheader() { - /* true if compressed data believed to be text */ - this.text = 0; - /* modification time */ - this.time = 0; - /* extra flags (not used when writing a gzip file) */ - this.xflags = 0; - /* operating system */ - this.os = 0; - /* pointer to extra field or Z_NULL if none */ - this.extra = null; - /* extra field length (valid if extra != Z_NULL) */ - this.extra_len = 0; // Actually, we don't need it in JS, - // but leave for few code modifications - - // - // Setup limits is not necessary because in js we should not preallocate memory - // for inflate use constant limit in 65536 bytes - // - - /* space at extra (only when reading header) */ - // this.extra_max = 0; - /* pointer to zero-terminated file name or Z_NULL */ - this.name = ''; - /* space at name (only when reading header) */ - // this.name_max = 0; - /* pointer to zero-terminated comment or Z_NULL */ - this.comment = ''; - /* space at comment (only when reading header) */ - // this.comm_max = 0; - /* true if there was or will be a header crc */ - this.hcrc = 0; - /* true when done reading gzip header (not used when writing a gzip file) */ - this.done = false; -} - -module.exports = GZheader; - - -/***/ }, -/* 72 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - -// See state defs from inflate.js -var BAD = 30; /* got a data error -- remain here until reset */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state.mode === LEN - strm.avail_in >= 6 - strm.avail_out >= 258 - start >= strm.avail_out - state.bits < 8 - - On return, state.mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm.avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm.avail_out >= 258 for each loop to avoid checking for - output space. - */ -module.exports = function inflate_fast(strm, start) { - var state; - var _in; /* local strm.input */ - var last; /* have enough input while in < last */ - var _out; /* local strm.output */ - var beg; /* inflate()'s initial strm.output */ - var end; /* while out < end, enough space available */ -//#ifdef INFLATE_STRICT - var dmax; /* maximum distance from zlib header */ -//#endif - var wsize; /* window size or zero if not using window */ - var whave; /* valid bytes in the window */ - var wnext; /* window write index */ - // Use `s_window` instead `window`, avoid conflict with instrumentation tools - var s_window; /* allocated sliding window, if wsize != 0 */ - var hold; /* local strm.hold */ - var bits; /* local strm.bits */ - var lcode; /* local strm.lencode */ - var dcode; /* local strm.distcode */ - var lmask; /* mask for first level of length codes */ - var dmask; /* mask for first level of distance codes */ - var here; /* retrieved table entry */ - var op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - var len; /* match length, unused bytes */ - var dist; /* match distance */ - var from; /* where to copy match from */ - var from_source; - - - var input, output; // JS specific, because we have no pointers - - /* copy state to local variables */ - state = strm.state; - //here = state.here; - _in = strm.next_in; - input = strm.input; - last = _in + (strm.avail_in - 5); - _out = strm.next_out; - output = strm.output; - beg = _out - (start - strm.avail_out); - end = _out + (strm.avail_out - 257); -//#ifdef INFLATE_STRICT - dmax = state.dmax; -//#endif - wsize = state.wsize; - whave = state.whave; - wnext = state.wnext; - s_window = state.window; - hold = state.hold; - bits = state.bits; - lcode = state.lencode; - dcode = state.distcode; - lmask = (1 << state.lenbits) - 1; - dmask = (1 << state.distbits) - 1; - - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - - top: - do { - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - - here = lcode[hold & lmask]; - - dolen: - for (;;) { // Goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - if (op === 0) { /* literal */ - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - output[_out++] = here & 0xffff/*here.val*/; - } - else if (op & 16) { /* length base */ - len = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - len += hold & ((1 << op) - 1); - hold >>>= op; - bits -= op; - } - //Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += input[_in++] << bits; - bits += 8; - hold += input[_in++] << bits; - bits += 8; - } - here = dcode[hold & dmask]; - - dodist: - for (;;) { // goto emulation - op = here >>> 24/*here.bits*/; - hold >>>= op; - bits -= op; - op = (here >>> 16) & 0xff/*here.op*/; - - if (op & 16) { /* distance base */ - dist = here & 0xffff/*here.val*/; - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - if (bits < op) { - hold += input[_in++] << bits; - bits += 8; - } - } - dist += hold & ((1 << op) - 1); -//#ifdef INFLATE_STRICT - if (dist > dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } -//#endif - hold >>>= op; - bits -= op; - //Tracevv((stderr, "inflate: distance %u\n", dist)); - op = _out - beg; /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break top; - } - -// (!) This block is disabled in zlib defailts, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// if (len <= op - whave) { -// do { -// output[_out++] = 0; -// } while (--len); -// continue top; -// } -// len -= op - whave; -// do { -// output[_out++] = 0; -// } while (--op > whave); -// if (op === 0) { -// from = _out - dist; -// do { -// output[_out++] = output[from++]; -// } while (--len); -// continue top; -// } -//#endif - } - from = 0; // window index - from_source = s_window; - if (wnext === 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - else if (wnext < op) { /* wrap around window */ - from += wsize + wnext - op; - op -= wnext; - if (op < len) { /* some from end of window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = 0; - if (wnext < len) { /* some from start of window */ - op = wnext; - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - } - else { /* contiguous in window */ - from += wnext - op; - if (op < len) { /* some from window */ - len -= op; - do { - output[_out++] = s_window[from++]; - } while (--op); - from = _out - dist; /* rest from output */ - from_source = output; - } - } - while (len > 2) { - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - output[_out++] = from_source[from++]; - len -= 3; - } - if (len) { - output[_out++] = from_source[from++]; - if (len > 1) { - output[_out++] = from_source[from++]; - } - } - } - else { - from = _out - dist; /* copy direct from output */ - do { /* minimum length is three */ - output[_out++] = output[from++]; - output[_out++] = output[from++]; - output[_out++] = output[from++]; - len -= 3; - } while (len > 2); - if (len) { - output[_out++] = output[from++]; - if (len > 1) { - output[_out++] = output[from++]; - } - } - } - } - else if ((op & 64) === 0) { /* 2nd level distance code */ - here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dodist; - } - else { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } - else if ((op & 64) === 0) { /* 2nd level length code */ - here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; - continue dolen; - } - else if (op & 32) { /* end-of-block */ - //Tracevv((stderr, "inflate: end of block\n")); - state.mode = TYPE; - break top; - } - else { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break top; - } - - break; // need to emulate goto via "continue" - } - } while (_in < last && _out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - _in -= len; - bits -= len << 3; - hold &= (1 << bits) - 1; - - /* update state and return */ - strm.next_in = _in; - strm.next_out = _out; - strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); - strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); - state.hold = hold; - state.bits = bits; - return; -}; - - -/***/ }, -/* 73 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -var utils = __webpack_require__(5); -var adler32 = __webpack_require__(45); -var crc32 = __webpack_require__(47); -var inflate_fast = __webpack_require__(72); -var inflate_table = __webpack_require__(74); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -/* Allowed flush values; see deflate() and inflate() below for details */ -//var Z_NO_FLUSH = 0; -//var Z_PARTIAL_FLUSH = 1; -//var Z_SYNC_FLUSH = 2; -//var Z_FULL_FLUSH = 3; -var Z_FINISH = 4; -var Z_BLOCK = 5; -var Z_TREES = 6; - - -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ -var Z_OK = 0; -var Z_STREAM_END = 1; -var Z_NEED_DICT = 2; -//var Z_ERRNO = -1; -var Z_STREAM_ERROR = -2; -var Z_DATA_ERROR = -3; -var Z_MEM_ERROR = -4; -var Z_BUF_ERROR = -5; -//var Z_VERSION_ERROR = -6; - -/* The deflate compression method */ -var Z_DEFLATED = 8; - - -/* STATES ====================================================================*/ -/* ===========================================================================*/ - - -var HEAD = 1; /* i: waiting for magic header */ -var FLAGS = 2; /* i: waiting for method and flags (gzip) */ -var TIME = 3; /* i: waiting for modification time (gzip) */ -var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ -var EXLEN = 5; /* i: waiting for extra length (gzip) */ -var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ -var NAME = 7; /* i: waiting for end of file name (gzip) */ -var COMMENT = 8; /* i: waiting for end of comment (gzip) */ -var HCRC = 9; /* i: waiting for header crc (gzip) */ -var DICTID = 10; /* i: waiting for dictionary check value */ -var DICT = 11; /* waiting for inflateSetDictionary() call */ -var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ -var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ -var STORED = 14; /* i: waiting for stored size (length and complement) */ -var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ -var COPY = 16; /* i/o: waiting for input or output to copy stored block */ -var TABLE = 17; /* i: waiting for dynamic block table lengths */ -var LENLENS = 18; /* i: waiting for code length code lengths */ -var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ -var LEN_ = 20; /* i: same as LEN below, but only first time in */ -var LEN = 21; /* i: waiting for length/lit/eob code */ -var LENEXT = 22; /* i: waiting for length extra bits */ -var DIST = 23; /* i: waiting for distance code */ -var DISTEXT = 24; /* i: waiting for distance extra bits */ -var MATCH = 25; /* o: waiting for output space to copy string */ -var LIT = 26; /* o: waiting for output space to write literal */ -var CHECK = 27; /* i: waiting for 32-bit check value */ -var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ -var DONE = 29; /* finished check, done -- remain here until reset */ -var BAD = 30; /* got a data error -- remain here until reset */ -var MEM = 31; /* got an inflate() memory error -- remain here until reset */ -var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ - -/* ===========================================================================*/ - - - -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var MAX_WBITS = 15; -/* 32K LZ77 window */ -var DEF_WBITS = MAX_WBITS; - - -function zswap32(q) { - return (((q >>> 24) & 0xff) + - ((q >>> 8) & 0xff00) + - ((q & 0xff00) << 8) + - ((q & 0xff) << 24)); -} - - -function InflateState() { - this.mode = 0; /* current inflate mode */ - this.last = false; /* true if processing last block */ - this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ - this.havedict = false; /* true if dictionary provided */ - this.flags = 0; /* gzip header method and flags (0 if zlib) */ - this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ - this.check = 0; /* protected copy of check value */ - this.total = 0; /* protected copy of output count */ - // TODO: may be {} - this.head = null; /* where to save gzip header information */ - - /* sliding window */ - this.wbits = 0; /* log base 2 of requested window size */ - this.wsize = 0; /* window size or zero if not using window */ - this.whave = 0; /* valid bytes in the window */ - this.wnext = 0; /* window write index */ - this.window = null; /* allocated sliding window, if needed */ - - /* bit accumulator */ - this.hold = 0; /* input bit accumulator */ - this.bits = 0; /* number of bits in "in" */ - - /* for string and stored block copying */ - this.length = 0; /* literal or length of data to copy */ - this.offset = 0; /* distance back to copy string from */ - - /* for table and code decoding */ - this.extra = 0; /* extra bits needed */ - - /* fixed and dynamic code tables */ - this.lencode = null; /* starting table for length/literal codes */ - this.distcode = null; /* starting table for distance codes */ - this.lenbits = 0; /* index bits for lencode */ - this.distbits = 0; /* index bits for distcode */ - - /* dynamic table building */ - this.ncode = 0; /* number of code length code lengths */ - this.nlen = 0; /* number of length code lengths */ - this.ndist = 0; /* number of distance code lengths */ - this.have = 0; /* number of code lengths in lens[] */ - this.next = null; /* next available space in codes[] */ - - this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ - this.work = new utils.Buf16(288); /* work area for code table building */ - - /* - because we don't have pointers in js, we use lencode and distcode directly - as buffers so we don't need codes - */ - //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ - this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ - this.distdyn = null; /* dynamic table for distance codes (JS specific) */ - this.sane = 0; /* if false, allow invalid distance too far */ - this.back = 0; /* bits back of last unprocessed length/lit */ - this.was = 0; /* initial length of match */ -} - -function inflateResetKeep(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - strm.total_in = strm.total_out = state.total = 0; - strm.msg = ''; /*Z_NULL*/ - if (state.wrap) { /* to support ill-conceived Java test suite */ - strm.adler = state.wrap & 1; - } - state.mode = HEAD; - state.last = 0; - state.havedict = 0; - state.dmax = 32768; - state.head = null/*Z_NULL*/; - state.hold = 0; - state.bits = 0; - //state.lencode = state.distcode = state.next = state.codes; - state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); - state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); - - state.sane = 1; - state.back = -1; - //Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -function inflateReset(strm) { - var state; - - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - state.wsize = 0; - state.whave = 0; - state.wnext = 0; - return inflateResetKeep(strm); - -} - -function inflateReset2(strm, windowBits) { - var wrap; - var state; - - /* get the state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - - /* extract wrap request from windowBits parameter */ - if (windowBits < 0) { - wrap = 0; - windowBits = -windowBits; - } - else { - wrap = (windowBits >> 4) + 1; - if (windowBits < 48) { - windowBits &= 15; - } - } - - /* set number of window bits, free window if different */ - if (windowBits && (windowBits < 8 || windowBits > 15)) { - return Z_STREAM_ERROR; - } - if (state.window !== null && state.wbits !== windowBits) { - state.window = null; - } - - /* update state and reset the rest of it */ - state.wrap = wrap; - state.wbits = windowBits; - return inflateReset(strm); -} - -function inflateInit2(strm, windowBits) { - var ret; - var state; - - if (!strm) { return Z_STREAM_ERROR; } - //strm.msg = Z_NULL; /* in case we return an error */ - - state = new InflateState(); - - //if (state === Z_NULL) return Z_MEM_ERROR; - //Tracev((stderr, "inflate: allocated\n")); - strm.state = state; - state.window = null/*Z_NULL*/; - ret = inflateReset2(strm, windowBits); - if (ret !== Z_OK) { - strm.state = null/*Z_NULL*/; - } - return ret; -} - -function inflateInit(strm) { - return inflateInit2(strm, DEF_WBITS); -} - - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -var virgin = true; - -var lenfix, distfix; // We have no pointers in JS, so keep tables separate - -function fixedtables(state) { - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - var sym; - - lenfix = new utils.Buf32(512); - distfix = new utils.Buf32(32); - - /* literal/length table */ - sym = 0; - while (sym < 144) { state.lens[sym++] = 8; } - while (sym < 256) { state.lens[sym++] = 9; } - while (sym < 280) { state.lens[sym++] = 7; } - while (sym < 288) { state.lens[sym++] = 8; } - - inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); - - /* distance table */ - sym = 0; - while (sym < 32) { state.lens[sym++] = 5; } - - inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); - - /* do this just once */ - virgin = false; - } - - state.lencode = lenfix; - state.lenbits = 9; - state.distcode = distfix; - state.distbits = 5; -} - - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -function updatewindow(strm, src, end, copy) { - var dist; - var state = strm.state; - - /* if it hasn't been done already, allocate space for the window */ - if (state.window === null) { - state.wsize = 1 << state.wbits; - state.wnext = 0; - state.whave = 0; - - state.window = new utils.Buf8(state.wsize); - } - - /* copy state->wsize or less output bytes into the circular window */ - if (copy >= state.wsize) { - utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); - state.wnext = 0; - state.whave = state.wsize; - } - else { - dist = state.wsize - state.wnext; - if (dist > copy) { - dist = copy; - } - //zmemcpy(state->window + state->wnext, end - copy, dist); - utils.arraySet(state.window, src, end - copy, dist, state.wnext); - copy -= dist; - if (copy) { - //zmemcpy(state->window, end - copy, copy); - utils.arraySet(state.window, src, end - copy, copy, 0); - state.wnext = copy; - state.whave = state.wsize; - } - else { - state.wnext += dist; - if (state.wnext === state.wsize) { state.wnext = 0; } - if (state.whave < state.wsize) { state.whave += dist; } - } - } - return 0; -} - -function inflate(strm, flush) { - var state; - var input, output; // input/output buffers - var next; /* next input INDEX */ - var put; /* next output INDEX */ - var have, left; /* available input and output */ - var hold; /* bit buffer */ - var bits; /* bits in bit buffer */ - var _in, _out; /* save starting available input and output */ - var copy; /* number of stored or match bytes to copy */ - var from; /* where to copy match bytes from */ - var from_source; - var here = 0; /* current decoding table entry */ - var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) - //var last; /* parent table entry */ - var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) - var len; /* length to copy for repeats, bits to drop */ - var ret; /* return code */ - var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ - var opts; - - var n; // temporary var for NEED_BITS - - var order = /* permutation of code lengths */ - [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; - - - if (!strm || !strm.state || !strm.output || - (!strm.input && strm.avail_in !== 0)) { - return Z_STREAM_ERROR; - } - - state = strm.state; - if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ - - - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - _in = have; - _out = left; - ret = Z_OK; - - inf_leave: // goto emulation - for (;;) { - switch (state.mode) { - case HEAD: - if (state.wrap === 0) { - state.mode = TYPEDO; - break; - } - //=== NEEDBITS(16); - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ - state.check = 0/*crc32(0L, Z_NULL, 0)*/; - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = FLAGS; - break; - } - state.flags = 0; /* expect zlib header */ - if (state.head) { - state.head.done = false; - } - if (!(state.wrap & 1) || /* check if zlib header allowed */ - (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { - strm.msg = 'incorrect header check'; - state.mode = BAD; - break; - } - if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// - len = (hold & 0x0f)/*BITS(4)*/ + 8; - if (state.wbits === 0) { - state.wbits = len; - } - else if (len > state.wbits) { - strm.msg = 'invalid window size'; - state.mode = BAD; - break; - } - state.dmax = 1 << len; - //Tracev((stderr, "inflate: zlib header ok\n")); - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = hold & 0x200 ? DICTID : TYPE; - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - break; - case FLAGS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.flags = hold; - if ((state.flags & 0xff) !== Z_DEFLATED) { - strm.msg = 'unknown compression method'; - state.mode = BAD; - break; - } - if (state.flags & 0xe000) { - strm.msg = 'unknown header flags set'; - state.mode = BAD; - break; - } - if (state.head) { - state.head.text = ((hold >> 8) & 1); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = TIME; - /* falls through */ - case TIME: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.time = hold; - } - if (state.flags & 0x0200) { - //=== CRC4(state.check, hold) - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - hbuf[2] = (hold >>> 16) & 0xff; - hbuf[3] = (hold >>> 24) & 0xff; - state.check = crc32(state.check, hbuf, 4, 0); - //=== - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = OS; - /* falls through */ - case OS: - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (state.head) { - state.head.xflags = (hold & 0xff); - state.head.os = (hold >> 8); - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = EXLEN; - /* falls through */ - case EXLEN: - if (state.flags & 0x0400) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length = hold; - if (state.head) { - state.head.extra_len = hold; - } - if (state.flags & 0x0200) { - //=== CRC2(state.check, hold); - hbuf[0] = hold & 0xff; - hbuf[1] = (hold >>> 8) & 0xff; - state.check = crc32(state.check, hbuf, 2, 0); - //===// - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - else if (state.head) { - state.head.extra = null/*Z_NULL*/; - } - state.mode = EXTRA; - /* falls through */ - case EXTRA: - if (state.flags & 0x0400) { - copy = state.length; - if (copy > have) { copy = have; } - if (copy) { - if (state.head) { - len = state.head.extra_len - state.length; - if (!state.head.extra) { - // Use untyped array for more conveniend processing later - state.head.extra = new Array(state.head.extra_len); - } - utils.arraySet( - state.head.extra, - input, - next, - // extra field is limited to 65536 bytes - // - no need for additional size check - copy, - /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ - len - ); - //zmemcpy(state.head.extra + len, next, - // len + copy > state.head.extra_max ? - // state.head.extra_max - len : copy); - } - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - state.length -= copy; - } - if (state.length) { break inf_leave; } - } - state.length = 0; - state.mode = NAME; - /* falls through */ - case NAME: - if (state.flags & 0x0800) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - // TODO: 2 or 1 bytes? - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.name_max*/)) { - state.head.name += String.fromCharCode(len); - } - } while (len && copy < have); - - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.name = null; - } - state.length = 0; - state.mode = COMMENT; - /* falls through */ - case COMMENT: - if (state.flags & 0x1000) { - if (have === 0) { break inf_leave; } - copy = 0; - do { - len = input[next + copy++]; - /* use constant limit because in js we should not preallocate memory */ - if (state.head && len && - (state.length < 65536 /*state.head.comm_max*/)) { - state.head.comment += String.fromCharCode(len); - } - } while (len && copy < have); - if (state.flags & 0x0200) { - state.check = crc32(state.check, input, copy, next); - } - have -= copy; - next += copy; - if (len) { break inf_leave; } - } - else if (state.head) { - state.head.comment = null; - } - state.mode = HCRC; - /* falls through */ - case HCRC: - if (state.flags & 0x0200) { - //=== NEEDBITS(16); */ - while (bits < 16) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.check & 0xffff)) { - strm.msg = 'header crc mismatch'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - } - if (state.head) { - state.head.hcrc = ((state.flags >> 9) & 1); - state.head.done = true; - } - strm.adler = state.check = 0; - state.mode = TYPE; - break; - case DICTID: - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - strm.adler = state.check = zswap32(hold); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = DICT; - /* falls through */ - case DICT: - if (state.havedict === 0) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - return Z_NEED_DICT; - } - strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; - state.mode = TYPE; - /* falls through */ - case TYPE: - if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } - /* falls through */ - case TYPEDO: - if (state.last) { - //--- BYTEBITS() ---// - hold >>>= bits & 7; - bits -= bits & 7; - //---// - state.mode = CHECK; - break; - } - //=== NEEDBITS(3); */ - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.last = (hold & 0x01)/*BITS(1)*/; - //--- DROPBITS(1) ---// - hold >>>= 1; - bits -= 1; - //---// - - switch ((hold & 0x03)/*BITS(2)*/) { - case 0: /* stored block */ - //Tracev((stderr, "inflate: stored block%s\n", - // state.last ? " (last)" : "")); - state.mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - //Tracev((stderr, "inflate: fixed codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = LEN_; /* decode codes */ - if (flush === Z_TREES) { - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break inf_leave; - } - break; - case 2: /* dynamic block */ - //Tracev((stderr, "inflate: dynamic codes block%s\n", - // state.last ? " (last)" : "")); - state.mode = TABLE; - break; - case 3: - strm.msg = 'invalid block type'; - state.mode = BAD; - } - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - break; - case STORED: - //--- BYTEBITS() ---// /* go to byte boundary */ - hold >>>= bits & 7; - bits -= bits & 7; - //---// - //=== NEEDBITS(32); */ - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { - strm.msg = 'invalid stored block lengths'; - state.mode = BAD; - break; - } - state.length = hold & 0xffff; - //Tracev((stderr, "inflate: stored length %u\n", - // state.length)); - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - state.mode = COPY_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case COPY_: - state.mode = COPY; - /* falls through */ - case COPY: - copy = state.length; - if (copy) { - if (copy > have) { copy = have; } - if (copy > left) { copy = left; } - if (copy === 0) { break inf_leave; } - //--- zmemcpy(put, next, copy); --- - utils.arraySet(output, input, next, copy, put); - //---// - have -= copy; - next += copy; - left -= copy; - put += copy; - state.length -= copy; - break; - } - //Tracev((stderr, "inflate: stored end\n")); - state.mode = TYPE; - break; - case TABLE: - //=== NEEDBITS(14); */ - while (bits < 14) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; - //--- DROPBITS(5) ---// - hold >>>= 5; - bits -= 5; - //---// - state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; - //--- DROPBITS(4) ---// - hold >>>= 4; - bits -= 4; - //---// -//#ifndef PKZIP_BUG_WORKAROUND - if (state.nlen > 286 || state.ndist > 30) { - strm.msg = 'too many length or distance symbols'; - state.mode = BAD; - break; - } -//#endif - //Tracev((stderr, "inflate: table sizes ok\n")); - state.have = 0; - state.mode = LENLENS; - /* falls through */ - case LENLENS: - while (state.have < state.ncode) { - //=== NEEDBITS(3); - while (bits < 3) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - while (state.have < 19) { - state.lens[order[state.have++]] = 0; - } - // We have separate tables & no pointers. 2 commented lines below not needed. - //state.next = state.codes; - //state.lencode = state.next; - // Switch to use dynamic table - state.lencode = state.lendyn; - state.lenbits = 7; - - opts = { bits: state.lenbits }; - ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); - state.lenbits = opts.bits; - - if (ret) { - strm.msg = 'invalid code lengths set'; - state.mode = BAD; - break; - } - //Tracev((stderr, "inflate: code lengths ok\n")); - state.have = 0; - state.mode = CODELENS; - /* falls through */ - case CODELENS: - while (state.have < state.nlen + state.ndist) { - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_val < 16) { - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.lens[state.have++] = here_val; - } - else { - if (here_val === 16) { - //=== NEEDBITS(here.bits + 2); - n = here_bits + 2; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - if (state.have === 0) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - len = state.lens[state.have - 1]; - copy = 3 + (hold & 0x03);//BITS(2); - //--- DROPBITS(2) ---// - hold >>>= 2; - bits -= 2; - //---// - } - else if (here_val === 17) { - //=== NEEDBITS(here.bits + 3); - n = here_bits + 3; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 3 + (hold & 0x07);//BITS(3); - //--- DROPBITS(3) ---// - hold >>>= 3; - bits -= 3; - //---// - } - else { - //=== NEEDBITS(here.bits + 7); - n = here_bits + 7; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - len = 0; - copy = 11 + (hold & 0x7f);//BITS(7); - //--- DROPBITS(7) ---// - hold >>>= 7; - bits -= 7; - //---// - } - if (state.have + copy > state.nlen + state.ndist) { - strm.msg = 'invalid bit length repeat'; - state.mode = BAD; - break; - } - while (copy--) { - state.lens[state.have++] = len; - } - } - } - - /* handle error breaks in while */ - if (state.mode === BAD) { break; } - - /* check for end-of-block code (better have one) */ - if (state.lens[256] === 0) { - strm.msg = 'invalid code -- missing end-of-block'; - state.mode = BAD; - break; - } - - /* build code tables -- note: do not change the lenbits or distbits - values here (9 and 6) without reading the comments in inftrees.h - concerning the ENOUGH constants, which depend on those values */ - state.lenbits = 9; - - opts = { bits: state.lenbits }; - ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.lenbits = opts.bits; - // state.lencode = state.next; - - if (ret) { - strm.msg = 'invalid literal/lengths set'; - state.mode = BAD; - break; - } - - state.distbits = 6; - //state.distcode.copy(state.codes); - // Switch to use dynamic table - state.distcode = state.distdyn; - opts = { bits: state.distbits }; - ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); - // We have separate tables & no pointers. 2 commented lines below not needed. - // state.next_index = opts.table_index; - state.distbits = opts.bits; - // state.distcode = state.next; - - if (ret) { - strm.msg = 'invalid distances set'; - state.mode = BAD; - break; - } - //Tracev((stderr, 'inflate: codes ok\n')); - state.mode = LEN_; - if (flush === Z_TREES) { break inf_leave; } - /* falls through */ - case LEN_: - state.mode = LEN; - /* falls through */ - case LEN: - if (have >= 6 && left >= 258) { - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - inflate_fast(strm, _out); - //--- LOAD() --- - put = strm.next_out; - output = strm.output; - left = strm.avail_out; - next = strm.next_in; - input = strm.input; - have = strm.avail_in; - hold = state.hold; - bits = state.bits; - //--- - - if (state.mode === TYPE) { - state.back = -1; - } - break; - } - state.back = 0; - for (;;) { - here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if (here_bits <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if (here_op && (here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.lencode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - state.length = here_val; - if (here_op === 0) { - //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? - // "inflate: literal '%c'\n" : - // "inflate: literal 0x%02x\n", here.val)); - state.mode = LIT; - break; - } - if (here_op & 32) { - //Tracevv((stderr, "inflate: end of block\n")); - state.back = -1; - state.mode = TYPE; - break; - } - if (here_op & 64) { - strm.msg = 'invalid literal/length code'; - state.mode = BAD; - break; - } - state.extra = here_op & 15; - state.mode = LENEXT; - /* falls through */ - case LENEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } - //Tracevv((stderr, "inflate: length %u\n", state.length)); - state.was = state.length; - state.mode = DIST; - /* falls through */ - case DIST: - for (;;) { - here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - if ((here_op & 0xf0) === 0) { - last_bits = here_bits; - last_op = here_op; - last_val = here_val; - for (;;) { - here = state.distcode[last_val + - ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; - here_bits = here >>> 24; - here_op = (here >>> 16) & 0xff; - here_val = here & 0xffff; - - if ((last_bits + here_bits) <= bits) { break; } - //--- PULLBYTE() ---// - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - //---// - } - //--- DROPBITS(last.bits) ---// - hold >>>= last_bits; - bits -= last_bits; - //---// - state.back += last_bits; - } - //--- DROPBITS(here.bits) ---// - hold >>>= here_bits; - bits -= here_bits; - //---// - state.back += here_bits; - if (here_op & 64) { - strm.msg = 'invalid distance code'; - state.mode = BAD; - break; - } - state.offset = here_val; - state.extra = (here_op) & 15; - state.mode = DISTEXT; - /* falls through */ - case DISTEXT: - if (state.extra) { - //=== NEEDBITS(state.extra); - n = state.extra; - while (bits < n) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; - //--- DROPBITS(state.extra) ---// - hold >>>= state.extra; - bits -= state.extra; - //---// - state.back += state.extra; - } -//#ifdef INFLATE_STRICT - if (state.offset > state.dmax) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -//#endif - //Tracevv((stderr, "inflate: distance %u\n", state.offset)); - state.mode = MATCH; - /* falls through */ - case MATCH: - if (left === 0) { break inf_leave; } - copy = _out - left; - if (state.offset > copy) { /* copy from window */ - copy = state.offset - copy; - if (copy > state.whave) { - if (state.sane) { - strm.msg = 'invalid distance too far back'; - state.mode = BAD; - break; - } -// (!) This block is disabled in zlib defailts, -// don't enable it for binary compatibility -//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR -// Trace((stderr, "inflate.c too far\n")); -// copy -= state.whave; -// if (copy > state.length) { copy = state.length; } -// if (copy > left) { copy = left; } -// left -= copy; -// state.length -= copy; -// do { -// output[put++] = 0; -// } while (--copy); -// if (state.length === 0) { state.mode = LEN; } -// break; -//#endif - } - if (copy > state.wnext) { - copy -= state.wnext; - from = state.wsize - copy; - } - else { - from = state.wnext - copy; - } - if (copy > state.length) { copy = state.length; } - from_source = state.window; - } - else { /* copy from output */ - from_source = output; - from = put - state.offset; - copy = state.length; - } - if (copy > left) { copy = left; } - left -= copy; - state.length -= copy; - do { - output[put++] = from_source[from++]; - } while (--copy); - if (state.length === 0) { state.mode = LEN; } - break; - case LIT: - if (left === 0) { break inf_leave; } - output[put++] = state.length; - left--; - state.mode = LEN; - break; - case CHECK: - if (state.wrap) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - // Use '|' insdead of '+' to make sure that result is signed - hold |= input[next++] << bits; - bits += 8; - } - //===// - _out -= left; - strm.total_out += _out; - state.total += _out; - if (_out) { - strm.adler = state.check = - /*UPDATE(state.check, put - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); - - } - _out = left; - // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too - if ((state.flags ? hold : zswap32(hold)) !== state.check) { - strm.msg = 'incorrect data check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: check matches trailer\n")); - } - state.mode = LENGTH; - /* falls through */ - case LENGTH: - if (state.wrap && state.flags) { - //=== NEEDBITS(32); - while (bits < 32) { - if (have === 0) { break inf_leave; } - have--; - hold += input[next++] << bits; - bits += 8; - } - //===// - if (hold !== (state.total & 0xffffffff)) { - strm.msg = 'incorrect length check'; - state.mode = BAD; - break; - } - //=== INITBITS(); - hold = 0; - bits = 0; - //===// - //Tracev((stderr, "inflate: length matches trailer\n")); - } - state.mode = DONE; - /* falls through */ - case DONE: - ret = Z_STREAM_END; - break inf_leave; - case BAD: - ret = Z_DATA_ERROR; - break inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - /* falls through */ - default: - return Z_STREAM_ERROR; - } - } - - // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - - //--- RESTORE() --- - strm.next_out = put; - strm.avail_out = left; - strm.next_in = next; - strm.avail_in = have; - state.hold = hold; - state.bits = bits; - //--- - - if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && - (state.mode < CHECK || flush !== Z_FINISH))) { - if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { - state.mode = MEM; - return Z_MEM_ERROR; - } - } - _in -= strm.avail_in; - _out -= strm.avail_out; - strm.total_in += _in; - strm.total_out += _out; - state.total += _out; - if (state.wrap && _out) { - strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ - (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); - } - strm.data_type = state.bits + (state.last ? 64 : 0) + - (state.mode === TYPE ? 128 : 0) + - (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); - if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { - ret = Z_BUF_ERROR; - } - return ret; -} - -function inflateEnd(strm) { - - if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { - return Z_STREAM_ERROR; - } - - var state = strm.state; - if (state.window) { - state.window = null; - } - strm.state = null; - return Z_OK; -} - -function inflateGetHeader(strm, head) { - var state; - - /* check state */ - if (!strm || !strm.state) { return Z_STREAM_ERROR; } - state = strm.state; - if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } - - /* save header structure */ - state.head = head; - head.done = false; - return Z_OK; -} - -function inflateSetDictionary(strm, dictionary) { - var dictLength = dictionary.length; - - var state; - var dictid; - var ret; - - /* check state */ - if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } - state = strm.state; - - if (state.wrap !== 0 && state.mode !== DICT) { - return Z_STREAM_ERROR; - } - - /* check for correct dictionary identifier */ - if (state.mode === DICT) { - dictid = 1; /* adler32(0, null, 0)*/ - /* dictid = adler32(dictid, dictionary, dictLength); */ - dictid = adler32(dictid, dictionary, dictLength, 0); - if (dictid !== state.check) { - return Z_DATA_ERROR; - } - } - /* copy dictionary to window using updatewindow(), which will amend the - existing dictionary if appropriate */ - ret = updatewindow(strm, dictionary, dictLength, dictLength); - if (ret) { - state.mode = MEM; - return Z_MEM_ERROR; - } - state.havedict = 1; - // Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -exports.inflateReset = inflateReset; -exports.inflateReset2 = inflateReset2; -exports.inflateResetKeep = inflateResetKeep; -exports.inflateInit = inflateInit; -exports.inflateInit2 = inflateInit2; -exports.inflate = inflate; -exports.inflateEnd = inflateEnd; -exports.inflateGetHeader = inflateGetHeader; -exports.inflateSetDictionary = inflateSetDictionary; -exports.inflateInfo = 'pako inflate (from Nodeca project)'; - -/* Not implemented -exports.inflateCopy = inflateCopy; -exports.inflateGetDictionary = inflateGetDictionary; -exports.inflateMark = inflateMark; -exports.inflatePrime = inflatePrime; -exports.inflateSync = inflateSync; -exports.inflateSyncPoint = inflateSyncPoint; -exports.inflateUndermine = inflateUndermine; -*/ - - -/***/ }, -/* 74 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -var utils = __webpack_require__(5); - -var MAXBITS = 15; -var ENOUGH_LENS = 852; -var ENOUGH_DISTS = 592; -//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); - -var CODES = 0; -var LENS = 1; -var DISTS = 2; - -var lbase = [ /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 -]; - -var lext = [ /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 -]; - -var dbase = [ /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0 -]; - -var dext = [ /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64 -]; - -module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) -{ - var bits = opts.bits; - //here = opts.here; /* table entry for duplication */ - - var len = 0; /* a code's length in bits */ - var sym = 0; /* index of code symbols */ - var min = 0, max = 0; /* minimum and maximum code lengths */ - var root = 0; /* number of index bits for root table */ - var curr = 0; /* number of index bits for current table */ - var drop = 0; /* code bits to drop for sub-table */ - var left = 0; /* number of prefix codes available */ - var used = 0; /* code entries in table used */ - var huff = 0; /* Huffman code */ - var incr; /* for incrementing code, index */ - var fill; /* index for replicating entries */ - var low; /* low bits for current root entry */ - var mask; /* mask for low root bits */ - var next; /* next available space in table */ - var base = null; /* base value table to use */ - var base_index = 0; -// var shoextra; /* extra bits table to use */ - var end; /* use base and extra for symbol > end */ - var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ - var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ - var extra = null; - var extra_index = 0; - - var here_bits, here_op, here_val; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) { - count[len] = 0; - } - for (sym = 0; sym < codes; sym++) { - count[lens[lens_index + sym]]++; - } - - /* bound code lengths, force root to be within code lengths */ - root = bits; - for (max = MAXBITS; max >= 1; max--) { - if (count[max] !== 0) { break; } - } - if (root > max) { - root = max; - } - if (max === 0) { /* no symbols to code at all */ - //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ - //table.bits[opts.table_index] = 1; //here.bits = (var char)1; - //table.val[opts.table_index++] = 0; //here.val = (var short)0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - - //table.op[opts.table_index] = 64; - //table.bits[opts.table_index] = 1; - //table.val[opts.table_index++] = 0; - table[table_index++] = (1 << 24) | (64 << 16) | 0; - - opts.bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min < max; min++) { - if (count[min] !== 0) { break; } - } - if (root < min) { - root = min; - } - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) { - return -1; - } /* over-subscribed */ - } - if (left > 0 && (type === CODES || max !== 1)) { - return -1; /* incomplete set */ - } - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) { - offs[len + 1] = offs[len] + count[len]; - } - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) { - if (lens[lens_index + sym] !== 0) { - work[offs[lens[lens_index + sym]]++] = sym; - } - } - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked for LENS and DIST tables against - the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in - the initial root table size constants. See the comments in inftrees.h - for more information. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - // poor man optimization - use if-else instead of switch, - // to avoid deopts in old v8 - if (type === CODES) { - base = extra = work; /* dummy value--not used */ - end = 19; - - } else if (type === LENS) { - base = lbase; - base_index -= 257; - extra = lext; - extra_index -= 257; - end = 256; - - } else { /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize opts for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = table_index; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = -1; /* trigger new sub-table when len > root */ - used = 1 << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - here_bits = len - drop; - if (work[sym] < end) { - here_op = 0; - here_val = work[sym]; - } - else if (work[sym] > end) { - here_op = extra[extra_index + work[sym]]; - here_val = base[base_index + work[sym]]; - } - else { - here_op = 32 + 64; /* end of block */ - here_val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1 << (len - drop); - fill = 1 << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; - } while (fill !== 0); - - /* backwards increment the len-bit code huff */ - incr = 1 << (len - 1); - while (huff & incr) { - incr >>= 1; - } - if (incr !== 0) { - huff &= incr - 1; - huff += incr; - } else { - huff = 0; - } - - /* go to next symbol, update count, len */ - sym++; - if (--count[len] === 0) { - if (len === max) { break; } - len = lens[lens_index + work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) !== low) { - /* if first time, transition to sub-tables */ - if (drop === 0) { - drop = root; - } - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = 1 << curr; - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) { break; } - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1 << curr; - if ((type === LENS && used > ENOUGH_LENS) || - (type === DISTS && used > ENOUGH_DISTS)) { - return 1; - } - - /* point entry in root table to sub-table */ - low = huff & mask; - /*table.op[low] = curr; - table.bits[low] = root; - table.val[low] = next - opts.table_index;*/ - table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; - } - } - - /* fill in remaining table entry if code is incomplete (guaranteed to have - at most one remaining entry, since if the code is incomplete, the - maximum code length that was allowed to get this far is one bit) */ - if (huff !== 0) { - //table.op[next + huff] = 64; /* invalid code marker */ - //table.bits[next + huff] = len - drop; - //table.val[next + huff] = 0; - table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; - } - - /* set return parameters */ - //opts.table_index += used; - opts.bits = root; - return 0; -}; - - -/***/ }, -/* 75 */ -/***/ function(module, exports, __webpack_require__) { - -"use strict"; - - - -var utils = __webpack_require__(5); - -/* Public constants ==========================================================*/ -/* ===========================================================================*/ - - -//var Z_FILTERED = 1; -//var Z_HUFFMAN_ONLY = 2; -//var Z_RLE = 3; -var Z_FIXED = 4; -//var Z_DEFAULT_STRATEGY = 0; - -/* Possible values of the data_type field (though see inflate()) */ -var Z_BINARY = 0; -var Z_TEXT = 1; -//var Z_ASCII = 1; // = Z_TEXT -var Z_UNKNOWN = 2; - -/*============================================================================*/ - - -function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } - -// From zutil.h - -var STORED_BLOCK = 0; -var STATIC_TREES = 1; -var DYN_TREES = 2; -/* The three kinds of block type */ - -var MIN_MATCH = 3; -var MAX_MATCH = 258; -/* The minimum and maximum match lengths */ - -// From deflate.h -/* =========================================================================== - * Internal compression state. - */ - -var LENGTH_CODES = 29; -/* number of length codes, not counting the special END_BLOCK code */ - -var LITERALS = 256; -/* number of literal bytes 0..255 */ - -var L_CODES = LITERALS + 1 + LENGTH_CODES; -/* number of Literal or Length codes, including the END_BLOCK code */ - -var D_CODES = 30; -/* number of distance codes */ - -var BL_CODES = 19; -/* number of codes used to transfer the bit lengths */ - -var HEAP_SIZE = 2 * L_CODES + 1; -/* maximum heap size */ - -var MAX_BITS = 15; -/* All codes must not exceed MAX_BITS bits */ - -var Buf_size = 16; -/* size of bit buffer in bi_buf */ - - -/* =========================================================================== - * Constants - */ - -var MAX_BL_BITS = 7; -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -var END_BLOCK = 256; -/* end of block literal code */ - -var REP_3_6 = 16; -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -var REPZ_3_10 = 17; -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -var REPZ_11_138 = 18; -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -/* eslint-disable comma-spacing,array-bracket-spacing */ -var extra_lbits = /* extra bits for each length code */ - [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; - -var extra_dbits = /* extra bits for each distance code */ - [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; - -var extra_blbits = /* extra bits for each bit length code */ - [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; - -var bl_order = - [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; -/* eslint-enable comma-spacing,array-bracket-spacing */ - -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -// We pre-fill arrays with 0 to avoid uninitialized gaps - -var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ - -// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 -var static_ltree = new Array((L_CODES + 2) * 2); -zero(static_ltree); -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -var static_dtree = new Array(D_CODES * 2); -zero(static_dtree); -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -var _dist_code = new Array(DIST_CODE_LEN); -zero(_dist_code); -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); -zero(_length_code); -/* length code for each normalized match length (0 == MIN_MATCH) */ - -var base_length = new Array(LENGTH_CODES); -zero(base_length); -/* First normalized length for each code (0 = MIN_MATCH) */ - -var base_dist = new Array(D_CODES); -zero(base_dist); -/* First normalized distance for each code (0 = distance of 1) */ - - -function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { - - this.static_tree = static_tree; /* static tree or NULL */ - this.extra_bits = extra_bits; /* extra bits for each code or NULL */ - this.extra_base = extra_base; /* base index for extra_bits */ - this.elems = elems; /* max number of elements in the tree */ - this.max_length = max_length; /* max bit length for the codes */ - - // show if `static_tree` has data or dummy - needed for monomorphic objects - this.has_stree = static_tree && static_tree.length; -} - - -var static_l_desc; -var static_d_desc; -var static_bl_desc; - - -function TreeDesc(dyn_tree, stat_desc) { - this.dyn_tree = dyn_tree; /* the dynamic tree */ - this.max_code = 0; /* largest code with non zero frequency */ - this.stat_desc = stat_desc; /* the corresponding static tree */ -} - - - -function d_code(dist) { - return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; -} - - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -function put_short(s, w) { -// put_byte(s, (uch)((w) & 0xff)); -// put_byte(s, (uch)((ush)(w) >> 8)); - s.pending_buf[s.pending++] = (w) & 0xff; - s.pending_buf[s.pending++] = (w >>> 8) & 0xff; -} - - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -function send_bits(s, value, length) { - if (s.bi_valid > (Buf_size - length)) { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - put_short(s, s.bi_buf); - s.bi_buf = value >> (Buf_size - s.bi_valid); - s.bi_valid += length - Buf_size; - } else { - s.bi_buf |= (value << s.bi_valid) & 0xffff; - s.bi_valid += length; - } -} - - -function send_code(s, c, tree) { - send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); -} - - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -function bi_reverse(code, len) { - var res = 0; - do { - res |= code & 1; - code >>>= 1; - res <<= 1; - } while (--len > 0); - return res >>> 1; -} - - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -function bi_flush(s) { - if (s.bi_valid === 16) { - put_short(s, s.bi_buf); - s.bi_buf = 0; - s.bi_valid = 0; - - } else if (s.bi_valid >= 8) { - s.pending_buf[s.pending++] = s.bi_buf & 0xff; - s.bi_buf >>= 8; - s.bi_valid -= 8; - } -} - - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -function gen_bitlen(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var max_code = desc.max_code; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var extra = desc.stat_desc.extra_bits; - var base = desc.stat_desc.extra_base; - var max_length = desc.stat_desc.max_length; - var h; /* heap index */ - var n, m; /* iterate over the tree elements */ - var bits; /* bit length */ - var xbits; /* extra bits */ - var f; /* frequency */ - var overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) { - s.bl_count[bits] = 0; - } - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ - - for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { - n = s.heap[h]; - bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; - if (bits > max_length) { - bits = max_length; - overflow++; - } - tree[n * 2 + 1]/*.Len*/ = bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) { continue; } /* not a leaf node */ - - s.bl_count[bits]++; - xbits = 0; - if (n >= base) { - xbits = extra[n - base]; - } - f = tree[n * 2]/*.Freq*/; - s.opt_len += f * (bits + xbits); - if (has_stree) { - s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); - } - } - if (overflow === 0) { return; } - - // Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length - 1; - while (s.bl_count[bits] === 0) { bits--; } - s.bl_count[bits]--; /* move one leaf down the tree */ - s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ - s.bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits !== 0; bits--) { - n = s.bl_count[bits]; - while (n !== 0) { - m = s.heap[--h]; - if (m > max_code) { continue; } - if (tree[m * 2 + 1]/*.Len*/ !== bits) { - // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; - tree[m * 2 + 1]/*.Len*/ = bits; - } - n--; - } - } -} - - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -function gen_codes(tree, max_code, bl_count) -// ct_data *tree; /* the tree to decorate */ -// int max_code; /* largest code with non zero frequency */ -// ushf *bl_count; /* number of codes at each bit length */ -{ - var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ - var code = 0; /* running code value */ - var bits; /* bit index */ - var n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits - 1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES - 1; code++) { - base_length[code] = length; - for (n = 0; n < (1 << extra_lbits[code]); n++) { - _length_code[length++] = code; - } - } - //Assert (length == 256, "tr_static_init: length != 256"); - /* Note that the length 255 (match length 258) can be represented - * in two different ways: code 284 + 5 bits or code 285, so we - * overwrite length_code[255] to use the best encoding: - */ - _length_code[length - 1] = code; - - /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ - dist = 0; - for (code = 0; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1 << extra_dbits[code]); n++) { - _dist_code[dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: dist != 256"); - dist >>= 7; /* from now on, all distances are divided by 128 */ - for (; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { - _dist_code[256 + dist++] = code; - } - } - //Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) { - bl_count[bits] = 0; - } - - n = 0; - while (n <= 143) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - while (n <= 255) { - static_ltree[n * 2 + 1]/*.Len*/ = 9; - n++; - bl_count[9]++; - } - while (n <= 279) { - static_ltree[n * 2 + 1]/*.Len*/ = 7; - n++; - bl_count[7]++; - } - while (n <= 287) { - static_ltree[n * 2 + 1]/*.Len*/ = 8; - n++; - bl_count[8]++; - } - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes(static_ltree, L_CODES + 1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n * 2 + 1]/*.Len*/ = 5; - static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); - } - - // Now data ready and we can init static trees - static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); - static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); - static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); - - //static_init_done = true; -} - - -/* =========================================================================== - * Initialize a new block. - */ -function init_block(s) { - var n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } - for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } - - s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; - s.opt_len = s.static_len = 0; - s.last_lit = s.matches = 0; -} - - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -function bi_windup(s) -{ - if (s.bi_valid > 8) { - put_short(s, s.bi_buf); - } else if (s.bi_valid > 0) { - //put_byte(s, (Byte)s->bi_buf); - s.pending_buf[s.pending++] = s.bi_buf; - } - s.bi_buf = 0; - s.bi_valid = 0; -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -function copy_block(s, buf, len, header) -//DeflateState *s; -//charf *buf; /* the input data */ -//unsigned len; /* its length */ -//int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - - if (header) { - put_short(s, len); - put_short(s, ~len); - } -// while (len--) { -// put_byte(s, *buf++); -// } - utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); - s.pending += len; -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -function smaller(tree, n, m, depth) { - var _n2 = n * 2; - var _m2 = m * 2; - return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || - (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); -} - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -function pqdownheap(s, tree, k) -// deflate_state *s; -// ct_data *tree; /* the tree to restore */ -// int k; /* node to move down */ -{ - var v = s.heap[k]; - var j = k << 1; /* left son of k */ - while (j <= s.heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s.heap_len && - smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s.heap[j], s.depth)) { break; } - - /* Exchange v with the smallest son */ - s.heap[k] = s.heap[j]; - k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s.heap[k] = v; -} - - -// inlined manually -// var SMALLEST = 1; - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -function compress_block(s, ltree, dtree) -// deflate_state *s; -// const ct_data *ltree; /* literal tree */ -// const ct_data *dtree; /* distance tree */ -{ - var dist; /* distance of matched string */ - var lc; /* match length or unmatched char (if dist == 0) */ - var lx = 0; /* running index in l_buf */ - var code; /* the code to send */ - var extra; /* number of extra bits to send */ - - if (s.last_lit !== 0) { - do { - dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); - lc = s.pending_buf[s.l_buf + lx]; - lx++; - - if (dist === 0) { - send_code(s, lc, ltree); /* send a literal byte */ - //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code + LITERALS + 1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra !== 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - //Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra !== 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - // "pendingBuf overflow"); - - } while (lx < s.last_lit); - } - - send_code(s, END_BLOCK, ltree); -} - - -/* =========================================================================== - * Construct one Huffman tree and assigns the code bit strings and lengths. - * Update the total bit length for the current block. - * IN assertion: the field freq is set for all tree elements. - * OUT assertions: the fields len and code are set to the optimal bit length - * and corresponding code. The length opt_len is updated; static_len is - * also updated if stree is not null. The field max_code is set. - */ -function build_tree(s, desc) -// deflate_state *s; -// tree_desc *desc; /* the tree descriptor */ -{ - var tree = desc.dyn_tree; - var stree = desc.stat_desc.static_tree; - var has_stree = desc.stat_desc.has_stree; - var elems = desc.stat_desc.elems; - var n, m; /* iterate over heap elements */ - var max_code = -1; /* largest code with non zero frequency */ - var node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s.heap_len = 0; - s.heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n * 2]/*.Freq*/ !== 0) { - s.heap[++s.heap_len] = max_code = n; - s.depth[n] = 0; - - } else { - tree[n * 2 + 1]/*.Len*/ = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s.heap_len < 2) { - node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); - tree[node * 2]/*.Freq*/ = 1; - s.depth[node] = 0; - s.opt_len--; - - if (has_stree) { - s.static_len -= stree[node * 2 + 1]/*.Len*/; - } - /* node is 0 or 1 so it does not have extra bits */ - } - desc.max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - //pqremove(s, tree, n); /* n = node of least frequency */ - /*** pqremove ***/ - n = s.heap[1/*SMALLEST*/]; - s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; - pqdownheap(s, tree, 1/*SMALLEST*/); - /***/ - - m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ - - s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ - s.heap[--s.heap_max] = m; - - /* Create a new node father of n and m */ - tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; - s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; - tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; - - /* and insert the new node in the heap */ - s.heap[1/*SMALLEST*/] = node++; - pqdownheap(s, tree, 1/*SMALLEST*/); - - } while (s.heap_len >= 2); - - s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes(tree, max_code, s.bl_count); -} - - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -function scan_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - s.bl_tree[curlen * 2]/*.Freq*/ += count; - - } else if (curlen !== 0) { - - if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } - s.bl_tree[REP_3_6 * 2]/*.Freq*/++; - - } else if (count <= 10) { - s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; - - } else { - s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; - } - - count = 0; - prevlen = curlen; - - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -function send_tree(s, tree, max_code) -// deflate_state *s; -// ct_data *tree; /* the tree to be scanned */ -// int max_code; /* and its largest code of non zero frequency */ -{ - var n; /* iterates over all tree elements */ - var prevlen = -1; /* last emitted length */ - var curlen; /* length of current code */ - - var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ - - var count = 0; /* repeat count of the current code */ - var max_count = 7; /* max repeat count */ - var min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen === 0) { - max_count = 138; - min_count = 3; - } - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; - nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; - - if (++count < max_count && curlen === nextlen) { - continue; - - } else if (count < min_count) { - do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); - - } else if (curlen !== 0) { - if (curlen !== prevlen) { - send_code(s, curlen, s.bl_tree); - count--; - } - //Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s.bl_tree); - send_bits(s, count - 3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s.bl_tree); - send_bits(s, count - 3, 3); - - } else { - send_code(s, REPZ_11_138, s.bl_tree); - send_bits(s, count - 11, 7); - } - - count = 0; - prevlen = curlen; - if (nextlen === 0) { - max_count = 138; - min_count = 3; - - } else if (curlen === nextlen) { - max_count = 6; - min_count = 3; - - } else { - max_count = 7; - min_count = 4; - } - } -} - - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -function build_bl_tree(s) { - var max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, s.dyn_ltree, s.l_desc.max_code); - scan_tree(s, s.dyn_dtree, s.d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, s.bl_desc); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { - if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { - break; - } - } - /* Update opt_len to include the bit length tree and counts */ - s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; - //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - // s->opt_len, s->static_len)); - - return max_blindex; -} - - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -function send_all_trees(s, lcodes, dcodes, blcodes) -// deflate_state *s; -// int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - var rank; /* index in bl_order */ - - //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - // "too many codes"); - //Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes - 1, 5); - send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); - } - //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ - //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ - //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - - -/* =========================================================================== - * Check if the data type is TEXT or BINARY, using the following algorithm: - * - TEXT if the two conditions below are satisfied: - * a) There are no non-portable control characters belonging to the - * "black list" (0..6, 14..25, 28..31). - * b) There is at least one printable character belonging to the - * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). - * - BINARY otherwise. - * - The following partially-portable control characters form a - * "gray list" that is ignored in this detection algorithm: - * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). - * IN assertion: the fields Freq of dyn_ltree are set. - */ -function detect_data_type(s) { - /* black_mask is the bit mask of black-listed bytes - * set bits 0..6, 14..25, and 28..31 - * 0xf3ffc07f = binary 11110011111111111100000001111111 - */ - var black_mask = 0xf3ffc07f; - var n; - - /* Check for non-textual ("black-listed") bytes. */ - for (n = 0; n <= 31; n++, black_mask >>>= 1) { - if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { - return Z_BINARY; - } - } - - /* Check for textual ("white-listed") bytes. */ - if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || - s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - for (n = 32; n < LITERALS; n++) { - if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { - return Z_TEXT; - } - } - - /* There are no "black-listed" or "white-listed" bytes: - * this stream either is empty or has tolerated ("gray-listed") bytes only. - */ - return Z_BINARY; -} - - -var static_init_done = false; - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -function _tr_init(s) -{ - - if (!static_init_done) { - tr_static_init(); - static_init_done = true; - } - - s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); - s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); - s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); - - s.bi_buf = 0; - s.bi_valid = 0; - - /* Initialize the first block of the first file: */ - init_block(s); -} - - -/* =========================================================================== - * Send a stored block - */ -function _tr_stored_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ - copy_block(s, buf, stored_len, true); /* with header */ -} - - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - */ -function _tr_align(s) { - send_bits(s, STATIC_TREES << 1, 3); - send_code(s, END_BLOCK, static_ltree); - bi_flush(s); -} - - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -function _tr_flush_block(s, buf, stored_len, last) -//DeflateState *s; -//charf *buf; /* input block, or NULL if too old */ -//ulg stored_len; /* length of input block */ -//int last; /* one if this is the last block for a file */ -{ - var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - var max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s.level > 0) { - - /* Check if the file is binary or text */ - if (s.strm.data_type === Z_UNKNOWN) { - s.strm.data_type = detect_data_type(s); - } - - /* Construct the literal and distance trees */ - build_tree(s, s.l_desc); - // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - - build_tree(s, s.d_desc); - // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - // s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s.opt_len + 3 + 7) >>> 3; - static_lenb = (s.static_len + 3 + 7) >>> 3; - - // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - // s->last_lit)); - - if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } - - } else { - // Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - - if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { - /* 4: two words for the lengths */ - - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, last); - - } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { - - send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); - compress_block(s, static_ltree, static_dtree); - - } else { - send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); - send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); - compress_block(s, s.dyn_ltree, s.dyn_dtree); - } - // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (last) { - bi_windup(s); - } - // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - // s->compressed_len-7*last)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -function _tr_tally(s, dist, lc) -// deflate_state *s; -// unsigned dist; /* distance of matched string */ -// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - //var out_length, in_length, dcode; - - s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; - s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; - - s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; - s.last_lit++; - - if (dist === 0) { - /* lc is the unmatched char */ - s.dyn_ltree[lc * 2]/*.Freq*/++; - } else { - s.matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - //Assert((ush)dist < (ush)MAX_DIST(s) && - // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; - s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; - } - -// (!) This block is disabled in zlib defailts, -// don't enable it for binary compatibility - -//#ifdef TRUNCATE_BLOCK -// /* Try to guess if it is profitable to stop the current block here */ -// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { -// /* Compute an upper bound for the compressed length */ -// out_length = s.last_lit*8; -// in_length = s.strstart - s.block_start; -// -// for (dcode = 0; dcode < D_CODES; dcode++) { -// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); -// } -// out_length >>>= 3; -// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", -// // s->last_lit, in_length, out_length, -// // 100L - out_length*100L/in_length)); -// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { -// return true; -// } -// } -//#endif - - return (s.last_lit === s.lit_bufsize - 1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -exports._tr_init = _tr_init; -exports._tr_stored_block = _tr_stored_block; -exports._tr_flush_block = _tr_flush_block; -exports._tr_tally = _tr_tally; -exports._tr_align = _tr_align; - - -/***/ }, -/* 76 */ -/***/ function(module, exports, __webpack_require__) { - -/** - * Check if `fn` is a function. - * - * @param {Function} fn - * @return {Boolean} - * @api private - */ -var isObject = __webpack_require__(26); - -function isFunction(fn) { - var tag = isObject(fn) ? Object.prototype.toString.call(fn) : ''; - return tag === '[object Function]'; -} - -module.exports = isFunction; - - -/***/ }, -/* 77 */ -/***/ function(module, exports, __webpack_require__) { - -/** - * Module of mixed-in functions shared between node and client code - */ -var isObject = __webpack_require__(26); - -/** - * Expose `RequestBase`. - */ - -module.exports = RequestBase; - -/** - * Initialize a new `RequestBase`. - * - * @api public - */ - -function RequestBase(obj) { - if (obj) return mixin(obj); -} - -/** - * Mixin the prototype properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in RequestBase.prototype) { - obj[key] = RequestBase.prototype[key]; - } - return obj; -} - -/** - * Clear previous timeout. - * - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.clearTimeout = function _clearTimeout(){ - this._timeout = 0; - this._responseTimeout = 0; - clearTimeout(this._timer); - clearTimeout(this._responseTimeoutTimer); - return this; -}; - -/** - * Override default response body parser - * - * This function will be called to convert incoming data into request.body - * - * @param {Function} - * @api public - */ - -RequestBase.prototype.parse = function parse(fn){ - this._parser = fn; - return this; -}; - -/** - * Set format of binary response body. - * In browser valid formats are 'blob' and 'arraybuffer', - * which return Blob and ArrayBuffer, respectively. - * - * In Node all values result in Buffer. - * - * Examples: - * - * req.get('/') - * .responseType('blob') - * .end(callback); - * - * @param {String} val - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.responseType = function(val){ - this._responseType = val; - return this; -}; - -/** - * Override default request body serializer - * - * This function will be called to convert data set via .send or .attach into payload to send - * - * @param {Function} - * @api public - */ - -RequestBase.prototype.serialize = function serialize(fn){ - this._serializer = fn; - return this; -}; - -/** - * Set timeouts. - * - * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. - * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. - * - * Value of 0 or false means no timeout. - * - * @param {Number|Object} ms or {response, read, deadline} - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.timeout = function timeout(options){ - if (!options || 'object' !== typeof options) { - this._timeout = options; - this._responseTimeout = 0; - return this; - } - - if ('undefined' !== typeof options.deadline) { - this._timeout = options.deadline; - } - if ('undefined' !== typeof options.response) { - this._responseTimeout = options.response; - } - return this; -}; - -/** - * Promise support - * - * @param {Function} resolve - * @param {Function} reject - * @return {Request} - */ - -RequestBase.prototype.then = function then(resolve, reject) { - if (!this._fullfilledPromise) { - var self = this; - if (this._endCalled) { - console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"); - } - this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ - self.end(function(err, res){ - if (err) innerReject(err); else innerResolve(res); - }); - }); - } - return this._fullfilledPromise.then(resolve, reject); -} - -RequestBase.prototype.catch = function(cb) { - return this.then(undefined, cb); -}; - -/** - * Allow for extension - */ - -RequestBase.prototype.use = function use(fn) { - fn(this); - return this; -} - -RequestBase.prototype.ok = function(cb) { - if ('function' !== typeof cb) throw Error("Callback required"); - this._okCallback = cb; - return this; -}; - -RequestBase.prototype._isResponseOK = function(res) { - if (!res) { - return false; - } - - if (this._okCallback) { - return this._okCallback(res); - } - - return res.status >= 200 && res.status < 300; -}; - - -/** - * Get request header `field`. - * Case-insensitive. - * - * @param {String} field - * @return {String} - * @api public - */ - -RequestBase.prototype.get = function(field){ - return this._header[field.toLowerCase()]; -}; - -/** - * Get case-insensitive header `field` value. - * This is a deprecated internal API. Use `.get(field)` instead. - * - * (getHeader is no longer used internally by the superagent code base) - * - * @param {String} field - * @return {String} - * @api private - * @deprecated - */ - -RequestBase.prototype.getHeader = RequestBase.prototype.get; - -/** - * Set header `field` to `val`, or multiple fields with one object. - * Case-insensitive. - * - * Examples: - * - * req.get('/') - * .set('Accept', 'application/json') - * .set('X-API-Key', 'foobar') - * .end(callback); - * - * req.get('/') - * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) - * .end(callback); - * - * @param {String|Object} field - * @param {String} val - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.set = function(field, val){ - if (isObject(field)) { - for (var key in field) { - this.set(key, field[key]); - } - return this; - } - this._header[field.toLowerCase()] = val; - this.header[field] = val; - return this; -}; - -/** - * Remove header `field`. - * Case-insensitive. - * - * Example: - * - * req.get('/') - * .unset('User-Agent') - * .end(callback); - * - * @param {String} field - */ -RequestBase.prototype.unset = function(field){ - delete this._header[field.toLowerCase()]; - delete this.header[field]; - return this; -}; - -/** - * Write the field `name` and `val`, or multiple fields with one object - * for "multipart/form-data" request bodies. - * - * ``` js - * request.post('/upload') - * .field('foo', 'bar') - * .end(callback); - * - * request.post('/upload') - * .field({ foo: 'bar', baz: 'qux' }) - * .end(callback); - * ``` - * - * @param {String|Object} name - * @param {String|Blob|File|Buffer|fs.ReadStream} val - * @return {Request} for chaining - * @api public - */ -RequestBase.prototype.field = function(name, val) { - - // name should be either a string or an object. - if (null === name || undefined === name) { - throw new Error('.field(name, val) name can not be empty'); - } - - if (isObject(name)) { - for (var key in name) { - this.field(key, name[key]); - } - return this; - } - - if (Array.isArray(val)) { - for (var i in val) { - this.field(name, val[i]); - } - return this; - } - - // val should be defined now - if (null === val || undefined === val) { - throw new Error('.field(name, val) val can not be empty'); - } - if ('boolean' === typeof val) { - val = '' + val; - } - this._getFormData().append(name, val); - return this; -}; - -/** - * Abort the request, and clear potential timeout. - * - * @return {Request} - * @api public - */ -RequestBase.prototype.abort = function(){ - if (this._aborted) { - return this; - } - this._aborted = true; - this.xhr && this.xhr.abort(); // browser - this.req && this.req.abort(); // node - this.clearTimeout(); - this.emit('abort'); - return this; -}; - -/** - * Enable transmission of cookies with x-domain requests. - * - * Note that for this to work the origin must not be - * using "Access-Control-Allow-Origin" with a wildcard, - * and also must set "Access-Control-Allow-Credentials" - * to "true". - * - * @api public - */ - -RequestBase.prototype.withCredentials = function(){ - // This is browser-only functionality. Node side is no-op. - this._withCredentials = true; - return this; -}; - -/** - * Set the max redirects to `n`. Does noting in browser XHR implementation. - * - * @param {Number} n - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.redirects = function(n){ - this._maxRedirects = n; - return this; -}; - -/** - * Convert to a plain javascript object (not JSON string) of scalar properties. - * Note as this method is designed to return a useful non-this value, - * it cannot be chained. - * - * @return {Object} describing method, url, and data of this request - * @api public - */ - -RequestBase.prototype.toJSON = function(){ - return { - method: this.method, - url: this.url, - data: this._data, - headers: this._header - }; -}; - - -/** - * Send `data` as the request body, defaulting the `.type()` to "json" when - * an object is given. - * - * Examples: - * - * // manual json - * request.post('/user') - * .type('json') - * .send('{"name":"tj"}') - * .end(callback) - * - * // auto json - * request.post('/user') - * .send({ name: 'tj' }) - * .end(callback) - * - * // manual x-www-form-urlencoded - * request.post('/user') - * .type('form') - * .send('name=tj') - * .end(callback) - * - * // auto x-www-form-urlencoded - * request.post('/user') - * .type('form') - * .send({ name: 'tj' }) - * .end(callback) - * - * // defaults to x-www-form-urlencoded - * request.post('/user') - * .send('name=tobi') - * .send('species=ferret') - * .end(callback) - * - * @param {String|Object} data - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.send = function(data){ - var isObj = isObject(data); - var type = this._header['content-type']; - - if (isObj && !this._data) { - if (Array.isArray(data)) { - this._data = []; - } else if (!this._isHost(data)) { - this._data = {}; - } - } else if (data && this._data && this._isHost(this._data)) { - throw Error("Can't merge these send calls"); - } - - // merge - if (isObj && isObject(this._data)) { - for (var key in data) { - this._data[key] = data[key]; - } - } else if ('string' == typeof data) { - // default to x-www-form-urlencoded - if (!type) this.type('form'); - type = this._header['content-type']; - if ('application/x-www-form-urlencoded' == type) { - this._data = this._data - ? this._data + '&' + data - : data; - } else { - this._data = (this._data || '') + data; - } - } else { - this._data = data; - } - - if (!isObj || this._isHost(data)) { - return this; - } - - // default to json - if (!type) this.type('json'); - return this; -}; - - -/** - * Sort `querystring` by the sort function - * - * - * Examples: - * - * // default order - * request.get('/user') - * .query('name=Nick') - * .query('search=Manny') - * .sortQuery() - * .end(callback) - * - * // customized sort function - * request.get('/user') - * .query('name=Nick') - * .query('search=Manny') - * .sortQuery(function(a, b){ - * return a.length - b.length; - * }) - * .end(callback) - * - * - * @param {Function} sort - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.sortQuery = function(sort) { - // _sort default to true but otherwise can be a function or boolean - this._sort = typeof sort === 'undefined' ? true : sort; - return this; -}; - -/** - * Invoke callback with timeout error. - * - * @api private - */ - -RequestBase.prototype._timeoutError = function(reason, timeout){ - if (this._aborted) { - return; - } - var err = new Error(reason + timeout + 'ms exceeded'); - err.timeout = timeout; - err.code = 'ECONNABORTED'; - this.timedout = true; - this.abort(); - this.callback(err); -}; - -RequestBase.prototype._setTimeouts = function() { - var self = this; - - // deadline - if (this._timeout && !this._timer) { - this._timer = setTimeout(function(){ - self._timeoutError('Timeout of ', self._timeout); - }, this._timeout); - } - // response timeout - if (this._responseTimeout && !this._responseTimeoutTimer) { - this._responseTimeoutTimer = setTimeout(function(){ - self._timeoutError('Response timeout of ', self._responseTimeout); - }, this._responseTimeout); - } -} - - -/***/ }, -/* 78 */ -/***/ function(module, exports, __webpack_require__) { - - -/** - * Module dependencies. - */ - -var utils = __webpack_require__(79); - -/** - * Expose `ResponseBase`. - */ - -module.exports = ResponseBase; - -/** - * Initialize a new `ResponseBase`. - * - * @api public - */ - -function ResponseBase(obj) { - if (obj) return mixin(obj); -} - -/** - * Mixin the prototype properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in ResponseBase.prototype) { - obj[key] = ResponseBase.prototype[key]; - } - return obj; -} - -/** - * Get case-insensitive `field` value. - * - * @param {String} field - * @return {String} - * @api public - */ - -ResponseBase.prototype.get = function(field){ - return this.header[field.toLowerCase()]; -}; - -/** - * Set header related properties: - * - * - `.type` the content type without params - * - * A response of "Content-Type: text/plain; charset=utf-8" - * will provide you with a `.type` of "text/plain". - * - * @param {Object} header - * @api private - */ - -ResponseBase.prototype._setHeaderProperties = function(header){ - // TODO: moar! - // TODO: make this a util - - // content-type - var ct = header['content-type'] || ''; - this.type = utils.type(ct); - - // params - var params = utils.params(ct); - for (var key in params) this[key] = params[key]; - - this.links = {}; - - // links - try { - if (header.link) { - this.links = utils.parseLinks(header.link); - } - } catch (err) { - // ignore - } -}; - -/** - * Set flags such as `.ok` based on `status`. - * - * For example a 2xx response will give you a `.ok` of __true__ - * whereas 5xx will be __false__ and `.error` will be __true__. The - * `.clientError` and `.serverError` are also available to be more - * specific, and `.statusType` is the class of error ranging from 1..5 - * sometimes useful for mapping respond colors etc. - * - * "sugar" properties are also defined for common cases. Currently providing: - * - * - .noContent - * - .badRequest - * - .unauthorized - * - .notAcceptable - * - .notFound - * - * @param {Number} status - * @api private - */ - -ResponseBase.prototype._setStatusProperties = function(status){ - var type = status / 100 | 0; - - // status / class - this.status = this.statusCode = status; - this.statusType = type; - - // basics - this.info = 1 == type; - this.ok = 2 == type; - this.redirect = 3 == type; - this.clientError = 4 == type; - this.serverError = 5 == type; - this.error = (4 == type || 5 == type) - ? this.toError() - : false; - - // sugar - this.accepted = 202 == status; - this.noContent = 204 == status; - this.badRequest = 400 == status; - this.unauthorized = 401 == status; - this.notAcceptable = 406 == status; - this.forbidden = 403 == status; - this.notFound = 404 == status; -}; - - -/***/ }, -/* 79 */ -/***/ function(module, exports) { - - -/** - * Return the mime type for the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.type = function(str){ - return str.split(/ *; */).shift(); -}; - -/** - * Return header field parameters. - * - * @param {String} str - * @return {Object} - * @api private - */ - -exports.params = function(str){ - return str.split(/ *; */).reduce(function(obj, str){ - var parts = str.split(/ *= */); - var key = parts.shift(); - var val = parts.shift(); - - if (key && val) obj[key] = val; - return obj; - }, {}); -}; - -/** - * Parse Link header fields. - * - * @param {String} str - * @return {Object} - * @api private - */ - -exports.parseLinks = function(str){ - return str.split(/ *, */).reduce(function(obj, str){ - var parts = str.split(/ *; */); - var url = parts[0].slice(1, -1); - var rel = parts[1].split(/ *= */)[1].slice(1, -1); - obj[rel] = url; - return obj; - }, {}); -}; - -/** - * Strip content related fields from `header`. - * - * @param {Object} header - * @return {Object} header - * @api private - */ - -exports.cleanHeader = function(header, shouldStripCookie){ - delete header['content-type']; - delete header['content-length']; - delete header['transfer-encoding']; - delete header['host']; - if (shouldStripCookie) { - delete header['cookie']; - } - return header; -}; - - -/***/ }, -/* 80 */ -/***/ function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { return this; })(); - -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); -} catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; - - -/***/ }, -/* 81 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); -const Guild = __webpack_require__(17); -const User = __webpack_require__(6); -const DMChannel = __webpack_require__(30); -const Emoji = __webpack_require__(10); -const TextChannel = __webpack_require__(41); -const VoiceChannel = __webpack_require__(42); -const GuildChannel = __webpack_require__(13); -const GroupDMChannel = __webpack_require__(31); - -class ClientDataManager { - constructor(client) { - this.client = client; - } - - get pastReady() { - return this.client.ws.status === Constants.Status.READY; - } - - newGuild(data) { - const already = this.client.guilds.has(data.id); - const guild = new Guild(this.client, data); - this.client.guilds.set(guild.id, guild); - if (this.pastReady && !already) { - /** - * Emitted whenever the client joins a guild. - * @event Client#guildCreate - * @param {Guild} guild The created guild - */ - if (this.client.options.fetchAllMembers) { - guild.fetchMembers().then(() => { this.client.emit(Constants.Events.GUILD_CREATE, guild); }); - } else { - this.client.emit(Constants.Events.GUILD_CREATE, guild); - } - } - - return guild; - } - - newUser(data) { - if (this.client.users.has(data.id)) return this.client.users.get(data.id); - const user = new User(this.client, data); - this.client.users.set(user.id, user); - return user; - } - - newChannel(data, guild) { - const already = this.client.channels.has(data.id); - let channel; - if (data.type === Constants.ChannelTypes.DM) { - channel = new DMChannel(this.client, data); - } else if (data.type === Constants.ChannelTypes.groupDM) { - channel = new GroupDMChannel(this.client, data); - } else { - guild = guild || this.client.guilds.get(data.guild_id); - if (guild) { - if (data.type === Constants.ChannelTypes.text) { - channel = new TextChannel(guild, data); - guild.channels.set(channel.id, channel); - } else if (data.type === Constants.ChannelTypes.voice) { - channel = new VoiceChannel(guild, data); - guild.channels.set(channel.id, channel); - } - } - } - - if (channel) { - if (this.pastReady && !already) this.client.emit(Constants.Events.CHANNEL_CREATE, channel); - this.client.channels.set(channel.id, channel); - return channel; - } - - return null; - } - - newEmoji(data, guild) { - const already = guild.emojis.has(data.id); - if (data && !already) { - let emoji = new Emoji(guild, data); - this.client.emit(Constants.Events.GUILD_EMOJI_CREATE, emoji); - guild.emojis.set(emoji.id, emoji); - return emoji; - } else if (already) { - return guild.emojis.get(data.id); - } - - return null; - } - - killEmoji(emoji) { - if (!(emoji instanceof Emoji && emoji.guild)) return; - this.client.emit(Constants.Events.GUILD_EMOJI_DELETE, emoji); - emoji.guild.emojis.delete(emoji.id); - } - - killGuild(guild) { - const already = this.client.guilds.has(guild.id); - this.client.guilds.delete(guild.id); - if (already && this.pastReady) this.client.emit(Constants.Events.GUILD_DELETE, guild); - } - - killUser(user) { - this.client.users.delete(user.id); - } - - killChannel(channel) { - this.client.channels.delete(channel.id); - if (channel instanceof GuildChannel) channel.guild.channels.delete(channel.id); - } - - updateGuild(currentGuild, newData) { - const oldGuild = cloneObject(currentGuild); - currentGuild.setup(newData); - if (this.pastReady) this.client.emit(Constants.Events.GUILD_UPDATE, oldGuild, currentGuild); - } - - updateChannel(currentChannel, newData) { - currentChannel.setup(newData); - } - - updateEmoji(currentEmoji, newData) { - const oldEmoji = cloneObject(currentEmoji); - currentEmoji.setup(newData); - this.client.emit(Constants.Events.GUILD_EMOJI_UPDATE, oldEmoji, currentEmoji); - } -} - -module.exports = ClientDataManager; - - -/***/ }, -/* 82 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -/** - * Manages the State and Background Tasks of the Client - * @private - */ -class ClientManager { - constructor(client) { - /** - * The Client that instantiated this Manager - * @type {Client} - */ - this.client = client; - - /** - * The heartbeat interval, null if not yet set - * @type {?number} - */ - this.heartbeatInterval = null; - } - - /** - * Connects the Client to the WebSocket - * @param {string} token The authorization token - * @param {Function} resolve Function to run when connection is successful - * @param {Function} reject Function to run when connection fails - */ - connectToWebSocket(token, resolve, reject) { - this.client.emit(Constants.Events.DEBUG, `Authenticated using token ${token}`); - this.client.token = token; - const timeout = this.client.setTimeout(() => reject(new Error(Constants.Errors.TOOK_TOO_LONG)), 1000 * 300); - this.client.rest.methods.getGateway().then(gateway => { - this.client.emit(Constants.Events.DEBUG, `Using gateway ${gateway}`); - this.client.ws.connect(gateway); - this.client.ws.once('close', event => { - if (event.code === 4004) reject(new Error(Constants.Errors.BAD_LOGIN)); - if (event.code === 4010) reject(new Error(Constants.Errors.INVALID_SHARD)); - }); - this.client.once(Constants.Events.READY, () => { - resolve(token); - this.client.clearTimeout(timeout); - }); - }, reject); - } - - /** - * Sets up a keep-alive interval to keep the Client's connection valid - * @param {number} time The interval in milliseconds at which heartbeat packets should be sent - */ - setupKeepAlive(time) { - this.heartbeatInterval = this.client.setInterval(() => this.client.ws.heartbeat(true), time); - } - - destroy() { - this.client.ws.destroy(); - if (this.client.user.bot) { - this.client.token = null; - return Promise.resolve(); - } else { - return this.client.rest.methods.logout().then(() => { - this.client.token = null; - }); - } - } -} - -module.exports = ClientManager; - - -/***/ }, -/* 83 */ -/***/ function(module, exports, __webpack_require__) { - -class ActionsManager { - constructor(client) { - this.client = client; - - this.register(__webpack_require__(100)); - this.register(__webpack_require__(101)); - this.register(__webpack_require__(102)); - this.register(__webpack_require__(106)); - this.register(__webpack_require__(103)); - this.register(__webpack_require__(104)); - this.register(__webpack_require__(105)); - this.register(__webpack_require__(84)); - this.register(__webpack_require__(85)); - this.register(__webpack_require__(86)); - this.register(__webpack_require__(88)); - this.register(__webpack_require__(99)); - this.register(__webpack_require__(92)); - this.register(__webpack_require__(93)); - this.register(__webpack_require__(87)); - this.register(__webpack_require__(94)); - this.register(__webpack_require__(95)); - this.register(__webpack_require__(96)); - this.register(__webpack_require__(107)); - this.register(__webpack_require__(109)); - this.register(__webpack_require__(108)); - this.register(__webpack_require__(98)); - this.register(__webpack_require__(89)); - this.register(__webpack_require__(90)); - this.register(__webpack_require__(91)); - this.register(__webpack_require__(97)); - } - - register(Action) { - this[Action.name.replace(/Action$/, '')] = new Action(this.client); - } -} - -module.exports = ActionsManager; - - -/***/ }, -/* 84 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class ChannelCreateAction extends Action { - handle(data) { - const client = this.client; - const channel = client.dataManager.newChannel(data); - return { - channel, - }; - } -} - -module.exports = ChannelCreateAction; - - -/***/ }, -/* 85 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class ChannelDeleteAction extends Action { - constructor(client) { - super(client); - this.deleted = new Map(); - } - - handle(data) { - const client = this.client; - - let channel = client.channels.get(data.id); - if (channel) { - client.dataManager.killChannel(channel); - this.deleted.set(channel.id, channel); - this.scheduleForDeletion(channel.id); - } else { - channel = this.deleted.get(data.id) || null; - } - - return { - channel, - }; - } - - scheduleForDeletion(id) { - this.client.setTimeout(() => this.deleted.delete(id), this.client.options.restWsBridgeTimeout); - } -} - -module.exports = ChannelDeleteAction; - - -/***/ }, -/* 86 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class ChannelUpdateAction extends Action { - handle(data) { - const client = this.client; - - const channel = client.channels.get(data.id); - if (channel) { - const oldChannel = cloneObject(channel); - channel.setup(data); - client.emit(Constants.Events.CHANNEL_UPDATE, oldChannel, channel); - return { - old: oldChannel, - updated: channel, - }; - } - - return { - old: null, - updated: null, - }; - } -} - -/** - * Emitted whenever a channel is updated - e.g. name change, topic change. - * @event Client#channelUpdate - * @param {Channel} oldChannel The channel before the update - * @param {Channel} newChannel The channel after the update - */ - -module.exports = ChannelUpdateAction; - - -/***/ }, -/* 87 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -class GuildBanRemove extends Action { - handle(data) { - const client = this.client; - const guild = client.guilds.get(data.guild_id); - const user = client.dataManager.newUser(data.user); - if (guild && user) client.emit(Constants.Events.GUILD_BAN_REMOVE, guild, user); - } -} - -module.exports = GuildBanRemove; - - -/***/ }, -/* 88 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -class GuildDeleteAction extends Action { - constructor(client) { - super(client); - this.deleted = new Map(); - } - - handle(data) { - const client = this.client; - - let guild = client.guilds.get(data.id); - if (guild) { - if (guild.available && data.unavailable) { - // guild is unavailable - guild.available = false; - client.emit(Constants.Events.GUILD_UNAVAILABLE, guild); - - // stops the GuildDelete packet thinking a guild was actually deleted, - // handles emitting of event itself - return { - guild: null, - }; - } - - // delete guild - client.guilds.delete(guild.id); - this.deleted.set(guild.id, guild); - this.scheduleForDeletion(guild.id); - } else { - guild = this.deleted.get(data.id) || null; - } - - return { - guild, - }; - } - - scheduleForDeletion(id) { - this.client.setTimeout(() => this.deleted.delete(id), this.client.options.restWsBridgeTimeout); - } -} - -/** - * Emitted whenever a guild becomes unavailable, likely due to a server outage. - * @event Client#guildUnavailable - * @param {Guild} guild The guild that has become unavailable. - */ - -module.exports = GuildDeleteAction; - - -/***/ }, -/* 89 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class GuildEmojiCreateAction extends Action { - handle(guild, createdEmoji) { - const client = this.client; - const emoji = client.dataManager.newEmoji(createdEmoji, guild); - return { - emoji, - }; - } -} - -/** - * Emitted whenever a custom emoji is created in a guild - * @event Client#emojiCreate - * @param {Emoji} emoji The emoji that was created. - */ -module.exports = GuildEmojiCreateAction; - - -/***/ }, -/* 90 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class GuildEmojiDeleteAction extends Action { - handle(emoji) { - const client = this.client; - client.dataManager.killEmoji(emoji); - return { - emoji, - }; - } -} - -/** - * Emitted whenever a custom guild emoji is deleted - * @event Client#emojiDelete - * @param {Emoji} emoji The emoji that was deleted. - */ -module.exports = GuildEmojiDeleteAction; - - -/***/ }, -/* 91 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class GuildEmojiUpdateAction extends Action { - handle(oldEmoji, newEmoji) { - this.client.dataManager.updateEmoji(oldEmoji, newEmoji); - } -} - -/** - * Emitted whenever a custom guild emoji is updated - * @event Client#emojiUpdate - * @param {Emoji} oldEmoji The old emoji - * @param {Emoji} newEmoji The new emoji - */ -module.exports = GuildEmojiUpdateAction; - - -/***/ }, -/* 92 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class GuildMemberGetAction extends Action { - handle(guild, data) { - const member = guild._addMember(data, false); - return { - member, - }; - } -} - -module.exports = GuildMemberGetAction; - - -/***/ }, -/* 93 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -class GuildMemberRemoveAction extends Action { - constructor(client) { - super(client); - this.deleted = new Map(); - } - - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - let member = guild.members.get(data.user.id); - if (member) { - guild.memberCount--; - guild._removeMember(member); - this.deleted.set(guild.id + data.user.id, member); - if (client.status === Constants.Status.READY) client.emit(Constants.Events.GUILD_MEMBER_REMOVE, member); - this.scheduleForDeletion(guild.id, data.user.id); - } else { - member = this.deleted.get(guild.id + data.user.id) || null; - } - - return { - guild, - member, - }; - } - - return { - guild, - member: null, - }; - } - - scheduleForDeletion(guildID, userID) { - this.client.setTimeout(() => this.deleted.delete(guildID + userID), this.client.options.restWsBridgeTimeout); - } -} - -/** - * Emitted whenever a member leaves a guild, or is kicked. - * @event Client#guildMemberRemove - * @param {GuildMember} member The member that has left/been kicked from the guild. - */ - -module.exports = GuildMemberRemoveAction; - - -/***/ }, -/* 94 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); -const Role = __webpack_require__(8); - -class GuildRoleCreate extends Action { - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - const already = guild.roles.has(data.role.id); - const role = new Role(guild, data.role); - guild.roles.set(role.id, role); - if (!already) client.emit(Constants.Events.GUILD_ROLE_CREATE, role); - return { - role, - }; - } - - return { - role: null, - }; - } -} - -/** - * Emitted whenever a role is created. - * @event Client#roleCreate - * @param {Role} role The role that was created. - */ - -module.exports = GuildRoleCreate; - - -/***/ }, -/* 95 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -class GuildRoleDeleteAction extends Action { - constructor(client) { - super(client); - this.deleted = new Map(); - } - - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - let role = guild.roles.get(data.role_id); - if (role) { - guild.roles.delete(data.role_id); - this.deleted.set(guild.id + data.role_id, role); - this.scheduleForDeletion(guild.id, data.role_id); - client.emit(Constants.Events.GUILD_ROLE_DELETE, role); - } else { - role = this.deleted.get(guild.id + data.role_id) || null; - } - - return { - role, - }; - } - - return { - role: null, - }; - } - - scheduleForDeletion(guildID, roleID) { - this.client.setTimeout(() => this.deleted.delete(guildID + roleID), this.client.options.restWsBridgeTimeout); - } -} - -/** - * Emitted whenever a guild role is deleted. - * @event Client#roleDelete - * @param {Role} role The role that was deleted. - */ - -module.exports = GuildRoleDeleteAction; - - -/***/ }, -/* 96 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class GuildRoleUpdateAction extends Action { - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - const roleData = data.role; - let oldRole = null; - - const role = guild.roles.get(roleData.id); - if (role) { - oldRole = cloneObject(role); - role.setup(data.role); - client.emit(Constants.Events.GUILD_ROLE_UPDATE, oldRole, role); - } - - return { - old: oldRole, - updated: role, - }; - } - - return { - old: null, - updated: null, - }; - } -} - -/** - * Emitted whenever a guild role is updated. - * @event Client#roleUpdate - * @param {Role} oldRole The role before the update. - * @param {Role} newRole The role after the update. - */ - -module.exports = GuildRoleUpdateAction; - - -/***/ }, -/* 97 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class GuildRolesPositionUpdate extends Action { - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - for (const partialRole of data.roles) { - const role = guild.roles.get(partialRole.id); - if (role) { - role.position = partialRole.position; - } - } - } - - return { - guild, - }; - } -} - -module.exports = GuildRolesPositionUpdate; - - -/***/ }, -/* 98 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class GuildSync extends Action { - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.id); - if (guild) { - data.presences = data.presences || []; - for (const presence of data.presences) { - guild._setPresence(presence.user.id, presence); - } - - data.members = data.members || []; - for (const syncMember of data.members) { - const member = guild.members.get(syncMember.user.id); - if (member) { - guild._updateMember(member, syncMember); - } else { - guild._addMember(syncMember, false); - } - } - } - } -} - -module.exports = GuildSync; - - -/***/ }, -/* 99 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class GuildUpdateAction extends Action { - handle(data) { - const client = this.client; - - const guild = client.guilds.get(data.id); - if (guild) { - const oldGuild = cloneObject(guild); - guild.setup(data); - client.emit(Constants.Events.GUILD_UPDATE, oldGuild, guild); - return { - old: oldGuild, - updated: guild, - }; - } - - return { - old: null, - updated: null, - }; - } -} - -/** - * Emitted whenever a guild is updated - e.g. name change. - * @event Client#guildUpdate - * @param {Guild} oldGuild The guild before the update. - * @param {Guild} newGuild The guild after the update. - */ - -module.exports = GuildUpdateAction; - - -/***/ }, -/* 100 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Message = __webpack_require__(11); - -class MessageCreateAction extends Action { - handle(data) { - const client = this.client; - - const channel = client.channels.get((data instanceof Array ? data[0] : data).channel_id); - const user = client.users.get((data instanceof Array ? data[0] : data).author.id); - if (channel) { - const member = channel.guild ? channel.guild.member(user) : null; - if (data instanceof Array) { - const messages = new Array(data.length); - for (let i = 0; i < data.length; i++) { - messages[i] = channel._cacheMessage(new Message(channel, data[i], client)); - } - channel.lastMessageID = messages[messages.length - 1].id; - if (user) user.lastMessageID = messages[messages.length - 1].id; - if (member) member.lastMessageID = messages[messages.length - 1].id; - return { - messages, - }; - } else { - const message = channel._cacheMessage(new Message(channel, data, client)); - channel.lastMessageID = data.id; - if (user) user.lastMessageID = data.id; - if (member) member.lastMessageID = data.id; - return { - message, - }; - } - } - - return { - message: null, - }; - } -} - -module.exports = MessageCreateAction; - - -/***/ }, -/* 101 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class MessageDeleteAction extends Action { - constructor(client) { - super(client); - this.deleted = new Map(); - } - - handle(data) { - const client = this.client; - - const channel = client.channels.get(data.channel_id); - if (channel) { - let message = channel.messages.get(data.id); - - if (message) { - channel.messages.delete(message.id); - this.deleted.set(channel.id + message.id, message); - this.scheduleForDeletion(channel.id, message.id); - } else { - message = this.deleted.get(channel.id + data.id) || null; - } - - return { - message, - }; - } - - return { - message: null, - }; - } - - scheduleForDeletion(channelID, messageID) { - this.client.setTimeout(() => this.deleted.delete(channelID + messageID), - this.client.options.restWsBridgeTimeout); - } -} - -module.exports = MessageDeleteAction; - - -/***/ }, -/* 102 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Collection = __webpack_require__(3); -const Constants = __webpack_require__(0); - -class MessageDeleteBulkAction extends Action { - handle(data) { - const client = this.client; - const channel = client.channels.get(data.channel_id); - - const ids = data.ids; - const messages = new Collection(); - for (const id of ids) { - const message = channel.messages.get(id); - if (message) messages.set(message.id, message); - } - - if (messages.size > 0) client.emit(Constants.Events.MESSAGE_BULK_DELETE, messages); - return { - messages, - }; - } -} - -module.exports = MessageDeleteBulkAction; - - -/***/ }, -/* 103 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -/* -{ user_id: 'id', - message_id: 'id', - emoji: { name: '�', id: null }, - channel_id: 'id' } } -*/ - -class MessageReactionAdd extends Action { - handle(data) { - const user = this.client.users.get(data.user_id); - if (!user) return false; - - const channel = this.client.channels.get(data.channel_id); - if (!channel || channel.type === 'voice') return false; - - const message = channel.messages.get(data.message_id); - if (!message) return false; - - if (!data.emoji) return false; - - const reaction = message._addReaction(data.emoji, user); - - if (reaction) { - this.client.emit(Constants.Events.MESSAGE_REACTION_ADD, reaction, user); - } - - return { - message, - reaction, - user, - }; - } -} -/** - * Emitted whenever a reaction is added to a message. - * @event Client#messageReactionAdd - * @param {MessageReaction} messageReaction The reaction object. - * @param {User} user The user that applied the emoji or reaction emoji. - */ -module.exports = MessageReactionAdd; - - -/***/ }, -/* 104 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -/* -{ user_id: 'id', - message_id: 'id', - emoji: { name: '�', id: null }, - channel_id: 'id' } } -*/ - -class MessageReactionRemove extends Action { - handle(data) { - const user = this.client.users.get(data.user_id); - if (!user) return false; - - const channel = this.client.channels.get(data.channel_id); - if (!channel || channel.type === 'voice') return false; - - const message = channel.messages.get(data.message_id); - if (!message) return false; - - if (!data.emoji) return false; - - const reaction = message._removeReaction(data.emoji, user); - - if (reaction) { - this.client.emit(Constants.Events.MESSAGE_REACTION_REMOVE, reaction, user); - } - - return { - message, - reaction, - user, - }; - } -} -/** - * Emitted whenever a reaction is removed from a message. - * @event Client#messageReactionRemove - * @param {MessageReaction} messageReaction The reaction object. - * @param {User} user The user that removed the emoji or reaction emoji. - */ -module.exports = MessageReactionRemove; - - -/***/ }, -/* 105 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -class MessageReactionRemoveAll extends Action { - handle(data) { - const channel = this.client.channels.get(data.channel_id); - if (!channel || channel.type === 'voice') return false; - - const message = channel.messages.get(data.message_id); - if (!message) return false; - - message._clearReactions(); - this.client.emit(Constants.Events.MESSAGE_REACTION_REMOVE_ALL, message); - - return { - message, - }; - } -} -/** - * Emitted whenever all reactions are removed from a message. - * @event Client#messageReactionRemoveAll - * @param {MessageReaction} messageReaction The reaction object. - */ -module.exports = MessageReactionRemoveAll; - - -/***/ }, -/* 106 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class MessageUpdateAction extends Action { - handle(data) { - const client = this.client; - - const channel = client.channels.get(data.channel_id); - if (channel) { - const message = channel.messages.get(data.id); - if (message) { - const oldMessage = cloneObject(message); - message.patch(data); - message._edits.unshift(oldMessage); - client.emit(Constants.Events.MESSAGE_UPDATE, oldMessage, message); - return { - old: oldMessage, - updated: message, - }; - } - - return { - old: message, - updated: message, - }; - } - - return { - old: null, - updated: null, - }; - } -} - -/** - * Emitted whenever a message is updated - e.g. embed or content change. - * @event Client#messageUpdate - * @param {Message} oldMessage The message before the update. - * @param {Message} newMessage The message after the update. - */ - -module.exports = MessageUpdateAction; - - -/***/ }, -/* 107 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); - -class UserGetAction extends Action { - handle(data) { - const client = this.client; - const user = client.dataManager.newUser(data); - return { - user, - }; - } -} - -module.exports = UserGetAction; - - -/***/ }, -/* 108 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); - -class UserNoteUpdateAction extends Action { - handle(data) { - const client = this.client; - - const oldNote = client.user.notes.get(data.id); - const note = data.note.length ? data.note : null; - - client.user.notes.set(data.id, note); - - client.emit(Constants.Events.USER_NOTE_UPDATE, data.id, oldNote, note); - - return { - old: oldNote, - updated: note, - }; - } -} - -/** - * Emitted whenever a note is updated. - * @event Client#userNoteUpdate - * @param {User} user The user the note belongs to - * @param {string} oldNote The note content before the update - * @param {string} newNote The note content after the update - */ - -module.exports = UserNoteUpdateAction; - - -/***/ }, -/* 109 */ -/***/ function(module, exports, __webpack_require__) { - -const Action = __webpack_require__(2); -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class UserUpdateAction extends Action { - handle(data) { - const client = this.client; - - if (client.user) { - if (client.user.equals(data)) { - return { - old: client.user, - updated: client.user, - }; - } - - const oldUser = cloneObject(client.user); - client.user.patch(data); - client.emit(Constants.Events.USER_UPDATE, oldUser, client.user); - return { - old: oldUser, - updated: client.user, - }; - } - - return { - old: null, - updated: null, - }; - } -} - -module.exports = UserUpdateAction; - - -/***/ }, -/* 110 */ -/***/ function(module, exports, __webpack_require__) { - -const request = __webpack_require__(25); -const Constants = __webpack_require__(0); - -function getRoute(url) { - let route = url.split('?')[0]; - if (route.includes('/channels/') || route.includes('/guilds/')) { - const startInd = route.includes('/channels/') ? route.indexOf('/channels/') : route.indexOf('/guilds/'); - const majorID = route.substring(startInd).split('/')[2]; - route = route.replace(/(\d{8,})/g, ':id').replace(':id', majorID); - } - return route; -} - -class APIRequest { - constructor(rest, method, url, auth, data, file) { - this.rest = rest; - this.method = method; - this.url = url; - this.auth = auth; - this.data = data; - this.file = file; - this.route = getRoute(this.url); - } - - getAuth() { - if (this.rest.client.token && this.rest.client.user && this.rest.client.user.bot) { - return `Bot ${this.rest.client.token}`; - } else if (this.rest.client.token) { - return this.rest.client.token; - } - throw new Error(Constants.Errors.NO_TOKEN); - } - - gen() { - const apiRequest = request[this.method](this.url); - if (this.auth) apiRequest.set('authorization', this.getAuth()); - if (this.file && this.file.file) { - apiRequest.attach('file', this.file.file, this.file.name); - this.data = this.data || {}; - apiRequest.field('payload_json', JSON.stringify(this.data)); - } else if (this.data) { - apiRequest.send(this.data); - } - if (!this.rest.client.browser) apiRequest.set('User-Agent', this.rest.userAgentManager.userAgent); - return apiRequest; - } -} - -module.exports = APIRequest; - - -/***/ }, -/* 111 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); -const splitMessage = __webpack_require__(43); -const parseEmoji = __webpack_require__(154); -const escapeMarkdown = __webpack_require__(15); - -const User = __webpack_require__(6); -const GuildMember = __webpack_require__(14); -const Message = __webpack_require__(11); -const Role = __webpack_require__(8); -const Invite = __webpack_require__(32); -const Webhook = __webpack_require__(19); -const UserProfile = __webpack_require__(152); -const ClientOAuth2Application = __webpack_require__(28); - -class RESTMethods { - constructor(restManager) { - this.rest = restManager; - this.client = restManager.client; - } - - login(token = this.client.token) { - return new Promise((resolve, reject) => { - if (typeof token !== 'string') throw new Error(Constants.Errors.INVALID_TOKEN); - token = token.replace(/^Bot\s*/i, ''); - this.client.manager.connectToWebSocket(token, resolve, reject); - }); - } - - logout() { - return this.rest.makeRequest('post', Constants.Endpoints.logout, true, {}); - } - - getGateway() { - return this.rest.makeRequest('get', Constants.Endpoints.gateway, true).then(res => { - this.client.ws.gateway = `${res.url}/?v=${Constants.PROTOCOL_VERSION}`; - return this.client.ws.gateway; - }); - } - - getBotGateway() { - return this.rest.makeRequest('get', Constants.Endpoints.botGateway, true); - } - - sendMessage(channel, content, { tts, nonce, embed, disableEveryone, split, code } = {}, file = null) { - return new Promise((resolve, reject) => { - if (typeof content !== 'undefined') content = this.client.resolver.resolveString(content); - - if (content) { - if (typeof code !== 'undefined' && (typeof code !== 'boolean' || code === true)) { - content = escapeMarkdown(this.client.resolver.resolveString(content), true); - content = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n${content}\n\`\`\``; - } - - if (disableEveryone || (typeof disableEveryone === 'undefined' && this.client.options.disableEveryone)) { - content = content.replace(/@(everyone|here)/g, '@\u200b$1'); - } - - if (split) content = splitMessage(content, typeof split === 'object' ? split : {}); - } - - const send = chan => { - if (content instanceof Array) { - const messages = []; - (function sendChunk(list, index) { - const options = index === list.length ? { tts, embed } : { tts }; - chan.send(list[index], options, index === list.length ? file : null).then((message) => { - messages.push(message); - if (index >= list.length) return resolve(messages); - return sendChunk(list, ++index); - }); - }(content, 0)); - } else { - this.rest.makeRequest('post', Constants.Endpoints.channelMessages(chan.id), true, { - content, tts, nonce, embed, - }, file).then(data => resolve(this.client.actions.MessageCreate.handle(data).message), reject); - } - }; - - if (channel instanceof User || channel instanceof GuildMember) { - this.createDM(channel).then(send, reject); - } else { - send(channel); - } - }); - } - - updateMessage(message, content, { embed, code } = {}) { - content = this.client.resolver.resolveString(content); - if (typeof code !== 'undefined' && (typeof code !== 'boolean' || code === true)) { - content = escapeMarkdown(this.client.resolver.resolveString(content), true); - content = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n${content}\n\`\`\``; - } - return this.rest.makeRequest('patch', Constants.Endpoints.channelMessage(message.channel.id, message.id), true, { - content, embed, - }).then(data => this.client.actions.MessageUpdate.handle(data).updated); - } - - deleteMessage(message) { - return this.rest.makeRequest('del', Constants.Endpoints.channelMessage(message.channel.id, message.id), true) - .then(() => - this.client.actions.MessageDelete.handle({ - id: message.id, - channel_id: message.channel.id, - }).message - ); - } - - bulkDeleteMessages(channel, messages) { - return this.rest.makeRequest('post', `${Constants.Endpoints.channelMessages(channel.id)}/bulk_delete`, true, { - messages, - }).then(() => - this.client.actions.MessageDeleteBulk.handle({ - channel_id: channel.id, - ids: messages, - }).messages - ); - } - - createChannel(guild, channelName, channelType, overwrites) { - if (overwrites instanceof Collection) overwrites = overwrites.array(); - return this.rest.makeRequest('post', Constants.Endpoints.guildChannels(guild.id), true, { - name: channelName, - type: channelType, - permission_overwrites: overwrites, - }).then(data => this.client.actions.ChannelCreate.handle(data).channel); - } - - createDM(recipient) { - const dmChannel = this.getExistingDM(recipient); - if (dmChannel) return Promise.resolve(dmChannel); - return this.rest.makeRequest('post', Constants.Endpoints.userChannels(this.client.user.id), true, { - recipient_id: recipient.id, - }).then(data => this.client.actions.ChannelCreate.handle(data).channel); - } - - getExistingDM(recipient) { - return this.client.channels.find(channel => - channel.recipient && channel.recipient.id === recipient.id - ); - } - - deleteChannel(channel) { - if (channel instanceof User || channel instanceof GuildMember) channel = this.getExistingDM(channel); - if (!channel) return Promise.reject(new Error('No channel to delete.')); - return this.rest.makeRequest('del', Constants.Endpoints.channel(channel.id), true).then(data => { - data.id = channel.id; - return this.client.actions.ChannelDelete.handle(data).channel; - }); - } - - updateChannel(channel, _data) { - const data = {}; - data.name = (_data.name || channel.name).trim(); - data.topic = _data.topic || channel.topic; - data.position = _data.position || channel.position; - data.bitrate = _data.bitrate || channel.bitrate; - data.user_limit = _data.userLimit || channel.userLimit; - return this.rest.makeRequest('patch', Constants.Endpoints.channel(channel.id), true, data).then(newData => - this.client.actions.ChannelUpdate.handle(newData).updated - ); - } - - leaveGuild(guild) { - if (guild.ownerID === this.client.user.id) return Promise.reject(new Error('Guild is owned by the client.')); - return this.rest.makeRequest('del', Constants.Endpoints.meGuild(guild.id), true).then(() => - this.client.actions.GuildDelete.handle({ id: guild.id }).guild - ); - } - - createGuild(options) { - options.icon = this.client.resolver.resolveBase64(options.icon) || null; - options.region = options.region || 'us-central'; - return new Promise((resolve, reject) => { - this.rest.makeRequest('post', Constants.Endpoints.guilds, true, options).then(data => { - if (this.client.guilds.has(data.id)) { - resolve(this.client.guilds.get(data.id)); - return; - } - - const handleGuild = guild => { - if (guild.id === data.id) { - this.client.removeListener('guildCreate', handleGuild); - this.client.clearTimeout(timeout); - resolve(guild); - } - }; - this.client.on('guildCreate', handleGuild); - - const timeout = this.client.setTimeout(() => { - this.client.removeListener('guildCreate', handleGuild); - reject(new Error('Took too long to receive guild data.')); - }, 10000); - }, reject); - }); - } - - // untested but probably will work - deleteGuild(guild) { - return this.rest.makeRequest('del', Constants.Endpoints.guild(guild.id), true).then(() => - this.client.actions.GuildDelete.handle({ id: guild.id }).guild - ); - } - - getUser(userID) { - return this.rest.makeRequest('get', Constants.Endpoints.user(userID), true).then(data => - this.client.actions.UserGet.handle(data).user - ); - } - - updateCurrentUser(_data, password) { - const user = this.client.user; - const data = {}; - data.username = _data.username || user.username; - data.avatar = this.client.resolver.resolveBase64(_data.avatar) || user.avatar; - if (!user.bot) { - data.email = _data.email || user.email; - data.password = password; - if (_data.new_password) data.new_password = _data.newPassword; - } - return this.rest.makeRequest('patch', Constants.Endpoints.me, true, data).then(newData => - this.client.actions.UserUpdate.handle(newData).updated - ); - } - - updateGuild(guild, _data) { - const data = {}; - if (_data.name) data.name = _data.name; - if (_data.region) data.region = _data.region; - if (_data.verificationLevel) data.verification_level = Number(_data.verificationLevel); - if (_data.afkChannel) data.afk_channel_id = this.client.resolver.resolveChannel(_data.afkChannel).id; - if (_data.afkTimeout) data.afk_timeout = Number(_data.afkTimeout); - if (_data.icon) data.icon = this.client.resolver.resolveBase64(_data.icon); - if (_data.owner) data.owner_id = this.client.resolver.resolveUser(_data.owner).id; - if (_data.splash) data.splash = this.client.resolver.resolveBase64(_data.splash); - return this.rest.makeRequest('patch', Constants.Endpoints.guild(guild.id), true, data).then(newData => - this.client.actions.GuildUpdate.handle(newData).updated - ); - } - - kickGuildMember(guild, member) { - return this.rest.makeRequest('del', Constants.Endpoints.guildMember(guild.id, member.id), true).then(() => - this.client.actions.GuildMemberRemove.handle({ - guild_id: guild.id, - user: member.user, - }).member - ); - } - - createGuildRole(guild) { - return this.rest.makeRequest('post', Constants.Endpoints.guildRoles(guild.id), true).then(role => - this.client.actions.GuildRoleCreate.handle({ - guild_id: guild.id, - role, - }).role - ); - } - - deleteGuildRole(role) { - return this.rest.makeRequest('del', Constants.Endpoints.guildRole(role.guild.id, role.id), true).then(() => - this.client.actions.GuildRoleDelete.handle({ - guild_id: role.guild.id, - role_id: role.id, - }).role - ); - } - - setChannelOverwrite(channel, payload) { - return this.rest.makeRequest( - 'put', `${Constants.Endpoints.channelPermissions(channel.id)}/${payload.id}`, true, payload - ); - } - - deletePermissionOverwrites(overwrite) { - return this.rest.makeRequest( - 'del', `${Constants.Endpoints.channelPermissions(overwrite.channel.id)}/${overwrite.id}`, true - ).then(() => overwrite); - } - - getChannelMessages(channel, payload = {}) { - const params = []; - if (payload.limit) params.push(`limit=${payload.limit}`); - if (payload.around) params.push(`around=${payload.around}`); - else if (payload.before) params.push(`before=${payload.before}`); - else if (payload.after) params.push(`after=${payload.after}`); - - let endpoint = Constants.Endpoints.channelMessages(channel.id); - if (params.length > 0) endpoint += `?${params.join('&')}`; - return this.rest.makeRequest('get', endpoint, true); - } - - getChannelMessage(channel, messageID) { - const msg = channel.messages.get(messageID); - if (msg) return Promise.resolve(msg); - return this.rest.makeRequest('get', Constants.Endpoints.channelMessage(channel.id, messageID), true); - } - - getGuildMember(guild, user) { - return this.rest.makeRequest('get', Constants.Endpoints.guildMember(guild.id, user.id), true).then(data => - this.client.actions.GuildMemberGet.handle(guild, data).member - ); - } - - updateGuildMember(member, data) { - if (data.channel) data.channel_id = this.client.resolver.resolveChannel(data.channel).id; - if (data.roles) data.roles = data.roles.map(role => role instanceof Role ? role.id : role); - - let endpoint = Constants.Endpoints.guildMember(member.guild.id, member.id); - // fix your endpoints, discord ;-; - if (member.id === this.client.user.id) { - const keys = Object.keys(data); - if (keys.length === 1 && keys[0] === 'nick') { - endpoint = Constants.Endpoints.guildMemberNickname(member.guild.id); - } - } - - return this.rest.makeRequest('patch', endpoint, true, data).then(newData => - member.guild._updateMember(member, newData).mem - ); - } - - addMemberRole(member, role) { - return this.rest.makeRequest('put', Constants.Endpoints.guildMemberRole(member.guild.id, member.id, role.id), true) - .then(() => { - if (!member._roles.includes(role.id)) member._roles.push(role.id); - return member; - }); - } - - removeMemberRole(member, role) { - return this.rest.makeRequest( - 'delete', - Constants.Endpoints.guildMemberRole(member.guild.id, member.id, role.id), - true - ).then(() => { - const index = member._roles.indexOf(role.id); - if (index >= 0) member._roles.splice(index, 1); - return member; - }); - } - - sendTyping(channelID) { - return this.rest.makeRequest('post', `${Constants.Endpoints.channel(channelID)}/typing`, true); - } - - banGuildMember(guild, member, deleteDays = 0) { - const id = this.client.resolver.resolveUserID(member); - if (!id) return Promise.reject(new Error('Couldn\'t resolve the user ID to ban.')); - return this.rest.makeRequest( - 'put', `${Constants.Endpoints.guildBans(guild.id)}/${id}?delete-message-days=${deleteDays}`, true, { - 'delete-message-days': deleteDays, - } - ).then(() => { - if (member instanceof GuildMember) return member; - const user = this.client.resolver.resolveUser(id); - if (user) { - member = this.client.resolver.resolveGuildMember(guild, user); - return member || user; - } - return id; - }); - } - - unbanGuildMember(guild, member) { - return new Promise((resolve, reject) => { - const id = this.client.resolver.resolveUserID(member); - if (!id) throw new Error('Couldn\'t resolve the user ID to unban.'); - - const listener = (eGuild, eUser) => { - if (eGuild.id === guild.id && eUser.id === id) { - this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener); - this.client.clearTimeout(timeout); - resolve(eUser); - } - }; - this.client.on(Constants.Events.GUILD_BAN_REMOVE, listener); - - const timeout = this.client.setTimeout(() => { - this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener); - reject(new Error('Took too long to receive the ban remove event.')); - }, 10000); - - this.rest.makeRequest('del', `${Constants.Endpoints.guildBans(guild.id)}/${id}`, true).catch(err => { - this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener); - this.client.clearTimeout(timeout); - reject(err); - }); - }); - } - - getGuildBans(guild) { - return this.rest.makeRequest('get', Constants.Endpoints.guildBans(guild.id), true).then(banItems => { - const bannedUsers = new Collection(); - for (const banItem of banItems) { - const user = this.client.dataManager.newUser(banItem.user); - bannedUsers.set(user.id, user); - } - return bannedUsers; - }); - } - - updateGuildRole(role, _data) { - const data = {}; - data.name = _data.name || role.name; - data.position = typeof _data.position !== 'undefined' ? _data.position : role.position; - data.color = _data.color || role.color; - if (typeof data.color === 'string' && data.color.startsWith('#')) { - data.color = parseInt(data.color.replace('#', ''), 16); - } - data.hoist = typeof _data.hoist !== 'undefined' ? _data.hoist : role.hoist; - data.mentionable = typeof _data.mentionable !== 'undefined' ? _data.mentionable : role.mentionable; - - if (_data.permissions) { - let perms = 0; - for (let perm of _data.permissions) { - if (typeof perm === 'string') perm = Constants.PermissionFlags[perm]; - perms |= perm; - } - data.permissions = perms; - } else { - data.permissions = role.permissions; - } - - return this.rest.makeRequest( - 'patch', Constants.Endpoints.guildRole(role.guild.id, role.id), true, data - ).then(_role => - this.client.actions.GuildRoleUpdate.handle({ - role: _role, - guild_id: role.guild.id, - }).updated - ); - } - - pinMessage(message) { - return this.rest.makeRequest('put', `${Constants.Endpoints.channel(message.channel.id)}/pins/${message.id}`, true) - .then(() => message); - } - - unpinMessage(message) { - return this.rest.makeRequest('del', `${Constants.Endpoints.channel(message.channel.id)}/pins/${message.id}`, true) - .then(() => message); - } - - getChannelPinnedMessages(channel) { - return this.rest.makeRequest('get', `${Constants.Endpoints.channel(channel.id)}/pins`, true); - } - - createChannelInvite(channel, options) { - const payload = {}; - payload.temporary = options.temporary; - payload.max_age = options.maxAge; - payload.max_uses = options.maxUses; - return this.rest.makeRequest('post', `${Constants.Endpoints.channelInvites(channel.id)}`, true, payload) - .then(invite => new Invite(this.client, invite)); - } - - deleteInvite(invite) { - return this.rest.makeRequest('del', Constants.Endpoints.invite(invite.code), true).then(() => invite); - } - - getInvite(code) { - return this.rest.makeRequest('get', Constants.Endpoints.invite(code), true).then(invite => - new Invite(this.client, invite) - ); - } - - getGuildInvites(guild) { - return this.rest.makeRequest('get', Constants.Endpoints.guildInvites(guild.id), true).then(inviteItems => { - const invites = new Collection(); - for (const inviteItem of inviteItems) { - const invite = new Invite(this.client, inviteItem); - invites.set(invite.code, invite); - } - return invites; - }); - } - - pruneGuildMembers(guild, days, dry) { - return this.rest.makeRequest(dry ? 'get' : 'post', `${Constants.Endpoints.guildPrune(guild.id)}?days=${days}`, true) - .then(data => data.pruned); - } - - createEmoji(guild, image, name) { - return this.rest.makeRequest('post', `${Constants.Endpoints.guildEmojis(guild.id)}`, true, { name, image }) - .then(data => this.client.actions.EmojiCreate.handle(data, guild).emoji); - } - - deleteEmoji(emoji) { - return this.rest.makeRequest('delete', `${Constants.Endpoints.guildEmojis(emoji.guild.id)}/${emoji.id}`, true) - .then(() => this.client.actions.EmojiDelete.handle(emoji).data); - } - - getWebhook(id, token) { - return this.rest.makeRequest('get', Constants.Endpoints.webhook(id, token), !token).then(data => - new Webhook(this.client, data) - ); - } - - getGuildWebhooks(guild) { - return this.rest.makeRequest('get', Constants.Endpoints.guildWebhooks(guild.id), true).then(data => { - const hooks = new Collection(); - for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook)); - return hooks; - }); - } - - getChannelWebhooks(channel) { - return this.rest.makeRequest('get', Constants.Endpoints.channelWebhooks(channel.id), true).then(data => { - const hooks = new Collection(); - for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook)); - return hooks; - }); - } - - createWebhook(channel, name, avatar) { - return this.rest.makeRequest('post', Constants.Endpoints.channelWebhooks(channel.id), true, { name, avatar }) - .then(data => new Webhook(this.client, data)); - } - - editWebhook(webhook, name, avatar) { - return this.rest.makeRequest('patch', Constants.Endpoints.webhook(webhook.id, webhook.token), false, { - name, - avatar, - }).then(data => { - webhook.name = data.name; - webhook.avatar = data.avatar; - return webhook; - }); - } - - deleteWebhook(webhook) { - return this.rest.makeRequest('delete', Constants.Endpoints.webhook(webhook.id, webhook.token), false); - } - - sendWebhookMessage(webhook, content, { avatarURL, tts, disableEveryone, embeds } = {}, file = null) { - if (typeof content !== 'undefined') content = this.client.resolver.resolveString(content); - if (content) { - if (disableEveryone || (typeof disableEveryone === 'undefined' && this.client.options.disableEveryone)) { - content = content.replace(/@(everyone|here)/g, '@\u200b$1'); - } - } - return this.rest.makeRequest('post', `${Constants.Endpoints.webhook(webhook.id, webhook.token)}?wait=true`, false, { - username: webhook.name, - avatar_url: avatarURL, - content, - tts, - file, - embeds, - }); - } - - sendSlackWebhookMessage(webhook, body) { - return this.rest.makeRequest( - 'post', `${Constants.Endpoints.webhook(webhook.id, webhook.token)}/slack?wait=true`, false, body - ); - } - - fetchUserProfile(user) { - return this.rest.makeRequest('get', Constants.Endpoints.userProfile(user.id), true).then(data => - new UserProfile(user, data) - ); - } - - fetchMeMentions(options) { - if (options.guild) options.guild = options.guild.id ? options.guild.id : options.guild; - return this.rest.makeRequest( - 'get', - Constants.Endpoints.meMentions(options.limit, options.roles, options.everyone, options.guild) - ).then(res => res.body.map(m => new Message(this.client.channels.get(m.channel_id), m, this.client))); - } - - addFriend(user) { - return this.rest.makeRequest('post', Constants.Endpoints.relationships('@me'), true, { - username: user.username, - discriminator: user.discriminator, - }).then(() => user); - } - - removeFriend(user) { - return this.rest.makeRequest('delete', `${Constants.Endpoints.relationships('@me')}/${user.id}`, true) - .then(() => user); - } - - blockUser(user) { - return this.rest.makeRequest('put', `${Constants.Endpoints.relationships('@me')}/${user.id}`, true, { type: 2 }) - .then(() => user); - } - - unblockUser(user) { - return this.rest.makeRequest('delete', `${Constants.Endpoints.relationships('@me')}/${user.id}`, true) - .then(() => user); - } - - setRolePositions(guildID, roles) { - return this.rest.makeRequest('patch', Constants.Endpoints.guildRoles(guildID), true, roles).then(() => - this.client.actions.GuildRolesPositionUpdate.handle({ - guild_id: guildID, - roles, - }).guild - ); - } - - addMessageReaction(message, emoji) { - return this.rest.makeRequest( - 'put', Constants.Endpoints.selfMessageReaction(message.channel.id, message.id, emoji), true - ).then(() => - this.client.actions.MessageReactionAdd.handle({ - user_id: this.client.user.id, - message_id: message.id, - emoji: parseEmoji(emoji), - channel_id: message.channel.id, - }).reaction - ); - } - - removeMessageReaction(message, emoji, user) { - let endpoint = Constants.Endpoints.selfMessageReaction(message.channel.id, message.id, emoji); - if (user.id !== this.client.user.id) { - endpoint = Constants.Endpoints.userMessageReaction(message.channel.id, message.id, emoji, null, user.id); - } - return this.rest.makeRequest('delete', endpoint, true).then(() => - this.client.actions.MessageReactionRemove.handle({ - user_id: user.id, - message_id: message.id, - emoji: parseEmoji(emoji), - channel_id: message.channel.id, - }).reaction - ); - } - - removeMessageReactions(message) { - return this.rest.makeRequest('delete', Constants.Endpoints.messageReactions(message.channel.id, message.id), true) - .then(() => message); - } - - getMessageReactionUsers(message, emoji, limit = 100) { - return this.rest.makeRequest( - 'get', Constants.Endpoints.messageReaction(message.channel.id, message.id, emoji, limit), true - ); - } - - getMyApplication() { - return this.rest.makeRequest('get', Constants.Endpoints.myApplication, true).then(app => - new ClientOAuth2Application(this.client, app) - ); - } - - setNote(user, note) { - return this.rest.makeRequest('put', Constants.Endpoints.note(user.id), true, { note }).then(() => user); - } -} - -module.exports = RESTMethods; - - -/***/ }, -/* 112 */ -/***/ function(module, exports, __webpack_require__) { - -const RequestHandler = __webpack_require__(52); - -class BurstRequestHandler extends RequestHandler { - constructor(restManager, endpoint) { - super(restManager, endpoint); - this.requestRemaining = 1; - this.first = true; - } - - push(request) { - super.push(request); - this.handle(); - } - - handleNext(time) { - if (this.waiting) return; - this.waiting = true; - this.restManager.client.setTimeout(() => { - this.requestRemaining = this.requestLimit; - this.waiting = false; - this.handle(); - }, time); - } - - execute(item) { - item.request.gen().end((err, res) => { - if (res && res.headers) { - this.requestLimit = res.headers['x-ratelimit-limit']; - this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000; - this.requestRemaining = Number(res.headers['x-ratelimit-remaining']); - this.timeDifference = Date.now() - new Date(res.headers.date).getTime(); - this.handleNext( - this.requestResetTime - Date.now() + this.timeDifference + this.restManager.client.options.restTimeOffset - ); - } - if (err) { - if (err.status === 429) { - this.requestRemaining = 0; - this.queue.unshift(item); - this.restManager.client.setTimeout(() => { - this.globalLimit = false; - this.handle(); - }, Number(res.headers['retry-after']) + this.restManager.client.options.restTimeOffset); - if (res.headers['x-ratelimit-global']) this.globalLimit = true; - } else { - item.reject(err); - } - } else { - this.globalLimit = false; - const data = res && res.body ? res.body : {}; - item.resolve(data); - if (this.first) { - this.first = false; - this.handle(); - } - } - }); - } - - handle() { - super.handle(); - if (this.requestRemaining < 1 || this.queue.length === 0 || this.globalLimit) return; - while (this.queue.length > 0 && this.requestRemaining > 0) { - this.execute(this.queue.shift()); - this.requestRemaining--; - } - } -} - -module.exports = BurstRequestHandler; - - -/***/ }, -/* 113 */ -/***/ function(module, exports, __webpack_require__) { - -const RequestHandler = __webpack_require__(52); - -/** - * Handles API Requests sequentially, i.e. we wait until the current request is finished before moving onto - * the next. This plays a _lot_ nicer in terms of avoiding 429's when there is more than one session of the account, - * but it can be slower. - * @extends {RequestHandler} - * @private - */ -class SequentialRequestHandler extends RequestHandler { - /** - * @param {RESTManager} restManager The REST manager to use - * @param {string} endpoint The endpoint to handle - */ - constructor(restManager, endpoint) { - super(restManager, endpoint); - - /** - * Whether this rate limiter is waiting for a response from a request - * @type {boolean} - */ - this.waiting = false; - - /** - * The endpoint that this handler is handling - * @type {string} - */ - this.endpoint = endpoint; - - /** - * The time difference between Discord's Dates and the local computer's Dates. A positive number means the local - * computer's time is ahead of Discord's. - * @type {number} - */ - this.timeDifference = 0; - } - - push(request) { - super.push(request); - this.handle(); - } - - /** - * Performs a request then resolves a promise to indicate its readiness for a new request - * @param {APIRequest} item The item to execute - * @returns {Promise} - */ - execute(item) { - return new Promise(resolve => { - item.request.gen().end((err, res) => { - if (res && res.headers) { - this.requestLimit = res.headers['x-ratelimit-limit']; - this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000; - this.requestRemaining = Number(res.headers['x-ratelimit-remaining']); - this.timeDifference = Date.now() - new Date(res.headers.date).getTime(); - } - if (err) { - if (err.status === 429) { - this.restManager.client.setTimeout(() => { - this.waiting = false; - this.globalLimit = false; - resolve(); - }, Number(res.headers['retry-after']) + this.restManager.client.options.restTimeOffset); - if (res.headers['x-ratelimit-global']) this.globalLimit = true; - } else { - this.queue.shift(); - this.waiting = false; - item.reject(err); - resolve(err); - } - } else { - this.queue.shift(); - this.globalLimit = false; - const data = res && res.body ? res.body : {}; - item.resolve(data); - if (this.requestRemaining === 0) { - this.restManager.client.setTimeout( - () => { - this.waiting = false; - resolve(data); - }, - this.requestResetTime - Date.now() + this.timeDifference + this.restManager.client.options.restTimeOffset - ); - } else { - this.waiting = false; - resolve(data); - } - } - }); - }); - } - - handle() { - super.handle(); - - if (this.waiting || this.queue.length === 0 || this.globalLimit) return; - this.waiting = true; - - const item = this.queue[0]; - this.execute(item).then(() => this.handle()); - } -} - -module.exports = SequentialRequestHandler; - - -/***/ }, -/* 114 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -class UserAgentManager { - constructor(restManager) { - this.restManager = restManager; - this._userAgent = { - url: 'https://github.com/hydrabolt/discord.js', - version: Constants.Package.version, - }; - } - - set(info) { - this._userAgent.url = info.url || 'https://github.com/hydrabolt/discord.js'; - this._userAgent.version = info.version || Constants.Package.version; - } - - get userAgent() { - return `DiscordBot (${this._userAgent.url}, ${this._userAgent.version})`; - } -} - -module.exports = UserAgentManager; - - -/***/ }, -/* 115 */ -/***/ function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const browser = typeof window !== 'undefined'; -const EventEmitter = __webpack_require__(21).EventEmitter; -const Constants = __webpack_require__(0); -const convertArrayBuffer = __webpack_require__(53); -const pako = __webpack_require__(67); -const zlib = __webpack_require__(49); -const PacketManager = __webpack_require__(116); - -let WebSocket, erlpack; -let serialize = JSON.stringify; -if (browser) { - WebSocket = window.WebSocket; // eslint-disable-line no-undef -} else { - try { - WebSocket = __webpack_require__(158); - } catch (err) { - WebSocket = __webpack_require__(159); - } - - try { - erlpack = __webpack_require__(157); - serialize = erlpack.pack; - } catch (err) { - erlpack = null; - } -} - -/** - * The WebSocket Manager of the Client - * @private - */ -class WebSocketManager extends EventEmitter { - constructor(client) { - super(); - /** - * The Client that instantiated this WebSocketManager - * @type {Client} - */ - this.client = client; - - /** - * A WebSocket Packet manager, it handles all the messages - * @type {PacketManager} - */ - this.packetManager = new PacketManager(this); - - /** - * The status of the WebSocketManager, a type of Constants.Status. It defaults to IDLE. - * @type {number} - */ - this.status = Constants.Status.IDLE; - - /** - * The session ID of the connection, null if not yet available. - * @type {?string} - */ - this.sessionID = null; - - /** - * The packet count of the client, null if not yet available. - * @type {?number} - */ - this.sequence = -1; - - /** - * The gateway address for this WebSocket connection, null if not yet available. - * @type {?string} - */ - this.gateway = null; - - /** - * Whether READY was emitted normally (all packets received) or not - * @type {boolean} - */ - this.normalReady = false; - - /** - * The WebSocket connection to the gateway - * @type {?WebSocket} - */ - this.ws = null; - - /** - * An object with keys that are websocket event names that should be ignored - * @type {Object} - */ - this.disabledEvents = {}; - for (const event of client.options.disabledEvents) this.disabledEvents[event] = true; - - this.first = true; - - this.lastHeartbeatAck = true; - } - - /** - * Connects the client to a given gateway - * @param {string} gateway The gateway to connect to - */ - _connect(gateway) { - this.client.emit('debug', `Connecting to gateway ${gateway}`); - this.normalReady = false; - if (this.status !== Constants.Status.RECONNECTING) this.status = Constants.Status.CONNECTING; - this.ws = new WebSocket(gateway); - if (browser) this.ws.binaryType = 'arraybuffer'; - this.ws.onopen = this.eventOpen.bind(this); - this.ws.onmessage = this.eventMessage.bind(this); - this.ws.onclose = this.eventClose.bind(this); - this.ws.onerror = this.eventError.bind(this); - this._queue = []; - this._remaining = 120; - this.client.setInterval(() => { - this._remaining = 120; - this._remainingReset = Date.now(); - }, 60e3); - } - - connect(gateway) { - gateway = `${gateway}&encoding=${erlpack ? 'etf' : 'json'}`; - if (this.first) { - this._connect(gateway); - this.first = false; - } else { - this.client.setTimeout(() => this._connect(gateway), 5500); - } - } - - heartbeat(normal) { - if (normal && !this.lastHeartbeatAck) { - this.ws.close(1007); - return; - } - - this.client.emit('debug', 'Sending heartbeat'); - this.client._pingTimestamp = Date.now(); - this.client.ws.send({ - op: Constants.OPCodes.HEARTBEAT, - d: this.sequence, - }, true); - - this.lastHeartbeatAck = false; - } - - /** - * Sends a packet to the gateway - * @param {Object} data An object that can be JSON stringified - * @param {boolean} force Whether or not to send the packet immediately - */ - send(data, force = false) { - if (force) { - this._send(serialize(data)); - return; - } - this._queue.push(serialize(data)); - this.doQueue(); - } - - destroy() { - this.ws.close(1000); - this._queue = []; - this.status = Constants.Status.IDLE; - } - - _send(data) { - if (this.ws.readyState === WebSocket.OPEN) { - this.emit('send', data); - this.ws.send(data); - } - } - - doQueue() { - const item = this._queue[0]; - if (!(this.ws.readyState === WebSocket.OPEN && item)) return; - if (this.remaining === 0) { - this.client.setTimeout(this.doQueue.bind(this), Date.now() - this.remainingReset); - return; - } - this._remaining--; - this._send(item); - this._queue.shift(); - this.doQueue(); - } - - /** - * Run whenever the gateway connections opens up - */ - eventOpen() { - this.client.emit('debug', 'Connection to gateway opened'); - this.lastHeartbeatAck = true; - if (this.status === Constants.Status.RECONNECTING) this._sendResume(); - else this._sendNewIdentify(); - } - - /** - * Sends a gateway resume packet, in cases of unexpected disconnections. - */ - _sendResume() { - if (!this.sessionID) { - this._sendNewIdentify(); - return; - } - this.client.emit('debug', 'Identifying as resumed session'); - const payload = { - token: this.client.token, - session_id: this.sessionID, - seq: this.sequence, - }; - - this.send({ - op: Constants.OPCodes.RESUME, - d: payload, - }); - } - - /** - * Sends a new identification packet, in cases of new connections or failed reconnections. - */ - _sendNewIdentify() { - this.reconnecting = false; - const payload = this.client.options.ws; - payload.token = this.client.token; - if (this.client.options.shardCount > 0) { - payload.shard = [Number(this.client.options.shardId), Number(this.client.options.shardCount)]; - } - this.client.emit('debug', 'Identifying as new session'); - this.send({ - op: Constants.OPCodes.IDENTIFY, - d: payload, - }); - this.sequence = -1; - } - - /** - * @external CloseEvent - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent} - */ - - /** - * Run whenever the connection to the gateway is closed, it will try to reconnect the client. - * @param {CloseEvent} event The WebSocket close event - */ - eventClose(event) { - this.emit('close', event); - this.client.clearInterval(this.client.manager.heartbeatInterval); - this.status = Constants.Status.DISCONNECTED; - this._queue = []; - /** - * Emitted whenever the client websocket is disconnected - * @event Client#disconnect - * @param {CloseEvent} event The WebSocket close event - */ - if (!this.reconnecting) this.client.emit(Constants.Events.DISCONNECT, event); - if (event.code === 4004) return; - if (event.code === 4010) return; - if (!this.reconnecting && event.code !== 1000) this.tryReconnect(); - } - - /** - * Run whenever a message is received from the WebSocket. Returns `true` if the message - * was handled properly. - * @param {Object} event The received websocket data - * @returns {boolean} - */ - eventMessage(event) { - const data = this.tryParseEventData(event.data); - if (data === null) { - this.eventError(new Error(Constants.Errors.BAD_WS_MESSAGE)); - return false; - } - - this.client.emit('raw', data); - - if (data.op === Constants.OPCodes.HELLO) this.client.manager.setupKeepAlive(data.d.heartbeat_interval); - return this.packetManager.handle(data); - } - - /** - * Parses the raw data from a websocket event, inflating it if necessary - * @param {*} data Event data - * @returns {Object} - */ - parseEventData(data) { - if (erlpack) { - if (data instanceof ArrayBuffer) data = convertArrayBuffer(data); - return erlpack.unpack(data); - } else { - if (data instanceof ArrayBuffer) data = pako.inflate(data, { to: 'string' }); - else if (data instanceof Buffer) data = zlib.inflateSync(data).toString(); - return JSON.parse(data); - } - } - - /** - * Tries to call `parseEventData()` and return its result, or returns `null` upon thrown errors. - * @param {*} data Event data - * @returns {?Object} - */ - tryParseEventData(data) { - try { - return this.parseEventData(data); - } catch (err) { - return null; - } - } - - /** - * Run whenever an error occurs with the WebSocket connection. Tries to reconnect - * @param {Error} err The encountered error - */ - eventError(err) { - /** - * Emitted whenever the Client encounters a serious connection error - * @event Client#error - * @param {Error} error The encountered error - */ - if (this.client.listenerCount('error') > 0) this.client.emit('error', err); - this.tryReconnect(); - } - - _emitReady(normal = true) { - /** - * Emitted when the Client becomes ready to start working - * @event Client#ready - */ - this.status = Constants.Status.READY; - this.client.emit(Constants.Events.READY); - this.packetManager.handleQueue(); - this.normalReady = normal; - } - - /** - * Runs on new packets before `READY` to see if the Client is ready yet, if it is prepares - * the `READY` event. - */ - checkIfReady() { - if (this.status !== Constants.Status.READY && this.status !== Constants.Status.NEARLY) { - let unavailableCount = 0; - for (const guildID of this.client.guilds.keys()) { - unavailableCount += this.client.guilds.get(guildID).available ? 0 : 1; - } - if (unavailableCount === 0) { - this.status = Constants.Status.NEARLY; - if (this.client.options.fetchAllMembers) { - const promises = this.client.guilds.map(g => g.fetchMembers()); - Promise.all(promises).then(() => this._emitReady(), e => { - this.client.emit(Constants.Events.WARN, 'Error in pre-ready guild member fetching'); - this.client.emit(Constants.Events.ERROR, e); - this._emitReady(); - }); - return; - } - this._emitReady(); - } - } - } - - /** - * Tries to reconnect the client, changing the status to Constants.Status.RECONNECTING. - */ - tryReconnect() { - if (this.status === Constants.Status.RECONNECTING || this.status === Constants.Status.CONNECTING) return; - this.status = Constants.Status.RECONNECTING; - this.ws.close(); - this.packetManager.handleQueue(); - /** - * Emitted when the Client tries to reconnect after being disconnected - * @event Client#reconnecting - */ - this.client.emit(Constants.Events.RECONNECTING); - this.connect(this.client.ws.gateway); - } -} - -module.exports = WebSocketManager; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20).Buffer)) - -/***/ }, -/* 116 */ -/***/ function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -const BeforeReadyWhitelist = [ - Constants.WSEvents.READY, - Constants.WSEvents.GUILD_CREATE, - Constants.WSEvents.GUILD_DELETE, - Constants.WSEvents.GUILD_MEMBERS_CHUNK, - Constants.WSEvents.GUILD_MEMBER_ADD, - Constants.WSEvents.GUILD_MEMBER_REMOVE, -]; - -class WebSocketPacketManager { - constructor(websocketManager) { - this.ws = websocketManager; - this.handlers = {}; - this.queue = []; - - this.register(Constants.WSEvents.READY, __webpack_require__(143)); - this.register(Constants.WSEvents.GUILD_CREATE, __webpack_require__(123)); - this.register(Constants.WSEvents.GUILD_DELETE, __webpack_require__(124)); - this.register(Constants.WSEvents.GUILD_UPDATE, __webpack_require__(134)); - this.register(Constants.WSEvents.GUILD_BAN_ADD, __webpack_require__(121)); - this.register(Constants.WSEvents.GUILD_BAN_REMOVE, __webpack_require__(122)); - this.register(Constants.WSEvents.GUILD_MEMBER_ADD, __webpack_require__(126)); - this.register(Constants.WSEvents.GUILD_MEMBER_REMOVE, __webpack_require__(127)); - this.register(Constants.WSEvents.GUILD_MEMBER_UPDATE, __webpack_require__(128)); - this.register(Constants.WSEvents.GUILD_ROLE_CREATE, __webpack_require__(130)); - this.register(Constants.WSEvents.GUILD_ROLE_DELETE, __webpack_require__(131)); - this.register(Constants.WSEvents.GUILD_ROLE_UPDATE, __webpack_require__(132)); - this.register(Constants.WSEvents.GUILD_EMOJIS_UPDATE, __webpack_require__(125)); - this.register(Constants.WSEvents.GUILD_MEMBERS_CHUNK, __webpack_require__(129)); - this.register(Constants.WSEvents.CHANNEL_CREATE, __webpack_require__(117)); - this.register(Constants.WSEvents.CHANNEL_DELETE, __webpack_require__(118)); - this.register(Constants.WSEvents.CHANNEL_UPDATE, __webpack_require__(120)); - this.register(Constants.WSEvents.CHANNEL_PINS_UPDATE, __webpack_require__(119)); - this.register(Constants.WSEvents.PRESENCE_UPDATE, __webpack_require__(142)); - this.register(Constants.WSEvents.USER_UPDATE, __webpack_require__(148)); - this.register(Constants.WSEvents.USER_NOTE_UPDATE, __webpack_require__(147)); - this.register(Constants.WSEvents.VOICE_STATE_UPDATE, __webpack_require__(150)); - this.register(Constants.WSEvents.TYPING_START, __webpack_require__(146)); - this.register(Constants.WSEvents.MESSAGE_CREATE, __webpack_require__(135)); - this.register(Constants.WSEvents.MESSAGE_DELETE, __webpack_require__(136)); - this.register(Constants.WSEvents.MESSAGE_UPDATE, __webpack_require__(141)); - this.register(Constants.WSEvents.MESSAGE_DELETE_BULK, __webpack_require__(137)); - this.register(Constants.WSEvents.VOICE_SERVER_UPDATE, __webpack_require__(149)); - this.register(Constants.WSEvents.GUILD_SYNC, __webpack_require__(133)); - this.register(Constants.WSEvents.RELATIONSHIP_ADD, __webpack_require__(144)); - this.register(Constants.WSEvents.RELATIONSHIP_REMOVE, __webpack_require__(145)); - this.register(Constants.WSEvents.MESSAGE_REACTION_ADD, __webpack_require__(138)); - this.register(Constants.WSEvents.MESSAGE_REACTION_REMOVE, __webpack_require__(139)); - this.register(Constants.WSEvents.MESSAGE_REACTION_REMOVE_ALL, __webpack_require__(140)); - } - - get client() { - return this.ws.client; - } - - register(event, Handler) { - this.handlers[event] = new Handler(this); - } - - handleQueue() { - this.queue.forEach((element, index) => { - this.handle(this.queue[index]); - this.queue.splice(index, 1); - }); - } - - setSequence(s) { - if (s && s > this.ws.sequence) this.ws.sequence = s; - } - - handle(packet) { - if (packet.op === Constants.OPCodes.RECONNECT) { - this.setSequence(packet.s); - this.ws.tryReconnect(); - return false; - } - - if (packet.op === Constants.OPCodes.INVALID_SESSION) { - if (packet.d) { - setTimeout(() => { - this.ws._sendResume(); - }, 2500); - } else { - this.ws.sessionID = null; - this.ws._sendNewIdentify(); - } - return false; - } - - if (packet.op === Constants.OPCodes.HEARTBEAT_ACK) { - this.ws.client._pong(this.ws.client._pingTimestamp); - this.ws.lastHeartbeatAck = true; - this.ws.client.emit('debug', 'Heartbeat acknowledged'); - } else if (packet.op === Constants.OPCodes.HEARTBEAT) { - this.client.ws.send({ - op: Constants.OPCodes.HEARTBEAT, - d: this.client.ws.sequence, - }); - this.ws.client.emit('debug', 'Received gateway heartbeat'); - } - - if (this.ws.status === Constants.Status.RECONNECTING) { - this.ws.reconnecting = false; - this.ws.checkIfReady(); - } - - this.setSequence(packet.s); - - if (this.ws.disabledEvents[packet.t] !== undefined) return false; - - if (this.ws.status !== Constants.Status.READY) { - if (BeforeReadyWhitelist.indexOf(packet.t) === -1) { - this.queue.push(packet); - return false; - } - } - - if (this.handlers[packet.t]) return this.handlers[packet.t].handle(packet); - return false; - } -} - -module.exports = WebSocketPacketManager; - - -/***/ }, -/* 117 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class ChannelCreateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.ChannelCreate.handle(data); - } -} - -/** - * Emitted whenever a channel is created. - * @event Client#channelCreate - * @param {Channel} channel The channel that was created - */ - -module.exports = ChannelCreateHandler; - - -/***/ }, -/* 118 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -const Constants = __webpack_require__(0); - -class ChannelDeleteHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const response = client.actions.ChannelDelete.handle(data); - if (response.channel) client.emit(Constants.Events.CHANNEL_DELETE, response.channel); - } -} - -/** - * Emitted whenever a channel is deleted. - * @event Client#channelDelete - * @param {Channel} channel The channel that was deleted - */ - -module.exports = ChannelDeleteHandler; - - -/***/ }, -/* 119 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -/* -{ t: 'CHANNEL_PINS_UPDATE', - s: 666, - op: 0, - d: - { last_pin_timestamp: '2016-08-28T17:37:13.171774+00:00', - channel_id: '314866471639044027' } } -*/ - -class ChannelPinsUpdate extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const channel = client.channels.get(data.channel_id); - const time = new Date(data.last_pin_timestamp); - if (channel && time) client.emit(Constants.Events.CHANNEL_PINS_UPDATE, channel, time); - } -} - -/** - * Emitted whenever the pins of a channel are updated. Due to the nature of the WebSocket event, not much information - * can be provided easily here - you need to manually check the pins yourself. - * @event Client#channelPinsUpdate - * @param {Channel} channel The channel that the pins update occured in - * @param {Date} time The time of the pins update - */ - -module.exports = ChannelPinsUpdate; - - -/***/ }, -/* 120 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class ChannelUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.ChannelUpdate.handle(data); - } -} - -module.exports = ChannelUpdateHandler; - - -/***/ }, -/* 121 */ -/***/ function(module, exports, __webpack_require__) { - -// ##untested handler## - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -class GuildBanAddHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const guild = client.guilds.get(data.guild_id); - const user = client.users.get(data.user.id); - if (guild && user) client.emit(Constants.Events.GUILD_BAN_ADD, guild, user); - } -} - -/** - * Emitted whenever a member is banned from a guild. - * @event Client#guildBanAdd - * @param {Guild} guild The guild that the ban occurred in - * @param {User} user The user that was banned - */ - -module.exports = GuildBanAddHandler; - - -/***/ }, -/* 122 */ -/***/ function(module, exports, __webpack_require__) { - -// ##untested handler## - -const AbstractHandler = __webpack_require__(1); - -class GuildBanRemoveHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildBanRemove.handle(data); - } -} - -/** - * Emitted whenever a member is unbanned from a guild. - * @event Client#guildBanRemove - * @param {Guild} guild The guild that the unban occurred in - * @param {User} user The user that was unbanned - */ - -module.exports = GuildBanRemoveHandler; - - -/***/ }, -/* 123 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class GuildCreateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - - const guild = client.guilds.get(data.id); - if (guild) { - if (!guild.available && !data.unavailable) { - // a newly available guild - guild.setup(data); - this.packetManager.ws.checkIfReady(); - } - } else { - // a new guild - client.dataManager.newGuild(data); - } - } -} - -module.exports = GuildCreateHandler; - - -/***/ }, -/* 124 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -class GuildDeleteHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const response = client.actions.GuildDelete.handle(data); - if (response.guild) client.emit(Constants.Events.GUILD_DELETE, response.guild); - } -} - -/** - * Emitted whenever a guild is deleted/left. - * @event Client#guildDelete - * @param {Guild} guild The guild that was deleted - */ - -module.exports = GuildDeleteHandler; - - -/***/ }, -/* 125 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -function mappify(iterable) { - const map = new Map(); - for (const x of iterable) map.set(...x); - return map; -} - -class GuildEmojisUpdate extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const guild = client.guilds.get(data.guild_id); - if (!guild || !guild.emojis) return; - - const deletions = mappify(guild.emojis.entries()); - - for (const emoji of data.emojis) { - // determine type of emoji event - const cachedEmoji = guild.emojis.get(emoji.id); - if (cachedEmoji) { - deletions.delete(emoji.id); - if (!cachedEmoji.equals(emoji, true)) { - // emoji updated - client.actions.GuildEmojiUpdate.handle(cachedEmoji, emoji); - } - } else { - // emoji added - client.actions.GuildEmojiCreate.handle(guild, emoji); - } - } - - for (const emoji of deletions.values()) { - // emoji deleted - client.actions.GuildEmojiDelete.handle(emoji); - } - } -} - -module.exports = GuildEmojisUpdate; - - -/***/ }, -/* 126 */ -/***/ function(module, exports, __webpack_require__) { - -// ##untested handler## - -const AbstractHandler = __webpack_require__(1); - -class GuildMemberAddHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const guild = client.guilds.get(data.guild_id); - if (guild) { - guild.memberCount++; - guild._addMember(data); - } - } -} - -module.exports = GuildMemberAddHandler; - - -/***/ }, -/* 127 */ -/***/ function(module, exports, __webpack_require__) { - -// ##untested handler## - -const AbstractHandler = __webpack_require__(1); - -class GuildMemberRemoveHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildMemberRemove.handle(data); - } -} - -module.exports = GuildMemberRemoveHandler; - - -/***/ }, -/* 128 */ -/***/ function(module, exports, __webpack_require__) { - -// ##untested handler## - -const AbstractHandler = __webpack_require__(1); - -class GuildMemberUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - const member = guild.members.get(data.user.id); - if (member) guild._updateMember(member, data); - } - } -} - -module.exports = GuildMemberUpdateHandler; - - -/***/ }, -/* 129 */ -/***/ function(module, exports, __webpack_require__) { - -// ##untested## - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -class GuildMembersChunkHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const guild = client.guilds.get(data.guild_id); - if (!guild) return; - - const members = data.members.map(member => guild._addMember(member, false)); - - guild._checkChunks(); - client.emit(Constants.Events.GUILD_MEMBERS_CHUNK, members); - - client.ws.lastHeartbeatAck = true; - } -} - -/** - * Emitted whenever a chunk of guild members is received (all members come from the same guild) - * @event Client#guildMembersChunk - * @param {GuildMember[]} members The members in the chunk - */ - -module.exports = GuildMembersChunkHandler; - - -/***/ }, -/* 130 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class GuildRoleCreateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildRoleCreate.handle(data); - } -} - -module.exports = GuildRoleCreateHandler; - - -/***/ }, -/* 131 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class GuildRoleDeleteHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildRoleDelete.handle(data); - } -} - -module.exports = GuildRoleDeleteHandler; - - -/***/ }, -/* 132 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class GuildRoleUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildRoleUpdate.handle(data); - } -} - -module.exports = GuildRoleUpdateHandler; - - -/***/ }, -/* 133 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class GuildSyncHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildSync.handle(data); - } -} - -module.exports = GuildSyncHandler; - - -/***/ }, -/* 134 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class GuildUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.GuildUpdate.handle(data); - } -} - -module.exports = GuildUpdateHandler; - - -/***/ }, -/* 135 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -class MessageCreateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const response = client.actions.MessageCreate.handle(data); - if (response.message) client.emit(Constants.Events.MESSAGE_CREATE, response.message); - } -} - -/** - * Emitted whenever a message is created - * @event Client#message - * @param {Message} message The created message - */ - -module.exports = MessageCreateHandler; - - -/***/ }, -/* 136 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -class MessageDeleteHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const response = client.actions.MessageDelete.handle(data); - if (response.message) client.emit(Constants.Events.MESSAGE_DELETE, response.message); - } -} - -/** - * Emitted whenever a message is deleted - * @event Client#messageDelete - * @param {Message} message The deleted message - */ - -module.exports = MessageDeleteHandler; - - -/***/ }, -/* 137 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class MessageDeleteBulkHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.MessageDeleteBulk.handle(data); - } -} - -/** - * Emitted whenever messages are deleted in bulk - * @event Client#messageDeleteBulk - * @param {Collection} messages The deleted messages, mapped by their ID - */ - -module.exports = MessageDeleteBulkHandler; - - -/***/ }, -/* 138 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class MessageReactionAddHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.MessageReactionAdd.handle(data); - } -} - -module.exports = MessageReactionAddHandler; - - -/***/ }, -/* 139 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class MessageReactionRemove extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.MessageReactionRemove.handle(data); - } -} - -module.exports = MessageReactionRemove; - - -/***/ }, -/* 140 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class MessageReactionRemoveAll extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.MessageReactionRemoveAll.handle(data); - } -} - -module.exports = MessageReactionRemoveAll; - - -/***/ }, -/* 141 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class MessageUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.MessageUpdate.handle(data); - } -} - -module.exports = MessageUpdateHandler; - - -/***/ }, -/* 142 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class PresenceUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - let user = client.users.get(data.user.id); - const guild = client.guilds.get(data.guild_id); - - // step 1 - if (!user) { - if (data.user.username) { - user = client.dataManager.newUser(data.user); - } else { - return; - } - } - - const oldUser = cloneObject(user); - user.patch(data.user); - if (!user.equals(oldUser)) { - client.emit(Constants.Events.USER_UPDATE, oldUser, user); - } - - if (guild) { - let member = guild.members.get(user.id); - if (!member && data.status !== 'offline') { - member = guild._addMember({ - user, - roles: data.roles, - deaf: false, - mute: false, - }, false); - client.emit(Constants.Events.GUILD_MEMBER_AVAILABLE, member); - } - if (member) { - const oldMember = cloneObject(member); - if (member.presence) { - oldMember.frozenPresence = cloneObject(member.presence); - } - guild._setPresence(user.id, data); - client.emit(Constants.Events.PRESENCE_UPDATE, oldMember, member); - } else { - guild._setPresence(user.id, data); - } - } - } -} - -/** - * Emitted whenever a guild member's presence changes, or they change one of their details. - * @event Client#presenceUpdate - * @param {GuildMember} oldMember The member before the presence update - * @param {GuildMember} newMember The member after the presence update - */ - -/** - * Emitted whenever a user's details (e.g. username) are changed. - * @event Client#userUpdate - * @param {User} oldUser The user before the update - * @param {User} newUser The user after the update - */ - -/** - * Emitted whenever a member becomes available in a large guild - * @event Client#guildMemberAvailable - * @param {GuildMember} member The member that became available - */ - -module.exports = PresenceUpdateHandler; - - -/***/ }, -/* 143 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -const ClientUser = __webpack_require__(29); - -class ReadyHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - - client.ws.heartbeat(); - - const clientUser = new ClientUser(client, data.user); - client.user = clientUser; - client.readyAt = new Date(); - client.users.set(clientUser.id, clientUser); - - for (const guild of data.guilds) client.dataManager.newGuild(guild); - for (const privateDM of data.private_channels) client.dataManager.newChannel(privateDM); - - for (const relation of data.relationships) { - const user = client.dataManager.newUser(relation.user); - if (relation.type === 1) { - client.user.friends.set(user.id, user); - } else if (relation.type === 2) { - client.user.blocked.set(user.id, user); - } - } - - data.presences = data.presences || []; - for (const presence of data.presences) { - client.dataManager.newUser(presence.user); - client._setPresence(presence.user.id, presence); - } - - if (data.notes) { - for (const user in data.notes) { - let note = data.notes[user]; - if (!note.length) note = null; - - client.user.notes.set(user, note); - } - } - - if (!client.user.bot && client.options.sync) client.setInterval(client.syncGuilds.bind(client), 30000); - client.once('ready', client.syncGuilds.bind(client)); - - if (!client.users.has('1')) { - client.dataManager.newUser({ - id: '1', - username: 'Clyde', - discriminator: '0000', - avatar: 'https://discordapp.com/assets/f78426a064bc9dd24847519259bc42af.png', - bot: true, - status: 'online', - game: null, - verified: true, - }); - } - - client.setTimeout(() => { - if (!client.ws.normalReady) client.ws._emitReady(false); - }, 1200 * data.guilds.length); - - this.packetManager.ws.sessionID = data.session_id; - this.packetManager.ws.checkIfReady(); - } -} - -module.exports = ReadyHandler; - - -/***/ }, -/* 144 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class RelationshipAddHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - if (data.type === 1) { - client.fetchUser(data.id).then(user => { - client.user.friends.set(user.id, user); - }); - } else if (data.type === 2) { - client.fetchUser(data.id).then(user => { - client.user.blocked.set(user.id, user); - }); - } - } -} - -module.exports = RelationshipAddHandler; - - -/***/ }, -/* 145 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class RelationshipRemoveHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - if (data.type === 2) { - if (client.user.blocked.has(data.id)) { - client.user.blocked.delete(data.id); - } - } else if (data.type === 1) { - if (client.user.friends.has(data.id)) { - client.user.friends.delete(data.id); - } - } - } -} - -module.exports = RelationshipRemoveHandler; - - -/***/ }, -/* 146 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); -const Constants = __webpack_require__(0); - -class TypingStartHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - const channel = client.channels.get(data.channel_id); - const user = client.users.get(data.user_id); - const timestamp = new Date(data.timestamp * 1000); - - if (channel && user) { - if (channel.type === 'voice') { - client.emit(Constants.Events.WARN, `Discord sent a typing packet to voice channel ${channel.id}`); - return; - } - if (channel._typing.has(user.id)) { - const typing = channel._typing.get(user.id); - typing.lastTimestamp = timestamp; - typing.resetTimeout(tooLate(channel, user)); - } else { - channel._typing.set(user.id, new TypingData(client, timestamp, timestamp, tooLate(channel, user))); - client.emit(Constants.Events.TYPING_START, channel, user); - } - } - } -} - -class TypingData { - constructor(client, since, lastTimestamp, _timeout) { - this.client = client; - this.since = since; - this.lastTimestamp = lastTimestamp; - this._timeout = _timeout; - } - - resetTimeout(_timeout) { - this.client.clearTimeout(this._timeout); - this._timeout = _timeout; - } - - get elapsedTime() { - return Date.now() - this.since; - } -} - -function tooLate(channel, user) { - return channel.client.setTimeout(() => { - channel.client.emit(Constants.Events.TYPING_STOP, channel, user, channel._typing.get(user.id)); - channel._typing.delete(user.id); - }, 6000); -} - -/** - * Emitted whenever a user starts typing in a channel - * @event Client#typingStart - * @param {Channel} channel The channel the user started typing in - * @param {User} user The user that started typing - */ - -/** - * Emitted whenever a user stops typing in a channel - * @event Client#typingStop - * @param {Channel} channel The channel the user stopped typing in - * @param {User} user The user that stopped typing - */ - -module.exports = TypingStartHandler; - - -/***/ }, -/* 147 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class UserNoteUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - - client.actions.UserNoteUpdate.handle(data); - } -} - -module.exports = UserNoteUpdateHandler; - - -/***/ }, -/* 148 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -class UserUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.actions.UserUpdate.handle(data); - } -} - -module.exports = UserUpdateHandler; - - -/***/ }, -/* 149 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -/* -{ - "token": "my_token", - "guild_id": "41771983423143937", - "endpoint": "smart.loyal.discord.gg" -} -*/ - -class VoiceServerUpdate extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - client.emit('self.voiceServer', data); - } -} - -module.exports = VoiceServerUpdate; - - -/***/ }, -/* 150 */ -/***/ function(module, exports, __webpack_require__) { - -const AbstractHandler = __webpack_require__(1); - -const Constants = __webpack_require__(0); -const cloneObject = __webpack_require__(4); - -class VoiceStateUpdateHandler extends AbstractHandler { - handle(packet) { - const client = this.packetManager.client; - const data = packet.d; - - const guild = client.guilds.get(data.guild_id); - if (guild) { - const member = guild.members.get(data.user_id); - if (member) { - const oldVoiceChannelMember = cloneObject(member); - if (member.voiceChannel && member.voiceChannel.id !== data.channel_id) { - member.voiceChannel.members.delete(oldVoiceChannelMember.id); - } - - // if the member left the voice channel, unset their speaking property - if (!data.channel_id) member.speaking = null; - - if (member.user.id === client.user.id && data.channel_id) { - client.emit('self.voiceStateUpdate', data); - } - - const newChannel = client.channels.get(data.channel_id); - if (newChannel) newChannel.members.set(member.user.id, member); - - member.serverMute = data.mute; - member.serverDeaf = data.deaf; - member.selfMute = data.self_mute; - member.selfDeaf = data.self_deaf; - member.voiceSessionID = data.session_id; - member.voiceChannelID = data.channel_id; - client.emit(Constants.Events.VOICE_STATE_UPDATE, oldVoiceChannelMember, member); - } - } - } -} - -/** - * Emitted whenever a user changes voice state - e.g. joins/leaves a channel, mutes/unmutes. - * @event Client#voiceStateUpdate - * @param {GuildMember} oldMember The member before the voice state update - * @param {GuildMember} newMember The member after the voice state update - */ - -module.exports = VoiceStateUpdateHandler; - - -/***/ }, -/* 151 */ -/***/ function(module, exports) { - -/** - * Represents a user connection (or "platform identity") - */ -class UserConnection { - constructor(user, data) { - /** - * The user that owns the Connection - * @type {User} - */ - this.user = user; - - this.setup(data); - } - - setup(data) { - /** - * The type of the Connection - * @type {string} - */ - this.type = data.type; - - /** - * The username of the connection account - * @type {string} - */ - this.name = data.name; - - /** - * The id of the connection account - * @type {string} - */ - this.id = data.id; - - /** - * Whether the connection is revoked - * @type {boolean} - */ - this.revoked = data.revoked; - - /** - * an array of partial server integrations (not yet implemented in this lib) - * @type {Object[]} - */ - this.integrations = data.integrations; - } -} - -module.exports = UserConnection; - - -/***/ }, -/* 152 */ -/***/ function(module, exports, __webpack_require__) { - -const Collection = __webpack_require__(3); -const UserConnection = __webpack_require__(151); - -/** - * Represents a user's profile on Discord. - */ -class UserProfile { - constructor(user, data) { - /** - * The owner of the profile - * @type {User} - */ - this.user = user; - - /** - * The Client that created the instance of the the UserProfile. - * @name UserProfile#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: user.client }); - - /** - * Guilds that the client user and the user share - * @type {Collection} - */ - this.mutualGuilds = new Collection(); - - /** - * The user's connections - * @type {Collection} - */ - this.connections = new Collection(); - - this.setup(data); - } - - setup(data) { - /** - * If the user has Discord Premium - * @type {boolean} - */ - this.premium = data.premium; - - for (const guild of data.mutual_guilds) { - if (this.client.guilds.has(guild.id)) { - this.mutualGuilds.set(guild.id, this.client.guilds.get(guild.id)); - } - } - for (const connection of data.connected_accounts) { - this.connections.set(connection.id, new UserConnection(this.user, connection)); - } - } -} - -module.exports = UserProfile; - - -/***/ }, -/* 153 */ -/***/ function(module, exports) { - -module.exports = function arraysEqual(a, b) { - if (a === b) return true; - if (a.length !== b.length) return false; - - for (const itemInd in a) { - const item = a[itemInd]; - const ind = b.indexOf(item); - if (ind) { - b.splice(ind, 1); - } - } - - return b.length === 0; -}; - - -/***/ }, -/* 154 */ -/***/ function(module, exports) { - -module.exports = function parseEmoji(text) { - if (text.includes('%')) { - text = decodeURIComponent(text); - } - if (text.includes(':')) { - const [name, id] = text.split(':'); - return { name, id }; - } else { - return { - name: text, - id: null, - }; - } -}; - - -/***/ }, -/* 155 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 156 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 157 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 158 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ }, -/* 159 */ -/***/ function(module, exports) { - -/* (ignored) */ - -/***/ } -/******/ ]); \ No newline at end of file diff --git a/discord.11.0.0.min.js b/discord.11.0.0.min.js deleted file mode 100644 index 40fe8a07..00000000 --- a/discord.11.0.0.min.js +++ /dev/null @@ -1,20 +0,0 @@ -!function(t){function e(i){if(n[i])return n[i].exports;var s=n[i]={i:i,l:!1,exports:{}};return t[i].call(s.exports,s,s.exports,e),s.l=!0,s.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=57)}([function(t,e,n){(function(t){e.Package=n(27),e.DefaultOptions={apiRequestMethod:"sequential",shardId:0,shardCount:0,messageCacheMaxSize:200,messageCacheLifetime:0,messageSweepInterval:0,fetchAllMembers:!1,disableEveryone:!1,sync:!1,restWsBridgeTimeout:5e3,disabledEvents:[],restTimeOffset:500,ws:{large_threshold:250,compress:"undefined"==typeof window,properties:{$os:t?t.platform:"discord.js",$browser:"discord.js",$device:"discord.js",$referrer:"",$referring_domain:""}}},e.Errors={NO_TOKEN:"Request to use token, but token was unavailable to the client.",NO_BOT_ACCOUNT:"Only bot accounts are able to make use of this feature.",NO_USER_ACCOUNT:"Only user accounts are able to make use of this feature.",BAD_WS_MESSAGE:"A bad message was received from the websocket; either bad compression, or not JSON.",TOOK_TOO_LONG:"Something took too long to do.",NOT_A_PERMISSION:"Invalid permission string or number.",INVALID_RATE_LIMIT_METHOD:"Unknown rate limiting method.",BAD_LOGIN:"Incorrect login details were provided.",INVALID_SHARD:"Invalid shard settings were provided.",INVALID_TOKEN:"An invalid token was provided."};const i=e.PROTOCOL_VERSION=6,s=e.HOST=`https://discordapp.com`,r=e.API=`${s}/api/v${i}`,o=e.Endpoints={login:`${r}/auth/login`,logout:`${r}/auth/logout`,gateway:`${r}/gateway`,botGateway:`${r}/gateway/bot`,invite:t=>`${r}/invite/${t}`,inviteLink:t=>`https://discord.gg/${t}`,assets:t=>`${s}/assets/${t}`,CDN:"https://cdn.discordapp.com",user:t=>`${r}/users/${t}`,userChannels:t=>`${o.user(t)}/channels`,userProfile:t=>`${o.user(t)}/profile`,avatar:(t,e)=>{return"1"===t?e:`${o.CDN}/avatars/${t}/${e}.${e.startsWith("a_")?"gif":"jpg"}?size=1024`},me:`${r}/users/@me`,meGuild:t=>`${o.me}/guilds/${t}`,meMentions:(t,e,n,i)=>`users/@me/mentions?limit=${t}&roles=${e}&everyone=${n}${i?`&guild_id=${i}`:""}`,relationships:t=>`${o.user(t)}/relationships`,note:t=>`${o.me}/notes/${t}`,guilds:`${r}/guilds`,guild:t=>`${o.guilds}/${t}`,guildIcon:(t,e)=>`${o.CDN}/icons/${t}/${e}.jpg`,guildSplash:(t,e)=>`${o.CDN}/splashes/${t}/${e}.jpg`,guildPrune:t=>`${o.guild(t)}/prune`,guildEmbed:t=>`${o.guild(t)}/embed`,guildInvites:t=>`${o.guild(t)}/invites`,guildRoles:t=>`${o.guild(t)}/roles`,guildRole:(t,e)=>`${o.guildRoles(t)}/${e}`,guildBans:t=>`${o.guild(t)}/bans`,guildIntegrations:t=>`${o.guild(t)}/integrations`,guildMembers:t=>`${o.guild(t)}/members`,guildMember:(t,e)=>`${o.guildMembers(t)}/${e}`,guildMemberRole:(t,e,n)=>`${o.guildMember(t,e)}/roles/${n}`,guildMemberNickname:t=>`${o.guildMember(t,"@me")}/nick`,guildChannels:t=>`${o.guild(t)}/channels`,guildEmojis:t=>`${o.guild(t)}/emojis`,channels:`${r}/channels`,channel:t=>`${o.channels}/${t}`,channelMessages:t=>`${o.channel(t)}/messages`,channelInvites:t=>`${o.channel(t)}/invites`,channelTyping:t=>`${o.channel(t)}/typing`,channelPermissions:t=>`${o.channel(t)}/permissions`,channelMessage:(t,e)=>`${o.channelMessages(t)}/${e}`,channelWebhooks:t=>`${o.channel(t)}/webhooks`,messageReactions:(t,e)=>`${o.channelMessage(t,e)}/reactions`,messageReaction:(t,e,n,i)=>`${o.messageReactions(t,e)}/${n}`+`${i?`?limit=${i}`:""}`,selfMessageReaction:(t,e,n,i)=>`${o.messageReaction(t,e,n,i)}/@me`,userMessageReaction:(t,e,n,i,s)=>`${o.messageReaction(t,e,n,i)}/${s}`,webhook:(t,e)=>`${r}/webhooks/${t}${e?`/${e}`:""}`,myApplication:`${r}/oauth2/applications/@me`,getApp:t=>`${r}/oauth2/authorize?client_id=${t}`,emoji:t=>`${o.CDN}/emojis/${t}.png`};e.Status={READY:0,CONNECTING:1,RECONNECTING:2,IDLE:3,NEARLY:4,DISCONNECTED:5},e.ChannelTypes={text:0,DM:1,voice:2,groupDM:3},e.OPCodes={DISPATCH:0,HEARTBEAT:1,IDENTIFY:2,STATUS_UPDATE:3,VOICE_STATE_UPDATE:4,VOICE_GUILD_PING:5,RESUME:6,RECONNECT:7,REQUEST_GUILD_MEMBERS:8,INVALID_SESSION:9,HELLO:10,HEARTBEAT_ACK:11},e.VoiceOPCodes={IDENTIFY:0,SELECT_PROTOCOL:1,READY:2,HEARTBEAT:3,SESSION_DESCRIPTION:4,SPEAKING:5},e.Events={READY:"ready",GUILD_CREATE:"guildCreate",GUILD_DELETE:"guildDelete",GUILD_UPDATE:"guildUpdate",GUILD_UNAVAILABLE:"guildUnavailable",GUILD_AVAILABLE:"guildAvailable",GUILD_MEMBER_ADD:"guildMemberAdd",GUILD_MEMBER_REMOVE:"guildMemberRemove",GUILD_MEMBER_UPDATE:"guildMemberUpdate",GUILD_MEMBER_AVAILABLE:"guildMemberAvailable",GUILD_MEMBER_SPEAKING:"guildMemberSpeaking",GUILD_MEMBERS_CHUNK:"guildMembersChunk",GUILD_ROLE_CREATE:"roleCreate",GUILD_ROLE_DELETE:"roleDelete",GUILD_ROLE_UPDATE:"roleUpdate",GUILD_EMOJI_CREATE:"emojiCreate",GUILD_EMOJI_DELETE:"emojiDelete",GUILD_EMOJI_UPDATE:"emojiUpdate",GUILD_BAN_ADD:"guildBanAdd",GUILD_BAN_REMOVE:"guildBanRemove",CHANNEL_CREATE:"channelCreate",CHANNEL_DELETE:"channelDelete",CHANNEL_UPDATE:"channelUpdate",CHANNEL_PINS_UPDATE:"channelPinsUpdate",MESSAGE_CREATE:"message",MESSAGE_DELETE:"messageDelete",MESSAGE_UPDATE:"messageUpdate",MESSAGE_BULK_DELETE:"messageDeleteBulk",MESSAGE_REACTION_ADD:"messageReactionAdd",MESSAGE_REACTION_REMOVE:"messageReactionRemove",MESSAGE_REACTION_REMOVE_ALL:"messageReactionRemoveAll",USER_UPDATE:"userUpdate",USER_NOTE_UPDATE:"userNoteUpdate",PRESENCE_UPDATE:"presenceUpdate",VOICE_STATE_UPDATE:"voiceStateUpdate",TYPING_START:"typingStart",TYPING_STOP:"typingStop",DISCONNECT:"disconnect",RECONNECTING:"reconnecting",ERROR:"error",WARN:"warn",DEBUG:"debug"},e.WSEvents={READY:"READY",GUILD_SYNC:"GUILD_SYNC",GUILD_CREATE:"GUILD_CREATE",GUILD_DELETE:"GUILD_DELETE",GUILD_UPDATE:"GUILD_UPDATE",GUILD_MEMBER_ADD:"GUILD_MEMBER_ADD",GUILD_MEMBER_REMOVE:"GUILD_MEMBER_REMOVE",GUILD_MEMBER_UPDATE:"GUILD_MEMBER_UPDATE",GUILD_MEMBERS_CHUNK:"GUILD_MEMBERS_CHUNK",GUILD_ROLE_CREATE:"GUILD_ROLE_CREATE",GUILD_ROLE_DELETE:"GUILD_ROLE_DELETE",GUILD_ROLE_UPDATE:"GUILD_ROLE_UPDATE",GUILD_BAN_ADD:"GUILD_BAN_ADD",GUILD_BAN_REMOVE:"GUILD_BAN_REMOVE",GUILD_EMOJIS_UPDATE:"GUILD_EMOJIS_UPDATE",CHANNEL_CREATE:"CHANNEL_CREATE",CHANNEL_DELETE:"CHANNEL_DELETE",CHANNEL_UPDATE:"CHANNEL_UPDATE",CHANNEL_PINS_UPDATE:"CHANNEL_PINS_UPDATE",MESSAGE_CREATE:"MESSAGE_CREATE",MESSAGE_DELETE:"MESSAGE_DELETE",MESSAGE_UPDATE:"MESSAGE_UPDATE",MESSAGE_DELETE_BULK:"MESSAGE_DELETE_BULK",MESSAGE_REACTION_ADD:"MESSAGE_REACTION_ADD",MESSAGE_REACTION_REMOVE:"MESSAGE_REACTION_REMOVE",MESSAGE_REACTION_REMOVE_ALL:"MESSAGE_REACTION_REMOVE_ALL",USER_UPDATE:"USER_UPDATE",USER_NOTE_UPDATE:"USER_NOTE_UPDATE",PRESENCE_UPDATE:"PRESENCE_UPDATE",VOICE_STATE_UPDATE:"VOICE_STATE_UPDATE",TYPING_START:"TYPING_START",VOICE_SERVER_UPDATE:"VOICE_SERVER_UPDATE",RELATIONSHIP_ADD:"RELATIONSHIP_ADD",RELATIONSHIP_REMOVE:"RELATIONSHIP_REMOVE"},e.MessageTypes={0:"DEFAULT",1:"RECIPIENT_ADD",2:"RECIPIENT_REMOVE",3:"CALL",4:"CHANNEL_NAME_CHANGE",5:"CHANNEL_ICON_CHANGE",6:"PINS_ADD"},e.DefaultAvatars={BLURPLE:"6debd47ed13483642cf09e832ed0bc1b",GREY:"322c936a8c8be1b803cd94861bdfa868",GREEN:"dd4dbc0016779df1378e7812eabaa04d",ORANGE:"0e291f67c9274a1abdddeb3fd919cbaa",RED:"1cbd08c76f8af6dddce02c5138971129"};const a=e.PermissionFlags={CREATE_INSTANT_INVITE:1,KICK_MEMBERS:2,BAN_MEMBERS:4,ADMINISTRATOR:8,MANAGE_CHANNELS:16,MANAGE_GUILD:32,ADD_REACTIONS:64,READ_MESSAGES:1024,SEND_MESSAGES:2048,SEND_TTS_MESSAGES:4096,MANAGE_MESSAGES:8192,EMBED_LINKS:16384,ATTACH_FILES:32768,READ_MESSAGE_HISTORY:65536,MENTION_EVERYONE:1<<17,EXTERNAL_EMOJIS:1<<18,CONNECT:1<<20,SPEAK:1<<21,MUTE_MEMBERS:1<<22,DEAFEN_MEMBERS:1<<23,MOVE_MEMBERS:1<<24,USE_VAD:1<<25,CHANGE_NICKNAME:1<<26,MANAGE_NICKNAMES:1<<27,MANAGE_ROLES_OR_PERMISSIONS:1<<28,MANAGE_WEBHOOKS:1<<29,MANAGE_EMOJIS:1<<30};let h=0;for(const u in a)h|=a[u];e.ALL_PERMISSIONS=h,e.DEFAULT_PERMISSIONS=104324097}).call(e,n(24))},function(t,e){class n{constructor(t){this.packetManager=t}handle(t){return t}}t.exports=n},function(t,e){class n{constructor(t){this.client=t}handle(t){return t}}t.exports=n},function(t,e){class n extends Map{constructor(t){super(t),this._array=null,this._keyArray=null}set(t,e){return this._array=null,this._keyArray=null,super.set(t,e)}delete(t){return this._array=null,this._keyArray=null,super.delete(t)}array(){return this._array&&this._array.length===this.size||(this._array=Array.from(this.values())),this._array}keyArray(){return this._keyArray&&this._keyArray.length===this.size||(this._keyArray=Array.from(this.keys())),this._keyArray}first(){return this.values().next().value}firstKey(){return this.keys().next().value}last(){const t=this.array();return t[t.length-1]}lastKey(){const t=this.keyArray();return t[t.length-1]}random(){const t=this.array();return t[Math.floor(Math.random()*t.length)]}randomKey(){const t=this.keyArray();return t[Math.floor(Math.random()*t.length)]}findAll(t,e){if("string"!=typeof t)throw new TypeError("Key must be a string.");if("undefined"==typeof e)throw new Error("Value must be specified.");const n=[];for(const i of this.values())i[t]===e&&n.push(i);return n}find(t,e){if("string"==typeof t){if("undefined"==typeof e)throw new Error("Value must be specified.");if("id"===t)throw new RangeError("Don't use .find() with IDs. Instead, use .get(id).");for(const n of this.values())if(n[t]===e)return n;return null}if("function"==typeof t){for(const[e,n]of this)if(t(n,e,this))return n;return null}throw new Error("First argument must be a property string or a function.")}findKey(t,e){if("string"==typeof t){if("undefined"==typeof e)throw new Error("Value must be specified.");for(const[n,i]of this)if(i[t]===e)return n;return null}if("function"==typeof t){for(const[e,n]of this)if(t(n,e,this))return e;return null}throw new Error("First argument must be a property string or a function.")}exists(t,e){if("id"===t)throw new RangeError("Don't use .exists() with IDs. Instead, use .has(id).");return Boolean(this.find(t,e))}filter(t,e){e&&(t=t.bind(e));const i=new n;for(const[s,r]of this)t(r,s,this)&&i.set(s,r);return i}filterArray(t,e){e&&(t=t.bind(e));const n=[];for(const[i,s]of this)t(s,i,this)&&n.push(s);return n}map(t,e){e&&(t=t.bind(e));const n=new Array(this.size);let i=0;for(const[s,r]of this)n[i++]=t(r,s,this);return n}some(t,e){e&&(t=t.bind(e));for(const[n,i]of this)if(t(i,n,this))return!0;return!1}every(t,e){e&&(t=t.bind(e));for(const[n,i]of this)if(!t(i,n,this))return!1;return!0}reduce(t,e){let n;if("undefined"!=typeof e){n=e;for(const[i,s]of this)n=t(n,s,i,this)}else{let e=!0;for(const[i,s]of this)e?(n=s,e=!1):n=t(n,s,i,this)}return n}concat(...t){const e=new this.constructor;for(const[n,i]of this)e.set(n,i);for(const s of t)for(const[n,i]of s)e.set(n,i);return e}deleteAll(){const t=[];for(const e of this.values())e.delete&&t.push(e.delete());return t}equals(t){return!!t&&(this===t||this.size===t.size&&!this.find((e,n)=>{const i=t.get(n);return i!==e||void 0===i&&!t.has(n)}))}}t.exports=n},function(t,e){t.exports=function(t){const e=Object.create(t);return Object.assign(e,t),e}},function(t,e,n){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;e.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var n=e.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])}}return t},e.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var s={arraySet:function(t,e,n,i,s){if(e.subarray&&t.subarray)return void t.set(e.subarray(n,n+i),s);for(var r=0;r"dm"===t.type).find(t=>t.recipient.id===this.id)}deleteDM(){return this.client.rest.methods.deleteChannel(this)}addFriend(){return this.client.rest.methods.addFriend(this)}removeFriend(){return this.client.rest.methods.removeFriend(this)}block(){return this.client.rest.methods.blockUser(this)}unblock(){return this.client.rest.methods.unblockUser(this)}fetchProfile(){return this.client.rest.methods.fetchUserProfile(this)}setNote(t){return this.client.rest.methods.setNote(this,t)}equals(t){let e=t&&this.id===t.id&&this.username===t.username&&this.discriminator===t.discriminator&&this.avatar===t.avatar&&this.bot===Boolean(t.bot);return e}toString(){return`<@${this.id}>`}send(){}sendMessage(){}sendEmbed(){}sendFile(){}sendCode(){}}i.applyToClass(o),t.exports=o},function(t,e){class n{constructor(t={}){this.status=t.status||"offline",this.game=t.game?new i(t.game):null}update(t){this.status=t.status||this.status,this.game=t.game?new i(t.game):null}equals(t){return this===t||(t&&this.status===t.status&&this.game?this.game.equals(t.game):!t.game)}}class i{constructor(t){this.name=t.name,this.type=t.type,this.url=t.url||null}get streaming(){return 1===this.type}equals(t){return this===t||t&&this.name===t.name&&this.type===t.type&&this.url===t.url}}e.Presence=n,e.Game=i},function(t,e,n){const i=n(0);class s{constructor(t,e){Object.defineProperty(this,"client",{value:t.client}),this.guild=t,e&&this.setup(e)}setup(t){this.id=t.id,this.name=t.name,this.color=t.color,this.hoist=t.hoist,this.position=t.position,this.permissions=t.permissions,this.managed=t.managed,this.mentionable=t.mentionable}get createdTimestamp(){return this.id/4194304+14200704e5}get createdAt(){return new Date(this.createdTimestamp)}get hexColor(){let t=this.color.toString(16);for(;t.length<6;)t=`0${t}`;return`#${t}`}get members(){return this.guild.members.filter(t=>t.roles.has(this.id))}get editable(){if(this.managed)return!1;const t=this.guild.member(this.client.user);return!!t.hasPermission(i.PermissionFlags.MANAGE_ROLES_OR_PERMISSIONS)&&t.highestRole.comparePositionTo(this)>0}serialize(){const t={};for(const e in i.PermissionFlags)t[e]=this.hasPermission(e);return t}hasPermission(t,e=false){return t=this.client.resolver.resolvePermission(t),!e&&(this.permissions&i.PermissionFlags.ADMINISTRATOR)>0||(this.permissions&t)>0}hasPermissions(t,e=false){return t.every(t=>this.hasPermission(t,e))}comparePositionTo(t){return this.constructor.comparePositions(this,t)}edit(t){return this.client.rest.methods.updateGuildRole(this,t)}setName(t){return this.edit({name:t})}setColor(t){return this.edit({color:t})}setHoist(t){return this.edit({hoist:t})}setPosition(t){return this.guild.setRolePosition(this,t).then(()=>this)}setPermissions(t){return this.edit({permissions:t})}setMentionable(t){return this.edit({mentionable:t})}delete(){return this.client.rest.methods.deleteGuildRole(this)}equals(t){return t&&this.id===t.id&&this.name===t.name&&this.color===t.color&&this.hoist===t.hoist&&this.position===t.position&&this.permissions===t.permissions&&this.managed===t.managed}toString(){return this.id===this.guild.id?"@everyone":`<@&${this.id}>`}static comparePositions(t,e){return t.position===e.position?e.id-t.id:t.position-e.position}}t.exports=s},function(t,e){class n{constructor(t,e){Object.defineProperty(this,"client",{value:t}),this.type=null,e&&this.setup(e)}setup(t){this.id=t.id}get createdTimestamp(){return this.id/4194304+14200704e5}get createdAt(){return new Date(this.createdTimestamp)}delete(){return this.client.rest.methods.deleteChannel(this)}}t.exports=n},function(t,e,n){const i=n(0),s=n(3);class r{constructor(t,e){Object.defineProperty(this,"client",{value:t.client}),this.guild=t,this.setup(e)}setup(t){this.id=t.id,this.name=t.name,this.requiresColons=t.require_colons,this.managed=t.managed,this._roles=t.roles}get createdTimestamp(){return this.id/4194304+14200704e5}get createdAt(){return new Date(this.createdTimestamp)}get roles(){const t=new s;for(const e of this._roles)this.guild.roles.has(e)&&t.set(e,this.guild.roles.get(e));return t}get url(){return i.Endpoints.emoji(this.id)}toString(){return this.requiresColons?`<:${this.name}:${this.id}>`:this.name}equals(t){return t instanceof r?t.id===this.id&&t.name===this.name&&t.managed===this.managed&&t.requiresColons===this.requiresColons:t.id===this.id&&t.name===this.name}get identifier(){return this.id?`${this.name}:${this.id}`:encodeURIComponent(this.name)}}t.exports=r},function(t,e,n){const i=n(33),s=n(35),r=n(36),o=n(3),a=n(0),h=n(15),u=n(57);class c{constructor(t,e,n){Object.defineProperty(this,"client",{value:n}),this.channel=t,e&&this.setup(e)}setup(t){this.id=t.id,this.type=a.MessageTypes[t.type],this.content=t.content,this.author=this.client.dataManager.newUser(t.author),this.member=this.guild?this.guild.member(this.author)||null:null,this.pinned=t.pinned,this.tts=t.tts,this.nonce=t.nonce,this.system=6===t.type,this.embeds=t.embeds.map(t=>new s(this,t)),this.attachments=new o;for(const e of t.attachments)this.attachments.set(e.id,new i(this,e));this.createdTimestamp=new Date(t.timestamp).getTime(),this.editedTimestamp=t.edited_timestamp?new Date(t.edited_timestamp).getTime():null,this.mentions={users:new o,roles:new o,channels:new o,everyone:t.mention_everyone};for(const n of t.mentions){let t=this.client.users.get(n.id);t?this.mentions.users.set(t.id,t):(t=this.client.dataManager.newUser(n),this.mentions.users.set(t.id,t))}if(t.mention_roles)for(const n of t.mention_roles){const t=this.channel.guild.roles.get(n);t&&this.mentions.roles.set(t.id,t)}if(this.channel.guild){const e=t.content.match(/<#([0-9]{14,20})>/g)||[];for(const n of e){const t=this.channel.guild.channels.get(n.match(/([0-9]{14,20})/g)[0]);t&&this.mentions.channels.set(t.id,t)}}if(this._edits=[],this.reactions=new o,t.reactions&&t.reactions.length>0)for(const h of t.reactions){const t=h.emoji.id?`${h.emoji.name}:${h.emoji.id}`:h.emoji.name;this.reactions.set(t,new r(this,h.emoji,h.count,h.me))}this.webhookID=t.webhook_id||null}patch(t){if(t.author&&(this.author=this.client.users.get(t.author.id),this.guild&&(this.member=this.guild.member(this.author))),t.content&&(this.content=t.content),t.timestamp&&(this.createdTimestamp=new Date(t.timestamp).getTime()),t.edited_timestamp&&(this.editedTimestamp=t.edited_timestamp?new Date(t.edited_timestamp).getTime():null),"tts"in t&&(this.tts=t.tts),"mention_everyone"in t&&(this.mentions.everyone=t.mention_everyone),t.nonce&&(this.nonce=t.nonce),t.embeds&&(this.embeds=t.embeds.map(t=>new s(this,t))),t.type>-1&&(this.system=!1,6===t.type&&(this.system=!0)),t.attachments){this.attachments=new o;for(const e of t.attachments)this.attachments.set(e.id,new i(this,e))}if(t.mentions)for(const e of t.mentions){let t=this.client.users.get(e.id);t?this.mentions.users.set(t.id,t):(t=this.client.dataManager.newUser(e),this.mentions.users.set(t.id,t))}if(t.mention_roles)for(const e of t.mention_roles){const t=this.channel.guild.roles.get(e);t&&this.mentions.roles.set(t.id,t)}if(t.id&&(this.id=t.id),this.channel.guild&&t.content){const e=t.content.match(/<#([0-9]{14,20})>/g)||[];for(const n of e){const t=this.channel.guild.channels.get(n.match(/([0-9]{14,20})/g)[0]);t&&this.mentions.channels.set(t.id,t)}}if(t.reactions&&(this.reactions=new o,t.reactions.length>0))for(const n of t.reactions){const e=n.emoji.id?`${n.emoji.name}:${n.emoji.id}`:n.emoji.name;this.reactions.set(e,new r(this,t.emoji,t.count,t.me))}}get createdAt(){return new Date(this.createdTimestamp)}get editedAt(){return this.editedTimestamp?new Date(this.editedTimestamp):null}get guild(){return this.channel.guild||null}get cleanContent(){return this.content.replace(/@(everyone|here)/g,"@​$1").replace(/<@!?[0-9]+>/g,t=>{const e=t.replace(/<|!|>|@/g,"");if("dm"===this.channel.type||"group"===this.channel.type)return this.client.users.has(e)?`@${this.client.users.get(e).username}`:t;const n=this.channel.guild.members.get(e);if(n)return n.nickname?`@${n.nickname}`:`@${n.user.username}`;{const n=this.client.users.get(e);return n?`@${n.username}`:t}}).replace(/<#[0-9]+>/g,t=>{const e=this.client.channels.get(t.replace(/<|#|>/g,""));return e?`#${e.name}`:t}).replace(/<@&[0-9]+>/g,t=>{if("dm"===this.channel.type||"group"===this.channel.type)return t;const e=this.guild.roles.get(t.replace(/<|@|>|&/g,""));return e?`@${e.name}`:t})}get edits(){const t=this._edits.slice();return t.unshift(this),t}get editable(){return this.author.id===this.client.user.id}get deletable(){return this.author.id===this.client.user.id||this.guild&&this.channel.permissionsFor(this.client.user).hasPermission(a.PermissionFlags.MANAGE_MESSAGES)}get pinnable(){return!this.guild||this.channel.permissionsFor(this.client.user).hasPermission(a.PermissionFlags.MANAGE_MESSAGES)}isMentioned(t){return t=t&&t.id?t.id:t,this.mentions.users.has(t)||this.mentions.channels.has(t)||this.mentions.roles.has(t)}isMemberMentioned(t){return!!this.mentions.everyone||(!!this.mentions.users.has(t.id)||!!(t instanceof u.GuildMember&&t.roles.some(t=>this.mentions.roles.has(t.id))))}edit(t,e){return e||"object"!=typeof t?e||(e={}):(e=t,t=""),this.client.rest.methods.updateMessage(this,t,e)}editCode(t,e){return e=h(this.client.resolver.resolveString(e),!0),this.edit(`\`\`\`${t||""} -${e} -\`\`\``)}pin(){return this.client.rest.methods.pinMessage(this)}unpin(){return this.client.rest.methods.unpinMessage(this)}react(t){if(t=this.client.resolver.resolveEmojiIdentifier(t),!t)throw new TypeError("Emoji must be a string or Emoji/ReactionEmoji");return this.client.rest.methods.addMessageReaction(this,t)}clearReactions(){return this.client.rest.methods.removeMessageReactions(this)}delete(t=0){return t<=0?this.client.rest.methods.deleteMessage(this):new Promise(e=>{this.client.setTimeout(()=>{e(this.delete())},t)})}reply(t,e={}){return t=`${this.guild||"group"===this.channel.type?`${this.author}, `:""}${t}`,this.channel.send(t,e)}fetchWebhook(){return this.webhookID?this.client.fetchWebhook(this.webhookID):Promise.reject(new Error("The message was not sent by a webhook."))}equals(t,e){if(!t)return!1;const n=!t.author&&!t.attachments;if(n)return this.id===t.id&&this.embeds.length===t.embeds.length;let i=this.id===t.id&&this.author.id===t.author.id&&this.content===t.content&&this.tts===t.tts&&this.nonce===t.nonce&&this.embeds.length===t.embeds.length&&this.attachments.length===t.attachments.length;return i&&e&&(i=this.mentions.everyone===t.mentions.everyone&&this.createdTimestamp===new Date(e.timestamp).getTime()&&this.editedTimestamp===new Date(e.edited_timestamp).getTime()),i}toString(){return this.content}_addReaction(t,e){const n=t.id?`${t.name}:${t.id}`:t.name;let i;return this.reactions.has(n)?(i=this.reactions.get(n),i.me||(i.me=e.id===this.client.user.id)):(i=new r(this,t,0,e.id===this.client.user.id),this.reactions.set(n,i)),i.users.has(e.id)?null:(i.users.set(e.id,e),i.count++,i)}_removeReaction(t,e){const n=t.id||t;if(this.reactions.has(n)){const t=this.reactions.get(n);if(t.users.has(e.id))return t.users.delete(e.id),t.count--,e.id===this.client.user.id&&(t.me=!1),t}return null}_clearReactions(){this.reactions.clear()}}t.exports=c},function(t,e,n){const i=n(23),s=n(11),r=n(34),o=n(3);class a{constructor(){this.messages=new o,this.lastMessageID=null}send(t,e){return e||"object"!=typeof t||t instanceof Array?e||(e={}):(e=t,t=""),e.file?("string"==typeof e.file&&(e.file={attachment:e.file}),e.file.name||("string"==typeof e.file.attachment?e.file.name=i.basename(e.file.attachment):e.file.attachment&&e.file.attachment.path?e.file.name=i.basename(e.file.attachment.path):e.file.name="file.jpg"),this.client.resolver.resolveBuffer(e.file.attachment).then(n=>this.client.rest.methods.sendMessage(this,t,e,{file:n,name:e.file.name}))):this.client.rest.methods.sendMessage(this,t,e)}sendMessage(t,e){return this.send(t,e)}sendEmbed(t,e,n){return n||"object"!=typeof e?n||(n={}):(n=e,e=""),this.send(e,Object.assign(n,{embed:t}))}sendFile(t,e,n,i={}){return this.send(n,Object.assign(i,{file:{attachment:t,name:e}}))}sendCode(t,e,n={}){return this.send(e,Object.assign(n,{code:t}))}fetchMessage(t){return this.client.rest.methods.getChannelMessage(this,t).then(t=>{const e=t instanceof s?t:new s(this,t,this.client);return this._cacheMessage(e),e})}fetchMessages(t={}){return this.client.rest.methods.getChannelMessages(this,t).then(t=>{const e=new o;for(const n of t){const t=new s(this,n,this.client);e.set(n.id,t),this._cacheMessage(t)}return e})}fetchPinnedMessages(){return this.client.rest.methods.getChannelPinnedMessages(this).then(t=>{const e=new o;for(const n of t){const t=new s(this,n,this.client);e.set(n.id,t),this._cacheMessage(t)}return e})}startTyping(t){if("undefined"!=typeof t&&t<1)throw new RangeError("Count must be at least 1.");if(this.client.user._typing.has(this.id)){const e=this.client.user._typing.get(this.id);e.count=t||e.count+1}else this.client.user._typing.set(this.id,{count:t||1,interval:this.client.setInterval(()=>{this.client.rest.methods.sendTyping(this.id)},4e3)}),this.client.rest.methods.sendTyping(this.id)}stopTyping(t=false){if(this.client.user._typing.has(this.id)){const e=this.client.user._typing.get(this.id);e.count--,(e.count<=0||t)&&(this.client.clearInterval(e.interval),this.client.user._typing.delete(this.id))}}get typing(){return this.client.user._typing.has(this.id)}get typingCount(){return this.client.user._typing.has(this.id)?this.client.user._typing.get(this.id).count:0}createCollector(t,e={}){return new r(this,t,e)}awaitMessages(t,e={}){return new Promise((n,i)=>{const s=this.createCollector(t,e);s.on("end",(t,s)=>{e.errors&&e.errors.includes(s)?i(t):n(t)})})}bulkDelete(t){if(!isNaN(t))return this.fetchMessages({limit:t}).then(t=>this.bulkDelete(t));if(t instanceof Array||t instanceof o){const e=t instanceof o?t.keyArray():t.map(t=>t.id);return this.client.rest.methods.bulkDeleteMessages(this,e)}throw new TypeError("The messages must be an Array, Collection, or number.")}_cacheMessage(t){const e=this.client.options.messageCacheMaxSize;return 0===e?null:(this.messages.size>=e&&e>0&&this.messages.delete(this.messages.firstKey()),this.messages.set(t.id,t),t)}}e.applyToClass=((t,e=false)=>{const n=["send","sendMessage","sendEmbed","sendFile","sendCode"];e&&n.push("_cacheMessage","fetchMessages","fetchMessage","bulkDelete","startTyping","stopTyping","typing","typingCount","fetchPinnedMessages","createCollector","awaitMessages");for(const i of n)Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(a.prototype,i))})},function(t,e,n){const i=n(9),s=n(8),r=n(40),o=n(16),a=n(0),h=n(3);class u extends i{constructor(t,e){super(t.client,e),this.guild=t}setup(t){if(super.setup(t),this.name=t.name,this.position=t.position,this.permissionOverwrites=new h,t.permission_overwrites)for(const e of t.permission_overwrites)this.permissionOverwrites.set(e.id,new r(this,e))}permissionsFor(t){if(t=this.client.resolver.resolveGuildMember(this.guild,t),!t)return null;if(t.id===this.guild.ownerID)return new o(t,a.ALL_PERMISSIONS);let e=0;const n=t.roles;for(const i of n.values())e|=i.permissions;const s=this.overwritesFor(t,!0,n);for(const r of s.role.concat(s.member))e&=~r.deny,e|=r.allow;const h=Boolean(e&a.PermissionFlags.ADMINISTRATOR);return h&&(e=a.ALL_PERMISSIONS),new o(t,e)}overwritesFor(t,e=false,n=null){if(e||(t=this.client.resolver.resolveGuildMember(this.guild,t)),!t)return[];n=n||t.roles;const i=[],s=[];for(const r of this.permissionOverwrites.values())r.id===t.id?s.push(r):n.has(r.id)&&i.push(r);return{role:i,member:s}}overwritePermissions(t,e){const n={allow:0,deny:0};if(t instanceof s)n.type="role";else if(this.guild.roles.has(t))t=this.guild.roles.get(t),n.type="role";else if(t=this.client.resolver.resolveUser(t),n.type="member",!t)return Promise.reject(new TypeError("Supplied parameter was neither a User nor a Role."));n.id=t.id;const i=this.permissionOverwrites.get(t.id);i&&(n.allow=i.allow,n.deny=i.deny);for(const r in e)e[r]===!0?(n.allow|=a.PermissionFlags[r]||0,n.deny&=~(a.PermissionFlags[r]||0)):e[r]===!1?(n.allow&=~(a.PermissionFlags[r]||0),n.deny|=a.PermissionFlags[r]||0):null===e[r]&&(n.allow&=~(a.PermissionFlags[r]||0),n.deny&=~(a.PermissionFlags[r]||0));return this.client.rest.methods.setChannelOverwrite(this,n)}edit(t){return this.client.rest.methods.updateChannel(this,t)}setName(t){return this.edit({name:t})}setPosition(t){return this.client.rest.methods.updateChannel(this,{position:t})}setTopic(t){return this.client.rest.methods.updateChannel(this,{topic:t})}createInvite(t={}){return this.client.rest.methods.createChannelInvite(this,t)}clone(t=this.name,e=true){return this.guild.createChannel(t,this.type,e?this.permissionOverwrites:[])}equals(t){let e=t&&this.id===t.id&&this.type===t.type&&this.topic===t.topic&&this.position===t.position&&this.name===t.name;return e&&(e=this.permissionOverwrites&&t.permissionOverwrites?this.permissionOverwrites.equals(t.permissionOverwrites):!this.permissionOverwrites&&!t.permissionOverwrites),e}toString(){return`<#${this.id}>`}}t.exports=u},function(t,e,n){const i=n(12),s=n(8),r=n(16),o=n(0),a=n(3),h=n(7).Presence;class u{constructor(t,e){Object.defineProperty(this,"client",{value:t.client}),this.guild=t,this.user={},this._roles=[],e&&this.setup(e),this.lastMessageID=null}setup(t){this.serverDeaf=t.deaf,this.serverMute=t.mute,this.selfMute=t.self_mute,this.selfDeaf=t.self_deaf,this.voiceSessionID=t.session_id,this.voiceChannelID=t.channel_id,this.speaking=!1,this.nickname=t.nick||null,this.joinedTimestamp=new Date(t.joined_at).getTime(),this.user=t.user,this._roles=t.roles}get joinedAt(){return new Date(this.joinedTimestamp)}get presence(){return this.frozenPresence||this.guild.presences.get(this.id)||new h}get roles(){const t=new a,e=this.guild.roles.get(this.guild.id);e&&t.set(e.id,e);for(const n of this._roles){const e=this.guild.roles.get(n);e&&t.set(e.id,e)}return t}get highestRole(){return this.roles.reduce((t,e)=>!t||e.comparePositionTo(t)>0?e:t)}get mute(){return this.selfMute||this.serverMute}get deaf(){return this.selfDeaf||this.serverDeaf}get voiceChannel(){return this.guild.channels.get(this.voiceChannelID)}get id(){return this.user.id}get displayName(){return this.nickname||this.user.username}get permissions(){if(this.user.id===this.guild.ownerID)return new r(this,o.ALL_PERMISSIONS);let t=0;const e=this.roles;for(const n of e.values())t|=n.permissions;const i=Boolean(t&o.PermissionFlags.ADMINISTRATOR);return i&&(t=o.ALL_PERMISSIONS),new r(this,t)}get kickable(){if(this.user.id===this.guild.ownerID)return!1;if(this.user.id===this.client.user.id)return!1;const t=this.guild.member(this.client.user);return!!t.hasPermission(o.PermissionFlags.KICK_MEMBERS)&&t.highestRole.comparePositionTo(this.highestRole)>0}get bannable(){if(this.user.id===this.guild.ownerID)return!1;if(this.user.id===this.client.user.id)return!1;const t=this.guild.member(this.client.user);return!!t.hasPermission(o.PermissionFlags.BAN_MEMBERS)&&t.highestRole.comparePositionTo(this.highestRole)>0}permissionsIn(t){if(t=this.client.resolver.resolveChannel(t),!t||!t.guild)throw new Error("Could not resolve channel to a guild channel.");return t.permissionsFor(this)}hasPermission(t,e=false){return!e&&this.user.id===this.guild.ownerID||this.roles.some(n=>n.hasPermission(t,e))}hasPermissions(t,e=false){return!e&&this.user.id===this.guild.ownerID||t.every(t=>this.hasPermission(t,e))}missingPermissions(t,e=false){return t.filter(t=>!this.hasPermission(t,e))}edit(t){return this.client.rest.methods.updateGuildMember(this,t)}setMute(t){return this.edit({mute:t})}setDeaf(t){return this.edit({deaf:t})}setVoiceChannel(t){return this.edit({channel:t})}setRoles(t){return this.edit({roles:t})}addRole(t){return t instanceof s||(t=this.guild.roles.get(t)),this.client.rest.methods.addMemberRole(this,t)}addRoles(t){let e;if(t instanceof a){e=this._roles.slice();for(const n of t.values())e.push(n.id)}else e=this._roles.concat(t);return this.edit({roles:e})}removeRole(t){return t instanceof s||(t=this.guild.roles.get(t)),this.client.rest.methods.removeMemberRole(this,t)}removeRoles(t){const e=this._roles.slice();if(t instanceof a)for(const n of t.values()){const t=e.indexOf(n.id);t>=0&&e.splice(t,1)}else for(const n of t){const t=e.indexOf(n instanceof s?n.id:n);t>=0&&e.splice(t,1)}return this.edit({roles:e})}setNickname(t){return this.edit({nick:t})}deleteDM(){return this.client.rest.methods.deleteChannel(this)}kick(){return this.client.rest.methods.kickGuildMember(this.guild,this)}ban(t=0){return this.client.rest.methods.banGuildMember(this.guild,this,t)}toString(){return`<@${this.nickname?"!":""}${this.user.id}>`}send(){}sendMessage(){}sendEmbed(){}sendFile(){}sendCode(){}}i.applyToClass(u),t.exports=u},function(t,e){t.exports=function(t,e=false,n=false){return e?t.replace(/```/g,"`​``"):n?t.replace(/\\(`|\\)/g,"$1").replace(/(`|\\)/g,"\\$1"):t.replace(/\\(\*|_|`|~|\\)/g,"$1").replace(/(\*|_|`|~|\\)/g,"\\$1")}},function(t,e,n){const i=n(0);class s{constructor(t,e){this.member=t,this.raw=e}serialize(){const t={};for(const e in i.PermissionFlags)t[e]=this.hasPermission(e);return t}hasPermission(t,e=false){return t=this.member.client.resolver.resolvePermission(t),!e&&(this.raw&i.PermissionFlags.ADMINISTRATOR)>0||(this.raw&t)>0}hasPermissions(t,e=false){return t.every(t=>this.hasPermission(t,e))}missingPermissions(t,e=false){return t.filter(t=>!this.hasPermission(t,e))}}t.exports=s},function(t,e,n){const i=n(6),s=n(8),r=n(10),o=n(7).Presence,a=n(14),h=n(0),u=n(3),c=n(4),l=n(153);class d{constructor(t,e){Object.defineProperty(this,"client",{value:t}),this.members=new u,this.channels=new u,this.roles=new u,this.presences=new u,e&&(e.unavailable?(this.available=!1,this.id=e.id):(this.available=!0,this.setup(e)))}setup(t){this.name=t.name,this.icon=t.icon,this.splash=t.splash,this.region=t.region,this.memberCount=t.member_count||this.memberCount,this.large=t.large||this.large,this.features=t.features,this.applicationID=t.application_id,this.emojis=new u;for(const e of t.emojis)this.emojis.set(e.id,new r(this,e));if(this.afkTimeout=t.afk_timeout,this.afkChannelID=t.afk_channel_id,this.embedEnabled=t.embed_enabled,this.verificationLevel=t.verification_level,this.joinedTimestamp=t.joined_at?new Date(t.joined_at).getTime():this.joinedTimestamp,this.id=t.id,this.available=!t.unavailable,this.features=t.features||this.features||[],t.members){this.members.clear();for(const e of t.members)this._addMember(e,!1)}if(t.owner_id&&(this.ownerID=t.owner_id),t.channels){this.channels.clear();for(const e of t.channels)this.client.dataManager.newChannel(e,this)}if(t.roles){this.roles.clear();for(const e of t.roles){const t=new s(this,e);this.roles.set(t.id,t)}}if(t.presences)for(const n of t.presences)this._setPresence(n.user.id,n);if(this._rawVoiceStates=new u,t.voice_states)for(const i of t.voice_states){this._rawVoiceStates.set(i.user_id,i);const t=this.members.get(i.user_id);t&&(t.serverMute=i.mute,t.serverDeaf=i.deaf,t.selfMute=i.self_mute,t.selfDeaf=i.self_deaf,t.voiceSessionID=i.session_id,t.voiceChannelID=i.channel_id,this.channels.get(i.channel_id).members.set(t.user.id,t))}}get createdTimestamp(){return this.id/4194304+14200704e5}get createdAt(){return new Date(this.createdTimestamp)}get joinedAt(){return new Date(this.joinedTimestamp)}get iconURL(){return this.icon?h.Endpoints.guildIcon(this.id,this.icon):null}get splashURL(){return this.splash?h.Endpoints.guildSplash(this.id,this.splash):null}get owner(){return this.members.get(this.ownerID)}get voiceConnection(){return this.client.browser?null:this.client.voice.connections.get(this.id)||null}get defaultChannel(){return this.channels.get(this.id)}member(t){return this.client.resolver.resolveGuildMember(this,t)}fetchBans(){return this.client.rest.methods.getGuildBans(this)}fetchInvites(){return this.client.rest.methods.getGuildInvites(this)}fetchWebhooks(){return this.client.rest.methods.getGuildWebhooks(this)}fetchMember(t){return this._fetchWaiter?Promise.reject(new Error("Already fetching guild members.")):(t=this.client.resolver.resolveUser(t),t?this.members.has(t.id)?Promise.resolve(this.members.get(t.id)):this.client.rest.methods.getGuildMember(this,t):Promise.reject(new Error("User is not cached. Use Client.fetchUser first.")))}fetchMembers(t=""){return new Promise((e,n)=>{if(this._fetchWaiter)throw new Error("Already fetching guild members in ${this.id}.");return this.memberCount===this.members.size?void e(this):(this._fetchWaiter=e,this.client.ws.send({op:h.OPCodes.REQUEST_GUILD_MEMBERS,d:{guild_id:this.id,query:t,limit:0}}),this._checkChunks(),void this.client.setTimeout(()=>n(new Error("Members didn't arrive in time.")),12e4))})}edit(t){return this.client.rest.methods.updateGuild(this,t)}setName(t){return this.edit({name:t})}setRegion(t){return this.edit({region:t})}setVerificationLevel(t){return this.edit({verificationLevel:t})}setAFKChannel(t){return this.edit({afkChannel:t})}setAFKTimeout(t){return this.edit({afkTimeout:t})}setIcon(t){return this.edit({icon:t})}setOwner(t){return this.edit({owner:t})}setSplash(t){return this.edit({splash:t})}ban(t,e=0){return this.client.rest.methods.banGuildMember(this,t,e)}unban(t){return this.client.rest.methods.unbanGuildMember(this,t)}pruneMembers(t,e=false){if("number"!=typeof t)throw new TypeError("Days must be a number.");return this.client.rest.methods.pruneGuildMembers(this,t,e)}sync(){this.client.user.bot||this.client.syncGuilds([this])}createChannel(t,e,n){return this.client.rest.methods.createChannel(this,t,e,n)}createRole(t){const e=this.client.rest.methods.createGuildRole(this);return t?e.then(e=>e.edit(t)):e}createEmoji(t,e){return new Promise(n=>{t.startsWith("data:")?n(this.client.rest.methods.createEmoji(this,t,e)):this.client.resolver.resolveBuffer(t).then(t=>n(this.client.rest.methods.createEmoji(this,t,e)))})}deleteEmoji(t){return t instanceof r||(t=this.emojis.get(t)),this.client.rest.methods.deleteEmoji(t)}leave(){return this.client.rest.methods.leaveGuild(this)}delete(){return this.client.rest.methods.deleteGuild(this)}setRolePosition(t,e){if("string"==typeof t&&(t=this.roles.get(t),!t))return Promise.reject(new Error("Supplied role is not a role or string."));if(e=Number(e),isNaN(e))return Promise.reject(new Error("Supplied position is not a number."));const n=Math.min(t.position,e),i=Math.max(t.position,e),s=this.roles.filter(t=>t.position>=n&&t.position<=i);e=e>t.position?s.first().position:s.last().position;const r=[];for(const o of s.values())r.push({id:o.id,position:o.id===t.id?e:o.position+(e`:this.name}}t.exports=n},function(t,e,n){const i=n(23),s=n(15);class r{constructor(t,e,n){t?(Object.defineProperty(this,"client",{value:t}),e&&this.setup(e)):(this.id=e,this.token=n,Object.defineProperty(this,"client",{value:this}))}setup(t){this.name=t.name,this.token=t.token,this.avatar=t.avatar,this.id=t.id,this.guildID=t.guild_id,this.channelID=t.channel_id,t.user&&(this.owner=t.user)}sendMessage(t,e={}){return this.client.rest.methods.sendWebhookMessage(this,t,e)}sendSlackMessage(t){return this.client.rest.methods.sendSlackWebhookMessage(this,t)}sendTTSMessage(t,e={}){return Object.assign(e,{tts:!0}),this.client.rest.methods.sendWebhookMessage(this,t,e)}sendFile(t,e,n,s={}){return e||(e="string"==typeof t?i.basename(t):t&&t.path?i.basename(t.path):"file.jpg"),this.client.resolver.resolveBuffer(t).then(t=>this.client.rest.methods.sendWebhookMessage(this,n,s,{file:t,name:e}))}sendCode(t,e,n={}){return n.split&&("object"!=typeof n.split&&(n.split={}),n.split.prepend||(n.split.prepend=`\`\`\`${t||""} -`),n.split.append||(n.split.append="\n```")),e=s(this.client.resolver.resolveString(e),!0),this.sendMessage(`\`\`\`${t||""} -${e} -\`\`\``,n)}edit(t=this.name,e){return e?this.client.resolver.resolveBuffer(e).then(e=>{const n=this.client.resolver.resolveBase64(e);return this.client.rest.methods.editWebhook(this,t,n)}):this.client.rest.methods.editWebhook(this,t).then(t=>{return this.setup(t),this})}delete(){return this.client.rest.methods.deleteWebhook(this)}}t.exports=r},function(t,e,n){"use strict";(function(t){function i(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}function s(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function r(t,e){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function g(t){return+t!=t&&(t=0),o.alloc(+t)}function _(t,e){if(o.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return F(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(t).length;default:if(i)return F(t).length;e=(""+e).toLowerCase(),i=!0}}function E(t,e,n){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,e>>>=0,n<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return L(this,e,n);case"utf8":case"utf-8":return S(this,e,n);case"ascii":return C(this,e,n);case"latin1":case"binary":return x(this,e,n);case"base64":return M(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,e,n);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function w(t,e,n){var i=t[e];t[e]=t[n],t[n]=i}function v(t,e,n,i,s){if(0===t.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=s?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(s)return-1;n=t.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof e&&(e=o.from(e,i)),o.isBuffer(e))return 0===e.length?-1:b(t,e,n,i,s);if("number"==typeof e)return e&=255,o.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):b(t,[e],n,i,s);throw new TypeError("val must be string, number or Buffer")}function b(t,e,n,i,s){function r(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}var o=1,a=t.length,h=e.length;if(void 0!==i&&(i=String(i).toLowerCase(),"ucs2"===i||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,n/=2}var u;if(s){var c=-1;for(u=n;ua&&(n=a-h),u=n;u>=0;u--){for(var l=!0,d=0;ds&&(i=s)):i=s;var r=e.length;if(r%2!==0)throw new TypeError("Invalid hex string");i>r/2&&(i=r/2);for(var o=0;o239?4:r>223?3:r>191?2:1;if(s+a<=n){var h,u,c,l;switch(a){case 1:r<128&&(o=r);break;case 2:h=t[s+1],128===(192&h)&&(l=(31&r)<<6|63&h,l>127&&(o=l));break;case 3:h=t[s+1],u=t[s+2],128===(192&h)&&128===(192&u)&&(l=(15&r)<<12|(63&h)<<6|63&u,l>2047&&(l<55296||l>57343)&&(o=l));break;case 4:h=t[s+1],u=t[s+2],c=t[s+3],128===(192&h)&&128===(192&u)&&128===(192&c)&&(l=(15&r)<<18|(63&h)<<12|(63&u)<<6|63&c,l>65535&&l<1114112&&(o=l))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),s+=a}return I(i)}function I(t){var e=t.length;if(e<=tt)return String.fromCharCode.apply(String,t);for(var n="",i=0;ii)&&(n=i);for(var s="",r=e;rn)throw new RangeError("Trying to access beyond buffer length")}function N(t,e,n,i,s,r){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>s||et.length)throw new RangeError("Index out of range")}function O(t,e,n,i){e<0&&(e=65535+e+1);for(var s=0,r=Math.min(t.length-n,2);s>>8*(i?s:1-s)}function B(t,e,n,i){e<0&&(e=4294967295+e+1);for(var s=0,r=Math.min(t.length-n,4);s>>8*(i?s:3-s)&255}function G(t,e,n,i,s,r){if(n+i>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function j(t,e,n,i,s){return s||G(t,e,n,4,3.4028234663852886e38,-3.4028234663852886e38),X.write(t,e,n,i,23,4),n+4}function q(t,e,n,i,s){return s||G(t,e,n,8,1.7976931348623157e308,-1.7976931348623157e308),X.write(t,e,n,i,52,8),n+8}function z(t){if(t=H(t).replace(et,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function H(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function W(t){return t<16?"0"+t.toString(16):t.toString(16)}function F(t,e){e=e||1/0;for(var n,i=t.length,s=null,r=[],o=0;o55295&&n<57344){if(!s){if(n>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===i){(e-=3)>-1&&r.push(239,191,189);continue}s=n;continue}if(n<56320){(e-=3)>-1&&r.push(239,191,189),s=n;continue}n=(s-55296<<10|n-56320)+65536}else s&&(e-=3)>-1&&r.push(239,191,189);if(s=null,n<128){if((e-=1)<0)break;r.push(n)}else if(n<2048){if((e-=2)<0)break;r.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;r.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return r}function Y(t){for(var e=[],n=0;n>8,s=n%256,r.push(s),r.push(i);return r}function K(t){return J.toByteArray(z(t))}function Z(t,e,n,i){for(var s=0;s=e.length||s>=t.length);++s)e[s+n]=t[s];return s}function $(t){return t!==t}/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var J=n(63),X=n(65),Q=n(66);e.Buffer=o,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),e.kMaxLength=s(),o.poolSize=8192,o._augment=function(t){return t.__proto__=o.prototype,t},o.from=function(t,e,n){return a(null,t,e,n)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(t,e,n){return u(null,t,e,n)},o.allocUnsafe=function(t){return c(null,t)},o.allocUnsafeSlow=function(t){return c(null,t)},o.isBuffer=function(t){return!(null==t||!t._isBuffer)},o.compare=function(t,e){if(!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,i=e.length,s=0,r=Math.min(n,i);s0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),""},o.prototype.compare=function(t,e,n,i,s){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),e<0||n>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&e>=n)return 0;if(i>=s)return-1;if(e>=n)return 1;if(e>>>=0,n>>>=0,i>>>=0,s>>>=0,this===t)return 0;for(var r=s-i,a=n-e,h=Math.min(r,a),u=this.slice(i,s),c=t.slice(e,n),l=0;ls)&&(n=s),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var r=!1;;)switch(i){case"hex":return y(this,t,e,n);case"utf8":case"utf-8":return A(this,t,e,n);case"ascii":return k(this,t,e,n);case"latin1":case"binary":return R(this,t,e,n);case"base64":return T(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,e,n);default:if(r)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),r=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var tt=4096;o.prototype.slice=function(t,e){var n=this.length;t=~~t,e=void 0===e?n:~~e,t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),e0&&(s*=256);)i+=this[t+--e]*s;return i},o.prototype.readUInt8=function(t,e){return e||P(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,e){return e||P(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,e){return e||P(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,e){return e||P(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,e){return e||P(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,e,n){t|=0,e|=0,n||P(t,e,this.length);for(var i=this[t],s=1,r=0;++r=s&&(i-=Math.pow(2,8*e)),i},o.prototype.readIntBE=function(t,e,n){t|=0,e|=0,n||P(t,e,this.length);for(var i=e,s=1,r=this[t+--i];i>0&&(s*=256);)r+=this[t+--i]*s;return s*=128,r>=s&&(r-=Math.pow(2,8*e)),r},o.prototype.readInt8=function(t,e){return e||P(t,1,this.length),128&this[t]?(255-this[t]+1)*-1:this[t]},o.prototype.readInt16LE=function(t,e){e||P(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(t,e){e||P(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(t,e){return e||P(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return e||P(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,e){return e||P(t,4,this.length),X.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return e||P(t,4,this.length),X.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return e||P(t,8,this.length),X.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return e||P(t,8,this.length),X.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,e,n,i){if(t=+t,e|=0,n|=0,!i){var s=Math.pow(2,8*n)-1;N(this,t,e,n,s,0)}var r=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+r]=t/o&255;return e+n},o.prototype.writeUInt8=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,1,255,0),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},o.prototype.writeUInt16LE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):O(this,t,e,!0),e+2},o.prototype.writeUInt16BE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):O(this,t,e,!1),e+2},o.prototype.writeUInt32LE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):B(this,t,e,!0),e+4},o.prototype.writeUInt32BE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):B(this,t,e,!1),e+4},o.prototype.writeIntLE=function(t,e,n,i){if(t=+t,e|=0,!i){var s=Math.pow(2,8*n-1);N(this,t,e,n,s-1,-s)}var r=0,o=1,a=0;for(this[e]=255&t;++r>0)-a&255;return e+n},o.prototype.writeIntBE=function(t,e,n,i){if(t=+t,e|=0,!i){var s=Math.pow(2,8*n-1);N(this,t,e,n,s-1,-s)}var r=n-1,o=1,a=0;for(this[e+r]=255&t;--r>=0&&(o*=256);)t<0&&0===a&&0!==this[e+r+1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+n},o.prototype.writeInt8=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,1,127,-128),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):O(this,t,e,!0),e+2},o.prototype.writeInt16BE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):O(this,t,e,!1),e+2},o.prototype.writeInt32LE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):B(this,t,e,!0),e+4},o.prototype.writeInt32BE=function(t,e,n){return t=+t,e|=0,n||N(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):B(this,t,e,!1),e+4},o.prototype.writeFloatLE=function(t,e,n){return j(this,t,e,!0,n)},o.prototype.writeFloatBE=function(t,e,n){return j(this,t,e,!1,n)},o.prototype.writeDoubleLE=function(t,e,n){return q(this,t,e,!0,n)},o.prototype.writeDoubleBE=function(t,e,n){return q(this,t,e,!1,n)},o.prototype.copy=function(t,e,n,i){if(n||(n=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e=0;--s)t[s+e]=this[s+n];else if(r<1e3||!o.TYPED_ARRAY_SUPPORT)for(s=0;s>>=0,n=void 0===n?this.length:n>>>0,t||(t=0);var r;if("number"==typeof t)for(r=e;r0&&this._events[t].length>s&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function n(){this.removeListener(t,n),s||(s=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var s=!1;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var n,s,o,a;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(n=this._events[t],o=n.length,s=-1,n===e||i(n.listener)&&n.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(r(n)){for(a=o;a-- >0;)if(n[a]===e||n[a].listener&&n[a].listener===e){s=a;break}if(s<0)return this;1===n.length?(n.length=0,delete this._events[t]):n.splice(s,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[t],i(n))this.removeListener(t,n);else if(n)for(;n.length;)this.removeListener(t,n[n.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,n){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},function(t,e,n){(function(t){function n(t,e){for(var n=0,i=t.length-1;i>=0;i--){var s=t[i];"."===s?t.splice(i,1):".."===s?(t.splice(i,1),n++):n&&(t.splice(i,1),n--)}if(e)for(;n--;n)t.unshift("..");return t}function i(t,e){if(t.filter)return t.filter(e);for(var n=[],i=0;i=-1&&!s;r--){var o=r>=0?arguments[r]:t.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(e=o+"/"+e,s="/"===o.charAt(0))}return e=n(i(e.split("/"),function(t){return!!t}),!s).join("/"),(s?"/":"")+e||"."},e.normalize=function(t){var s=e.isAbsolute(t),r="/"===o(t,-1);return t=n(i(t.split("/"),function(t){return!!t}),!s).join("/"),t||s||(t="."),t&&r&&(t+="/"),(s?"/":"")+t},e.isAbsolute=function(t){return"/"===t.charAt(0)},e.join=function(){var t=Array.prototype.slice.call(arguments,0);return e.normalize(i(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},e.relative=function(t,n){function i(t){for(var e=0;e=0&&""===t[n];n--);return e>n?[]:t.slice(e,n-e+1)}t=e.resolve(t).substr(1),n=e.resolve(n).substr(1);for(var s=i(t.split("/")),r=i(n.split("/")),o=Math.min(s.length,r.length),a=o,h=0;h1)for(var n=1;n=0?"&":"?")+t),this._sort){var e=this.url.indexOf("?");if(e>=0){var n=this.url.substring(e+1).split("&");g(this._sort)?n.sort(this._sort):n.sort(),this.url=this.url.substring(0,e)+"?"+n.join("&")}}},c.prototype._isHost=function(t){return t&&"object"==typeof t&&!Array.isArray(t)&&"[object Object]"!==Object.prototype.toString.call(t)},c.prototype.end=function(t){var e=this,n=this.xhr=E.getXHR(),s=this._formData||this._data;this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=t||i,n.onreadystatechange=function(){var t=n.readyState;if(t>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4==t){var i;try{i=n.status}catch(t){i=0}if(!i){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}};var r=function(t,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{n.onprogress=r.bind(null,"download"),n.upload&&(n.upload.onprogress=r.bind(null,"upload"))}catch(t){}if(this._appendQueryString(),this._setTimeouts(),this.username&&this.password?n.open(this.method,this.url,!0,this.username,this.password):n.open(this.method,this.url,!0),this._withCredentials&&(n.withCredentials=!0),!this._formData&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof s&&!this._isHost(s)){var o=this._header["content-type"],a=this._serializer||E.serialize[o?o.split(";")[0]:""];!a&&h(o)&&(a=E.serialize["application/json"]),a&&(s=a(s))}for(var u in this.header)null!=this.header[u]&&n.setRequestHeader(u,this.header[u]);return this._responseType&&(n.responseType=this._responseType),this.emit("request",this),n.send("undefined"!=typeof s?s:null),this},E.get=function(t,e,n){var i=E("GET",t);return"function"==typeof e&&(n=e,e=null),e&&i.query(e),n&&i.end(n),i},E.head=function(t,e,n){var i=E("HEAD",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},E.options=function(t,e,n){var i=E("OPTIONS",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},E.del=l,E.delete=l,E.patch=function(t,e,n){var i=E("PATCH",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},E.post=function(t,e,n){var i=E("POST",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i},E.put=function(t,e,n){var i=E("PUT",t);return"function"==typeof e&&(n=e,e=null),e&&i.send(e),n&&i.end(n),i}},function(t,e){function n(t){return null!==t&&"object"==typeof t}t.exports=n},function(t,e){t.exports={name:"discord.js",version:"11.0.0",description:"A powerful library for interacting with the Discord API",main:"./src/index",types:"./typings/index.d.ts",scripts:{test:"eslint src && docgen --source src --custom docs/index.yml",docs:"docgen --source src --custom docs/index.yml --output docs/docs.json","test-docs":"docgen --source src --custom docs",lint:"eslint src","web-dist":"node ./node_modules/parallel-webpack/bin/run.js"},repository:{type:"git",url:"git+https://github.com/hydrabolt/discord.js.git"},keywords:["discord","api","bot","client","node","discordapp"],author:"Amish Shah ",license:"Apache-2.0",bugs:{url:"https://github.com/hydrabolt/discord.js/issues"},homepage:"https://github.com/hydrabolt/discord.js#readme",runkitExampleFilename:"./docs/examples/ping.js",dependencies:{"@types/node":"^6.0.0",pako:"^1.0.0",superagent:"^3.3.0",tweetnacl:"^0.14.0",ws:"^1.1.0"},peerDependencies:{erlpack:"hammerandchisel/erlpack#master","node-opus":"^0.2.0",opusscript:"^0.0.1",uws:"^0.12.0"},devDependencies:{"discord.js-docgen":"hydrabolt/discord.js-docgen#master",eslint:"^3.12.0","parallel-webpack":"^1.6.0","uglify-js":"mishoo/UglifyJS2#harmony",webpack:"2.2.0-rc.3"},engines:{node:">=6.0.0"},browser:{ws:!1,uws:!1,erlpack:!1,opusscript:!1,"node-opus":!1,"tweet-nacl":!1,"src/sharding/Shard.js":!1,"src/sharding/ShardClientUtil.js":!1,"src/sharding/ShardingManager.js":!1,"src/client/voice/dispatcher/StreamDispatcher.js":!1,"src/client/voice/opus/BaseOpusEngine.js":!1,"src/client/voice/opus/NodeOpusEngine.js":!1,"src/client/voice/opus/OpusEngineList.js":!1,"src/client/voice/opus/OpusScriptEngine.js":!1,"src/client/voice/pcm/ConverterEngine.js":!1,"src/client/voice/pcm/ConverterEngineList.js":!1,"src/client/voice/pcm/FfmpegConverterEngine.js":!1,"src/client/voice/player/AudioPlayer.js":!1,"src/client/voice/player/BasePlayer.js":!1,"src/client/voice/player/DefaultPlayer.js":!1,"src/client/voice/receiver/VoiceReadable.js":!1,"src/client/voice/receiver/VoiceReceiver.js":!1,"src/client/voice/util/SecretKey.js":!1,"src/client/voice/ClientVoiceManager.js":!1,"src/client/voice/VoiceConnection.js":!1,"src/client/voice/VoiceUDPClient.js":!1,"src/client/voice/VoiceWebSocket.js":!1}}},function(t,e,n){const i=n(6),s=n(37);class r extends s{setup(t){super.setup(t),this.flags=t.flags,this.owner=new i(this.client,t.owner)}}t.exports=r},function(t,e,n){const i=n(6),s=n(3);class r extends i{setup(t){super.setup(t),this.verified=t.verified,this.email=t.email,this.localPresence={},this._typing=new Map,this.friends=new s,this.blocked=new s,this.notes=new s}edit(t){return this.client.rest.methods.updateCurrentUser(t)}setUsername(t,e){return this.client.rest.methods.updateCurrentUser({username:t},e)}setEmail(t,e){return this.client.rest.methods.updateCurrentUser({email:t},e)}setPassword(t,e){return this.client.rest.methods.updateCurrentUser({password:t},e)}setAvatar(t){return t.startsWith("data:")?this.client.rest.methods.updateCurrentUser({avatar:t}):this.client.resolver.resolveBuffer(t).then(t=>this.client.rest.methods.updateCurrentUser({avatar:t}))}setPresence(t){return new Promise(e=>{let n=this.localPresence.status||this.presence.status,i=this.localPresence.game,s=this.localPresence.afk||this.presence.afk;if(!i&&this.presence.game&&(i={name:this.presence.game.name,type:this.presence.game.type,url:this.presence.game.url}),t.status){if("string"!=typeof t.status)throw new TypeError("Status must be a string");n=t.status}t.game&&(i=t.game,i.url&&(i.type=1)),"undefined"!=typeof t.afk&&(s=t.afk),s=Boolean(s),this.localPresence={status:n,game:i,afk:s},this.localPresence.since=0,this.localPresence.game=this.localPresence.game||null,this.client.ws.send({op:3,d:this.localPresence}),this.client._setPresence(this.id,this.localPresence),e(this)})}setStatus(t){return this.setPresence({status:t})}setGame(t,e){return this.setPresence({game:{name:t,url:e}})}setAFK(t){return this.setPresence({afk:t})}fetchMentions(t={limit:25,roles:true,everyone:true,guild:null}){return this.client.rest.methods.fetchMentions(t)}addFriend(t){return t=this.client.resolver.resolveUser(t),this.client.rest.methods.addFriend(t)}removeFriend(t){return t=this.client.resolver.resolveUser(t),this.client.rest.methods.removeFriend(t)}createGuild(t,e,n=null){return n?n.startsWith("data:")?this.client.rest.methods.createGuild({name:t,icon:n,region:e}):this.client.resolver.resolveBuffer(n).then(n=>this.client.rest.methods.createGuild({name:t,icon:n,region:e})):this.client.rest.methods.createGuild({name:t,icon:n,region:e})}}t.exports=r},function(t,e,n){const i=n(9),s=n(12),r=n(3);class o extends i{constructor(t,e){super(t,e),this.type="dm",this.messages=new r,this._typing=new Map}setup(t){super.setup(t),this.recipient=this.client.dataManager.newUser(t.recipients[0]),this.lastMessageID=t.last_message_id}toString(){return this.recipient.toString()}send(){}sendMessage(){}sendEmbed(){}sendFile(){}sendCode(){}fetchMessage(){}fetchMessages(){}fetchPinnedMessages(){}startTyping(){}stopTyping(){}get typing(){}get typingCount(){}createCollector(){}awaitMessages(){}bulkDelete(){}_cacheMessage(){}}s.applyToClass(o,!0),t.exports=o},function(t,e,n){const i=n(9),s=n(12),r=n(3);class o extends i{constructor(t,e){super(t,e),this.type="group",this.messages=new r,this._typing=new Map}setup(t){if(super.setup(t),this.name=t.name,this.icon=t.icon,this.ownerID=t.owner_id,this.recipients||(this.recipients=new r),t.recipients)for(const e of t.recipients){const t=this.client.dataManager.newUser(e);this.recipients.set(t.id,t)}this.lastMessageID=t.last_message_id}get owner(){return this.client.users.get(this.ownerID)}equals(t){const e=t&&this.id===t.id&&this.name===t.name&&this.icon===t.icon&&this.ownerID===t.ownerID; -return e?this.recipients.equals(t.recipients):e}toString(){return this.name}send(){}sendMessage(){}sendEmbed(){}sendFile(){}sendCode(){}fetchMessage(){}fetchMessages(){}fetchPinnedMessages(){}startTyping(){}stopTyping(){}get typing(){}get typingCount(){}createCollector(){}awaitMessages(){}bulkDelete(){}_cacheMessage(){}}s.applyToClass(o,!0),t.exports=o},function(t,e,n){const i=n(38),s=n(39),r=n(0);class o{constructor(t,e){Object.defineProperty(this,"client",{value:t}),this.setup(e)}setup(t){this.guild=this.client.guilds.get(t.guild.id)||new i(this.client,t.guild),this.code=t.code,this.temporary=t.temporary,this.maxAge=t.max_age,this.uses=t.uses,this.maxUses=t.max_uses,t.inviter&&(this.inviter=this.client.dataManager.newUser(t.inviter)),this.channel=this.client.channels.get(t.channel.id)||new s(this.client,t.channel),this.createdTimestamp=new Date(t.created_at).getTime()}get createdAt(){return new Date(this.createdTimestamp)}get expiresTimestamp(){return this.createdTimestamp+1e3*this.maxAge}get expiresAt(){return new Date(this.expiresTimestamp)}get url(){return r.Endpoints.inviteLink(this.code)}delete(){return this.client.rest.methods.deleteInvite(this)}toString(){return this.url}}t.exports=o},function(t,e){class n{constructor(t,e){Object.defineProperty(this,"client",{value:t.client}),this.message=t,this.setup(e)}setup(t){this.id=t.id,this.filename=t.filename,this.filesize=t.size,this.url=t.url,this.proxyURL=t.proxy_url,this.height=t.height,this.width=t.width}}t.exports=n},function(t,e,n){const i=n(21).EventEmitter,s=n(3);class r extends i{constructor(t,e,n={}){super(),this.channel=t,this.filter=e,this.options=n,this.ended=!1,this.collected=new s,this.listener=(t=>this.verify(t)),this.channel.client.on("message",this.listener),n.time&&this.channel.client.setTimeout(()=>this.stop("time"),n.time)}verify(t){return(!this.channel||this.channel.id===t.channel.id)&&(!!this.filter(t,this)&&(this.collected.set(t.id,t),this.emit("message",t,this),this.collected.size>=this.options.maxMatches?this.stop("matchesLimit"):this.options.max&&this.collected.size===this.options.max&&this.stop("limit"),!0))}get next(){return new Promise((t,e)=>{if(this.ended)return void e(this.collected);const n=()=>{this.removeListener("message",i),this.removeListener("end",s)},i=(...e)=>{n(),t(...e)},s=(...t)=>{n(),e(...t)};this.once("message",i),this.once("end",s)})}stop(t="user"){this.ended||(this.ended=!0,this.channel.client.removeListener("message",this.listener),this.emit("end",this.collected,t))}}t.exports=r},function(t,e){class n{constructor(t,e){Object.defineProperty(this,"client",{value:t.client}),this.message=t,this.setup(e)}setup(t){if(this.type=t.type,this.title=t.title,this.description=t.description,this.url=t.url,this.color=t.color,this.fields=[],t.fields)for(const e of t.fields)this.fields.push(new o(this,e));this.createdTimestamp=t.timestamp,this.thumbnail=t.thumbnail?new i(this,t.thumbnail):null,this.author=t.author?new r(this,t.author):null,this.provider=t.provider?new s(this,t.provider):null,this.footer=t.footer?new a(this,t.footer):null}get createdAt(){return new Date(this.createdTimestamp)}get hexColor(){let t=this.color.toString(16);for(;t.length<6;)t=`0${t}`;return`#${t}`}}class i{constructor(t,e){this.embed=t,this.setup(e)}setup(t){this.url=t.url,this.proxyURL=t.proxy_url,this.height=t.height,this.width=t.width}}class s{constructor(t,e){this.embed=t,this.setup(e)}setup(t){this.name=t.name,this.url=t.url}}class r{constructor(t,e){this.embed=t,this.setup(e)}setup(t){this.name=t.name,this.url=t.url,this.iconURL=t.icon_url}}class o{constructor(t,e){this.embed=t,this.setup(e)}setup(t){this.name=t.name,this.value=t.value,this.inline=t.inline}}class a{constructor(t,e){this.embed=t,this.setup(e)}setup(t){this.text=t.text,this.iconURL=t.icon_url,this.proxyIconUrl=t.proxy_icon_url}}n.Thumbnail=i,n.Provider=s,n.Author=r,n.Field=o,n.Footer=a,t.exports=n},function(t,e,n){const i=n(3),s=n(10),r=n(18);class o{constructor(t,e,n,s){this.message=t,this.me=s,this.count=n||0,this.users=new i,this._emoji=new r(this,e.name,e.id)}get emoji(){if(this._emoji instanceof s)return this._emoji;if(this._emoji.id){const t=this.message.client.emojis;if(t.has(this._emoji.id)){const e=t.get(this._emoji.id);return this._emoji=e,e}}return this._emoji}remove(t=this.message.client.user){const e=this.message;return t=this.message.client.resolver.resolveUserID(t),t?e.client.rest.methods.removeMessageReaction(e,this.emoji.identifier,t):Promise.reject("Couldn't resolve the user ID to remove from the reaction.")}fetchUsers(t=100){const e=this.message;return e.client.rest.methods.getMessageReactionUsers(e,this.emoji.identifier,t).then(t=>{this.users=new i;for(const e of t){const t=this.message.client.dataManager.newUser(e);this.users.set(t.id,t)}return this.count=this.users.size,t})}}t.exports=o},function(t,e){class n{constructor(t,e){Object.defineProperty(this,"client",{value:t}),this.setup(e)}setup(t){this.id=t.id,this.name=t.name,this.description=t.description,this.icon=t.icon,this.iconURL=`https://cdn.discordapp.com/app-icons/${this.id}/${this.icon}.jpg`,this.rpcOrigins=t.rpc_origins}get createdTimestamp(){return this.id/4194304+14200704e5}get createdAt(){return new Date(this.createdTimestamp)}toString(){return this.name}}t.exports=n},function(t,e){class n{constructor(t,e){Object.defineProperty(this,"client",{value:t}),this.setup(e)}setup(t){this.id=t.id,this.name=t.name,this.icon=t.icon,this.splash=t.splash}}t.exports=n},function(t,e,n){const i=n(0);class s{constructor(t,e){Object.defineProperty(this,"client",{value:t}),this.setup(e)}setup(t){this.id=t.id,this.name=t.name,this.type=i.ChannelTypes.text===t.type?"text":"voice"}}t.exports=s},function(t,e){class n{constructor(t,e){Object.defineProperty(this,"channel",{value:t}),e&&this.setup(e)}setup(t){this.id=t.id,this.type=t.type,this.deny=t.deny,this.allow=t.allow}delete(){return this.channel.client.rest.methods.deletePermissionOverwrites(this)}}t.exports=n},function(t,e,n){const i=n(13),s=n(12),r=n(3);class o extends i{constructor(t,e){super(t,e),this.type="text",this.messages=new r,this._typing=new Map}setup(t){super.setup(t),this.topic=t.topic,this.lastMessageID=t.last_message_id}get members(){const t=new r;for(const e of this.guild.members.values())this.permissionsFor(e).hasPermission("READ_MESSAGES")&&t.set(e.id,e);return t}fetchWebhooks(){return this.client.rest.methods.getChannelWebhooks(this)}createWebhook(t,e){return new Promise(n=>{e.startsWith("data:")?n(this.client.rest.methods.createWebhook(this,t,e)):this.client.resolver.resolveBuffer(e).then(e=>n(this.client.rest.methods.createWebhook(this,t,e)))})}send(){}sendMessage(){}sendEmbed(){}sendFile(){}sendCode(){}fetchMessage(){}fetchMessages(){}fetchPinnedMessages(){}startTyping(){}stopTyping(){}get typing(){}get typingCount(){}createCollector(){}awaitMessages(){}bulkDelete(){}_cacheMessage(){}}s.applyToClass(o,!0),t.exports=o},function(t,e,n){const i=n(13),s=n(3);class r extends i{constructor(t,e){super(t,e),this.members=new s,this.type="voice"}setup(t){super.setup(t),this.bitrate=t.bitrate,this.userLimit=t.user_limit}get connection(){const t=this.guild.voiceConnection;return t&&t.channel.id===this.id?t:null}get joinable(){return!this.client.browser&&this.permissionsFor(this.client.user).hasPermission("CONNECT")}get speakable(){return this.permissionsFor(this.client.user).hasPermission("SPEAK")}setBitrate(t){return this.edit({bitrate:t})}setUserLimit(t){return this.edit({userLimit:t})}join(){return this.client.browser?Promise.reject(new Error("Voice connections are not available in browsers.")):this.client.voice.joinChannel(this)}leave(){if(!this.client.browser){const t=this.client.voice.connections.get(this.guild.id);t&&t.channel.id===this.id&&t.disconnect()}}}t.exports=r},function(t,e){t.exports=function(t,{maxLength=1950,char="\n",prepend="",append=""}={}){if(t.length<=maxLength)return t;const e=t.split(char);if(1===e.length)throw new Error("Message exceeds the max length and contains no split characters.");const n=[""];let i=0;for(let s=0;smaxLength&&(n[i]+=append,n.push(prepend),i++),n[i]+=(n[i].length>0&&n[i]!==prepend?char:"")+e[s];return n}},function(t,e,n){"use strict";function i(t,e){if(e<65537&&(t.subarray&&o||!t.subarray&&r))return String.fromCharCode.apply(null,s.shrinkBuf(t,e));for(var n="",i=0;i=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;a[254]=a[254]=1,e.string2buf=function(t){var e,n,i,r,o,a=t.length,h=0;for(r=0;r>>6,e[o++]=128|63&n):n<65536?(e[o++]=224|n>>>12,e[o++]=128|n>>>6&63,e[o++]=128|63&n):(e[o++]=240|n>>>18,e[o++]=128|n>>>12&63,e[o++]=128|n>>>6&63,e[o++]=128|63&n);return e},e.buf2binstring=function(t){return i(t,t.length)},e.binstring2buf=function(t){for(var e=new s.Buf8(t.length),n=0,i=e.length;n4)u[s++]=65533,n+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&n1?u[s++]=65533:r<65536?u[s++]=r:(r-=65536,u[s++]=55296|r>>10&1023,u[s++]=56320|1023&r)}return i(u,s)},e.utf8border=function(t,e){var n;for(e=e||t.length,e>t.length&&(e=t.length),n=e-1;n>=0&&128===(192&t[n]);)n--;return n<0?e:0===n?e:n+a[t[n]]>e?n:e}},function(t,e,n){"use strict";function i(t,e,n,i){for(var s=65535&t|0,r=t>>>16&65535|0,o=0;0!==n;){o=n>2e3?2e3:n,n-=o;do s=s+e[i++]|0,r=r+s|0;while(--o);s%=65521,r%=65521}return s|r<<16|0}t.exports=i},function(t,e,n){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(t,e,n){"use strict";function i(){for(var t,e=[],n=0;n<256;n++){t=n;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[n]=t}return e}function s(t,e,n,i){var s=r,o=i+n;t^=-1;for(var a=i;a>>8^s[255&(t^e[a])];return t^-1}var r=i();t.exports=s},function(t,e,n){"use strict";function i(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}t.exports=i},function(t,e){},function(t,e,n){(function(e){const i=n(23),s=n(49),r=n(25),o=n(0),a=n(53),h=n(6),u=n(11),c=n(17),l=n(9),d=n(14),f=n(10),p=n(18);class m{constructor(t){this.client=t}resolveUser(t){return t instanceof h?t:"string"==typeof t?this.client.users.get(t)||null:t instanceof d?t.user:t instanceof u?t.author:t instanceof c?t.owner:null}resolveUserID(t){return t instanceof h||t instanceof d?t.id:"string"==typeof t?t||null:t instanceof u?t.author.id:t instanceof c?t.ownerID:null}resolveGuild(t){return t instanceof c?t:"string"==typeof t?this.client.guilds.get(t)||null:null}resolveGuildMember(t,e){return e instanceof d?e:(t=this.resolveGuild(t),e=this.resolveUser(e),t&&e?t.members.get(e.id)||null:null)}resolveChannel(t){return t instanceof l?t:t instanceof u?t.channel:t instanceof c?t.channels.get(t.id)||null:"string"==typeof t?this.client.channels.get(t)||null:null}resolveInviteCode(t){const e=/discord(?:app)?\.(?:gg|com\/invite)\/([a-z0-9]{5})/i,n=e.exec(t);return n&&n[1]?n[1]:t}resolvePermission(t){if("string"==typeof t&&(t=o.PermissionFlags[t]),"number"!=typeof t||t<1)throw new Error(o.Errors.NOT_A_PERMISSION);return t}resolvePermissions(t){let e=0;for(const n of t)e|=this.resolvePermission(n);return e}resolveString(t){return"string"==typeof t?t:t instanceof Array?t.join("\n"):String(t)}resolveBase64(t){return t instanceof e?`data:image/jpg;base64,${t.toString("base64")}`:t}resolveBuffer(t){return t instanceof e?Promise.resolve(t):this.client.browser&&t instanceof ArrayBuffer?Promise.resolve(a(t)):"string"==typeof t?new Promise((n,o)=>{if(/^https?:\/\//.test(t)){const i=r.get(t).set("Content-Type","blob");this.client.browser&&i.responseType("arraybuffer"),i.end((t,i)=>{return t?o(t):this.client.browser?n(a(i.xhr.response)):i.body instanceof e?n(i.body):o(new TypeError("The response body isn't a Buffer."))})}else{const e=i.resolve(t);s.stat(e,(t,i)=>{if(t&&o(t),!i||!i.isFile())throw new Error(`The file could not be found: ${e}`);s.readFile(e,(t,e)=>{t?o(t):n(e)})})}}):Promise.reject(new TypeError("The resource must be a string or Buffer."))}resolveEmojiIdentifier(t){return t instanceof f||t instanceof p?t.identifier:"string"!=typeof t||t.includes("%")?null:encodeURIComponent(t)}}t.exports=m}).call(e,n(20).Buffer)},function(t,e,n){const i=n(114),s=n(111),r=n(113),o=n(112),a=n(110),h=n(0);class u{constructor(t){this.client=t,this.handlers={},this.userAgentManager=new i(this),this.methods=new s(this),this.rateLimitedEndpoints={},this.globallyRateLimited=!1}push(t,e){return new Promise((n,i)=>{t.push({request:e,resolve:n,reject:i})})}getRequestHandler(){switch(this.client.options.apiRequestMethod){case"sequential":return r;case"burst":return o;default:throw new Error(h.Errors.INVALID_RATE_LIMIT_METHOD)}}makeRequest(t,e,n,i,s){const r=new a(this,t,e,n,i,s);if(!this.handlers[r.route]){const t=this.getRequestHandler();this.handlers[r.route]=new t(this,r.route)}return this.push(this.handlers[r.route],r)}}t.exports=u},function(t,e){class n{constructor(t){this.restManager=t,this.queue=[]}get globalLimit(){return this.restManager.globallyRateLimited}set globalLimit(t){this.restManager.globallyRateLimited=t}push(t){this.queue.push(t)}handle(){}}t.exports=n},function(t,e,n){(function(e){function n(t){const n=new e(t.byteLength),i=new Uint8Array(t);for(var s=0;s0&&this.setInterval(this.sweepMessages.bind(this),1e3*this.options.messageSweepInterval)}get status(){return this.ws.status}get uptime(){return this.readyAt?Date.now()-this.readyAt:null}get ping(){return this.pings.reduce((t,e)=>t+e,0)/this.pings.length}get voiceConnections(){return this.browser?new Collection:this.voice.connections}get emojis(){const t=new Collection;for(const e of this.guilds.values())for(const n of e.emojis.values())t.set(n.id,n);return t}get readyTimestamp(){return this.readyAt?this.readyAt.getTime():null}get browser(){return"undefined"!=typeof window}login(t){return this.rest.methods.login(t)}destroy(){for(const t of this._timeouts)clearTimeout(t);for(const e of this._intervals)clearInterval(e);return this._timeouts.clear(),this._intervals.clear(),this.manager.destroy()}syncGuilds(t=this.guilds){this.user.bot||this.ws.send({op:12,d:t instanceof Collection?t.keyArray():t.map(t=>t.id)})}fetchUser(t){return this.users.has(t)?Promise.resolve(this.users.get(t)):this.rest.methods.getUser(t)}fetchInvite(t){const e=this.resolver.resolveInviteCode(t);return this.rest.methods.getInvite(e)}fetchWebhook(t,e){return this.rest.methods.getWebhook(t,e)}sweepMessages(t=this.options.messageCacheLifetime){if("number"!=typeof t||isNaN(t))throw new TypeError("The lifetime must be a number.");if(t<=0)return this.emit("debug","Didn't sweep messages - lifetime is unlimited"),-1;const e=1e3*t,n=Date.now();let i=0,s=0;for(const r of this.channels.values())if(r.messages){i++;for(const t of r.messages.values())n-(t.editedTimestamp||t.createdTimestamp)>e&&(r.messages.delete(t.id),s++)}return this.emit("debug",`Swept ${s} messages older than ${t} seconds in ${i} text-based channels`),s}fetchApplication(){if(!this.user.bot)throw new Error(Constants.Errors.NO_BOT_ACCOUNT);return this.rest.methods.getMyApplication()}generateInvite(t){return t?t instanceof Array&&(t=this.resolver.resolvePermissions(t)):t=0,this.fetchApplication().then(e=>`https://discordapp.com/oauth2/authorize?client_id=${e.id}&permissions=${t}&scope=bot`)}setTimeout(t,e,...n){const i=setTimeout(()=>{t(),this._timeouts.delete(i)},e,...n);return this._timeouts.add(i),i}clearTimeout(t){clearTimeout(t),this._timeouts.delete(t)}setInterval(t,e,...n){const i=setInterval(t,e,...n);return this._intervals.add(i),i}clearInterval(t){clearInterval(t),this._intervals.delete(t)}_pong(t){this.pings.unshift(Date.now()-t),this.pings.length>3&&(this.pings.length=3),this.ws.lastHeartbeatAck=!0}_setPresence(t,e){return this.presences.get(t)?void this.presences.get(t).update(e):void this.presences.set(t,new Presence(e))}_eval(script){return eval(script)}_validateOptions(t=this.options){if("number"!=typeof t.shardCount||isNaN(t.shardCount))throw new TypeError("The shardCount option must be a number.");if("number"!=typeof t.shardId||isNaN(t.shardId))throw new TypeError("The shardId option must be a number.");if(t.shardCount<0)throw new RangeError("The shardCount option must be at least 0.");if(t.shardId<0)throw new RangeError("The shardId option must be at least 0.");if(0!==t.shardId&&t.shardId>=t.shardCount)throw new RangeError("The shardId option must be less than shardCount.");if("number"!=typeof t.messageCacheMaxSize||isNaN(t.messageCacheMaxSize))throw new TypeError("The messageCacheMaxSize option must be a number.");if("number"!=typeof t.messageCacheLifetime||isNaN(t.messageCacheLifetime))throw new TypeError("The messageCacheLifetime option must be a number.");if("number"!=typeof t.messageSweepInterval||isNaN(t.messageSweepInterval))throw new TypeError("The messageSweepInterval option must be a number.");if("boolean"!=typeof t.fetchAllMembers)throw new TypeError("The fetchAllMembers option must be a boolean.");if("boolean"!=typeof t.disableEveryone)throw new TypeError("The disableEveryone option must be a boolean.");if("number"!=typeof t.restWsBridgeTimeout||isNaN(t.restWsBridgeTimeout))throw new TypeError("The restWsBridgeTimeout option must be a number.");if(!(t.disabledEvents instanceof Array))throw new TypeError("The disabledEvents option must be an Array.")}}module.exports=Client}).call(exports,__webpack_require__(24))},function(t,e,n){const i=n(19),s=n(51),r=n(50),o=n(54),a=n(0);class h extends i{constructor(t,e,n){super(null,t,e),this.options=o(a.DefaultOptions,n),this.rest=new s(this),this.resolver=new r(this)}}t.exports=h},function(t,e,n){t.exports={Client:n(55),WebhookClient:n(56),Shard:n(60),ShardClientUtil:n(61),ShardingManager:n(62),Collection:n(3),splitMessage:n(43),escapeMarkdown:n(15),fetchRecommendedShards:n(59),Channel:n(9),ClientOAuth2Application:n(28),ClientUser:n(29),DMChannel:n(30),Emoji:n(10),EvaluatedPermissions:n(16),Game:n(7).Game,GroupDMChannel:n(31),Guild:n(17),GuildChannel:n(13),GuildMember:n(14),Invite:n(32),Message:n(11),MessageAttachment:n(33),MessageCollector:n(34),MessageEmbed:n(35),MessageReaction:n(36),OAuth2Application:n(37),PartialGuild:n(38),PartialGuildChannel:n(39),PermissionOverwrites:n(40),Presence:n(7).Presence,ReactionEmoji:n(18),RichEmbed:n(58),Role:n(8),TextChannel:n(41),User:n(6),VoiceChannel:n(42),Webhook:n(19),version:n(27).version,Constants:n(0)},"undefined"!=typeof window&&(window.Discord=t.exports)},function(t,e){function n(t){return"string"==typeof t?t:t instanceof Array?t.join("\n"):String(t)}class i{constructor(t={}){this.title=t.title,this.description=t.description,this.url=t.url,this.color=t.color,this.author=t.author,this.timestamp=t.timestamp,this.fields=t.fields||[],this.thumbnail=t.thumbnail,this.image=t.image,this.footer=t.footer}setTitle(t){if(t=n(t),t.length>256)throw new RangeError("RichEmbed titles may not exceed 256 characters.");return this.title=t,this}setDescription(t){if(t=n(t),t.length>2048)throw new RangeError("RichEmbed descriptions may not exceed 2048 characters.");return this.description=t,this}setURL(t){return this.url=t,this}setColor(t){let e=10;if(t instanceof Array?t=(t[0]<<16)+(t[1]<<8)+t[2]:"string"==typeof t&&t.startsWith("#")&&(e=16,t=t.replace("#","")),t=parseInt(t,e),t<0||t>16777215)throw new RangeError("RichEmbed color must be within the range 0 - 16777215 (0xFFFFFF).");if(t&&isNaN(t))throw new TypeError("Unable to convert RichEmbed color to a number.");return this.color=t,this}setAuthor(t,e,i){return this.author={name:n(t),icon_url:e,url:i},this}setTimestamp(t=new Date){return this.timestamp=t,this}addField(t,e,i=false){if(this.fields.length>=25)throw new RangeError("RichEmbeds may not exceed 25 fields.");if(t=n(t),t.length>256)throw new RangeError("RichEmbed field names may not exceed 256 characters.");if(e=n(e),e.length>1024)throw new RangeError("RichEmbed field values may not exceed 1024 characters.");return this.fields.push({name:String(t),value:e,inline:i}),this}setThumbnail(t){return this.thumbnail={url:t},this}setImage(t){return this.image={url:t},this}setFooter(t,e){if(t=n(t),t.length>2048)throw new RangeError("RichEmbed footer text may not exceed 2048 characters.");return this.footer={text:t,icon_url:e},this}}t.exports=i},function(t,e,n){const i=n(25),s=n(0).Endpoints.botGateway;t.exports=function(t){return new Promise((e,n)=>{if(!t)throw new Error("A token must be provided.");i.get(s).set("Authorization",`Bot ${t.replace(/^Bot\s*/i,"")}`).end((t,i)=>{t&&n(t),e(i.body.shards)})})}},function(t,e){},function(t,e){},function(t,e){},function(t,e,n){"use strict";function i(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function s(t){return 3*t.length/4-i(t)}function r(t){var e,n,s,r,o,a,h=t.length;o=i(t),a=new l(3*h/4-o),s=o>0?h-4:h;var u=0;for(e=0,n=0;e>16&255,a[u++]=r>>8&255,a[u++]=255&r;return 2===o?(r=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,a[u++]=255&r):1===o&&(r=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,a[u++]=r>>8&255,a[u++]=255&r),a}function o(t){return u[t>>18&63]+u[t>>12&63]+u[t>>6&63]+u[63&t]}function a(t,e,n){for(var i,s=[],r=e;rc?c:h+o));return 1===i?(e=t[n-1],s+=u[e>>2],s+=u[e<<4&63],s+="=="):2===i&&(e=(t[n-2]<<8)+t[n-1],s+=u[e>>10],s+=u[e>>4&63],s+=u[e<<2&63],s+="="),r.push(s),r.join("")}e.byteLength=s,e.toByteArray=r,e.fromByteArray=h;for(var u=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=0,p=d.length;f>1,c=-7,l=n?s-1:0,d=n?-1:1,f=t[e+l];for(l+=d,r=f&(1<<-c)-1,f>>=-c,c+=a;c>0;r=256*r+t[e+l],l+=d,c-=8);for(o=r&(1<<-c)-1,r>>=-c,c+=i;c>0;o=256*o+t[e+l],l+=d,c-=8);if(0===r)r=1-u;else{if(r===h)return o?NaN:(f?-1:1)*(1/0);o+=Math.pow(2,i),r-=u}return(f?-1:1)*o*Math.pow(2,r-i)},e.write=function(t,e,n,i,s,r){var o,a,h,u=8*r-s-1,c=(1<>1,d=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:r-1,p=i?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),e+=o+l>=1?d/h:d*Math.pow(2,1-l),e*h>=2&&(o++,h/=2),o+l>=c?(a=0,o=c):o+l>=1?(a=(e*h-1)*Math.pow(2,s),o+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,s),o=0));s>=8;t[n+f]=255&a,f+=p,a/=256,s-=8);for(o=o<0;t[n+f]=255&o,f+=p,o/=256,u-=8);t[n+f-p]|=128*m}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,n){"use strict";var i=n(5).assign,s=n(68),r=n(69),o=n(46),a={};i(a,s,r,o),t.exports=a},function(t,e,n){"use strict";function i(t){if(!(this instanceof i))return new i(t);this.options=h.assign({level:E,method:v,chunkSize:16384,windowBits:15,memLevel:8,strategy:w,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var n=a.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(n!==m)throw new Error(c[n]);if(e.header&&a.deflateSetHeader(this.strm,e.header),e.dictionary){var s;if(s="string"==typeof e.dictionary?u.string2buf(e.dictionary):"[object ArrayBuffer]"===d.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,n=a.deflateSetDictionary(this.strm,s),n!==m)throw new Error(c[n]);this._dict_set=!0}}function s(t,e){var n=new i(e);if(n.push(t,!0),n.err)throw n.msg||c[n.err];return n.result}function r(t,e){return e=e||{},e.raw=!0,s(t,e)}function o(t,e){return e=e||{},e.gzip=!0,s(t,e)}var a=n(70),h=n(5),u=n(44),c=n(22),l=n(48),d=Object.prototype.toString,f=0,p=4,m=0,g=1,_=2,E=-1,w=0,v=8;i.prototype.push=function(t,e){var n,i,s=this.strm,r=this.options.chunkSize;if(this.ended)return!1;i=e===~~e?e:e===!0?p:f,"string"==typeof t?s.input=u.string2buf(t):"[object ArrayBuffer]"===d.call(t)?s.input=new Uint8Array(t):s.input=t,s.next_in=0,s.avail_in=s.input.length;do{if(0===s.avail_out&&(s.output=new h.Buf8(r),s.next_out=0,s.avail_out=r),n=a.deflate(s,i),n!==g&&n!==m)return this.onEnd(n),this.ended=!0,!1;0!==s.avail_out&&(0!==s.avail_in||i!==p&&i!==_)||("string"===this.options.to?this.onData(u.buf2binstring(h.shrinkBuf(s.output,s.next_out))):this.onData(h.shrinkBuf(s.output,s.next_out)))}while((s.avail_in>0||0===s.avail_out)&&n!==g);return i===p?(n=a.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===m):i!==_||(this.onEnd(m),s.avail_out=0,!0)},i.prototype.onData=function(t){this.chunks.push(t)},i.prototype.onEnd=function(t){t===m&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Deflate=i,e.deflate=s,e.deflateRaw=r,e.gzip=o},function(t,e,n){"use strict";function i(t){if(!(this instanceof i))return new i(t);this.options=a.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0===(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var n=o.inflateInit2(this.strm,e.windowBits);if(n!==u.Z_OK)throw new Error(c[n]);this.header=new d,o.inflateGetHeader(this.strm,this.header)}function s(t,e){var n=new i(e);if(n.push(t,!0),n.err)throw n.msg||c[n.err];return n.result}function r(t,e){return e=e||{},e.raw=!0,s(t,e)}var o=n(73),a=n(5),h=n(44),u=n(46),c=n(22),l=n(48),d=n(71),f=Object.prototype.toString;i.prototype.push=function(t,e){var n,i,s,r,c,l,d=this.strm,p=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;i=e===~~e?e:e===!0?u.Z_FINISH:u.Z_NO_FLUSH,"string"==typeof t?d.input=h.binstring2buf(t):"[object ArrayBuffer]"===f.call(t)?d.input=new Uint8Array(t):d.input=t,d.next_in=0,d.avail_in=d.input.length;do{if(0===d.avail_out&&(d.output=new a.Buf8(p),d.next_out=0,d.avail_out=p),n=o.inflate(d,u.Z_NO_FLUSH),n===u.Z_NEED_DICT&&m&&(l="string"==typeof m?h.string2buf(m):"[object ArrayBuffer]"===f.call(m)?new Uint8Array(m):m,n=o.inflateSetDictionary(this.strm,l)),n===u.Z_BUF_ERROR&&g===!0&&(n=u.Z_OK,g=!1),n!==u.Z_STREAM_END&&n!==u.Z_OK)return this.onEnd(n),this.ended=!0,!1;d.next_out&&(0!==d.avail_out&&n!==u.Z_STREAM_END&&(0!==d.avail_in||i!==u.Z_FINISH&&i!==u.Z_SYNC_FLUSH)||("string"===this.options.to?(s=h.utf8border(d.output,d.next_out),r=d.next_out-s,c=h.buf2string(d.output,s),d.next_out=r,d.avail_out=p-r,r&&a.arraySet(d.output,d.output,s,r,0),this.onData(c)):this.onData(a.shrinkBuf(d.output,d.next_out)))),0===d.avail_in&&0===d.avail_out&&(g=!0)}while((d.avail_in>0||0===d.avail_out)&&n!==u.Z_STREAM_END);return n===u.Z_STREAM_END&&(i=u.Z_FINISH),i===u.Z_FINISH?(n=o.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===u.Z_OK):i!==u.Z_SYNC_FLUSH||(this.onEnd(u.Z_OK),d.avail_out=0,!0)},i.prototype.onData=function(t){this.chunks.push(t)},i.prototype.onEnd=function(t){t===u.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=a.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},e.Inflate=i,e.inflate=s,e.inflateRaw=r,e.ungzip=s},function(t,e,n){ -"use strict";function i(t,e){return t.msg=U[e],e}function s(t){return(t<<1)-(t>4?9:0)}function r(t){for(var e=t.length;--e>=0;)t[e]=0}function o(t){var e=t.state,n=e.pending;n>t.avail_out&&(n=t.avail_out),0!==n&&(I.arraySet(t.output,e.pending_buf,e.pending_out,n,t.next_out),t.next_out+=n,e.pending_out+=n,t.total_out+=n,t.avail_out-=n,e.pending-=n,0===e.pending&&(e.pending_out=0))}function a(t,e){C._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,o(t.strm)}function h(t,e){t.pending_buf[t.pending++]=e}function u(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function c(t,e,n,i){var s=t.avail_in;return s>i&&(s=i),0===s?0:(t.avail_in-=s,I.arraySet(e,t.input,t.next_in,s,n),1===t.state.wrap?t.adler=x(t.adler,e,s,n):2===t.state.wrap&&(t.adler=L(t.adler,e,s,n)),t.next_in+=s,t.total_in+=s,s)}function l(t,e){var n,i,s=t.max_chain_length,r=t.strstart,o=t.prev_length,a=t.nice_match,h=t.strstart>t.w_size-lt?t.strstart-(t.w_size-lt):0,u=t.window,c=t.w_mask,l=t.prev,d=t.strstart+ct,f=u[r+o-1],p=u[r+o];t.prev_length>=t.good_match&&(s>>=2),a>t.lookahead&&(a=t.lookahead);do if(n=e,u[n+o]===p&&u[n+o-1]===f&&u[n]===u[r]&&u[++n]===u[r+1]){r+=2,n++;do;while(u[++r]===u[++n]&&u[++r]===u[++n]&&u[++r]===u[++n]&&u[++r]===u[++n]&&u[++r]===u[++n]&&u[++r]===u[++n]&&u[++r]===u[++n]&&u[++r]===u[++n]&&ro){if(t.match_start=e,o=i,i>=a)break;f=u[r+o-1],p=u[r+o]}}while((e=l[e&c])>h&&0!==--s);return o<=t.lookahead?o:t.lookahead}function d(t){var e,n,i,s,r,o=t.w_size;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=o+(o-lt)){I.arraySet(t.window,t.window,o,o,0),t.match_start-=o,t.strstart-=o,t.block_start-=o,n=t.hash_size,e=n;do i=t.head[--e],t.head[e]=i>=o?i-o:0;while(--n);n=o,e=n;do i=t.prev[--e],t.prev[e]=i>=o?i-o:0;while(--n);s+=o}if(0===t.strm.avail_in)break;if(n=c(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=n,t.lookahead+t.insert>=ut)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(n=t.pending_buf_size-5);;){if(t.lookahead<=1){if(d(t),0===t.lookahead&&e===P)return vt;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+n;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,a(t,!1),0===t.strm.avail_out))return vt;if(t.strstart-t.block_start>=t.w_size-lt&&(a(t,!1),0===t.strm.avail_out))return vt}return t.insert=0,e===B?(a(t,!0),0===t.strm.avail_out?yt:At):t.strstart>t.block_start&&(a(t,!1),0===t.strm.avail_out)?vt:vt}function p(t,e){for(var n,i;;){if(t.lookahead=ut&&(t.ins_h=(t.ins_h<=ut)if(i=C._tr_tally(t,t.strstart-t.match_start,t.match_length-ut),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=ut){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=ut&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=ut-1)),t.prev_length>=ut&&t.match_length<=t.prev_length){s=t.strstart+t.lookahead-ut,i=C._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-ut),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=s&&(t.ins_h=(t.ins_h<=ut&&t.strstart>0&&(s=t.strstart-1,i=o[s],i===o[++s]&&i===o[++s]&&i===o[++s])){r=t.strstart+ct;do;while(i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&i===o[++s]&&st.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=ut?(n=C._tr_tally(t,1,t.match_length-ut),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(n=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),n&&(a(t,!1),0===t.strm.avail_out))return vt}return t.insert=0,e===B?(a(t,!0),0===t.strm.avail_out?yt:At):t.last_lit&&(a(t,!1),0===t.strm.avail_out)?vt:bt}function _(t,e){for(var n;;){if(0===t.lookahead&&(d(t),0===t.lookahead)){if(e===P)return vt;break}if(t.match_length=0,n=C._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,n&&(a(t,!1),0===t.strm.avail_out))return vt}return t.insert=0,e===B?(a(t,!0),0===t.strm.avail_out?yt:At):t.last_lit&&(a(t,!1),0===t.strm.avail_out)?vt:bt}function E(t,e,n,i,s){this.good_length=t,this.max_lazy=e,this.nice_length=n,this.max_chain=i,this.func=s}function w(t){t.window_size=2*t.w_size,r(t.head),t.max_lazy_match=S[t.level].max_lazy,t.good_match=S[t.level].good_length,t.nice_match=S[t.level].nice_length,t.max_chain_length=S[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=ut-1,t.match_available=0,t.ins_h=0}function v(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=X,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new I.Buf16(2*at),this.dyn_dtree=new I.Buf16(2*(2*rt+1)),this.bl_tree=new I.Buf16(2*(2*ot+1)),r(this.dyn_ltree),r(this.dyn_dtree),r(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new I.Buf16(ht+1),this.heap=new I.Buf16(2*st+1),r(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new I.Buf16(2*st+1),r(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function b(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=J,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?ft:Et,t.adler=2===e.wrap?0:1,e.last_flush=P,C._tr_init(e),j):i(t,z)}function y(t){var e=b(t);return e===j&&w(t.state),e}function A(t,e){return t&&t.state?2!==t.state.wrap?z:(t.state.gzhead=e,j):z}function k(t,e,n,s,r,o){if(!t)return z;var a=1;if(e===F&&(e=6),s<0?(a=0,s=-s):s>15&&(a=2,s-=16),r<1||r>Q||n!==X||s<8||s>15||e<0||e>9||o<0||o>Z)return i(t,z);8===s&&(s=9);var h=new v;return t.state=h,h.strm=t,h.wrap=a,h.gzhead=null,h.w_bits=s,h.w_size=1<G||e<0)return t?i(t,z):z;if(a=t.state,!t.output||!t.input&&0!==t.avail_in||a.status===wt&&e!==B)return i(t,0===t.avail_out?W:z);if(a.strm=t,n=a.last_flush,a.last_flush=e,a.status===ft)if(2===a.wrap)t.adler=0,h(a,31),h(a,139),h(a,8),a.gzhead?(h(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),h(a,255&a.gzhead.time),h(a,a.gzhead.time>>8&255),h(a,a.gzhead.time>>16&255),h(a,a.gzhead.time>>24&255),h(a,9===a.level?2:a.strategy>=V||a.level<2?4:0),h(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(h(a,255&a.gzhead.extra.length),h(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=L(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=pt):(h(a,0),h(a,0),h(a,0),h(a,0),h(a,0),h(a,9===a.level?2:a.strategy>=V||a.level<2?4:0),h(a,kt),a.status=Et);else{var d=X+(a.w_bits-8<<4)<<8,f=-1;f=a.strategy>=V||a.level<2?0:a.level<6?1:6===a.level?2:3,d|=f<<6,0!==a.strstart&&(d|=dt),d+=31-d%31,a.status=Et,u(a,d),0!==a.strstart&&(u(a,t.adler>>>16),u(a,65535&t.adler)),t.adler=1}if(a.status===pt)if(a.gzhead.extra){for(c=a.pending;a.gzindex<(65535&a.gzhead.extra.length)&&(a.pending!==a.pending_buf_size||(a.gzhead.hcrc&&a.pending>c&&(t.adler=L(t.adler,a.pending_buf,a.pending-c,c)),o(t),c=a.pending,a.pending!==a.pending_buf_size));)h(a,255&a.gzhead.extra[a.gzindex]),a.gzindex++;a.gzhead.hcrc&&a.pending>c&&(t.adler=L(t.adler,a.pending_buf,a.pending-c,c)),a.gzindex===a.gzhead.extra.length&&(a.gzindex=0,a.status=mt)}else a.status=mt;if(a.status===mt)if(a.gzhead.name){c=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>c&&(t.adler=L(t.adler,a.pending_buf,a.pending-c,c)),o(t),c=a.pending,a.pending===a.pending_buf_size)){l=1;break}l=a.gzindexc&&(t.adler=L(t.adler,a.pending_buf,a.pending-c,c)),0===l&&(a.gzindex=0,a.status=gt)}else a.status=gt;if(a.status===gt)if(a.gzhead.comment){c=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>c&&(t.adler=L(t.adler,a.pending_buf,a.pending-c,c)),o(t),c=a.pending,a.pending===a.pending_buf_size)){l=1;break}l=a.gzindexc&&(t.adler=L(t.adler,a.pending_buf,a.pending-c,c)),0===l&&(a.status=_t)}else a.status=_t;if(a.status===_t&&(a.gzhead.hcrc?(a.pending+2>a.pending_buf_size&&o(t),a.pending+2<=a.pending_buf_size&&(h(a,255&t.adler),h(a,t.adler>>8&255),t.adler=0,a.status=Et)):a.status=Et),0!==a.pending){if(o(t),0===t.avail_out)return a.last_flush=-1,j}else if(0===t.avail_in&&s(e)<=s(n)&&e!==B)return i(t,W);if(a.status===wt&&0!==t.avail_in)return i(t,W);if(0!==t.avail_in||0!==a.lookahead||e!==P&&a.status!==wt){var p=a.strategy===V?_(a,e):a.strategy===K?g(a,e):S[a.level].func(a,e);if(p!==yt&&p!==At||(a.status=wt),p===vt||p===yt)return 0===t.avail_out&&(a.last_flush=-1),j;if(p===bt&&(e===N?C._tr_align(a):e!==G&&(C._tr_stored_block(a,0,0,!1),e===O&&(r(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),o(t),0===t.avail_out))return a.last_flush=-1,j}return e!==B?j:a.wrap<=0?q:(2===a.wrap?(h(a,255&t.adler),h(a,t.adler>>8&255),h(a,t.adler>>16&255),h(a,t.adler>>24&255),h(a,255&t.total_in),h(a,t.total_in>>8&255),h(a,t.total_in>>16&255),h(a,t.total_in>>24&255)):(u(a,t.adler>>>16),u(a,65535&t.adler)),o(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?j:q)}function D(t){var e;return t&&t.state?(e=t.state.status,e!==ft&&e!==pt&&e!==mt&&e!==gt&&e!==_t&&e!==Et&&e!==wt?i(t,z):(t.state=null,e===Et?i(t,H):j)):z}function M(t,e){var n,i,s,o,a,h,u,c,l=e.length;if(!t||!t.state)return z;if(n=t.state,o=n.wrap,2===o||1===o&&n.status!==ft||n.lookahead)return z;for(1===o&&(t.adler=x(t.adler,e,l,0)),n.wrap=0,l>=n.w_size&&(0===o&&(r(n.head),n.strstart=0,n.block_start=0,n.insert=0),c=new I.Buf8(n.w_size),I.arraySet(c,e,l-n.w_size,n.w_size,0),e=c,l=n.w_size),a=t.avail_in,h=t.next_in,u=t.input,t.avail_in=l,t.next_in=0,t.input=e,d(n);n.lookahead>=ut;){i=n.strstart,s=n.lookahead-(ut-1);do n.ins_h=(n.ins_h<>>24,m>>>=y,g-=y,y=b>>>16&255,0===y)M[a++]=65535&b;else{if(!(16&y)){if(0===(64&y)){b=_[(65535&b)+(m&(1<>>=y,g-=y),g<15&&(m+=D[r++]<>>24,m>>>=y,g-=y,y=b>>>16&255,!(16&y)){if(0===(64&y)){b=E[(65535&b)+(m&(1<c){t.msg="invalid distance too far back",n.mode=i;break t}if(m>>>=y,g-=y,y=a-h,k>y){if(y=k-y,y>d&&n.sane){t.msg="invalid distance too far back",n.mode=i;break t}if(R=0,T=p,0===f){if(R+=l-y,y2;)M[a++]=T[R++],M[a++]=T[R++],M[a++]=T[R++],A-=3;A&&(M[a++]=T[R++],A>1&&(M[a++]=T[R++]))}else{R=a-k;do M[a++]=M[R++],M[a++]=M[R++],M[a++]=M[R++],A-=3;while(A>2);A&&(M[a++]=M[R++],A>1&&(M[a++]=M[R++]))}break}}break}}while(r>3,r-=A,g-=A<<3,m&=(1<>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function s(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function r(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=O,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new E.Buf32(mt),e.distcode=e.distdyn=new E.Buf32(gt),e.sane=1,e.back=-1,S):x}function o(t){var e;return t&&t.state?(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,r(t)):x}function a(t,e){var n,i;return t&&t.state?(i=t.state,e<0?(n=0,e=-e):(n=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15)?x:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=n,i.wbits=e,o(t))):x}function h(t,e){var n,i;return t?(i=new s,t.state=i,i.window=null,n=a(t,e),n!==S&&(t.state=null),n):x}function u(t){return h(t,Et)}function c(t){if(wt){var e;for(g=new E.Buf32(512),_=new E.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(y(k,t.lens,0,288,g,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;y(R,t.lens,0,32,_,0,t.work,{bits:5}),wt=!1}t.lencode=g,t.lenbits=9,t.distcode=_,t.distbits=5}function l(t,e,n,i){var s,r=t.state;return null===r.window&&(r.wsize=1<=r.wsize?(E.arraySet(r.window,e,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(s=r.wsize-r.wnext,s>i&&(s=i),E.arraySet(r.window,e,n-i,s,r.wnext),i-=s,i?(E.arraySet(r.window,e,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=s,r.wnext===r.wsize&&(r.wnext=0),r.whave>>8&255,n.check=v(n.check,Dt,2,0),d=0,f=0,n.mode=B;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&d)<<8)+(d>>8))%31){t.msg="incorrect header check",n.mode=dt;break}if((15&d)!==N){t.msg="unknown compression method",n.mode=dt;break}if(d>>>=4,f-=4,yt=(15&d)+8,0===n.wbits)n.wbits=yt;else if(yt>n.wbits){t.msg="invalid window size",n.mode=dt;break}n.dmax=1<>8&1),512&n.flags&&(Dt[0]=255&d,Dt[1]=d>>>8&255,n.check=v(n.check,Dt,2,0)),d=0,f=0,n.mode=G;case G:for(;f<32;){if(0===h)break t;h--,d+=s[o++]<>>8&255,Dt[2]=d>>>16&255,Dt[3]=d>>>24&255,n.check=v(n.check,Dt,4,0)),d=0,f=0,n.mode=j;case j:for(;f<16;){if(0===h)break t;h--,d+=s[o++]<>8),512&n.flags&&(Dt[0]=255&d,Dt[1]=d>>>8&255,n.check=v(n.check,Dt,2,0)),d=0,f=0,n.mode=q;case q:if(1024&n.flags){for(;f<16;){if(0===h)break t;h--,d+=s[o++]<>>8&255,n.check=v(n.check,Dt,2,0)),d=0,f=0}else n.head&&(n.head.extra=null);n.mode=z;case z:if(1024&n.flags&&(g=n.length,g>h&&(g=h),g&&(n.head&&(yt=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),E.arraySet(n.head.extra,s,o,g,yt)),512&n.flags&&(n.check=v(n.check,s,g,o)),h-=g,o+=g,n.length-=g),n.length))break t;n.length=0,n.mode=H;case H:if(2048&n.flags){if(0===h)break t;g=0;do yt=s[o+g++],n.head&&yt&&n.length<65536&&(n.head.name+=String.fromCharCode(yt));while(yt&&g>9&1,n.head.done=!0),t.adler=n.check=0,n.mode=K;break;case Y:for(;f<32;){if(0===h)break t;h--,d+=s[o++]<>>=7&f,f-=7&f,n.mode=ut;break}for(;f<3;){if(0===h)break t;h--,d+=s[o++]<>>=1,f-=1,3&d){case 0:n.mode=$;break;case 1:if(c(n),n.mode=nt,e===M){d>>>=2,f-=2;break t}break;case 2:n.mode=Q;break;case 3:t.msg="invalid block type",n.mode=dt}d>>>=2,f-=2;break;case $:for(d>>>=7&f,f-=7&f;f<32;){if(0===h)break t;h--,d+=s[o++]<>>16^65535)){t.msg="invalid stored block lengths",n.mode=dt;break}if(n.length=65535&d,d=0,f=0,n.mode=J,e===M)break t;case J:n.mode=X;case X:if(g=n.length){if(g>h&&(g=h),g>u&&(g=u),0===g)break t;E.arraySet(r,s,o,g,a),h-=g,o+=g,u-=g,a+=g,n.length-=g;break}n.mode=K;break;case Q:for(;f<14;){if(0===h)break t;h--,d+=s[o++]<>>=5,f-=5,n.ndist=(31&d)+1,d>>>=5,f-=5,n.ncode=(15&d)+4,d>>>=4,f-=4,n.nlen>286||n.ndist>30){t.msg="too many length or distance symbols",n.mode=dt;break}n.have=0,n.mode=tt;case tt:for(;n.have>>=3,f-=3}for(;n.have<19;)n.lens[Mt[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,kt={bits:n.lenbits},At=y(A,n.lens,0,19,n.lencode,0,n.work,kt),n.lenbits=kt.bits,At){t.msg="invalid code lengths set",n.mode=dt;break}n.have=0,n.mode=et;case et:for(;n.have>>24,_t=Tt>>>16&255,Et=65535&Tt,!(gt<=f);){if(0===h)break t;h--,d+=s[o++]<>>=gt,f-=gt,n.lens[n.have++]=Et;else{if(16===Et){for(Rt=gt+2;f>>=gt,f-=gt,0===n.have){t.msg="invalid bit length repeat",n.mode=dt;break}yt=n.lens[n.have-1],g=3+(3&d),d>>>=2,f-=2}else if(17===Et){for(Rt=gt+3;f>>=gt,f-=gt,yt=0,g=3+(7&d),d>>>=3,f-=3}else{for(Rt=gt+7;f>>=gt,f-=gt,yt=0,g=11+(127&d),d>>>=7,f-=7}if(n.have+g>n.nlen+n.ndist){t.msg="invalid bit length repeat",n.mode=dt;break}for(;g--;)n.lens[n.have++]=yt}}if(n.mode===dt)break;if(0===n.lens[256]){t.msg="invalid code -- missing end-of-block",n.mode=dt;break}if(n.lenbits=9,kt={bits:n.lenbits},At=y(k,n.lens,0,n.nlen,n.lencode,0,n.work,kt),n.lenbits=kt.bits,At){t.msg="invalid literal/lengths set",n.mode=dt;break}if(n.distbits=6,n.distcode=n.distdyn,kt={bits:n.distbits},At=y(R,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,kt),n.distbits=kt.bits,At){t.msg="invalid distances set",n.mode=dt;break}if(n.mode=nt,e===M)break t;case nt:n.mode=it;case it:if(h>=6&&u>=258){t.next_out=a,t.avail_out=u,t.next_in=o,t.avail_in=h,n.hold=d,n.bits=f,b(t,m),a=t.next_out,r=t.output,u=t.avail_out,o=t.next_in,s=t.input,h=t.avail_in,d=n.hold,f=n.bits,n.mode===K&&(n.back=-1);break}for(n.back=0;Tt=n.lencode[d&(1<>>24,_t=Tt>>>16&255,Et=65535&Tt,!(gt<=f);){if(0===h)break t;h--,d+=s[o++]<>wt)],gt=Tt>>>24,_t=Tt>>>16&255,Et=65535&Tt,!(wt+gt<=f);){if(0===h)break t;h--,d+=s[o++]<>>=wt,f-=wt,n.back+=wt}if(d>>>=gt,f-=gt,n.back+=gt,n.length=Et,0===_t){n.mode=ht;break}if(32&_t){n.back=-1,n.mode=K;break}if(64&_t){t.msg="invalid literal/length code",n.mode=dt;break}n.extra=15&_t,n.mode=st;case st:if(n.extra){for(Rt=n.extra;f>>=n.extra,f-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=rt;case rt:for(;Tt=n.distcode[d&(1<>>24,_t=Tt>>>16&255,Et=65535&Tt,!(gt<=f);){if(0===h)break t;h--,d+=s[o++]<>wt)],gt=Tt>>>24,_t=Tt>>>16&255,Et=65535&Tt,!(wt+gt<=f);){if(0===h)break t;h--,d+=s[o++]<>>=wt,f-=wt,n.back+=wt}if(d>>>=gt,f-=gt,n.back+=gt,64&_t){t.msg="invalid distance code",n.mode=dt;break}n.offset=Et,n.extra=15&_t,n.mode=ot;case ot:if(n.extra){for(Rt=n.extra;f>>=n.extra,f-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){t.msg="invalid distance too far back",n.mode=dt;break}n.mode=at;case at:if(0===u)break t;if(g=m-u,n.offset>g){if(g=n.offset-g,g>n.whave&&n.sane){t.msg="invalid distance too far back",n.mode=dt;break}g>n.wnext?(g-=n.wnext,_=n.wsize-g):_=n.wnext-g,g>n.length&&(g=n.length),mt=n.window}else mt=r,_=a-n.offset,g=n.length;g>u&&(g=u),u-=g,n.length-=g;do r[a++]=mt[_++];while(--g);0===n.length&&(n.mode=it);break;case ht:if(0===u)break t;r[a++]=n.length,u--,n.mode=it;break;case ut:if(n.wrap){for(;f<32;){if(0===h)break t;h--,d|=s[o++]<=1&&0===q[x];x--);if(L>x&&(L=x),0===x)return m[g++]=20971520,m[g++]=20971520,E.bits=1,0;for(C=1;C0&&(t===a||1!==x))return-1;for(z[1]=0,S=1;Sr||t===u&&O>o)return 1;for(;;){R=S-P,_[I]k?(T=H[W+_[I]],D=G[j+_[I]]):(T=96,D=0),w=1<>P)+v]=R<<24|T<<16|D|0;while(0!==v);for(w=1<>=1;if(0!==w?(B&=w-1,B+=w):B=0,I++,0===--q[S]){if(S===x)break;S=e[n+_[I]]}if(S>L&&(B&y)!==b){for(0===P&&(P=L),A+=C,U=S-P,N=1<r||t===u&&O>o)return 1;b=B&y,m[b]=L<<24|U<<16|A-g|0}}return 0!==B&&(m[A+B]=S-P<<24|64<<16|0),E.bits=L,0}},function(t,e,n){"use strict";function i(t){for(var e=t.length;--e>=0;)t[e]=0}function s(t,e,n,i,s){this.static_tree=t,this.extra_bits=e,this.extra_base=n,this.elems=i,this.max_length=s,this.has_stree=t&&t.length}function r(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function o(t){return t<256?ht[t]:ht[256+(t>>>7)]}function a(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function h(t,e,n){t.bi_valid>Z-n?(t.bi_buf|=e<>Z-t.bi_valid,t.bi_valid+=n-Z):(t.bi_buf|=e<>>=1,n<<=1;while(--e>0);return n>>>1}function l(t){16===t.bi_valid?(a(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}function d(t,e){var n,i,s,r,o,a,h=e.dyn_tree,u=e.max_code,c=e.stat_desc.static_tree,l=e.stat_desc.has_stree,d=e.stat_desc.extra_bits,f=e.stat_desc.extra_base,p=e.stat_desc.max_length,m=0;for(r=0;r<=K;r++)t.bl_count[r]=0;for(h[2*t.heap[t.heap_max]+1]=0,n=t.heap_max+1;np&&(r=p,m++),h[2*i+1]=r,i>u||(t.bl_count[r]++,o=0,i>=f&&(o=d[i-f]),a=h[2*i],t.opt_len+=a*(r+o),l&&(t.static_len+=a*(c[2*i+1]+o)));if(0!==m){do{for(r=p-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[p]--,m-=2}while(m>0);for(r=p;0!==r;r--)for(i=t.bl_count[r];0!==i;)s=t.heap[--n],s>u||(h[2*s+1]!==r&&(t.opt_len+=(r-h[2*s+1])*h[2*s],h[2*s+1]=r),i--)}}function f(t,e,n){var i,s,r=new Array(K+1),o=0;for(i=1;i<=K;i++)r[i]=o=o+n[i-1]<<1;for(s=0;s<=e;s++){var a=t[2*s+1];0!==a&&(t[2*s]=c(r[a]++,a))}}function p(){var t,e,n,i,r,o=new Array(K+1);for(n=0,i=0;i>=7;i8?a(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function _(t,e,n,i){g(t),i&&(a(t,n),a(t,~n)),x.arraySet(t.pending_buf,t.window,e,n,t.pending),t.pending+=n}function E(t,e,n,i){var s=2*e,r=2*n;return t[s]>1;n>=1;n--)w(t,r,n);s=h;do n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],w(t,r,1),i=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=i,r[2*s]=r[2*n]+r[2*i],t.depth[s]=(t.depth[n]>=t.depth[i]?t.depth[n]:t.depth[i])+1,r[2*n+1]=r[2*i+1]=s,t.heap[1]=s++,w(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],d(t,e),f(r,u,t.bl_count)}function y(t,e,n){var i,s,r=-1,o=e[1],a=0,h=7,u=4;for(0===o&&(h=138,u=3),e[2*(n+1)+1]=65535,i=0;i<=n;i++)s=o,o=e[2*(i+1)+1],++a=3&&0===t.bl_tree[2*st[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}function R(t,e,n,i){var s;for(h(t,e-257,5),h(t,n-1,5),h(t,i-4,4),s=0;s>>=1)if(1&n&&0!==t.dyn_ltree[2*e])return U;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return P;for(e=32;e0?(t.strm.data_type===N&&(t.strm.data_type=T(t)),b(t,t.l_desc),b(t,t.d_desc),o=k(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=n+5,n+4<=s&&e!==-1?M(t,e,n,i):t.strategy===L||r===s?(h(t,(B<<1)+(i?1:0),3),v(t,ot,at)):(h(t,(G<<1)+(i?1:0),3),R(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),v(t,t.dyn_ltree,t.dyn_dtree)),m(t),i&&g(t)}function C(t,e,n){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&n,t.last_lit++,0===e?t.dyn_ltree[2*n]++:(t.matches++,e--,t.dyn_ltree[2*(ut[n]+H+1)]++,t.dyn_dtree[2*o(e)]++),t.last_lit===t.lit_bufsize-1}var x=n(5),L=4,U=0,P=1,N=2,O=0,B=1,G=2,j=3,q=258,z=29,H=256,W=H+1+z,F=30,Y=19,V=2*W+1,K=15,Z=16,$=7,J=256,X=16,Q=17,tt=18,et=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],nt=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],it=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],st=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],rt=512,ot=new Array(2*(W+2));i(ot);var at=new Array(2*F);i(at);var ht=new Array(rt);i(ht);var ut=new Array(q-j+1);i(ut);var ct=new Array(z);i(ct);var lt=new Array(F);i(lt);var dt,ft,pt,mt=!1;e._tr_init=D,e._tr_stored_block=M,e._tr_flush_block=I,e._tr_tally=C,e._tr_align=S},function(t,e,n){function i(t){var e=s(t)?Object.prototype.toString.call(t):"";return"[object Function]"===e}var s=n(26);t.exports=i},function(t,e,n){function i(t){if(t)return s(t)}function s(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}var r=n(26);t.exports=i,i.prototype.clearTimeout=function(){return this._timeout=0,this._responseTimeout=0,clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),this},i.prototype.parse=function(t){return this._parser=t,this},i.prototype.responseType=function(t){return this._responseType=t,this},i.prototype.serialize=function(t){return this._serializer=t,this},i.prototype.timeout=function(t){return t&&"object"==typeof t?("undefined"!=typeof t.deadline&&(this._timeout=t.deadline),"undefined"!=typeof t.response&&(this._responseTimeout=t.response),this):(this._timeout=t,this._responseTimeout=0,this)},i.prototype.then=function(t,e){if(!this._fullfilledPromise){var n=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(t,e){n.end(function(n,i){n?e(n):t(i)})})}return this._fullfilledPromise.then(t,e)},i.prototype.catch=function(t){return this.then(void 0,t)},i.prototype.use=function(t){return t(this),this},i.prototype.ok=function(t){if("function"!=typeof t)throw Error("Callback required");return this._okCallback=t,this},i.prototype._isResponseOK=function(t){return!!t&&(this._okCallback?this._okCallback(t):t.status>=200&&t.status<300)},i.prototype.get=function(t){return this._header[t.toLowerCase()]},i.prototype.getHeader=i.prototype.get,i.prototype.set=function(t,e){if(r(t)){for(var n in t)this.set(n,t[n]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},i.prototype.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},i.prototype.field=function(t,e){if(null===t||void 0===t)throw new Error(".field(name, val) name can not be empty");if(r(t)){for(var n in t)this.field(n,t[n]);return this}if(Array.isArray(e)){for(var i in e)this.field(t,e[i]);return this}if(null===e||void 0===e)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof e&&(e=""+e),this._getFormData().append(t,e),this},i.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},i.prototype.withCredentials=function(){return this._withCredentials=!0,this},i.prototype.redirects=function(t){return this._maxRedirects=t,this},i.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},i.prototype.send=function(t){var e=r(t),n=this._header["content-type"];if(e&&!this._data)Array.isArray(t)?this._data=[]:this._isHost(t)||(this._data={});else if(t&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(e&&r(this._data))for(var i in t)this._data[i]=t[i];else"string"==typeof t?(n||this.type("form"),n=this._header["content-type"],"application/x-www-form-urlencoded"==n?this._data=this._data?this._data+"&"+t:t:this._data=(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(n||this.type("json"),this)},i.prototype.sortQuery=function(t){return this._sort="undefined"==typeof t||t,this},i.prototype._timeoutError=function(t,e){if(!this._aborted){var n=new Error(t+e+"ms exceeded");n.timeout=e,n.code="ECONNABORTED",this.timedout=!0,this.abort(),this.callback(n)}},i.prototype._setTimeouts=function(){var t=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){t._timeoutError("Timeout of ",t._timeout)},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){t._timeoutError("Response timeout of ",t._responseTimeout)},this._responseTimeout))}},function(t,e,n){function i(t){if(t)return s(t)}function s(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}var r=n(79);t.exports=i,i.prototype.get=function(t){return this.header[t.toLowerCase()]},i.prototype._setHeaderProperties=function(t){var e=t["content-type"]||"";this.type=r.type(e);var n=r.params(e);for(var i in n)this[i]=n[i];this.links={};try{t.link&&(this.links=r.parseLinks(t.link))}catch(t){}},i.prototype._setStatusProperties=function(t){var e=t/100|0;this.status=this.statusCode=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.redirect=3==e,this.clientError=4==e,this.serverError=5==e,this.error=(4==e||5==e)&&this.toError(),this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.forbidden=403==t,this.notFound=404==t}},function(t,e){e.type=function(t){return t.split(/ *; */).shift()},e.params=function(t){return t.split(/ *; */).reduce(function(t,e){var n=e.split(/ *= */),i=n.shift(),s=n.shift();return i&&s&&(t[i]=s),t},{})},e.parseLinks=function(t){return t.split(/ *, */).reduce(function(t,e){var n=e.split(/ *; */),i=n[0].slice(1,-1),s=n[1].split(/ *= */)[1].slice(1,-1);return t[s]=i,t},{})},e.cleanHeader=function(t,e){return delete t["content-type"],delete t["content-length"],delete t["transfer-encoding"],delete t.host,e&&delete t.cookie,t}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){const i=n(0),s=n(4),r=n(17),o=n(6),a=n(30),h=n(10),u=n(41),c=n(42),l=n(13),d=n(31);class f{constructor(t){this.client=t}get pastReady(){return this.client.ws.status===i.Status.READY}newGuild(t){const e=this.client.guilds.has(t.id),n=new r(this.client,t);return this.client.guilds.set(n.id,n),this.pastReady&&!e&&(this.client.options.fetchAllMembers?n.fetchMembers().then(()=>{this.client.emit(i.Events.GUILD_CREATE,n)}):this.client.emit(i.Events.GUILD_CREATE,n)),n}newUser(t){if(this.client.users.has(t.id))return this.client.users.get(t.id);const e=new o(this.client,t);return this.client.users.set(e.id,e),e}newChannel(t,e){const n=this.client.channels.has(t.id);let s;return t.type===i.ChannelTypes.DM?s=new a(this.client,t):t.type===i.ChannelTypes.groupDM?s=new d(this.client,t):(e=e||this.client.guilds.get(t.guild_id),e&&(t.type===i.ChannelTypes.text?(s=new u(e,t),e.channels.set(s.id,s)):t.type===i.ChannelTypes.voice&&(s=new c(e,t),e.channels.set(s.id,s)))),s?(this.pastReady&&!n&&this.client.emit(i.Events.CHANNEL_CREATE,s),this.client.channels.set(s.id,s),s):null}newEmoji(t,e){const n=e.emojis.has(t.id);if(t&&!n){let n=new h(e,t);return this.client.emit(i.Events.GUILD_EMOJI_CREATE,n),e.emojis.set(n.id,n),n}return n?e.emojis.get(t.id):null}killEmoji(t){t instanceof h&&t.guild&&(this.client.emit(i.Events.GUILD_EMOJI_DELETE,t),t.guild.emojis.delete(t.id))}killGuild(t){const e=this.client.guilds.has(t.id);this.client.guilds.delete(t.id),e&&this.pastReady&&this.client.emit(i.Events.GUILD_DELETE,t)}killUser(t){this.client.users.delete(t.id)}killChannel(t){this.client.channels.delete(t.id),t instanceof l&&t.guild.channels.delete(t.id)}updateGuild(t,e){const n=s(t);t.setup(e),this.pastReady&&this.client.emit(i.Events.GUILD_UPDATE,n,t)}updateChannel(t,e){t.setup(e)}updateEmoji(t,e){const n=s(t);t.setup(e),this.client.emit(i.Events.GUILD_EMOJI_UPDATE,n,t)}}t.exports=f},function(t,e,n){const i=n(0);class s{constructor(t){this.client=t,this.heartbeatInterval=null}connectToWebSocket(t,e,n){this.client.emit(i.Events.DEBUG,`Authenticated using token ${t}`),this.client.token=t;const s=this.client.setTimeout(()=>n(new Error(i.Errors.TOOK_TOO_LONG)),3e5);this.client.rest.methods.getGateway().then(r=>{this.client.emit(i.Events.DEBUG,`Using gateway ${r}`),this.client.ws.connect(r),this.client.ws.once("close",t=>{4004===t.code&&n(new Error(i.Errors.BAD_LOGIN)),4010===t.code&&n(new Error(i.Errors.INVALID_SHARD))}),this.client.once(i.Events.READY,()=>{e(t),this.client.clearTimeout(s)})},n)}setupKeepAlive(t){this.heartbeatInterval=this.client.setInterval(()=>this.client.ws.heartbeat(!0),t)}destroy(){return this.client.ws.destroy(),this.client.user.bot?(this.client.token=null,Promise.resolve()):this.client.rest.methods.logout().then(()=>{this.client.token=null})}}t.exports=s},function(t,e,n){class i{constructor(t){this.client=t,this.register(n(100)),this.register(n(101)),this.register(n(102)),this.register(n(106)),this.register(n(103)),this.register(n(104)),this.register(n(105)),this.register(n(84)),this.register(n(85)),this.register(n(86)),this.register(n(88)),this.register(n(99)),this.register(n(92)),this.register(n(93)),this.register(n(87)),this.register(n(94)),this.register(n(95)),this.register(n(96)),this.register(n(107)),this.register(n(109)),this.register(n(108)),this.register(n(98)),this.register(n(89)),this.register(n(90)),this.register(n(91)),this.register(n(97))}register(t){this[t.name.replace(/Action$/,"")]=new t(this.client)}}t.exports=i},function(t,e,n){const i=n(2);class s extends i{handle(t){const e=this.client,n=e.dataManager.newChannel(t);return{channel:n}}}t.exports=s},function(t,e,n){const i=n(2);class s extends i{constructor(t){super(t),this.deleted=new Map}handle(t){const e=this.client;let n=e.channels.get(t.id);return n?(e.dataManager.killChannel(n),this.deleted.set(n.id,n),this.scheduleForDeletion(n.id)):n=this.deleted.get(t.id)||null,{channel:n}}scheduleForDeletion(t){this.client.setTimeout(()=>this.deleted.delete(t),this.client.options.restWsBridgeTimeout)}}t.exports=s},function(t,e,n){const i=n(2),s=n(0),r=n(4);class o extends i{handle(t){const e=this.client,n=e.channels.get(t.id);if(n){const i=r(n);return n.setup(t),e.emit(s.Events.CHANNEL_UPDATE,i,n),{old:i,updated:n}}return{old:null,updated:null}}}t.exports=o},function(t,e,n){const i=n(2),s=n(0);class r extends i{handle(t){const e=this.client,n=e.guilds.get(t.guild_id),i=e.dataManager.newUser(t.user);n&&i&&e.emit(s.Events.GUILD_BAN_REMOVE,n,i)}}t.exports=r},function(t,e,n){const i=n(2),s=n(0);class r extends i{constructor(t){super(t),this.deleted=new Map}handle(t){const e=this.client;let n=e.guilds.get(t.id);if(n){if(n.available&&t.unavailable)return n.available=!1,e.emit(s.Events.GUILD_UNAVAILABLE,n),{guild:null};e.guilds.delete(n.id),this.deleted.set(n.id,n),this.scheduleForDeletion(n.id)}else n=this.deleted.get(t.id)||null;return{guild:n}}scheduleForDeletion(t){this.client.setTimeout(()=>this.deleted.delete(t),this.client.options.restWsBridgeTimeout)}}t.exports=r},function(t,e,n){const i=n(2);class s extends i{handle(t,e){const n=this.client,i=n.dataManager.newEmoji(e,t);return{emoji:i}}}t.exports=s},function(t,e,n){const i=n(2);class s extends i{handle(t){const e=this.client;return e.dataManager.killEmoji(t),{emoji:t}}}t.exports=s},function(t,e,n){const i=n(2);class s extends i{handle(t,e){this.client.dataManager.updateEmoji(t,e)}}t.exports=s},function(t,e,n){const i=n(2);class s extends i{handle(t,e){const n=t._addMember(e,!1);return{member:n}}}t.exports=s},function(t,e,n){const i=n(2),s=n(0);class r extends i{constructor(t){super(t),this.deleted=new Map}handle(t){const e=this.client,n=e.guilds.get(t.guild_id);if(n){let i=n.members.get(t.user.id);return i?(n.memberCount--,n._removeMember(i),this.deleted.set(n.id+t.user.id,i),e.status===s.Status.READY&&e.emit(s.Events.GUILD_MEMBER_REMOVE,i),this.scheduleForDeletion(n.id,t.user.id)):i=this.deleted.get(n.id+t.user.id)||null,{guild:n,member:i}}return{guild:n,member:null}}scheduleForDeletion(t,e){this.client.setTimeout(()=>this.deleted.delete(t+e),this.client.options.restWsBridgeTimeout)}}t.exports=r},function(t,e,n){const i=n(2),s=n(0),r=n(8);class o extends i{handle(t){const e=this.client,n=e.guilds.get(t.guild_id);if(n){const i=n.roles.has(t.role.id),o=new r(n,t.role);return n.roles.set(o.id,o),i||e.emit(s.Events.GUILD_ROLE_CREATE,o),{role:o}}return{role:null}}}t.exports=o},function(t,e,n){const i=n(2),s=n(0);class r extends i{constructor(t){super(t),this.deleted=new Map}handle(t){const e=this.client,n=e.guilds.get(t.guild_id);if(n){let i=n.roles.get(t.role_id);return i?(n.roles.delete(t.role_id),this.deleted.set(n.id+t.role_id,i),this.scheduleForDeletion(n.id,t.role_id),e.emit(s.Events.GUILD_ROLE_DELETE,i)):i=this.deleted.get(n.id+t.role_id)||null,{role:i}}return{role:null}}scheduleForDeletion(t,e){this.client.setTimeout(()=>this.deleted.delete(t+e),this.client.options.restWsBridgeTimeout)}}t.exports=r},function(t,e,n){const i=n(2),s=n(0),r=n(4);class o extends i{handle(t){const e=this.client,n=e.guilds.get(t.guild_id);if(n){const i=t.role;let o=null;const a=n.roles.get(i.id);return a&&(o=r(a),a.setup(t.role),e.emit(s.Events.GUILD_ROLE_UPDATE,o,a)),{old:o,updated:a}}return{old:null,updated:null}}}t.exports=o},function(t,e,n){const i=n(2);class s extends i{handle(t){const e=this.client,n=e.guilds.get(t.guild_id);if(n)for(const i of t.roles){const t=n.roles.get(i.id);t&&(t.position=i.position)}return{guild:n}}}t.exports=s},function(t,e,n){const i=n(2);class s extends i{handle(t){const e=this.client,n=e.guilds.get(t.id);if(n){t.presences=t.presences||[];for(const e of t.presences)n._setPresence(e.user.id,e);t.members=t.members||[];for(const i of t.members){const t=n.members.get(i.user.id);t?n._updateMember(t,i):n._addMember(i,!1)}}}}t.exports=s},function(t,e,n){const i=n(2),s=n(0),r=n(4);class o extends i{handle(t){const e=this.client,n=e.guilds.get(t.id);if(n){const i=r(n);return n.setup(t),e.emit(s.Events.GUILD_UPDATE,i,n),{old:i,updated:n}}return{old:null,updated:null}}}t.exports=o},function(t,e,n){const i=n(2),s=n(11);class r extends i{handle(t){const e=this.client,n=e.channels.get((t instanceof Array?t[0]:t).channel_id),i=e.users.get((t instanceof Array?t[0]:t).author.id);if(n){const r=n.guild?n.guild.member(i):null;if(t instanceof Array){const o=new Array(t.length);for(let a=0;athis.deleted.delete(t+e),this.client.options.restWsBridgeTimeout)}}t.exports=s},function(t,e,n){const i=n(2),s=n(3),r=n(0);class o extends i{handle(t){const e=this.client,n=e.channels.get(t.channel_id),i=t.ids,o=new s;for(const a of i){const t=n.messages.get(a);t&&o.set(t.id,t)}return o.size>0&&e.emit(r.Events.MESSAGE_BULK_DELETE,o),{messages:o}}}t.exports=o},function(t,e,n){const i=n(2),s=n(0);class r extends i{handle(t){const e=this.client.users.get(t.user_id);if(!e)return!1;const n=this.client.channels.get(t.channel_id);if(!n||"voice"===n.type)return!1;const i=n.messages.get(t.message_id);if(!i)return!1;if(!t.emoji)return!1;const r=i._addReaction(t.emoji,e);return r&&this.client.emit(s.Events.MESSAGE_REACTION_ADD,r,e),{message:i,reaction:r,user:e}}}t.exports=r},function(t,e,n){const i=n(2),s=n(0);class r extends i{handle(t){const e=this.client.users.get(t.user_id);if(!e)return!1;const n=this.client.channels.get(t.channel_id);if(!n||"voice"===n.type)return!1;const i=n.messages.get(t.message_id);if(!i)return!1;if(!t.emoji)return!1;const r=i._removeReaction(t.emoji,e);return r&&this.client.emit(s.Events.MESSAGE_REACTION_REMOVE,r,e),{message:i,reaction:r,user:e}}}t.exports=r},function(t,e,n){const i=n(2),s=n(0);class r extends i{handle(t){const e=this.client.channels.get(t.channel_id);if(!e||"voice"===e.type)return!1;const n=e.messages.get(t.message_id);return!!n&&(n._clearReactions(),this.client.emit(s.Events.MESSAGE_REACTION_REMOVE_ALL,n),{message:n})}}t.exports=r},function(t,e,n){const i=n(2),s=n(0),r=n(4);class o extends i{handle(t){const e=this.client,n=e.channels.get(t.channel_id);if(n){const i=n.messages.get(t.id);if(i){const n=r(i);return i.patch(t),i._edits.unshift(n),e.emit(s.Events.MESSAGE_UPDATE,n,i),{old:n,updated:i}}return{old:i,updated:i}}return{old:null,updated:null}}}t.exports=o},function(t,e,n){const i=n(2);class s extends i{handle(t){const e=this.client,n=e.dataManager.newUser(t);return{user:n}}}t.exports=s},function(t,e,n){const i=n(2),s=n(0);class r extends i{handle(t){const e=this.client,n=e.user.notes.get(t.id),i=t.note.length?t.note:null;return e.user.notes.set(t.id,i),e.emit(s.Events.USER_NOTE_UPDATE,t.id,n,i),{old:n,updated:i}}}t.exports=r},function(t,e,n){const i=n(2),s=n(0),r=n(4);class o extends i{handle(t){const e=this.client;if(e.user){if(e.user.equals(t))return{old:e.user,updated:e.user};const n=r(e.user);return e.user.patch(t),e.emit(s.Events.USER_UPDATE,n,e.user),{old:n,updated:e.user}}return{old:null,updated:null}}}t.exports=o},function(t,e,n){function i(t){let e=t.split("?")[0];if(e.includes("/channels/")||e.includes("/guilds/")){const t=e.includes("/channels/")?e.indexOf("/channels/"):e.indexOf("/guilds/"),n=e.substring(t).split("/")[2];e=e.replace(/(\d{8,})/g,":id").replace(":id",n)}return e}const s=n(25),r=n(0);class o{constructor(t,e,n,s,r,o){this.rest=t,this.method=e,this.url=n,this.auth=s,this.data=r,this.file=o,this.route=i(this.url)}getAuth(){if(this.rest.client.token&&this.rest.client.user&&this.rest.client.user.bot)return`Bot ${this.rest.client.token}`;if(this.rest.client.token)return this.rest.client.token;throw new Error(r.Errors.NO_TOKEN)}gen(){const t=s[this.method](this.url);return this.auth&&t.set("authorization",this.getAuth()),this.file&&this.file.file?(t.attach("file",this.file.file,this.file.name),this.data=this.data||{},t.field("payload_json",JSON.stringify(this.data))):this.data&&t.send(this.data),this.rest.client.browser||t.set("User-Agent",this.rest.userAgentManager.userAgent),t}}t.exports=o},function(t,e,n){const i=n(0),s=n(3),r=n(43),o=n(154),a=n(15),h=n(6),u=n(14),c=n(11),l=n(8),d=n(32),f=n(19),p=n(152),m=n(28);class g{constructor(t){this.rest=t,this.client=t.client}login(t=this.client.token){return new Promise((e,n)=>{if("string"!=typeof t)throw new Error(i.Errors.INVALID_TOKEN);t=t.replace(/^Bot\s*/i,""),this.client.manager.connectToWebSocket(t,e,n)})}logout(){return this.rest.makeRequest("post",i.Endpoints.logout,!0,{})}getGateway(){return this.rest.makeRequest("get",i.Endpoints.gateway,!0).then(t=>{return this.client.ws.gateway=`${t.url}/?v=${i.PROTOCOL_VERSION}`,this.client.ws.gateway})}getBotGateway(){return this.rest.makeRequest("get",i.Endpoints.botGateway,!0)}sendMessage(t,e,{tts,nonce,embed,disableEveryone,split,code}={},n=null){return new Promise((s,o)=>{"undefined"!=typeof e&&(e=this.client.resolver.resolveString(e)),e&&("undefined"==typeof code||"boolean"==typeof code&&code!==!0||(e=a(this.client.resolver.resolveString(e),!0),e=`\`\`\`${"boolean"!=typeof code?code||"":""} -${e} -\`\`\``),(disableEveryone||"undefined"==typeof disableEveryone&&this.client.options.disableEveryone)&&(e=e.replace(/@(everyone|here)/g,"@​$1")),split&&(e=r(e,"object"==typeof split?split:{})));const c=t=>{if(e instanceof Array){const i=[];!function e(r,o){const a=o===r.length?{tts:tts,embed:embed}:{tts:tts};t.send(r[o],a,o===r.length?n:null).then(t=>{return i.push(t),o>=r.length?s(i):e(r,++o)})}(e,0)}else this.rest.makeRequest("post",i.Endpoints.channelMessages(t.id),!0,{content:e,tts:tts,nonce:nonce,embed:embed},n).then(t=>s(this.client.actions.MessageCreate.handle(t).message),o)};t instanceof h||t instanceof u?this.createDM(t).then(c,o):c(t)})}updateMessage(t,e,{embed,code}={}){return e=this.client.resolver.resolveString(e),"undefined"==typeof code||"boolean"==typeof code&&code!==!0||(e=a(this.client.resolver.resolveString(e),!0),e=`\`\`\`${"boolean"!=typeof code?code||"":""} -${e} -\`\`\``),this.rest.makeRequest("patch",i.Endpoints.channelMessage(t.channel.id,t.id),!0,{content:e,embed:embed}).then(t=>this.client.actions.MessageUpdate.handle(t).updated)}deleteMessage(t){return this.rest.makeRequest("del",i.Endpoints.channelMessage(t.channel.id,t.id),!0).then(()=>this.client.actions.MessageDelete.handle({id:t.id,channel_id:t.channel.id}).message)}bulkDeleteMessages(t,e){return this.rest.makeRequest("post",`${i.Endpoints.channelMessages(t.id)}/bulk_delete`,!0,{messages:e}).then(()=>this.client.actions.MessageDeleteBulk.handle({channel_id:t.id,ids:e}).messages)}createChannel(t,e,n,r){return r instanceof s&&(r=r.array()),this.rest.makeRequest("post",i.Endpoints.guildChannels(t.id),!0,{name:e,type:n,permission_overwrites:r}).then(t=>this.client.actions.ChannelCreate.handle(t).channel)}createDM(t){const e=this.getExistingDM(t);return e?Promise.resolve(e):this.rest.makeRequest("post",i.Endpoints.userChannels(this.client.user.id),!0,{recipient_id:t.id}).then(t=>this.client.actions.ChannelCreate.handle(t).channel)}getExistingDM(t){return this.client.channels.find(e=>e.recipient&&e.recipient.id===t.id)}deleteChannel(t){return(t instanceof h||t instanceof u)&&(t=this.getExistingDM(t)),t?this.rest.makeRequest("del",i.Endpoints.channel(t.id),!0).then(e=>{return e.id=t.id,this.client.actions.ChannelDelete.handle(e).channel}):Promise.reject(new Error("No channel to delete."))}updateChannel(t,e){const n={};return n.name=(e.name||t.name).trim(),n.topic=e.topic||t.topic,n.position=e.position||t.position,n.bitrate=e.bitrate||t.bitrate,n.user_limit=e.userLimit||t.userLimit,this.rest.makeRequest("patch",i.Endpoints.channel(t.id),!0,n).then(t=>this.client.actions.ChannelUpdate.handle(t).updated)}leaveGuild(t){return t.ownerID===this.client.user.id?Promise.reject(new Error("Guild is owned by the client.")):this.rest.makeRequest("del",i.Endpoints.meGuild(t.id),!0).then(()=>this.client.actions.GuildDelete.handle({id:t.id}).guild)}createGuild(t){return t.icon=this.client.resolver.resolveBase64(t.icon)||null,t.region=t.region||"us-central",new Promise((e,n)=>{this.rest.makeRequest("post",i.Endpoints.guilds,!0,t).then(t=>{if(this.client.guilds.has(t.id))return void e(this.client.guilds.get(t.id));const i=n=>{n.id===t.id&&(this.client.removeListener("guildCreate",i),this.client.clearTimeout(s),e(n))};this.client.on("guildCreate",i);const s=this.client.setTimeout(()=>{this.client.removeListener("guildCreate",i),n(new Error("Took too long to receive guild data."))},1e4)},n)})}deleteGuild(t){return this.rest.makeRequest("del",i.Endpoints.guild(t.id),!0).then(()=>this.client.actions.GuildDelete.handle({id:t.id}).guild)}getUser(t){return this.rest.makeRequest("get",i.Endpoints.user(t),!0).then(t=>this.client.actions.UserGet.handle(t).user)}updateCurrentUser(t,e){const n=this.client.user,s={};return s.username=t.username||n.username,s.avatar=this.client.resolver.resolveBase64(t.avatar)||n.avatar,n.bot||(s.email=t.email||n.email,s.password=e,t.new_password&&(s.new_password=t.newPassword)),this.rest.makeRequest("patch",i.Endpoints.me,!0,s).then(t=>this.client.actions.UserUpdate.handle(t).updated)}updateGuild(t,e){const n={};return e.name&&(n.name=e.name),e.region&&(n.region=e.region),e.verificationLevel&&(n.verification_level=Number(e.verificationLevel)),e.afkChannel&&(n.afk_channel_id=this.client.resolver.resolveChannel(e.afkChannel).id),e.afkTimeout&&(n.afk_timeout=Number(e.afkTimeout)),e.icon&&(n.icon=this.client.resolver.resolveBase64(e.icon)),e.owner&&(n.owner_id=this.client.resolver.resolveUser(e.owner).id),e.splash&&(n.splash=this.client.resolver.resolveBase64(e.splash)),this.rest.makeRequest("patch",i.Endpoints.guild(t.id),!0,n).then(t=>this.client.actions.GuildUpdate.handle(t).updated)}kickGuildMember(t,e){return this.rest.makeRequest("del",i.Endpoints.guildMember(t.id,e.id),!0).then(()=>this.client.actions.GuildMemberRemove.handle({guild_id:t.id,user:e.user}).member)}createGuildRole(t){return this.rest.makeRequest("post",i.Endpoints.guildRoles(t.id),!0).then(e=>this.client.actions.GuildRoleCreate.handle({guild_id:t.id,role:e}).role)}deleteGuildRole(t){return this.rest.makeRequest("del",i.Endpoints.guildRole(t.guild.id,t.id),!0).then(()=>this.client.actions.GuildRoleDelete.handle({guild_id:t.guild.id,role_id:t.id}).role)}setChannelOverwrite(t,e){return this.rest.makeRequest("put",`${i.Endpoints.channelPermissions(t.id)}/${e.id}`,!0,e)}deletePermissionOverwrites(t){return this.rest.makeRequest("del",`${i.Endpoints.channelPermissions(t.channel.id)}/${t.id}`,!0).then(()=>t)}getChannelMessages(t,e={}){const n=[];e.limit&&n.push(`limit=${e.limit}`),e.around?n.push(`around=${e.around}`):e.before?n.push(`before=${e.before}`):e.after&&n.push(`after=${e.after}`);let s=i.Endpoints.channelMessages(t.id);return n.length>0&&(s+=`?${n.join("&")}`),this.rest.makeRequest("get",s,!0)}getChannelMessage(t,e){const n=t.messages.get(e);return n?Promise.resolve(n):this.rest.makeRequest("get",i.Endpoints.channelMessage(t.id,e),!0)}getGuildMember(t,e){return this.rest.makeRequest("get",i.Endpoints.guildMember(t.id,e.id),!0).then(e=>this.client.actions.GuildMemberGet.handle(t,e).member)}updateGuildMember(t,e){e.channel&&(e.channel_id=this.client.resolver.resolveChannel(e.channel).id),e.roles&&(e.roles=e.roles.map(t=>t instanceof l?t.id:t));let n=i.Endpoints.guildMember(t.guild.id,t.id);if(t.id===this.client.user.id){const s=Object.keys(e);1===s.length&&"nick"===s[0]&&(n=i.Endpoints.guildMemberNickname(t.guild.id))}return this.rest.makeRequest("patch",n,!0,e).then(e=>t.guild._updateMember(t,e).mem)}addMemberRole(t,e){return this.rest.makeRequest("put",i.Endpoints.guildMemberRole(t.guild.id,t.id,e.id),!0).then(()=>{return t._roles.includes(e.id)||t._roles.push(e.id),t})}removeMemberRole(t,e){return this.rest.makeRequest("delete",i.Endpoints.guildMemberRole(t.guild.id,t.id,e.id),!0).then(()=>{const n=t._roles.indexOf(e.id);return n>=0&&t._roles.splice(n,1),t})}sendTyping(t){return this.rest.makeRequest("post",`${i.Endpoints.channel(t)}/typing`,!0)}banGuildMember(t,e,n=0){const s=this.client.resolver.resolveUserID(e);return s?this.rest.makeRequest("put",`${i.Endpoints.guildBans(t.id)}/${s}?delete-message-days=${n}`,!0,{"delete-message-days":n}).then(()=>{if(e instanceof u)return e;const n=this.client.resolver.resolveUser(s);return n?(e=this.client.resolver.resolveGuildMember(t,n),e||n):s}):Promise.reject(new Error("Couldn't resolve the user ID to ban."))}unbanGuildMember(t,e){return new Promise((n,s)=>{const r=this.client.resolver.resolveUserID(e);if(!r)throw new Error("Couldn't resolve the user ID to unban.");const o=(e,s)=>{e.id===t.id&&s.id===r&&(this.client.removeListener(i.Events.GUILD_BAN_REMOVE,o),this.client.clearTimeout(a),n(s))};this.client.on(i.Events.GUILD_BAN_REMOVE,o);const a=this.client.setTimeout(()=>{this.client.removeListener(i.Events.GUILD_BAN_REMOVE,o),s(new Error("Took too long to receive the ban remove event."))},1e4);this.rest.makeRequest("del",`${i.Endpoints.guildBans(t.id)}/${r}`,!0).catch(t=>{this.client.removeListener(i.Events.GUILD_BAN_REMOVE,o),this.client.clearTimeout(a),s(t)})})}getGuildBans(t){return this.rest.makeRequest("get",i.Endpoints.guildBans(t.id),!0).then(t=>{const e=new s;for(const n of t){const t=this.client.dataManager.newUser(n.user);e.set(t.id,t)}return e})}updateGuildRole(t,e){const n={};if(n.name=e.name||t.name,n.position="undefined"!=typeof e.position?e.position:t.position,n.color=e.color||t.color,"string"==typeof n.color&&n.color.startsWith("#")&&(n.color=parseInt(n.color.replace("#",""),16)),n.hoist="undefined"!=typeof e.hoist?e.hoist:t.hoist,n.mentionable="undefined"!=typeof e.mentionable?e.mentionable:t.mentionable,e.permissions){let t=0;for(let s of e.permissions)"string"==typeof s&&(s=i.PermissionFlags[s]),t|=s;n.permissions=t}else n.permissions=t.permissions;return this.rest.makeRequest("patch",i.Endpoints.guildRole(t.guild.id,t.id),!0,n).then(e=>this.client.actions.GuildRoleUpdate.handle({role:e,guild_id:t.guild.id}).updated)}pinMessage(t){return this.rest.makeRequest("put",`${i.Endpoints.channel(t.channel.id)}/pins/${t.id}`,!0).then(()=>t)}unpinMessage(t){return this.rest.makeRequest("del",`${i.Endpoints.channel(t.channel.id)}/pins/${t.id}`,!0).then(()=>t)}getChannelPinnedMessages(t){return this.rest.makeRequest("get",`${i.Endpoints.channel(t.id)}/pins`,!0)}createChannelInvite(t,e){const n={};return n.temporary=e.temporary,n.max_age=e.maxAge,n.max_uses=e.maxUses,this.rest.makeRequest("post",`${i.Endpoints.channelInvites(t.id)}`,!0,n).then(t=>new d(this.client,t))}deleteInvite(t){return this.rest.makeRequest("del",i.Endpoints.invite(t.code),!0).then(()=>t)}getInvite(t){return this.rest.makeRequest("get",i.Endpoints.invite(t),!0).then(t=>new d(this.client,t))}getGuildInvites(t){return this.rest.makeRequest("get",i.Endpoints.guildInvites(t.id),!0).then(t=>{const e=new s;for(const n of t){const t=new d(this.client,n);e.set(t.code,t)}return e})}pruneGuildMembers(t,e,n){return this.rest.makeRequest(n?"get":"post",`${i.Endpoints.guildPrune(t.id)}?days=${e}`,!0).then(t=>t.pruned)}createEmoji(t,e,n){return this.rest.makeRequest("post",`${i.Endpoints.guildEmojis(t.id)}`,!0,{name:n,image:e}).then(e=>this.client.actions.EmojiCreate.handle(e,t).emoji)}deleteEmoji(t){return this.rest.makeRequest("delete",`${i.Endpoints.guildEmojis(t.guild.id)}/${t.id}`,!0).then(()=>this.client.actions.EmojiDelete.handle(t).data)}getWebhook(t,e){return this.rest.makeRequest("get",i.Endpoints.webhook(t,e),!e).then(t=>new f(this.client,t))}getGuildWebhooks(t){return this.rest.makeRequest("get",i.Endpoints.guildWebhooks(t.id),!0).then(t=>{const e=new s;for(const n of t)e.set(n.id,new f(this.client,n));return e})}getChannelWebhooks(t){return this.rest.makeRequest("get",i.Endpoints.channelWebhooks(t.id),!0).then(t=>{const e=new s;for(const n of t)e.set(n.id,new f(this.client,n));return e})}createWebhook(t,e,n){return this.rest.makeRequest("post",i.Endpoints.channelWebhooks(t.id),!0,{name:e,avatar:n}).then(t=>new f(this.client,t))}editWebhook(t,e,n){return this.rest.makeRequest("patch",i.Endpoints.webhook(t.id,t.token),!1,{name:e,avatar:n}).then(e=>{return t.name=e.name,t.avatar=e.avatar,t})}deleteWebhook(t){return this.rest.makeRequest("delete",i.Endpoints.webhook(t.id,t.token),!1)}sendWebhookMessage(t,e,{avatarURL,tts,disableEveryone,embeds}={},n=null){return"undefined"!=typeof e&&(e=this.client.resolver.resolveString(e)),e&&(disableEveryone||"undefined"==typeof disableEveryone&&this.client.options.disableEveryone)&&(e=e.replace(/@(everyone|here)/g,"@​$1")),this.rest.makeRequest("post",`${i.Endpoints.webhook(t.id,t.token)}?wait=true`,!1,{username:t.name,avatar_url:avatarURL,content:e,tts:tts,file:n,embeds:embeds})}sendSlackWebhookMessage(t,e){return this.rest.makeRequest("post",`${i.Endpoints.webhook(t.id,t.token)}/slack?wait=true`,!1,e)}fetchUserProfile(t){return this.rest.makeRequest("get",i.Endpoints.userProfile(t.id),!0).then(e=>new p(t,e))}fetchMeMentions(t){return t.guild&&(t.guild=t.guild.id?t.guild.id:t.guild),this.rest.makeRequest("get",i.Endpoints.meMentions(t.limit,t.roles,t.everyone,t.guild)).then(t=>t.body.map(t=>new c(this.client.channels.get(t.channel_id),t,this.client)))}addFriend(t){return this.rest.makeRequest("post",i.Endpoints.relationships("@me"),!0,{username:t.username,discriminator:t.discriminator}).then(()=>t)}removeFriend(t){return this.rest.makeRequest("delete",`${i.Endpoints.relationships("@me")}/${t.id}`,!0).then(()=>t)}blockUser(t){return this.rest.makeRequest("put",`${i.Endpoints.relationships("@me")}/${t.id}`,!0,{type:2}).then(()=>t)}unblockUser(t){return this.rest.makeRequest("delete",`${i.Endpoints.relationships("@me")}/${t.id}`,!0).then(()=>t)}setRolePositions(t,e){return this.rest.makeRequest("patch",i.Endpoints.guildRoles(t),!0,e).then(()=>this.client.actions.GuildRolesPositionUpdate.handle({guild_id:t,roles:e}).guild)}addMessageReaction(t,e){return this.rest.makeRequest("put",i.Endpoints.selfMessageReaction(t.channel.id,t.id,e),!0).then(()=>this.client.actions.MessageReactionAdd.handle({user_id:this.client.user.id,message_id:t.id,emoji:o(e),channel_id:t.channel.id}).reaction)}removeMessageReaction(t,e,n){let s=i.Endpoints.selfMessageReaction(t.channel.id,t.id,e);return n.id!==this.client.user.id&&(s=i.Endpoints.userMessageReaction(t.channel.id,t.id,e,null,n.id)),this.rest.makeRequest("delete",s,!0).then(()=>this.client.actions.MessageReactionRemove.handle({user_id:n.id,message_id:t.id,emoji:o(e),channel_id:t.channel.id}).reaction)}removeMessageReactions(t){return this.rest.makeRequest("delete",i.Endpoints.messageReactions(t.channel.id,t.id),!0).then(()=>t)}getMessageReactionUsers(t,e,n=100){return this.rest.makeRequest("get",i.Endpoints.messageReaction(t.channel.id,t.id,e,n),!0)}getMyApplication(){return this.rest.makeRequest("get",i.Endpoints.myApplication,!0).then(t=>new m(this.client,t))}setNote(t,e){return this.rest.makeRequest("put",i.Endpoints.note(t.id),!0,{note:e}).then(()=>t)}}t.exports=g},function(t,e,n){const i=n(52);class s extends i{constructor(t,e){super(t,e),this.requestRemaining=1,this.first=!0}push(t){super.push(t),this.handle()}handleNext(t){this.waiting||(this.waiting=!0,this.restManager.client.setTimeout(()=>{this.requestRemaining=this.requestLimit,this.waiting=!1,this.handle()},t))}execute(t){t.request.gen().end((e,n)=>{if(n&&n.headers&&(this.requestLimit=n.headers["x-ratelimit-limit"],this.requestResetTime=1e3*Number(n.headers["x-ratelimit-reset"]),this.requestRemaining=Number(n.headers["x-ratelimit-remaining"]),this.timeDifference=Date.now()-new Date(n.headers.date).getTime(),this.handleNext(this.requestResetTime-Date.now()+this.timeDifference+this.restManager.client.options.restTimeOffset)),e)429===e.status?(this.requestRemaining=0,this.queue.unshift(t),this.restManager.client.setTimeout(()=>{this.globalLimit=!1,this.handle()},Number(n.headers["retry-after"])+this.restManager.client.options.restTimeOffset),n.headers["x-ratelimit-global"]&&(this.globalLimit=!0)):t.reject(e);else{this.globalLimit=!1;const e=n&&n.body?n.body:{};t.resolve(e),this.first&&(this.first=!1,this.handle())}})}handle(){if(super.handle(),!(this.requestRemaining<1||0===this.queue.length||this.globalLimit))for(;this.queue.length>0&&this.requestRemaining>0;)this.execute(this.queue.shift()),this.requestRemaining--}}t.exports=s},function(t,e,n){const i=n(52);class s extends i{constructor(t,e){super(t,e),this.waiting=!1,this.endpoint=e,this.timeDifference=0}push(t){super.push(t),this.handle()}execute(t){return new Promise(e=>{t.request.gen().end((n,i)=>{if(i&&i.headers&&(this.requestLimit=i.headers["x-ratelimit-limit"],this.requestResetTime=1e3*Number(i.headers["x-ratelimit-reset"]),this.requestRemaining=Number(i.headers["x-ratelimit-remaining"]),this.timeDifference=Date.now()-new Date(i.headers.date).getTime()),n)429===n.status?(this.restManager.client.setTimeout(()=>{this.waiting=!1,this.globalLimit=!1,e()},Number(i.headers["retry-after"])+this.restManager.client.options.restTimeOffset),i.headers["x-ratelimit-global"]&&(this.globalLimit=!0)):(this.queue.shift(),this.waiting=!1,t.reject(n),e(n));else{this.queue.shift(),this.globalLimit=!1;const n=i&&i.body?i.body:{};t.resolve(n),0===this.requestRemaining?this.restManager.client.setTimeout(()=>{this.waiting=!1,e(n)},this.requestResetTime-Date.now()+this.timeDifference+this.restManager.client.options.restTimeOffset):(this.waiting=!1,e(n))}})})}handle(){if(super.handle(),!this.waiting&&0!==this.queue.length&&!this.globalLimit){this.waiting=!0;const t=this.queue[0];this.execute(t).then(()=>this.handle())}}}t.exports=s},function(t,e,n){const i=n(0);class s{constructor(t){this.restManager=t,this._userAgent={url:"https://github.com/hydrabolt/discord.js",version:i.Package.version}}set(t){this._userAgent.url=t.url||"https://github.com/hydrabolt/discord.js",this._userAgent.version=t.version||i.Package.version}get userAgent(){return`DiscordBot (${this._userAgent.url}, ${this._userAgent.version})`}}t.exports=s},function(t,e,n){(function(e){const i="undefined"!=typeof window,s=n(21).EventEmitter,r=n(0),o=n(53),a=n(67),h=n(49),u=n(116);let c,l,d=JSON.stringify;if(i)c=window.WebSocket;else{try{c=n(158)}catch(t){c=n(159)}try{l=n(157),d=l.pack}catch(t){l=null}}class f extends s{constructor(t){super(),this.client=t,this.packetManager=new u(this),this.status=r.Status.IDLE,this.sessionID=null,this.sequence=-1,this.gateway=null,this.normalReady=!1,this.ws=null,this.disabledEvents={};for(const e of t.options.disabledEvents)this.disabledEvents[e]=!0;this.first=!0,this.lastHeartbeatAck=!0}_connect(t){this.client.emit("debug",`Connecting to gateway ${t}`),this.normalReady=!1,this.status!==r.Status.RECONNECTING&&(this.status=r.Status.CONNECTING),this.ws=new c(t),i&&(this.ws.binaryType="arraybuffer"),this.ws.onopen=this.eventOpen.bind(this),this.ws.onmessage=this.eventMessage.bind(this),this.ws.onclose=this.eventClose.bind(this),this.ws.onerror=this.eventError.bind(this),this._queue=[],this._remaining=120,this.client.setInterval(()=>{this._remaining=120,this._remainingReset=Date.now()},6e4)}connect(t){t=`${t}&encoding=${l?"etf":"json"}`,this.first?(this._connect(t),this.first=!1):this.client.setTimeout(()=>this._connect(t),5500)}heartbeat(t){return t&&!this.lastHeartbeatAck?void this.ws.close(1007):(this.client.emit("debug","Sending heartbeat"),this.client._pingTimestamp=Date.now(),this.client.ws.send({op:r.OPCodes.HEARTBEAT,d:this.sequence},!0),void(this.lastHeartbeatAck=!1))}send(t,e=false){return e?void this._send(d(t)):(this._queue.push(d(t)),void this.doQueue())}destroy(){this.ws.close(1e3),this._queue=[],this.status=r.Status.IDLE}_send(t){this.ws.readyState===c.OPEN&&(this.emit("send",t),this.ws.send(t))}doQueue(){const t=this._queue[0];if(this.ws.readyState===c.OPEN&&t){if(0===this.remaining)return void this.client.setTimeout(this.doQueue.bind(this),Date.now()-this.remainingReset);this._remaining--,this._send(t),this._queue.shift(),this.doQueue()}}eventOpen(){this.client.emit("debug","Connection to gateway opened"),this.lastHeartbeatAck=!0,this.status===r.Status.RECONNECTING?this._sendResume():this._sendNewIdentify()}_sendResume(){if(!this.sessionID)return void this._sendNewIdentify();this.client.emit("debug","Identifying as resumed session");const t={token:this.client.token,session_id:this.sessionID,seq:this.sequence};this.send({op:r.OPCodes.RESUME,d:t})}_sendNewIdentify(){this.reconnecting=!1;const t=this.client.options.ws;t.token=this.client.token,this.client.options.shardCount>0&&(t.shard=[Number(this.client.options.shardId),Number(this.client.options.shardCount)]),this.client.emit("debug","Identifying as new session"),this.send({op:r.OPCodes.IDENTIFY,d:t}),this.sequence=-1}eventClose(t){this.emit("close",t),this.client.clearInterval(this.client.manager.heartbeatInterval),this.status=r.Status.DISCONNECTED,this._queue=[],this.reconnecting||this.client.emit(r.Events.DISCONNECT,t),4004!==t.code&&4010!==t.code&&(this.reconnecting||1e3===t.code||this.tryReconnect())}eventMessage(t){const e=this.tryParseEventData(t.data);return null===e?(this.eventError(new Error(r.Errors.BAD_WS_MESSAGE)),!1):(this.client.emit("raw",e),e.op===r.OPCodes.HELLO&&this.client.manager.setupKeepAlive(e.d.heartbeat_interval),this.packetManager.handle(e))}parseEventData(t){return l?(t instanceof ArrayBuffer&&(t=o(t)),l.unpack(t)):(t instanceof ArrayBuffer?t=a.inflate(t,{to:"string"}):t instanceof e&&(t=h.inflateSync(t).toString()),JSON.parse(t))}tryParseEventData(t){try{return this.parseEventData(t)}catch(t){return null}}eventError(t){this.client.listenerCount("error")>0&&this.client.emit("error",t),this.tryReconnect()}_emitReady(t=true){this.status=r.Status.READY,this.client.emit(r.Events.READY),this.packetManager.handleQueue(),this.normalReady=t}checkIfReady(){if(this.status!==r.Status.READY&&this.status!==r.Status.NEARLY){let t=0;for(const e of this.client.guilds.keys())t+=this.client.guilds.get(e).available?0:1;if(0===t){if(this.status=r.Status.NEARLY,this.client.options.fetchAllMembers){const t=this.client.guilds.map(t=>t.fetchMembers());return void Promise.all(t).then(()=>this._emitReady(),t=>{this.client.emit(r.Events.WARN,"Error in pre-ready guild member fetching"),this.client.emit(r.Events.ERROR,t),this._emitReady()})}this._emitReady()}}}tryReconnect(){this.status!==r.Status.RECONNECTING&&this.status!==r.Status.CONNECTING&&(this.status=r.Status.RECONNECTING,this.ws.close(),this.packetManager.handleQueue(),this.client.emit(r.Events.RECONNECTING),this.connect(this.client.ws.gateway))}}t.exports=f}).call(e,n(20).Buffer)},function(t,e,n){const i=n(0),s=[i.WSEvents.READY,i.WSEvents.GUILD_CREATE,i.WSEvents.GUILD_DELETE,i.WSEvents.GUILD_MEMBERS_CHUNK,i.WSEvents.GUILD_MEMBER_ADD,i.WSEvents.GUILD_MEMBER_REMOVE];class r{constructor(t){this.ws=t,this.handlers={},this.queue=[],this.register(i.WSEvents.READY,n(143)),this.register(i.WSEvents.GUILD_CREATE,n(123)),this.register(i.WSEvents.GUILD_DELETE,n(124)),this.register(i.WSEvents.GUILD_UPDATE,n(134)),this.register(i.WSEvents.GUILD_BAN_ADD,n(121)),this.register(i.WSEvents.GUILD_BAN_REMOVE,n(122)),this.register(i.WSEvents.GUILD_MEMBER_ADD,n(126)),this.register(i.WSEvents.GUILD_MEMBER_REMOVE,n(127)),this.register(i.WSEvents.GUILD_MEMBER_UPDATE,n(128)),this.register(i.WSEvents.GUILD_ROLE_CREATE,n(130)),this.register(i.WSEvents.GUILD_ROLE_DELETE,n(131)),this.register(i.WSEvents.GUILD_ROLE_UPDATE,n(132)),this.register(i.WSEvents.GUILD_EMOJIS_UPDATE,n(125)),this.register(i.WSEvents.GUILD_MEMBERS_CHUNK,n(129)),this.register(i.WSEvents.CHANNEL_CREATE,n(117)),this.register(i.WSEvents.CHANNEL_DELETE,n(118)),this.register(i.WSEvents.CHANNEL_UPDATE,n(120)),this.register(i.WSEvents.CHANNEL_PINS_UPDATE,n(119)),this.register(i.WSEvents.PRESENCE_UPDATE,n(142)),this.register(i.WSEvents.USER_UPDATE,n(148)),this.register(i.WSEvents.USER_NOTE_UPDATE,n(147)),this.register(i.WSEvents.VOICE_STATE_UPDATE,n(150)),this.register(i.WSEvents.TYPING_START,n(146)),this.register(i.WSEvents.MESSAGE_CREATE,n(135)),this.register(i.WSEvents.MESSAGE_DELETE,n(136)),this.register(i.WSEvents.MESSAGE_UPDATE,n(141)),this.register(i.WSEvents.MESSAGE_DELETE_BULK,n(137)),this.register(i.WSEvents.VOICE_SERVER_UPDATE,n(149)),this.register(i.WSEvents.GUILD_SYNC,n(133)),this.register(i.WSEvents.RELATIONSHIP_ADD,n(144)),this.register(i.WSEvents.RELATIONSHIP_REMOVE,n(145)),this.register(i.WSEvents.MESSAGE_REACTION_ADD,n(138)),this.register(i.WSEvents.MESSAGE_REACTION_REMOVE,n(139)),this.register(i.WSEvents.MESSAGE_REACTION_REMOVE_ALL,n(140))}get client(){return this.ws.client}register(t,e){this.handlers[t]=new e(this)}handleQueue(){this.queue.forEach((t,e)=>{this.handle(this.queue[e]),this.queue.splice(e,1)})}setSequence(t){t&&t>this.ws.sequence&&(this.ws.sequence=t)}handle(t){return t.op===i.OPCodes.RECONNECT?(this.setSequence(t.s),this.ws.tryReconnect(),!1):t.op===i.OPCodes.INVALID_SESSION?(t.d?setTimeout(()=>{this.ws._sendResume()},2500):(this.ws.sessionID=null,this.ws._sendNewIdentify()),!1):(t.op===i.OPCodes.HEARTBEAT_ACK?(this.ws.client._pong(this.ws.client._pingTimestamp),this.ws.lastHeartbeatAck=!0,this.ws.client.emit("debug","Heartbeat acknowledged")):t.op===i.OPCodes.HEARTBEAT&&(this.client.ws.send({op:i.OPCodes.HEARTBEAT,d:this.client.ws.sequence}),this.ws.client.emit("debug","Received gateway heartbeat")),this.ws.status===i.Status.RECONNECTING&&(this.ws.reconnecting=!1,this.ws.checkIfReady()),this.setSequence(t.s),void 0===this.ws.disabledEvents[t.t]&&(this.ws.status!==i.Status.READY&&s.indexOf(t.t)===-1?(this.queue.push(t),!1):!!this.handlers[t.t]&&this.handlers[t.t].handle(t)))}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.ChannelCreate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.actions.ChannelDelete.handle(n);i.channel&&e.emit(s.Events.CHANNEL_DELETE,i.channel)}}t.exports=r},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.channels.get(n.channel_id),r=new Date(n.last_pin_timestamp);i&&r&&e.emit(s.Events.CHANNEL_PINS_UPDATE,i,r)}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.ChannelUpdate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.guilds.get(n.guild_id),r=e.users.get(n.user.id);i&&r&&e.emit(s.Events.GUILD_BAN_ADD,i,r)}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildBanRemove.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.guilds.get(n.id);i?i.available||n.unavailable||(i.setup(n),this.packetManager.ws.checkIfReady()):e.dataManager.newGuild(n)}}t.exports=s},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.actions.GuildDelete.handle(n);i.guild&&e.emit(s.Events.GUILD_DELETE,i.guild)}}t.exports=r},function(t,e,n){function i(t){const e=new Map;for(const n of t)e.set(...n);return e}const s=n(1);class r extends s{handle(t){const e=this.packetManager.client,n=t.d,s=e.guilds.get(n.guild_id);if(s&&s.emojis){const t=i(s.emojis.entries());for(const r of n.emojis){const n=s.emojis.get(r.id);n?(t.delete(r.id),n.equals(r,!0)||e.actions.GuildEmojiUpdate.handle(n,r)):e.actions.GuildEmojiCreate.handle(s,r)}for(const r of t.values())e.actions.GuildEmojiDelete.handle(r)}}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.guilds.get(n.guild_id);i&&(i.memberCount++,i._addMember(n))}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildMemberRemove.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.guilds.get(n.guild_id);if(i){const t=i.members.get(n.user.id);t&&i._updateMember(t,n)}}}t.exports=s},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.guilds.get(n.guild_id);if(i){const t=n.members.map(t=>i._addMember(t,!1));i._checkChunks(),e.emit(s.Events.GUILD_MEMBERS_CHUNK,t),e.ws.lastHeartbeatAck=!0}}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildRoleCreate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildRoleDelete.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildRoleUpdate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildSync.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.GuildUpdate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.actions.MessageCreate.handle(n);i.message&&e.emit(s.Events.MESSAGE_CREATE,i.message)}}t.exports=r},function(t,e,n){const i=n(1),s=n(0);class r extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.actions.MessageDelete.handle(n);i.message&&e.emit(s.Events.MESSAGE_DELETE,i.message)}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.MessageDeleteBulk.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.MessageReactionAdd.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.MessageReactionRemove.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.MessageReactionRemoveAll.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.MessageUpdate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1),s=n(0),r=n(4);class o extends i{handle(t){const e=this.packetManager.client,n=t.d;let i=e.users.get(n.user.id);const o=e.guilds.get(n.guild_id);if(!i){if(!n.user.username)return;i=e.dataManager.newUser(n.user)}const a=r(i);if(i.patch(n.user),i.equals(a)||e.emit(s.Events.USER_UPDATE,a,i),o){let t=o.members.get(i.id);if(t||"offline"===n.status||(t=o._addMember({user:i,roles:n.roles,deaf:!1,mute:!1},!1),e.emit(s.Events.GUILD_MEMBER_AVAILABLE,t)),t){const a=r(t);t.presence&&(a.frozenPresence=r(t.presence)),o._setPresence(i.id,n),e.emit(s.Events.PRESENCE_UPDATE,a,t)}else o._setPresence(i.id,n)}}}t.exports=o},function(t,e,n){const i=n(1),s=n(29);class r extends i{handle(t){const e=this.packetManager.client,n=t.d;e.ws.heartbeat();const i=new s(e,n.user);e.user=i,e.readyAt=new Date,e.users.set(i.id,i);for(const r of n.guilds)e.dataManager.newGuild(r);for(const o of n.private_channels)e.dataManager.newChannel(o);for(const a of n.relationships){const t=e.dataManager.newUser(a.user);1===a.type?e.user.friends.set(t.id,t):2===a.type&&e.user.blocked.set(t.id,t)}n.presences=n.presences||[];for(const h of n.presences)e.dataManager.newUser(h.user),e._setPresence(h.user.id,h);if(n.notes)for(const u in n.notes){let t=n.notes[u];t.length||(t=null),e.user.notes.set(u,t)}!e.user.bot&&e.options.sync&&e.setInterval(e.syncGuilds.bind(e),3e4),e.once("ready",e.syncGuilds.bind(e)),e.users.has("1")||e.dataManager.newUser({id:"1",username:"Clyde",discriminator:"0000",avatar:"https://discordapp.com/assets/f78426a064bc9dd24847519259bc42af.png",bot:!0,status:"online",game:null,verified:!0}),e.setTimeout(()=>{e.ws.normalReady||e.ws._emitReady(!1)},1200*n.guilds.length),this.packetManager.ws.sessionID=n.session_id,this.packetManager.ws.checkIfReady()}}t.exports=r},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;1===n.type?e.fetchUser(n.id).then(t=>{e.user.friends.set(t.id,t)}):2===n.type&&e.fetchUser(n.id).then(t=>{e.user.blocked.set(t.id,t)})}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;2===n.type?e.user.blocked.has(n.id)&&e.user.blocked.delete(n.id):1===n.type&&e.user.friends.has(n.id)&&e.user.friends.delete(n.id)}}t.exports=s},function(t,e,n){function i(t,e){return t.client.setTimeout(()=>{t.client.emit(r.Events.TYPING_STOP,t,e,t._typing.get(e.id)),t._typing.delete(e.id)},6e3)}const s=n(1),r=n(0);class o extends s{handle(t){const e=this.packetManager.client,n=t.d,s=e.channels.get(n.channel_id),o=e.users.get(n.user_id),h=new Date(1e3*n.timestamp);if(s&&o){if("voice"===s.type)return void e.emit(r.Events.WARN,`Discord sent a typing packet to voice channel ${s.id}`);if(s._typing.has(o.id)){const t=s._typing.get(o.id);t.lastTimestamp=h,t.resetTimeout(i(s,o))}else s._typing.set(o.id,new a(e,h,h,i(s,o))),e.emit(r.Events.TYPING_START,s,o)}}}class a{constructor(t,e,n,i){this.client=t,this.since=e,this.lastTimestamp=n,this._timeout=i}resetTimeout(t){this.client.clearTimeout(this._timeout),this._timeout=t}get elapsedTime(){return Date.now()-this.since}}t.exports=o},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.UserNoteUpdate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.actions.UserUpdate.handle(n)}}t.exports=s},function(t,e,n){const i=n(1);class s extends i{handle(t){const e=this.packetManager.client,n=t.d;e.emit("self.voiceServer",n)}}t.exports=s},function(t,e,n){const i=n(1),s=n(0),r=n(4);class o extends i{handle(t){const e=this.packetManager.client,n=t.d,i=e.guilds.get(n.guild_id);if(i){const t=i.members.get(n.user_id);if(t){ -const i=r(t);t.voiceChannel&&t.voiceChannel.id!==n.channel_id&&t.voiceChannel.members.delete(i.id),n.channel_id||(t.speaking=null),t.user.id===e.user.id&&n.channel_id&&e.emit("self.voiceStateUpdate",n);const o=e.channels.get(n.channel_id);o&&o.members.set(t.user.id,t),t.serverMute=n.mute,t.serverDeaf=n.deaf,t.selfMute=n.self_mute,t.selfDeaf=n.self_deaf,t.voiceSessionID=n.session_id,t.voiceChannelID=n.channel_id,e.emit(s.Events.VOICE_STATE_UPDATE,i,t)}}}}t.exports=o},function(t,e){class n{constructor(t,e){this.user=t,this.setup(e)}setup(t){this.type=t.type,this.name=t.name,this.id=t.id,this.revoked=t.revoked,this.integrations=t.integrations}}t.exports=n},function(t,e,n){const i=n(3),s=n(151);class r{constructor(t,e){this.user=t,Object.defineProperty(this,"client",{value:t.client}),this.mutualGuilds=new i,this.connections=new i,this.setup(e)}setup(t){this.premium=t.premium;for(const e of t.mutual_guilds)this.client.guilds.has(e.id)&&this.mutualGuilds.set(e.id,this.client.guilds.get(e.id));for(const n of t.connected_accounts)this.connections.set(n.id,new s(this.user,n))}}t.exports=r},function(t,e){t.exports=function(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(const n in t){const i=t[n],s=e.indexOf(i);s&&e.splice(s,1)}return 0===e.length}},function(t,e){t.exports=function(t){if(t.includes("%")&&(t=decodeURIComponent(t)),t.includes(":")){const[e,n]=t.split(":");return{name:e,id:n}}return{name:t,id:null}}},function(t,e){},function(t,e){},function(t,e){},function(t,e){},function(t,e){}]); \ No newline at end of file diff --git a/discord.11.1-dev-datastores.js b/discord.11.1-dev-datastores.js deleted file mode 100644 index 9896c345..00000000 --- a/discord.11.1-dev-datastores.js +++ /dev/null @@ -1,27017 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); -/******/ } -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 74); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process) {exports.Package = __webpack_require__(54); - -/** - * Options for a client. - * @typedef {Object} ClientOptions - * @property {string} [apiRequestMethod='sequential'] One of `sequential` or `burst`. The sequential handler executes - * all requests in the order they are triggered, whereas the burst handler runs multiple in parallel, and doesn't - * provide the guarantee of any particular order. Burst mode is more likely to hit a 429 ratelimit error by its nature, - * and is therefore slightly riskier to use. - * @property {number} [shardId=0] ID of the shard to run - * @property {number} [shardCount=0] Total number of shards - * @property {number} [messageCacheMaxSize=200] Maximum number of messages to cache per channel - * (-1 or Infinity for unlimited - don't do this without message sweeping, otherwise memory usage will climb - * indefinitely) - * @property {number} [messageCacheLifetime=0] How long a message should stay in the cache until it is considered - * sweepable (in seconds, 0 for forever) - * @property {number} [messageSweepInterval=0] How frequently to remove messages from the cache that are older than - * the message cache lifetime (in seconds, 0 for never) - * @property {boolean} [fetchAllMembers=false] Whether to cache all guild members and users upon startup, as well as - * upon joining a guild (should be avoided whenever possible) - * @property {boolean} [disableEveryone=false] Default value for {@link MessageOptions#disableEveryone} - * @property {boolean} [sync=false] Whether to periodically sync guilds (for user accounts) - * @property {number} [restWsBridgeTimeout=5000] Maximum time permitted between REST responses and their - * corresponding websocket events - * @property {number} [restTimeOffset=500] Extra time in millseconds to wait before continuing to make REST - * requests (higher values will reduce rate-limiting errors on bad connections) - * @property {WSEventType[]} [disabledEvents] An array of disabled websocket events. Events in this array will not be - * processed, potentially resulting in performance improvements for larger bots. Only disable events you are - * 100% certain you don't need, as many are important, but not obviously so. The safest one to disable with the - * most impact is typically `TYPING_START`. - * @property {WebsocketOptions} [ws] Options for the WebSocket - * @property {HTTPOptions} [http] HTTP options - */ -exports.DefaultOptions = { - apiRequestMethod: 'sequential', - shardId: 0, - shardCount: 0, - messageCacheMaxSize: 200, - messageCacheLifetime: 0, - messageSweepInterval: 0, - fetchAllMembers: false, - disableEveryone: false, - sync: false, - restWsBridgeTimeout: 5000, - disabledEvents: [], - restTimeOffset: 500, - - /** - * WebSocket options (these are left as snake_case to match the API) - * @typedef {Object} WebsocketOptions - * @property {number} [large_threshold=250] Number of members in a guild to be considered large - * @property {boolean} [compress=true] Whether to compress data sent on the connection - * (defaults to `false` for browsers) - */ - ws: { - large_threshold: 250, - compress: __webpack_require__(105).platform() !== 'browser', - properties: { - $os: process ? process.platform : 'discord.js', - $browser: 'discord.js', - $device: 'discord.js', - $referrer: '', - $referring_domain: '', - }, - version: 6, - }, - - /** - * HTTP options - * @typedef {Object} HTTPOptions - * @property {number} [version=7] API version to use - * @property {string} [api='https://discordapp.com/api'] Base url of the API - * @property {string} [cdn='https://cdn.discordapp.com'] Base url of the CDN - * @property {string} [invite='https://discord.gg'] Base url of invites - */ - http: { - version: 7, - host: 'https://discordapp.com', - cdn: 'https://cdn.discordapp.com', - }, -}; - -exports.WSCodes = { - 1000: 'Connection gracefully closed', - 4004: 'Tried to identify with an invalid token', - 4010: 'Sharding data provided was invalid', - 4011: 'Shard would be on too many guilds if connected', -}; - -exports.Errors = { - NO_TOKEN: 'Request to use token, but token was unavailable to the client.', - NO_BOT_ACCOUNT: 'Only bot accounts are able to make use of this feature.', - NO_USER_ACCOUNT: 'Only user accounts are able to make use of this feature.', - BAD_WS_MESSAGE: 'A bad message was received from the websocket; either bad compression, or not JSON.', - TOOK_TOO_LONG: 'Something took too long to do.', - NOT_A_PERMISSION: 'Invalid permission string or number.', - INVALID_RATE_LIMIT_METHOD: 'Unknown rate limiting method.', - BAD_LOGIN: 'Incorrect login details were provided.', - INVALID_SHARD: 'Invalid shard settings were provided.', - SHARDING_REQUIRED: 'This session would have handled too many guilds - Sharding is required.', - INVALID_TOKEN: 'An invalid token was provided.', -}; - -const Endpoints = exports.Endpoints = { - User: userID => { - if (userID.id) userID = userID.id; - const base = `/users/${userID}`; - return { - toString: () => base, - channels: `${base}/channels`, - profile: `${base}/profile`, - relationships: `${base}/relationships`, - settings: `${base}/settings`, - Relationship: uID => `${base}/relationships/${uID}`, - Guild: guildID => ({ - toString: () => `${base}/guilds/${guildID}`, - settings: `${base}/guilds/${guildID}/settings`, - }), - Note: id => `${base}/notes/${id}`, - Mentions: (limit, roles, everyone, guildID) => - `${base}/mentions?limit=${limit}&roles=${roles}&everyone=${everyone}${guildID ? `&guild_id=${guildID}` : ''}`, - Avatar: (root, hash) => { - if (userID === '1') return hash; - return Endpoints.CDN(root).Avatar(userID, hash); - }, - }; - }, - guilds: '/guilds', - Guild: guildID => { - if (guildID.id) guildID = guildID.id; - const base = `/guilds/${guildID}`; - return { - toString: () => base, - prune: `${base}/prune`, - embed: `${base}/embed`, - bans: `${base}/bans`, - integrations: `${base}/integrations`, - members: `${base}/members`, - channels: `${base}/channels`, - invites: `${base}/invites`, - roles: `${base}/roles`, - emojis: `${base}/emojis`, - search: `${base}/messages/search`, - voiceRegions: `${base}/regions`, - webhooks: `${base}/webhooks`, - ack: `${base}/ack`, - settings: `${base}/settings`, - auditLogs: `${base}/audit-logs`, - Emoji: emojiID => `${base}/emojis/${emojiID}`, - Icon: (root, hash) => Endpoints.CDN(root).Icon(guildID, hash), - Splash: (root, hash) => Endpoints.CDN(root).Splash(guildID, hash), - Role: roleID => `${base}/roles/${roleID}`, - Member: memberID => { - if (memberID.id) memberID = memberID.id; - const mbase = `${base}/members/${memberID}`; - return { - toString: () => mbase, - Role: roleID => `${mbase}/roles/${roleID}`, - nickname: `${base}/members/@me/nick`, - }; - }, - }; - }, - channels: '/channels', - Channel: channelID => { - if (channelID.id) channelID = channelID.id; - const base = `/channels/${channelID}`; - return { - toString: () => base, - messages: { - toString: () => `${base}/messages`, - bulkDelete: `${base}/messages/bulk-delete`, - }, - invites: `${base}/invites`, - typing: `${base}/typing`, - permissions: `${base}/permissions`, - webhooks: `${base}/webhooks`, - search: `${base}/messages/search`, - pins: `${base}/pins`, - Icon: (root, hash) => Endpoints.CDN(root).GDMIcon(channelID, hash), - Pin: messageID => `${base}/pins/${messageID}`, - Recipient: recipientID => `${base}/recipients/${recipientID}`, - Message: messageID => { - if (messageID.id) messageID = messageID.id; - const mbase = `${base}/messages/${messageID}`; - return { - toString: () => mbase, - reactions: `${mbase}/reactions`, - ack: `${mbase}/ack`, - Reaction: (emoji, limit) => { - const rbase = `${mbase}/reactions/${emoji}${limit ? `?limit=${limit}` : ''}`; - return { - toString: () => rbase, - User: userID => `${rbase}/${userID}`, - }; - }, - }; - }, - }; - }, - Message: m => exports.Endpoints.Channel(m.channel).Message(m), - Member: m => exports.Endpoints.Guild(m.guild).Member(m), - CDN(root) { - return { - Emoji: emojiID => `${root}/emojis/${emojiID}.png`, - Asset: name => `${root}/assets/${name}`, - Avatar: (userID, hash) => `${root}/avatars/${userID}/${hash}.${hash.startsWith('a_') ? 'gif' : 'png'}?size=2048`, - Icon: (guildID, hash) => `${root}/icons/${guildID}/${hash}.jpg`, - GDMIcon: (channelID, hash) => `${root}/channel-icons/${channelID}/${hash}.jpg?size=2048`, - Splash: (guildID, hash) => `${root}/splashes/${guildID}/${hash}.jpg`, - }; - }, - OAUTH2: { - Application: appID => { - const base = `/oauth2/applications/${appID}`; - return { - toString: () => base, - resetSecret: `${base}/reset`, - resetToken: `${base}/bot/reset`, - }; - }, - App: appID => `/oauth2/authorize?client_id=${appID}`, - }, - login: '/auth/login', - logout: '/auth/logout', - voiceRegions: '/voice/regions', - gateway: { - toString: () => '/gateway', - bot: '/gateway/bot', - }, - Invite: inviteID => `/invite/${inviteID}?with_counts=true`, - inviteLink: id => `https://discord.gg/${id}`, - Webhook: (webhookID, token) => `/webhooks/${webhookID}${token ? `/${token}` : ''}`, -}; - - -/** - * The current status of the client. Here are the available statuses: - * * READY - * * CONNECTING - * * RECONNECTING - * * IDLE - * * NEARLY - * * DISCONNECTED - * @typedef {number} Status - */ -exports.Status = { - READY: 0, - CONNECTING: 1, - RECONNECTING: 2, - IDLE: 3, - NEARLY: 4, - DISCONNECTED: 5, -}; - -/** - * The current status of a voice connection. Here are the available statuses: - * * CONNECTED - * * CONNECTING - * * AUTHENTICATING - * * RECONNECTING - * * DISCONNECTED - * @typedef {number} VoiceStatus - */ -exports.VoiceStatus = { - CONNECTED: 0, - CONNECTING: 1, - AUTHENTICATING: 2, - RECONNECTING: 3, - DISCONNECTED: 4, -}; - -exports.ChannelTypes = { - TEXT: 0, - DM: 1, - VOICE: 2, - GROUP_DM: 3, -}; - -exports.OPCodes = { - DISPATCH: 0, - HEARTBEAT: 1, - IDENTIFY: 2, - STATUS_UPDATE: 3, - VOICE_STATE_UPDATE: 4, - VOICE_GUILD_PING: 5, - RESUME: 6, - RECONNECT: 7, - REQUEST_GUILD_MEMBERS: 8, - INVALID_SESSION: 9, - HELLO: 10, - HEARTBEAT_ACK: 11, -}; - -exports.VoiceOPCodes = { - IDENTIFY: 0, - SELECT_PROTOCOL: 1, - READY: 2, - HEARTBEAT: 3, - SESSION_DESCRIPTION: 4, - SPEAKING: 5, -}; - -exports.Events = { - READY: 'ready', - RESUME: 'resume', - GUILD_CREATE: 'guildCreate', - GUILD_DELETE: 'guildDelete', - GUILD_UPDATE: 'guildUpdate', - GUILD_UNAVAILABLE: 'guildUnavailable', - GUILD_AVAILABLE: 'guildAvailable', - GUILD_MEMBER_ADD: 'guildMemberAdd', - GUILD_MEMBER_REMOVE: 'guildMemberRemove', - GUILD_MEMBER_UPDATE: 'guildMemberUpdate', - GUILD_MEMBER_AVAILABLE: 'guildMemberAvailable', - GUILD_MEMBER_SPEAKING: 'guildMemberSpeaking', - GUILD_MEMBERS_CHUNK: 'guildMembersChunk', - GUILD_ROLE_CREATE: 'roleCreate', - GUILD_ROLE_DELETE: 'roleDelete', - GUILD_ROLE_UPDATE: 'roleUpdate', - GUILD_EMOJI_CREATE: 'emojiCreate', - GUILD_EMOJI_DELETE: 'emojiDelete', - GUILD_EMOJI_UPDATE: 'emojiUpdate', - GUILD_BAN_ADD: 'guildBanAdd', - GUILD_BAN_REMOVE: 'guildBanRemove', - CHANNEL_CREATE: 'channelCreate', - CHANNEL_DELETE: 'channelDelete', - CHANNEL_UPDATE: 'channelUpdate', - CHANNEL_PINS_UPDATE: 'channelPinsUpdate', - MESSAGE_CREATE: 'message', - MESSAGE_DELETE: 'messageDelete', - MESSAGE_UPDATE: 'messageUpdate', - MESSAGE_BULK_DELETE: 'messageDeleteBulk', - MESSAGE_REACTION_ADD: 'messageReactionAdd', - MESSAGE_REACTION_REMOVE: 'messageReactionRemove', - MESSAGE_REACTION_REMOVE_ALL: 'messageReactionRemoveAll', - USER_UPDATE: 'userUpdate', - USER_NOTE_UPDATE: 'userNoteUpdate', - USER_SETTINGS_UPDATE: 'clientUserSettingsUpdate', - USER_GUILD_SETTINGS_UPDATE: 'clientUserGuildSettingsUpdate', - PRESENCE_UPDATE: 'presenceUpdate', - VOICE_STATE_UPDATE: 'voiceStateUpdate', - TYPING_START: 'typingStart', - TYPING_STOP: 'typingStop', - DISCONNECT: 'disconnect', - RECONNECTING: 'reconnecting', - ERROR: 'error', - WARN: 'warn', - DEBUG: 'debug', -}; - -/** - * The type of a websocket message event, e.g. `MESSAGE_CREATE`. Here are the available events: - * * READY - * * RESUMED - * * GUILD_SYNC - * * GUILD_CREATE - * * GUILD_DELETE - * * GUILD_UPDATE - * * GUILD_MEMBER_ADD - * * GUILD_MEMBER_REMOVE - * * GUILD_MEMBER_UPDATE - * * GUILD_MEMBERS_CHUNK - * * GUILD_ROLE_CREATE - * * GUILD_ROLE_DELETE - * * GUILD_ROLE_UPDATE - * * GUILD_BAN_ADD - * * GUILD_BAN_REMOVE - * * CHANNEL_CREATE - * * CHANNEL_DELETE - * * CHANNEL_UPDATE - * * CHANNEL_PINS_UPDATE - * * MESSAGE_CREATE - * * MESSAGE_DELETE - * * MESSAGE_UPDATE - * * MESSAGE_DELETE_BULK - * * MESSAGE_REACTION_ADD - * * MESSAGE_REACTION_REMOVE - * * MESSAGE_REACTION_REMOVE_ALL - * * USER_UPDATE - * * USER_NOTE_UPDATE - * * USER_SETTINGS_UPDATE - * * PRESENCE_UPDATE - * * VOICE_STATE_UPDATE - * * TYPING_START - * * VOICE_SERVER_UPDATE - * * RELATIONSHIP_ADD - * * RELATIONSHIP_REMOVE - * @typedef {string} WSEventType - */ -exports.WSEvents = { - READY: 'READY', - RESUMED: 'RESUMED', - GUILD_SYNC: 'GUILD_SYNC', - GUILD_CREATE: 'GUILD_CREATE', - GUILD_DELETE: 'GUILD_DELETE', - GUILD_UPDATE: 'GUILD_UPDATE', - GUILD_MEMBER_ADD: 'GUILD_MEMBER_ADD', - GUILD_MEMBER_REMOVE: 'GUILD_MEMBER_REMOVE', - GUILD_MEMBER_UPDATE: 'GUILD_MEMBER_UPDATE', - GUILD_MEMBERS_CHUNK: 'GUILD_MEMBERS_CHUNK', - GUILD_ROLE_CREATE: 'GUILD_ROLE_CREATE', - GUILD_ROLE_DELETE: 'GUILD_ROLE_DELETE', - GUILD_ROLE_UPDATE: 'GUILD_ROLE_UPDATE', - GUILD_BAN_ADD: 'GUILD_BAN_ADD', - GUILD_BAN_REMOVE: 'GUILD_BAN_REMOVE', - GUILD_EMOJIS_UPDATE: 'GUILD_EMOJIS_UPDATE', - CHANNEL_CREATE: 'CHANNEL_CREATE', - CHANNEL_DELETE: 'CHANNEL_DELETE', - CHANNEL_UPDATE: 'CHANNEL_UPDATE', - CHANNEL_PINS_UPDATE: 'CHANNEL_PINS_UPDATE', - MESSAGE_CREATE: 'MESSAGE_CREATE', - MESSAGE_DELETE: 'MESSAGE_DELETE', - MESSAGE_UPDATE: 'MESSAGE_UPDATE', - MESSAGE_DELETE_BULK: 'MESSAGE_DELETE_BULK', - MESSAGE_REACTION_ADD: 'MESSAGE_REACTION_ADD', - MESSAGE_REACTION_REMOVE: 'MESSAGE_REACTION_REMOVE', - MESSAGE_REACTION_REMOVE_ALL: 'MESSAGE_REACTION_REMOVE_ALL', - USER_UPDATE: 'USER_UPDATE', - USER_NOTE_UPDATE: 'USER_NOTE_UPDATE', - USER_SETTINGS_UPDATE: 'USER_SETTINGS_UPDATE', - USER_GUILD_SETTINGS_UPDATE: 'USER_GUILD_SETTINGS_UPDATE', - PRESENCE_UPDATE: 'PRESENCE_UPDATE', - VOICE_STATE_UPDATE: 'VOICE_STATE_UPDATE', - TYPING_START: 'TYPING_START', - VOICE_SERVER_UPDATE: 'VOICE_SERVER_UPDATE', - RELATIONSHIP_ADD: 'RELATIONSHIP_ADD', - RELATIONSHIP_REMOVE: 'RELATIONSHIP_REMOVE', -}; - -/** - * The type of a message, e.g. `DEFAULT`. Here are the available types: - * * DEFAULT - * * RECIPIENT_ADD - * * RECIPIENT_REMOVE - * * CALL - * * CHANNEL_NAME_CHANGE - * * CHANNEL_ICON_CHANGE - * * PINS_ADD - * * GUILD_MEMBER_JOIN - * @typedef {string} MessageType - */ -exports.MessageTypes = [ - 'DEFAULT', - 'RECIPIENT_ADD', - 'RECIPIENT_REMOVE', - 'CALL', - 'CHANNEL_NAME_CHANGE', - 'CHANNEL_ICON_CHANGE', - 'PINS_ADD', - 'GUILD_MEMBER_JOIN', -]; - -/** - * The type of a message notification setting. Here are the available types: - * * EVERYTHING - * * MENTIONS - * * NOTHING - * * INHERIT (only for GuildChannel) - * @typedef {string} MessageNotificationType - */ -exports.MessageNotificationTypes = [ - 'EVERYTHING', - 'MENTIONS', - 'NOTHING', - 'INHERIT', -]; - -exports.DefaultAvatars = { - BLURPLE: '6debd47ed13483642cf09e832ed0bc1b', - GREY: '322c936a8c8be1b803cd94861bdfa868', - GREEN: 'dd4dbc0016779df1378e7812eabaa04d', - ORANGE: '0e291f67c9274a1abdddeb3fd919cbaa', - RED: '1cbd08c76f8af6dddce02c5138971129', -}; - -exports.ExplicitContentFilterTypes = [ - 'DISABLED', - 'NON_FRIENDS', - 'FRIENDS_AND_NON_FRIENDS', -]; - -exports.UserSettingsMap = { - /** - * Automatically convert emoticons in your messages to emoji - * For example, when you type `:-)` Discord will convert it to 😃 - * @name ClientUserSettings#convertEmoticons - * @type {boolean} - */ - convert_emoticons: 'convertEmoticons', - - /** - * If new guilds should automatically disable DMs between you and its members - * @name ClientUserSettings#defaultGuildsRestricted - * @type {boolean} - */ - default_guilds_restricted: 'defaultGuildsRestricted', - - /** - * Automatically detect accounts from services like Steam and Blizzard when you open the Discord client - * @name ClientUserSettings#detectPlatformAccounts - * @type {boolean} - */ - detect_platform_accounts: 'detectPlatformAccounts', - - /** - * Developer Mode exposes context menu items helpful for people writing bots using the Discord API - * @name ClientUserSettings#developerMode - * @type {boolean} - */ - developer_mode: 'developerMode', - - /** - * Allow playback and usage of the `/tts` command - * @name ClientUserSettings#enableTTSCommand - * @type {boolean} - */ - enable_tts_command: 'enableTTSCommand', - - /** - * The theme of the client. Either `light` or `dark` - * @name ClientUserSettings#theme - * @type {string} - */ - theme: 'theme', - - /** - * Last status set in the client - * @name ClientUserSettings#status - * @type {PresenceStatus} - */ - status: 'status', - - /** - * Display currently running game as status message - * @name ClientUserSettings#showCurrentGame - * @type {boolean} - */ - show_current_game: 'showCurrentGame', - - /** - * Display images, videos, and lolcats when uploaded directly to Discord - * @name ClientUserSettings#inlineAttachmentMedia - * @type {boolean} - */ - inline_attachment_media: 'inlineAttachmentMedia', - - /** - * Display images, videos, and lolcats when uploaded posted as links in chat - * @name ClientUserSettings#inlineEmbedMedia - * @type {boolean} - */ - inline_embed_media: 'inlineEmbedMedia', - - /** - * Language the Discord client will use, as an RFC 3066 language identifier - * @name ClientUserSettings#locale - * @type {string} - */ - locale: 'locale', - - /** - * Display messages in compact mode - * @name ClientUserSettings#messageDisplayCompact - * @type {boolean} - */ - message_display_compact: 'messageDisplayCompact', - - /** - * Show emoji reactions on messages - * @name ClientUserSettings#renderReactions - * @type {boolean} - */ - render_reactions: 'renderReactions', - - /** - * Array of snowflake IDs for guilds, in the order they appear in the Discord client - * @name ClientUserSettings#guildPositions - * @type {Snowflake[]} - */ - guild_positions: 'guildPositions', - - /** - * Array of snowflake IDs for guilds which you will not recieve DMs from - * @name ClientUserSettings#restrictedGuilds - * @type {Snowflake[]} - */ - restricted_guilds: 'restrictedGuilds', - - explicit_content_filter: function explicitContentFilter(type) { // eslint-disable-line func-name-matching - /** - * Safe direct messaging; force people's messages with images to be scanned before they are sent to you. - * One of `DISABLED`, `NON_FRIENDS`, `FRIENDS_AND_NON_FRIENDS` - * @name ClientUserSettings#explicitContentFilter - * @type {string} - */ - return exports.ExplicitContentFilterTypes[type]; - }, - friend_source_flags: function friendSources(flags) { // eslint-disable-line func-name-matching - /** - * Who can add you as a friend - * @name ClientUserSettings#friendSources - * @type {Object} - * @property {boolean} all Mutual friends and mutual guilds - * @property {boolean} mutualGuilds Only mutual guilds - * @property {boolean} mutualFriends Only mutual friends - */ - return { - all: flags.all || false, - mutualGuilds: flags.all ? true : flags.mutual_guilds || false, - mutualFriends: flags.all ? true : flags.mutualFriends || false, - }; - }, -}; - -exports.UserGuildSettingsMap = { - message_notifications: function messageNotifications(type) { // eslint-disable-line func-name-matching - /** - * The type of message that should notify you - * @name ClientUserGuildSettings#messageNotifications - * @type {MessageNotificationType} - */ - return exports.MessageNotificationTypes[type]; - }, - /** - * Whether to receive mobile push notifications - * @name ClientUserGuildSettings#mobilePush - * @type {boolean} - */ - mobile_push: 'mobilePush', - /** - * Whether the guild is muted - * @name ClientUserGuildSettings#muted - * @type {boolean} - */ - muted: 'muted', - /** - * Whether to suppress everyone mention - * @name ClientUserGuildSettings#suppressEveryone - * @type {boolean} - */ - suppress_everyone: 'suppressEveryone', - /** - * A collection containing all the channel overrides - * @name ClientUserGuildSettings#channelOverrides - * @type {Collection} - */ - channel_overrides: 'channelOverrides', -}; - -exports.UserChannelOverrideMap = { - message_notifications: function messageNotifications(type) { // eslint-disable-line func-name-matching - /** - * The type of message that should notify you - * @name ClientUserChannelOverride#messageNotifications - * @type {MessageNotificationType} - */ - return exports.MessageNotificationTypes[type]; - }, - /** - * Whether the channel is muted - * @name ClientUserChannelOverride#muted - * @type {boolean} - */ - muted: 'muted', -}; - -exports.Colors = { - DEFAULT: 0x000000, - AQUA: 0x1ABC9C, - GREEN: 0x2ECC71, - BLUE: 0x3498DB, - PURPLE: 0x9B59B6, - GOLD: 0xF1C40F, - ORANGE: 0xE67E22, - RED: 0xE74C3C, - GREY: 0x95A5A6, - NAVY: 0x34495E, - DARK_AQUA: 0x11806A, - DARK_GREEN: 0x1F8B4C, - DARK_BLUE: 0x206694, - DARK_PURPLE: 0x71368A, - DARK_GOLD: 0xC27C0E, - DARK_ORANGE: 0xA84300, - DARK_RED: 0x992D22, - DARK_GREY: 0x979C9F, - DARKER_GREY: 0x7F8C8D, - LIGHT_GREY: 0xBCC0C0, - DARK_NAVY: 0x2C3E50, - BLURPLE: 0x7289DA, - GREYPLE: 0x99AAB5, - DARK_BUT_NOT_BLACK: 0x2C2F33, - NOT_QUITE_BLACK: 0x23272A, -}; - -/** - * An error encountered while performing an API request. Here are the potential errors: - * * UNKNOWN_ACCOUNT - * * UNKNOWN_APPLICATION - * * UNKNOWN_CHANNEL - * * UNKNOWN_GUILD - * * UNKNOWN_INTEGRATION - * * UNKNOWN_INVITE - * * UNKNOWN_MEMBER - * * UNKNOWN_MESSAGE - * * UNKNOWN_OVERWRITE - * * UNKNOWN_PROVIDER - * * UNKNOWN_ROLE - * * UNKNOWN_TOKEN - * * UNKNOWN_USER - * * UNKNOWN_EMOJI - * * BOT_PROHIBITED_ENDPOINT - * * BOT_ONLY_ENDPOINT - * * MAXIMUM_GUILDS - * * MAXIMUM_FRIENDS - * * MAXIMUM_PINS - * * MAXIMUM_ROLES - * * MAXIMUM_REACTIONS - * * UNAUTHORIZED - * * MISSING_ACCESS - * * INVALID_ACCOUNT_TYPE - * * CANNOT_EXECUTE_ON_DM - * * EMBED_DISABLED - * * CANNOT_EDIT_MESSAGE_BY_OTHER - * * CANNOT_SEND_EMPTY_MESSAGE - * * CANNOT_MESSAGE_USER - * * CANNOT_SEND_MESSAGES_IN_VOICE_CHANNEL - * * CHANNEL_VERIFICATION_LEVEL_TOO_HIGH - * * OAUTH2_APPLICATION_BOT_ABSENT - * * MAXIMUM_OAUTH2_APPLICATIONS - * * INVALID_OAUTH_STATE - * * MISSING_PERMISSIONS - * * INVALID_AUTHENTICATION_TOKEN - * * NOTE_TOO_LONG - * * INVALID_BULK_DELETE_QUANTITY - * * CANNOT_PIN_MESSAGE_IN_OTHER_CHANNEL - * * CANNOT_EXECUTE_ON_SYSTEM_MESSAGE - * * BULK_DELETE_MESSAGE_TOO_OLD - * * INVITE_ACCEPTED_TO_GUILD_NOT_CONTANING_BOT - * * REACTION_BLOCKED - * @typedef {string} APIError - */ -exports.APIErrors = { - UNKNOWN_ACCOUNT: 10001, - UNKNOWN_APPLICATION: 10002, - UNKNOWN_CHANNEL: 10003, - UNKNOWN_GUILD: 10004, - UNKNOWN_INTEGRATION: 10005, - UNKNOWN_INVITE: 10006, - UNKNOWN_MEMBER: 10007, - UNKNOWN_MESSAGE: 10008, - UNKNOWN_OVERWRITE: 10009, - UNKNOWN_PROVIDER: 10010, - UNKNOWN_ROLE: 10011, - UNKNOWN_TOKEN: 10012, - UNKNOWN_USER: 10013, - UNKNOWN_EMOJI: 10014, - BOT_PROHIBITED_ENDPOINT: 20001, - BOT_ONLY_ENDPOINT: 20002, - MAXIMUM_GUILDS: 30001, - MAXIMUM_FRIENDS: 30002, - MAXIMUM_PINS: 30003, - MAXIMUM_ROLES: 30005, - MAXIMUM_REACTIONS: 30010, - UNAUTHORIZED: 40001, - MISSING_ACCESS: 50001, - INVALID_ACCOUNT_TYPE: 50002, - CANNOT_EXECUTE_ON_DM: 50003, - EMBED_DISABLED: 50004, - CANNOT_EDIT_MESSAGE_BY_OTHER: 50005, - CANNOT_SEND_EMPTY_MESSAGE: 50006, - CANNOT_MESSAGE_USER: 50007, - CANNOT_SEND_MESSAGES_IN_VOICE_CHANNEL: 50008, - CHANNEL_VERIFICATION_LEVEL_TOO_HIGH: 50009, - OAUTH2_APPLICATION_BOT_ABSENT: 50010, - MAXIMUM_OAUTH2_APPLICATIONS: 50011, - INVALID_OAUTH_STATE: 50012, - MISSING_PERMISSIONS: 50013, - INVALID_AUTHENTICATION_TOKEN: 50014, - NOTE_TOO_LONG: 50015, - INVALID_BULK_DELETE_QUANTITY: 50016, - CANNOT_PIN_MESSAGE_IN_OTHER_CHANNEL: 50019, - CANNOT_EXECUTE_ON_SYSTEM_MESSAGE: 50021, - BULK_DELETE_MESSAGE_TOO_OLD: 50034, - INVITE_ACCEPTED_TO_GUILD_NOT_CONTANING_BOT: 50036, - REACTION_BLOCKED: 90001, -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) - -/***/ }), -/* 1 */ -/***/ (function(module, exports) { - -class AbstractHandler { - constructor(packetManager) { - this.packetManager = packetManager; - } - - handle(packet) { - return packet; - } -} - -module.exports = AbstractHandler; - - -/***/ }), -/* 2 */ -/***/ (function(module, exports) { - -/* - -ABOUT ACTIONS - -Actions are similar to WebSocket Packet Handlers, but since introducing -the REST API methods, in order to prevent rewriting code to handle data, -"actions" have been introduced. They're basically what Packet Handlers -used to be but they're strictly for manipulating data and making sure -that WebSocket events don't clash with REST methods. - -*/ - -class GenericAction { - constructor(client) { - this.client = client; - } - - handle(data) { - return data; - } -} - -module.exports = GenericAction; - - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - -/** - * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has - * an ID, for significantly improved performance and ease-of-use. - * @extends {Map} - */ -class Collection extends Map { - constructor(iterable) { - super(iterable); - - /** - * Cached array for the `array()` method - will be reset to `null` whenever `set()` or `delete()` are called - * @name Collection#_array - * @type {?Array} - * @private - */ - Object.defineProperty(this, '_array', { value: null, writable: true, configurable: true }); - - /** - * Cached array for the `keyArray()` method - will be reset to `null` whenever `set()` or `delete()` are called - * @name Collection#_keyArray - * @type {?Array} - * @private - */ - Object.defineProperty(this, '_keyArray', { value: null, writable: true, configurable: true }); - } - - set(key, val) { - this._array = null; - this._keyArray = null; - return super.set(key, val); - } - - delete(key) { - this._array = null; - this._keyArray = null; - return super.delete(key); - } - - /** - * Creates an ordered array of the values of this collection, and caches it internally. The array will only be - * reconstructed if an item is added to or removed from the collection, or if you change the length of the array - * itself. If you don't want this caching behaviour, use `Array.from(collection.values())` instead. - * @returns {Array} - */ - array() { - if (!this._array || this._array.length !== this.size) this._array = Array.from(this.values()); - return this._array; - } - - /** - * Creates an ordered array of the keys of this collection, and caches it internally. The array will only be - * reconstructed if an item is added to or removed from the collection, or if you change the length of the array - * itself. If you don't want this caching behaviour, use `Array.from(collection.keys())` instead. - * @returns {Array} - */ - keyArray() { - if (!this._keyArray || this._keyArray.length !== this.size) this._keyArray = Array.from(this.keys()); - return this._keyArray; - } - - /** - * Obtains the first value(s) in this collection. - * @param {number} [count] Number of values to obtain from the beginning - * @returns {*|Array<*>} The single value if `count` is undefined, or an array of values of `count` length - */ - first(count) { - if (count === undefined) return this.values().next().value; - if (typeof count !== 'number') throw new TypeError('The count must be a number.'); - if (!Number.isInteger(count) || count < 1) throw new RangeError('The count must be an integer greater than 0.'); - count = Math.min(this.size, count); - const arr = new Array(count); - const iter = this.values(); - for (let i = 0; i < count; i++) arr[i] = iter.next().value; - return arr; - } - - /** - * Obtains the first key(s) in this collection. - * @param {number} [count] Number of keys to obtain from the beginning - * @returns {*|Array<*>} The single key if `count` is undefined, or an array of keys of `count` length - */ - firstKey(count) { - if (count === undefined) return this.keys().next().value; - if (typeof count !== 'number') throw new TypeError('The count must be a number.'); - if (!Number.isInteger(count) || count < 1) throw new RangeError('The count must be an integer greater than 0.'); - count = Math.min(this.size, count); - const arr = new Array(count); - const iter = this.iter(); - for (let i = 0; i < count; i++) arr[i] = iter.next().value; - return arr; - } - - /** - * Obtains the last value(s) in this collection. This relies on {@link Collection#array}, and thus the caching - * mechanism applies here as well. - * @param {number} [count] Number of values to obtain from the end - * @returns {*|Array<*>} The single value if `count` is undefined, or an array of values of `count` length - */ - last(count) { - const arr = this.array(); - if (count === undefined) return arr[arr.length - 1]; - if (typeof count !== 'number') throw new TypeError('The count must be a number.'); - if (!Number.isInteger(count) || count < 1) throw new RangeError('The count must be an integer greater than 0.'); - return arr.slice(-count); - } - - /** - * Obtains the last key(s) in this collection. This relies on {@link Collection#keyArray}, and thus the caching - * mechanism applies here as well. - * @param {number} [count] Number of keys to obtain from the end - * @returns {*|Array<*>} The single key if `count` is undefined, or an array of keys of `count` length - */ - lastKey(count) { - const arr = this.keyArray(); - if (count === undefined) return arr[arr.length - 1]; - if (typeof count !== 'number') throw new TypeError('The count must be a number.'); - if (!Number.isInteger(count) || count < 1) throw new RangeError('The count must be an integer greater than 0.'); - return arr.slice(-count); - } - - /** - * Obtains random value(s) from this collection. This relies on {@link Collection#array}, and thus the caching - * mechanism applies here as well. - * @param {number} [count] Number of values to obtain randomly - * @returns {*|Array<*>} The single value if `count` is undefined, or an array of values of `count` length - */ - random(count) { - let arr = this.array(); - if (count === undefined) return arr[Math.floor(Math.random() * arr.length)]; - if (typeof count !== 'number') throw new TypeError('The count must be a number.'); - if (!Number.isInteger(count) || count < 1) throw new RangeError('The count must be an integer greater than 0.'); - if (arr.length === 0) return []; - const rand = new Array(count); - arr = arr.slice(); - for (let i = 0; i < count; i++) rand[i] = arr.splice(Math.floor(Math.random() * arr.length), 1)[0]; - return rand; - } - - /** - * Obtains random key(s) from this collection. This relies on {@link Collection#keyArray}, and thus the caching - * mechanism applies here as well. - * @param {number} [count] Number of keys to obtain randomly - * @returns {*|Array<*>} The single key if `count` is undefined, or an array of keys of `count` length - */ - randomKey(count) { - let arr = this.keyArray(); - if (count === undefined) return arr[Math.floor(Math.random() * arr.length)]; - if (typeof count !== 'number') throw new TypeError('The count must be a number.'); - if (!Number.isInteger(count) || count < 1) throw new RangeError('The count must be an integer greater than 0.'); - if (arr.length === 0) return []; - const rand = new Array(count); - arr = arr.slice(); - for (let i = 0; i < count; i++) rand[i] = arr.splice(Math.floor(Math.random() * arr.length), 1)[0]; - return rand; - } - - /** - * Searches for all items where their specified property's value is identical to the given value - * (`item[prop] === value`). - * @param {string} prop The property to test against - * @param {*} value The expected value - * @returns {Array} - * @example - * collection.findAll('username', 'Bob'); - */ - findAll(prop, value) { - if (typeof prop !== 'string') throw new TypeError('Key must be a string.'); - if (typeof value === 'undefined') throw new Error('Value must be specified.'); - const results = []; - for (const item of this.values()) { - if (item[prop] === value) results.push(item); - } - return results; - } - - /** - * Searches for a single item where its specified property's value is identical to the given value - * (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is identical to - * [Array.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find). - * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you - * should use the `get` method. See - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get) for details. - * @param {string|Function} propOrFn The property to test against, or the function to test with - * @param {*} [value] The expected value - only applicable and required if using a property for the first argument - * @returns {*} - * @example - * collection.find('username', 'Bob'); - * @example - * collection.find(val => val.username === 'Bob'); - */ - find(propOrFn, value) { - if (typeof propOrFn === 'string') { - if (typeof value === 'undefined') throw new Error('Value must be specified.'); - for (const item of this.values()) { - if (item[propOrFn] === value) return item; - } - return null; - } else if (typeof propOrFn === 'function') { - for (const [key, val] of this) { - if (propOrFn(val, key, this)) return val; - } - return null; - } else { - throw new Error('First argument must be a property string or a function.'); - } - } - - /* eslint-disable max-len */ - /** - * Searches for the key of a single item where its specified property's value is identical to the given value - * (`item[prop] === value`), or the given function returns a truthy value. In the latter case, this is identical to - * [Array.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex). - * @param {string|Function} propOrFn The property to test against, or the function to test with - * @param {*} [value] The expected value - only applicable and required if using a property for the first argument - * @returns {*} - * @example - * collection.findKey('username', 'Bob'); - * @example - * collection.findKey(val => val.username === 'Bob'); - */ - /* eslint-enable max-len */ - findKey(propOrFn, value) { - if (typeof propOrFn === 'string') { - if (typeof value === 'undefined') throw new Error('Value must be specified.'); - for (const [key, val] of this) { - if (val[propOrFn] === value) return key; - } - return null; - } else if (typeof propOrFn === 'function') { - for (const [key, val] of this) { - if (propOrFn(val, key, this)) return key; - } - return null; - } else { - throw new Error('First argument must be a property string or a function.'); - } - } - - /** - * Searches for the existence of a single item where its specified property's value is identical to the given value - * (`item[prop] === value`). - * Do not use this to check for an item by its ID. Instead, use `collection.has(id)`. See - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has) for details. - * @param {string} prop The property to test against - * @param {*} value The expected value - * @returns {boolean} - * @example - * if (collection.exists('username', 'Bob')) { - * console.log('user here!'); - * } - */ - exists(prop, value) { - return Boolean(this.find(prop, value)); - } - - /** - * Identical to - * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), - * but returns a Collection instead of an Array. - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {Collection} - */ - filter(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - const results = new Collection(); - for (const [key, val] of this) { - if (fn(val, key, this)) results.set(key, val); - } - return results; - } - - /** - * Identical to - * [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {Array} - */ - filterArray(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - const results = []; - for (const [key, val] of this) { - if (fn(val, key, this)) results.push(val); - } - return results; - } - - /** - * Identical to - * [Array.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). - * @param {Function} fn Function that produces an element of the new array, taking three arguments - * @param {*} [thisArg] Value to use as `this` when executing function - * @returns {Array} - */ - map(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - const arr = new Array(this.size); - let i = 0; - for (const [key, val] of this) arr[i++] = fn(val, key, this); - return arr; - } - - /** - * Identical to - * [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some). - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {boolean} - */ - some(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - for (const [key, val] of this) { - if (fn(val, key, this)) return true; - } - return false; - } - - /** - * Identical to - * [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). - * @param {Function} fn Function used to test (should return a boolean) - * @param {Object} [thisArg] Value to use as `this` when executing function - * @returns {boolean} - */ - every(fn, thisArg) { - if (thisArg) fn = fn.bind(thisArg); - for (const [key, val] of this) { - if (!fn(val, key, this)) return false; - } - return true; - } - - /** - * Identical to - * [Array.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). - * @param {Function} fn Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, - * and `collection` - * @param {*} [initialValue] Starting value for the accumulator - * @returns {*} - */ - reduce(fn, initialValue) { - let accumulator; - if (typeof initialValue !== 'undefined') { - accumulator = initialValue; - for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); - } else { - let first = true; - for (const [key, val] of this) { - if (first) { - accumulator = val; - first = false; - continue; - } - accumulator = fn(accumulator, val, key, this); - } - } - return accumulator; - } - - /** - * Creates an identical shallow copy of this collection. - * @returns {Collection} - * @example const newColl = someColl.clone(); - */ - clone() { - return new this.constructor(this); - } - - /** - * Combines this collection with others into a new collection. None of the source collections are modified. - * @param {...Collection} collections Collections to merge - * @returns {Collection} - * @example const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); - */ - concat(...collections) { - const newColl = this.clone(); - for (const coll of collections) { - for (const [key, val] of coll) newColl.set(key, val); - } - return newColl; - } - - /** - * Calls the `delete()` method on all items that have it. - * @returns {Promise[]} - */ - deleteAll() { - const returns = []; - for (const item of this.values()) { - if (item.delete) returns.push(item.delete()); - } - return returns; - } - - /** - * Checks if this collection shares identical key-value pairings with another. - * This is different to checking for equality using equal-signs, because - * the collections may be different objects, but contain the same data. - * @param {Collection} collection Collection to compare with - * @returns {boolean} Whether the collections have identical contents - */ - equals(collection) { - if (!collection) return false; - if (this === collection) return true; - if (this.size !== collection.size) return false; - return !this.find((value, key) => { - const testVal = collection.get(key); - return testVal !== value || (testVal === undefined && !collection.has(key)); - }); - } - - /** - * The sort() method sorts the elements of a collection in place and returns the collection. - * The sort is not necessarily stable. The default sort order is according to string Unicode code points. - * @param {Function} [compareFunction] Specifies a function that defines the sort order. - * if omitted, the collection is sorted according to each character's Unicode code point value, - * according to the string conversion of each element. - * @returns {Collection} - */ - sort(compareFunction = (x, y) => +(x > y) || +(x === y) - 1) { - return new Collection(Array.from(this.entries()).sort((a, b) => compareFunction(a[1], b[1], a[0], b[0]))); - } -} - -module.exports = Collection; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const snekfetch = __webpack_require__(31); -const Constants = __webpack_require__(0); -const ConstantsHttp = Constants.DefaultOptions.http; - -/** - * Contains various general-purpose utility methods. These functions are also available on the base `Discord` object. - */ -class Util { - constructor() { - throw new Error(`The ${this.constructor.name} class may not be instantiated.`); - } - - /** - * Splits a string into multiple chunks at a designated character that do not exceed a specific length. - * @param {string} text Content to split - * @param {SplitOptions} [options] Options controlling the behaviour of the split - * @returns {string|string[]} - */ - static splitMessage(text, { maxLength = 1950, char = '\n', prepend = '', append = '' } = {}) { - if (text.length <= maxLength) return text; - const splitText = text.split(char); - if (splitText.length === 1) throw new Error('Message exceeds the max length and contains no split characters.'); - const messages = ['']; - let msg = 0; - for (let i = 0; i < splitText.length; i++) { - if (messages[msg].length + splitText[i].length + 1 > maxLength) { - messages[msg] += append; - messages.push(prepend); - msg++; - } - messages[msg] += (messages[msg].length > 0 && messages[msg] !== prepend ? char : '') + splitText[i]; - } - return messages; - } - - /** - * Escapes any Discord-flavour markdown in a string. - * @param {string} text Content to escape - * @param {boolean} [onlyCodeBlock=false] Whether to only escape codeblocks (takes priority) - * @param {boolean} [onlyInlineCode=false] Whether to only escape inline code - * @returns {string} - */ - static escapeMarkdown(text, onlyCodeBlock = false, onlyInlineCode = false) { - if (onlyCodeBlock) return text.replace(/```/g, '`\u200b``'); - if (onlyInlineCode) return text.replace(/\\(`|\\)/g, '$1').replace(/(`|\\)/g, '\\$1'); - return text.replace(/\\(\*|_|`|~|\\)/g, '$1').replace(/(\*|_|`|~|\\)/g, '\\$1'); - } - - /** - * Gets the recommended shard count from Discord. - * @param {string} token Discord auth token - * @param {number} [guildsPerShard=1000] Number of guilds per shard - * @returns {Promise} The recommended number of shards - */ - static fetchRecommendedShards(token, guildsPerShard = 1000) { - return new Promise((resolve, reject) => { - if (!token) throw new Error('A token must be provided.'); - snekfetch.get(`${ConstantsHttp.host}/api/v${ConstantsHttp.version}${Constants.Endpoints.gateway.bot}`) - .set('Authorization', `Bot ${token.replace(/^Bot\s*/i, '')}`) - .end((err, res) => { - if (err) reject(err); - resolve(res.body.shards * (1000 / guildsPerShard)); - }); - }); - } - - /** - * Parses emoji info out of a string. The string must be one of: - * * A UTF-8 emoji (no ID) - * * A URL-encoded UTF-8 emoji (no ID) - * * A Discord custom emoji (`<:name:id>`) - * @param {string} text Emoji string to parse - * @returns {Object} Object with `name` and `id` properties - * @private - */ - static parseEmoji(text) { - if (text.includes('%')) text = decodeURIComponent(text); - if (text.includes(':')) { - const [name, id] = text.split(':'); - return { name, id }; - } else { - return { - name: text, - id: null, - }; - } - } - - /** - * Checks whether the arrays are equal, also removes duplicated entries from b. - * @param {Array<*>} a Array which will not be modified. - * @param {Array<*>} b Array to remove duplicated entries from. - * @returns {boolean} Whether the arrays are equal. - * @private - */ - static arraysEqual(a, b) { - if (a === b) return true; - if (a.length !== b.length) return false; - - for (const item of a) { - const ind = b.indexOf(item); - if (ind !== -1) b.splice(ind, 1); - } - - return b.length === 0; - } - - /** - * Shallow-copies an object with its class/prototype intact. - * @param {Object} obj Object to clone - * @returns {Object} - * @private - */ - static cloneObject(obj) { - return Object.assign(Object.create(obj), obj); - } - - /** - * Sets default properties on an object that aren't already specified. - * @param {Object} def Default properties - * @param {Object} given Object to assign defaults to - * @returns {Object} - * @private - */ - static mergeDefault(def, given) { - if (!given) return def; - for (const key in def) { - if (!{}.hasOwnProperty.call(given, key)) { - given[key] = def[key]; - } else if (given[key] === Object(given[key])) { - given[key] = this.mergeDefault(def[key], given[key]); - } - } - - return given; - } - - /** - * Converts an ArrayBuffer or string to a Buffer. - * @param {ArrayBuffer|string} ab ArrayBuffer to convert - * @returns {Buffer} - * @private - */ - static convertToBuffer(ab) { - if (typeof ab === 'string') ab = this.str2ab(ab); - return Buffer.from(ab); - } - - /** - * Converts a string to an ArrayBuffer. - * @param {string} str String to convert - * @returns {ArrayBuffer} - * @private - */ - static str2ab(str) { - const buffer = new ArrayBuffer(str.length * 2); - const view = new Uint16Array(buffer); - for (var i = 0, strLen = str.length; i < strLen; i++) view[i] = str.charCodeAt(i); - return buffer; - } - - /** - * Makes an Error from a plain info object. - * @param {Object} obj Error info - * @param {string} obj.name Error type - * @param {string} obj.message Message for the error - * @param {string} obj.stack Stack for the error - * @returns {Error} - * @private - */ - static makeError(obj) { - const err = new Error(obj.message); - err.name = obj.name; - err.stack = obj.stack; - return err; - } - - /** - * Makes a plain error info object from an Error. - * @param {Error} err Error to get info from - * @returns {Object} - * @private - */ - static makePlainError(err) { - const obj = {}; - obj.name = err.name; - obj.message = err.message; - obj.stack = err.stack; - return obj; - } - - /** - * Moves an element in an array *in place*. - * @param {Array<*>} array Array to modify - * @param {*} element Element to move - * @param {number} newIndex Index or offset to move the element to - * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index - * @returns {number} - * @private - */ - static moveElementInArray(array, element, newIndex, offset = false) { - const index = array.indexOf(element); - newIndex = (offset ? index : 0) + newIndex; - if (newIndex > -1 && newIndex < array.length) { - const removedElement = array.splice(index, 1)[0]; - array.splice(newIndex, 0, removedElement); - } - return array.indexOf(element); - } -} - -module.exports = Util; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - - - -var base64 = __webpack_require__(76) -var ieee754 = __webpack_require__(77) -var isArray = __webpack_require__(44) - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - -function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -} - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr -} - -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} - -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -} - -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -} - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that -} - -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} - -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 -} - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6))) - -/***/ }), -/* 6 */ -/***/ (function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); -} catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - -const Long = __webpack_require__(36); - -// Discord epoch (2015-01-01T00:00:00.000Z) -const EPOCH = 1420070400000; -let INCREMENT = 0; - -/** - * A container for useful snowflake-related methods. - */ -class SnowflakeUtil { - constructor() { - throw new Error(`The ${this.constructor.name} class may not be instantiated.`); - } - - /** - * A Twitter snowflake, except the epoch is 2015-01-01T00:00:00.000Z - * ``` - * If we have a snowflake '266241948824764416' we can represent it as binary: - * - * 64 22 17 12 0 - * 000000111011000111100001101001000101000000 00001 00000 000000000000 - * number of ms since Discord epoch worker pid increment - * ``` - * @typedef {string} Snowflake - */ - - /** - * Generates a Discord snowflake. - * This hardcodes the worker ID as 1 and the process ID as 0. - * @returns {Snowflake} The generated snowflake - */ - static generate() { - if (INCREMENT >= 4095) INCREMENT = 0; - const BINARY = `${pad((Date.now() - EPOCH).toString(2), 42)}0000100000${pad((INCREMENT++).toString(2), 12)}`; - return Long.fromString(BINARY, 2).toString(); - } - - /** - * A deconstructed snowflake. - * @typedef {Object} DeconstructedSnowflake - * @property {number} timestamp Timestamp the snowflake was created - * @property {Date} date Date the snowflake was created - * @property {number} workerID Worker ID in the snowflake - * @property {number} processID Process ID in the snowflake - * @property {number} increment Increment in the snowflake - * @property {string} binary Binary representation of the snowflake - */ - - /** - * Deconstructs a Discord snowflake. - * @param {Snowflake} snowflake Snowflake to deconstruct - * @returns {DeconstructedSnowflake} Deconstructed snowflake - */ - static deconstruct(snowflake) { - const BINARY = pad(Long.fromString(snowflake).toString(2), 64); - const res = { - timestamp: parseInt(BINARY.substring(0, 42), 2) + EPOCH, - workerID: parseInt(BINARY.substring(42, 47), 2), - processID: parseInt(BINARY.substring(47, 52), 2), - increment: parseInt(BINARY.substring(52, 64), 2), - binary: BINARY, - }; - Object.defineProperty(res, 'date', { - get: function get() { return new Date(this.timestamp); }, - enumerable: true, - }); - return res; - } -} - -function pad(v, n, c = '0') { - return String(v).length >= n ? String(v) : (String(c).repeat(n) + v).slice(-n); -} - -module.exports = SnowflakeUtil; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - - -/***/ }), -/* 10 */ -/***/ (function(module, exports) { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); -const util = __webpack_require__(13); - -/** - * Data structure that makes it easy to interact with a permission bitfield. All {@link GuildMember}s have a set of - * permissions in their guild, and each channel in the guild may also have {@link PermissionOverwrites} for the member - * that override their default permissions. - */ -class Permissions { - /** - * @param {GuildMember} [member] Member the permissions are for **(deprecated)** - * @param {number|PermissionResolvable[]} permissions Permissions or bitfield to read from - */ - constructor(member, permissions) { - permissions = typeof member === 'object' && !(member instanceof Array) ? permissions : member; - - /** - * Member the permissions are for - * @type {GuildMember} - * @deprecated - */ - this._member = typeof member === 'object' ? member : null; - - /** - * Bitfield of the packed permissions - * @type {number} - */ - this.bitfield = typeof permissions === 'number' ? permissions : this.constructor.resolve(permissions); - } - - get member() { - return this._member; - } - - set member(value) { - this._member = value; - } - - /** - * Bitfield of the packed permissions - * @type {number} - * @see {@link Permissions#bitfield} - * @deprecated - * @readonly - */ - get raw() { - return this.bitfield; - } - - set raw(raw) { - this.bitfield = raw; - } - - /** - * Checks whether the bitfield has a permission, or multiple permissions. - * @param {PermissionResolvable|PermissionResolvable[]} permission Permission(s) to check for - * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override - * @returns {boolean} - */ - has(permission, checkAdmin = true) { - if (permission instanceof Array) return permission.every(p => this.has(p, checkAdmin)); - permission = this.constructor.resolve(permission); - if (checkAdmin && (this.bitfield & this.constructor.FLAGS.ADMINISTRATOR) > 0) return true; - return (this.bitfield & permission) === permission; - } - - /** - * Gets all given permissions that are missing from the bitfield. - * @param {PermissionResolvable[]} permissions Permissions to check for - * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override - * @returns {PermissionResolvable[]} - */ - missing(permissions, checkAdmin = true) { - return permissions.filter(p => !this.has(p, checkAdmin)); - } - - /** - * Adds permissions to this one, creating a new instance to represent the new bitfield. - * @param {...PermissionResolvable} permissions Permissions to add - * @returns {Permissions} - */ - add(...permissions) { - let total = 0; - for (let p = 0; p < permissions.length; p++) { - const perm = this.constructor.resolve(permissions[p]); - if ((this.bitfield & perm) !== perm) total |= perm; - } - return new this.constructor(this.member, this.bitfield | total); - } - - /** - * Removes permissions to this one, creating a new instance to represent the new bitfield. - * @param {...PermissionResolvable} permissions Permissions to remove - * @returns {Permissions} - */ - remove(...permissions) { - let total = 0; - for (let p = 0; p < permissions.length; p++) { - const perm = this.constructor.resolve(permissions[p]); - if ((this.bitfield & perm) === perm) total |= perm; - } - return new this.constructor(this.member, this.bitfield & ~total); - } - - /** - * Gets an object mapping permission name (like `VIEW_CHANNEL`) to a {@link boolean} indicating whether the - * permission is available. - * @param {boolean} [checkAdmin=true] Whether to allow the administrator permission to override - * @returns {Object} - */ - serialize(checkAdmin = true) { - const serialized = {}; - for (const perm in this.constructor.FLAGS) serialized[perm] = this.has(perm, checkAdmin); - return serialized; - } - - /** - * Checks whether the user has a certain permission, e.g. `READ_MESSAGES`. - * @param {PermissionResolvable} permission The permission to check for - * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permission - * @returns {boolean} - * @see {@link Permissions#has} - * @deprecated - */ - hasPermission(permission, explicit = false) { - return this.has(permission, !explicit); - } - - /** - * Checks whether the user has all specified permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions - * @returns {boolean} - * @see {@link Permissions#has} - * @deprecated - */ - hasPermissions(permissions, explicit = false) { - return this.has(permissions, !explicit); - } - - /** - * Checks whether the user has all specified permissions, and lists any missing permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the user to explicitly have the exact permissions - * @returns {PermissionResolvable[]} - * @see {@link Permissions#missing} - * @deprecated - */ - missingPermissions(permissions, explicit = false) { - return this.missing(permissions, !explicit); - } - - /** - * Data that can be resolved to give a permission number. This can be: - * * A string (see {@link Permissions.FLAGS}) - * * A permission number - * @typedef {string|number} PermissionResolvable - */ - - /** - * Resolves permissions to their numeric form. - * @param {PermissionResolvable|PermissionResolvable[]} permission - Permission(s) to resolve - * @returns {number} - */ - static resolve(permission) { - if (permission instanceof Array) return permission.map(p => this.resolve(p)).reduce((prev, p) => prev | p, 0); - if (typeof permission === 'string') permission = this.FLAGS[permission]; - if (typeof permission !== 'number' || permission < 1) throw new RangeError(Constants.Errors.NOT_A_PERMISSION); - return permission; - } -} - -/** - * Numeric permission flags. All available properties: - * - `ADMINISTRATOR` (implicitly has *all* permissions, and bypasses all channel overwrites) - * - `CREATE_INSTANT_INVITE` (create invitations to the guild) - * - `KICK_MEMBERS` - * - `BAN_MEMBERS` - * - `MANAGE_CHANNELS` (edit and reorder channels) - * - `MANAGE_GUILD` (edit the guild information, region, etc.) - * - `ADD_REACTIONS` (add new reactions to messages) - * - `VIEW_AUDIT_LOG` - * - `VIEW_CHANNEL` - * - `READ_MESSAGES` **(deprecated)** - * - `SEND_MESSAGES` - * - `SEND_TTS_MESSAGES` - * - `MANAGE_MESSAGES` (delete messages and reactions) - * - `EMBED_LINKS` (links posted will have a preview embedded) - * - `ATTACH_FILES` - * - `READ_MESSAGE_HISTORY` (view messages that were posted prior to opening Discord) - * - `MENTION_EVERYONE` - * - `USE_EXTERNAL_EMOJIS` (use emojis from different guilds) - * - `EXTERNAL_EMOJIS` **(deprecated)** - * - `CONNECT` (connect to a voice channel) - * - `SPEAK` (speak in a voice channel) - * - `MUTE_MEMBERS` (mute members across all voice channels) - * - `DEAFEN_MEMBERS` (deafen members across all voice channels) - * - `MOVE_MEMBERS` (move members between voice channels) - * - `USE_VAD` (use voice activity detection) - * - `CHANGE_NICKNAME` - * - `MANAGE_NICKNAMES` (change other members' nicknames) - * - `MANAGE_ROLES` - * - `MANAGE_ROLES_OR_PERMISSIONS` **(deprecated)** - * - `MANAGE_WEBHOOKS` - * - `MANAGE_EMOJIS` - * @type {Object} - * @see {@link https://discordapp.com/developers/docs/topics/permissions} - */ -Permissions.FLAGS = { - CREATE_INSTANT_INVITE: 1 << 0, - KICK_MEMBERS: 1 << 1, - BAN_MEMBERS: 1 << 2, - ADMINISTRATOR: 1 << 3, - MANAGE_CHANNELS: 1 << 4, - MANAGE_GUILD: 1 << 5, - ADD_REACTIONS: 1 << 6, - VIEW_AUDIT_LOG: 1 << 7, - - VIEW_CHANNEL: 1 << 10, - READ_MESSAGES: 1 << 10, - SEND_MESSAGES: 1 << 11, - SEND_TTS_MESSAGES: 1 << 12, - MANAGE_MESSAGES: 1 << 13, - EMBED_LINKS: 1 << 14, - ATTACH_FILES: 1 << 15, - READ_MESSAGE_HISTORY: 1 << 16, - MENTION_EVERYONE: 1 << 17, - EXTERNAL_EMOJIS: 1 << 18, - USE_EXTERNAL_EMOJIS: 1 << 18, - - CONNECT: 1 << 20, - SPEAK: 1 << 21, - MUTE_MEMBERS: 1 << 22, - DEAFEN_MEMBERS: 1 << 23, - MOVE_MEMBERS: 1 << 24, - USE_VAD: 1 << 25, - - CHANGE_NICKNAME: 1 << 26, - MANAGE_NICKNAMES: 1 << 27, - MANAGE_ROLES: 1 << 28, - MANAGE_ROLES_OR_PERMISSIONS: 1 << 28, - MANAGE_WEBHOOKS: 1 << 29, - MANAGE_EMOJIS: 1 << 30, -}; - -/** - * Bitfield representing every permission combined - * @type {number} - */ -Permissions.ALL = Object.keys(Permissions.FLAGS).reduce((all, p) => all | Permissions.FLAGS[p], 0); - -/** - * Bitfield representing the default permissions for users - * @type {number} - */ -Permissions.DEFAULT = 104324097; - -/** - * @class EvaluatedPermissions - * @classdesc The final evaluated permissions for a member in a channel - * @see {@link Permissions} - * @deprecated - */ - -Permissions.prototype.hasPermission = util.deprecate(Permissions.prototype.hasPermission, - 'EvaluatedPermissions#hasPermission is deprecated, use Permissions#has instead'); -Permissions.prototype.hasPermissions = util.deprecate(Permissions.prototype.hasPermissions, - 'EvaluatedPermissions#hasPermissions is deprecated, use Permissions#has instead'); -Permissions.prototype.missingPermissions = util.deprecate(Permissions.prototype.missingPermissions, - 'EvaluatedPermissions#missingPermissions is deprecated, use Permissions#missing instead'); -Object.defineProperty(Permissions.prototype, 'member', { - get: util - .deprecate(Object.getOwnPropertyDescriptor(Permissions.prototype, 'member').get, - 'EvaluatedPermissions#member is deprecated'), -}); - -module.exports = Permissions; - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - - - -/**/ - -var processNextTick = __webpack_require__(25); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var util = __webpack_require__(19); -util.inherits = __webpack_require__(10); -/**/ - -var Readable = __webpack_require__(45); -var Writable = __webpack_require__(34); - -util.inherits(Duplex, Readable); - -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - - processNextTick(cb, err); -}; - -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = Object({"__DISCORD_WEBPACK__":"true"}).NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = __webpack_require__(107); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = __webpack_require__(108); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6), __webpack_require__(7))) - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -const TextBasedChannel = __webpack_require__(21); -const Constants = __webpack_require__(0); -const Presence = __webpack_require__(16).Presence; -const Snowflake = __webpack_require__(8); - -/** - * Represents a user on Discord. - * @implements {TextBasedChannel} - */ -class User { - constructor(client, data) { - /** - * The client that created the instance of the user - * @name User#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - if (data) this.setup(data); - } - - setup(data) { - /** - * The ID of the user - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The username of the user - * @type {string} - */ - this.username = data.username; - - /** - * A discriminator based on username for the user - * @type {string} - */ - this.discriminator = data.discriminator; - - /** - * The ID of the user's avatar - * @type {string} - */ - this.avatar = data.avatar; - - /** - * Whether or not the user is a bot - * @type {boolean} - */ - this.bot = Boolean(data.bot); - - /** - * The ID of the last message sent by the user, if one was sent - * @type {?Snowflake} - */ - this.lastMessageID = null; - - /** - * The Message object of the last message sent by the user, if one was sent - * @type {?Message} - */ - this.lastMessage = null; - } - - patch(data) { - for (const prop of ['id', 'username', 'discriminator', 'avatar', 'bot']) { - if (typeof data[prop] !== 'undefined') this[prop] = data[prop]; - } - if (data.token) this.client.token = data.token; - } - - /** - * The timestamp the user was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time the user was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The presence of this user - * @type {Presence} - * @readonly - */ - get presence() { - if (this.client.presences.has(this.id)) return this.client.presences.get(this.id); - for (const guild of this.client.guilds.values()) { - if (guild.presences.has(this.id)) return guild.presences.get(this.id); - } - return new Presence(); - } - - /** - * A link to the user's avatar - * @type {?string} - * @readonly - */ - get avatarURL() { - if (!this.avatar) return null; - return Constants.Endpoints.User(this).Avatar(this.client.options.http.cdn, this.avatar); - } - - /** - * A link to the user's default avatar - * @type {string} - * @readonly - */ - get defaultAvatarURL() { - const avatars = Object.keys(Constants.DefaultAvatars); - const avatar = avatars[this.discriminator % avatars.length]; - return Constants.Endpoints.CDN(this.client.options.http.host).Asset(`${Constants.DefaultAvatars[avatar]}.png`); - } - - /** - * A link to the user's avatar if they have one. Otherwise a link to their default avatar will be returned - * @type {string} - * @readonly - */ - get displayAvatarURL() { - return this.avatarURL || this.defaultAvatarURL; - } - - /** - * The Discord "tag" for this user - * @type {string} - * @readonly - */ - get tag() { - return `${this.username}#${this.discriminator}`; - } - - /** - * The note that is set for the user - * This is only available when using a user account. - * @type {?string} - * @readonly - */ - get note() { - return this.client.user.notes.get(this.id) || null; - } - - /** - * Check whether the user is typing in a channel. - * @param {ChannelResolvable} channel The channel to check in - * @returns {boolean} - */ - typingIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - return channel._typing.has(this.id); - } - - /** - * Get the time that the user started typing. - * @param {ChannelResolvable} channel The channel to get the time in - * @returns {?Date} - */ - typingSinceIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - return channel._typing.has(this.id) ? new Date(channel._typing.get(this.id).since) : null; - } - - /** - * Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing. - * @param {ChannelResolvable} channel The channel to get the time in - * @returns {number} - */ - typingDurationIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - return channel._typing.has(this.id) ? channel._typing.get(this.id).elapsedTime : -1; - } - - /** - * The DM between the client's user and this user - * @type {?DMChannel} - * @readonly - */ - get dmChannel() { - return this.client.channels.filter(c => c.type === 'dm').find(c => c.recipient.id === this.id); - } - - /** - * Creates a DM channel between the client and the user. - * @returns {Promise} - */ - createDM() { - return this.client.rest.methods.createDM(this); - } - - /** - * Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful. - * @returns {Promise} - */ - deleteDM() { - return this.client.rest.methods.deleteChannel(this); - } - - /** - * Sends a friend request to the user. - * This is only available when using a user account. - * @returns {Promise} - */ - addFriend() { - return this.client.rest.methods.addFriend(this); - } - - /** - * Removes the user from your friends. - * This is only available when using a user account. - * @returns {Promise} - */ - removeFriend() { - return this.client.rest.methods.removeFriend(this); - } - - /** - * Blocks the user. - * This is only available when using a user account. - * @returns {Promise} - */ - block() { - return this.client.rest.methods.blockUser(this); - } - - /** - * Unblocks the user. - * This is only available when using a user account. - * @returns {Promise} - */ - unblock() { - return this.client.rest.methods.unblockUser(this); - } - - /** - * Get the profile of the user. - * This is only available when using a user account. - * @returns {Promise} - */ - fetchProfile() { - return this.client.rest.methods.fetchUserProfile(this); - } - - /** - * Sets a note for the user. - * This is only available when using a user account. - * @param {string} note The note to set for the user - * @returns {Promise} - */ - setNote(note) { - return this.client.rest.methods.setNote(this, note); - } - - /** - * Checks if the user is equal to another. It compares ID, username, discriminator, avatar, and bot flags. - * It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties. - * @param {User} user User to compare with - * @returns {boolean} - */ - equals(user) { - let equal = user && - this.id === user.id && - this.username === user.username && - this.discriminator === user.discriminator && - this.avatar === user.avatar && - this.bot === Boolean(user.bot); - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the user's mention instead of the User object. - * @returns {string} - * @example - * // logs: Hello from <@123456789>! - * console.log(`Hello from ${user}!`); - */ - toString() { - return `<@${this.id}>`; - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ - send() {} - sendMessage() {} - sendEmbed() {} - sendFile() {} - sendCode() {} -} - -TextBasedChannel.applyToClass(User); - -module.exports = User; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -const Snowflake = __webpack_require__(8); -const Permissions = __webpack_require__(11); -const util = __webpack_require__(13); - -/** - * Represents a role on Discord. - */ -class Role { - constructor(guild, data) { - /** - * The client that instantiated the role - * @name Role#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: guild.client }); - - /** - * The guild that the role belongs to - * @type {Guild} - */ - this.guild = guild; - - if (data) this.setup(data); - } - - setup(data) { - /** - * The ID of the role (unique to the guild it is part of) - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The name of the role - * @type {string} - */ - this.name = data.name; - - /** - * The base 10 color of the role - * @type {number} - */ - this.color = data.color; - - /** - * If true, users that are part of this role will appear in a separate category in the users list - * @type {boolean} - */ - this.hoist = data.hoist; - - /** - * The position of the role from the API - * @type {number} - */ - this.position = data.position; - - /** - * The permissions bitfield of the role - * @type {number} - */ - this.permissions = data.permissions; - - /** - * Whether or not the role is managed by an external service - * @type {boolean} - */ - this.managed = data.managed; - - /** - * Whether or not the role can be mentioned by anyone - * @type {boolean} - */ - this.mentionable = data.mentionable; - } - - /** - * The timestamp the role was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time the role was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The hexadecimal version of the role color, with a leading hashtag - * @type {string} - * @readonly - */ - get hexColor() { - let col = this.color.toString(16); - while (col.length < 6) col = `0${col}`; - return `#${col}`; - } - - /** - * The cached guild members that have this role - * @type {Collection} - * @readonly - */ - get members() { - return this.guild.members.filter(m => m.roles.has(this.id)); - } - - /** - * Whether the role is editable by the client user - * @type {boolean} - * @readonly - */ - get editable() { - if (this.managed) return false; - const clientMember = this.guild.member(this.client.user); - if (!clientMember.permissions.has(Permissions.FLAGS.MANAGE_ROLES_OR_PERMISSIONS)) return false; - return clientMember.highestRole.comparePositionTo(this) > 0; - } - - /** - * The position of the role in the role manager - * @type {number} - * @readonly - */ - get calculatedPosition() { - const sorted = this.guild._sortedRoles; - return sorted.array().indexOf(sorted.get(this.id)); - } - - /** - * Get an object mapping permission names to whether or not the role enables that permission. - * @returns {Object} - * @example - * // Print the serialized role permissions - * console.log(role.serialize()); - */ - serialize() { - return new Permissions(this.permissions).serialize(); - } - - /** - * Checks if the role has a permission. - * @param {PermissionResolvable|PermissionResolvable[]} permission Permission(s) to check for - * @param {boolean} [explicit=false] Whether to require the role to explicitly have the exact permission - * **(deprecated)** - * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override - * (takes priority over `explicit`) - * @returns {boolean} - * @example - * // See if a role can ban a member - * if (role.hasPermission('BAN_MEMBERS')) { - * console.log('This role can ban members'); - * } else { - * console.log('This role can\'t ban members'); - * } - */ - hasPermission(permission, explicit = false, checkAdmin) { - return new Permissions(this.permissions).has( - permission, typeof checkAdmin !== 'undefined' ? checkAdmin : !explicit - ); - } - - /** - * Checks if the role has all specified permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the role to explicitly have the exact permissions - * @returns {boolean} - * @deprecated - */ - hasPermissions(permissions, explicit = false) { - return new Permissions(this.permissions).has(permissions, !explicit); - } - - /** - * Compares this role's position to another role's. - * @param {Role} role Role to compare to this one - * @returns {number} Negative number if the this role's position is lower (other role's is higher), - * positive number if the this one is higher (other's is lower), 0 if equal - */ - comparePositionTo(role) { - return this.constructor.comparePositions(this, role); - } - - /** - * The data for a role. - * @typedef {Object} RoleData - * @property {string} [name] The name of the role - * @property {ColorResolvable} [color] The color of the role, either a hex string or a base 10 number - * @property {boolean} [hoist] Whether or not the role should be hoisted - * @property {number} [position] The position of the role - * @property {PermissionResolvable[]|number} [permissions] The permissions of the role - * @property {boolean} [mentionable] Whether or not the role should be mentionable - */ - - /** - * Edits the role. - * @param {RoleData} data The new data for the role - * @param {string} [reason] The reason for editing this role - * @returns {Promise} - * @example - * // Edit a role - * role.edit({name: 'new role'}) - * .then(r => console.log(`Edited role ${r}`)) - * .catch(console.error); - */ - edit(data, reason) { - return this.client.rest.methods.updateGuildRole(this, data, reason); - } - - /** - * Set a new name for the role. - * @param {string} name The new name of the role - * @param {string} [reason] Reason for changing the role's name - * @returns {Promise} - * @example - * // Set the name of the role - * role.setName('new role') - * .then(r => console.log(`Edited name of role ${r}`)) - * .catch(console.error); - */ - setName(name, reason) { - return this.edit({ name }, reason); - } - - /** - * Set a new color for the role. - * @param {ColorResolvable} color The color of the role - * @param {string} [reason] Reason for changing the role's color - * @returns {Promise} - * @example - * // Set the color of a role - * role.setColor('#FF0000') - * .then(r => console.log(`Set color of role ${r}`)) - * .catch(console.error); - */ - setColor(color, reason) { - return this.edit({ color }, reason); - } - - /** - * Set whether or not the role should be hoisted. - * @param {boolean} hoist Whether or not to hoist the role - * @param {string} [reason] Reason for setting whether or not the role should be hoisted - * @returns {Promise} - * @example - * // Set the hoist of the role - * role.setHoist(true) - * .then(r => console.log(`Role hoisted: ${r.hoist}`)) - * .catch(console.error); - */ - setHoist(hoist, reason) { - return this.edit({ hoist }, reason); - } - - /** - * Set the position of the role. - * @param {number} position The position of the role - * @param {boolean} [relative=false] Move the position relative to its current value - * @returns {Promise} - * @example - * // Set the position of the role - * role.setPosition(1) - * .then(r => console.log(`Role position: ${r.position}`)) - * .catch(console.error); - */ - setPosition(position, relative) { - return this.guild.setRolePosition(this, position, relative).then(() => this); - } - - /** - * Set the permissions of the role. - * @param {string[]} permissions The permissions of the role - * @param {string} [reason] Reason for changing the role's permissions - * @returns {Promise} - * @example - * // Set the permissions of the role - * role.setPermissions(['KICK_MEMBERS', 'BAN_MEMBERS']) - * .then(r => console.log(`Role updated ${r}`)) - * .catch(console.error); - */ - setPermissions(permissions, reason) { - return this.edit({ permissions }, reason); - } - - /** - * Set whether this role is mentionable. - * @param {boolean} mentionable Whether this role should be mentionable - * @param {string} [reason] Reason for setting whether or not this role should be mentionable - * @returns {Promise} - * @example - * // Make the role mentionable - * role.setMentionable(true) - * .then(r => console.log(`Role updated ${r}`)) - * .catch(console.error); - */ - setMentionable(mentionable, reason) { - return this.edit({ mentionable }, reason); - } - - /** - * Deletes the role. - * @param {string} [reason] Reason for deleting the role - * @returns {Promise} - * @example - * // Delete a role - * role.delete() - * .then(r => console.log(`Deleted role ${r}`)) - * .catch(console.error); - */ - delete(reason) { - return this.client.rest.methods.deleteGuildRole(this, reason); - } - - /** - * Whether this role equals another role. It compares all properties, so for most operations - * it is advisable to just compare `role.id === role2.id` as it is much faster and is often - * what most users need. - * @param {Role} role Role to compare with - * @returns {boolean} - */ - equals(role) { - return role && - this.id === role.id && - this.name === role.name && - this.color === role.color && - this.hoist === role.hoist && - this.position === role.position && - this.permissions === role.permissions && - this.managed === role.managed; - } - - /** - * When concatenated with a string, this automatically concatenates the role mention rather than the Role object. - * @returns {string} - */ - toString() { - if (this.id === this.guild.id) return '@everyone'; - return `<@&${this.id}>`; - } - - /** - * Compares the positions of two roles. - * @param {Role} role1 First role to compare - * @param {Role} role2 Second role to compare - * @returns {number} Negative number if the first role's position is lower (second role's is higher), - * positive number if the first's is higher (second's is lower), 0 if equal - */ - static comparePositions(role1, role2) { - if (role1.position === role2.position) return role2.id - role1.id; - return role1.position - role2.position; - } -} - -Role.prototype.hasPermissions = util - .deprecate(Role.prototype.hasPermissions, - 'Role#hasPermissions is deprecated - use Role#hasPermission instead, it now takes an array'); - -module.exports = Role; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports) { - -/** - * Represents a user's presence. - */ -class Presence { - constructor(data = {}) { - /** - * The status of the presence: - * - * * **`online`** - user is online - * * **`offline`** - user is offline or invisible - * * **`idle`** - user is AFK - * * **`dnd`** - user is in Do not Disturb - * @type {string} - */ - this.status = data.status || 'offline'; - - /** - * The game that the user is playing - * @type {?Game} - */ - this.game = data.game ? new Game(data.game) : null; - } - - update(data) { - this.status = data.status || this.status; - this.game = data.game ? new Game(data.game) : null; - } - - /** - * Whether this presence is equal to another - * @param {Presence} presence The presence to compare with - * @returns {boolean} - */ - equals(presence) { - return this === presence || ( - presence && - this.status === presence.status && - this.game ? this.game.equals(presence.game) : !presence.game - ); - } -} - -/** - * Represents a game that is part of a user's presence. - */ -class Game { - constructor(data) { - /** - * The name of the game being played - * @type {string} - */ - this.name = data.name; - - /** - * The type of the game status - * @type {number} - */ - this.type = data.type; - - /** - * If the game is being streamed, a link to the stream - * @type {?string} - */ - this.url = data.url || null; - } - - /** - * Whether or not the game is being streamed - * @type {boolean} - * @readonly - */ - get streaming() { - return this.type === 1; - } - - /** - * Whether this game is equal to another game - * @param {Game} game The game to compare with - * @returns {boolean} - */ - equals(game) { - return this === game || ( - game && - this.name === game.name && - this.type === game.type && - this.url === game.url - ); - } -} - -exports.Presence = Presence; -exports.Game = Game; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -const Snowflake = __webpack_require__(8); - -/** - * Represents any channel on Discord. - */ -class Channel { - constructor(client, data) { - /** - * The client that instantiated the Channel - * @name Channel#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * The type of the channel, either: - * * `dm` - a DM channel - * * `group` - a Group DM channel - * * `text` - a guild text channel - * * `voice` - a guild voice channel - * @type {string} - */ - this.type = null; - - if (data) this.setup(data); - } - - setup(data) { - /** - * The unique ID of the channel - * @type {Snowflake} - */ - this.id = data.id; - } - - /** - * The timestamp the channel was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time the channel was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * Deletes the channel. - * @returns {Promise} - * @example - * // Delete the channel - * channel.delete() - * .then() // Success - * .catch(console.error); // Log error - */ - delete() { - return this.client.rest.methods.deleteChannel(this); - } -} - -module.exports = Channel; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -exports = module.exports = __webpack_require__(45); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = __webpack_require__(34); -exports.Duplex = __webpack_require__(12); -exports.Transform = __webpack_require__(49); -exports.PassThrough = __webpack_require__(84); - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; - - -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; - -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const path = __webpack_require__(20); -const Message = __webpack_require__(22); -const MessageCollector = __webpack_require__(61); -const Collection = __webpack_require__(3); -const Attachment = __webpack_require__(28); -const RichEmbed = __webpack_require__(27); -const util = __webpack_require__(13); - -/** - * Interface for classes that have text-channel-like features. - * @interface - */ -class TextBasedChannel { - constructor() { - /** - * A collection containing the messages sent to this channel - * @type {Collection} - */ - this.messages = new Collection(); - - /** - * The ID of the last message in the channel, if one was sent - * @type {?Snowflake} - */ - this.lastMessageID = null; - - /** - * The Message object of the last message in the channel, if one was sent - * @type {?Message} - */ - this.lastMessage = null; - } - - /** - * Options provided when sending or editing a message. - * @typedef {Object} MessageOptions - * @property {boolean} [tts=false] Whether or not the message should be spoken aloud - * @property {string} [nonce=''] The nonce for the message - * @property {RichEmbed|Object} [embed] An embed for the message - * (see [here](https://discordapp.com/developers/docs/resources/channel#embed-object) for more details) - * @property {boolean} [disableEveryone=this.client.options.disableEveryone] Whether or not @everyone and @here - * should be replaced with plain-text - * @property {FileOptions|BufferResolvable|Attachment} [file] A file to send with the message **(deprecated)** - * @property {FileOptions[]|BufferResolvable[]|Attachment[]} [files] Files to send with the message - * @property {string|boolean} [code] Language for optional codeblock formatting to apply - * @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if - * it exceeds the character limit. If an object is provided, these are the options for splitting the message - * @property {UserResolvable} [reply] User to reply to (prefixes the message with a mention, except in DMs) - */ - - /** - * @typedef {Object} FileOptions - * @property {BufferResolvable} attachment File to attach - * @property {string} [name='file.jpg'] Filename of the attachment - */ - - /** - * Options for splitting a message. - * @typedef {Object} SplitOptions - * @property {number} [maxLength=1950] Maximum character length per message piece - * @property {string} [char='\n'] Character to split the message with - * @property {string} [prepend=''] Text to prepend to every piece except the first - * @property {string} [append=''] Text to append to every piece except the last - */ - - /** - * Send a message to this channel. - * @param {StringResolvable} [content] Text for the message - * @param {MessageOptions|Attachment|RichEmbed} [options] Options for the message, - * can also be just a RichEmbed or Attachment - * @returns {Promise} - * @example - * // Send a message - * channel.send('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - send(content, options) { - if (!options && typeof content === 'object' && !(content instanceof Array)) { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - - if (options instanceof Attachment) options = { files: [options.file] }; - if (options instanceof RichEmbed) options = { embed: options }; - - if (options.embed && options.embed.file) { - if (options.files) options.files.push(options.embed.file); - else options.files = [options.embed.file]; - } - - if (options.file) { - if (options.files) options.files.push(options.file); - else options.files = [options.file]; - } - - if (options.files) { - for (let i = 0; i < options.files.length; i++) { - let file = options.files[i]; - if (typeof file === 'string' || Buffer.isBuffer(file)) file = { attachment: file }; - if (!file.name) { - if (typeof file.attachment === 'string') { - file.name = path.basename(file.attachment); - } else if (file.attachment && file.attachment.path) { - file.name = path.basename(file.attachment.path); - } else if (file instanceof Attachment) { - file = { attachment: file.file, name: path.basename(file.file) || 'file.jpg' }; - } else { - file.name = 'file.jpg'; - } - } else if (file instanceof Attachment) { - file = file.file; - } - options.files[i] = file; - } - - return Promise.all(options.files.map(file => - this.client.resolver.resolveFile(file.attachment).then(resource => { - file.file = resource; - return file; - }) - )).then(files => this.client.rest.methods.sendMessage(this, content, options, files)); - } - - return this.client.rest.methods.sendMessage(this, content, options); - } - - /** - * Gets a single message from this channel, regardless of it being cached or not. Since the single message fetching - * endpoint is reserved for bot accounts, this abstracts the `fetchMessages` method to obtain the single message when - * using a user account. - * @param {Snowflake} messageID ID of the message to get - * @returns {Promise} - * @example - * // Get message - * channel.fetchMessage('99539446449315840') - * .then(message => console.log(message.content)) - * .catch(console.error); - */ - fetchMessage(messageID) { - if (!this.client.user.bot) { - return this.fetchMessages({ limit: 1, around: messageID }).then(messages => { - const msg = messages.get(messageID); - if (!msg) throw new Error('Message not found.'); - return msg; - }); - } - return this.client.rest.methods.getChannelMessage(this, messageID).then(data => { - const msg = data instanceof Message ? data : new Message(this, data, this.client); - this._cacheMessage(msg); - return msg; - }); - } - - /** - * The parameters to pass in when requesting previous messages from a channel. `around`, `before` and - * `after` are mutually exclusive. All the parameters are optional. - * @typedef {Object} ChannelLogsQueryOptions - * @property {number} [limit=50] Number of messages to acquire - * @property {Snowflake} [before] ID of a message to get the messages that were posted before it - * @property {Snowflake} [after] ID of a message to get the messages that were posted after it - * @property {Snowflake} [around] ID of a message to get the messages that were posted around it - */ - - /** - * Gets the past messages sent in this channel. Resolves with a collection mapping message ID's to Message objects. - * @param {ChannelLogsQueryOptions} [options={}] Query parameters to pass in - * @returns {Promise>} - * @example - * // Get messages - * channel.fetchMessages({limit: 10}) - * .then(messages => console.log(`Received ${messages.size} messages`)) - * .catch(console.error); - */ - fetchMessages(options = {}) { - return this.client.rest.methods.getChannelMessages(this, options).then(data => { - const messages = new Collection(); - for (const message of data) { - const msg = new Message(this, message, this.client); - messages.set(message.id, msg); - this._cacheMessage(msg); - } - return messages; - }); - } - - /** - * Fetches the pinned messages of this channel and returns a collection of them. - * @returns {Promise>} - */ - fetchPinnedMessages() { - return this.client.rest.methods.getChannelPinnedMessages(this).then(data => { - const messages = new Collection(); - for (const message of data) { - const msg = new Message(this, message, this.client); - messages.set(message.id, msg); - this._cacheMessage(msg); - } - return messages; - }); - } - - /** - * @typedef {Object} MessageSearchOptions - * @property {string} [content] Message content - * @property {Snowflake} [maxID] Maximum ID for the filter - * @property {Snowflake} [minID] Minimum ID for the filter - * @property {string} [has] One of `link`, `embed`, `file`, `video`, `image`, or `sound`, - * or add `-` to negate (e.g. `-file`) - * @property {ChannelResolvable} [channel] Channel to limit search to (only for guild search endpoint) - * @property {UserResolvable} [author] Author to limit search - * @property {string} [authorType] One of `user`, `bot`, `webhook`, or add `-` to negate (e.g. `-webhook`) - * @property {string} [sortBy='recent'] `recent` or `relevant` - * @property {string} [sortOrder='desc'] `asc` or `desc` - * @property {number} [contextSize=2] How many messages to get around the matched message (0 to 2) - * @property {number} [limit=25] Maximum number of results to get (1 to 25) - * @property {number} [offset=0] Offset the "pages" of results (since you can only see 25 at a time) - * @property {UserResolvable} [mentions] Mentioned user filter - * @property {boolean} [mentionsEveryone] If everyone is mentioned - * @property {string} [linkHostname] Filter links by hostname - * @property {string} [embedProvider] The name of an embed provider - * @property {string} [embedType] one of `image`, `video`, `url`, `rich` - * @property {string} [attachmentFilename] The name of an attachment - * @property {string} [attachmentExtension] The extension of an attachment - * @property {Date} [before] Date to find messages before - * @property {Date} [after] Date to find messages before - * @property {Date} [during] Date to find messages during (range of date to date + 24 hours) - * @property {boolean} [nsfw=false] Include results from NSFW channels - */ - - /** - * @typedef {Object} MessageSearchResult - * @property {number} totalResults Total result count - * @property {Message[][]} messages Array of message results - * The message which has triggered the result will have the `hit` property set to `true` - */ - - /** - * Performs a search within the channel. - * This is only available when using a user account. - * @param {MessageSearchOptions} [options={}] Options to pass to the search - * @returns {Promise} - * @example - * channel.search({ - * content: 'discord.js', - * before: '2016-11-17' - * }).then(res => { - * const hit = res.messages[0].find(m => m.hit).content; - * console.log(`I found: **${hit}**, total results: ${res.totalResults}`); - * }).catch(console.error); - */ - search(options = {}) { - return this.client.rest.methods.search(this, options); - } - - /** - * Starts a typing indicator in the channel. - * @param {number} [count] The number of times startTyping should be considered to have been called - * @example - * // Start typing in a channel - * channel.startTyping(); - */ - startTyping(count) { - if (typeof count !== 'undefined' && count < 1) throw new RangeError('Count must be at least 1.'); - if (!this.client.user._typing.has(this.id)) { - this.client.user._typing.set(this.id, { - count: count || 1, - interval: this.client.setInterval(() => { - this.client.rest.methods.sendTyping(this.id); - }, 9000), - }); - this.client.rest.methods.sendTyping(this.id); - } else { - const entry = this.client.user._typing.get(this.id); - entry.count = count || entry.count + 1; - } - } - - /** - * Stops the typing indicator in the channel. - * The indicator will only stop if this is called as many times as startTyping(). - * It can take a few seconds for the client user to stop typing. - * @param {boolean} [force=false] Whether or not to reset the call count and force the indicator to stop - * @example - * // Stop typing in a channel - * channel.stopTyping(); - * @example - * // Force typing to fully stop in a channel - * channel.stopTyping(true); - */ - stopTyping(force = false) { - if (this.client.user._typing.has(this.id)) { - const entry = this.client.user._typing.get(this.id); - entry.count--; - if (entry.count <= 0 || force) { - this.client.clearInterval(entry.interval); - this.client.user._typing.delete(this.id); - } - } - } - - /** - * Whether or not the typing indicator is being shown in the channel - * @type {boolean} - * @readonly - */ - get typing() { - return this.client.user._typing.has(this.id); - } - - /** - * Number of times `startTyping` has been called - * @type {number} - * @readonly - */ - get typingCount() { - if (this.client.user._typing.has(this.id)) return this.client.user._typing.get(this.id).count; - return 0; - } - - /** - * Creates a Message Collector - * @param {CollectorFilter} filter The filter to create the collector with - * @param {MessageCollectorOptions} [options={}] The options to pass to the collector - * @returns {MessageCollector} - * @deprecated - */ - createCollector(filter, options) { - return this.createMessageCollector(filter, options); - } - - /** - * Creates a Message Collector. - * @param {CollectorFilter} filter The filter to create the collector with - * @param {MessageCollectorOptions} [options={}] The options to pass to the collector - * @returns {MessageCollector} - * @example - * // Create a message collector - * const collector = channel.createMessageCollector( - * m => m.content.includes('discord'), - * { time: 15000 } - * ); - * collector.on('collect', m => console.log(`Collected ${m.content}`)); - * collector.on('end', collected => console.log(`Collected ${collected.size} items`)); - */ - createMessageCollector(filter, options = {}) { - return new MessageCollector(this, filter, options); - } - - /** - * An object containing the same properties as CollectorOptions, but a few more: - * @typedef {MessageCollectorOptions} AwaitMessagesOptions - * @property {string[]} [errors] Stop/end reasons that cause the promise to reject - */ - - /** - * Similar to createCollector but in promise form. Resolves with a collection of messages that pass the specified - * filter. - * @param {CollectorFilter} filter The filter function to use - * @param {AwaitMessagesOptions} [options={}] Optional options to pass to the internal collector - * @returns {Promise>} - * @example - * // Await !vote messages - * const filter = m => m.content.startsWith('!vote'); - * // Errors: ['time'] treats ending because of the time limit as an error - * channel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] }) - * .then(collected => console.log(collected.size)) - * .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`)); - */ - awaitMessages(filter, options = {}) { - return new Promise((resolve, reject) => { - const collector = this.createCollector(filter, options); - collector.once('end', (collection, reason) => { - if (options.errors && options.errors.includes(reason)) { - reject(collection); - } else { - resolve(collection); - } - }); - }); - } - - /** - * Bulk delete given messages that are newer than two weeks. - * This is only available when using a bot account. - * @param {Collection|Message[]|number} messages Messages or number of messages to delete - * @param {boolean} [filterOld=false] Filter messages to remove those which are older than two weeks automatically - * @returns {Promise>} Deleted messages - */ - bulkDelete(messages, filterOld = false) { - if (!isNaN(messages)) return this.fetchMessages({ limit: messages }).then(msgs => this.bulkDelete(msgs, filterOld)); - if (messages instanceof Array || messages instanceof Collection) { - const messageIDs = messages instanceof Collection ? messages.keyArray() : messages.map(m => m.id); - return this.client.rest.methods.bulkDeleteMessages(this, messageIDs, filterOld); - } - throw new TypeError('The messages must be an Array, Collection, or number.'); - } - - /** - * Marks all messages in this channel as read. - * This is only available when using a user account. - * @returns {Promise} - */ - acknowledge() { - if (!this.lastMessageID) return Promise.resolve(this); - return this.client.rest.methods.ackTextChannel(this); - } - - _cacheMessage(message) { - const maxSize = this.client.options.messageCacheMaxSize; - if (maxSize === 0) return null; - if (this.messages.size >= maxSize && maxSize > 0) this.messages.delete(this.messages.firstKey()); - this.messages.set(message.id, message); - return message; - } -} - -/** @lends TextBasedChannel.prototype */ -const Deprecated = { - /** - * Send a message to this channel. - * @param {StringResolvable} [content] Text for the message - * @param {MessageOptions} [options={}] Options for the message - * @returns {Promise} - * @deprecated - * @example - * // Send a message - * channel.sendMessage('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - sendMessage(content, options) { - return this.send(content, options); - }, - - /** - * Send an embed to this channel. - * @param {RichEmbed|Object} embed Embed for the message - * @param {string} [content] Text for the message - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - * @deprecated - */ - sendEmbed(embed, content, options) { - if (!options && typeof content === 'object' && !(content instanceof Array)) { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - return this.send(content, Object.assign(options, { embed })); - }, - - /** - * Send files to this channel. - * @param {FileOptions[]|string[]} files Files to send with the message - * @param {StringResolvable} [content] Text for the message - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - * @deprecated - */ - sendFiles(files, content, options = {}) { - return this.send(content, Object.assign(options, { files })); - }, - - /** - * Send a file to this channel. - * @param {BufferResolvable} attachment File to send - * @param {string} [name='file.jpg'] Name and extension of the file - * @param {StringResolvable} [content] Text for the message - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - * @deprecated - */ - sendFile(attachment, name, content, options = {}) { - return this.send({ files: [{ attachment, name }], content, options }); - }, - - /** - * Send a code block to this channel. - * @param {string} lang Language for the code block - * @param {StringResolvable} content Content of the code block - * @param {MessageOptions} [options] Options for the message - * @returns {Promise} - * @deprecated - */ - sendCode(lang, content, options = {}) { - return this.send(content, Object.assign(options, { code: lang })); - }, -}; - -for (const key of Object.keys(Deprecated)) { - TextBasedChannel.prototype[key] = util.deprecate(Deprecated[key], `TextChannel#${key}: use TextChannel#send instead`); -} - -exports.applyToClass = (structure, full = false, ignore = []) => { - const props = ['send', 'sendMessage', 'sendEmbed', 'sendFile', 'sendFiles', 'sendCode']; - if (full) { - props.push( - '_cacheMessage', - 'acknowledge', - 'fetchMessages', - 'fetchMessage', - 'search', - 'bulkDelete', - 'startTyping', - 'stopTyping', - 'typing', - 'typingCount', - 'fetchPinnedMessages', - 'createCollector', - 'createMessageCollector', - 'awaitMessages' - ); - } - for (const prop of props) { - if (ignore.includes(prop)) continue; - Object.defineProperty(structure.prototype, prop, Object.getOwnPropertyDescriptor(TextBasedChannel.prototype, prop)); - } -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - -const Mentions = __webpack_require__(56); -const Attachment = __webpack_require__(57); -const Embed = __webpack_require__(58); -const RichEmbed = __webpack_require__(27); -const MessageReaction = __webpack_require__(59); -const ReactionCollector = __webpack_require__(60); -const Util = __webpack_require__(4); -const Collection = __webpack_require__(3); -const Constants = __webpack_require__(0); -const Permissions = __webpack_require__(11); -let GuildMember; - -/** - * Represents a message on Discord. - */ -class Message { - constructor(channel, data, client) { - /** - * The client that instantiated the Message - * @name Message#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * The channel that the message was sent in - * @type {TextChannel|DMChannel|GroupDMChannel} - */ - this.channel = channel; - - if (data) this.setup(data); - } - - setup(data) { // eslint-disable-line complexity - /** - * The ID of the message - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The type of the message - * @type {string} - */ - this.type = Constants.MessageTypes[data.type]; - - /** - * The content of the message - * @type {string} - */ - this.content = data.content; - - /** - * The author of the message - * @type {User} - */ - this.author = this.client.dataManager.newUser(data.author); - - /** - * Represents the author of the message as a guild member - * Only available if the message comes from a guild where the author is still a member - * @type {?GuildMember} - */ - this.member = this.guild ? this.guild.member(this.author) || null : null; - - /** - * Whether or not this message is pinned - * @type {boolean} - */ - this.pinned = data.pinned; - - /** - * Whether or not the message was Text-To-Speech - * @type {boolean} - */ - this.tts = data.tts; - - /** - * A random number or string used for checking message delivery - * @type {string} - */ - this.nonce = data.nonce; - - /** - * Whether or not this message was sent by Discord, not actually a user (e.g. pin notifications) - * @type {boolean} - */ - this.system = data.type === 6; - - /** - * A list of embeds in the message - e.g. YouTube Player - * @type {MessageEmbed[]} - */ - this.embeds = data.embeds.map(e => new Embed(this, e)); - - /** - * A collection of attachments in the message - e.g. Pictures - mapped by their ID - * @type {Collection} - */ - this.attachments = new Collection(); - for (const attachment of data.attachments) this.attachments.set(attachment.id, new Attachment(this, attachment)); - - /** - * The timestamp the message was sent at - * @type {number} - */ - this.createdTimestamp = new Date(data.timestamp).getTime(); - - /** - * The timestamp the message was last edited at (if applicable) - * @type {?number} - */ - this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null; - - /** - * A collection of reactions to this message, mapped by the reaction ID - * @type {Collection} - */ - this.reactions = new Collection(); - if (data.reactions && data.reactions.length > 0) { - for (const reaction of data.reactions) { - const id = reaction.emoji.id ? `${reaction.emoji.name}:${reaction.emoji.id}` : reaction.emoji.name; - this.reactions.set(id, new MessageReaction(this, reaction.emoji, reaction.count, reaction.me)); - } - } - - /** - * All valid mentions that the message contains - * @type {MessageMentions} - */ - this.mentions = new Mentions(this, data.mentions, data.mention_roles, data.mention_everyone); - - /** - * ID of the webhook that sent the message, if applicable - * @type {?Snowflake} - */ - this.webhookID = data.webhook_id || null; - - /** - * Whether this message is a hit in a search - * @type {?boolean} - */ - this.hit = typeof data.hit === 'boolean' ? data.hit : null; - - /** - * The previous versions of the message, sorted with the most recent first - * @type {Message[]} - * @private - */ - this._edits = []; - } - - /** - * Updates the message. - * @param {Object} data Raw Discord message update data - * @private - */ - patch(data) { - const clone = Util.cloneObject(this); - this._edits.unshift(clone); - - this.editedTimestamp = new Date(data.edited_timestamp).getTime(); - if ('content' in data) this.content = data.content; - if ('pinned' in data) this.pinned = data.pinned; - if ('tts' in data) this.tts = data.tts; - if ('embeds' in data) this.embeds = data.embeds.map(e => new Embed(this, e)); - else this.embeds = this.embeds.slice(); - - if ('attachments' in data) { - this.attachments = new Collection(); - for (const attachment of data.attachments) this.attachments.set(attachment.id, new Attachment(this, attachment)); - } else { - this.attachments = new Collection(this.attachments); - } - - this.mentions = new Mentions( - this, - 'mentions' in data ? data.mentions : this.mentions.users, - 'mentions_roles' in data ? data.mentions_roles : this.mentions.roles, - 'mention_everyone' in data ? data.mention_everyone : this.mentions.everyone - ); - } - - /** - * The time the message was sent - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The time the message was last edited at (if applicable) - * @type {?Date} - * @readonly - */ - get editedAt() { - return this.editedTimestamp ? new Date(this.editedTimestamp) : null; - } - - /** - * The guild the message was sent in (if in a guild channel) - * @type {?Guild} - * @readonly - */ - get guild() { - return this.channel.guild || null; - } - - /** - * The message contents with all mentions replaced by the equivalent text. - * If mentions cannot be resolved to a name, the relevant mention in the message content will not be converted. - * @type {string} - * @readonly - */ - get cleanContent() { - return this.content - .replace(/@(everyone|here)/g, '@\u200b$1') - .replace(/<@!?[0-9]+>/g, input => { - const id = input.replace(/<|!|>|@/g, ''); - if (this.channel.type === 'dm' || this.channel.type === 'group') { - return this.client.users.has(id) ? `@${this.client.users.get(id).username}` : input; - } - - const member = this.channel.guild.members.get(id); - if (member) { - if (member.nickname) return `@${member.nickname}`; - return `@${member.user.username}`; - } else { - const user = this.client.users.get(id); - if (user) return `@${user.username}`; - return input; - } - }) - .replace(/<#[0-9]+>/g, input => { - const channel = this.client.channels.get(input.replace(/<|#|>/g, '')); - if (channel) return `#${channel.name}`; - return input; - }) - .replace(/<@&[0-9]+>/g, input => { - if (this.channel.type === 'dm' || this.channel.type === 'group') return input; - const role = this.guild.roles.get(input.replace(/<|@|>|&/g, '')); - if (role) return `@${role.name}`; - return input; - }); - } - - /** - * Creates a reaction collector. - * @param {CollectorFilter} filter The filter to apply - * @param {ReactionCollectorOptions} [options={}] Options to send to the collector - * @returns {ReactionCollector} - * @example - * // Create a reaction collector - * const collector = message.createReactionCollector( - * (reaction, user) => reaction.emoji.name === '👌' && user.id === 'someID', - * { time: 15000 } - * ); - * collector.on('collect', r => console.log(`Collected ${r.emoji.name}`)); - * collector.on('end', collected => console.log(`Collected ${collected.size} items`)); - */ - createReactionCollector(filter, options = {}) { - return new ReactionCollector(this, filter, options); - } - - /** - * An object containing the same properties as CollectorOptions, but a few more: - * @typedef {ReactionCollectorOptions} AwaitReactionsOptions - * @property {string[]} [errors] Stop/end reasons that cause the promise to reject - */ - - /** - * Similar to createMessageCollector but in promise form. - * Resolves with a collection of reactions that pass the specified filter. - * @param {CollectorFilter} filter The filter function to use - * @param {AwaitReactionsOptions} [options={}] Optional options to pass to the internal collector - * @returns {Promise>} - */ - awaitReactions(filter, options = {}) { - return new Promise((resolve, reject) => { - const collector = this.createReactionCollector(filter, options); - collector.once('end', (reactions, reason) => { - if (options.errors && options.errors.includes(reason)) reject(reactions); - else resolve(reactions); - }); - }); - } - - /** - * An array of cached versions of the message, including the current version - * Sorted from latest (first) to oldest (last) - * @type {Message[]} - * @readonly - */ - get edits() { - const copy = this._edits.slice(); - copy.unshift(this); - return copy; - } - - /** - * Whether the message is editable by the client user - * @type {boolean} - * @readonly - */ - get editable() { - return this.author.id === this.client.user.id; - } - - /** - * Whether the message is deletable by the client user - * @type {boolean} - * @readonly - */ - get deletable() { - return this.author.id === this.client.user.id || (this.guild && - this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES) - ); - } - - /** - * Whether the message is pinnable by the client user - * @type {boolean} - * @readonly - */ - get pinnable() { - return !this.guild || - this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES); - } - - /** - * Whether or not a user, channel or role is mentioned in this message. - * @param {GuildChannel|User|Role|string} data Either a guild channel, user or a role object, or a string representing - * the ID of any of these - * @returns {boolean} - */ - isMentioned(data) { - data = data && data.id ? data.id : data; - return this.mentions.users.has(data) || this.mentions.channels.has(data) || this.mentions.roles.has(data); - } - - /** - * Whether or not a guild member is mentioned in this message. Takes into account - * user mentions, role mentions, and @everyone/@here mentions. - * @param {GuildMember|User} member The member/user to check for a mention of - * @returns {boolean} - */ - isMemberMentioned(member) { - // Lazy-loading is used here to get around a circular dependency that breaks things - if (!GuildMember) GuildMember = __webpack_require__(24); - if (this.mentions.everyone) return true; - if (this.mentions.users.has(member.id)) return true; - if (member instanceof GuildMember && member.roles.some(r => this.mentions.roles.has(r.id))) return true; - return false; - } - - /** - * Options that can be passed into editMessage. - * @typedef {Object} MessageEditOptions - * @property {Object} [embed] An embed to be added/edited - * @property {string|boolean} [code] Language for optional codeblock formatting to apply - */ - - /** - * Edit the content of the message. - * @param {StringResolvable} [content] The new content for the message - * @param {MessageEditOptions|RichEmbed} [options] The options to provide - * @returns {Promise} - * @example - * // Update the content of a message - * message.edit('This is my new content!') - * .then(msg => console.log(`Updated the content of a message from ${msg.author}`)) - * .catch(console.error); - */ - edit(content, options) { - if (!options && typeof content === 'object' && !(content instanceof Array)) { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - if (options instanceof RichEmbed) options = { embed: options }; - return this.client.rest.methods.updateMessage(this, content, options); - } - - /** - * Edit the content of the message, with a code block. - * @param {string} lang The language for the code block - * @param {StringResolvable} content The new content for the message - * @returns {Promise} - * @deprecated - */ - editCode(lang, content) { - content = Util.escapeMarkdown(this.client.resolver.resolveString(content), true); - return this.edit(`\`\`\`${lang || ''}\n${content}\n\`\`\``); - } - - /** - * Pins this message to the channel's pinned messages. - * @returns {Promise} - */ - pin() { - return this.client.rest.methods.pinMessage(this); - } - - /** - * Unpins this message from the channel's pinned messages. - * @returns {Promise} - */ - unpin() { - return this.client.rest.methods.unpinMessage(this); - } - - /** - * Add a reaction to the message. - * @param {string|Emoji|ReactionEmoji} emoji The emoji to react with - * @returns {Promise} - */ - react(emoji) { - emoji = this.client.resolver.resolveEmojiIdentifier(emoji); - if (!emoji) throw new TypeError('Emoji must be a string or Emoji/ReactionEmoji'); - - return this.client.rest.methods.addMessageReaction(this, emoji); - } - - /** - * Remove all reactions from a message. - * @returns {Promise} - */ - clearReactions() { - return this.client.rest.methods.removeMessageReactions(this); - } - - /** - * Deletes the message. - * @param {number} [timeout=0] How long to wait to delete the message in milliseconds - * @returns {Promise} - * @example - * // Delete a message - * message.delete() - * .then(msg => console.log(`Deleted message from ${msg.author}`)) - * .catch(console.error); - */ - delete(timeout = 0) { - if (timeout <= 0) { - return this.client.rest.methods.deleteMessage(this); - } else { - return new Promise(resolve => { - this.client.setTimeout(() => { - resolve(this.delete()); - }, timeout); - }); - } - } - - /** - * Reply to the message. - * @param {StringResolvable} [content] The content for the message - * @param {MessageOptions} [options] The options to provide - * @returns {Promise} - * @example - * // Reply to a message - * message.reply('Hey, I\'m a reply!') - * .then(msg => console.log(`Sent a reply to ${msg.author}`)) - * .catch(console.error); - */ - reply(content, options) { - if (!options && typeof content === 'object' && !(content instanceof Array)) { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - return this.channel.send(content, Object.assign(options, { reply: this.member || this.author })); - } - - /** - * Marks the message as read. - * This is only available when using a user account. - * @returns {Promise} - */ - acknowledge() { - return this.client.rest.methods.ackMessage(this); - } - - /** - * Fetches the webhook used to create this message. - * @returns {Promise} - */ - fetchWebhook() { - if (!this.webhookID) return Promise.reject(new Error('The message was not sent by a webhook.')); - return this.client.fetchWebhook(this.webhookID); - } - - /** - * Used mainly internally. Whether two messages are identical in properties. If you want to compare messages - * without checking all the properties, use `message.id === message2.id`, which is much more efficient. This - * method allows you to see if there are differences in content, embeds, attachments, nonce and tts properties. - * @param {Message} message The message to compare it to - * @param {Object} rawData Raw data passed through the WebSocket about this message - * @returns {boolean} - */ - equals(message, rawData) { - if (!message) return false; - const embedUpdate = !message.author && !message.attachments; - if (embedUpdate) return this.id === message.id && this.embeds.length === message.embeds.length; - - let equal = this.id === message.id && - this.author.id === message.author.id && - this.content === message.content && - this.tts === message.tts && - this.nonce === message.nonce && - this.embeds.length === message.embeds.length && - this.attachments.length === message.attachments.length; - - if (equal && rawData) { - equal = this.mentions.everyone === message.mentions.everyone && - this.createdTimestamp === new Date(rawData.timestamp).getTime() && - this.editedTimestamp === new Date(rawData.edited_timestamp).getTime(); - } - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the message's content instead of the object. - * @returns {string} - * @example - * // Logs: Message: This is a message! - * console.log(`Message: ${message}`); - */ - toString() { - return this.content; - } - - _addReaction(emoji, user) { - const emojiID = emoji.id ? `${emoji.name}:${emoji.id}` : encodeURIComponent(emoji.name); - let reaction; - if (this.reactions.has(emojiID)) { - reaction = this.reactions.get(emojiID); - if (!reaction.me) reaction.me = user.id === this.client.user.id; - } else { - reaction = new MessageReaction(this, emoji, 0, user.id === this.client.user.id); - this.reactions.set(emojiID, reaction); - } - if (!reaction.users.has(user.id)) { - reaction.users.set(user.id, user); - reaction.count++; - } - return reaction; - } - - _removeReaction(emoji, user) { - const emojiID = emoji.id ? `${emoji.name}:${emoji.id}` : encodeURIComponent(emoji.name); - if (this.reactions.has(emojiID)) { - const reaction = this.reactions.get(emojiID); - if (reaction.users.has(user.id)) { - reaction.users.delete(user.id); - reaction.count--; - if (user.id === this.client.user.id) reaction.me = false; - if (reaction.count <= 0) this.reactions.delete(emojiID); - return reaction; - } - } - return null; - } - - _clearReactions() { - this.reactions.clear(); - } -} - -module.exports = Message; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); -const Snowflake = __webpack_require__(8); - -/** - * Represents a custom emoji. - */ -class Emoji { - constructor(guild, data) { - /** - * The client that instantiated this object - * @name Emoji#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: guild.client }); - - /** - * The guild this emoji is part of - * @type {Guild} - */ - this.guild = guild; - - this.setup(data); - } - - setup(data) { - /** - * The ID of the emoji - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The name of the emoji - * @type {string} - */ - this.name = data.name; - - /** - * Whether or not this emoji requires colons surrounding it - * @type {boolean} - */ - this.requiresColons = data.require_colons; - - /** - * Whether this emoji is managed by an external service - * @type {boolean} - */ - this.managed = data.managed; - - this._roles = data.roles; - } - - /** - * The timestamp the emoji was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time the emoji was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * A collection of roles this emoji is active for (empty if all), mapped by role ID - * @type {Collection} - * @readonly - */ - get roles() { - const roles = new Collection(); - for (const role of this._roles) { - if (this.guild.roles.has(role)) roles.set(role, this.guild.roles.get(role)); - } - return roles; - } - - /** - * The URL to the emoji file - * @type {string} - * @readonly - */ - get url() { - return Constants.Endpoints.CDN(this.client.options.http.cdn).Emoji(this.id); - } - - /** - * The identifier of this emoji, used for message reactions - * @type {string} - * @readonly - */ - get identifier() { - if (this.id) return `${this.name}:${this.id}`; - return encodeURIComponent(this.name); - } - - /** - * Data for editing an emoji. - * @typedef {Object} EmojiEditData - * @property {string} [name] The name of the emoji - * @property {Collection|Array} [roles] Roles to restrict emoji to - */ - - /** - * Edits the emoji. - * @param {EmojiEditData} data The new data for the emoji - * @param {string} [reason] Reason for editing this emoji - * @returns {Promise} - * @example - * // Edit an emoji - * emoji.edit({name: 'newemoji'}) - * .then(e => console.log(`Edited emoji ${e}`)) - * .catch(console.error); - */ - edit(data, reason) { - return this.client.rest.methods.updateEmoji(this, data, reason); - } - - /** - * Set the name of the emoji. - * @param {string} name The new name for the emoji - * @param {string} [reason] The reason for changing the emoji's name - * @returns {Promise} - */ - setName(name, reason) { - return this.edit({ name }, reason); - } - - /** - * Add a role to the list of roles that can use this emoji. - * @param {Role} role The role to add - * @returns {Promise} - */ - addRestrictedRole(role) { - return this.addRestrictedRoles([role]); - } - - /** - * Add multiple roles to the list of roles that can use this emoji. - * @param {Role[]} roles Roles to add - * @returns {Promise} - */ - addRestrictedRoles(roles) { - const newRoles = new Collection(this.roles); - for (const role of roles) { - if (this.guild.roles.has(role.id)) newRoles.set(role.id, role); - } - return this.edit({ roles: newRoles }); - } - - /** - * Remove a role from the list of roles that can use this emoji. - * @param {Role} role The role to remove - * @returns {Promise} - */ - removeRestrictedRole(role) { - return this.removeRestrictedRoles([role]); - } - - /** - * Remove multiple roles from the list of roles that can use this emoji. - * @param {Role[]} roles Roles to remove - * @returns {Promise} - */ - removeRestrictedRoles(roles) { - const newRoles = new Collection(this.roles); - for (const role of roles) { - if (newRoles.has(role.id)) newRoles.delete(role.id); - } - return this.edit({ roles: newRoles }); - } - - /** - * When concatenated with a string, this automatically returns the emoji mention rather than the object. - * @returns {string} - * @example - * // Send an emoji: - * const emoji = guild.emojis.first(); - * msg.reply(`Hello! ${emoji}`); - */ - toString() { - return this.requiresColons ? `<:${this.name}:${this.id}>` : this.name; - } - - /** - * Whether this emoji is the same as another one. - * @param {Emoji|Object} other The emoji to compare it to - * @returns {boolean} Whether the emoji is equal to the given emoji or not - */ - equals(other) { - if (other instanceof Emoji) { - return ( - other.id === this.id && - other.name === this.name && - other.managed === this.managed && - other.requiresColons === this.requiresColons - ); - } else { - return ( - other.id === this.id && - other.name === this.name - ); - } - } -} - -module.exports = Emoji; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -const TextBasedChannel = __webpack_require__(21); -const Role = __webpack_require__(15); -const Permissions = __webpack_require__(11); -const Collection = __webpack_require__(3); -const Presence = __webpack_require__(16).Presence; -const util = __webpack_require__(13); - -/** - * Represents a member of a guild on Discord. - * @implements {TextBasedChannel} - */ -class GuildMember { - constructor(guild, data) { - /** - * The client that instantiated this GuildMember - * @name GuildMember#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: guild.client }); - - /** - * The guild that this member is part of - * @type {Guild} - */ - this.guild = guild; - - /** - * The user that this guild member instance Represents - * @type {User} - */ - this.user = {}; - - this._roles = []; - if (data) this.setup(data); - - /** - * The ID of the last message sent by the member in their guild, if one was sent - * @type {?Snowflake} - */ - this.lastMessageID = null; - - /** - * The Message object of the last message sent by the member in their guild, if one was sent - * @type {?Message} - */ - this.lastMessage = null; - } - - setup(data) { - /** - * Whether this member is deafened server-wide - * @type {boolean} - */ - this.serverDeaf = data.deaf; - - /** - * Whether this member is muted server-wide - * @type {boolean} - */ - this.serverMute = data.mute; - - /** - * Whether this member is self-muted - * @type {boolean} - */ - this.selfMute = data.self_mute; - - /** - * Whether this member is self-deafened - * @type {boolean} - */ - this.selfDeaf = data.self_deaf; - - /** - * The voice session ID of this member, if any - * @type {?Snowflake} - */ - this.voiceSessionID = data.session_id; - - /** - * The voice channel ID of this member, if any - * @type {?Snowflake} - */ - this.voiceChannelID = data.channel_id; - - /** - * Whether this member is speaking - * @type {boolean} - */ - this.speaking = false; - - /** - * The nickname of this guild member, if they have one - * @type {?string} - */ - this.nickname = data.nick || null; - - /** - * The timestamp the member joined the guild at - * @type {number} - */ - this.joinedTimestamp = new Date(data.joined_at).getTime(); - - this.user = data.user; - this._roles = data.roles; - } - - /** - * The time the member joined the guild - * @type {Date} - * @readonly - */ - get joinedAt() { - return new Date(this.joinedTimestamp); - } - - /** - * The presence of this guild member - * @type {Presence} - * @readonly - */ - get presence() { - return this.frozenPresence || this.guild.presences.get(this.id) || new Presence(); - } - - /** - * A list of roles that are applied to this GuildMember, mapped by the role ID - * @type {Collection} - * @readonly - */ - get roles() { - const list = new Collection(); - const everyoneRole = this.guild.roles.get(this.guild.id); - - if (everyoneRole) list.set(everyoneRole.id, everyoneRole); - - for (const roleID of this._roles) { - const role = this.guild.roles.get(roleID); - if (role) list.set(role.id, role); - } - - return list; - } - - /** - * The role of the member with the highest position - * @type {Role} - * @readonly - */ - get highestRole() { - return this.roles.reduce((prev, role) => !prev || role.comparePositionTo(prev) > 0 ? role : prev); - } - - /** - * The role of the member used to set their color - * @type {?Role} - * @readonly - */ - get colorRole() { - const coloredRoles = this.roles.filter(role => role.color); - if (!coloredRoles.size) return null; - return coloredRoles.reduce((prev, role) => !prev || role.comparePositionTo(prev) > 0 ? role : prev); - } - - /** - * The displayed color of the member in base 10 - * @type {number} - * @readonly - */ - get displayColor() { - const role = this.colorRole; - return (role && role.color) || 0; - } - - /** - * The displayed color of the member in hexadecimal - * @type {string} - * @readonly - */ - get displayHexColor() { - const role = this.colorRole; - return (role && role.hexColor) || '#000000'; - } - - /** - * The role of the member used to hoist them in a separate category in the users list - * @type {?Role} - * @readonly - */ - get hoistRole() { - const hoistedRoles = this.roles.filter(role => role.hoist); - if (!hoistedRoles.size) return null; - return hoistedRoles.reduce((prev, role) => !prev || role.comparePositionTo(prev) > 0 ? role : prev); - } - - /** - * Whether this member is muted in any way - * @type {boolean} - * @readonly - */ - get mute() { - return this.selfMute || this.serverMute; - } - - /** - * Whether this member is deafened in any way - * @type {boolean} - * @readonly - */ - get deaf() { - return this.selfDeaf || this.serverDeaf; - } - - /** - * The voice channel this member is in, if any - * @type {?VoiceChannel} - * @readonly - */ - get voiceChannel() { - return this.guild.channels.get(this.voiceChannelID); - } - - /** - * The ID of this user - * @type {Snowflake} - * @readonly - */ - get id() { - return this.user.id; - } - - /** - * The nickname of the member, or their username if they don't have one - * @type {string} - * @readonly - */ - get displayName() { - return this.nickname || this.user.username; - } - - /** - * The overall set of permissions for the guild member, taking only roles into account - * @type {Permissions} - * @readonly - */ - get permissions() { - if (this.user.id === this.guild.ownerID) return new Permissions(this, Permissions.ALL); - - let permissions = 0; - const roles = this.roles; - for (const role of roles.values()) permissions |= role.permissions; - - return new Permissions(this, permissions); - } - - /** - * Whether the member is kickable by the client user - * @type {boolean} - * @readonly - */ - get kickable() { - if (this.user.id === this.guild.ownerID) return false; - if (this.user.id === this.client.user.id) return false; - const clientMember = this.guild.member(this.client.user); - if (!clientMember.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) return false; - return clientMember.highestRole.comparePositionTo(this.highestRole) > 0; - } - - /** - * Whether the member is bannable by the client user - * @type {boolean} - * @readonly - */ - get bannable() { - if (this.user.id === this.guild.ownerID) return false; - if (this.user.id === this.client.user.id) return false; - const clientMember = this.guild.member(this.client.user); - if (!clientMember.permissions.has(Permissions.FLAGS.BAN_MEMBERS)) return false; - return clientMember.highestRole.comparePositionTo(this.highestRole) > 0; - } - - /** - * Returns `channel.permissionsFor(guildMember)`. Returns permissions for a member in a guild channel, - * taking into account roles and permission overwrites. - * @param {ChannelResolvable} channel The guild channel to use as context - * @returns {?Permissions} - */ - permissionsIn(channel) { - channel = this.client.resolver.resolveChannel(channel); - if (!channel || !channel.guild) throw new Error('Could not resolve channel to a guild channel.'); - return channel.permissionsFor(this); - } - - /** - * Checks if any of the member's roles have a permission. - * @param {PermissionResolvable|PermissionResolvable[]} permission Permission(s) to check for - * @param {boolean} [explicit=false] Whether to require the role to explicitly have the exact permission - * **(deprecated)** - * @param {boolean} [checkAdmin] Whether to allow the administrator permission to override - * (takes priority over `explicit`) - * @param {boolean} [checkOwner] Whether to allow being the guild's owner to override - * (takes priority over `explicit`) - * @returns {boolean} - */ - hasPermission(permission, explicit = false, checkAdmin, checkOwner) { - if (typeof checkAdmin === 'undefined') checkAdmin = !explicit; - if (typeof checkOwner === 'undefined') checkOwner = !explicit; - if (checkOwner && this.user.id === this.guild.ownerID) return true; - return this.roles.some(r => r.hasPermission(permission, undefined, checkAdmin)); - } - - /** - * Checks whether the roles of the member allows them to perform specific actions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions - * @returns {boolean} - * @deprecated - */ - hasPermissions(permissions, explicit = false) { - if (!explicit && this.user.id === this.guild.ownerID) return true; - return this.hasPermission(permissions, explicit); - } - - /** - * Checks whether the roles of the member allows them to perform specific actions, and lists any missing permissions. - * @param {PermissionResolvable[]} permissions The permissions to check for - * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions - * @returns {PermissionResolvable[]} - */ - missingPermissions(permissions, explicit = false) { - return permissions.missing(permissions, explicit); - } - - /** - * The data for editing a guild member. - * @typedef {Object} GuildMemberEditData - * @property {string} [nick] The nickname to set for the member - * @property {Collection|Role[]|Snowflake[]} [roles] The roles or role IDs to apply - * @property {boolean} [mute] Whether or not the member should be muted - * @property {boolean} [deaf] Whether or not the member should be deafened - * @property {ChannelResolvable} [channel] Channel to move member to (if they are connected to voice) - */ - - /** - * Edit a guild member. - * @param {GuildMemberEditData} data The data to edit the member with - * @param {string} [reason] Reason for editing this user - * @returns {Promise} - */ - edit(data, reason) { - return this.client.rest.methods.updateGuildMember(this, data, reason); - } - - /** - * Mute/unmute a user. - * @param {boolean} mute Whether or not the member should be muted - * @param {string} [reason] Reason for muting or unmuting - * @returns {Promise} - */ - setMute(mute, reason) { - return this.edit({ mute }, reason); - } - - /** - * Deafen/undeafen a user. - * @param {boolean} deaf Whether or not the member should be deafened - * @param {string} [reason] Reason for deafening or undeafening - * @returns {Promise} - */ - setDeaf(deaf, reason) { - return this.edit({ deaf }, reason); - } - - /** - * Moves the guild member to the given channel. - * @param {ChannelResolvable} channel The channel to move the member to - * @returns {Promise} - */ - setVoiceChannel(channel) { - return this.edit({ channel }); - } - - /** - * Sets the roles applied to the member. - * @param {Collection|Role[]|Snowflake[]} roles The roles or role IDs to apply - * @param {string} [reason] Reason for applying the roles - * @returns {Promise} - */ - setRoles(roles, reason) { - return this.edit({ roles }, reason); - } - - /** - * Adds a single role to the member. - * @param {Role|Snowflake} role The role or ID of the role to add - * @param {string} [reason] Reason for adding the role - * @returns {Promise} - */ - addRole(role, reason) { - if (!(role instanceof Role)) role = this.guild.roles.get(role); - if (!role) return Promise.reject(new TypeError('Supplied parameter was neither a Role nor a Snowflake.')); - return this.client.rest.methods.addMemberRole(this, role, reason); - } - - /** - * Adds multiple roles to the member. - * @param {Collection|Role[]|Snowflake[]} roles The roles or role IDs to add - * @param {string} [reason] Reason for adding the roles - * @returns {Promise} - */ - addRoles(roles, reason) { - let allRoles; - if (roles instanceof Collection) { - allRoles = this._roles.slice(); - for (const role of roles.values()) allRoles.push(role.id); - } else { - allRoles = this._roles.concat(roles); - } - return this.edit({ roles: allRoles }, reason); - } - - /** - * Removes a single role from the member. - * @param {Role|Snowflake} role The role or ID of the role to remove - * @param {string} [reason] Reason for removing the role - * @returns {Promise} - */ - removeRole(role, reason) { - if (!(role instanceof Role)) role = this.guild.roles.get(role); - if (!role) return Promise.reject(new TypeError('Supplied parameter was neither a Role nor a Snowflake.')); - return this.client.rest.methods.removeMemberRole(this, role, reason); - } - - /** - * Removes multiple roles from the member. - * @param {Collection|Role[]|Snowflake[]} roles The roles or role IDs to remove - * @param {string} [reason] Reason for removing the roles - * @returns {Promise} - */ - removeRoles(roles, reason) { - const allRoles = this._roles.slice(); - if (roles instanceof Collection) { - for (const role of roles.values()) { - const index = allRoles.indexOf(role.id); - if (index >= 0) allRoles.splice(index, 1); - } - } else { - for (const role of roles) { - const index = allRoles.indexOf(role instanceof Role ? role.id : role); - if (index >= 0) allRoles.splice(index, 1); - } - } - return this.edit({ roles: allRoles }, reason); - } - - /** - * Set the nickname for the guild member. - * @param {string} nick The nickname for the guild member - * @param {string} [reason] Reason for setting the nickname - * @returns {Promise} - */ - setNickname(nick, reason) { - return this.edit({ nick }, reason); - } - - /** - * Creates a DM channel between the client and the member. - * @returns {Promise} - */ - createDM() { - return this.user.createDM(); - } - - /** - * Deletes any DMs with this guild member. - * @returns {Promise} - */ - deleteDM() { - return this.user.deleteDM(); - } - - /** - * Kick this member from the guild. - * @param {string} [reason] Reason for kicking user - * @returns {Promise} - */ - kick(reason) { - return this.client.rest.methods.kickGuildMember(this.guild, this, reason); - } - - /** - * Ban this guild member. - * @param {Object|number|string} [options] Ban options. If a number, the number of days to delete messages for, if a - * string, the ban reason. Supplying an object allows you to do both. - * @param {number} [options.days=0] Number of days of messages to delete - * @param {string} [options.reason] Reason for banning - * @returns {Promise} - * @example - * // ban a guild member - * guildMember.ban(7); - */ - ban(options) { - return this.guild.ban(this, options); - } - - /** - * When concatenated with a string, this automatically concatenates the user's mention instead of the Member object. - * @returns {string} - * @example - * // Logs: Hello from <@123456789>! - * console.log(`Hello from ${member}!`); - */ - toString() { - return `<@${this.nickname ? '!' : ''}${this.user.id}>`; - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ - send() {} - sendMessage() {} - sendEmbed() {} - sendFile() {} - sendCode() {} -} - -TextBasedChannel.applyToClass(GuildMember); - -GuildMember.prototype.hasPermissions = util.deprecate(GuildMember.prototype.hasPermissions, - 'GuildMember#hasPermissions is deprecated - use GuildMember#hasPermission, it now takes an array'); - -module.exports = GuildMember; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) { - -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; -} else { - module.exports = process.nextTick; -} - -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) - -/***/ }), -/* 26 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -const Attachment = __webpack_require__(28); -let ClientDataResolver; - -/** - * A rich embed to be sent with a message with a fluent interface for creation. - * @param {Object} [data] Data to set in the rich embed - */ -class RichEmbed { - constructor(data = {}) { - /** - * Title for this Embed - * @type {string} - */ - this.title = data.title; - - /** - * Description for this Embed - * @type {string} - */ - this.description = data.description; - - /** - * URL for this Embed - * @type {string} - */ - this.url = data.url; - - /** - * Color for this Embed - * @type {number} - */ - this.color = data.color; - - /** - * Author for this Embed - * @type {Object} - */ - this.author = data.author; - - /** - * Timestamp for this Embed - * @type {Date} - */ - this.timestamp = data.timestamp; - - /** - * Fields for this Embed - * @type {Object[]} - */ - this.fields = data.fields || []; - - /** - * Thumbnail for this Embed - * @type {Object} - */ - this.thumbnail = data.thumbnail; - - /** - * Image for this Embed - * @type {Object} - */ - this.image = data.image; - - /** - * Footer for this Embed - * @type {Object} - */ - this.footer = data.footer; - - /** - * File to upload alongside this Embed - * @type {FileOptions|string|Attachment} - */ - this.file = data.file; - } - - /** - * Sets the title of this embed. - * @param {StringResolvable} title The title - * @returns {RichEmbed} This embed - */ - setTitle(title) { - title = resolveString(title); - if (title.length > 256) throw new RangeError('RichEmbed titles may not exceed 256 characters.'); - this.title = title; - return this; - } - - /** - * Sets the description of this embed. - * @param {StringResolvable} description The description - * @returns {RichEmbed} This embed - */ - setDescription(description) { - description = resolveString(description); - if (description.length > 2048) throw new RangeError('RichEmbed descriptions may not exceed 2048 characters.'); - this.description = description; - return this; - } - - /** - * Sets the URL of this embed. - * @param {string} url The URL - * @returns {RichEmbed} This embed - */ - setURL(url) { - this.url = url; - return this; - } - - /** - * Sets the color of this embed. - * @param {ColorResolvable} color The color of the embed - * @returns {RichEmbed} This embed - */ - setColor(color) { - if (!ClientDataResolver) ClientDataResolver = __webpack_require__(37); - this.color = ClientDataResolver.resolveColor(color); - return this; - } - - /** - * Sets the author of this embed. - * @param {StringResolvable} name The name of the author - * @param {string} [icon] The icon URL of the author - * @param {string} [url] The URL of the author - * @returns {RichEmbed} This embed - */ - setAuthor(name, icon, url) { - this.author = { name: resolveString(name), icon_url: icon, url }; - return this; - } - - /** - * Sets the timestamp of this embed. - * @param {Date} [timestamp=current date] The timestamp - * @returns {RichEmbed} This embed - */ - setTimestamp(timestamp = new Date()) { - this.timestamp = timestamp; - return this; - } - - /** - * Adds a field to the embed (max 25). - * @param {StringResolvable} name The name of the field - * @param {StringResolvable} value The value of the field - * @param {boolean} [inline=false] Set the field to display inline - * @returns {RichEmbed} This embed - */ - addField(name, value, inline = false) { - if (this.fields.length >= 25) throw new RangeError('RichEmbeds may not exceed 25 fields.'); - name = resolveString(name); - if (name.length > 256) throw new RangeError('RichEmbed field names may not exceed 256 characters.'); - if (!/\S/.test(name)) throw new RangeError('RichEmbed field names may not be empty.'); - value = resolveString(value); - if (value.length > 1024) throw new RangeError('RichEmbed field values may not exceed 1024 characters.'); - if (!/\S/.test(value)) throw new RangeError('RichEmbed field values may not be empty.'); - this.fields.push({ name, value, inline }); - return this; - } - - /** - * Convenience function for `.addField('\u200B', '\u200B', inline)`. - * @param {boolean} [inline=false] Set the field to display inline - * @returns {RichEmbed} This embed - */ - addBlankField(inline = false) { - return this.addField('\u200B', '\u200B', inline); - } - - /** - * Set the thumbnail of this embed. - * @param {string} url The URL of the thumbnail - * @returns {RichEmbed} This embed - */ - setThumbnail(url) { - this.thumbnail = { url }; - return this; - } - - /** - * Set the image of this embed. - * @param {string} url The URL of the image - * @returns {RichEmbed} This embed - */ - setImage(url) { - this.image = { url }; - return this; - } - - /** - * Sets the footer of this embed. - * @param {StringResolvable} text The text of the footer - * @param {string} [icon] The icon URL of the footer - * @returns {RichEmbed} This embed - */ - setFooter(text, icon) { - text = resolveString(text); - if (text.length > 2048) throw new RangeError('RichEmbed footer text may not exceed 2048 characters.'); - this.footer = { text, icon_url: icon }; - return this; - } - - /** - * Sets the file to upload alongside the embed. This file can be accessed via `attachment://fileName.extension` when - * setting an embed image or author/footer icons. Only one file may be attached. - * @param {FileOptions|string|Attachment} file Local path or URL to the file to attach, - * or valid FileOptions for a file to attach - * @returns {RichEmbed} This embed - */ - attachFile(file) { - if (this.file) throw new RangeError('You may not upload more than one file at once.'); - if (file instanceof Attachment) file = file.file; - this.file = file; - return this; - } -} - -module.exports = RichEmbed; - -function resolveString(data) { - if (typeof data === 'string') return data; - if (data instanceof Array) return data.join('\n'); - return String(data); -} - - -/***/ }), -/* 28 */ -/***/ (function(module, exports) { - -/** - * Represents an attachment in a message. - * @param {BufferResolvable|Stream} file The file - * @param {string} [name] The name of the file, if any - */ -class Attachment { - constructor(file, name) { - this.file = null; - if (name) this.setAttachment(file, name); - else this._attach(file); - } - - /** - * The name of the file - * @type {?string} - * @readonly - */ - get name() { - return this.file.name; - } - - /** - * The file - * @type {?BufferResolvable|Stream} - * @readonly - */ - get attachment() { - return this.file.attachment; - } - - /** - * Set the file of this attachment. - * @param {BufferResolvable|Stream} file The file - * @param {string} name The name of the file - * @returns {Attachment} This attachment - */ - setAttachment(file, name) { - this.file = { attachment: file, name }; - return this; - } - - /** - * Set the file of this attachment. - * @param {BufferResolvable|Stream} attachment The file - * @returns {Attachment} This attachment - */ - setFile(attachment) { - this.file = { attachment }; - return this; - } - - /** - * Set the name of this attachment. - * @param {string} name The name of the image - * @returns {Attachment} This attachment - */ - setName(name) { - this.file.name = name; - return this; - } - - /** - * Set the file of this attachment. - * @param {BufferResolvable|Stream} file The file - * @param {string} name The name of the file - * @returns {void} - * @private - */ - _attach(file, name) { - if (typeof file === 'string') this.file = file; - else this.setAttachment(file, name); - } -} - -module.exports = Attachment; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -const util = __webpack_require__(13); -const Long = __webpack_require__(36); -const User = __webpack_require__(14); -const Role = __webpack_require__(15); -const Emoji = __webpack_require__(23); -const Presence = __webpack_require__(16).Presence; -const GuildMember = __webpack_require__(24); -const Constants = __webpack_require__(0); -const Collection = __webpack_require__(3); -const Util = __webpack_require__(4); -const Snowflake = __webpack_require__(8); - -/** - * Represents a guild (or a server) on Discord. - * It's recommended to see if a guild is available before performing operations or reading data from it. You can - * check this with `guild.available`. - */ -class Guild { - constructor(client, data) { - /** - * The client that created the instance of the guild - * @name Guild#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * A collection of members that are in this guild. The key is the member's ID, the value is the member - * @type {Collection} - */ - this.members = new Collection(); - - /** - * A collection of channels that are in this guild. The key is the channel's ID, the value is the channel - * @type {Collection} - */ - this.channels = new Collection(); - - /** - * A collection of roles that are in this guild. The key is the role's ID, the value is the role - * @type {Collection} - */ - this.roles = new Collection(); - - /** - * A collection of presences in this guild - * @type {Collection} - */ - this.presences = new Collection(); - - if (!data) return; - if (data.unavailable) { - /** - * Whether the guild is available to access. If it is not available, it indicates a server outage - * @type {boolean} - */ - this.available = false; - - /** - * The Unique ID of the guild, useful for comparisons - * @type {Snowflake} - */ - this.id = data.id; - } else { - this.setup(data); - if (!data.channels) this.available = false; - } - } - - /** - * Sets up the guild. - * @param {*} data The raw data of the guild - * @private - */ - setup(data) { - /** - * The name of the guild - * @type {string} - */ - this.name = data.name; - - /** - * The hash of the guild icon - * @type {?string} - */ - this.icon = data.icon; - - /** - * The hash of the guild splash image (VIP only) - * @type {?string} - */ - this.splash = data.splash; - - /** - * The region the guild is located in - * @type {string} - */ - this.region = data.region; - - /** - * The full amount of members in this guild as of `READY` - * @type {number} - */ - this.memberCount = data.member_count || this.memberCount; - - /** - * Whether the guild is "large" (has more than 250 members) - * @type {boolean} - */ - this.large = Boolean('large' in data ? data.large : this.large); - - /** - * An array of guild features - * @type {Object[]} - */ - this.features = data.features; - - /** - * The ID of the application that created this guild (if applicable) - * @type {?Snowflake} - */ - this.applicationID = data.application_id; - - /** - * The time in seconds before a user is counted as "away from keyboard" - * @type {?number} - */ - this.afkTimeout = data.afk_timeout; - - /** - * The ID of the voice channel where AFK members are moved - * @type {?string} - */ - this.afkChannelID = data.afk_channel_id; - - /** - * The ID of the system channel - * @type {?Snowflake} - */ - this.systemChannelID = data.system_channel_id; - - /** - * Whether embedded images are enabled on this guild - * @type {boolean} - */ - this.embedEnabled = data.embed_enabled; - - /** - * The verification level of the guild - * @type {number} - */ - this.verificationLevel = data.verification_level; - - /** - * The explicit content filter level of the guild - * @type {number} - */ - this.explicitContentFilter = data.explicit_content_filter; - - /** - * The timestamp the client user joined the guild at - * @type {number} - */ - this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp; - - this.id = data.id; - this.available = !data.unavailable; - this.features = data.features || this.features || []; - - if (data.members) { - this.members.clear(); - for (const guildUser of data.members) this._addMember(guildUser, false); - } - - if (data.owner_id) { - /** - * The user ID of this guild's owner - * @type {Snowflake} - */ - this.ownerID = data.owner_id; - } - - if (data.channels) { - this.channels.clear(); - for (const channel of data.channels) this.client.dataManager.newChannel(channel, this); - } - - if (data.roles) { - this.roles.clear(); - for (const role of data.roles) { - const newRole = new Role(this, role); - this.roles.set(newRole.id, newRole); - } - } - - if (data.presences) { - for (const presence of data.presences) { - this._setPresence(presence.user.id, presence); - } - } - - this._rawVoiceStates = new Collection(); - if (data.voice_states) { - for (const voiceState of data.voice_states) { - this._rawVoiceStates.set(voiceState.user_id, voiceState); - const member = this.members.get(voiceState.user_id); - if (member) { - member.serverMute = voiceState.mute; - member.serverDeaf = voiceState.deaf; - member.selfMute = voiceState.self_mute; - member.selfDeaf = voiceState.self_deaf; - member.voiceSessionID = voiceState.session_id; - member.voiceChannelID = voiceState.channel_id; - this.channels.get(voiceState.channel_id).members.set(member.user.id, member); - } - } - } - - if (!this.emojis) { - /** - * A collection of emojis that are in this guild - * The key is the emoji's ID, the value is the emoji - * @type {Collection} - */ - this.emojis = new Collection(); - for (const emoji of data.emojis) this.emojis.set(emoji.id, new Emoji(this, emoji)); - } else { - this.client.actions.GuildEmojisUpdate.handle({ - guild_id: this.id, - emojis: data.emojis, - }); - } - } - - /** - * The timestamp the guild was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time the guild was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The time the client user joined the guild - * @type {Date} - * @readonly - */ - get joinedAt() { - return new Date(this.joinedTimestamp); - } - - /** - * The URL to this guild's icon - * @type {?string} - * @readonly - */ - get iconURL() { - if (!this.icon) return null; - return Constants.Endpoints.Guild(this).Icon(this.client.options.http.cdn, this.icon); - } - - /** - * The acronym that shows up in place of a guild icon. - * @type {string} - * @readonly - */ - get nameAcronym() { - return this.name.replace(/\w+/g, name => name[0]).replace(/\s/g, ''); - } - - /** - * The URL to this guild's splash - * @type {?string} - * @readonly - */ - get splashURL() { - if (!this.splash) return null; - return Constants.Endpoints.Guild(this).Splash(this.client.options.http.cdn, this.splash); - } - - /** - * The owner of the guild - * @type {GuildMember} - * @readonly - */ - get owner() { - return this.members.get(this.ownerID); - } - - /** - * AFK voice channel for this guild - * @type {?VoiceChannel} - * @readonly - */ - get afkChannel() { - return this.client.channels.get(this.afkChannelID); - } - - /** - * System channel for this guild - * @type {?GuildChannel} - * @readonly - */ - get systemChannel() { - return this.client.channels.get(this.systemChannelID); - } - - /** - * If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection - * @type {?VoiceConnection} - * @readonly - */ - get voiceConnection() { - if (this.client.browser) return null; - return this.client.voice.connections.get(this.id) || null; - } - - /** - * The position of this guild - * This is only available when using a user account. - * @type {?number} - * @readonly - */ - get position() { - if (this.client.user.bot) return null; - if (!this.client.user.settings.guildPositions) return null; - return this.client.user.settings.guildPositions.indexOf(this.id); - } - - /** - * Whether the guild is muted - * This is only available when using a user account. - * @type {?boolean} - * @readonly - */ - get muted() { - if (this.client.user.bot) return null; - try { - return this.client.user.guildSettings.get(this.id).muted; - } catch (err) { - return false; - } - } - - /** - * The type of message that should notify you - * This is only available when using a user account. - * @type {?MessageNotificationType} - * @readonly - */ - get messageNotifications() { - if (this.client.user.bot) return null; - try { - return this.client.user.guildSettings.get(this.id).messageNotifications; - } catch (err) { - return null; - } - } - - /** - * Whether to receive mobile push notifications - * This is only available when using a user account. - * @type {?boolean} - * @readonly - */ - get mobilePush() { - if (this.client.user.bot) return null; - try { - return this.client.user.guildSettings.get(this.id).mobilePush; - } catch (err) { - return false; - } - } - - /** - * Whether to suppress everyone messages - * This is only available when using a user account. - * @type {?boolean} - * @readonly - */ - get suppressEveryone() { - if (this.client.user.bot) return null; - try { - return this.client.user.guildSettings.get(this.id).suppressEveryone; - } catch (err) { - return null; - } - } - - /** - * The `@everyone` role of the guild - * @type {Role} - * @readonly - */ - get defaultRole() { - return this.roles.get(this.id); - } - - /** - * The client user as a GuildMember of this guild - * @type {?GuildMember} - * @readonly - */ - get me() { - return this.members.get(this.client.user.id); - } - - /** - * Fetches a collection of roles in the current guild sorted by position - * @type {Collection} - * @readonly - * @private - */ - get _sortedRoles() { - return this._sortPositionWithID(this.roles); - } - - /** - * Returns the GuildMember form of a User object, if the user is present in the guild. - * @param {UserResolvable} user The user that you want to obtain the GuildMember of - * @returns {?GuildMember} - * @example - * // Get the guild member of a user - * const member = guild.member(message.author); - */ - member(user) { - return this.client.resolver.resolveGuildMember(this, user); - } - - /** - * Fetch a collection of banned users in this guild. - * @returns {Promise>} - */ - fetchBans() { - return this.client.rest.methods.getGuildBans(this) - // This entire re-mapping can be removed in the next major release - .then(bans => { - const users = new Collection(); - for (const ban of bans.values()) users.set(ban.user.id, ban.user); - return users; - }); - } - - /** - * Fetch a collection of invites to this guild. - * Resolves with a collection mapping invites by their codes. - * @returns {Promise>} - */ - fetchInvites() { - return this.client.rest.methods.getGuildInvites(this); - } - - /** - * Fetch all webhooks for the guild. - * @returns {Collection} - */ - fetchWebhooks() { - return this.client.rest.methods.getGuildWebhooks(this); - } - - /** - * Fetch available voice regions. - * @returns {Collection} - */ - fetchVoiceRegions() { - return this.client.rest.methods.fetchVoiceRegions(this.id); - } - - /** - * Fetch audit logs for this guild. - * @param {Object} [options={}] Options for fetching audit logs - * @param {Snowflake|GuildAuditLogsEntry} [options.before] Limit to entries from before specified entry - * @param {Snowflake|GuildAuditLogsEntry} [options.after] Limit to entries from after specified entry - * @param {number} [options.limit] Limit number of entries - * @param {UserResolvable} [options.user] Only show entries involving this user - * @param {string|number} [options.type] Only show entries involving this action type - * @returns {Promise} - */ - fetchAuditLogs(options) { - return this.client.rest.methods.getGuildAuditLogs(this, options); - } - - /** - * Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission. - * @param {UserResolvable} user User to add to the guild - * @param {Object} options Options for the addition - * @param {string} options.accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the - * bot's application - * @param {string} [options.nick] Nickname to give the member (requires `MANAGE_NICKNAMES`) - * @param {Collection|Role[]|Snowflake[]} [options.roles] Roles to add to the member - * (requires `MANAGE_ROLES`) - * @param {boolean} [options.mute] Whether the member should be muted (requires `MUTE_MEMBERS`) - * @param {boolean} [options.deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`) - * @returns {Promise} - */ - addMember(user, options) { - if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id)); - return this.client.rest.methods.putGuildMember(this, user, options); - } - - /** - * Fetch a single guild member from a user. - * @param {UserResolvable} user The user to fetch the member for - * @param {boolean} [cache=true] Insert the member into the members cache - * @returns {Promise} - */ - fetchMember(user, cache = true) { - user = this.client.resolver.resolveUser(user); - if (!user) return Promise.reject(new Error('User is not cached. Use Client.fetchUser first.')); - if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id)); - return this.client.rest.methods.getGuildMember(this, user, cache); - } - - /** - * Fetches all the members in the guild, even if they are offline. If the guild has less than 250 members, - * this should not be necessary. - * @param {string} [query=''] Limit fetch to members with similar usernames - * @param {number} [limit=0] Maximum number of members to request - * @returns {Promise} - */ - fetchMembers(query = '', limit = 0) { - return new Promise((resolve, reject) => { - if (this.memberCount === this.members.size) { - // Uncomment in v12 - // resolve(this.members) - resolve(this); - return; - } - this.client.ws.send({ - op: Constants.OPCodes.REQUEST_GUILD_MEMBERS, - d: { - guild_id: this.id, - query, - limit, - }, - }); - const handler = (members, guild) => { - if (guild.id !== this.id) return; - if (this.memberCount === this.members.size || members.length < 1000) { - this.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler); - // Uncomment in v12 - // resolve(this.members) - resolve(this); - } - }; - this.client.on(Constants.Events.GUILD_MEMBERS_CHUNK, handler); - this.client.setTimeout(() => reject(new Error('Members didn\'t arrive in time.')), 120 * 1000); - }); - } - - /** - * Performs a search within the entire guild. - * This is only available when using a user account. - * @param {MessageSearchOptions} [options={}] Options to pass to the search - * @returns {Promise} - * @example - * guild.search({ - * content: 'discord.js', - * before: '2016-11-17' - * }).then(res => { - * const hit = res.messages[0].find(m => m.hit).content; - * console.log(`I found: **${hit}**, total results: ${res.totalResults}`); - * }).catch(console.error); - */ - search(options = {}) { - return this.client.rest.methods.search(this, options); - } - - /** - * The data for editing a guild. - * @typedef {Object} GuildEditData - * @property {string} [name] The name of the guild - * @property {string} [region] The region of the guild - * @property {number} [verificationLevel] The verification level of the guild - * @property {number} [explicitContentFilter] The level of the explicit content filter - * @property {ChannelResolvable} [afkChannel] The AFK channel of the guild - * @property {ChannelResolvable} [systemChannel] The system channel of the guild - * @property {number} [afkTimeout] The AFK timeout of the guild - * @property {Base64Resolvable} [icon] The icon of the guild - * @property {GuildMemberResolvable} [owner] The owner of the guild - * @property {Base64Resolvable} [splash] The splash screen of the guild - */ - - /** - * Updates the guild with new information - e.g. a new name. - * @param {GuildEditData} data The data to update the guild with - * @param {string} [reason] Reason for editing the guild - * @returns {Promise} - * @example - * // Set the guild name and region - * guild.edit({ - * name: 'Discord Guild', - * region: 'london', - * }) - * .then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`)) - * .catch(console.error); - */ - edit(data, reason) { - const _data = {}; - if (data.name) _data.name = data.name; - if (data.region) _data.region = data.region; - if (typeof data.verificationLevel !== 'undefined') _data.verification_level = Number(data.verificationLevel); - if (data.afkChannel) _data.afk_channel_id = this.client.resolver.resolveChannel(data.afkChannel).id; - if (data.systemChannel) _data.system_channel_id = this.client.resolver.resolveChannel(data.systemChannel).id; - if (data.afkTimeout) _data.afk_timeout = Number(data.afkTimeout); - if (typeof data.icon !== 'undefined') _data.icon = data.icon; - if (data.owner) _data.owner_id = this.client.resolver.resolveUser(data.owner).id; - if (typeof data.splash !== 'undefined') _data.splash = data.splash; - if (typeof data.explicitContentFilter !== 'undefined') { - _data.explicit_content_filter = Number(data.explicitContentFilter); - } - return this.client.rest.methods.updateGuild(this, _data, reason); - } - - /** - * Edit the level of the explicit content filter. - * @param {number} explicitContentFilter The new level of the explicit content filter - * @param {string} [reason] Reason for changing the level of the guild's explicit content filter - * @returns {Promise} - */ - setExplicitContentFilter(explicitContentFilter, reason) { - return this.edit({ explicitContentFilter }, reason); - } - - /** - * Edit the name of the guild. - * @param {string} name The new name of the guild - * @param {string} [reason] Reason for changing the guild's name - * @returns {Promise} - * @example - * // Edit the guild name - * guild.setName('Discord Guild') - * .then(updated => console.log(`Updated guild name to ${guild.name}`)) - * .catch(console.error); - */ - setName(name, reason) { - return this.edit({ name }, reason); - } - - /** - * Edit the region of the guild. - * @param {string} region The new region of the guild - * @param {string} [reason] Reason for changing the guild's region - * @returns {Promise} - * @example - * // Edit the guild region - * guild.setRegion('london') - * .then(updated => console.log(`Updated guild region to ${guild.region}`)) - * .catch(console.error); - */ - setRegion(region, reason) { - return this.edit({ region }, reason); - } - - /** - * Edit the verification level of the guild. - * @param {number} verificationLevel The new verification level of the guild - * @param {string} [reason] Reason for changing the guild's verification level - * @returns {Promise} - * @example - * // Edit the guild verification level - * guild.setVerificationLevel(1) - * .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`)) - * .catch(console.error); - */ - setVerificationLevel(verificationLevel, reason) { - return this.edit({ verificationLevel }, reason); - } - - /** - * Edit the AFK channel of the guild. - * @param {ChannelResolvable} afkChannel The new AFK channel - * @param {string} [reason] Reason for changing the guild's AFK channel - * @returns {Promise} - * @example - * // Edit the guild AFK channel - * guild.setAFKChannel(channel) - * .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`)) - * .catch(console.error); - */ - setAFKChannel(afkChannel, reason) { - return this.edit({ afkChannel }, reason); - } - - /** - * Edit the system channel of the guild. - * @param {ChannelResolvable} systemChannel The new system channel - * @param {string} [reason] Reason for changing the guild's system channel - * @returns {Promise} - */ - setSystemChannel(systemChannel, reason) { - return this.edit({ systemChannel }, reason); - } - - /** - * Edit the AFK timeout of the guild. - * @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK - * @param {string} [reason] Reason for changing the guild's AFK timeout - * @returns {Promise} - * @example - * // Edit the guild AFK channel - * guild.setAFKTimeout(60) - * .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`)) - * .catch(console.error); - */ - setAFKTimeout(afkTimeout, reason) { - return this.edit({ afkTimeout }, reason); - } - - /** - * Set a new guild icon. - * @param {Base64Resolvable|BufferResolvable} icon The new icon of the guild - * @param {string} [reason] Reason for changing the guild's icon - * @returns {Promise} - * @example - * // Edit the guild icon - * guild.setIcon('./icon.png') - * .then(updated => console.log('Updated the guild icon')) - * .catch(console.error); - */ - setIcon(icon, reason) { - return this.client.resolver.resolveImage(icon).then(data => this.edit({ icon: data, reason })); - } - - /** - * Sets a new owner of the guild. - * @param {GuildMemberResolvable} owner The new owner of the guild - * @param {string} [reason] Reason for setting the new owner - * @returns {Promise} - * @example - * // Edit the guild owner - * guild.setOwner(guild.members.first()) - * .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`)) - * .catch(console.error); - */ - setOwner(owner, reason) { - return this.edit({ owner }, reason); - } - - /** - * Set a new guild splash screen. - * @param {BufferResolvable|Base64Resolvable} splash The new splash screen of the guild - * @param {string} [reason] Reason for changing the guild's splash screen - * @returns {Promise} - * @example - * // Edit the guild splash - * guild.setSplash('./splash.png') - * .then(updated => console.log('Updated the guild splash')) - * .catch(console.error); - */ - setSplash(splash) { - return this.client.resolver.resolveImage(splash).then(data => this.edit({ splash: data })); - } - - /** - * Sets the position of the guild in the guild listing. - * This is only available when using a user account. - * @param {number} position Absolute or relative position - * @param {boolean} [relative=false] Whether to position relatively or absolutely - * @returns {Promise} - */ - setPosition(position, relative) { - if (this.client.user.bot) { - return Promise.reject(new Error('Setting guild position is only available for user accounts')); - } - return this.client.user.settings.setGuildPosition(this, position, relative); - } - - /** - * Marks all messages in this guild as read. - * This is only available when using a user account. - * @returns {Promise} - */ - acknowledge() { - return this.client.rest.methods.ackGuild(this); - } - - /** - * Allow direct messages from guild members. - * This is only available when using a user account. - * @param {boolean} allow Whether to allow direct messages - * @returns {Promise} - */ - allowDMs(allow) { - const settings = this.client.user.settings; - if (allow) return settings.removeRestrictedGuild(this); - else return settings.addRestrictedGuild(this); - } - - /** - * Bans a user from the guild. - * @param {UserResolvable} user The user to ban - * @param {Object|number|string} [options] Ban options. If a number, the number of days to delete messages for, if a - * string, the ban reason. Supplying an object allows you to do both. - * @param {number} [options.days=0] Number of days of messages to delete - * @param {string} [options.reason] Reason for banning - * @returns {Promise} Result object will be resolved as specifically as possible. - * If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot - * be resolved, the user ID will be the result. - * @example - * // Ban a user by ID (or with a user/guild member object) - * guild.ban('some user ID') - * .then(user => console.log(`Banned ${user.username || user.id || user} from ${guild.name}`)) - * .catch(console.error); - */ - ban(user, options = {}) { - if (typeof options === 'number') { - options = { reason: null, 'delete-message-days': options }; - } else if (typeof options === 'string') { - options = { reason: options, 'delete-message-days': 0 }; - } - if (options.days) options['delete-message-days'] = options.days; - return this.client.rest.methods.banGuildMember(this, user, options); - } - - /** - * Unbans a user from the guild. - * @param {UserResolvable} user The user to unban - * @param {string} [reason] Reason for unbanning the user - * @returns {Promise} - * @example - * // Unban a user by ID (or with a user/guild member object) - * guild.unban('some user ID') - * .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`)) - * .catch(console.error); - */ - unban(user, reason) { - return this.client.rest.methods.unbanGuildMember(this, user, reason); - } - - /** - * Prunes members from the guild based on how long they have been inactive. - * @param {number} days Number of days of inactivity required to kick - * @param {boolean} [dry=false] If true, will return number of users that will be kicked, without actually doing it - * @param {string} [reason] Reason for this prune - * @returns {Promise} The number of members that were/will be kicked - * @example - * // See how many members will be pruned - * guild.pruneMembers(12, true) - * .then(pruned => console.log(`This will prune ${pruned} people!`)) - * .catch(console.error); - * @example - * // Actually prune the members - * guild.pruneMembers(12) - * .then(pruned => console.log(`I just pruned ${pruned} people!`)) - * .catch(console.error); - */ - pruneMembers(days, dry = false, reason) { - if (typeof days !== 'number') throw new TypeError('Days must be a number.'); - return this.client.rest.methods.pruneGuildMembers(this, days, dry, reason); - } - - /** - * Syncs this guild (already done automatically every 30 seconds). - * This is only available when using a user account. - */ - sync() { - if (!this.client.user.bot) this.client.syncGuilds([this]); - } - - /** - * Creates a new channel in the guild. - * @param {string} name The name of the new channel - * @param {string} type The type of the new channel, either `text` or `voice` - * @param {Array} [overwrites] Permission overwrites to apply to the new channel - * @param {string} [reason] Reason for creating this channel - * @returns {Promise} - * @example - * // Create a new text channel - * guild.createChannel('new-general', 'text') - * .then(channel => console.log(`Created new channel ${channel}`)) - * .catch(console.error); - */ - createChannel(name, type, overwrites, reason) { - return this.client.rest.methods.createChannel(this, name, type, overwrites, reason); - } - - /** - * The data needed for updating a channel's position. - * @typedef {Object} ChannelPosition - * @property {ChannelResolvable} channel Channel to update - * @property {number} position New position for the channel - */ - - /** - * Batch-updates the guild's channels' positions. - * @param {ChannelPosition[]} channelPositions Channel positions to update - * @returns {Promise} - * @example - * guild.updateChannels([{ channel: channelID, position: newChannelIndex }]) - * .then(guild => console.log(`Updated channel positions for ${guild.id}`)) - * .catch(console.error); - */ - setChannelPositions(channelPositions) { - return this.client.rest.methods.updateChannelPositions(this.id, channelPositions); - } - - /** - * Creates a new role in the guild with given information - * @param {RoleData} [data] The data to update the role with - * @param {string} [reason] Reason for creating this role - * @returns {Promise} - * @example - * // Create a new role - * guild.createRole() - * .then(role => console.log(`Created role ${role}`)) - * .catch(console.error); - * @example - * // Create a new role with data - * guild.createRole({ - * name: 'Super Cool People', - * color: 'BLUE', - * }) - * .then(role => console.log(`Created role ${role}`)) - * .catch(console.error) - */ - createRole(data = {}, reason) { - return this.client.rest.methods.createGuildRole(this, data, reason); - } - - /** - * Creates a new custom emoji in the guild. - * @param {BufferResolvable|Base64Resolvable} attachment The image for the emoji - * @param {string} name The name for the emoji - * @param {Collection|Role[]} [roles] Roles to limit the emoji to - * @param {string} [reason] Reason for creating the emoji - * @returns {Promise} The created emoji - * @example - * // Create a new emoji from a url - * guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip') - * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) - * .catch(console.error); - * @example - * // Create a new emoji from a file on your computer - * guild.createEmoji('./memes/banana.png', 'banana') - * .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`)) - * .catch(console.error); - */ - createEmoji(attachment, name, roles, reason) { - if (typeof attachment === 'string' && attachment.startsWith('data:')) { - return this.client.rest.methods.createEmoji(this, attachment, name, roles, reason); - } else { - return this.client.resolver.resolveImage(attachment).then(data => - this.client.rest.methods.createEmoji(this, data, name, roles, reason) - ); - } - } - - /** - * Delete an emoji. - * @param {Emoji|string} emoji The emoji to delete - * @param {string} [reason] Reason for deleting the emoji - * @returns {Promise} - */ - deleteEmoji(emoji, reason) { - if (!(emoji instanceof Emoji)) emoji = this.emojis.get(emoji); - return this.client.rest.methods.deleteEmoji(emoji, reason); - } - - /** - * Causes the client to leave the guild. - * @returns {Promise} - * @example - * // Leave a guild - * guild.leave() - * .then(g => console.log(`Left the guild ${g}`)) - * .catch(console.error); - */ - leave() { - return this.client.rest.methods.leaveGuild(this); - } - - /** - * Causes the client to delete the guild. - * @returns {Promise} - * @example - * // Delete a guild - * guild.delete() - * .then(g => console.log(`Deleted the guild ${g}`)) - * .catch(console.error); - */ - delete() { - return this.client.rest.methods.deleteGuild(this); - } - - /** - * Whether this guild equals another guild. It compares all properties, so for most operations - * it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often - * what most users need. - * @param {Guild} guild The guild to compare with - * @returns {boolean} - */ - equals(guild) { - let equal = - guild && - this.id === guild.id && - this.available === !guild.unavailable && - this.splash === guild.splash && - this.region === guild.region && - this.name === guild.name && - this.memberCount === guild.member_count && - this.large === guild.large && - this.icon === guild.icon && - Util.arraysEqual(this.features, guild.features) && - this.ownerID === guild.owner_id && - this.verificationLevel === guild.verification_level && - this.embedEnabled === guild.embed_enabled; - - if (equal) { - if (this.embedChannel) { - if (this.embedChannel.id !== guild.embed_channel_id) equal = false; - } else if (guild.embed_channel_id) { - equal = false; - } - } - - return equal; - } - - /** - * When concatenated with a string, this automatically concatenates the guild's name instead of the guild object. - * @returns {string} - * @example - * // Logs: Hello from My Guild! - * console.log(`Hello from ${guild}!`); - * @example - * // Logs: Hello from My Guild! - * console.log('Hello from ' + guild + '!'); - */ - toString() { - return this.name; - } - - _addMember(guildUser, emitEvent = true) { - const existing = this.members.has(guildUser.user.id); - if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user); - - guildUser.joined_at = guildUser.joined_at || 0; - const member = new GuildMember(this, guildUser); - this.members.set(member.id, member); - - if (this._rawVoiceStates && this._rawVoiceStates.has(member.user.id)) { - const voiceState = this._rawVoiceStates.get(member.user.id); - member.serverMute = voiceState.mute; - member.serverDeaf = voiceState.deaf; - member.selfMute = voiceState.self_mute; - member.selfDeaf = voiceState.self_deaf; - member.voiceSessionID = voiceState.session_id; - member.voiceChannelID = voiceState.channel_id; - if (this.client.channels.has(voiceState.channel_id)) { - this.client.channels.get(voiceState.channel_id).members.set(member.user.id, member); - } else { - this.client.emit('warn', `Member ${member.id} added in guild ${this.id} with an uncached voice channel`); - } - } - - /** - * Emitted whenever a user joins a guild. - * @event Client#guildMemberAdd - * @param {GuildMember} member The member that has joined a guild - */ - if (this.client.ws.connection.status === Constants.Status.READY && emitEvent && !existing) { - this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member); - } - - return member; - } - - _updateMember(member, data) { - const oldMember = Util.cloneObject(member); - - if (data.roles) member._roles = data.roles; - if (typeof data.nick !== 'undefined') member.nickname = data.nick; - - const notSame = member.nickname !== oldMember.nickname || !Util.arraysEqual(member._roles, oldMember._roles); - - if (this.client.ws.connection.status === Constants.Status.READY && notSame) { - /** - * Emitted whenever a guild member changes - i.e. new role, removed role, nickname. - * @event Client#guildMemberUpdate - * @param {GuildMember} oldMember The member before the update - * @param {GuildMember} newMember The member after the update - */ - this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member); - } - - return { - old: oldMember, - mem: member, - }; - } - - _removeMember(guildMember) { - this.members.delete(guildMember.id); - } - - _memberSpeakUpdate(user, speaking) { - const member = this.members.get(user); - if (member && member.speaking !== speaking) { - member.speaking = speaking; - /** - * Emitted once a guild member starts/stops speaking. - * @event Client#guildMemberSpeaking - * @param {GuildMember} member The member that started/stopped speaking - * @param {boolean} speaking Whether or not the member is speaking - */ - this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking); - } - } - - _setPresence(id, presence) { - if (this.presences.get(id)) { - this.presences.get(id).update(presence); - return; - } - this.presences.set(id, new Presence(presence)); - } - - /** - * Set the position of a role in this guild. - * @param {string|Role} role The role to edit, can be a role object or a role ID - * @param {number} position The new position of the role - * @param {boolean} [relative=false] Position Moves the role relative to its current position - * @returns {Promise} - */ - setRolePosition(role, position, relative = false) { - if (typeof role === 'string') { - role = this.roles.get(role); - if (!role) return Promise.reject(new Error('Supplied role is not a role or snowflake.')); - } - - position = Number(position); - if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); - - let updatedRoles = this._sortedRoles.array(); - - Util.moveElementInArray(updatedRoles, role, position, relative); - - updatedRoles = updatedRoles.map((r, i) => ({ id: r.id, position: i })); - return this.client.rest.methods.setRolePositions(this.id, updatedRoles); - } - - /** - * Set the position of a channel in this guild. - * @param {string|GuildChannel} channel The channel to edit, can be a channel object or a channel ID - * @param {number} position The new position of the channel - * @param {boolean} [relative=false] Position Moves the channel relative to its current position - * @returns {Promise} - */ - setChannelPosition(channel, position, relative = false) { - if (typeof channel === 'string') { - channel = this.channels.get(channel); - if (!channel) return Promise.reject(new Error('Supplied channel is not a channel or snowflake.')); - } - - position = Number(position); - if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.')); - - let updatedChannels = this._sortedChannels(channel.type).array(); - - Util.moveElementInArray(updatedChannels, channel, position, relative); - - updatedChannels = updatedChannels.map((r, i) => ({ id: r.id, position: i })); - return this.client.rest.methods.setChannelPositions(this.id, updatedChannels); - } - - /** - * Fetches a collection of channels in the current guild sorted by position. - * @param {string} type The channel type - * @returns {Collection} - * @private - */ - _sortedChannels(type) { - return this._sortPositionWithID(this.channels.filter(c => { - if (type === 'voice' && c.type === 'voice') return true; - else if (type !== 'voice' && c.type !== 'voice') return true; - else return type === c.type; - })); - } - - /** - * Sorts a collection by object position or ID if the positions are equivalent. - * Intended to be identical to Discord's sorting method. - * @param {Collection} collection The collection to sort - * @returns {Collection} - * @private - */ - _sortPositionWithID(collection) { - return collection.sort((a, b) => - a.position !== b.position ? - a.position - b.position : - Long.fromString(a.id).sub(Long.fromString(b.id)).toNumber() - ); - } -} - -/** - * The `#general` TextChannel of the guild - * @name Guild#defaultChannel - * @type {TextChannel} - * @readonly - */ -Object.defineProperty(Guild.prototype, 'defaultChannel', { - get: util.deprecate(function defaultChannel() { - return this.channels.get(this.id); - }, 'Guild#defaultChannel: This property is obsolete, will be removed in v12.0.0, and may not function as expected.'), -}); - -module.exports = Guild; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - -const Channel = __webpack_require__(17); -const Role = __webpack_require__(15); -const PermissionOverwrites = __webpack_require__(69); -const Permissions = __webpack_require__(11); -const Collection = __webpack_require__(3); -const Constants = __webpack_require__(0); - -/** - * Represents a guild channel (i.e. text channels and voice channels). - * @extends {Channel} - */ -class GuildChannel extends Channel { - constructor(guild, data) { - super(guild.client, data); - - /** - * The guild the channel is in - * @type {Guild} - */ - this.guild = guild; - } - - setup(data) { - super.setup(data); - - /** - * The name of the guild channel - * @type {string} - */ - this.name = data.name; - - /** - * The position of the channel in the list - * @type {number} - */ - this.position = data.position; - - /** - * A map of permission overwrites in this channel for roles and users - * @type {Collection} - */ - this.permissionOverwrites = new Collection(); - if (data.permission_overwrites) { - for (const overwrite of data.permission_overwrites) { - this.permissionOverwrites.set(overwrite.id, new PermissionOverwrites(this, overwrite)); - } - } - } - - /** - * The position of the channel - * @type {number} - * @readonly - */ - get calculatedPosition() { - const sorted = this.guild._sortedChannels(this.type); - return sorted.array().indexOf(sorted.get(this.id)); - } - - /** - * Gets the overall set of permissions for a user in this channel, taking into account roles and permission - * overwrites. - * @param {GuildMemberResolvable} member The user that you want to obtain the overall permissions for - * @returns {?Permissions} - */ - permissionsFor(member) { - member = this.client.resolver.resolveGuildMember(this.guild, member); - if (!member) return null; - if (member.id === this.guild.ownerID) return new Permissions(member, Permissions.ALL); - - let permissions = 0; - - const roles = member.roles; - for (const role of roles.values()) permissions |= role.permissions; - - const overwrites = this.overwritesFor(member, true, roles); - - if (overwrites.everyone) { - permissions &= ~overwrites.everyone.deny; - permissions |= overwrites.everyone.allow; - } - - let allow = 0; - for (const overwrite of overwrites.roles) { - permissions &= ~overwrite.deny; - allow |= overwrite.allow; - } - permissions |= allow; - - if (overwrites.member) { - permissions &= ~overwrites.member.deny; - permissions |= overwrites.member.allow; - } - - const admin = Boolean(permissions & Permissions.FLAGS.ADMINISTRATOR); - if (admin) permissions = Permissions.ALL; - - return new Permissions(member, permissions); - } - - overwritesFor(member, verified = false, roles = null) { - if (!verified) member = this.client.resolver.resolveGuildMember(this.guild, member); - if (!member) return []; - - roles = roles || member.roles; - const roleOverwrites = []; - let memberOverwrites; - let everyoneOverwrites; - - for (const overwrite of this.permissionOverwrites.values()) { - if (overwrite.id === this.guild.id) { - everyoneOverwrites = overwrite; - } else if (roles.has(overwrite.id)) { - roleOverwrites.push(overwrite); - } else if (overwrite.id === member.id) { - memberOverwrites = overwrite; - } - } - - return { - everyone: everyoneOverwrites, - roles: roleOverwrites, - member: memberOverwrites, - }; - } - - /** - * An object mapping permission flags to `true` (enabled) or `false` (disabled). - * ```js - * { - * 'SEND_MESSAGES': true, - * 'ATTACH_FILES': false, - * } - * ``` - * @typedef {Object} PermissionOverwriteOptions - */ - - /** - * Overwrites the permissions for a user or role in this channel. - * @param {Role|Snowflake|UserResolvable} userOrRole The user or role to update - * @param {PermissionOverwriteOptions} options The configuration for the update - * @param {string} [reason] Reason for creating/editing this overwrite - * @returns {Promise} - * @example - * // Overwrite permissions for a message author - * message.channel.overwritePermissions(message.author, { - * SEND_MESSAGES: false - * }) - * .then(() => console.log('Done!')) - * .catch(console.error); - */ - overwritePermissions(userOrRole, options, reason) { - const payload = { - allow: 0, - deny: 0, - }; - - if (userOrRole instanceof Role) { - payload.type = 'role'; - } else if (this.guild.roles.has(userOrRole)) { - userOrRole = this.guild.roles.get(userOrRole); - payload.type = 'role'; - } else { - userOrRole = this.client.resolver.resolveUser(userOrRole); - payload.type = 'member'; - if (!userOrRole) return Promise.reject(new TypeError('Supplied parameter was neither a User nor a Role.')); - } - - payload.id = userOrRole.id; - - const prevOverwrite = this.permissionOverwrites.get(userOrRole.id); - - if (prevOverwrite) { - payload.allow = prevOverwrite.allow; - payload.deny = prevOverwrite.deny; - } - - for (const perm in options) { - if (options[perm] === true) { - payload.allow |= Permissions.FLAGS[perm] || 0; - payload.deny &= ~(Permissions.FLAGS[perm] || 0); - } else if (options[perm] === false) { - payload.allow &= ~(Permissions.FLAGS[perm] || 0); - payload.deny |= Permissions.FLAGS[perm] || 0; - } else if (options[perm] === null) { - payload.allow &= ~(Permissions.FLAGS[perm] || 0); - payload.deny &= ~(Permissions.FLAGS[perm] || 0); - } - } - - return this.client.rest.methods.setChannelOverwrite(this, payload, reason); - } - - /** - * The data for a guild channel. - * @typedef {Object} ChannelData - * @property {string} [name] The name of the channel - * @property {number} [position] The position of the channel - * @property {string} [topic] The topic of the text channel - * @property {number} [bitrate] The bitrate of the voice channel - * @property {number} [userLimit] The user limit of the channel - */ - - /** - * Edits the channel. - * @param {ChannelData} data The new data for the channel - * @param {string} [reason] Reason for editing this channel - * @returns {Promise} - * @example - * // Edit a channel - * channel.edit({name: 'new-channel'}) - * .then(c => console.log(`Edited channel ${c}`)) - * .catch(console.error); - */ - edit(data, reason) { - return this.client.rest.methods.updateChannel(this, data, reason); - } - - /** - * Set a new name for the guild channel. - * @param {string} name The new name for the guild channel - * @param {string} [reason] Reason for changing the guild channel's name - * @returns {Promise} - * @example - * // Set a new channel name - * channel.setName('not_general') - * .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`)) - * .catch(console.error); - */ - setName(name, reason) { - return this.edit({ name }, reason); - } - - /** - * Set a new position for the guild channel. - * @param {number} position The new position for the guild channel - * @param {boolean} [relative=false] Move the position relative to its current value - * @returns {Promise} - * @example - * // Set a new channel position - * channel.setPosition(2) - * .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`)) - * .catch(console.error); - */ - setPosition(position, relative) { - return this.guild.setChannelPosition(this, position, relative).then(() => this); - } - - /** - * Set a new topic for the guild channel. - * @param {string} topic The new topic for the guild channel - * @param {string} [reason] Reason for changing the guild channel's topic - * @returns {Promise} - * @example - * // Set a new channel topic - * channel.setTopic('needs more rate limiting') - * .then(newChannel => console.log(`Channel's new topic is ${newChannel.topic}`)) - * .catch(console.error); - */ - setTopic(topic, reason) { - return this.edit({ topic }, reason); - } - - /** - * Create an invite to this guild channel. - * This is only available when using a bot account. - * @param {Object} [options={}] Options for the invite - * @param {boolean} [options.temporary=false] Whether members that joined via the invite should be automatically - * kicked after 24 hours if they have not yet received a role - * @param {number} [options.maxAge=86400] How long the invite should last (in seconds, 0 for forever) - * @param {number} [options.maxUses=0] Maximum number of uses - * @param {boolean} [options.unique=false] Create a unique invite, or use an existing one with similar settings - * @param {string} [reason] Reason for creating the invite - * @returns {Promise} - */ - createInvite(options = {}, reason) { - return this.client.rest.methods.createChannelInvite(this, options, reason); - } - - /** - * Clone this channel. - * @param {string} [name=this.name] Optional name for the new channel, otherwise it has the name of this channel - * @param {boolean} [withPermissions=true] Whether to clone the channel with this channel's permission overwrites - * @param {boolean} [withTopic=true] Whether to clone the channel with this channel's topic - * @param {string} [reason] Reason for cloning this channel - * @returns {Promise} - */ - clone(name = this.name, withPermissions = true, withTopic = true, reason) { - return this.guild.createChannel(name, this.type, withPermissions ? this.permissionOverwrites : [], reason) - .then(channel => withTopic ? channel.setTopic(this.topic) : channel); - } - - /** - * Deletes this channel. - * @param {string} [reason] Reason for deleting this channel - * @returns {Promise} - * @example - * // Delete the channel - * channel.delete('making room for new channels') - * .then(channel => console.log(`Deleted ${channel.name} to make room for new channels`)) - * .catch(console.error); // Log error - */ - delete(reason) { - return this.client.rest.methods.deleteChannel(this, reason); - } - - /** - * Checks if this channel has the same type, topic, position, name, overwrites and ID as another channel. - * In most cases, a simple `channel.id === channel2.id` will do, and is much faster too. - * @param {GuildChannel} channel Channel to compare with - * @returns {boolean} - */ - equals(channel) { - let equal = channel && - this.id === channel.id && - this.type === channel.type && - this.topic === channel.topic && - this.position === channel.position && - this.name === channel.name; - - if (equal) { - if (this.permissionOverwrites && channel.permissionOverwrites) { - equal = this.permissionOverwrites.equals(channel.permissionOverwrites); - } else { - equal = !this.permissionOverwrites && !channel.permissionOverwrites; - } - } - - return equal; - } - - /** - * Whether the channel is deletable by the client user - * @type {boolean} - * @readonly - */ - get deletable() { - return this.id !== this.guild.id && - this.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_CHANNELS); - } - - /** - * Whether the channel is muted - * This is only available when using a user account. - * @type {?boolean} - * @readonly - */ - get muted() { - if (this.client.user.bot) return null; - try { - return this.client.user.guildSettings.get(this.guild.id).channelOverrides.get(this.id).muted; - } catch (err) { - return false; - } - } - - /** - * The type of message that should notify you - * This is only available when using a user account. - * @type {?MessageNotificationType} - * @readonly - */ - get messageNotifications() { - if (this.client.user.bot) return null; - try { - return this.client.user.guildSettings.get(this.guild.id).channelOverrides.get(this.id).messageNotifications; - } catch (err) { - return Constants.MessageNotificationTypes[3]; - } - } - - /** - * When concatenated with a string, this automatically returns the channel's mention instead of the Channel object. - * @returns {string} - * @example - * // Outputs: Hello from #general - * console.log(`Hello from ${channel}`); - * @example - * // Outputs: Hello from #general - * console.log('Hello from ' + channel); - */ - toString() { - return `<#${this.id}>`; - } -} - -module.exports = GuildChannel; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - -const Snekfetch = __webpack_require__(78); - -// Sync stuff might go here - -module.exports = Snekfetch; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Stream; - -var EE = __webpack_require__(9).EventEmitter; -var inherits = __webpack_require__(10); - -inherits(Stream, EE); -Stream.Readable = __webpack_require__(18); -Stream.Writable = __webpack_require__(85); -Stream.Duplex = __webpack_require__(86); -Stream.Transform = __webpack_require__(87); -Stream.PassThrough = __webpack_require__(88); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(5) -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - - - -/**/ - -var processNextTick = __webpack_require__(25); -/**/ - -module.exports = Writable; - -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var util = __webpack_require__(19); -util.inherits = __webpack_require__(10); -/**/ - -/**/ -var internalUtil = { - deprecate: __webpack_require__(83) -}; -/**/ - -/**/ -var Stream = __webpack_require__(46); -/**/ - -/**/ -var Buffer = __webpack_require__(33).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - -var destroyImpl = __webpack_require__(47); - -util.inherits(Writable, Stream); - -function nop() {} - -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(12); - - options = options || {}; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // if _final has been called - this.finalCalled = false; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // has it been destroyed - this.destroyed = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || __webpack_require__(12); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - processNextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; - } - return valid; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = _isUint8Array(chunk) && !state.objectMode; - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - processNextTick(cb, er); - // this can emit finish, and it will always happen - // after error - processNextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - processNextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; - } -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); - -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(81).setImmediate, __webpack_require__(6))) - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.decode = exports.parse = __webpack_require__(89); -exports.encode = exports.stringify = __webpack_require__(90); - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* - Copyright 2013 Daniel Wirtz - Copyright 2009 The Closure Library Authors. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS-IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -/** - * @license long.js (c) 2013 Daniel Wirtz - * Released under the Apache License, Version 2.0 - * see: https://github.com/dcodeIO/long.js for details - */ -(function(global, factory) { - - /* AMD */ if (true) - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"]) - module["exports"] = factory(); - /* Global */ else - (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory(); - -})(this, function() { - "use strict"; - - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * @exports Long - * @class A Long class for representing a 64 bit two's-complement integer value. - * @param {number} low The low (signed) 32 bits of the long - * @param {number} high The high (signed) 32 bits of the long - * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed - * @constructor - */ - function Long(low, high, unsigned) { - - /** - * The low 32 bits as a signed value. - * @type {number} - */ - this.low = low | 0; - - /** - * The high 32 bits as a signed value. - * @type {number} - */ - this.high = high | 0; - - /** - * Whether unsigned or not. - * @type {boolean} - */ - this.unsigned = !!unsigned; - } - - // The internal representation of a long is the two given signed, 32-bit values. - // We use 32-bit pieces because these are the size of integers on which - // Javascript performs bit-operations. For operations like addition and - // multiplication, we split each number into 16 bit pieces, which can easily be - // multiplied within Javascript's floating-point representation without overflow - // or change in sign. - // - // In the algorithms below, we frequently reduce the negative case to the - // positive case by negating the input(s) and then post-processing the result. - // Note that we must ALWAYS check specially whether those values are MIN_VALUE - // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - // a positive number, it overflows back into a negative). Not handling this - // case would often result in infinite recursion. - // - // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* - // methods on which they depend. - - /** - * An indicator used to reliably determine if an object is a Long or not. - * @type {boolean} - * @const - * @private - */ - Long.prototype.__isLong__; - - Object.defineProperty(Long.prototype, "__isLong__", { - value: true, - enumerable: false, - configurable: false - }); - - /** - * @function - * @param {*} obj Object - * @returns {boolean} - * @inner - */ - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; - } - - /** - * Tests if the specified object is a Long. - * @function - * @param {*} obj Object - * @returns {boolean} - */ - Long.isLong = isLong; - - /** - * A cache of the Long representations of small integer values. - * @type {!Object} - * @inner - */ - var INT_CACHE = {}; - - /** - * A cache of the Long representations of small unsigned integer values. - * @type {!Object} - * @inner - */ - var UINT_CACHE = {}; - - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if (cache = (0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if (cache = (-128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } - } - - /** - * Returns a Long representing the given 32 bit integer value. - * @function - * @param {number} value The 32 bit integer in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed - * @returns {!Long} The corresponding Long value - */ - Long.fromInt = fromInt; - - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromNumber(value, unsigned) { - if (isNaN(value) || !isFinite(value)) - return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) - return UZERO; - if (value >= TWO_PWR_64_DBL) - return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) - return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return MAX_VALUE; - } - if (value < 0) - return fromNumber(-value, unsigned).neg(); - return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); - } - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @function - * @param {number} value The number in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed - * @returns {!Long} The corresponding Long value - */ - Long.fromNumber = fromNumber; - - /** - * @param {number} lowBits - * @param {number} highBits - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } - - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is - * assumed to use 32 bits. - * @function - * @param {number} lowBits The low 32 bits - * @param {number} highBits The high 32 bits - * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBits = fromBits; - - /** - * @function - * @param {number} base - * @param {number} exponent - * @returns {number} - * @inner - */ - var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) - - /** - * @param {string} str - * @param {(boolean|number)=} unsigned - * @param {number=} radix - * @returns {!Long} - * @inner - */ - function fromString(str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") - return ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - radix = unsigned, - unsigned = false; - } else { - unsigned = !! unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 8)); - - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), - value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - - /** - * Returns a Long representation of the given string, written using the specified radix. - * @function - * @param {string} str The textual representation of the Long - * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed - * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 - * @returns {!Long} The corresponding Long value - */ - Long.fromString = fromString; - - /** - * @function - * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val - * @returns {!Long} - * @inner - */ - function fromValue(val) { - if (val /* is compatible */ instanceof Long) - return val; - if (typeof val === 'number') - return fromNumber(val); - if (typeof val === 'string') - return fromString(val); - // Throws for non-objects, converts non-instanceof Long: - return fromBits(val.low, val.high, val.unsigned); - } - - /** - * Converts the specified value to a Long. - * @function - * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value - * @returns {!Long} - */ - Long.fromValue = fromValue; - - // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be - // no runtime penalty for these. - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_16_DBL = 1 << 16; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_24_DBL = 1 << 24; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - - /** - * @type {!Long} - * @const - * @inner - */ - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); - - /** - * @type {!Long} - * @inner - */ - var ZERO = fromInt(0); - - /** - * Signed zero. - * @type {!Long} - */ - Long.ZERO = ZERO; - - /** - * @type {!Long} - * @inner - */ - var UZERO = fromInt(0, true); - - /** - * Unsigned zero. - * @type {!Long} - */ - Long.UZERO = UZERO; - - /** - * @type {!Long} - * @inner - */ - var ONE = fromInt(1); - - /** - * Signed one. - * @type {!Long} - */ - Long.ONE = ONE; - - /** - * @type {!Long} - * @inner - */ - var UONE = fromInt(1, true); - - /** - * Unsigned one. - * @type {!Long} - */ - Long.UONE = UONE; - - /** - * @type {!Long} - * @inner - */ - var NEG_ONE = fromInt(-1); - - /** - * Signed negative one. - * @type {!Long} - */ - Long.NEG_ONE = NEG_ONE; - - /** - * @type {!Long} - * @inner - */ - var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false); - - /** - * Maximum signed value. - * @type {!Long} - */ - Long.MAX_VALUE = MAX_VALUE; - - /** - * @type {!Long} - * @inner - */ - var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true); - - /** - * Maximum unsigned value. - * @type {!Long} - */ - Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; - - /** - * @type {!Long} - * @inner - */ - var MIN_VALUE = fromBits(0, 0x80000000|0, false); - - /** - * Minimum signed value. - * @type {!Long} - */ - Long.MIN_VALUE = MIN_VALUE; - - /** - * @alias Long.prototype - * @inner - */ - var LongPrototype = Long.prototype; - - /** - * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. - * @returns {number} - */ - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; - - /** - * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). - * @returns {number} - */ - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - - /** - * Converts the Long to a string written in the specified radix. - * @param {number=} radix Radix (2-36), defaults to 10 - * @returns {string} - * @override - * @throws {RangeError} If `radix` is out of range - */ - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { // Unsigned Longs are never negative - if (this.eq(MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = fromNumber(radix), - div = this.div(radixLong), - rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else - return '-' + this.neg().toString(radix); - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), - rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower), - intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, - digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) - return digits + result; - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } - } - }; - - /** - * Gets the high 32 bits as a signed integer. - * @returns {number} Signed high bits - */ - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; - - /** - * Gets the high 32 bits as an unsigned integer. - * @returns {number} Unsigned high bits - */ - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; - - /** - * Gets the low 32 bits as a signed integer. - * @returns {number} Signed low bits - */ - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; - - /** - * Gets the low 32 bits as an unsigned integer. - * @returns {number} Unsigned low bits - */ - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; - - /** - * Gets the number of bits needed to represent the absolute value of this Long. - * @returns {number} - */ - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) // Unsigned Longs are never negative - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) != 0) - break; - return this.high != 0 ? bit + 33 : bit + 1; - }; - - /** - * Tests if this Long's value equals zero. - * @returns {boolean} - */ - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; - - /** - * Tests if this Long's value is negative. - * @returns {boolean} - */ - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; - - /** - * Tests if this Long's value is positive. - * @returns {boolean} - */ - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; - - /** - * Tests if this Long's value is odd. - * @returns {boolean} - */ - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; - - /** - * Tests if this Long's value is even. - * @returns {boolean} - */ - LongPrototype.isEven = function isEven() { - return (this.low & 1) === 0; - }; - - /** - * Tests if this Long's value equals the specified's. - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.equals = function equals(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - - /** - * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. - * @function - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.eq = LongPrototype.equals; - - /** - * Tests if this Long's value differs from the specified's. - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.notEquals = function notEquals(other) { - return !this.eq(/* validates */ other); - }; - - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.neq = LongPrototype.notEquals; - - /** - * Tests if this Long's value is less than the specified's. - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThan = function lessThan(other) { - return this.comp(/* validates */ other) < 0; - }; - - /** - * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. - * @function - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.lt = LongPrototype.lessThan; - - /** - * Tests if this Long's value is less than or equal the specified's. - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(/* validates */ other) <= 0; - }; - - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.lte = LongPrototype.lessThanOrEqual; - - /** - * Tests if this Long's value is greater than the specified's. - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(/* validates */ other) > 0; - }; - - /** - * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. - * @function - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.gt = LongPrototype.greaterThan; - - /** - * Tests if this Long's value is greater than or equal the specified's. - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(/* validates */ other) >= 0; - }; - - /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|string} other Other value - * @returns {boolean} - */ - LongPrototype.gte = LongPrototype.greaterThanOrEqual; - - /** - * Compares this Long's value with the specified's. - * @param {!Long|number|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - */ - LongPrototype.compare = function compare(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), - otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1; - }; - - /** - * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. - * @function - * @param {!Long|number|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - */ - LongPrototype.comp = LongPrototype.compare; - - /** - * Negates this Long's value. - * @returns {!Long} Negated Long - */ - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) - return MIN_VALUE; - return this.not().add(ONE); - }; - - /** - * Negates this Long's value. This is an alias of {@link Long#negate}. - * @function - * @returns {!Long} Negated Long - */ - LongPrototype.neg = LongPrototype.negate; - - /** - * Returns the sum of this and the specified Long. - * @param {!Long|number|string} addend Addend - * @returns {!Long} Sum - */ - LongPrototype.add = function add(addend) { - if (!isLong(addend)) - addend = fromValue(addend); - - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xFFFF; - var a16 = this.low >>> 16; - var a00 = this.low & 0xFFFF; - - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xFFFF; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - - /** - * Returns the difference of this and the specified Long. - * @param {!Long|number|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) - subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - - /** - * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. - * @function - * @param {!Long|number|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.sub = LongPrototype.subtract; - - /** - * Returns the product of this and the specified Long. - * @param {!Long|number|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.multiply = function multiply(multiplier) { - if (this.isZero()) - return ZERO; - if (!isLong(multiplier)) - multiplier = fromValue(multiplier); - if (multiplier.isZero()) - return ZERO; - if (this.eq(MIN_VALUE)) - return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) - return this.isOdd() ? MIN_VALUE : ZERO; - - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - - // If both longs are small, use float multiplication - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xFFFF; - var a16 = this.low >>> 16; - var a00 = this.low & 0xFFFF; - - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xFFFF; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - - /** - * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. - * @function - * @param {!Long|number|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.mul = LongPrototype.multiply; - - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or - * unsigned if this Long is unsigned. - * @param {!Long|number|string} divisor Divisor - * @returns {!Long} Quotient - */ - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - if (this.isZero()) - return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(MIN_VALUE)) - return ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) - return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return UZERO; - if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true - return UONE; - res = UZERO; - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2), - delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48), - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - approxRes = fromNumber(approx), - approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = ONE; - - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - - /** - * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. - * @function - * @param {!Long|number|string} divisor Divisor - * @returns {!Long} Quotient - */ - LongPrototype.div = LongPrototype.divide; - - /** - * Returns this Long modulo the specified. - * @param {!Long|number|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - return this.sub(this.div(divisor).mul(divisor)); - }; - - /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.mod = LongPrototype.modulo; - - /** - * Returns the bitwise NOT of this Long. - * @returns {!Long} - */ - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; - - /** - * Returns the bitwise AND of this Long and the specified. - * @param {!Long|number|string} other Other Long - * @returns {!Long} - */ - LongPrototype.and = function and(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - - /** - * Returns the bitwise OR of this Long and the specified. - * @param {!Long|number|string} other Other Long - * @returns {!Long} - */ - LongPrototype.or = function or(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - - /** - * Returns the bitwise XOR of this Long and the given one. - * @param {!Long|number|string} other Other Long - * @returns {!Long} - */ - LongPrototype.xor = function xor(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shl = LongPrototype.shiftLeft; - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); - }; - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr = LongPrototype.shiftRight; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } else if (numBits === 32) - return fromBits(high, 0, this.unsigned); - else - return fromBits(high >>> (numBits - 32), 0, this.unsigned); - } - }; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shru = LongPrototype.shiftRightUnsigned; - - /** - * Converts this Long to signed. - * @returns {!Long} Signed long - */ - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) - return this; - return fromBits(this.low, this.high, false); - }; - - /** - * Converts this Long to unsigned. - * @returns {!Long} Unsigned long - */ - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) - return this; - return fromBits(this.low, this.high, true); - }; - - /** - * Converts this Long to its byte representation. - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @returns {!Array.} Byte representation - */ - LongPrototype.toBytes = function(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - } - - /** - * Converts this Long to its little endian byte representation. - * @returns {!Array.} Little endian byte representation - */ - LongPrototype.toBytesLE = function() { - var hi = this.high, - lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - (lo >>> 24) & 0xff, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - (hi >>> 24) & 0xff - ]; - } - - /** - * Converts this Long to its big endian byte representation. - * @returns {!Array.} Big endian byte representation - */ - LongPrototype.toBytesBE = function() { - var hi = this.high, - lo = this.low; - return [ - (hi >>> 24) & 0xff, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - (lo >>> 24) & 0xff, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff - ]; - } - - return Long; -}); - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const path = __webpack_require__(20); -const fs = __webpack_require__(26); -const snekfetch = __webpack_require__(31); - -const Constants = __webpack_require__(0); -const convertToBuffer = __webpack_require__(4).convertToBuffer; -const User = __webpack_require__(14); -const Message = __webpack_require__(22); -const Guild = __webpack_require__(29); -const Channel = __webpack_require__(17); -const GuildMember = __webpack_require__(24); -const Emoji = __webpack_require__(23); -const ReactionEmoji = __webpack_require__(38); - -/** - * The DataResolver identifies different objects and tries to resolve a specific piece of information from them, e.g. - * extracting a User from a Message object. - * @private - */ -class ClientDataResolver { - /** - * @param {Client} client The client the resolver is for - */ - constructor(client) { - this.client = client; - } - - /** - * Data that resolves to give a User object. This can be: - * * A User object - * * A Snowflake - * * A Message object (resolves to the message author) - * * A Guild object (owner of the guild) - * * A GuildMember object - * @typedef {User|Snowflake|Message|Guild|GuildMember} UserResolvable - */ - - /** - * Resolves a UserResolvable to a User object. - * @param {UserResolvable} user The UserResolvable to identify - * @returns {?User} - */ - resolveUser(user) { - if (user instanceof User) return user; - if (typeof user === 'string') return this.client.users.get(user) || null; - if (user instanceof GuildMember) return user.user; - if (user instanceof Message) return user.author; - if (user instanceof Guild) return user.owner; - return null; - } - - /** - * Resolves a UserResolvable to a user ID string. - * @param {UserResolvable} user The UserResolvable to identify - * @returns {?Snowflake} - */ - resolveUserID(user) { - if (user instanceof User || user instanceof GuildMember) return user.id; - if (typeof user === 'string') return user || null; - if (user instanceof Message) return user.author.id; - if (user instanceof Guild) return user.ownerID; - return null; - } - - /** - * Data that resolves to give a Guild object. This can be: - * * A Guild object - * * A Snowflake - * @typedef {Guild|Snowflake} GuildResolvable - */ - - /** - * Resolves a GuildResolvable to a Guild object. - * @param {GuildResolvable} guild The GuildResolvable to identify - * @returns {?Guild} - */ - resolveGuild(guild) { - if (guild instanceof Guild) return guild; - if (typeof guild === 'string') return this.client.guilds.get(guild) || null; - return null; - } - - /** - * Data that resolves to give a GuildMember object. This can be: - * * A GuildMember object - * * A User object - * @typedef {GuildMember|User} GuildMemberResolvable - */ - - /** - * Resolves a GuildMemberResolvable to a GuildMember object. - * @param {GuildResolvable} guild The guild that the member is part of - * @param {UserResolvable} user The user that is part of the guild - * @returns {?GuildMember} - */ - resolveGuildMember(guild, user) { - if (user instanceof GuildMember) return user; - guild = this.resolveGuild(guild); - user = this.resolveUser(user); - if (!guild || !user) return null; - return guild.members.get(user.id) || null; - } - - /** - * Data that can be resolved to give a Channel object. This can be: - * * A Channel object - * * A Message object (the channel the message was sent in) - * * A Guild object (the #general channel) - * * A Snowflake - * @typedef {Channel|Guild|Message|Snowflake} ChannelResolvable - */ - - /** - * Resolves a ChannelResolvable to a Channel object. - * @param {ChannelResolvable} channel The channel resolvable to resolve - * @returns {?Channel} - */ - resolveChannel(channel) { - if (channel instanceof Channel) return channel; - if (typeof channel === 'string') return this.client.channels.get(channel) || null; - if (channel instanceof Message) return channel.channel; - if (channel instanceof Guild) return channel.channels.get(channel.id) || null; - return null; - } - - /** - * Resolves a ChannelResolvable to a channel ID. - * @param {ChannelResolvable} channel The channel resolvable to resolve - * @returns {?Snowflake} - */ - resolveChannelID(channel) { - if (channel instanceof Channel) return channel.id; - if (typeof channel === 'string') return channel; - if (channel instanceof Message) return channel.channel.id; - if (channel instanceof Guild) return channel.defaultChannel.id; - return null; - } - - /** - * Data that can be resolved to give an invite code. This can be: - * * An invite code - * * An invite URL - * @typedef {string} InviteResolvable - */ - - /** - * Resolves InviteResolvable to an invite code. - * @param {InviteResolvable} data The invite resolvable to resolve - * @returns {string} - */ - resolveInviteCode(data) { - const inviteRegex = /discord(?:app\.com\/invite|\.gg)\/([\w-]{2,255})/i; - const match = inviteRegex.exec(data); - if (match && match[1]) return match[1]; - return data; - } - - /** - * Data that can be resolved to give a string. This can be: - * * A string - * * An array (joined with a new line delimiter to give a string) - * * Any value - * @typedef {string|Array|*} StringResolvable - */ - - /** - * Resolves a StringResolvable to a string. - * @param {StringResolvable} data The string resolvable to resolve - * @returns {string} - */ - resolveString(data) { - if (typeof data === 'string') return data; - if (data instanceof Array) return data.join('\n'); - return String(data); - } - - - /** - * Resolves a Base64Resolvable, a string, or a BufferResolvable to a Base 64 image. - * @param {BufferResolvable|Base64Resolvable} image The image to be resolved - * @returns {Promise} - */ - resolveImage(image) { - if (!image) return Promise.resolve(null); - if (typeof image === 'string' && image.startsWith('data:')) { - return Promise.resolve(image); - } - return this.resolveFile(image).then(this.resolveBase64); - } - - /** - * Data that resolves to give a Base64 string, typically for image uploading. This can be: - * * A Buffer - * * A base64 string - * @typedef {Buffer|string} Base64Resolvable - */ - - /** - * Resolves a Base64Resolvable to a Base 64 image. - * @param {Base64Resolvable} data The base 64 resolvable you want to resolve - * @returns {?string} - */ - resolveBase64(data) { - if (data instanceof Buffer) return `data:image/jpg;base64,${data.toString('base64')}`; - return data; - } - - /** - * Data that can be resolved to give a Buffer. This can be: - * * A Buffer - * * The path to a local file - * * A URL - * * A Stream - * @typedef {string|Buffer} BufferResolvable - */ - - /** - * @external Stream - * @see {@link https://nodejs.org/api/stream.html} - */ - - /** - * Resolves a BufferResolvable to a Buffer. - * @param {BufferResolvable|Stream} resource The buffer or stream resolvable to resolve - * @returns {Promise} - */ - resolveFile(resource) { - if (resource instanceof Buffer) return Promise.resolve(resource); - if (this.client.browser && resource instanceof ArrayBuffer) return Promise.resolve(convertToBuffer(resource)); - - if (typeof resource === 'string') { - return new Promise((resolve, reject) => { - if (/^https?:\/\//.test(resource)) { - snekfetch.get(resource) - .end((err, res) => { - if (err) return reject(err); - if (!(res.body instanceof Buffer)) return reject(new TypeError('The response body isn\'t a Buffer.')); - return resolve(res.body); - }); - } else { - const file = path.resolve(resource); - fs.stat(file, (err, stats) => { - if (err) return reject(err); - if (!stats || !stats.isFile()) return reject(new Error(`The file could not be found: ${file}`)); - fs.readFile(file, (err2, data) => { - if (err2) reject(err2); else resolve(data); - }); - return null; - }); - } - }); - } else if (resource.pipe && typeof resource.pipe === 'function') { - return new Promise((resolve, reject) => { - const buffers = []; - resource.once('error', reject); - resource.on('data', data => buffers.push(data)); - resource.once('end', () => resolve(Buffer.concat(buffers))); - }); - } - - return Promise.reject(new TypeError('The resource must be a string or Buffer.')); - } - - /** - * Data that can be resolved to give an emoji identifier. This can be: - * * The unicode representation of an emoji - * * A custom emoji ID - * * An Emoji object - * * A ReactionEmoji object - * @typedef {string|Emoji|ReactionEmoji} EmojiIdentifierResolvable - */ - - /** - * Resolves an EmojiResolvable to an emoji identifier. - * @param {EmojiIdentifierResolvable} emoji The emoji resolvable to resolve - * @returns {?string} - */ - resolveEmojiIdentifier(emoji) { - if (emoji instanceof Emoji || emoji instanceof ReactionEmoji) return emoji.identifier; - if (typeof emoji === 'string') { - if (this.client.emojis.has(emoji)) return this.client.emojis.get(emoji).identifier; - else if (!emoji.includes('%')) return encodeURIComponent(emoji); - else return emoji; - } - return null; - } - - /** - * Can be a Hex Literal, Hex String, Number, RGB Array, or one of the following - * ``` - * [ - * 'DEFAULT', - * 'AQUA', - * 'GREEN', - * 'BLUE', - * 'PURPLE', - * 'GOLD', - * 'ORANGE', - * 'RED', - * 'GREY', - * 'DARKER_GREY', - * 'NAVY', - * 'DARK_AQUA', - * 'DARK_GREEN', - * 'DARK_BLUE', - * 'DARK_PURPLE', - * 'DARK_GOLD', - * 'DARK_ORANGE', - * 'DARK_RED', - * 'DARK_GREY', - * 'LIGHT_GREY', - * 'DARK_NAVY', - * 'RANDOM', - * ] - * ``` - * or something like - * ``` - * [255, 0, 255] - * ``` - * for purple - * @typedef {string|number|Array} ColorResolvable - */ - - /** - * Resolves a ColorResolvable into a color number. - * @param {ColorResolvable} color Color to resolve - * @returns {number} A color - */ - static resolveColor(color) { - if (typeof color === 'string') { - if (color === 'RANDOM') return Math.floor(Math.random() * (0xFFFFFF + 1)); - color = Constants.Colors[color] || parseInt(color.replace('#', ''), 16); - } else if (color instanceof Array) { - color = (color[0] << 16) + (color[1] << 8) + color[2]; - } - - if (color < 0 || color > 0xFFFFFF) { - throw new RangeError('Color must be within the range 0 - 16777215 (0xFFFFFF).'); - } else if (color && isNaN(color)) { - throw new TypeError('Unable to convert color to a number.'); - } - - return color; - } - - /** - * @param {ColorResolvable} color Color to resolve - * @returns {number} A color - */ - resolveColor(color) { - return this.constructor.resolveColor(color); - } -} - -module.exports = ClientDataResolver; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - -/** - * Represents a limited emoji set used for both custom and unicode emojis. Custom emojis - * will use this class opposed to the Emoji class when the client doesn't know enough - * information about them. - */ -class ReactionEmoji { - constructor(reaction, name, id) { - /** - * The message reaction this emoji refers to - * @type {MessageReaction} - */ - this.reaction = reaction; - - /** - * The name of this reaction emoji - * @type {string} - */ - this.name = name; - - /** - * The ID of this reaction emoji - * @type {?Snowflake} - */ - this.id = id; - } - - /** - * The identifier of this emoji, used for message reactions - * @type {string} - * @readonly - */ - get identifier() { - if (this.id) return `${this.name}:${this.id}`; - return encodeURIComponent(this.name); - } - - /** - * Creates the text required to form a graphical emoji on Discord. - * @example - * // Send the emoji used in a reaction to the channel the reaction is part of - * reaction.message.channel.send(`The emoji used is ${reaction.emoji}`); - * @returns {string} - */ - toString() { - return this.id ? `<:${this.name}:${this.id}>` : this.name; - } -} - -module.exports = ReactionEmoji; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -const Collection = __webpack_require__(3); -const EventEmitter = __webpack_require__(9).EventEmitter; - -/** - * Filter to be applied to the collector. - * @typedef {Function} CollectorFilter - * @param {...*} args Any arguments received by the listener - * @param {Collection} collection The items collected by this collector - * @returns {boolean} - */ - -/** - * Options to be applied to the collector. - * @typedef {Object} CollectorOptions - * @property {number} [time] How long to run the collector for - */ - -/** - * Abstract class for defining a new Collector. - * @abstract - */ -class Collector extends EventEmitter { - constructor(client, filter, options = {}) { - super(); - - /** - * The client - * @name Collector#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - /** - * The filter applied to this collector - * @type {CollectorFilter} - */ - this.filter = filter; - - /** - * The options of this collector - * @type {CollectorOptions} - */ - this.options = options; - - /** - * The items collected by this collector - * @type {Collection} - */ - this.collected = new Collection(); - - /** - * Whether this collector has finished collecting - * @type {boolean} - */ - this.ended = false; - - /** - * Timeout for cleanup - * @type {?Timeout} - * @private - */ - this._timeout = null; - - /** - * Call this to handle an event as a collectable element - * Accepts any event data as parameters - * @type {Function} - * @private - */ - this.listener = this._handle.bind(this); - if (options.time) this._timeout = this.client.setTimeout(() => this.stop('time'), options.time); - } - - /** - * @param {...*} args The arguments emitted by the listener - * @emits Collector#collect - * @private - */ - _handle(...args) { - const collect = this.handle(...args); - if (!collect || !this.filter(...args, this.collected)) return; - - this.collected.set(collect.key, collect.value); - - /** - * Emitted whenever an element is collected. - * @event Collector#collect - * @param {*} element The element that got collected - * @param {Collector} collector The collector - */ - this.emit('collect', collect.value, this); - - const post = this.postCheck(...args); - if (post) this.stop(post); - } - - /** - * Return a promise that resolves with the next collected element; - * rejects with collected elements if the collector finishes without receving a next element - * @type {Promise} - * @readonly - */ - get next() { - return new Promise((resolve, reject) => { - if (this.ended) { - reject(this.collected); - return; - } - - const cleanup = () => { - this.removeListener('collect', onCollect); - this.removeListener('end', onEnd); - }; - - const onCollect = item => { - cleanup(); - resolve(item); - }; - - const onEnd = () => { - cleanup(); - reject(this.collected); // eslint-disable-line prefer-promise-reject-errors - }; - - this.on('collect', onCollect); - this.on('end', onEnd); - }); - } - - /** - * Stop this collector and emit the `end` event. - * @param {string} [reason='user'] The reason this collector is ending - * @emits Collector#end - */ - stop(reason = 'user') { - if (this.ended) return; - - if (this._timeout) this.client.clearTimeout(this._timeout); - this.ended = true; - this.cleanup(); - - /** - * Emitted when the collector is finished collecting. - * @event Collector#end - * @param {Collection} collected The elements collected by the collector - * @param {string} reason The reason the collector ended - */ - this.emit('end', this.collected, reason); - } - - /* eslint-disable no-empty-function, valid-jsdoc */ - /** - * Handles incoming events from the `listener` function. Returns null if the event should not be collected, - * or returns an object describing the data that should be stored. - * @see Collector#listener - * @param {...*} args Any args the event listener emits - * @returns {?{key: string, value}} Data to insert into collection, if any - * @abstract - */ - handle() {} - - /** - * This method runs after collection to see if the collector should finish. - * @param {...*} args Any args the event listener emits - * @returns {?string} Reason to end the collector, if any - * @abstract - */ - postCheck() {} - - /** - * Called when the collector is ending. - * @abstract - */ - cleanup() {} - /* eslint-enable no-empty-function, valid-jsdoc */ -} - -module.exports = Collector; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const path = __webpack_require__(20); -const Util = __webpack_require__(4); -const Attachment = __webpack_require__(28); -const RichEmbed = __webpack_require__(27); - -/** - * Represents a webhook. - */ -class Webhook { - constructor(client, dataOrID, token) { - if (client) { - /** - * The client that instantiated the webhook - * @name Webhook#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - if (dataOrID) this.setup(dataOrID); - } else { - this.id = dataOrID; - this.token = token; - Object.defineProperty(this, 'client', { value: this }); - } - } - - setup(data) { - /** - * The name of the webhook - * @type {string} - */ - this.name = data.name; - - /** - * The token for the webhook - * @type {string} - */ - this.token = data.token; - - /** - * The avatar for the webhook - * @type {?string} - */ - this.avatar = data.avatar; - - /** - * The ID of the webhook - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The guild the webhook belongs to - * @type {Snowflake} - */ - this.guildID = data.guild_id; - - /** - * The channel the webhook belongs to - * @type {Snowflake} - */ - this.channelID = data.channel_id; - - if (data.user) { - /** - * The owner of the webhook - * @type {?User|Object} - */ - this.owner = this.client.users ? this.client.users.get(data.user.id) : data.user; - } else { - this.owner = null; - } - } - - /** - * Options that can be passed into send, sendMessage, sendFile, sendEmbed, and sendCode. - * @typedef {Object} WebhookMessageOptions - * @property {string} [username=this.name] Username override for the message - * @property {string} [avatarURL] Avatar URL override for the message - * @property {boolean} [tts=false] Whether or not the message should be spoken aloud - * @property {string} [nonce=''] The nonce for the message - * @property {Array} [embeds] An array of embeds for the message - * (see [here](https://discordapp.com/developers/docs/resources/channel#embed-object) for more details) - * @property {boolean} [disableEveryone=this.client.options.disableEveryone] Whether or not @everyone and @here - * should be replaced with plain-text - * @property {FileOptions|BufferResolvable|Attachment} [file] A file to send with the message **(deprecated)** - * @property {FileOptions[]|BufferResolvable[]|Attachment[]} [files] Files to send with the message - * @property {string|boolean} [code] Language for optional codeblock formatting to apply - * @property {boolean|SplitOptions} [split=false] Whether or not the message should be split into multiple messages if - * it exceeds the character limit. If an object is provided, these are the options for splitting the message. - */ - - /** - * Send a message with this webhook. - * @param {StringResolvable} content The content to send - * @param {WebhookMessageOptions|Attachment|RichEmbed} [options] The options to provide - * can also be just a RichEmbed or Attachment - * @returns {Promise} - * @example - * // Send a message - * webhook.send('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - send(content, options) { // eslint-disable-line complexity - if (!options && typeof content === 'object' && !(content instanceof Array)) { - options = content; - content = ''; - } else if (!options) { - options = {}; - } - - if (options instanceof Attachment) options = { files: [options] }; - if (options instanceof RichEmbed) options = { embeds: [options] }; - - if (content) { - content = this.client.resolver.resolveString(content); - let { split, code, disableEveryone } = options; - if (split && typeof split !== 'object') split = {}; - if (typeof code !== 'undefined' && (typeof code !== 'boolean' || code === true)) { - content = Util.escapeMarkdown(content, true); - content = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n${content}\n\`\`\``; - if (split) { - split.prepend = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n`; - split.append = '\n```'; - } - } - if (disableEveryone || (typeof disableEveryone === 'undefined' && this.client.options.disableEveryone)) { - content = content.replace(/@(everyone|here)/g, '@\u200b$1'); - } - - if (split) content = Util.splitMessage(content, split); - } - - if (options.file) { - if (options.files) options.files.push(options.file); - else options.files = [options.file]; - } - - if (options.embeds) { - const files = []; - for (const embed of options.embeds) { - if (embed.file) files.push(embed.file); - } - if (options.files) options.files.push(...files); - else options.files = files; - } - - if (options.files) { - for (let i = 0; i < options.files.length; i++) { - let file = options.files[i]; - if (typeof file === 'string' || Buffer.isBuffer(file)) file = { attachment: file }; - if (!file.name) { - if (typeof file.attachment === 'string') { - file.name = path.basename(file.attachment); - } else if (file.attachment && file.attachment.path) { - file.name = path.basename(file.attachment.path); - } else if (file instanceof Attachment) { - file = { attachment: file.file, name: path.basename(file.file) || 'file.jpg' }; - } else { - file.name = 'file.jpg'; - } - } else if (file instanceof Attachment) { - file = file.file; - } - options.files[i] = file; - } - - return Promise.all(options.files.map(file => - this.client.resolver.resolveFile(file.attachment).then(resource => { - file.file = resource; - return file; - }) - )).then(files => this.client.rest.methods.sendWebhookMessage(this, content, options, files)); - } - - return this.client.rest.methods.sendWebhookMessage(this, content, options); - } - - /** - * Send a message with this webhook - * @param {StringResolvable} content The content to send - * @param {WebhookMessageOptions} [options={}] The options to provide - * @returns {Promise} - * @deprecated - * @example - * // Send a message - * webhook.sendMessage('hello!') - * .then(message => console.log(`Sent message: ${message.content}`)) - * .catch(console.error); - */ - sendMessage(content, options = {}) { - return this.send(content, options); - } - - /** - * Send a file with this webhook. - * @param {BufferResolvable} attachment The file to send - * @param {string} [name='file.jpg'] The name and extension of the file - * @param {StringResolvable} [content] Text message to send with the attachment - * @param {WebhookMessageOptions} [options] The options to provide - * @returns {Promise} - * @deprecated - */ - sendFile(attachment, name, content, options = {}) { - return this.send(content, Object.assign(options, { file: { attachment, name } })); - } - - /** - * Send a code block with this webhook. - * @param {string} lang Language for the code block - * @param {StringResolvable} content Content of the code block - * @param {WebhookMessageOptions} options The options to provide - * @returns {Promise} - * @deprecated - */ - sendCode(lang, content, options = {}) { - return this.send(content, Object.assign(options, { code: lang })); - } - - /** - * Send a raw slack message with this webhook. - * @param {Object} body The raw body to send - * @returns {Promise} - * @example - * // Send a slack message - * webhook.sendSlackMessage({ - * 'username': 'Wumpus', - * 'attachments': [{ - * 'pretext': 'this looks pretty cool', - * 'color': '#F0F', - * 'footer_icon': 'http://snek.s3.amazonaws.com/topSnek.png', - * 'footer': 'Powered by sneks', - * 'ts': Date.now() / 1000 - * }] - * }).catch(console.error); - */ - sendSlackMessage(body) { - return this.client.rest.methods.sendSlackWebhookMessage(this, body); - } - - /** - * Edit the webhook. - * @param {string} name The new name for the webhook - * @param {BufferResolvable} [avatar] The new avatar for the webhook - * @returns {Promise} - */ - edit(name = this.name, avatar) { - if (avatar) { - return this.client.resolver.resolveImage(avatar).then(data => - this.client.rest.methods.editWebhook(this, name, data) - ); - } - return this.client.rest.methods.editWebhook(this, name); - } - - /** - * Delete the webhook. - * @param {string} [reason] Reason for deleting the webhook - * @returns {Promise} - */ - delete(reason) { - return this.client.rest.methods.deleteWebhook(this, reason); - } -} - -module.exports = Webhook; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -const Snowflake = __webpack_require__(8); - -/** - * Represents an OAuth2 Application. - */ -class OAuth2Application { - constructor(client, data) { - /** - * The client that instantiated the application - * @name OAuth2Application#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The ID of the app - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The name of the app - * @type {string} - */ - this.name = data.name; - - /** - * The app's description - * @type {string} - */ - this.description = data.description; - - /** - * The app's icon hash - * @type {?string} - */ - this.icon = data.icon; - - /** - * The app's icon URL - * @type {string} - */ - this.iconURL = `https://cdn.discordapp.com/app-icons/${this.id}/${this.icon}.jpg`; - - /** - * The app's RPC origins - * @type {?string[]} - */ - this.rpcOrigins = data.rpc_origins; - - /** - * The app's redirect URIs - * @type {string[]} - */ - this.redirectURIs = data.redirect_uris; - - /** - * If this app's bot requires a code grant when using the OAuth2 flow - * @type {boolean} - */ - this.botRequireCodeGrant = data.bot_require_code_grant; - - /** - * If this app's bot is public - * @type {boolean} - */ - this.botPublic = data.bot_public; - - /** - * If this app can use rpc - * @type {boolean} - */ - this.rpcApplicationState = data.rpc_application_state; - - /** - * Object containing basic info about this app's bot - * @type {Object} - */ - this.bot = data.bot; - - /** - * The flags for the app - * @type {number} - */ - this.flags = data.flags; - - /** - * OAuth2 secret for the application - * @type {boolean} - */ - this.secret = data.secret; - - if (data.owner) { - /** - * The owner of this OAuth application - * @type {?User} - */ - this.owner = this.client.dataManager.newUser(data.owner); - } - } - - /** - * The timestamp the app was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time the app was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * Reset the app's secret and bot token. - * This is only available when using a user account. - * @returns {OAuth2Application} - */ - reset() { - return this.client.rest.methods.resetApplication(this.id); - } - - /** - * When concatenated with a string, this automatically concatenates the app name rather than the app object. - * @returns {string} - */ - toString() { - return this.name; - } -} - -module.exports = OAuth2Application; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -const Channel = __webpack_require__(17); -const TextBasedChannel = __webpack_require__(21); -const Collection = __webpack_require__(3); -const Constants = __webpack_require__(0); - -/* -{ type: 3, - recipients: - [ { username: 'Charlie', - id: '123', - discriminator: '6631', - avatar: '123' }, - { username: 'Ben', - id: '123', - discriminator: '2055', - avatar: '123' }, - { username: 'Adam', - id: '123', - discriminator: '2406', - avatar: '123' } ], - owner_id: '123', - name: null, - last_message_id: '123', - id: '123', - icon: null } -*/ - -/** - * Represents a Group DM on Discord. - * @extends {Channel} - * @implements {TextBasedChannel} - */ -class GroupDMChannel extends Channel { - constructor(client, data) { - super(client, data); - this.type = 'group'; - this.messages = new Collection(); - this._typing = new Map(); - } - - setup(data) { - super.setup(data); - - /** - * The name of this Group DM, can be null if one isn't set - * @type {string} - */ - this.name = data.name; - - /** - * A hash of this Group DM icon - * @type {?string} - */ - this.icon = data.icon; - - /** - * The user ID of this Group DM's owner - * @type {string} - */ - this.ownerID = data.owner_id; - - /** - * If the DM is managed by an application - * @type {boolean} - */ - this.managed = data.managed; - - /** - * Application ID of the application that made this Group DM, if applicable - * @type {?string} - */ - this.applicationID = data.application_id; - - if (data.nicks) { - /** - * Nicknames for group members - * @type {?Collection} - */ - this.nicks = new Collection(data.nicks.map(n => [n.id, n.nick])); - } - - if (!this.recipients) { - /** - * A collection of the recipients of this DM, mapped by their ID - * @type {Collection} - */ - this.recipients = new Collection(); - } - - if (data.recipients) { - for (const recipient of data.recipients) { - const user = this.client.dataManager.newUser(recipient); - this.recipients.set(user.id, user); - } - } - - this.lastMessageID = data.last_message_id; - } - - /** - * The owner of this Group DM - * @type {User} - * @readonly - */ - get owner() { - return this.client.users.get(this.ownerID); - } - - /** - * The URL to this guild's icon - * @type {?string} - * @readonly - */ - get iconURL() { - if (!this.icon) return null; - return Constants.Endpoints.Channel(this).Icon(this.client.options.http.cdn, this.icon); - } - - edit(data) { - const _data = {}; - if (data.name) _data.name = data.name; - if (typeof data.icon !== 'undefined') _data.icon = data.icon; - return this.client.rest.methods.updateGroupDMChannel(this, _data); - } - - /** - * Whether this channel equals another channel. It compares all properties, so for most operations - * it is advisable to just compare `channel.id === channel2.id` as it is much faster and is often - * what most users need. - * @param {GroupDMChannel} channel Channel to compare with - * @returns {boolean} - */ - equals(channel) { - const equal = channel && - this.id === channel.id && - this.name === channel.name && - this.icon === channel.icon && - this.ownerID === channel.ownerID; - - if (equal) { - return this.recipients.equals(channel.recipients); - } - - return equal; - } - - /** - * Add a user to the DM - * @param {UserResolvable|string} accessTokenOrID Access token or user resolvable - * @param {string} [nick] Permanent nickname to give the user (only available if a bot is creating the DM) - * @returns {Promise} - */ - - addUser(accessTokenOrID, nick) { - return this.client.rest.methods.addUserToGroupDM(this, { - nick, - id: this.client.resolver.resolveUserID(accessTokenOrID), - accessToken: accessTokenOrID, - }); - } - - /** - * Set a new GroupDMChannel icon. - * @param {Base64Resolvable|BufferResolvable} icon The new icon of the group dm - * @returns {Promise} - * @example - * // Edit the group dm icon - * channel.setIcon('./icon.png') - * .then(updated => console.log('Updated the channel icon')) - * .catch(console.error); - */ - setIcon(icon) { - return this.client.resolver.resolveImage(icon).then(data => this.edit({ icon: data })); - } - - /** - * Sets a new name for this Group DM. - * @param {string} name New name for this Group DM - * @returns {Promise} - */ - setName(name) { - return this.edit({ name }); - } - - /** - * Removes an user from this Group DM. - * @param {UserResolvable} user User to remove - * @returns {Promise} - */ - removeUser(user) { - const id = this.client.resolver.resolveUserID(user); - return this.client.rest.methods.removeUserFromGroupDM(this, id); - } - - /** - * When concatenated with a string, this automatically concatenates the channel's name instead of the Channel object. - * @returns {string} - * @example - * // Logs: Hello from My Group DM! - * console.log(`Hello from ${channel}!`); - * @example - * // Logs: Hello from My Group DM! - * console.log(`Hello from ' + channel + '!'); - */ - toString() { - return this.name; - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ - send() {} - sendMessage() {} - sendEmbed() {} - sendFile() {} - sendFiles() {} - sendCode() {} - fetchMessage() {} - fetchMessages() {} - fetchPinnedMessages() {} - search() {} - startTyping() {} - stopTyping() {} - get typing() {} - get typingCount() {} - createCollector() {} - createMessageCollector() {} - awaitMessages() {} - // Doesn't work on Group DMs; bulkDelete() {} - acknowledge() {} - _cacheMessage() {} -} - -TextBasedChannel.applyToClass(GroupDMChannel, true, ['bulkDelete']); - -module.exports = GroupDMChannel; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - -/** - * Represents an error from the Discord API. - * @extends Error - */ -class DiscordAPIError extends Error { - constructor(error) { - super(); - const flattened = this.constructor.flattenErrors(error.errors || error).join('\n'); - this.name = 'DiscordAPIError'; - this.message = error.message && flattened ? `${error.message}\n${flattened}` : error.message || flattened; - - /** - * HTTP error code returned by Discord - * @type {number} - */ - this.code = error.code; - } - - /** - * Flattens an errors object returned from the API into an array. - * @param {Object} obj Discord errors object - * @param {string} [key] Used internally to determine key names of nested fields - * @returns {string[]} - * @private - */ - static flattenErrors(obj, key = '') { - let messages = []; - - for (const k of Object.keys(obj)) { - if (k === 'message') continue; - const newKey = key ? isNaN(k) ? `${key}.${k}` : `${key}[${k}]` : k; - - if (obj[k]._errors) { - messages.push(`${newKey}: ${obj[k]._errors.map(e => e.message).join(' ')}`); - } else if (obj[k].code || obj[k].message) { - messages.push(`${obj[k].code ? `${obj[k].code}: ` : ''}: ${obj[k].message}`.trim()); - } else if (typeof obj[k] === 'string') { - messages.push(obj[k]); - } else { - messages = messages.concat(this.flattenErrors(obj[k], newKey)); - } - } - - return messages; - } -} - -module.exports = DiscordAPIError; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -/**/ - -var processNextTick = __webpack_require__(25); -/**/ - -module.exports = Readable; - -/**/ -var isArray = __webpack_require__(44); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = __webpack_require__(9).EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = __webpack_require__(46); -/**/ - -// TODO(bmeurer): Change this back to const once hole checks are -// properly optimized away early in Ignition+TurboFan. -/**/ -var Buffer = __webpack_require__(33).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - -/**/ -var util = __webpack_require__(19); -util.inherits = __webpack_require__(10); -/**/ - -/**/ -var debugUtil = __webpack_require__(79); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = __webpack_require__(80); -var destroyImpl = __webpack_require__(47); -var StringDecoder; - -util.inherits(Readable, Stream); - -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } -} - -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(12); - - options = options || {}; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(48).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || __webpack_require__(12); - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } - } - - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(48).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - - return ret; -}; - -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this, unpipeInfo); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); - } - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} - -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6), __webpack_require__(7))) - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(9).EventEmitter; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/**/ - -var processNextTick = __webpack_require__(25); -/**/ - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - processNextTick(emitErrorNT, this, err); - } - return; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - processNextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy -}; - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var Buffer = __webpack_require__(5).Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} - -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; - -var Duplex = __webpack_require__(12); - -/**/ -var util = __webpack_require__(19); -util.inherits = __webpack_require__(10); -/**/ - -util.inherits(Transform, Duplex); - -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) { - return stream.emit('error', new Error('write callback called multiple times')); - } - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) stream.push(data); - - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(this); - - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } - - // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this.emit('close'); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - - if (data !== null && data !== undefined) stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - - if (ts.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); -} - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var ClientRequest = __webpack_require__(91) -var extend = __webpack_require__(94) -var statusCodes = __webpack_require__(95) -var url = __webpack_require__(52) - -var http = exports - -http.request = function (opts, cb) { - if (typeof opts === 'string') - opts = url.parse(opts) - else - opts = extend(opts) - - // Normally, the page is loaded from http or https, so not specifying a protocol - // will result in a (valid) protocol-relative url. However, this won't work if - // the protocol is something else, like 'file:' - var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' - - var protocol = opts.protocol || defaultProtocol - var host = opts.hostname || opts.host - var port = opts.port - var path = opts.path || '/' - - // Necessary for IPv6 addresses - if (host && host.indexOf(':') !== -1) - host = '[' + host + ']' - - // This may be a relative url. The browser should always be able to interpret it correctly. - opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path - opts.method = (opts.method || 'GET').toUpperCase() - opts.headers = opts.headers || {} - - // Also valid opts.auth, opts.mode - - var req = new ClientRequest(opts) - if (cb) - req.on('response', cb) - return req -} - -http.get = function get (opts, cb) { - var req = http.request(opts, cb) - req.end() - return req -} - -http.Agent = function () {} -http.Agent.defaultMaxSockets = 4 - -http.STATUS_CODES = statusCodes - -http.METHODS = [ - 'CHECKOUT', - 'CONNECT', - 'COPY', - 'DELETE', - 'GET', - 'HEAD', - 'LOCK', - 'M-SEARCH', - 'MERGE', - 'MKACTIVITY', - 'MKCOL', - 'MOVE', - 'NOTIFY', - 'OPTIONS', - 'PATCH', - 'POST', - 'PROPFIND', - 'PROPPATCH', - 'PURGE', - 'PUT', - 'REPORT', - 'SEARCH', - 'SUBSCRIBE', - 'TRACE', - 'UNLOCK', - 'UNSUBSCRIBE' -] -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6))) - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) - -exports.blobConstructor = false -try { - new Blob([new ArrayBuffer(1)]) - exports.blobConstructor = true -} catch (e) {} - -// The xhr request to example.com may violate some restrictive CSP configurations, -// so if we're running in a browser that supports `fetch`, avoid calling getXHR() -// and assume support for certain features below. -var xhr -function getXHR () { - // Cache the xhr value - if (xhr !== undefined) return xhr - - if (global.XMLHttpRequest) { - xhr = new global.XMLHttpRequest() - // If XDomainRequest is available (ie only, where xhr might not work - // cross domain), use the page location. Otherwise use example.com - // Note: this doesn't actually make an http request. - try { - xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') - } catch(e) { - xhr = null - } - } else { - // Service workers don't have XHR - xhr = null - } - return xhr -} - -function checkTypeSupport (type) { - var xhr = getXHR() - if (!xhr) return false - try { - xhr.responseType = type - return xhr.responseType === type - } catch (e) {} - return false -} - -// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. -// Safari 7.1 appears to have fixed this bug. -var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' -var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) - -// If fetch is supported, then arraybuffer will be supported too. Skip calling -// checkTypeSupport(), since that calls getXHR(). -exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) - -// These next two tests unavoidably show warnings in Chrome. Since fetch will always -// be used if it's available, just return false for these to avoid the warnings. -exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') -exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && - checkTypeSupport('moz-chunked-arraybuffer') - -// If fetch is supported, then overrideMimeType will be supported too. Skip calling -// getXHR(). -exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) - -exports.vbArray = isFunction(global.VBArray) - -function isFunction (value) { - return typeof value === 'function' -} - -xhr = null // Help gc - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(6))) - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var punycode = __webpack_require__(96); -var util = __webpack_require__(98); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; - -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; -} - -// Reference: RFC 3986, RFC 1808, RFC 2396 - -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = __webpack_require__(35); - -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; -} - -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); - } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; - } - } - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - continue; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; - -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} - -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } - - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; -}; - -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} - -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; - -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); -} - -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; - } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - result[rkey] = relative[rkey]; - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; -}; - -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) this.hostname = host; -}; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - -const mimes = __webpack_require__(102); -const mimeOfBuffer = __webpack_require__(103); - -function lookupMime(ext) { - return mimes[ext.replace(/^\./, '')] || mimes.bin; -} - -function lookupBuffer(buffer) { - const ret = mimeOfBuffer(buffer) - return ret ? ret.mime : mimes.bin; -} - -module.exports = { - buffer: lookupBuffer, - lookup: lookupMime, -}; - - -/***/ }), -/* 54 */ -/***/ (function(module, exports) { - -module.exports = {"name":"discord.js","version":"11.2.0","description":"A powerful library for interacting with the Discord API","main":"./src/index","types":"./typings/index.d.ts","scripts":{"test":"npm run lint && npm run docs:test","docs":"docgen --source src --custom docs/index.yml --output docs/docs.json","docs:test":"docgen --source src --custom docs/index.yml","lint":"eslint src","lint:fix":"eslint --fix src","webpack":"parallel-webpack"},"repository":{"type":"git","url":"git+https://github.com/hydrabolt/discord.js.git"},"keywords":["discord","api","bot","client","node","discordapp"],"author":"Amish Shah ","license":"Apache-2.0","bugs":{"url":"https://github.com/hydrabolt/discord.js/issues"},"homepage":"https://github.com/hydrabolt/discord.js#readme","runkitExampleFilename":"./docs/examples/ping.js","dependencies":{"long":"^3.2.0","prism-media":"^0.0.1","snekfetch":"^3.2.0","tweetnacl":"^1.0.0","ws":"^3.0.0"},"peerDependencies":{"bufferutil":"^3.0.0","erlpack":"hammerandchisel/erlpack","node-opus":"^0.2.0","opusscript":"^0.0.3","sodium":"^2.0.0","libsodium-wrappers":"^0.5.0","uws":"^0.14.0"},"devDependencies":{"@types/node":"^7.0.0","discord.js-docgen":"hydrabolt/discord.js-docgen","eslint":"^4.0.0","parallel-webpack":"^2.0.0","uglifyjs-webpack-plugin":"^1.0.0-beta.1","webpack":"^3.0.0"},"engines":{"node":">=6.0.0"},"browser":{"ws":false,"uws":false,"erlpack":false,"prism-media":false,"opusscript":false,"node-opus":false,"tweetnacl":false,"sodium":false,"src/sharding/Shard.js":false,"src/sharding/ShardClientUtil.js":false,"src/sharding/ShardingManager.js":false,"src/client/voice/dispatcher/StreamDispatcher.js":false,"src/client/voice/opus/BaseOpusEngine.js":false,"src/client/voice/opus/NodeOpusEngine.js":false,"src/client/voice/opus/OpusEngineList.js":false,"src/client/voice/opus/OpusScriptEngine.js":false,"src/client/voice/pcm/ConverterEngine.js":false,"src/client/voice/pcm/ConverterEngineList.js":false,"src/client/voice/pcm/FfmpegConverterEngine.js":false,"src/client/voice/player/AudioPlayer.js":false,"src/client/voice/receiver/VoiceReadable.js":false,"src/client/voice/receiver/VoiceReceiver.js":false,"src/client/voice/util/Secretbox.js":false,"src/client/voice/util/SecretKey.js":false,"src/client/voice/util/VolumeInterface.js":false,"src/client/voice/ClientVoiceManager.js":false,"src/client/voice/VoiceBroadcast.js":false,"src/client/voice/VoiceConnection.js":false,"src/client/voice/VoiceUDPClient.js":false,"src/client/voice/VoiceWebSocket.js":false}} - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -const UserAgentManager = __webpack_require__(109); -const RESTMethods = __webpack_require__(110); -const SequentialRequestHandler = __webpack_require__(114); -const BurstRequestHandler = __webpack_require__(115); -const APIRequest = __webpack_require__(116); -const Constants = __webpack_require__(0); - -class RESTManager { - constructor(client) { - this.client = client; - this.handlers = {}; - this.userAgentManager = new UserAgentManager(this); - this.methods = new RESTMethods(this); - this.rateLimitedEndpoints = {}; - this.globallyRateLimited = false; - } - - destroy() { - for (const handlerID in this.handlers) { - this.handlers[handlerID].destroy(); - } - } - - push(handler, apiRequest) { - return new Promise((resolve, reject) => { - handler.push({ - request: apiRequest, - resolve, - reject, - }); - }); - } - - getRequestHandler() { - switch (this.client.options.apiRequestMethod) { - case 'sequential': - return SequentialRequestHandler; - case 'burst': - return BurstRequestHandler; - default: - throw new Error(Constants.Errors.INVALID_RATE_LIMIT_METHOD); - } - } - - makeRequest(method, url, auth, data, file, reason) { - const apiRequest = new APIRequest(this, method, url, auth, data, file, reason); - if (!this.handlers[apiRequest.route]) { - const RequestHandlerType = this.getRequestHandler(); - this.handlers[apiRequest.route] = new RequestHandlerType(this, apiRequest.route); - } - - return this.push(this.handlers[apiRequest.route], apiRequest); - } -} - -module.exports = RESTManager; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -const Collection = __webpack_require__(3); - -/** - * Keeps track of mentions in a {@link Message}. - */ -class MessageMentions { - constructor(message, users, roles, everyone) { - /** - * Whether `@everyone` or `@here` were mentioned - * @type {boolean} - */ - this.everyone = Boolean(everyone); - - if (users) { - if (users instanceof Collection) { - /** - * Any users that were mentioned - * @type {Collection} - */ - this.users = new Collection(users); - } else { - this.users = new Collection(); - for (const mention of users) { - let user = message.client.users.get(mention.id); - if (!user) user = message.client.dataManager.newUser(mention); - this.users.set(user.id, user); - } - } - } else { - this.users = new Collection(); - } - - if (roles) { - if (roles instanceof Collection) { - /** - * Any roles that were mentioned - * @type {Collection} - */ - this.roles = new Collection(roles); - } else { - this.roles = new Collection(); - for (const mention of roles) { - const role = message.channel.guild.roles.get(mention); - if (role) this.roles.set(role.id, role); - } - } - } else { - this.roles = new Collection(); - } - - /** - * Content of the message - * @type {Message} - * @private - */ - this._content = message.content; - - /** - * The client the message is from - * @type {Client} - * @private - */ - this._client = message.client; - - /** - * The guild the message is in - * @type {?Guild} - * @private - */ - this._guild = message.channel.guild; - - /** - * Cached members for {@MessageMention#members} - * @type {?Collection} - * @private - */ - this._members = null; - - /** - * Cached channels for {@MessageMention#channels} - * @type {?Collection} - * @private - */ - this._channels = null; - } - - /** - * Any members that were mentioned (only in {@link TextChannel}s) - * @type {?Collection} - * @readonly - */ - get members() { - if (this._members) return this._members; - if (!this._guild) return null; - this._members = new Collection(); - this.users.forEach(user => { - const member = this._guild.member(user); - if (member) this._members.set(member.user.id, member); - }); - return this._members; - } - - /** - * Any channels that were mentioned - * @type {Collection} - * @readonly - */ - get channels() { - if (this._channels) return this._channels; - this._channels = new Collection(); - let matches; - while ((matches = this.constructor.CHANNELS_PATTERN.exec(this._content)) !== null) { - const chan = this._client.channels.get(matches[1]); - if (chan) this._channels.set(chan.id, chan); - } - return this._channels; - } -} - -/** - * Regular expression that globally matches `@everyone` and `@here` - * @type {RegExp} - */ -MessageMentions.EVERYONE_PATTERN = /@(everyone|here)/g; - -/** - * Regular expression that globally matches user mentions like `<@81440962496172032>` - * @type {RegExp} - */ -MessageMentions.USERS_PATTERN = /<@!?[0-9]+>/g; - -/** - * Regular expression that globally matches role mentions like `<@&297577916114403338>` - * @type {RegExp} - */ -MessageMentions.ROLES_PATTERN = /<@&[0-9]+>/g; - -/** - * Regular expression that globally matches channel mentions like `<#222079895583457280>` - * @type {RegExp} - */ -MessageMentions.CHANNELS_PATTERN = /<#([0-9]+)>/g; - -module.exports = MessageMentions; - - -/***/ }), -/* 57 */ -/***/ (function(module, exports) { - -/** - * Represents an attachment in a message. - */ -class MessageAttachment { - constructor(message, data) { - /** - * The client that instantiated this MessageAttachment - * @name MessageAttachment#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: message.client }); - - /** - * The message this attachment is part of - * @type {Message} - */ - this.message = message; - - this.setup(data); - } - - setup(data) { - /** - * The ID of this attachment - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The file name of this attachment - * @type {string} - */ - this.filename = data.filename; - - /** - * The size of this attachment in bytes - * @type {number} - */ - this.filesize = data.size; - - /** - * The URL to this attachment - * @type {string} - */ - this.url = data.url; - - /** - * The Proxy URL to this attachment - * @type {string} - */ - this.proxyURL = data.proxy_url; - - /** - * The height of this attachment (if an image) - * @type {?number} - */ - this.height = data.height; - - /** - * The width of this attachment (if an image) - * @type {?number} - */ - this.width = data.width; - } -} - -module.exports = MessageAttachment; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports) { - -/** - * Represents an embed in a message (image/video preview, rich embed, etc.) - * This class is only used for *recieved* embeds. If you wish to send one, use the {@link RichEmbed} class. - */ -class MessageEmbed { - constructor(message, data) { - /** - * The client that instantiated this embed - * @name MessageEmbed#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: message.client }); - - /** - * The message this embed is part of - * @type {Message} - */ - this.message = message; - - this.setup(data); - } - - setup(data) { - /** - * The type of this embed - * @type {string} - */ - this.type = data.type; - - /** - * The title of this embed - * @type {?string} - */ - this.title = data.title; - - /** - * The description of this embed - * @type {?string} - */ - this.description = data.description; - - /** - * The URL of this embed - * @type {string} - */ - this.url = data.url; - - /** - * The color of the embed - * @type {number} - */ - this.color = data.color; - - /** - * The fields of this embed - * @type {MessageEmbedField[]} - */ - this.fields = []; - if (data.fields) for (const field of data.fields) this.fields.push(new MessageEmbedField(this, field)); - - /** - * The timestamp of this embed - * @type {number} - */ - this.createdTimestamp = data.timestamp; - - /** - * The thumbnail of this embed - * @type {?MessageEmbedThumbnail} - */ - this.thumbnail = data.thumbnail ? new MessageEmbedThumbnail(this, data.thumbnail) : null; - - /** - * The image of this embed - * @type {?MessageEmbedImage} - */ - this.image = data.image ? new MessageEmbedImage(this, data.image) : null; - - /** - * The video of this embed - * @type {?MessageEmbedVideo} - */ - this.video = data.video ? new MessageEmbedVideo(this, data.video) : null; - - /** - * The author of this embed - * @type {?MessageEmbedAuthor} - */ - this.author = data.author ? new MessageEmbedAuthor(this, data.author) : null; - - /** - * The provider of this embed - * @type {?MessageEmbedProvider} - */ - this.provider = data.provider ? new MessageEmbedProvider(this, data.provider) : null; - - /** - * The footer of this embed - * @type {?MessageEmbedFooter} - */ - this.footer = data.footer ? new MessageEmbedFooter(this, data.footer) : null; - } - - /** - * The date this embed was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The hexadecimal version of the embed color, with a leading hash - * @type {string} - * @readonly - */ - get hexColor() { - let col = this.color.toString(16); - while (col.length < 6) col = `0${col}`; - return `#${col}`; - } -} - -/** - * Represents a thumbnail for a message embed. - */ -class MessageEmbedThumbnail { - constructor(embed, data) { - /** - * The embed this thumbnail is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The URL for this thumbnail - * @type {string} - */ - this.url = data.url; - - /** - * The Proxy URL for this thumbnail - * @type {string} - */ - this.proxyURL = data.proxy_url; - - /** - * The height of the thumbnail - * @type {number} - */ - this.height = data.height; - - /** - * The width of the thumbnail - * @type {number} - */ - this.width = data.width; - } -} - -/** - * Represents an image for a message embed. - */ -class MessageEmbedImage { - constructor(embed, data) { - /** - * The embed this image is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The URL for this image - * @type {string} - */ - this.url = data.url; - - /** - * The Proxy URL for this image - * @type {string} - */ - this.proxyURL = data.proxy_url; - - /** - * The height of the image - * @type {number} - */ - this.height = data.height; - - /** - * The width of the image - * @type {number} - */ - this.width = data.width; - } -} - -/** - * Represents a video for a message embed. - */ -class MessageEmbedVideo { - constructor(embed, data) { - /** - * The embed this video is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The source URL for this video - * @type {string} - */ - this.url = data.url; - - /** - * The height of the video - * @type {number} - */ - this.height = data.height; - - /** - * The width of the video - * @type {number} - */ - this.width = data.width; - } -} - -/** - * Represents a provider for a message embed. - */ -class MessageEmbedProvider { - constructor(embed, data) { - /** - * The embed this provider is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The name of this provider - * @type {string} - */ - this.name = data.name; - - /** - * The URL of this provider - * @type {string} - */ - this.url = data.url; - } -} - -/** - * Represents an author for a message embed. - */ -class MessageEmbedAuthor { - constructor(embed, data) { - /** - * The embed this author is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The name of this author - * @type {string} - */ - this.name = data.name; - - /** - * The URL of this author - * @type {string} - */ - this.url = data.url; - - /** - * The icon URL of this author - * @type {string} - */ - this.iconURL = data.icon_url; - } -} - -/** - * Represents a field for a message embed. - */ -class MessageEmbedField { - constructor(embed, data) { - /** - * The embed this footer is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The name of this field - * @type {string} - */ - this.name = data.name; - - /** - * The value of this field - * @type {string} - */ - this.value = data.value; - - /** - * If this field is displayed inline - * @type {boolean} - */ - this.inline = data.inline; - } -} - -/** - * Represents the footer of a message embed. - */ -class MessageEmbedFooter { - constructor(embed, data) { - /** - * The embed this footer is part of - * @type {MessageEmbed} - */ - this.embed = embed; - - this.setup(data); - } - - setup(data) { - /** - * The text in this footer - * @type {string} - */ - this.text = data.text; - - /** - * The icon URL of this footer - * @type {string} - */ - this.iconURL = data.icon_url; - - /** - * The proxy icon URL of this footer - * @type {string} - */ - this.proxyIconUrl = data.proxy_icon_url; - } -} - -MessageEmbed.Thumbnail = MessageEmbedThumbnail; -MessageEmbed.Image = MessageEmbedImage; -MessageEmbed.Video = MessageEmbedVideo; -MessageEmbed.Provider = MessageEmbedProvider; -MessageEmbed.Author = MessageEmbedAuthor; -MessageEmbed.Field = MessageEmbedField; -MessageEmbed.Footer = MessageEmbedFooter; - -module.exports = MessageEmbed; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - -const Collection = __webpack_require__(3); -const Emoji = __webpack_require__(23); -const ReactionEmoji = __webpack_require__(38); - -/** - * Represents a reaction to a message. - */ -class MessageReaction { - constructor(message, emoji, count, me) { - /** - * The message that this reaction refers to - * @type {Message} - */ - this.message = message; - - /** - * Whether the client has given this reaction - * @type {boolean} - */ - this.me = me; - - /** - * The number of people that have given the same reaction - * @type {number} - */ - this.count = count || 0; - - /** - * The users that have given this reaction, mapped by their ID - * @type {Collection} - */ - this.users = new Collection(); - - this._emoji = new ReactionEmoji(this, emoji.name, emoji.id); - } - - /** - * The emoji of this reaction, either an Emoji object for known custom emojis, or a ReactionEmoji - * object which has fewer properties. Whatever the prototype of the emoji, it will still have - * `name`, `id`, `identifier` and `toString()` - * @type {Emoji|ReactionEmoji} - * @readonly - */ - get emoji() { - if (this._emoji instanceof Emoji) return this._emoji; - // Check to see if the emoji has become known to the client - if (this._emoji.id) { - const emojis = this.message.client.emojis; - if (emojis.has(this._emoji.id)) { - const emoji = emojis.get(this._emoji.id); - this._emoji = emoji; - return emoji; - } - } - return this._emoji; - } - - /** - * Removes a user from this reaction. - * @param {UserResolvable} [user=this.message.client.user] The user to remove the reaction of - * @returns {Promise} - */ - remove(user = this.message.client.user) { - const message = this.message; - const userID = this.message.client.resolver.resolveUserID(user); - if (!userID) return Promise.reject(new Error('Couldn\'t resolve the user ID to remove from the reaction.')); - return message.client.rest.methods.removeMessageReaction( - message, this.emoji.identifier, userID - ); - } - - /** - * Fetch all the users that gave this reaction. Resolves with a collection of users, mapped by their IDs. - * @param {number} [limit=100] The maximum amount of users to fetch, defaults to 100 - * @returns {Promise>} - */ - fetchUsers(limit = 100) { - const message = this.message; - return message.client.rest.methods.getMessageReactionUsers( - message, this.emoji.identifier, limit - ).then(users => { - this.users = new Collection(); - for (const rawUser of users) { - const user = this.message.client.dataManager.newUser(rawUser); - this.users.set(user.id, user); - } - this.count = this.users.size; - return this.users; - }); - } -} - -module.exports = MessageReaction; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - -const Collector = __webpack_require__(39); -const Collection = __webpack_require__(3); - -/** - * @typedef {CollectorOptions} ReactionCollectorOptions - * @property {number} max The maximum total amount of reactions to collect - * @property {number} maxEmojis The maximum number of emojis to collect - * @property {number} maxUsers The maximum number of users to react - */ - -/** - * Collects reactions on messages. - * @extends {Collector} - */ -class ReactionCollector extends Collector { - /** - * @param {Message} message The message upon which to collect reactions - * @param {CollectorFilter} filter The filter to apply to this collector - * @param {ReactionCollectorOptions} [options={}] The options to apply to this collector - */ - constructor(message, filter, options = {}) { - super(message.client, filter, options); - - /** - * The message - * @type {Message} - */ - this.message = message; - - /** - * The users which have reacted - * @type {Collection} - */ - this.users = new Collection(); - - /** - * The total number of reactions collected - * @type {number} - */ - this.total = 0; - - this.client.on('messageReactionAdd', this.listener); - } - - /** - * Handle an incoming reaction for possible collection. - * @param {MessageReaction} reaction The reaction to possibly collect - * @returns {?{key: Snowflake, value: MessageReaction}} - * @private - */ - handle(reaction) { - if (reaction.message.id !== this.message.id) return null; - return { - key: reaction.emoji.id || reaction.emoji.name, - value: reaction, - }; - } - - /** - * Check after collection to see if the collector is done. - * @param {MessageReaction} reaction The reaction that was collected - * @param {User} user The user that reacted - * @returns {?string} Reason to end the collector, if any - * @private - */ - postCheck(reaction, user) { - this.users.set(user.id, user); - if (this.options.max && ++this.total >= this.options.max) return 'limit'; - if (this.options.maxEmojis && this.collected.size >= this.options.maxEmojis) return 'emojiLimit'; - if (this.options.maxUsers && this.users.size >= this.options.maxUsers) return 'userLimit'; - return null; - } - - /** - * Remove event listeners. - * @private - */ - cleanup() { - this.client.removeListener('messageReactionAdd', this.listener); - } -} - -module.exports = ReactionCollector; - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - -const Collector = __webpack_require__(39); -const util = __webpack_require__(13); - -/** - * @typedef {CollectorOptions} MessageCollectorOptions - * @property {number} max The maximum amount of messages to process - * @property {number} maxMatches The maximum amount of messages to collect - */ - -/** - * Collects messages on a channel. - * @extends {Collector} - */ -class MessageCollector extends Collector { - /** - * @param {TextChannel|DMChannel|GroupDMChannel} channel The channel - * @param {CollectorFilter} filter The filter to be applied to this collector - * @param {MessageCollectorOptions} options The options to be applied to this collector - * @emits MessageCollector#message - */ - constructor(channel, filter, options = {}) { - super(channel.client, filter, options); - - /** - * The channel - * @type {TextBasedChannel} - */ - this.channel = channel; - - /** - * Total number of messages that were received in the channel during message collection - * @type {number} - */ - this.received = 0; - - this.client.on('message', this.listener); - - // For backwards compatibility (remove in v12) - if (this.options.max) this.options.maxProcessed = this.options.max; - if (this.options.maxMatches) this.options.max = this.options.maxMatches; - this._reEmitter = message => { - /** - * Emitted when the collector receives a message. - * @event MessageCollector#message - * @param {Message} message The message - * @deprecated - */ - this.emit('message', message); - }; - this.on('collect', this._reEmitter); - } - - // Remove in v12 - on(eventName, listener) { - if (eventName === 'message') { - listener = util.deprecate(listener, 'MessageCollector will soon no longer emit "message", use "collect" instead'); - } - super.on(eventName, listener); - } - - /** - * Handle an incoming message for possible collection. - * @param {Message} message The message that could be collected - * @returns {?{key: Snowflake, value: Message}} - * @private - */ - handle(message) { - if (message.channel.id !== this.channel.id) return null; - this.received++; - return { - key: message.id, - value: message, - }; - } - - /** - * Check after collection to see if the collector is done. - * @returns {?string} Reason to end the collector, if any - * @private - */ - postCheck() { - // Consider changing the end reasons for v12 - if (this.options.maxMatches && this.collected.size >= this.options.max) return 'matchesLimit'; - if (this.options.max && this.received >= this.options.maxProcessed) return 'limit'; - return null; - } - - /** - * Removes event listeners. - * @private - */ - cleanup() { - this.removeListener('collect', this._reEmitter); - this.client.removeListener('message', this.listener); - } -} - -module.exports = MessageCollector; - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -const PartialGuild = __webpack_require__(63); -const PartialGuildChannel = __webpack_require__(64); -const Constants = __webpack_require__(0); - -/** - * Represents an invitation to a guild channel. - * The only guaranteed properties are `code`, `guild` and `channel`. Other properties can be missing. - */ -class Invite { - constructor(client, data) { - /** - * The client that instantiated the invite - * @name Invite#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The guild the invite is for. If this guild is already known, this will be a guild object. If the guild is - * unknown, this will be a PartialGuild object - * @type {Guild|PartialGuild} - */ - this.guild = this.client.guilds.get(data.guild.id) || new PartialGuild(this.client, data.guild); - - /** - * The code for this invite - * @type {string} - */ - this.code = data.code; - - /** - * The approximate number of online members of the guild this invite is for - * @type {number} - */ - this.presenceCount = data.approximate_presence_count; - - /** - * The approximate total number of members of the guild this invite is for - * @type {number} - */ - this.memberCount = data.approximate_member_count; - - /** - * The number of text channels the guild this invite goes to has - * @type {number} - */ - this.textChannelCount = data.guild.text_channel_count; - - /** - * The number of voice channels the guild this invite goes to has - * @type {number} - */ - this.voiceChannelCount = data.guild.voice_channel_count; - - /** - * Whether or not this invite is temporary - * @type {boolean} - */ - this.temporary = data.temporary; - - /** - * The maximum age of the invite, in seconds - * @type {?number} - */ - this.maxAge = data.max_age; - - /** - * How many times this invite has been used - * @type {number} - */ - this.uses = data.uses; - - /** - * The maximum uses of this invite - * @type {number} - */ - this.maxUses = data.max_uses; - - if (data.inviter) { - /** - * The user who created this invite - * @type {User} - */ - this.inviter = this.client.dataManager.newUser(data.inviter); - } - - /** - * The channel the invite is for. If this channel is already known, this will be a GuildChannel object. - * If the channel is unknown, this will be a PartialGuildChannel object. - * @type {GuildChannel|PartialGuildChannel} - */ - this.channel = this.client.channels.get(data.channel.id) || new PartialGuildChannel(this.client, data.channel); - - /** - * The timestamp the invite was created at - * @type {number} - */ - this.createdTimestamp = new Date(data.created_at).getTime(); - } - - /** - * The time the invite was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } - - /** - * The timestamp the invite will expire at - * @type {number} - * @readonly - */ - get expiresTimestamp() { - return this.createdTimestamp + (this.maxAge * 1000); - } - - /** - * The time the invite will expire - * @type {Date} - * @readonly - */ - get expiresAt() { - return new Date(this.expiresTimestamp); - } - - /** - * The URL to the invite - * @type {string} - * @readonly - */ - get url() { - return Constants.Endpoints.inviteLink(this.code); - } - - /** - * Deletes this invite. - * @param {string} [reason] Reason for deleting this invite - * @returns {Promise} - */ - delete(reason) { - return this.client.rest.methods.deleteInvite(this, reason); - } - - /** - * When concatenated with a string, this automatically concatenates the invite's URL instead of the object. - * @returns {string} - * @example - * // Logs: Invite: https://discord.gg/A1b2C3 - * console.log(`Invite: ${invite}`); - */ - toString() { - return this.url; - } -} - -module.exports = Invite; - - -/***/ }), -/* 63 */ -/***/ (function(module, exports) { - -/* -{ splash: null, - id: '123123123', - icon: '123123123', - name: 'name' } -*/ - -/** - * Represents a guild that the client only has limited information for - e.g. from invites. - */ -class PartialGuild { - constructor(client, data) { - /** - * The client that instantiated this PartialGuild - * @name PartialGuild#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The ID of this guild - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The name of this guild - * @type {string} - */ - this.name = data.name; - - /** - * The hash of this guild's icon - * @type {?string} - */ - this.icon = data.icon; - - /** - * The hash of the guild splash image (VIP only) - * @type {?string} - */ - this.splash = data.splash; - } -} - -module.exports = PartialGuild; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); - -/* -{ type: 0, id: '123123', name: 'heavy-testing' } } -*/ - -/** - * Represents a guild channel that the client only has limited information for - e.g. from invites. - */ -class PartialGuildChannel { - constructor(client, data) { - /** - * The client that instantiated this PartialGuildChannel - * @name PartialGuildChannel#client - * @type {Client} - * @readonly - */ - Object.defineProperty(this, 'client', { value: client }); - - this.setup(data); - } - - setup(data) { - /** - * The ID of this guild channel - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The name of this guild channel - * @type {string} - */ - this.name = data.name; - - /** - * The type of this guild channel - `text` or `voice` - * @type {string} - */ - this.type = Constants.ChannelTypes.TEXT === data.type ? 'text' : 'voice'; - } -} - -module.exports = PartialGuildChannel; - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -const Collection = __webpack_require__(3); -const Snowflake = __webpack_require__(8); - -const Targets = { - ALL: 'ALL', - GUILD: 'GUILD', - CHANNEL: 'CHANNEL', - USER: 'USER', - ROLE: 'ROLE', - INVITE: 'INVITE', - WEBHOOK: 'WEBHOOK', - EMOJI: 'EMOJI', - MESSAGE: 'MESSAGE', -}; - -const Actions = { - ALL: null, - GUILD_UPDATE: 1, - CHANNEL_CREATE: 10, - CHANNEL_UPDATE: 11, - CHANNEL_DELETE: 12, - CHANNEL_OVERWRITE_CREATE: 13, - CHANNEL_OVERWRITE_UPDATE: 14, - CHANNEL_OVERWRITE_DELETE: 15, - MEMBER_KICK: 20, - MEMBER_PRUNE: 21, - MEMBER_BAN_ADD: 22, - MEMBER_BAN_REMOVE: 23, - MEMBER_UPDATE: 24, - MEMBER_ROLE_UPDATE: 25, - ROLE_CREATE: 30, - ROLE_UPDATE: 31, - ROLE_DELETE: 32, - INVITE_CREATE: 40, - INVITE_UPDATE: 41, - INVITE_DELETE: 42, - WEBHOOK_CREATE: 50, - WEBHOOK_UPDATE: 51, - WEBHOOK_DELETE: 52, - EMOJI_CREATE: 60, - EMOJI_UPDATE: 61, - EMOJI_DELETE: 62, - MESSAGE_DELETE: 72, -}; - - -/** - * Audit logs entries are held in this class. - */ -class GuildAuditLogs { - constructor(guild, data) { - if (data.users) for (const user of data.users) guild.client.dataManager.newUser(user); - - /** - * The entries for this guild's audit logs - * @type {Collection} - */ - this.entries = new Collection(); - for (const item of data.audit_log_entries) { - const entry = new GuildAuditLogsEntry(guild, item); - this.entries.set(entry.id, entry); - } - } - - /** - * Handles possible promises for entry targets. - * @returns {Promise} - */ - static build(...args) { - const logs = new GuildAuditLogs(...args); - return Promise.all(logs.entries.map(e => e.target)).then(() => logs); - } - - /** - * Find target type from entry action. - * @param {number} target The action target - * @returns {?string} - */ - static targetType(target) { - if (target < 10) return Targets.GUILD; - if (target < 20) return Targets.CHANNEL; - if (target < 30) return Targets.USER; - if (target < 40) return Targets.ROLE; - if (target < 50) return Targets.INVITE; - if (target < 60) return Targets.WEBHOOK; - if (target < 70) return Targets.EMOJI; - if (target < 80) return Targets.MESSAGE; - return null; - } - - - /** - * Find action type from entry action. - * @param {string} action The action target - * @returns {string} - */ - static actionType(action) { - if ([ - Actions.CHANNEL_CREATE, - Actions.CHANNEL_OVERWRITE_CREATE, - Actions.MEMBER_BAN_REMOVE, - Actions.ROLE_CREATE, - Actions.INVITE_CREATE, - Actions.WEBHOOK_CREATE, - Actions.EMOJI_CREATE, - ].includes(action)) return 'CREATE'; - - if ([ - Actions.CHANNEL_DELETE, - Actions.CHANNEL_OVERWRITE_DELETE, - Actions.MEMBER_KICK, - Actions.MEMBER_PRUNE, - Actions.MEMBER_BAN_ADD, - Actions.ROLE_DELETE, - Actions.INVITE_DELETE, - Actions.WEBHOOK_DELETE, - Actions.EMOJI_DELETE, - Actions.MESSAGE_DELETE, - ].includes(action)) return 'DELETE'; - - if ([ - Actions.GUILD_UPDATE, - Actions.CHANNEL_UPDATE, - Actions.CHANNEL_OVERWRITE_UPDATE, - Actions.MEMBER_UPDATE, - Actions.MEMBER_ROLE_UPDATE, - Actions.ROLE_UPDATE, - Actions.INVITE_UPDATE, - Actions.WEBHOOK_UPDATE, - Actions.EMOJI_UPDATE, - ].includes(action)) return 'UPDATE'; - - return 'ALL'; - } -} - -/** - * Audit logs entry. - */ -class GuildAuditLogsEntry { - constructor(guild, data) { - const targetType = GuildAuditLogs.targetType(data.action_type); - /** - * The target type of this entry - * @type {string} - */ - this.targetType = targetType; - - /** - * The action type of this entry - * @type {string} - */ - this.actionType = GuildAuditLogs.actionType(data.action_type); - - /** - * Specific action type of this entry - * @type {string} - */ - this.action = Object.keys(Actions).find(k => Actions[k] === data.action_type); - - /** - * The reason of this entry - * @type {?string} - */ - this.reason = data.reason || null; - - /** - * The user that executed this entry - * @type {User} - */ - this.executor = guild.client.users.get(data.user_id); - - /** - * An entry in the audit log representing a specific change. - * @typedef {object} AuditLogChange - * @property {string} key The property that was changed, e.g. `nick` for nickname changes - * @property {*} [old] The old value of the change, e.g. for nicknames, the old nickname - * @property {*} [new] The new value of the change, e.g. for nicknames, the new nickname - */ - - /** - * Specific property changes - * @type {AuditLogChange[]} - */ - this.changes = data.changes ? data.changes.map(c => ({ key: c.key, old: c.old_value, new: c.new_value })) : null; - - /** - * The ID of this entry - * @type {Snowflake} - */ - this.id = data.id; - - /** - * Any extra data from the entry - * @type {?Object|Role|GuildMember} - */ - this.extra = null; - if (data.options) { - if (data.action_type === Actions.MEMBER_PRUNE) { - this.extra = { - removed: data.options.members_removed, - days: data.options.delete_member_days, - }; - } else if (data.action_type === Actions.MESSAGE_DELETE) { - this.extra = { - count: data.options.count, - channel: guild.channels.get(data.options.channel_id), - }; - } else { - switch (data.options.type) { - case 'member': - this.extra = guild.members.get(data.options.id); - if (!this.extra) this.extra = { id: data.options.id }; - break; - case 'role': - this.extra = guild.roles.get(data.options.id); - if (!this.extra) this.extra = { id: data.options.id, name: data.options.role_name }; - break; - default: - break; - } - } - } - - if ([Targets.USER, Targets.GUILD].includes(targetType)) { - /** - * The target of this entry - * @type {?Guild|User|Role|Emoji|Invite|Webhook} - */ - this.target = guild.client[`${targetType.toLowerCase()}s`].get(data.target_id); - } else if (targetType === Targets.WEBHOOK) { - this.target = guild.fetchWebhooks() - .then(hooks => { - this.target = hooks.find(h => h.id === data.target_id); - return this.target; - }); - } else if (targetType === Targets.INVITE) { - const change = this.changes.find(c => c.key === 'code'); - this.target = guild.fetchInvites() - .then(invites => { - this.target = invites.find(i => i.code === (change.new_value || change.old_value)); - return this.target; - }); - } else if (targetType === Targets.MESSAGE) { - this.target = guild.client.users.get(data.target_id); - } else { - this.target = guild[`${targetType.toLowerCase()}s`].get(data.target_id); - } - } - - /** - * The timestamp this entry was created at - * @type {number} - * @readonly - */ - get createdTimestamp() { - return Snowflake.deconstruct(this.id).timestamp; - } - - /** - * The time this entry was created - * @type {Date} - * @readonly - */ - get createdAt() { - return new Date(this.createdTimestamp); - } -} - -GuildAuditLogs.Actions = Actions; -GuildAuditLogs.Targets = Targets; -GuildAuditLogs.Entry = GuildAuditLogsEntry; - -module.exports = GuildAuditLogs; - - -/***/ }), -/* 66 */ -/***/ (function(module, exports) { - -/** - * A base class for different types of rate limiting handlers for the REST API. - * @private - */ -class RequestHandler { - /** - * @param {RESTManager} restManager The REST manager to use - */ - constructor(restManager) { - /** - * The RESTManager that instantiated this RequestHandler - * @type {RESTManager} - */ - this.restManager = restManager; - - /** - * A list of requests that have yet to be processed - * @type {APIRequest[]} - */ - this.queue = []; - } - - /** - * Whether or not the client is being rate limited on every endpoint - * @type {boolean} - * @readonly - */ - get globalLimit() { - return this.restManager.globallyRateLimited; - } - - set globalLimit(value) { - this.restManager.globallyRateLimited = value; - } - - /** - * Push a new API request into this bucket. - * @param {APIRequest} request The new request to push into the queue - */ - push(request) { - this.queue.push(request); - } - - /** - * Attempts to get this RequestHandler to process its current queue. - */ - handle() {} // eslint-disable-line no-empty-function - - destroy() { - this.queue = []; - } -} - -module.exports = RequestHandler; - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - -const Channel = __webpack_require__(17); -const TextBasedChannel = __webpack_require__(21); -const Collection = __webpack_require__(3); - -/** - * Represents a direct message channel between two users. - * @extends {Channel} - * @implements {TextBasedChannel} - */ -class DMChannel extends Channel { - constructor(client, data) { - super(client, data); - this.type = 'dm'; - this.messages = new Collection(); - this._typing = new Map(); - } - - setup(data) { - super.setup(data); - - /** - * The recipient on the other end of the DM - * @type {User} - */ - this.recipient = this.client.dataManager.newUser(data.recipients[0]); - - this.lastMessageID = data.last_message_id; - } - - /** - * When concatenated with a string, this automatically concatenates the recipient's mention instead of the - * DM channel object. - * @returns {string} - */ - toString() { - return this.recipient.toString(); - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ - send() {} - sendMessage() {} - sendEmbed() {} - sendFile() {} - sendFiles() {} - sendCode() {} - fetchMessage() {} - fetchMessages() {} - fetchPinnedMessages() {} - search() {} - startTyping() {} - stopTyping() {} - get typing() {} - get typingCount() {} - createCollector() {} - createMessageCollector() {} - awaitMessages() {} - // Doesn't work on DM channels; bulkDelete() {} - acknowledge() {} - _cacheMessage() {} -} - -TextBasedChannel.applyToClass(DMChannel, true, ['bulkDelete']); - -module.exports = DMChannel; - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -const GuildChannel = __webpack_require__(30); -const TextBasedChannel = __webpack_require__(21); -const Collection = __webpack_require__(3); - -/** - * Represents a guild text channel on Discord. - * @extends {GuildChannel} - * @implements {TextBasedChannel} - */ -class TextChannel extends GuildChannel { - constructor(guild, data) { - super(guild, data); - this.type = 'text'; - this.messages = new Collection(); - this._typing = new Map(); - } - - setup(data) { - super.setup(data); - - /** - * The topic of the text channel - * @type {?string} - */ - this.topic = data.topic; - - /** - * If the Discord considers this channel NSFW - * @type {boolean} - * @readonly - */ - this.nsfw = Boolean(data.nsfw); - - this.lastMessageID = data.last_message_id; - } - - /** - * A collection of members that can see this channel, mapped by their ID - * @type {Collection} - * @readonly - */ - get members() { - const members = new Collection(); - for (const member of this.guild.members.values()) { - if (this.permissionsFor(member).has('READ_MESSAGES')) { - members.set(member.id, member); - } - } - return members; - } - - /** - * Fetch all webhooks for the channel. - * @returns {Promise>} - */ - fetchWebhooks() { - return this.client.rest.methods.getChannelWebhooks(this); - } - - /** - * Create a webhook for the channel. - * @param {string} name The name of the webhook - * @param {BufferResolvable|Base64Resolvable} [avatar] The avatar for the webhook - * @param {string} [reason] Reason for creating this webhook - * @returns {Promise} webhook The created webhook - * @example - * channel.createWebhook('Snek', 'https://i.imgur.com/mI8XcpG.jpg') - * .then(webhook => console.log(`Created webhook ${webhook}`)) - * .catch(console.error) - */ - createWebhook(name, avatar, reason) { - if (typeof avatar === 'string' && avatar.startsWith('data:')) { - return this.client.rest.methods.createWebhook(this, name, avatar, reason); - } else { - return this.client.resolver.resolveImage(avatar).then(data => - this.client.rest.methods.createWebhook(this, name, data, reason) - ); - } - } - - // These are here only for documentation purposes - they are implemented by TextBasedChannel - /* eslint-disable no-empty-function */ - send() {} - sendMessage() {} - sendEmbed() {} - sendFile() {} - sendFiles() {} - sendCode() {} - fetchMessage() {} - fetchMessages() {} - fetchPinnedMessages() {} - search() {} - startTyping() {} - stopTyping() {} - get typing() {} - get typingCount() {} - createCollector() {} - createMessageCollector() {} - awaitMessages() {} - bulkDelete() {} - acknowledge() {} - _cacheMessage() {} -} - -TextBasedChannel.applyToClass(TextChannel, true); - -module.exports = TextChannel; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports) { - -/** - * Represents a permission overwrite for a role or member in a guild channel. - */ -class PermissionOverwrites { - constructor(guildChannel, data) { - /** - * The GuildChannel this overwrite is for - * @name PermissionOverwrites#channel - * @type {GuildChannel} - * @readonly - */ - Object.defineProperty(this, 'channel', { value: guildChannel }); - - if (data) this.setup(data); - } - - setup(data) { - /** - * The ID of this overwrite, either a user ID or a role ID - * @type {Snowflake} - */ - this.id = data.id; - - /** - * The type of this overwrite - * @type {string} - */ - this.type = data.type; - - this.deny = data.deny; - this.allow = data.allow; - } - - /** - * Delete this Permission Overwrite. - * @param {string} [reason] Reason for deleting this overwrite - * @returns {Promise} - */ - delete(reason) { - return this.channel.client.rest.methods.deletePermissionOverwrites(this, reason); - } -} - -module.exports = PermissionOverwrites; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -const GuildChannel = __webpack_require__(30); -const Collection = __webpack_require__(3); - -/** - * Represents a guild voice channel on Discord. - * @extends {GuildChannel} - */ -class VoiceChannel extends GuildChannel { - constructor(guild, data) { - super(guild, data); - - /** - * The members in this voice channel - * @type {Collection} - */ - this.members = new Collection(); - - this.type = 'voice'; - } - - setup(data) { - super.setup(data); - - /** - * The bitrate of this voice channel - * @type {number} - */ - this.bitrate = data.bitrate * 0.001; - - /** - * The maximum amount of users allowed in this channel - 0 means unlimited. - * @type {number} - */ - this.userLimit = data.user_limit; - } - - /** - * The voice connection for this voice channel, if the client is connected - * @type {?VoiceConnection} - * @readonly - */ - get connection() { - const connection = this.guild.voiceConnection; - if (connection && connection.channel.id === this.id) return connection; - return null; - } - - /** - * Checks if the voice channel is full - * @type {boolean} - * @readonly - */ - get full() { - return this.userLimit > 0 && this.members.size >= this.userLimit; - } - - /** - * Checks if the client has permission join the voice channel - * @type {boolean} - * @readonly - */ - get joinable() { - if (this.client.browser) return false; - if (!this.permissionsFor(this.client.user).has('CONNECT')) return false; - if (this.full && !this.permissionsFor(this.client.user).has('MOVE_MEMBERS')) return false; - return true; - } - - /** - * Checks if the client has permission to send audio to the voice channel - * @type {boolean} - * @readonly - */ - get speakable() { - return this.permissionsFor(this.client.user).has('SPEAK'); - } - - /** - * Sets the bitrate of the channel (in kbps). - * @param {number} bitrate The new bitrate - * @param {string} [reason] Reason for changing the channel's bitrate - * @returns {Promise} - * @example - * // Set the bitrate of a voice channel - * voiceChannel.setBitrate(48) - * .then(vc => console.log(`Set bitrate to ${vc.bitrate}kbps for ${vc.name}`)) - * .catch(console.error); - */ - setBitrate(bitrate, reason) { - bitrate *= 1000; - return this.edit({ bitrate }, reason); - } - - /** - * Sets the user limit of the channel. - * @param {number} userLimit The new user limit - * @param {string} [reason] Reason for changing the user limit - * @returns {Promise} - * @example - * // Set the user limit of a voice channel - * voiceChannel.setUserLimit(42) - * .then(vc => console.log(`Set user limit to ${vc.userLimit} for ${vc.name}`)) - * .catch(console.error); - */ - setUserLimit(userLimit, reason) { - return this.edit({ userLimit }, reason); - } - - /** - * Attempts to join this voice channel. - * @returns {Promise} - * @example - * // Join a voice channel - * voiceChannel.join() - * .then(connection => console.log('Connected!')) - * .catch(console.error); - */ - join() { - if (this.client.browser) return Promise.reject(new Error('Voice connections are not available in browsers.')); - return this.client.voice.joinChannel(this); - } - - /** - * Leaves this voice channel. - * @example - * // Leave a voice channel - * voiceChannel.leave(); - */ - leave() { - if (this.client.browser) return; - const connection = this.client.voice.connections.get(this.guild.id); - if (connection && connection.channel.id === this.id) connection.disconnect(); - } -} - -module.exports = VoiceChannel; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {const browser = typeof window !== 'undefined'; -const EventEmitter = __webpack_require__(9); -const Constants = __webpack_require__(0); -const zlib = __webpack_require__(26); -const PacketManager = __webpack_require__(119); -const erlpack = (function findErlpack() { - try { - const e = __webpack_require__(159); - if (!e.pack) return null; - return e; - } catch (e) { - return null; - } -}()); - -const WebSocket = (function findWebSocket() { - if (browser) return window.WebSocket; // eslint-disable-line no-undef - try { - return __webpack_require__(160); - } catch (e) { - return __webpack_require__(161); - } -}()); - -/** - * Abstracts a WebSocket connection with decoding/encoding for the Discord gateway. - * @private - */ -class WebSocketConnection extends EventEmitter { - /** - * @param {WebSocketManager} manager The WebSocket manager - * @param {string} gateway The WebSocket gateway to connect to - */ - constructor(manager, gateway) { - super(); - /** - * The WebSocket Manager of this connection - * @type {WebSocketManager} - */ - this.manager = manager; - - /** - * The client this belongs to - * @type {Client} - */ - this.client = manager.client; - - /** - * The WebSocket connection itself - * @type {WebSocket} - */ - this.ws = null; - - /** - * The current sequence of the WebSocket - * @type {number} - */ - this.sequence = -1; - - /** - * The current status of the client - * @type {number} - */ - this.status = Constants.Status.IDLE; - - /** - * The Packet Manager of the connection - * @type {WebSocketPacketManager} - */ - this.packetManager = new PacketManager(this); - - /** - * The last time a ping was sent (a timestamp) - * @type {number} - */ - this.lastPingTimestamp = 0; - - /** - * Contains the rate limit queue and metadata - * @type {Object} - */ - this.ratelimit = { - queue: [], - remaining: 120, - resetTime: -1, - }; - this.connect(gateway); - - /** - * Events that are disabled (will not be processed) - * @type {Object} - */ - this.disabledEvents = {}; - - /** - * The sequence on WebSocket close - * @type {number} - */ - this.closeSequence = 0; - - /** - * Whether or not the WebSocket is expecting to be closed - * @type {boolean} - */ - this.expectingClose = false; - for (const event of this.client.options.disabledEvents) this.disabledEvents[event] = true; - } - - /** - * Causes the client to be marked as ready and emits the ready event. - * @returns {void} - */ - triggerReady() { - if (this.status === Constants.Status.READY) { - this.debug('Tried to mark self as ready, but already ready'); - return; - } - /** - * Emitted when the client becomes ready to start working. - * @event Client#ready - */ - this.status = Constants.Status.READY; - this.client.emit(Constants.Events.READY); - this.packetManager.handleQueue(); - } - - /** - * Checks whether the client is ready to be marked as ready. - * @returns {void} - */ - checkIfReady() { - if (this.status === Constants.Status.READY || this.status === Constants.Status.NEARLY) return false; - let unavailableGuilds = 0; - for (const guild of this.client.guilds.values()) { - if (!guild.available) unavailableGuilds++; - } - if (unavailableGuilds === 0) { - this.status = Constants.Status.NEARLY; - if (!this.client.options.fetchAllMembers) return this.triggerReady(); - // Fetch all members before marking self as ready - const promises = this.client.guilds.map(g => g.fetchMembers()); - Promise.all(promises) - .then(() => this.triggerReady()) - .catch(e => { - this.debug(`Failed to fetch all members before ready! ${e}`); - this.triggerReady(); - }); - } - return true; - } - - // Util - /** - * Emits a debug message. - * @param {string} message Debug message - * @returns {void} - */ - debug(message) { - if (message instanceof Error) message = message.stack; - return this.manager.debug(`[connection] ${message}`); - } - - /** - * Attempts to serialise data from the WebSocket. - * @param {string|Object} data Data to unpack - * @returns {Object} - */ - unpack(data) { - if (data instanceof ArrayBuffer) data = Buffer.from(new Uint8Array(data)); - - if (erlpack && typeof data !== 'string') return erlpack.unpack(data); - else if (data instanceof Buffer) data = zlib.inflateSync(data).toString(); - - return JSON.parse(data); - } - - /** - * Packs an object ready to be sent. - * @param {Object} data Data to pack - * @returns {string|Buffer} - */ - pack(data) { - return erlpack ? erlpack.pack(data) : JSON.stringify(data); - } - - /** - * Processes the current WebSocket queue. - */ - processQueue() { - if (this.ratelimit.remaining === 0) return; - if (this.ratelimit.queue.length === 0) return; - if (this.ratelimit.remaining === 120) { - this.ratelimit.resetTimer = setTimeout(() => { - this.ratelimit.remaining = 120; - this.processQueue(); - }, 120e3); // eslint-disable-line - } - while (this.ratelimit.remaining > 0) { - const item = this.ratelimit.queue.shift(); - if (!item) return; - this._send(item); - this.ratelimit.remaining--; - } - } - - /** - * Sends data, bypassing the queue. - * @param {Object} data Packet to send - * @returns {void} - */ - _send(data) { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { - this.debug(`Tried to send packet ${data} but no WebSocket is available!`); - return; - } - this.ws.send(this.pack(data)); - } - - /** - * Adds data to the queue to be sent. - * @param {Object} data Packet to send - * @returns {void} - */ - send(data) { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) { - this.debug(`Tried to send packet ${data} but no WebSocket is available!`); - return; - } - this.ratelimit.queue.push(data); - this.processQueue(); - } - - /** - * Creates a connection to a gateway. - * @param {string} gateway The gateway to connect to - * @param {number} [after=0] How long to wait before connecting - * @param {boolean} [force=false] Whether or not to force a new connection even if one already exists - * @returns {boolean} - */ - connect(gateway = this.gateway, after = 0, force = false) { - if (after) return this.client.setTimeout(() => this.connect(gateway, 0, force), after); // eslint-disable-line - if (this.ws && !force) { - this.debug('WebSocket connection already exists'); - return false; - } else if (typeof gateway !== 'string') { - this.debug(`Tried to connect to an invalid gateway: ${gateway}`); - return false; - } - this.expectingClose = false; - this.gateway = gateway; - this.debug(`Connecting to ${gateway}`); - const ws = this.ws = new WebSocket(gateway); - if (browser) ws.binaryType = 'arraybuffer'; - ws.onmessage = this.onMessage.bind(this); - ws.onopen = this.onOpen.bind(this); - ws.onerror = this.onError.bind(this); - ws.onclose = this.onClose.bind(this); - this.status = Constants.Status.CONNECTING; - return true; - } - - /** - * Destroys the connection. - * @returns {boolean} - */ - destroy() { - const ws = this.ws; - if (!ws) { - this.debug('Attempted to destroy WebSocket but no connection exists!'); - return false; - } - this.heartbeat(-1); - this.expectingClose = true; - ws.close(1000); - this.packetManager.handleQueue(); - this.ws = null; - this.status = Constants.Status.DISCONNECTED; - return true; - } - - /** - * Called whenever a message is received. - * @param {Event} event Event received - * @returns {boolean} - */ - onMessage(event) { - let data; - try { - data = this.unpack(event.data); - } catch (err) { - this.emit('debug', err); - } - return this.onPacket(data); - } - - /** - * Sets the current sequence of the connection. - * @param {number} s New sequence - */ - setSequence(s) { - this.sequence = s > this.sequence ? s : this.sequence; - } - - /** - * Called whenever a packet is received. - * @param {Object} packet Received packet - * @returns {boolean} - */ - onPacket(packet) { - if (!packet) { - this.debug('Received null packet'); - return false; - } - this.client.emit('raw', packet); - switch (packet.op) { - case Constants.OPCodes.HELLO: - return this.heartbeat(packet.d.heartbeat_interval); - case Constants.OPCodes.RECONNECT: - return this.reconnect(); - case Constants.OPCodes.INVALID_SESSION: - if (!packet.d) this.sessionID = null; - this.sequence = -1; - this.debug('Session invalidated -- will identify with a new session'); - return this.identify(packet.d ? 2500 : 0); - case Constants.OPCodes.HEARTBEAT_ACK: - return this.ackHeartbeat(); - case Constants.OPCodes.HEARTBEAT: - return this.heartbeat(); - default: - return this.packetManager.handle(packet); - } - } - - /** - * Called whenever a connection is opened to the gateway. - * @param {Event} event Received open event - */ - onOpen(event) { - if (event && event.target && event.target.url) this.gateway = event.target.url; - this.debug(`Connected to gateway ${this.gateway}`); - this.identify(); - } - - /** - * Causes a reconnection to the gateway. - */ - reconnect() { - this.debug('Attemping to reconnect in 5500ms...'); - /** - * Emitted whenever the client tries to reconnect to the WebSocket. - * @event Client#reconnecting - */ - this.client.emit(Constants.Events.RECONNECTING); - this.connect(this.gateway, 5500, true); - } - - /** - * Called whenever an error occurs with the WebSocket. - * @param {Error} error The error that occurred - */ - onError(error) { - if (error && error.message === 'uWs client connection error') { - this.reconnect(); - return; - } - /** - * Emitted whenever the client's WebSocket encounters a connection error. - * @event Client#error - * @param {Error} error The encountered error - */ - this.client.emit(Constants.Events.ERROR, error); - } - - /** - * @external CloseEvent - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent} - */ - - /** - * Called whenever a connection to the gateway is closed. - * @param {CloseEvent} event Close event that was received - */ - onClose(event) { - this.debug(`${this.expectingClose ? 'Client' : 'Server'} closed the WebSocket connection: ${event.code}`); - this.closeSequence = this.sequence; - // Reset the state before trying to fix anything - this.emit('close', event); - this.heartbeat(-1); - // Should we reconnect? - if (event.code === 1000 ? this.expectingClose : Constants.WSCodes[event.code]) { - this.expectingClose = false; - /** - * Emitted when the client's WebSocket disconnects and will no longer attempt to reconnect. - * @event Client#disconnect - * @param {CloseEvent} event The WebSocket close event - */ - this.client.emit(Constants.Events.DISCONNECT, event); - this.debug(Constants.WSCodes[event.code]); - this.destroy(); - return; - } - this.expectingClose = false; - this.reconnect(); - } - - // Heartbeat - /** - * Acknowledges a heartbeat. - */ - ackHeartbeat() { - this.debug(`Heartbeat acknowledged, latency of ${Date.now() - this.lastPingTimestamp}ms`); - this.client._pong(this.lastPingTimestamp); - } - - /** - * Sends a heartbeat or sets an interval for sending heartbeats. - * @param {number} [time] If -1, clears the interval, any other number sets an interval - * If no value is given, a heartbeat will be sent instantly - */ - heartbeat(time) { - if (!isNaN(time)) { - if (time === -1) { - this.debug('Clearing heartbeat interval'); - this.client.clearInterval(this.heartbeatInterval); - this.heartbeatInterval = null; - } else { - this.debug(`Setting a heartbeat interval for ${time}ms`); - this.heartbeatInterval = this.client.setInterval(() => this.heartbeat(), time); - } - return; - } - this.debug('Sending a heartbeat'); - this.lastPingTimestamp = Date.now(); - this.send({ - op: Constants.OPCodes.HEARTBEAT, - d: this.sequence, - }); - } - - // Identification - /** - * Identifies the client on a connection. - * @param {number} [after] How long to wait before identifying - * @returns {void} - */ - identify(after) { - if (after) return this.client.setTimeout(this.identify.bind(this), after); - return this.sessionID ? this.identifyResume() : this.identifyNew(); - } - - /** - * Identifies as a new connection on the gateway. - * @returns {void} - */ - identifyNew() { - if (!this.client.token) { - this.debug('No token available to identify a new session with'); - return; - } - // Clone the generic payload and assign the token - const d = Object.assign({ token: this.client.token }, this.client.options.ws); - - // Sharding stuff - const { shardId, shardCount } = this.client.options; - if (shardCount > 0) d.shard = [Number(shardId), Number(shardCount)]; - - // Send the payload - this.debug('Identifying as a new session'); - this.send({ op: Constants.OPCodes.IDENTIFY, d }); - } - - /** - * Resumes a session on the gateway. - * @returns {void} - */ - identifyResume() { - if (!this.sessionID) { - this.debug('Warning: wanted to resume but session ID not available; identifying as a new session instead'); - return this.identifyNew(); - } - this.debug(`Attempting to resume session ${this.sessionID}`); - - const d = { - token: this.client.token, - session_id: this.sessionID, - seq: this.sequence, - }; - - return this.send({ - op: Constants.OPCodes.RESUME, - d, - }); - } -} - -/** - * Encoding the WebSocket connections will use. - * @type {string} - */ -WebSocketConnection.ENCODING = erlpack ? 'etf' : 'json'; -WebSocketConnection.WebSocket = WebSocket; - -module.exports = WebSocketConnection; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - -const User = __webpack_require__(14); -const Collection = __webpack_require__(3); -const ClientUserSettings = __webpack_require__(73); -const ClientUserGuildSettings = __webpack_require__(121); -const Constants = __webpack_require__(0); - -/** - * Represents the logged in client's Discord user. - * @extends {User} - */ -class ClientUser extends User { - setup(data) { - super.setup(data); - - /** - * Whether or not this account has been verified - * @type {boolean} - */ - this.verified = data.verified; - - /** - * The email of this account - * @type {string} - */ - this.email = data.email; - this.localPresence = {}; - this._typing = new Map(); - - /** - * A Collection of friends for the logged in user - * This is only filled when using a user account. - * @type {Collection} - */ - this.friends = new Collection(); - - /** - * A Collection of blocked users for the logged in user - * This is only filled when using a user account. - * @type {Collection} - */ - this.blocked = new Collection(); - - /** - * A Collection of notes for the logged in user - * This is only filled when using a user account. - * @type {Collection} - */ - this.notes = new Collection(); - - /** - * If the user has Discord premium (nitro) - * This is only filled when using a user account. - * @type {?boolean} - */ - this.premium = typeof data.premium === 'boolean' ? data.premium : null; - - /** - * If the user has MFA enabled on their account - * This is only filled when using a user account. - * @type {?boolean} - */ - this.mfaEnabled = typeof data.mfa_enabled === 'boolean' ? data.mfa_enabled : null; - - /** - * If the user has ever used a mobile device on Discord - * This is only filled when using a user account. - * @type {?boolean} - */ - this.mobile = typeof data.mobile === 'boolean' ? data.mobile : null; - - /** - * Various settings for this user - * This is only filled when using a user account. - * @type {?ClientUserSettings} - */ - this.settings = data.user_settings ? new ClientUserSettings(this, data.user_settings) : null; - - /** - * All of the user's guild settings - * This is only filled when using a user account - * @type {Collection} - */ - this.guildSettings = new Collection(); - if (data.user_guild_settings) { - for (const settings of data.user_guild_settings) { - this.guildSettings.set(settings.guild_id, new ClientUserGuildSettings(settings, this.client)); - } - } - } - - edit(data) { - return this.client.rest.methods.updateCurrentUser(data); - } - - /** - * Set the username of the logged in client. - * Changing usernames in Discord is heavily rate limited, with only 2 requests - * every hour. Use this sparingly! - * @param {string} username The new username - * @param {string} [password] Current password (only for user accounts) - * @returns {Promise} - * @example - * // Set username - * client.user.setUsername('discordjs') - * .then(user => console.log(`My new username is ${user.username}`)) - * .catch(console.error); - */ - setUsername(username, password) { - return this.client.rest.methods.updateCurrentUser({ username }, password); - } - - /** - * Changes the email for the client user's account. - * This is only available when using a user account. - * @param {string} email New email to change to - * @param {string} password Current password - * @returns {Promise} - * @example - * // Set email - * client.user.setEmail('bob@gmail.com', 'some amazing password 123') - * .then(user => console.log(`My new email is ${user.email}`)) - * .catch(console.error); - */ - setEmail(email, password) { - return this.client.rest.methods.updateCurrentUser({ email }, password); - } - - /** - * Changes the password for the client user's account. - * This is only available when using a user account. - * @param {string} newPassword New password to change to - * @param {string} oldPassword Current password - * @returns {Promise} - * @example - * // Set password - * client.user.setPassword('some new amazing password 456', 'some amazing password 123') - * .then(user => console.log('New password set!')) - * .catch(console.error); - */ - setPassword(newPassword, oldPassword) { - return this.client.rest.methods.updateCurrentUser({ password: newPassword }, oldPassword); - } - - /** - * Set the avatar of the logged in client. - * @param {BufferResolvable|Base64Resolvable} avatar The new avatar - * @returns {Promise} - * @example - * // Set avatar - * client.user.setAvatar('./avatar.png') - * .then(user => console.log(`New avatar set!`)) - * .catch(console.error); - */ - setAvatar(avatar) { - return this.client.resolver.resolveImage(avatar).then(data => - this.client.rest.methods.updateCurrentUser({ avatar: data }) - ); - } - - /** - * Data resembling a raw Discord presence. - * @typedef {Object} PresenceData - * @property {PresenceStatus} [status] Status of the user - * @property {boolean} [afk] Whether the user is AFK - * @property {Object} [game] Game the user is playing - * @property {string} [game.name] Name of the game - * @property {string} [game.url] Twitch stream URL - */ - - /** - * Sets the full presence of the client user. - * @param {PresenceData} data Data for the presence - * @returns {Promise} - */ - setPresence(data) { - // {"op":3,"d":{"status":"dnd","since":0,"game":null,"afk":false}} - return new Promise(resolve => { - let status = this.localPresence.status || this.presence.status; - let game = this.localPresence.game; - let afk = this.localPresence.afk || this.presence.afk; - - if (!game && this.presence.game) { - game = { - name: this.presence.game.name, - type: this.presence.game.type, - url: this.presence.game.url, - }; - } - - if (data.status) { - if (typeof data.status !== 'string') throw new TypeError('Status must be a string'); - if (this.bot) { - status = data.status; - } else { - this.settings.update(Constants.UserSettingsMap.status, data.status); - status = 'invisible'; - } - } - - if (data.game) { - game = data.game; - game.type = game.url ? 1 : 0; - } else if (typeof data.game !== 'undefined') { - game = null; - } - - if (typeof data.afk !== 'undefined') afk = data.afk; - afk = Boolean(afk); - - this.localPresence = { status, game, afk }; - this.localPresence.since = 0; - this.localPresence.game = this.localPresence.game || null; - - this.client.ws.send({ - op: 3, - d: this.localPresence, - }); - - this.client._setPresence(this.id, this.localPresence); - - resolve(this); - }); - } - - /** - * A user's status. Must be one of: - * * `online` - * * `idle` - * * `invisible` - * * `dnd` (do not disturb) - * @typedef {string} PresenceStatus - */ - - /** - * Sets the status of the client user. - * @param {PresenceStatus} status Status to change to - * @returns {Promise} - */ - setStatus(status) { - return this.setPresence({ status }); - } - - /** - * Sets the game the client user is playing. - * @param {?string} game Game being played - * @param {string} [streamingURL] Twitch stream URL - * @returns {Promise} - */ - setGame(game, streamingURL) { - if (!game) return this.setPresence({ game: null }); - return this.setPresence({ - game: { - name: game, - url: streamingURL, - }, - }); - } - - /** - * Sets/removes the AFK flag for the client user. - * @param {boolean} afk Whether or not the user is AFK - * @returns {Promise} - */ - setAFK(afk) { - return this.setPresence({ afk }); - } - - /** - * Fetches messages that mentioned the client's user. - * @param {Object} [options] Options for the fetch - * @param {number} [options.limit=25] Maximum number of mentions to retrieve - * @param {boolean} [options.roles=true] Whether to include role mentions - * @param {boolean} [options.everyone=true] Whether to include everyone/here mentions - * @param {Guild|Snowflake} [options.guild] Limit the search to a specific guild - * @returns {Promise} - */ - fetchMentions(options = {}) { - return this.client.rest.methods.fetchMentions(options); - } - - /** - * Send a friend request. - * This is only available when using a user account. - * @param {UserResolvable} user The user to send the friend request to - * @returns {Promise} The user the friend request was sent to - */ - addFriend(user) { - user = this.client.resolver.resolveUser(user); - return this.client.rest.methods.addFriend(user); - } - - /** - * Remove a friend. - * This is only available when using a user account. - * @param {UserResolvable} user The user to remove from your friends - * @returns {Promise} The user that was removed - */ - removeFriend(user) { - user = this.client.resolver.resolveUser(user); - return this.client.rest.methods.removeFriend(user); - } - - /** - * Creates a guild. - * This is only available when using a user account. - * @param {string} name The name of the guild - * @param {string} [region] The region for the server - * @param {BufferResolvable|Base64Resolvable} [icon=null] The icon for the guild - * @returns {Promise} The guild that was created - */ - createGuild(name, region, icon = null) { - if (typeof icon === 'string' && icon.startsWith('data:')) { - return this.client.rest.methods.createGuild({ name, icon, region }); - } else { - return this.client.resolver.resolveImage(icon).then(data => - this.client.rest.methods.createGuild({ name, icon: data, region }) - ); - } - } - - /** - * An object containing either a user or access token, and an optional nickname. - * @typedef {Object} GroupDMRecipientOptions - * @property {UserResolvable|Snowflake} [user] User to add to the Group DM - * (only available if a user is creating the DM) - * @property {string} [accessToken] Access token to use to add a user to the Group DM - * (only available if a bot is creating the DM) - * @property {string} [nick] Permanent nickname (only available if a bot is creating the DM) - */ - - /** - * Creates a Group DM. - * @param {GroupDMRecipientOptions[]} recipients The recipients - * @returns {Promise} - */ - createGroupDM(recipients) { - return this.client.rest.methods.createGroupDM({ - recipients: recipients.map(u => this.client.resolver.resolveUserID(u.user)), - accessTokens: recipients.map(u => u.accessToken), - nicks: recipients.map(u => u.nick), - }); - } - - /** - * Accepts an invite to join a guild. - * This is only available when using a user account. - * @param {Invite|string} invite Invite or code to accept - * @returns {Promise} Joined guild - */ - acceptInvite(invite) { - return this.client.rest.methods.acceptInvite(invite); - } -} - -module.exports = ClientUser; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - -const Constants = __webpack_require__(0); -const Util = __webpack_require__(4); - -/** - * A wrapper around the ClientUser's settings. - */ -class ClientUserSettings { - constructor(user, data) { - this.user = user; - this.patch(data); - } - - /** - * Patch the data contained in this class with new partial data. - * @param {Object} data Data to patch this with - * @returns {void} - * @private - */ - patch(data) { - for (const key of Object.keys(Constants.UserSettingsMap)) { - const value = Constants.UserSettingsMap[key]; - if (!data.hasOwnProperty(key)) continue; - if (typeof value === 'function') { - this[value.name] = value(data[key]); - } else { - this[value] = data[key]; - } - } - } - - /** - * Update a specific property of of user settings. - * @param {string} name Name of property - * @param {*} value Value to patch - * @returns {Promise} - */ - update(name, value) { - return this.user.client.rest.methods.patchUserSettings({ [name]: value }); - } - - /** - * Sets the position at which this guild will appear in the Discord client. - * @param {Guild} guild The guild to move - * @param {number} position Absolute or relative position - * @param {boolean} [relative=false] Whether to position relatively or absolutely - * @returns {Promise} - */ - setGuildPosition(guild, position, relative) { - const temp = Object.assign([], this.guildPositions); - Util.moveElementInArray(temp, guild.id, position, relative); - return this.update('guild_positions', temp).then(() => guild); - } - - /** - * Add a guild to the list of restricted guilds. - * @param {Guild} guild The guild to add - * @returns {Promise} - */ - addRestrictedGuild(guild) { - const temp = Object.assign([], this.restrictedGuilds); - if (temp.includes(guild.id)) return Promise.reject(new Error('Guild is already restricted')); - temp.push(guild.id); - return this.update('restricted_guilds', temp).then(() => guild); - } - - /** - * Remove a guild from the list of restricted guilds. - * @param {Guild} guild The guild to remove - * @returns {Promise} - */ - removeRestrictedGuild(guild) { - const temp = Object.assign([], this.restrictedGuilds); - const index = temp.indexOf(guild.id); - if (index < 0) return Promise.reject(new Error('Guild is not restricted')); - temp.splice(index, 1); - return this.update('restricted_guilds', temp).then(() => guild); - } -} - -module.exports = ClientUserSettings; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -const browser = typeof window !== 'undefined'; -const webpack = !!"true"; - -const Discord = __webpack_require__(75); - -module.exports = Discord; -if (browser && webpack) window.Discord = Discord; // eslint-disable-line no-undef -// eslint-disable-next-line no-console -else if (!browser) console.warn('Warning: Attempting to use browser version of Discord.js in a non-browser environment!'); - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -const Util = __webpack_require__(4); - -module.exports = { - // "Root" classes (starting points) - Client: __webpack_require__(106), - Shard: __webpack_require__(195), - ShardClientUtil: __webpack_require__(196), - ShardingManager: __webpack_require__(197), - WebhookClient: __webpack_require__(198), - - // Utilities - Collection: __webpack_require__(3), - Constants: __webpack_require__(0), - DiscordAPIError: __webpack_require__(43), - EvaluatedPermissions: __webpack_require__(11), - Permissions: __webpack_require__(11), - Snowflake: __webpack_require__(8), - SnowflakeUtil: __webpack_require__(8), - Util: Util, - util: Util, - version: __webpack_require__(54).version, - - // Shortcuts to Util methods - escapeMarkdown: Util.escapeMarkdown, - fetchRecommendedShards: Util.fetchRecommendedShards, - splitMessage: Util.splitMessage, - - // Structures - Attachment: __webpack_require__(28), - Channel: __webpack_require__(17), - ClientUser: __webpack_require__(72), - ClientUserSettings: __webpack_require__(73), - Collector: __webpack_require__(39), - DMChannel: __webpack_require__(67), - Emoji: __webpack_require__(23), - Game: __webpack_require__(16).Game, - GroupDMChannel: __webpack_require__(42), - Guild: __webpack_require__(29), - GuildAuditLogs: __webpack_require__(65), - GuildChannel: __webpack_require__(30), - GuildMember: __webpack_require__(24), - Invite: __webpack_require__(62), - Message: __webpack_require__(22), - MessageAttachment: __webpack_require__(57), - MessageCollector: __webpack_require__(61), - MessageEmbed: __webpack_require__(58), - MessageMentions: __webpack_require__(56), - MessageReaction: __webpack_require__(59), - OAuth2Application: __webpack_require__(41), - ClientOAuth2Application: __webpack_require__(41), - PartialGuild: __webpack_require__(63), - PartialGuildChannel: __webpack_require__(64), - PermissionOverwrites: __webpack_require__(69), - Presence: __webpack_require__(16).Presence, - ReactionEmoji: __webpack_require__(38), - ReactionCollector: __webpack_require__(60), - RichEmbed: __webpack_require__(27), - Role: __webpack_require__(15), - TextChannel: __webpack_require__(68), - User: __webpack_require__(14), - VoiceChannel: __webpack_require__(70), - Webhook: __webpack_require__(40), -}; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} - -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return (b64.length * 3 / 4) - placeHoldersCount(b64) -} - -function toByteArray (b64) { - var i, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) - - arr = new Arr((len * 3 / 4) - placeHolders) - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len - - var L = 0 - - for (i = 0; i < l; i += 4) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } - - parts.push(output) - - return parts.join('') -} - - -/***/ }), -/* 77 */ -/***/ (function(module, exports) { - -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {__webpack_require__(32); -const zlib = __webpack_require__(26); -const qs = __webpack_require__(35); -const http = __webpack_require__(50); -const https = __webpack_require__(99); -const URL = __webpack_require__(52); -const Package = __webpack_require__(100); -const Stream = __webpack_require__(32); -const FormData = __webpack_require__(101); -const fileLoader = __webpack_require__(104); - -/** - * Snekfetch - * @extends Stream.Readable - * @extends Promise - */ -class Snekfetch extends Stream.Readable { - /** - * Create a request, but you probably wanna use `snekfetch#method` - * @param {string} method HTTP method - * @param {string} url URL - * @param {Object} opts Options - * @param {Object} [opts.headers] Headers to initialize the request with - * @param {Object|string|Buffer} [opts.data] Data to initialize the request with - * @param {string|Object} [opts.query] Query to intialize the request with - */ - constructor(method, url, opts = { headers: null, data: null, query: null }) { - super(); - - const options = URL.parse(url); - options.method = method.toUpperCase(); - if (opts.headers) options.headers = opts.headers; - if ('agent' in opts) options.agent = opts.agent; - - this.request = { https, http, file: fileLoader }[options.protocol.replace(':', '')].request(options); - this.request.followRedirects = opts.followRedirects; - if (opts.query) this.query(opts.query); - if (opts.data) this.send(opts.data); - } - - /** - * Add a query param to the request - * @param {string|Object} name Name of query param or object to add to query - * @param {string} [value] If name is a string value, this will be the value of the query param - * @returns {Snekfetch} This request - */ - query(name, value) { - if (this.response) throw new Error('Cannot modify query after being sent!'); - if (!this.request.query) this.request.query = {}; - if (name !== null && typeof name === 'object') { - this.request.query = Object.assign(this.request.query, name); - } else { - this.request.query[name] = value; - } - return this; - } - - /** - * Add a header to the request - * @param {string|Object} name Name of query param or object to add to headers - * @param {string} [value] If name is a string value, this will be the value of the header - * @returns {Snekfetch} This request - */ - set(name, value) { - if (this.response) throw new Error('Cannot modify headers after being sent!'); - if (name !== null && typeof name === 'object') { - for (const key of Object.keys(name)) this.set(key, name[key]); - } else { - this.request.setHeader(name, value); - } - return this; - } - - /** - * Attach a form data object - * @param {string} name Name of the form attachment - * @param {string|Object|Buffer} data Data for the attachment - * @param {string} [filename] Optional filename if form attachment name needs to be overridden - * @returns {Snekfetch} This request - */ - attach(name, data, filename) { - if (this.response) throw new Error('Cannot modify data after being sent!'); - const form = this._getFormData(); - this.set('Content-Type', `multipart/form-data; boundary=${form.boundary}`); - form.append(name, data, filename); - this.data = form; - return this; - } - - /** - * Send data with the request - * @param {string|Buffer|Object} data Data to send - * @returns {Snekfetch} This request - */ - send(data) { - if (this.response) throw new Error('Cannot modify data after being sent!'); - if (data instanceof Buffer || data instanceof Stream) { - this.data = data; - } else if (data !== null && typeof data === 'object') { - const header = this._getRequestHeader('content-type'); - let serialize; - if (header) { - if (header.includes('json')) serialize = JSON.stringify; - else if (header.includes('urlencoded')) serialize = qs.stringify; - } else { - this.set('Content-Type', 'application/json'); - serialize = JSON.stringify; - } - this.data = serialize(data); - } else { - this.data = data; - } - return this; - } - - then(resolver, rejector) { - return new Promise((resolve, reject) => { - const request = this.request; - - const handleError = (err) => { - if (!err) err = new Error('Unknown error occured'); - err.request = request; - reject(err); - }; - - request.once('abort', handleError); - request.once('aborted', handleError); - request.once('error', handleError); - - request.once('response', (response) => { - const stream = new Stream.PassThrough(); - if (this._shouldUnzip(response)) { - response.pipe(zlib.createUnzip({ - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH, - })).pipe(stream); - } else { - response.pipe(stream); - } - - const body = []; - - stream.on('data', (chunk) => { - if (!this.push(chunk)) this.pause(); - body.push(chunk); - }); - - stream.once('end', () => { - this.push(null); - const concated = Buffer.concat(body); - - if (this.request.followRedirects !== false && this._shouldRedirect(response)) { - let method = this.request.method; - if ([301, 302].includes(response.statusCode)) { - if (method !== 'HEAD') method = 'GET'; - this.data = null; - } else if (response.statusCode === 303) { - method = 'GET'; - } - - const headers = {}; - if (this.request._headerNames) { - for (const name of Object.keys(this.request._headerNames)) { - if (name.toLowerCase() === 'host') continue; - headers[this.request._headerNames[name]] = this.request._headers[name]; - } - } else { - for (const name of Object.keys(this.request._headers)) { - if (name.toLowerCase() === 'host') continue; - const header = this.request._headers[name]; - headers[header.name] = header.value; - } - } - - const newURL = /^https?:\/\//i.test(response.headers.location) ? - response.headers.location : - URL.resolve(makeURLFromRequest(request), response.headers.location); - resolve(new Snekfetch(method, newURL, { data: this.data, headers })); - return; - } - - /** - * @typedef {Object} SnekfetchResponse - * @prop {HTTP.Request} request - * @prop {?string|object|Buffer} body Processed response body - * @prop {string} text Raw response body - * @prop {boolean} ok If the response code is >= 200 and < 300 - * @prop {number} status HTTP status code - * @prop {string} statusText Human readable HTTP status - */ - const res = { - request: this.request, - get body() { - delete res.body; - const type = response.headers['content-type']; - if (type && type.includes('application/json')) { - try { - res.body = JSON.parse(res.text); - } catch (err) { - res.body = res.text; - } // eslint-disable-line no-empty - } else if (type && type.includes('application/x-www-form-urlencoded')) { - res.body = qs.parse(res.text); - } else { - res.body = concated; - } - - return res.body; - }, - text: concated.toString(), - ok: response.statusCode >= 200 && response.statusCode < 300, - headers: response.headers, - status: response.statusCode, - statusText: response.statusText || http.STATUS_CODES[response.statusCode], - }; - - if (res.ok) { - resolve(res); - } else { - const err = new Error(`${res.status} ${res.statusText}`.trim()); - Object.assign(err, res); - reject(err); - } - }); - }); - - const data = this.data ? this.data.end ? this.data.end() : this.data : null; - this._addFinalHeaders(); - if (this.request.query) this.request.path = `${this.request.path}?${qs.stringify(this.request.query)}`; - if (Array.isArray(data)) { - for (const chunk of data) request.write(chunk); - request.end(); - } else if (data instanceof Stream) { - data.pipe(request); - } else if (data instanceof Buffer) { - this.set('Content-Length', Buffer.byteLength(data)); - request.end(data); - } else { - request.end(data); - } - }) - .then(resolver, rejector); - } - - catch(rejector) { - return this.then(null, rejector); - } - - /** - * End the request - * @param {Function} [cb] Optional callback to handle the response - * @returns {Snekfetch} This request - */ - end(cb) { - return this.then( - (res) => cb ? cb(null, res) : res, - (err) => cb ? cb(err, err.status ? err : null) : err - ); - } - - _read() { - this.resume(); - if (this.response) return; - this.catch((err) => this.emit('error', err)); - } - - _shouldUnzip(res) { - if (res.statusCode === 204 || res.statusCode === 304) return false; - if (res.headers['content-length'] === '0') return false; - return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']); - } - - _shouldRedirect(res) { - return [301, 302, 303, 307, 308].includes(res.statusCode); - } - - _getFormData() { - if (!this._formData) this._formData = new FormData(); - return this._formData; - } - - _addFinalHeaders() { - if (!this.request) return; - if (!this._getRequestHeader('user-agent')) { - this.set('User-Agent', `snekfetch/${Snekfetch.version} (${Package.repository.url.replace(/\.?git/, '')})`); - } - if (this.request.method !== 'HEAD') this.set('Accept-Encoding', 'gzip, deflate'); - if (this.data && this.data.end) this.set('Content-Length', this.data.length); - } - - get response() { - return this.request ? this.request.res || this.request._response || null : null; - } - - _getRequestHeader(header) { - // https://github.com/jhiesey/stream-http/pull/77 - try { - return this.request.getHeader(header); - } catch (err) { - return null; - } - } -} - -Snekfetch.version = Package.version; - -Snekfetch.METHODS = http.METHODS ? - http.METHODS.concat('BREW') : - ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD']; -for (const method of Snekfetch.METHODS) { - Snekfetch[method === 'M-SEARCH' ? 'msearch' : method.toLowerCase()] = (url, opts) => new Snekfetch(method, url, opts); -} - -if (true) module.exports = Snekfetch; -else if (typeof window !== 'undefined') window.Snekfetch = Snekfetch; - -function makeURLFromRequest(request) { - return URL.format({ - protocol: request.connection.encrypted ? 'https:' : 'http:', - hostname: request.getHeader('host'), - pathname: request.path.split('?')[0], - query: request.query, - }); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer)) - -/***/ }), -/* 79 */ -/***/ (function(module, exports) { - -/* (ignored) */ - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/**/ - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = __webpack_require__(33).Buffer; -/**/ - -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} - -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - return BufferList; -}(); - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - -var apply = Function.prototype.apply; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { - if (timeout) { - timeout.close(); - } -}; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// setimmediate attaches itself to the global object -__webpack_require__(82); -exports.setImmediate = setImmediate; -exports.clearImmediate = clearImmediate; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { - "use strict"; - - if (global.setImmediate) { - return; - } - - var nextHandle = 1; // Spec says greater than zero - var tasksByHandle = {}; - var currentlyRunningATask = false; - var doc = global.document; - var registerImmediate; - - function setImmediate(callback) { - // Callback can either be a function or a string - if (typeof callback !== "function") { - callback = new Function("" + callback); - } - // Copy function arguments - var args = new Array(arguments.length - 1); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 1]; - } - // Store and register the task - var task = { callback: callback, args: args }; - tasksByHandle[nextHandle] = task; - registerImmediate(nextHandle); - return nextHandle++; - } - - function clearImmediate(handle) { - delete tasksByHandle[handle]; - } - - function run(task) { - var callback = task.callback; - var args = task.args; - switch (args.length) { - case 0: - callback(); - break; - case 1: - callback(args[0]); - break; - case 2: - callback(args[0], args[1]); - break; - case 3: - callback(args[0], args[1], args[2]); - break; - default: - callback.apply(undefined, args); - break; - } - } - - function runIfPresent(handle) { - // From the spec: "Wait until any invocations of this algorithm started before this one have completed." - // So if we're currently running a task, we'll need to delay this invocation. - if (currentlyRunningATask) { - // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a - // "too much recursion" error. - setTimeout(runIfPresent, 0, handle); - } else { - var task = tasksByHandle[handle]; - if (task) { - currentlyRunningATask = true; - try { - run(task); - } finally { - clearImmediate(handle); - currentlyRunningATask = false; - } - } - } - } - - function installNextTickImplementation() { - registerImmediate = function(handle) { - process.nextTick(function () { runIfPresent(handle); }); - }; - } - - function canUsePostMessage() { - // The test against `importScripts` prevents this implementation from being installed inside a web worker, - // where `global.postMessage` means something completely different and can't be used for this purpose. - if (global.postMessage && !global.importScripts) { - var postMessageIsAsynchronous = true; - var oldOnMessage = global.onmessage; - global.onmessage = function() { - postMessageIsAsynchronous = false; - }; - global.postMessage("", "*"); - global.onmessage = oldOnMessage; - return postMessageIsAsynchronous; - } - } - - function installPostMessageImplementation() { - // Installs an event handler on `global` for the `message` event: see - // * https://developer.mozilla.org/en/DOM/window.postMessage - // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages - - var messagePrefix = "setImmediate$" + Math.random() + "$"; - var onGlobalMessage = function(event) { - if (event.source === global && - typeof event.data === "string" && - event.data.indexOf(messagePrefix) === 0) { - runIfPresent(+event.data.slice(messagePrefix.length)); - } - }; - - if (global.addEventListener) { - global.addEventListener("message", onGlobalMessage, false); - } else { - global.attachEvent("onmessage", onGlobalMessage); - } - - registerImmediate = function(handle) { - global.postMessage(messagePrefix + handle, "*"); - }; - } - - function installMessageChannelImplementation() { - var channel = new MessageChannel(); - channel.port1.onmessage = function(event) { - var handle = event.data; - runIfPresent(handle); - }; - - registerImmediate = function(handle) { - channel.port2.postMessage(handle); - }; - } - - function installReadyStateChangeImplementation() { - var html = doc.documentElement; - registerImmediate = function(handle) { - // Create a